From b441647df4fcc5fbaeee018078c4a74f2fc2044b Mon Sep 17 00:00:00 2001 From: airline233 Date: Sun, 17 May 2026 15:27:43 +0800 Subject: [PATCH] feat(http-server): support parse content-type of urlencoded --- .../src/onebot/network/http-server-adapter.ts | 66 ++++++-- .../tests/http-server-content-type.test.ts | 149 ++++++++++++++++++ 2 files changed, 203 insertions(+), 12 deletions(-) create mode 100644 packages/core/tests/http-server-content-type.test.ts diff --git a/packages/core/src/onebot/network/http-server-adapter.ts b/packages/core/src/onebot/network/http-server-adapter.ts index 778ae4b2..4c36e68a 100644 --- a/packages/core/src/onebot/network/http-server-adapter.ts +++ b/packages/core/src/onebot/network/http-server-adapter.ts @@ -136,19 +136,61 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter } else if (req.method === 'POST') { const bodyContent = await readRequestBody(req); if (bodyContent.trim()) { - try { - const parsedBody = JSON.parse(bodyContent); - if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) { - if (parsedBody.action && !action) action = String(parsedBody.action); - if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) { - params = parsedBody.params as Record; - } else { - params = parsedBody as Record; + const contentType = req.headers['content-type'] ?? ''; + if (contentType.includes('application/x-www-form-urlencoded')) { + const parsed = new URLSearchParams(bodyContent); + parsed.forEach((value, key) => { + try { + params[key] = JSON.parse(value); + } catch { + params[key] = value; } - echo = parsedBody.echo; + }); + if (params.action && !action) { + action = String(params.action); + delete params.action; } - } catch { - writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' }); + if (params.echo !== undefined) { + echo = params.echo; + delete params.echo; + } + } else if (contentType.includes('application/json') || !contentType) { + try { + const parsedBody = JSON.parse(bodyContent); + if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) { + if (parsedBody.action && !action) action = String(parsedBody.action); + if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) { + params = parsedBody.params as Record; + } else { + params = parsedBody as Record; + } + echo = parsedBody.echo; + } + } catch { + if (contentType.includes('application/json')) { + writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' }); + return; + } + // 无 content-type,JSON 失败则 fallback 到 urlencoded + const parsed = new URLSearchParams(bodyContent); + parsed.forEach((value, key) => { + try { + params[key] = JSON.parse(value); + } catch { + params[key] = value; + } + }); + if (params.action && !action) { + action = String(params.action); + delete params.action; + } + if (params.echo !== undefined) { + echo = params.echo; + delete params.echo; + } + } + } else { + writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: `bad request: unsupported content-type: ${contentType}` }); return; } } @@ -200,4 +242,4 @@ function writeJson(res: ServerResponse, statusCode: number, data: unknown): void res.statusCode = statusCode; res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.end(JSON.stringify(data)); -} +} \ No newline at end of file diff --git a/packages/core/tests/http-server-content-type.test.ts b/packages/core/tests/http-server-content-type.test.ts new file mode 100644 index 00000000..71d7ea26 --- /dev/null +++ b/packages/core/tests/http-server-content-type.test.ts @@ -0,0 +1,149 @@ +// Tests for HTTP server adapter content-type parsing (POST body). +// Covers: application/x-www-form-urlencoded, application/json, +// no content-type fallback, and unsupported content-type rejection. + +import { describe, expect, it, vi, beforeAll, afterAll } from 'vitest'; +import http from 'http'; +import { HttpServerAdapter } from '../src/onebot/network/http-server-adapter'; +import type { NetworkAdapterContext } from '../src/onebot/network/adapter'; +import type { HttpServerNetwork } from '../src/onebot/types'; + +// ─── Helpers ─── + +function fakeCtx(handleFn: (action: string, params: Record) => unknown): NetworkAdapterContext { + return { + uin: '10001', + api: { + handle: vi.fn(async (action: string, params: Record) => { + const data = handleFn(action, params); + return { status: 'ok', retcode: 0, data }; + }), + } as any, + buildLifecycleEvent: vi.fn(() => ({})), + buildHeartbeatEvent: vi.fn(() => ({})), + }; +} + +function post(port: number, path: string, body: string, headers: Record = {}): Promise<{ status: number; body: any }> { + return new Promise((resolve, reject) => { + const req = http.request({ hostname: '127.0.0.1', port, path, method: 'POST', headers }, (res) => { + const chunks: Buffer[] = []; + res.on('data', (c) => chunks.push(c)); + res.on('end', () => { + const raw = Buffer.concat(chunks).toString('utf8'); + try { + resolve({ status: res.statusCode!, body: JSON.parse(raw) }); + } catch { + resolve({ status: res.statusCode!, body: raw }); + } + }); + }); + req.on('error', reject); + req.end(body); + }); +} + +// ─── Tests ─── + +describe('HttpServerAdapter content-type parsing', () => { + let adapter: HttpServerAdapter; + let handleFn: ReturnType) => unknown>>; + const PORT = 19876; + + beforeAll(async () => { + handleFn = vi.fn((_action: string, params: Record) => params); + const ctx = fakeCtx(handleFn); + const config: HttpServerNetwork = { name: 'test-http', port: PORT, enabled: true, messageFormat: 'array', reportSelfMessage: false }; + adapter = new HttpServerAdapter('test-http', config, ctx); + adapter.open(); + // Wait for server to be listening + await new Promise((resolve) => setTimeout(resolve, 100)); + }); + + afterAll(() => { + adapter.close(); + }); + + it('should parse application/json body', async () => { + const res = await post(PORT, '/send_message', JSON.stringify({ params: { group_id: 123, message: 'hi' } }), { + 'content-type': 'application/json', + }); + expect(res.status).toBe(200); + expect(res.body.status).toBe('ok'); + expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 123, message: 'hi' }); + }); + + it('should parse application/x-www-form-urlencoded body', async () => { + handleFn.mockClear(); + const body = 'group_id=456&message=hello'; + const res = await post(PORT, '/send_message', body, { + 'content-type': 'application/x-www-form-urlencoded', + }); + expect(res.status).toBe(200); + expect(res.body.status).toBe('ok'); + expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 456, message: 'hello' }); + }); + + it('should JSON-parse values in urlencoded body', async () => { + handleFn.mockClear(); + const body = 'user_id=789&data={"nested":true}'; + const res = await post(PORT, '/get_info', body, { + 'content-type': 'application/x-www-form-urlencoded', + }); + expect(res.status).toBe(200); + expect(handleFn).toHaveBeenCalledWith('get_info', { user_id: 789, data: { nested: true } }); + }); + + it('should extract action from urlencoded body when path has no action', async () => { + handleFn.mockClear(); + const body = 'action=get_status&key=value'; + const res = await post(PORT, '/', body, { + 'content-type': 'application/x-www-form-urlencoded', + }); + expect(res.status).toBe(200); + expect(handleFn).toHaveBeenCalledWith('get_status', { key: 'value' }); + }); + + it('should extract echo from urlencoded body', async () => { + handleFn.mockClear(); + const body = 'action=test_action&echo=12345&foo=bar'; + const res = await post(PORT, '/', body, { + 'content-type': 'application/x-www-form-urlencoded', + }); + expect(res.status).toBe(200); + expect(res.body.echo).toBe(12345); + expect(handleFn).toHaveBeenCalledWith('test_action', { foo: 'bar' }); + }); + + it('should reject unsupported content-type with 400', async () => { + const res = await post(PORT, '/send_message', '', { + 'content-type': 'application/xml', + }); + expect(res.status).toBe(400); + expect(res.body.wording).toContain('unsupported content-type'); + }); + + it('should reject invalid JSON with explicit application/json content-type', async () => { + const res = await post(PORT, '/send_message', 'not-json{{{', { + 'content-type': 'application/json', + }); + expect(res.status).toBe(400); + expect(res.body.wording).toContain('invalid json'); + }); + + it('should fallback to urlencoded when no content-type and body is not valid JSON', async () => { + handleFn.mockClear(); + const body = 'action=fallback_action¶m1=value1'; + const res = await post(PORT, '/', body, {}); + expect(res.status).toBe(200); + expect(handleFn).toHaveBeenCalledWith('fallback_action', { param1: 'value1' }); + }); + + it('should parse JSON when no content-type and body is valid JSON', async () => { + handleFn.mockClear(); + const body = JSON.stringify({ action: 'json_action', params: { x: 1 } }); + const res = await post(PORT, '/', body, {}); + expect(res.status).toBe(200); + expect(handleFn).toHaveBeenCalledWith('json_action', { x: 1 }); + }); +});