diff --git a/pkgs/id/web/src/collab.test.ts b/pkgs/id/web/src/collab.test.ts new file mode 100644 index 0000000000..b56163973c --- /dev/null +++ b/pkgs/id/web/src/collab.test.ts @@ -0,0 +1,177 @@ +import { Packr, Unpackr } from "msgpackr"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { initCollab } from "./collab"; + +// Same MessagePack configuration as collab.ts +const packr = new Packr({ useRecords: false, structuredClone: true }); +const unpackr = new Unpackr({ useRecords: false, structuredClone: true }); + +const MSG_AUTH = 8; +const MSG_AUTH_OK = 9; + +/** Minimal WebSocket stand-in: records sent frames, lets the test drive + * open/message/close by hand. No real network is involved. */ +class FakeWebSocket { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + static instances: FakeWebSocket[] = []; + + readonly CONNECTING = 0; + readonly OPEN = 1; + readonly CLOSING = 2; + readonly CLOSED = 3; + + readyState = FakeWebSocket.CONNECTING; + binaryType = ""; + sent: unknown[] = []; + onopen: (() => void) | null = null; + onclose: ((event: { code: number; reason: string }) => void) | null = null; + onerror: ((event: unknown) => void) | null = null; + onmessage: ((event: { data: unknown }) => void) | null = null; + + constructor(readonly url: string) { + FakeWebSocket.instances.push(this); + } + + send(data: unknown): void { + this.sent.push(data); + } + + close(): void { + this.readyState = FakeWebSocket.CLOSED; + } + + // Test drivers ----------------------------------------------------------- + open(): void { + this.readyState = FakeWebSocket.OPEN; + this.onopen?.(); + } + + deliver(msg: unknown[]): void { + const packed = packr.pack(msg); + const buf = packed.buffer.slice( + packed.byteOffset, + packed.byteOffset + packed.byteLength, + ) as ArrayBuffer; + this.onmessage?.({ data: buf }); + } + + drop(): void { + this.readyState = FakeWebSocket.CLOSED; + // 1006 = abnormal closure (a dropped connection, not an intentional one) + this.onclose?.({ code: 1006, reason: "dropped" }); + } + + firstFrame(): unknown { + expect(this.sent.length).toBeGreaterThan(0); + return unpackr.unpack(this.sent[0] as Uint8Array); + } +} + +function makeContainer(): HTMLElement { + const el = document.createElement("div"); + document.body.appendChild(el); + return el; +} + +const liveConnections: { disconnect: () => void }[] = []; +function track void }>(conn: T): T { + liveConnections.push(conn); + return conn; +} + +describe("initCollab token handling (#1463)", () => { + beforeEach(() => { + vi.useFakeTimers(); + FakeWebSocket.instances = []; + vi.stubGlobal("WebSocket", FakeWebSocket); + }); + + afterEach(() => { + while (liveConnections.length > 0) { + liveConnections.pop()?.disconnect(); + } + vi.unstubAllGlobals(); + vi.useRealTimers(); + document.body.innerHTML = ""; + }); + + it("reconnect AUTH sends the AUTH_OK refreshed token, not the init token", () => { + const onTokenRefresh = vi.fn(); + const conn = track(initCollab( + "ws://example.test/collab", + makeContainer(), + "doc-1", + "notes.md", + "OLD_TOKEN_A", + onTokenRefresh, + )); + + const first = FakeWebSocket.instances[0]; + first.open(); + expect(first.firstFrame()).toEqual([MSG_AUTH, "OLD_TOKEN_A"]); + + // Server confirms identity and hands back a refreshed token + first.deliver([MSG_AUTH_OK, "client-1", "alice", "NEW_TOKEN_B"]); + expect(onTokenRefresh).toHaveBeenCalledWith("NEW_TOKEN_B"); + + // Connection drops; the scheduled reconnect creates a second socket + first.drop(); + vi.advanceTimersByTime(1_000); + expect(FakeWebSocket.instances.length).toBe(2); + + const second = FakeWebSocket.instances[1]; + second.open(); + expect(second.firstFrame()).toEqual([MSG_AUTH, "NEW_TOKEN_B"]); + + conn.disconnect(); + }); + + it("reconnect without any refresh re-sends the init token", () => { + const conn = track(initCollab( + "ws://example.test/collab", + makeContainer(), + "doc-1", + "notes.md", + "ONLY_TOKEN", + undefined, + )); + + const first = FakeWebSocket.instances[0]; + first.open(); + expect(first.firstFrame()).toEqual([MSG_AUTH, "ONLY_TOKEN"]); + + first.drop(); + vi.advanceTimersByTime(1_000); + const second = FakeWebSocket.instances[1]; + second.open(); + expect(second.firstFrame()).toEqual([MSG_AUTH, "ONLY_TOKEN"]); + + conn.disconnect(); + }); + + it("anonymous connect sends no AUTH frame, before or after reconnect", () => { + const conn = track(initCollab( + "ws://example.test/collab", + makeContainer(), + "doc-1", + "notes.md", + null, + undefined, + )); + + const first = FakeWebSocket.instances[0]; + first.open(); + expect(first.sent.length).toBe(0); + + first.drop(); + vi.advanceTimersByTime(1_000); + const second = FakeWebSocket.instances[1]; + second.open(); + expect(second.sent.length).toBe(0); + + conn.disconnect(); + }); +}); diff --git a/pkgs/id/web/src/collab.ts b/pkgs/id/web/src/collab.ts index a81a576c5b..b313cc6f7e 100644 --- a/pkgs/id/web/src/collab.ts +++ b/pkgs/id/web/src/collab.ts @@ -102,6 +102,13 @@ export function initCollab( const queryStr = params.toString(); const finalWsUrl = queryStr ? `${wsUrl}?${queryStr}` : wsUrl; + // Single mutable source of truth for the identity token (#1463). The + // AUTH_OK handler overwrites this when the server refreshes the token, + // and every (re)connect sends this value. Sending the init-time `token` + // parameter instead would re-send the original token on every reconnect, + // so the refresh would never reach the socket that needs it. + let currentToken: string | null = token ?? null; + let reconnectAttempts = 0; let reconnectTimer: ReturnType | null = null; const sendQueue: Uint8Array[] = []; @@ -385,9 +392,15 @@ export function initCollab( const authName = msg[2] as string | null; const refreshedToken = msg[3] as string | null | undefined; console.log("[collab] Auth OK: client_id=%s, name=%s", authClientId, authName); - // Save the refreshed token so long-lived WS sessions stay fresh - if (refreshedToken && onTokenRefresh) { - onTokenRefresh(refreshedToken); + // Save the refreshed token so long-lived WS sessions stay fresh. + // Write it back to currentToken first: reconnects authenticate with + // currentToken, so the refreshed value must live here, not only in + // the caller's onTokenRefresh callback (#1463). + if (refreshedToken) { + currentToken = refreshedToken; + if (onTokenRefresh) { + onTokenRefresh(refreshedToken); + } } break; } @@ -451,8 +464,8 @@ export function initCollab( // Send AUTH as the very first message (before flushing queued messages). // The server waits for this before sending INIT. Token is kept out of // the URL to avoid leaking in logs/Referer headers over HTTPS. - if (token) { - const authData = packr.pack([MSG.AUTH, token]); + if (currentToken) { + const authData = packr.pack([MSG.AUTH, currentToken]); socket.send(authData); console.log("[collab] Sent AUTH message"); }