import { describe, expect, it } from "vitest"; import { CHAT_EVENT_NAMES, CHAT_MESSAGE_MAX_BODY_LENGTH, CHAT_MESSAGE_MAX_MENTIONS } from "./chat-events.js"; import { CHAT_CLIENT_FRAME_TYPES, CHAT_MAX_ACTIVE_SUBSCRIPTIONS, CHAT_WIRE_MAX_CLIENT_JSON_LENGTH, CHAT_WIRE_MAX_GAP_EVENTS, CHAT_WIRE_MAX_RESUME_CURSORS, CHAT_WIRE_MAX_SERVER_JSON_LENGTH, isChatClientFrame, isChatServerFrame, parseChatClientFrameJson, parseChatServerFrameJson, serializeChatClientFrame, serializeChatServerFrame, validateChatClientFrame, validateChatServerFrame, } from "./chat-wire.js"; const occurredAt = "2026-07-15T12:00:00.000Z"; const message = { id: "message_1", clientMessageId: "client_message_1", authorUserId: "user_1", body: "Hello team", bodyFormat: "markdown", parentMessageId: null, mentions: [], attachmentIds: [], linkPreviews: [], createdAt: occurredAt, updatedAt: occurredAt, editedAt: null, deletedAt: null, } as const; function persistentEvent(sequence = 1, overrides: Record = {}): Record { return { event: CHAT_EVENT_NAMES.messageCreated, cursor: `stream_1:${sequence}`, requestId: `request_${sequence}`, tenantId: "tenant_1", chatId: "chat_1", occurredAt, data: { message: { ...message, id: `message_${sequence}`, clientMessageId: `client_message_${sequence}` } }, ...overrides, }; } function typingEvent(): Record { return { event: CHAT_EVENT_NAMES.typingStarted, cursor: null, requestId: "request_typing", tenantId: "tenant_1", chatId: "chat_1", occurredAt, data: { userId: "user_2" }, }; } describe("chat websocket client wire contract", () => { it("shares one bounded active-subscription ceiling", () => { expect(CHAT_MAX_ACTIVE_SUBSCRIPTIONS).toBe(64); expect(CHAT_WIRE_MAX_RESUME_CURSORS).toBe(CHAT_MAX_ACTIVE_SUBSCRIPTIONS); }); it("validates authentication and canonical per-chat resume cursors", () => { expect( validateChatClientFrame({ type: CHAT_CLIENT_FRAME_TYPES.authenticate, token: "session-token-value", resumeCursors: [ { chatId: " chat_1 ", afterCursor: "stream_1:42" }, { chatId: "chat_2", afterCursor: "0" }, ], }) ).toEqual({ type: CHAT_CLIENT_FRAME_TYPES.authenticate, token: "session-token-value", resumeCursors: [ { chatId: "chat_1", afterCursor: "stream_1:42" }, { chatId: "chat_2", afterCursor: "0" }, ], }); }); it("validates subscribe, unsubscribe, typing, presence, read, and ping frames", () => { expect(validateChatClientFrame({ type: "subscribe", chatId: "chat_1", afterCursor: "0" })).toEqual({ type: "subscribe", chatId: "chat_1", afterCursor: "0", }); expect(validateChatClientFrame({ type: "unsubscribe", chatId: "chat_1" })).toEqual({ type: "unsubscribe", chatId: "chat_1" }); expect(validateChatClientFrame({ type: "typing", chatId: "chat_1", status: "started" })).toEqual({ type: "typing", chatId: "chat_1", status: "started", }); expect(validateChatClientFrame({ type: "typing", chatId: "chat_1", status: "stopped" })).toMatchObject({ status: "stopped" }); expect(validateChatClientFrame({ type: "presence", status: "online" })).toEqual({ type: "presence", status: "online" }); expect(validateChatClientFrame({ type: "presence", status: "away" })).toEqual({ type: "presence", status: "away" }); expect(validateChatClientFrame({ type: "mark_read", chatId: "chat_1", messageId: "message_1", requestId: "request_1" })).toEqual({ type: "mark_read", chatId: "chat_1", messageId: "message_1", requestId: "request_1", }); expect(validateChatClientFrame({ type: "ping" })).toEqual({ type: "ping" }); }); it("validates bounded message content and normalized mention targets", () => { expect( validateChatClientFrame({ type: "send_message", chatId: "chat_1", requestId: "request_1", clientMessageId: "client_message_1", body: " Hello\nteam ", mentions: [ { type: "user", id: "user_2", label: " Ada " }, { type: "project", id: "project_1" }, ], }) ).toEqual({ type: "send_message", chatId: "chat_1", requestId: "request_1", clientMessageId: "client_message_1", body: " Hello\nteam ", mentions: [ { type: "user", id: "user_2", label: "Ada" }, { type: "project", id: "project_1", label: null }, ], }); }); it("rejects unsupported keys, invalid types, and unsafe identifiers", () => { expect(() => validateChatClientFrame(null)).toThrow(/must be an object/); expect(() => validateChatClientFrame([])).toThrow(/must be an object/); expect(() => validateChatClientFrame({ type: "unknown" })).toThrow(/supported chat client frame type/); expect(() => validateChatClientFrame({ type: "ping", metadata: {} })).toThrow(/unsupported key/); expect(() => validateChatClientFrame({ type: "subscribe", chatId: "chat id", afterCursor: "0" })).toThrow(/safe identifier/); expect(() => validateChatClientFrame({ type: "typing", chatId: "chat_1", status: "active" })).toThrow(/started or stopped/); expect(() => validateChatClientFrame({ type: "presence", status: "offline" })).toThrow(/online or away/); expect(() => validateChatClientFrame({ type: "mark_read", chatId: "chat_1", messageId: null, requestId: "request_1" })).toThrow( /messageId must be a string/ ); }); it("rejects secret token shape errors without reflecting token contents", () => { const secret = " Bearer private-session-token "; let diagnostic = ""; try { validateChatClientFrame({ type: "authenticate", token: secret, resumeCursors: [] }); } catch (error) { diagnostic = error instanceof Error ? error.message : String(error); } expect(diagnostic).toBe("authenticate token is invalid"); expect(diagnostic).not.toContain("private-session-token"); expect(() => validateChatClientFrame({ type: "authenticate", token: "x".repeat(8_193), resumeCursors: [] })).toThrow(/token is invalid/); }); it("rejects malformed, duplicate, invalid, and oversized resume cursors", () => { expect(() => validateChatClientFrame({ type: "authenticate", token: "token", resumeCursors: null })).toThrow(/must be an array/); expect(() => validateChatClientFrame({ type: "authenticate", token: "token", resumeCursors: [ { chatId: "chat_1", afterCursor: "0" }, { chatId: "chat_1", afterCursor: "stream_1:2" }, ], }) ).toThrow(/duplicate chatId/); expect(() => validateChatClientFrame({ type: "authenticate", token: "token", resumeCursors: [{ chatId: "chat_1", afterCursor: "stream_1:0" }] })).toThrow( /positive canonical/ ); expect(() => validateChatClientFrame({ type: "authenticate", token: "token", resumeCursors: [{ chatId: "chat_1", afterCursor: "0", extra: true }] }) ).toThrow(/unsupported key/); expect(() => validateChatClientFrame({ type: "authenticate", token: "token", resumeCursors: Array.from({ length: CHAT_WIRE_MAX_RESUME_CURSORS + 1 }, (_, index) => ({ chatId: `chat_${index}`, afterCursor: "0" })), }) ).toThrow(/too many entries/); }); it("rejects empty or oversized bodies and malformed mentions", () => { const base = { type: "send_message", chatId: "chat_1", requestId: "request_1", clientMessageId: "client_message_1", body: "Hello", mentions: [], }; expect(() => validateChatClientFrame({ ...base, body: " \n " })).toThrow(/must not be empty/); expect(() => validateChatClientFrame({ ...base, body: "x".repeat(CHAT_MESSAGE_MAX_BODY_LENGTH + 1) })).toThrow(/maximum length/); expect(() => validateChatClientFrame({ ...base, body: "Hello\u0000" })).toThrow(/control character/); expect(() => validateChatClientFrame({ ...base, mentions: [ { type: "user", id: "user_2" }, { type: "user", id: "user_2" }, ], }) ).toThrow(/duplicate targets/); expect(() => validateChatClientFrame({ ...base, mentions: [{ type: "email", id: "user_2" }] })).toThrow(/supported mention type/); expect(() => validateChatClientFrame({ ...base, mentions: [{ type: "user", id: "user_2", token: "secret" }] })).toThrow(/unsupported key/); expect(() => validateChatClientFrame({ ...base, mentions: Array.from({ length: CHAT_MESSAGE_MAX_MENTIONS + 1 }, (_, index) => ({ type: "user", id: `user_${index}` })), }) ).toThrow(/too many entries/); }); it("parses and serializes size-bounded client JSON without exposing raw input", () => { const raw = serializeChatClientFrame({ type: "subscribe", chatId: "chat_1", afterCursor: "stream_1:42" }); expect(parseChatClientFrameJson(raw)).toEqual({ type: "subscribe", chatId: "chat_1", afterCursor: "stream_1:42" }); expect(() => parseChatClientFrameJson("{private-token")).toThrow("chat client frame must contain valid JSON"); expect(() => parseChatClientFrameJson("x".repeat(CHAT_WIRE_MAX_CLIENT_JSON_LENGTH + 1))).toThrow(/exceeds its maximum length/); }); it("provides a non-throwing client-frame guard", () => { expect(isChatClientFrame({ type: "ping" })).toBe(true); expect(isChatClientFrame({ type: "ping", extra: true })).toBe(false); }); }); describe("chat websocket server wire contract", () => { it("validates ready, event, error, and pong frames", () => { expect(validateChatServerFrame({ type: "ready", connectionId: "connection_1" })).toEqual({ type: "ready", connectionId: "connection_1" }); expect(validateChatServerFrame({ type: "event", event: persistentEvent() })).toMatchObject({ type: "event", event: { event: CHAT_EVENT_NAMES.messageCreated, cursor: "stream_1:1" }, }); expect(validateChatServerFrame({ type: "event", event: typingEvent() })).toMatchObject({ type: "event", event: { event: CHAT_EVENT_NAMES.typingStarted, cursor: null }, }); expect( validateChatServerFrame({ type: "error", i18nKey: "chat.errors.invalidInput", retryable: false, requestId: "request_1", clientMessageId: "client_message_1", }) ).toEqual({ type: "error", i18nKey: "chat.errors.invalidInput", retryable: false, requestId: "request_1", clientMessageId: "client_message_1", }); expect(validateChatServerFrame({ type: "pong" })).toEqual({ type: "pong" }); }); it("validates ordered gap pages and reset results", () => { expect( validateChatServerFrame({ type: "subscribed", chatId: "chat_1", result: { status: "ok", events: [persistentEvent(2), persistentEvent(8)], nextCursor: "stream_1:8", hasMore: true, }, }) ).toMatchObject({ type: "subscribed", chatId: "chat_1", result: { status: "ok", nextCursor: "stream_1:8", hasMore: true }, }); expect( validateChatServerFrame({ type: "subscribed", chatId: "chat_1", result: { status: "reset_required", currentStreamId: "new-stream_1" }, }) ).toEqual({ type: "subscribed", chatId: "chat_1", result: { status: "reset_required", currentStreamId: "new-stream_1" }, }); }); it("rejects malformed or unsafe error diagnostics", () => { expect(() => validateChatServerFrame({ type: "error", i18nKey: "Something failed with token abc", retryable: false })).toThrow(/catalog error key/); expect(() => validateChatServerFrame({ type: "error", i18nKey: "chat.status.offline", retryable: false })).toThrow(/catalog error key/); expect(() => validateChatServerFrame({ type: "error", i18nKey: "chat.errors.invalidInput", retryable: "yes" })).toThrow(/must be a boolean/); expect(() => validateChatServerFrame({ type: "error", i18nKey: "chat.errors.invalidInput", retryable: false, message: "raw failure" })).toThrow( /unsupported key/ ); expect(() => validateChatServerFrame({ type: "error", i18nKey: "chat.errors.invalidInput", retryable: false, stack: "token" })).toThrow(/unsupported key/); expect(() => validateChatServerFrame({ type: "error", i18nKey: "chat.errors.invalidInput", retryable: false, requestId: null })).toThrow( /requestId must be a string/ ); }); it("rejects non-persistent, cross-scope, mixed-stream, unordered, and inconsistent gap pages", () => { const subscribed = (events: unknown[], nextCursor: string, hasMore = false) => ({ type: "subscribed", chatId: "chat_1", result: { status: "ok", events, nextCursor, hasMore }, }); expect(() => validateChatServerFrame(subscribed([typingEvent()], "stream_1:1"))).toThrow(/must be persistent/); expect(() => validateChatServerFrame(subscribed([persistentEvent(1, { chatId: "chat_2" })], "stream_1:1"))).toThrow(/chatId does not match/); expect(() => validateChatServerFrame(subscribed([persistentEvent(1), persistentEvent(2, { tenantId: "tenant_2" })], "stream_1:2"))).toThrow(/one tenant/); expect(() => validateChatServerFrame(subscribed([persistentEvent(1), persistentEvent(2, { cursor: "stream_2:2" })], "stream_2:2"))).toThrow( /one stream generation/ ); expect(() => validateChatServerFrame(subscribed([persistentEvent(2), persistentEvent(1)], "stream_1:1"))).toThrow(/strictly ascending/); expect(() => validateChatServerFrame(subscribed([persistentEvent(1)], "stream_1:2"))).toThrow(/nextCursor must match/); expect(() => validateChatServerFrame(subscribed([], "0", true))).toThrow(/empty page/); expect(() => validateChatServerFrame( subscribed( Array.from({ length: CHAT_WIRE_MAX_GAP_EVENTS + 1 }, (_, index) => persistentEvent(index + 1)), "stream_1:251" ) ) ).toThrow(/too many events/); }); it("rejects unsupported server frame keys and malformed nested events", () => { expect(() => validateChatServerFrame(new Date())).toThrow(/plain object/); expect(() => validateChatServerFrame({ type: "unknown" })).toThrow(/supported chat server frame type/); expect(() => validateChatServerFrame({ type: "ready", connectionId: "connection_1", token: "secret" })).toThrow(/unsupported key/); expect(() => validateChatServerFrame({ type: "event", event: { ...persistentEvent(), authorization: "secret" } })).toThrow( /unsupported key: authorization/ ); expect(() => validateChatServerFrame({ type: "subscribed", chatId: "chat_1", result: { status: "reset_required", currentStreamId: "bad:stream" } }) ).toThrow(/separator/); }); it("parses and serializes size-bounded server JSON", () => { const raw = serializeChatServerFrame({ type: "event", event: persistentEvent() }); expect(parseChatServerFrameJson(raw)).toMatchObject({ type: "event", event: { cursor: "stream_1:1" } }); expect(() => parseChatServerFrameJson("{")).toThrow("chat server frame must contain valid JSON"); expect(() => parseChatServerFrameJson("x".repeat(CHAT_WIRE_MAX_SERVER_JSON_LENGTH + 1))).toThrow(/exceeds its maximum length/); }); it("provides a non-throwing server-frame guard", () => { expect(isChatServerFrame({ type: "pong" })).toBe(true); expect(isChatServerFrame({ type: "pong", payload: "secret" })).toBe(false); }); });