From c26fce350d75f7c70cc6cb1493a8bf24791ae198 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 21:50:56 -0600 Subject: [PATCH 1/2] fix(id/web): validate identity endpoint responses before persisting (#7839) --- pkgs/id/web/src/identity-refresh.test.ts | 92 +++++++++++++++++++++++- pkgs/id/web/src/identity-refresh.ts | 91 +++++++++++++++++++++++ pkgs/id/web/src/main.ts | 23 +++--- 3 files changed, 196 insertions(+), 10 deletions(-) diff --git a/pkgs/id/web/src/identity-refresh.test.ts b/pkgs/id/web/src/identity-refresh.test.ts index d1f1948f8f..3dbcf74630 100644 --- a/pkgs/id/web/src/identity-refresh.test.ts +++ b/pkgs/id/web/src/identity-refresh.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from "vitest"; -import { identityNeedsRefresh } from "./identity-refresh"; +import { + identityNeedsRefresh, + parseIdentityMeResponse, + parseIdentityNameResponse, + parseIdentityRegisterResponse, +} from "./identity-refresh"; const INTERVAL = 24 * 60 * 60 * 1000; const NOW = 1_800_000_000_000; @@ -34,3 +39,88 @@ describe("identityNeedsRefresh", () => { expect(identityNeedsRefresh(String(NOW - INTERVAL * 30), NOW, INTERVAL)).toBe(true); }); }); + +// Oracle for the #7839 suites below: a wrong-shape body must THROW, because +// throwing is what routes the caller through its existing error path before +// saveIdentity/updateStoredName can run — i.e. localStorage stays unchanged +// and no identity is returned. A returned value of the wrong type, or a +// coerced string, is the failure these tests pin against. +describe("parseIdentityRegisterResponse (#7839)", () => { + it("accepts a well-shaped registration", () => { + expect(parseIdentityRegisterResponse({ token: "tok", client_id: "cid", name: "Ada" })).toEqual({ + token: "tok", + clientId: "cid", + name: "Ada", + }); + expect(parseIdentityRegisterResponse({ token: "tok", client_id: "cid", name: null })).toEqual({ + token: "tok", + clientId: "cid", + name: null, + }); + expect(parseIdentityRegisterResponse({ token: "tok", client_id: "cid" })).toEqual({ + token: "tok", + clientId: "cid", + name: null, + }); + }); + + it("rejects non-object bodies", () => { + expect(() => parseIdentityRegisterResponse({})).toThrow(); + expect(() => parseIdentityRegisterResponse(null)).toThrow(); + expect(() => parseIdentityRegisterResponse("abc")).toThrow(); + expect(() => parseIdentityRegisterResponse([])).toThrow(); + }); + + it("rejects numeric or object token/client_id instead of coercing them", () => { + expect(() => parseIdentityRegisterResponse({ token: 123, client_id: "cid" })).toThrow(); + expect(() => parseIdentityRegisterResponse({ token: {}, client_id: "cid" })).toThrow(); + expect(() => parseIdentityRegisterResponse({ token: "tok", client_id: 123 })).toThrow(); + expect(() => parseIdentityRegisterResponse({ token: "tok", client_id: {} })).toThrow(); + expect(() => parseIdentityRegisterResponse({ token: "", client_id: "cid" })).toThrow(); + expect(() => parseIdentityRegisterResponse({ token: "tok" })).toThrow(); + }); + + it("rejects a non-string name", () => { + expect(() => parseIdentityRegisterResponse({ token: "tok", client_id: "cid", name: 123 })).toThrow(); + }); +}); + +describe("parseIdentityMeResponse (#7839)", () => { + it("accepts a rotation, a name-only update, and an empty object", () => { + expect(parseIdentityMeResponse({ token: "fresh", name: "Ada" })).toEqual({ token: "fresh", name: "Ada" }); + expect(parseIdentityMeResponse({ name: null })).toEqual({ token: null, name: null }); + expect(parseIdentityMeResponse({})).toEqual({ token: null, name: null }); + }); + + it("rejects non-object bodies", () => { + expect(() => parseIdentityMeResponse(null)).toThrow(); + expect(() => parseIdentityMeResponse("abc")).toThrow(); + expect(() => parseIdentityMeResponse([])).toThrow(); + }); + + it("rejects a numeric or object token instead of overwriting the stored one", () => { + expect(() => parseIdentityMeResponse({ token: 123 })).toThrow(); + expect(() => parseIdentityMeResponse({ token: { evil: 1 } })).toThrow(); + expect(() => parseIdentityMeResponse({ token: "" })).toThrow(); + expect(() => parseIdentityMeResponse({ token: null })).toThrow(); + }); + + it("rejects a non-string name", () => { + expect(() => parseIdentityMeResponse({ name: 123 })).toThrow(); + }); +}); + +describe("parseIdentityNameResponse (#7839)", () => { + it("accepts a string or null name", () => { + expect(parseIdentityNameResponse({ name: "Ada" })).toEqual({ name: "Ada" }); + expect(parseIdentityNameResponse({ name: null })).toEqual({ name: null }); + }); + + it("rejects a non-string name and non-object bodies", () => { + expect(() => parseIdentityNameResponse({ name: 123 })).toThrow(); + expect(() => parseIdentityNameResponse({ name: {} })).toThrow(); + expect(() => parseIdentityNameResponse({})).toThrow(); + expect(() => parseIdentityNameResponse(null)).toThrow(); + expect(() => parseIdentityNameResponse("abc")).toThrow(); + }); +}); diff --git a/pkgs/id/web/src/identity-refresh.ts b/pkgs/id/web/src/identity-refresh.ts index 5465812ef1..507a13042b 100644 --- a/pkgs/id/web/src/identity-refresh.ts +++ b/pkgs/id/web/src/identity-refresh.ts @@ -19,3 +19,94 @@ export function identityNeedsRefresh(refreshedAt: string | null, now: number, in if (elapsed < 0) return true; return elapsed >= intervalMs; } + +// ============================================================================ +// Identity endpoint response validation (#7839) +// ============================================================================ + +/** Validated `/api/identity/me` response: a rotated token and/or the current display name. */ +export interface IdentityMeResponse { + token: string | null; + name: string | null; +} + +/** Validated `/api/identity/register` response: the newly issued identity. */ +export interface IdentityRegisterResponse { + token: string; + clientId: string; + name: string | null; +} + +/** Validated `/api/identity/name` response: the stored display name. */ +export interface IdentityNameResponse { + name: string | null; +} + +function asIdentityRecord(payload: unknown, endpoint: string): Record { + if (typeof payload !== "object" || payload === null || Array.isArray(payload)) { + throw new Error(`malformed ${endpoint} response (expected an object)`); + } + return payload as Record; +} + +function identityNameField(value: unknown, endpoint: string): string | null { + if (value === undefined || value === null) return null; + if (typeof value !== "string") { + throw new Error(`malformed ${endpoint} response (name must be a string or null)`); + } + return value; +} + +function requiredIdentityString(value: unknown, field: string, endpoint: string): string { + if (typeof value !== "string" || value.length === 0) { + throw new Error(`malformed ${endpoint} response (${field} must be a non-empty string)`); + } + return value; +} + +/** + * Validate a `/api/identity/me` payload at the fetch boundary (#7839). + * + * The token is optional (present only when the server rotates it) and the + * name is optional, but either one, when present, must be a non-empty + * string / a string-or-null. Anything else throws, so the caller's error + * path leaves the stored identity untouched: without this check a + * wrong-shape 200 overwrote a valid stored token with the coerced string + * "[object Object]". + */ +export function parseIdentityMeResponse(payload: unknown): IdentityMeResponse { + const record = asIdentityRecord(payload, "/api/identity/me"); + const token = + record.token === undefined ? null : requiredIdentityString(record.token, "token", "/api/identity/me"); + return { token, name: identityNameField(record.name, "/api/identity/me") }; +} + +/** + * Validate a `/api/identity/register` payload at the fetch boundary + * (#7839). Both `token` and `client_id` are required non-empty strings: + * anything else throws before the caller can persist a fake identity + * (the unvalidated cast stored the literal strings "undefined" / + * "[object Object]" in localStorage as token/client_id). + */ +export function parseIdentityRegisterResponse(payload: unknown): IdentityRegisterResponse { + const record = asIdentityRecord(payload, "/api/identity/register"); + return { + token: requiredIdentityString(record.token, "token", "/api/identity/register"), + clientId: requiredIdentityString(record.client_id, "client_id", "/api/identity/register"), + name: identityNameField(record.name, "/api/identity/register"), + }; +} + +/** + * Validate a `/api/identity/name` payload at the fetch boundary (#7839). + * The response's only field is the stored display name, so it must be + * present and a string or null; anything else throws and the caller + * leaves the stored name unchanged. + */ +export function parseIdentityNameResponse(payload: unknown): IdentityNameResponse { + const record = asIdentityRecord(payload, "/api/identity/name"); + if (!("name" in record)) { + throw new Error("malformed /api/identity/name response (name must be a string or null)"); + } + return { name: identityNameField(record.name, "/api/identity/name") }; +} diff --git a/pkgs/id/web/src/main.ts b/pkgs/id/web/src/main.ts index 29be20ace0..222d86f0e9 100644 --- a/pkgs/id/web/src/main.ts +++ b/pkgs/id/web/src/main.ts @@ -11,7 +11,12 @@ import { AutoSaveManager, type SaveResult } from "./auto-save"; import { buildCollabWsUrl, type CollabConnection, initCollab } from "./collab"; import { type EditorInstance, getEditorState } from "./editor"; import { updateHeaderSubtitle } from "./header-subtitle"; -import { identityNeedsRefresh } from "./identity-refresh"; +import { + identityNeedsRefresh, + parseIdentityMeResponse, + parseIdentityNameResponse, + parseIdentityRegisterResponse, +} from "./identity-refresh"; import { clientIdForDisplay } from "./settings-identity"; import { closeImageBrowser } from "./image-browser"; import { createNavigation } from "./navigation"; @@ -145,16 +150,16 @@ async function ensureIdentity(): Promise { try { const resp = await fetch(`/api/identity/me?token=${encodeURIComponent(stored.token)}`); if (resp.ok) { - const data = await resp.json(); + const data = parseIdentityMeResponse(await resp.json()); // Server returns a refreshed token on each validation, resetting the // 30-day expiry clock. Save it so the client stays authenticated as // long as they visit within every 30 days. if (data.token) { stored.token = data.token; - saveIdentity(stored.token, stored.clientId, data.name || null); + saveIdentity(stored.token, stored.clientId, data.name); } // Update name from server (may have changed via another tab/session) - const serverName = data.name || null; + const serverName = data.name; if (serverName !== stored.name) { updateStoredName(serverName); stored.name = serverName; @@ -182,11 +187,11 @@ async function ensureIdentity(): Promise { console.error("[id] Identity registration failed:", resp.status); return null; } - const data = await resp.json(); + const data = parseIdentityRegisterResponse(await resp.json()); const identity: IdentityState = { token: data.token, - clientId: data.client_id, - name: data.name || null, + clientId: data.clientId, + name: data.name, }; saveIdentity(identity.token, identity.clientId, identity.name); console.log("[id] New identity registered:", identity.clientId); @@ -212,8 +217,8 @@ async function updateDisplayName(token: string, name: string | null): Promise Date: Tue, 10 Nov 2026 21:57:31 -0600 Subject: [PATCH 2/2] test(id/web): add property coverage for identity response parsers (#7839) --- pkgs/id/web/src/identity-refresh.test.ts | 103 +++++++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/pkgs/id/web/src/identity-refresh.test.ts b/pkgs/id/web/src/identity-refresh.test.ts index 3dbcf74630..7cd2e73203 100644 --- a/pkgs/id/web/src/identity-refresh.test.ts +++ b/pkgs/id/web/src/identity-refresh.test.ts @@ -124,3 +124,106 @@ describe("parseIdentityNameResponse (#7839)", () => { expect(() => parseIdentityNameResponse("abc")).toThrow(); }); }); + +// --------------------------------------------------------------------------- +// Property coverage for the three parsers (#7839, Codex P1 on PR #8505). +// Oracle: the independent acceptance predicates below, written directly from +// the endpoint contracts — they share no code with the parsers. Generator: a +// seeded PRNG builds random JSON-shaped values (random field subsets, random +// value types), so a failure reproduces from the seed alone. +// --------------------------------------------------------------------------- + +function mulberry32(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +const SCALARS: unknown[] = ["tok", "cid", "Ada", "", 123, 0, true, false, null, { evil: 1 }, ["x"]]; + +function randomIdentityPayload(rand: () => number): unknown { + if (rand() < 0.15) return SCALARS[Math.floor(rand() * SCALARS.length)]; + const record: Record = {}; + for (const field of ["token", "client_id", "name", "extra"]) { + if (rand() < 0.6) record[field] = SCALARS[Math.floor(rand() * SCALARS.length)]; + } + return record; +} + +function isPlainRecord(v: unknown): v is Record { + return typeof v === "object" && v !== null && !Array.isArray(v); +} +function nonEmptyString(v: unknown): v is string { + return typeof v === "string" && v.length > 0; +} +function nameOk(v: unknown): boolean { + return v === undefined || v === null || typeof v === "string"; +} + +// Independent acceptance predicates (the oracle). +function registerAccepts(v: unknown): boolean { + return isPlainRecord(v) && nonEmptyString(v.token) && nonEmptyString(v.client_id) && nameOk(v.name); +} +function meAccepts(v: unknown): boolean { + return isPlainRecord(v) && (v.token === undefined || nonEmptyString(v.token)) && nameOk(v.name); +} +function nameAccepts(v: unknown): boolean { + return isPlainRecord(v) && "name" in v && nameOk(v.name); +} + +describe("identity response parsers — property coverage (#7839)", () => { + const ITERATIONS = 2000; + + it("parseIdentityRegisterResponse agrees with its predicate on generated inputs, without coercion", () => { + const rand = mulberry32(0x7839a); + for (let i = 0; i < ITERATIONS; i++) { + const input = randomIdentityPayload(rand); + if (registerAccepts(input)) { + const rec = input as Record; + expect(parseIdentityRegisterResponse(input)).toEqual({ + token: rec.token, + clientId: rec.client_id, + name: typeof rec.name === "string" ? rec.name : null, + }); + } else { + expect(() => parseIdentityRegisterResponse(input)).toThrow(); + } + } + }); + + it("parseIdentityMeResponse agrees with its predicate on generated inputs, without coercion", () => { + const rand = mulberry32(0x7839b); + for (let i = 0; i < ITERATIONS; i++) { + const input = randomIdentityPayload(rand); + if (meAccepts(input)) { + const rec = input as Record; + expect(parseIdentityMeResponse(input)).toEqual({ + token: typeof rec.token === "string" ? rec.token : null, + name: typeof rec.name === "string" ? rec.name : null, + }); + } else { + expect(() => parseIdentityMeResponse(input)).toThrow(); + } + } + }); + + it("parseIdentityNameResponse agrees with its predicate on generated inputs, without coercion", () => { + const rand = mulberry32(0x7839c); + for (let i = 0; i < ITERATIONS; i++) { + const input = randomIdentityPayload(rand); + if (nameAccepts(input)) { + const rec = input as Record; + expect(parseIdentityNameResponse(input)).toEqual({ + name: typeof rec.name === "string" ? rec.name : null, + }); + } else { + expect(() => parseIdentityNameResponse(input)).toThrow(); + } + } + }); +});