Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 60 additions & 9 deletions pkgs/id/web/src/shell-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,23 +67,42 @@ const INTEGER_MAX: Partial<Record<FieldType, number>> = {
const encoder = new TextEncoder();
const byteLength = (text: string): number => encoder.encode(text).length;

function parseField(raw: RawField): Field {
function parseField(raw: unknown): Field {
if (typeof raw === "string") {
const optional = raw.endsWith("?");
const kind = optional ? raw.slice(0, -1) : raw;
if (!FIELD_TYPES.has(kind)) throw new Error(`unknown field type \`${kind}\``);
return { kind: kind as FieldType, optional, nullable: optional };
}
if (!FIELD_TYPES.has(raw.type)) throw new Error(`unknown field type \`${raw.type}\``);
if (!isObject(raw)) throw new Error("field spec must be a string or object");
const kind = raw.type;
if (typeof kind !== "string" || !FIELD_TYPES.has(kind)) {
throw new Error(`unknown field type \`${String(kind)}\``);
}
const optional = raw.optional ?? false;
if (typeof optional !== "boolean") throw new Error("optional must be a boolean");
const nullable = raw.nullable ?? optional;
if (typeof nullable !== "boolean") throw new Error("nullable must be a boolean");
for (const key of ["min", "max", "max_bytes"] as const) {
const bound = raw[key];
if (bound !== undefined && (typeof bound !== "number" || !Number.isFinite(bound))) {
throw new Error(`${key} must be a finite number`);
}
}
if (
raw.enum !== undefined &&
(!Array.isArray(raw.enum) || raw.enum.some((item) => typeof item !== "string"))
) {
throw new Error("enum must be an array of strings");
}
return {
kind: raw.type,
kind: kind as FieldType,
optional,
nullable: raw.nullable ?? optional,
min: raw.min,
max: raw.max,
maxBytes: raw.max_bytes,
allowed: raw.enum,
nullable,
min: raw.min as number | undefined,
max: raw.max as number | undefined,
maxBytes: raw.max_bytes as number | undefined,
allowed: raw.enum as string[] | undefined,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate constraint types before accepting field specs

When a contract contains a malformed constraint such as chat.text: {"type":"string","enum":7}, the new parseShellContract accepts it because this assertion performs no runtime validation. Passing the returned contract to checkClientFrame with a chat message then throws TypeError: field.allowed.includes is not a function, bypassing the failed-check handling and preventing Conformance from recording a violation. Validate the constraint types during parsing, particularly that enum is an array of strings, so successfully loaded contracts cannot reach this failure.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 04af08e: parseField now validates constraint types at load — enum must be an array of strings, and min/max/max_bytes must be finite numbers — so parseShellContract rejects a malformed spec with the frame.field prefix instead of letting checkValue throw later. Regression tests added ("rejects malformed constraint values when loading a contract"); bun run test -- src/world-contract.test.ts passes 21/21 on the laptop.

};
}

Expand All @@ -92,6 +111,32 @@ const isObject = (value: unknown): value is Record<string, unknown> =>

const isInteger = (value: unknown): value is number => typeof value === "number" && Number.isInteger(value);

/** Parse a contract document, validating every client and server field spec. */
export function parseShellContract(value: unknown): ShellContract {
if (!isObject(value)) throw new Error("shell contract must be an object");

for (const side of ["client_frames", "server_frames"] as const) {
const frames = value[side];
if (!isObject(frames)) throw new Error(`${side} must be an object`);

for (const [frameName, frame] of Object.entries(frames)) {
if (!isObject(frame) || !isObject(frame.fields)) {
throw new Error(`${frameName}: frame fields must be an object`);
}
for (const [fieldName, raw] of Object.entries(frame.fields)) {
try {
parseField(raw);
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
throw new Error(`${frameName}.${fieldName}: ${detail}`);
}
}
}
}

return value as unknown as ShellContract;
}

function lookup(
contract: ShellContract,
frame: unknown,
Expand Down Expand Up @@ -185,7 +230,13 @@ function checkFields(
if (!Object.hasOwn(spec.fields, key)) return `\`${kind}\` has no field \`${key}\``;
}
for (const [name, raw] of Object.entries(spec.fields)) {
const field = parseField(raw);
let field: Field;
try {
field = parseField(raw);
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
return `\`${kind}.${name}\` has an invalid field spec: ${detail}`;
}
const present = Object.hasOwn(object, name) && object[name] !== undefined;
const value = present ? object[name] : undefined;
if (!present && field.optional) continue;
Expand Down
93 changes: 86 additions & 7 deletions pkgs/id/web/src/world-contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,33 @@ import { readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { Conformance, checkClientFrame, checkServerFrame, type ShellContract } from "./shell-contract";
import {
Conformance,
checkClientFrame,
checkServerFrame,
parseShellContract,
type ShellContract,
} from "./shell-contract";

const here = dirname(fileURLToPath(import.meta.url));
const contract = JSON.parse(
const contractDocument: unknown = JSON.parse(
readFileSync(resolve(here, "../../contract/shell-contract.v1.json"), "utf8"),
) as ShellContract;
);
const contract = parseShellContract(contractDocument);

function withFieldType(
side: "client" | "server",
frameName: string,
fieldName: string,
type: string,
): ShellContract {
const malformed = structuredClone(contract);
const frames = side === "client" ? malformed.client_frames : malformed.server_frames;
const frame = frames[frameName];
if (!frame) throw new Error(`missing ${side} frame ${frameName}`);
(frame.fields as Record<string, unknown>)[fieldName] = type;
return malformed;
}

/** The world page markup, read from the Rust template so the test cannot drift from it. */
function worldPageMarkup(): string {
Expand All @@ -22,6 +43,58 @@ function worldPageMarkup(): string {
describe("shell contract validator", () => {
const cap = "cap";

it("validates every client and server field spec when loading a contract", () => {
expect(parseShellContract(contractDocument)).toEqual(contract);

const malformedClient = withFieldType("client", "chat", "text", "u65");
expect(() => parseShellContract(malformedClient)).toThrow("chat.text: unknown field type `u65`");

const malformedServer = withFieldType("server", "view", "sequence", "u65");
expect(() => parseShellContract(malformedServer)).toThrow("view.sequence: unknown field type `u65`");
});

it("rejects malformed constraint values when loading a contract", () => {
const badEnum = structuredClone(contract);
(badEnum.client_frames.chat!.fields as Record<string, unknown>).text = { type: "string", enum: 7 };
expect(() => parseShellContract(badEnum)).toThrow("chat.text: enum must be an array of strings");

const badBound = structuredClone(contract);
(badBound.client_frames.chat!.fields as Record<string, unknown>).text = { type: "string", max_bytes: "9" };
expect(() => parseShellContract(badBound)).toThrow("chat.text: max_bytes must be a finite number");
});

it("returns violations instead of throwing for malformed field specs", () => {
const malformedClient = withFieldType("client", "chat", "text", "u65");
const clientCheck = checkClientFrame(malformedClient, { type: "chat", text: "hi" }, "joined");
expect(clientCheck).toEqual({
ok: false,
error: expect.stringContaining("chat.text"),
});
if (!clientCheck.ok) expect(clientCheck.error).toContain("unknown field type `u65`");

const malformedServer = withFieldType("server", "view", "sequence", "u65");
const serverCheck = checkServerFrame(malformedServer, {
type: "view",
sequence: 1,
data: "x",
surface: null,
view_revision: 1,
});
expect(serverCheck).toEqual({
ok: false,
error: expect.stringContaining("view.sequence"),
});
if (!serverCheck.ok) expect(serverCheck.error).toContain("unknown field type `u65`");

const session = new Conformance(malformedClient);
session.client({ type: "join", capability: cap, after: null, world: null });
expect(session.phase).toBe("joined");
expect(() => session.client({ type: "chat", text: "hi" })).not.toThrow();
expect(session.violations).toEqual([
{ index: 1, side: "client", message: expect.stringContaining("chat.text") },
]);
});

it("accepts the frames a joined shell sends", () => {
expect(checkClientFrame(contract, { type: "join", capability: cap, after: null, world: null }, "opening")).toEqual({
ok: true,
Expand All @@ -30,7 +103,9 @@ describe("shell contract validator", () => {
expect(checkClientFrame(contract, { type: "resize", width: 500, height: 200 }, "joined").ok).toBe(true);
expect(checkClientFrame(contract, { type: "input", data_hex: "1b5b41" }, "joined").ok).toBe(true);
expect(checkClientFrame(contract, { type: "records", capability: cap, after: "k" }, "joined").ok).toBe(true);
expect(checkServerFrame(contract, { type: "view", sequence: 1, data: "x", surface: null }).ok).toBe(true);
expect(
checkServerFrame(contract, { type: "view", sequence: 1, data: "x", surface: null, view_revision: 1 }).ok,
).toBe(true);
});

it.each([
Expand Down Expand Up @@ -67,7 +142,9 @@ describe("shell contract validator", () => {
expect(seed(2 ** 53).ok).toBe(true);
// u64::MAX as it arrives from wire JSON: already rounded by the parser.
expect(seed(JSON.parse("18446744073709551615") as number).ok).toBe(true);
expect(checkServerFrame(contract, { type: "view", sequence: 2 ** 53, data: "x", surface: null }).ok).toBe(true);
expect(
checkServerFrame(contract, { type: "view", sequence: 2 ** 53, data: "x", surface: null, view_revision: 1 }).ok,
).toBe(true);
expect(checkServerFrame(contract, { type: "records", sequence: 2 ** 53, records: {} }).ok).toBe(true);
});

Expand All @@ -80,7 +157,9 @@ describe("shell contract validator", () => {
expect(over64.ok).toBe(false);
if (!over64.ok) expect(over64.error).toContain("18446744073709551615");
expect(seed(1e100).ok).toBe(false);
expect(checkServerFrame(contract, { type: "view", sequence: 2 ** 65, data: "x", surface: null }).ok).toBe(false);
expect(
checkServerFrame(contract, { type: "view", sequence: 2 ** 65, data: "x", surface: null, view_revision: 1 }).ok,
).toBe(false);
});

it("still enforces the u64 bounds JS can check exactly (#1441)", () => {
Expand Down Expand Up @@ -247,7 +326,7 @@ describe("web shell conformance", () => {
type: "snapshot",
snapshot: { world_id: "lobby", current_sequence: 4, participants: [{ id: 1, display_name: "ada" }], seed: 0 },
});
session.deliver({ type: "view", sequence: 4, data: "hello", surface: null });
session.deliver({ type: "view", sequence: 4, data: "hello", surface: null, view_revision: 1 });
expect(q("[data-world-view]").textContent).toBe("hello");
expect(session.sent("records")).toEqual([{ type: "records", capability: "guest-capability" }]);
session.deliver({ type: "records", sequence: 4, records: { a: 1 }, next_after: "a" });
Expand Down
Loading