From 87734e93316fa387b76f74829a5599dafd64359b Mon Sep 17 00:00:00 2001 From: Saad Date: Tue, 27 Oct 2026 09:18:58 +0300 Subject: [PATCH] test(transport): cover the protocol gaps later suites left, and floor src/transport Most of #79's criteria are now covered by suites written after it. This adds what nothing covered: the 10,000-character boundary, whitespace content, an unknown type and a ping timestamp in the validator; parseWsData and rejectSocket; an INVALID_FORMAT answer that leaves the socket open, over a real socket; the CORS default; and a debug-level run proving no log line carries a turn's content. Each test is cited from the statement it validates. src/transport/ gets its own coverage floor at the measured figures, and global is re-measured without those files. No covered count fell; the counts are recorded in the npm-release spec. Co-Authored-By: Claude Opus 5.5 --- jest.config.js | 3 +- specs/hal-engine-architecture/spec.md | 1 + specs/hal-engine-npm-release/spec.md | 2 + specs/hal-engine-session-resume/spec.md | 10 +-- specs/hal-engine-websocket-protocol/spec.md | 14 +++-- src/contentFreeLogs.test.ts | 68 +++++++++++++++++++++ src/transport/createApp.test.ts | 13 ++++ src/transport/invalidFrame.test.ts | 29 +++++++++ src/transport/ws/helpers.test.ts | 33 +++++++++- src/transport/ws/validation.test.ts | 32 ++++++++++ 10 files changed, 194 insertions(+), 11 deletions(-) create mode 100644 src/contentFreeLogs.test.ts create mode 100644 src/transport/invalidFrame.test.ts diff --git a/jest.config.js b/jest.config.js index 34667c33..7419f2b1 100644 --- a/jest.config.js +++ b/jest.config.js @@ -60,7 +60,8 @@ export default { 'src/infrastructure/stores/': {statements: 100, branches: 100, functions: 100, lines: 100}, 'src/providers/vertex/': {statements: 94.23, branches: 84.7, functions: 100, lines: 97.72}, 'src/providers/mock/': {statements: 100, branches: 81.25, functions: 100, lines: 100}, + 'src/transport/': {statements: 97.19, branches: 93.77, functions: 96.81, lines: 97.3}, // Measured over the files no path floor above claims, which is what Jest holds `global` to. - global: {statements: 95.05, branches: 90.7, functions: 93.75, lines: 95.74}, + global: {statements: 92.33, branches: 85.71, functions: 90.9, lines: 93.77}, }, }; diff --git a/specs/hal-engine-architecture/spec.md b/specs/hal-engine-architecture/spec.md index 17c268cd..9e5facaa 100644 --- a/specs/hal-engine-architecture/spec.md +++ b/specs/hal-engine-architecture/spec.md @@ -491,6 +491,7 @@ When a connection drops, the frontend reconnects automatically: - `HalEngineConfig.transport.additionalRoutes` is forwarded to `createApp`, so a route registered there mounts under `basePath` in the server the engine builds, and not at the root. ([validated by: forwards transport.additionalRoutes to createApp so the route mounts under basePath](../../src/config.test.ts#L244)) - Neither `additionalRoutes` nor `rootRoutes` is covered by `auth.http`; both receive requests before any authentication middleware the engine installs, so a consumer applies its own middleware inside the callback. ([validated by: leaves additionalRoutes and rootRoutes open while auth.http still guards the chat routes](../../src/config.test.ts#L263)) - Both callbacks inherit the CORS, JSON body-parsing, and cookie-parsing middleware that `createApp` mounts unconditionally. ([validated by: gives additionalRoutes and rootRoutes the parsed JSON body, the cookies and the CORS headers](../../src/config.test.ts#L288)) +- With neither `transport.corsOrigin` nor `CORS_ORIGIN` set, that CORS middleware allows the origin `http://localhost:3000` and sends `Access-Control-Allow-Credentials: true`, a default for a front end on the developer's own machine ([validated by: allows http://localhost:3000 with credentials when neither corsOrigin nor CORS_ORIGIN is set](../../src/transport/createApp.test.ts#L165)). - A `transport.errorHandler` receives what a route throws, whether synchronously or as a rejected promise, and the response it writes is the one the client gets, instead of Express's default HTML page. ([validated by: hands transport.errorHandler a route's synchronous throw and its rejected promise, and answers with its response](../../src/config.test.ts#L311)) - `engine.app` cannot be extended after `createHalEngine` returns: `createApp` registers a terminal `404` catch-all before returning, and Express matches routes in registration order, so a route added afterwards always returns `404`. ([validated by: answers 404 for a route added to engine.app after createHalEngine returns](../../src/config.test.ts#L332)) diff --git a/specs/hal-engine-npm-release/spec.md b/specs/hal-engine-npm-release/spec.md index ee6bec22..179334a6 100644 --- a/specs/hal-engine-npm-release/spec.md +++ b/specs/hal-engine-npm-release/spec.md @@ -101,6 +101,8 @@ Nothing from `src/`, `example/`, `smoke/`, `docs/`, `specs/`, `adrs/` or `script - The floor is set at the measured baseline, not an aspiration, and exactly at it rather than rounded down: an integer floor leaves roughly a percent of slack, which was measured to let four untested lines through without failing. - Measured at `3186f07` with those exclusions: 67.96% statements, 57.54% branches, 68% functions, 68.34% lines, across 206 tests in 17 suites. The earlier figure of 61.32% lines predates the exclusions and three of this branch's commits. - The floor is a ratchet: a change that lowers coverage fails the job and is fixed by adding the missing test, never by lowering the number; a change that raises coverage should raise the floor with it. +- `src/transport/` gained its own floor on 2026-10-27, at what it measured that day: 97.19% statements (659/678), 93.77% branches (407/434), 96.81% functions (152/157) and 97.30% lines (578/594). +- Naming that path took its files out of `global`, which Jest measures over the files no path floor claims, so `global` was re-measured in the same commit: 458/496 statements, 228/266 branches, 120/132 functions and 392/418 lines. Its percentages fell because well-covered files left the group, not because coverage did. Measured the same day without the change, the files still in the group covered 457 statements, 228 branches, 119 functions and 391 lines, so none of the four counts went down. - `coverage/` is gitignored already, so nothing is added for it. ### Build-chain audit diff --git a/specs/hal-engine-session-resume/spec.md b/specs/hal-engine-session-resume/spec.md index e39e518c..13c67e37 100644 --- a/specs/hal-engine-session-resume/spec.md +++ b/specs/hal-engine-session-resume/spec.md @@ -9,10 +9,10 @@ A reconnect used to resume nothing: the server minted a fresh id on every connec ## Reading the requested id -- The id is the `sessionId` query parameter of the upgrade request, never a path segment, and only 1–128 characters of `[A-Za-z0-9_-]` count: an empty value, a longer one and a path-traversal value read as no id at all ([validated by: reads abc-123 from the query and nothing from a bare path, a path segment, an empty, a 129-character or a traversal value](../../src/transport/ws/helpers.test.ts#L6)). -- A 128-character id is the longest one read ([validated by: reads a 128-character id, the longest it accepts](../../src/transport/ws/helpers.test.ts#L24)). -- An upgrade outside `{basePath}/ws` carries no id ([validated by: reads nothing from an upgrade outside the base path](../../src/transport/ws/helpers.test.ts#L30)). -- Reading the id never throws: a target that is not a URL, such as `//`, or an empty one carries no id ([validated by: reads nothing, without throwing, from a target that is not a URL or is empty](../../src/transport/ws/helpers.test.ts#L34)). +- The id is the `sessionId` query parameter of the upgrade request, never a path segment, and only 1–128 characters of `[A-Za-z0-9_-]` count: an empty value, a longer one and a path-traversal value read as no id at all ([validated by: reads abc-123 from the query and nothing from a bare path, a path segment, an empty, a 129-character or a traversal value](../../src/transport/ws/helpers.test.ts#L7)). +- A 128-character id is the longest one read ([validated by: reads a 128-character id, the longest it accepts](../../src/transport/ws/helpers.test.ts#L25)). +- An upgrade outside `{basePath}/ws` carries no id ([validated by: reads nothing from an upgrade outside the base path](../../src/transport/ws/helpers.test.ts#L31)). +- Reading the id never throws: a target that is not a URL, such as `//`, or an empty one carries no id ([validated by: reads nothing, without throwing, from a target that is not a URL or is empty](../../src/transport/ws/helpers.test.ts#L35)). ## Opt-in @@ -52,7 +52,7 @@ A reconnect used to resume nothing: the server minted a fresh id on every connec - A connect that names an id rejoins that session, whichever is latest ([validated by: with latest on, still rejoins the session a connect names rather than the latest one](../../src/transport/sessionResume.test.ts#L488)). - A session `latestFor` answers for another user is never rejoined, and a `latestFor` that throws or that the store does not implement starts a new session ([validated by: starts a new session when the store's latestFor answers another user's session, throws, or is absent](../../src/transport/sessionResume.test.ts#L500)). - Without `latest`, a connect that names no id starts a new session, as before ([validated by: with resume on but latest off, starts a new session for a connect that names none](../../src/transport/sessionResume.test.ts#L524)). -- `?new=1` counts only when it is exactly `1`, and only on an upgrade inside `{basePath}/ws` ([validated by: reads exactly ?new=1 inside the base path as a request for a new session, and nothing else](../../src/transport/ws/helpers.test.ts#L40)). +- `?new=1` counts only when it is exactly `1`, and only on an upgrade inside `{basePath}/ws` ([validated by: reads exactly ?new=1 inside the base path as a request for a new session, and nothing else](../../src/transport/ws/helpers.test.ts#L41)). - `InMemorySessionStore.latestFor` goes by a session's newest timed entry, so the conversation the user last wrote to beats one created later, and an entry with no time, such as a thought, counts for nothing ([validated by: returns the user's session with the newest entry, not the one created last, a thought counting for nothing](../../src/infrastructure/stores/inMemoryLatestSession.test.ts#L17)). - A session with no entries counts from its creation, and of two last active at the same moment the larger session id wins, the rule `listFor` orders by, so a resume rejoins the conversation at the head of the list ([validated by: falls back to creation time for sessions with no entries, the one created later winning](../../src/infrastructure/stores/inMemoryLatestSession.test.ts#L30), [validated by: breaks a tie between two sessions created in the same millisecond by the larger session id, zeta over alpha](../../src/infrastructure/stores/inMemoryLatestSession.test.ts#L39)). - It never returns a session that has aged out, nor one belonging to another user ([validated by: returns nothing for a user whose only session aged out, nor another user's live one](../../src/infrastructure/stores/inMemoryLatestSession.test.ts#L47)). diff --git a/specs/hal-engine-websocket-protocol/spec.md b/specs/hal-engine-websocket-protocol/spec.md index a676f126..a50ead00 100644 --- a/specs/hal-engine-websocket-protocol/spec.md +++ b/specs/hal-engine-websocket-protocol/spec.md @@ -148,8 +148,8 @@ Any other field is ignored, and the validator forwards only the fields the frame Constraints: -- `content` MUST NOT be empty or whitespace-only after trimming. -- `content` MUST NOT exceed 10,000 characters. +- `content` MUST NOT be empty or whitespace-only after trimming ([validated by: refuses content of three spaces as empty](../../src/transport/ws/validation.test.ts#L82)). +- `content` MUST NOT exceed 10,000 characters: 10,000 is accepted and 10,001 refused, the error naming the limit ([validated by: accepts content of exactly 10,000 characters and refuses 10,001, naming the limit](../../src/transport/ws/validation.test.ts#L72)). - Violation of these constraints results in an `error` response with code `INVALID_MESSAGE`. One at a time: @@ -177,6 +177,8 @@ Application-level heartbeat. The server MUST respond with a `pong` message echoi | `type` | string | Yes | `"ping"` | | `timestamp` | number | Yes | Client timestamp in milliseconds | +A `ping` whose `timestamp` is missing or is not a number is refused, its error naming the field, and a numeric `timestamp` is passed on unchanged for the `pong` to echo ([validated by: refuses a ping with no timestamp or a text one, and passes a numeric timestamp through unchanged](../../src/transport/ws/validation.test.ts#L92)). + ### 4.3 list_conversations Asks for the connecting user's own conversations. Served only when the server enables @@ -381,6 +383,8 @@ Semantics: - A `list_conversations` the server does not serve is answered with `UNSUPPORTED`, whether because `transport.history` is off or because its store implements no `listFor`, and never with an empty list, which a client could not tell from a user who has no conversations ([validated by: refuses the frame when conversation history is not turned on](../../src/transport/conversationList.test.ts#L302), [validated by: refuses the frame when the store cannot list, rather than reporting no conversations](../../src/transport/conversationList.test.ts#L353)). - A store that fails while listing is answered `SERVER_ERROR` carrying none of the store's own words, and the server logs the session id, the user id and the error's type rather than its message, since a driver's message can hold a connection string and its password; the user id in that line is personal data, as it is in every log line the engine writes ([validated by: answers a failing store with a server error, keeps the socket open, and logs no word the store said](../../src/transport/conversationList.test.ts#L388)). - A message the server cannot parse into a known type is answered with `INVALID_MESSAGE`, and no message stream is started for it ([validated by: rejects an unparseable message and never starts a stream](../../src/transport/ws/messageHandler.test.ts#L72)). +- Each frame's bytes are parsed as JSON as they arrive, and bytes that do not parse read as no frame at all, without throwing ([validated by: reads a JSON object from text or from bytes, and an unterminated brace as null, without throwing](../../src/transport/ws/helpers.test.ts#L63)). +- A frame that is not JSON is answered with `INVALID_FORMAT` and the message `Invalid JSON`, and the connection stays open: the frame after it is handled as usual ([validated by: answers a frame that is not JSON with INVALID_FORMAT and Invalid JSON, and keeps the socket open for the next frame](../../src/transport/invalidFrame.test.ts#L16)). - A rate limit reported by the AI provider is surfaced as `RATE_LIMITED`, which tells the client the same request is worth retrying ([validated by: tells the client to retry when the provider is rate limited](../../src/transport/ws/messageHandler.test.ts#L372)). - Any other failure raised while processing a message that is no `AIError` is reported as `SERVER_ERROR` ([validated by: reports any other failure as a server error](../../src/transport/ws/messageHandler.test.ts#L381)). @@ -779,6 +783,7 @@ Once the `101` is sent the socket speaks WebSocket, so the server never writes a - A failure while the session opens, such as a session store whose `create` throws, is answered first with an `error` frame and then the same `1011` close ([validated by: sends an error frame and closes with 1011, with no client error, through createHalEngine when the session store create throws synchronously](../../src/sessionSetupFailure.test.ts#L15)). - The failure is logged once at `error` under `ws` as `connection failed after the handshake`, with the error's message; the upgrade request's `authorization` and `cookie` values reach no log line ([validated by: logs the failure at error under ws and keeps the authorization and cookie values out of every log line](../../src/transport/upgradeFailure.test.ts#L64)). - Before the handshake completes, the server still answers in HTTP: a `wsAuth` that rejects gets `500 Internal Server Error` and one that resolves `null` gets `401 Unauthorized`, with no `101` and no connection opened ([validated by: answers a rejecting wsAuth with 500 and a null one with 401, with no 101 and no connection event](../../src/transport/upgradeFailure.test.ts#L85)). +- Every answer the engine itself writes before the handshake, these two and its `400`s, is a status line and an empty header block alone, such as `HTTP/1.1 401 Unauthorized\r\n\r\n`, with no header and no body, so nothing from the request is echoed into it, and the socket is destroyed once it is written. A refusal `ws` writes for an upgrade it cannot parse is its own ([validated by: writes HTTP/1.1 401 Unauthorized and an empty header block, nothing else, then destroys the socket](../../src/transport/ws/helpers.test.ts#L73)). ## 12. Security Considerations @@ -787,8 +792,9 @@ Once the `101` is sent the socket speaks WebSocket, so the server never writes a - No offered subprotocol value is written to the engine's own log at any level. Every place a credential exists during a connection - request headers, the socket's and the session's `authHeaders`, and the tool context - is listed in [the subprotocol marker spec](../hal-engine-subprotocol-marker/spec.md#where-a-credential-exists). - An upgrade whose `Authorization` header and subprotocol carry different credentials is refused with `400` before authentication, so the credential a `WsAuthenticator` validated is the one forwarded to the session and to every tool ([validated by: refuses Bearer attacker-token beside a victim-token subprotocol with 400 before wsAuth runs, and neither value reaches the response or a log line](../../src/transport/handshake.test.ts#L182)). - **NIS-2 (Art. 21), supply-chain security.** Before that rule, a tool calling a downstream API could receive a bearer token no authenticator had validated: the authenticator could check one carrier while the other's value was forwarded, defeating the per-user data boundary downstream ([validated by: refuses Bearer attacker-token beside a victim-token subprotocol with 400 before wsAuth runs, and neither value reaches the response or a log line](../../src/transport/handshake.test.ts#L182)). -- Message content is validated at the server boundary. Content exceeding 10,000 characters is rejected. -- The server validates all incoming messages against known types. Unrecognized types receive an `INVALID_MESSAGE` error. +- Message content is validated at the server boundary. Content exceeding 10,000 characters is rejected ([validated by: accepts content of exactly 10,000 characters and refuses 10,001, naming the limit](../../src/transport/ws/validation.test.ts#L72)). +- The server validates all incoming messages against known types. Unrecognized types receive an `INVALID_MESSAGE` error ([validated by: refuses a frame of type nope, naming the type](../../src/transport/ws/validation.test.ts#L88), [validated by: rejects an unparseable message and never starts a stream](../../src/transport/ws/messageHandler.test.ts#L72)). +- **GDPR (Art. 5(1)(c)), data minimisation.** A turn's log lines record the length of the user's message as `contentLength`, never its text. At every level, `debug` included, no line carries the message, a tool's arguments or result, or the answer ([validated by: logs a 32-character question as contentLength 32 at debug level, and no line carries the question, a tool argument or result, or the answer](../../src/contentFreeLogs.test.ts#L59)). ## 13. Source Files diff --git a/src/contentFreeLogs.test.ts b/src/contentFreeLogs.test.ts new file mode 100644 index 00000000..5ac888bd --- /dev/null +++ b/src/contentFreeLogs.test.ts @@ -0,0 +1,68 @@ +import {jest} from '@jest/globals'; +import type {AddressInfo} from 'node:net'; + +// The level is read once, when the logger loads, so it is set before anything first-party is imported. +process.env.LOG_LEVEL = 'debug'; +const {createHalEngine} = await import('./config.js'); +const {ToolRegistry} = await import('./orchestration/tools/registry.js'); +const {InMemorySessionStore} = await import('./infrastructure/stores/inMemorySessionStore.js'); +const {connectClient, framesUntil} = await import('./transport/wsTestSupport.js'); + +const QUESTION = 'Where is parcel ZX-4471 heading?'; +const TOOL_ARGUMENT = 'QK-9083'; +const TOOL_RESULT = 'Held at the Aarhus depot'; +const ANSWER = 'It reaches Odense on Friday.'; + +interface Line { + severity: string; + data?: {contentLength?: number}; +} + +async function oneTurnLogged(): Promise { + const lines: string[] = []; + const keep = (raw: unknown) => void lines.push(String(raw)); + jest.spyOn(console, 'log').mockImplementation(keep); + jest.spyOn(console, 'error').mockImplementation(keep); + const engine = createHalEngine({ + prompt: {identity: 'Log content test.'}, + session: new InMemorySessionStore(), + auth: {ws: async () => ({id: 'u1'})}, + provider: { + type: 'mock', + turns: [{toolCalls: [{id: 'c1', name: 'lookup', input: {reference: TOOL_ARGUMENT}}]}, {text: ANSWER}], + }, + tools: lookupTool(), + }); + await engine.start(0); + const {port} = engine.server.address() as AddressInfo; + const client = connectClient(`ws://127.0.0.1:${port}/hal/ws`); + const ended = framesUntil(client, 'stream_end'); + const socketClosed = new Promise(resolve => + engine.wss.once('connection', socket => socket.once('close', () => resolve())) + ); + client.on('open', () => client.send(JSON.stringify({type: 'user_message', content: QUESTION}))); + await ended; + await engine.stop(); + await socketClosed; + return lines; +} + +function lookupTool() { + const registry = new ToolRegistry(); + registry.register( + {name: 'lookup', description: 'Looks a parcel up.', inputSchema: {type: 'object'}}, + async () => TOOL_RESULT + ); + return registry; +} + +it('logs a 32-character question as contentLength 32 at debug level, and no line carries the question, a tool argument or result, or the answer', async () => { + const lines = await oneTurnLogged(); + + const parsed = lines.map(line => JSON.parse(line) as Line); + expect({ + debugLogged: parsed.some(line => line.severity === 'DEBUG'), + contentLength: parsed.find(line => line.data?.contentLength !== undefined)?.data, + leaked: [QUESTION, TOOL_ARGUMENT, TOOL_RESULT, ANSWER].filter(text => lines.some(line => line.includes(text))), + }).toMatchObject({debugLogged: true, contentLength: {contentLength: 32}, leaked: []}); +}); diff --git a/src/transport/createApp.test.ts b/src/transport/createApp.test.ts index bf576ae1..25ac700d 100644 --- a/src/transport/createApp.test.ts +++ b/src/transport/createApp.test.ts @@ -160,3 +160,16 @@ describe('createApp rootRoutes extension', () => { }); }); }); + +describe('createApp CORS', () => { + it('allows http://localhost:3000 with credentials when neither corsOrigin nor CORS_ORIGIN is set', async () => { + delete process.env.CORS_ORIGIN; + + const response = await request(app()).get('/hal/health').set('Origin', 'http://localhost:3000'); + + expect({ + origin: response.headers['access-control-allow-origin'], + credentials: response.headers['access-control-allow-credentials'], + }).toEqual({origin: 'http://localhost:3000', credentials: 'true'}); + }); +}); diff --git a/src/transport/invalidFrame.test.ts b/src/transport/invalidFrame.test.ts new file mode 100644 index 00000000..fa1bd82b --- /dev/null +++ b/src/transport/invalidFrame.test.ts @@ -0,0 +1,29 @@ +import {once} from 'node:events'; +import type {WebSocket} from 'ws'; +import {InMemorySessionStore} from '../infrastructure/stores/inMemorySessionStore.js'; +import {setLogger} from '../shared/logger.js'; +import {connectClient, startEngine, stopEngines} from './wsTestSupport.js'; + +// Left quiet rather than restored: the server logs the socket's close after the suite has finished. +beforeAll(() => setLogger({debug() {}, info() {}, warn() {}, error() {}})); +afterEach(stopEngines); + +async function nextFrame(client: WebSocket): Promise { + const [raw] = (await once(client, 'message')) as [Buffer]; + return JSON.parse(raw.toString()); +} + +it('answers a frame that is not JSON with INVALID_FORMAT and Invalid JSON, and keeps the socket open for the next frame', async () => { + const client = connectClient(await startEngine(new InMemorySessionStore())); + await nextFrame(client); + + client.send('{"type": "user_message", "content": '); + const refused = await nextFrame(client); + client.send(JSON.stringify({type: 'ping', timestamp: 1705312200000})); + const answered = await nextFrame(client); + + expect({refused, answered}).toEqual({ + refused: {type: 'error', code: 'INVALID_FORMAT', message: 'Invalid JSON'}, + answered: {type: 'pong', timestamp: 1705312200000}, + }); +}); diff --git a/src/transport/ws/helpers.test.ts b/src/transport/ws/helpers.test.ts index 67b94b6f..ca62863f 100644 --- a/src/transport/ws/helpers.test.ts +++ b/src/transport/ws/helpers.test.ts @@ -1,4 +1,5 @@ -import {newSessionRequested, sessionIdFromUpgrade} from './helpers.js'; +import {Duplex} from 'node:stream'; +import {newSessionRequested, parseWsData, rejectSocket, sessionIdFromUpgrade} from './helpers.js'; const read = (url: string): string | undefined => sessionIdFromUpgrade(url, '/hal'); @@ -57,3 +58,33 @@ describe('newSessionRequested', () => { }); }); }); + +describe('parseWsData', () => { + it('reads a JSON object from text or from bytes, and an unterminated brace as null, without throwing', () => { + expect({ + text: parseWsData('{"a":1}'), + bytes: parseWsData(Buffer.from('{"a":1}')), + unterminated: parseWsData('{'), + }).toEqual({text: {a: 1}, bytes: {a: 1}, unterminated: null}); + }); +}); + +describe('rejectSocket', () => { + it('writes HTTP/1.1 401 Unauthorized and an empty header block, nothing else, then destroys the socket', () => { + const written: string[] = []; + const socket = new Duplex({ + read: () => undefined, + write: (chunk: Buffer, _encoding, done) => { + written.push(chunk.toString()); + done(); + }, + }); + + rejectSocket(socket, '401 Unauthorized'); + + expect({written, destroyed: socket.destroyed}).toEqual({ + written: ['HTTP/1.1 401 Unauthorized\r\n\r\n'], + destroyed: true, + }); + }); +}); diff --git a/src/transport/ws/validation.test.ts b/src/transport/ws/validation.test.ts index b242546b..bc867ff3 100644 --- a/src/transport/ws/validation.test.ts +++ b/src/transport/ws/validation.test.ts @@ -68,4 +68,36 @@ describe('the websocket frame validator', () => { expect(results.map(result => result.valid)).toEqual([false, false, false]); }); + + it('accepts content of exactly 10,000 characters and refuses 10,001, naming the limit', () => { + const longest = validateMessage({type: 'user_message', content: 'x'.repeat(10_000)}); + const over = validateMessage({type: 'user_message', content: 'x'.repeat(10_001)}); + + expect({longest: longest.valid, over}).toEqual({ + longest: true, + over: {valid: false, error: 'Message content too long (max 10000 chars)'}, + }); + }); + + it('refuses content of three spaces as empty', () => { + const result = validateMessage({type: 'user_message', content: ' '}); + + expect(result).toEqual({valid: false, error: 'Message content cannot be empty'}); + }); + + it('refuses a frame of type nope, naming the type', () => { + expect(validateMessage({type: 'nope'})).toEqual({valid: false, error: 'Unknown message type: nope'}); + }); + + it('refuses a ping with no timestamp or a text one, and passes a numeric timestamp through unchanged', () => { + expect({ + missing: validateMessage({type: 'ping'}), + text: validateMessage({type: 'ping', timestamp: '1705312200000'}), + numeric: validateMessage({type: 'ping', timestamp: 1705312200000}), + }).toEqual({ + missing: {valid: false, error: 'ping must have timestamp number'}, + text: {valid: false, error: 'ping must have timestamp number'}, + numeric: {valid: true, data: {type: 'ping', timestamp: 1705312200000}}, + }); + }); });