From a2051e9d72cba84d9fbf3a6d2ecdf51c982cadaa Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 16:05:54 -0800 Subject: [PATCH 01/10] chore(quest): claim quest/m1/js-net-input-checks.md Quest-Claim: c0d9874500216a7e From fd7f4cbb71dfab7a4deea35701cc8f990b130c04 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 16:14:55 -0800 Subject: [PATCH 02/10] fix(net): js/net parses dial targets once and checks the inputs Rust does Co-Authored-By: Claude Opus 5.5 --- js/net/src/connection/accept.ts | 4 +- js/net/src/connection/connect.test.ts | 22 +++- js/net/src/connection/connect.ts | 31 ++---- js/net/src/connection/endpoint.test.ts | 73 +++++++++++++ js/net/src/connection/endpoint.ts | 144 +++++++++++++++++++++++++ js/net/src/connection/goaway.test.ts | 36 ++----- js/net/src/connection/goaway.ts | 116 ++++---------------- js/net/src/connection/reload.ts | 12 ++- js/net/src/datagram.ts | 3 +- js/net/src/open.test.ts | 27 +++++ js/net/src/open.ts | 4 +- js/net/src/track.test.ts | 7 ++ js/net/src/util/log.test.ts | 12 --- js/net/src/util/log.ts | 4 - js/net/src/util/sequence.ts | 3 +- 15 files changed, 322 insertions(+), 176 deletions(-) create mode 100644 js/net/src/connection/endpoint.test.ts create mode 100644 js/net/src/connection/endpoint.ts delete mode 100644 js/net/src/util/log.test.ts delete mode 100644 js/net/src/util/log.ts diff --git a/js/net/src/connection/accept.ts b/js/net/src/connection/accept.ts index 7156d204208..7bb37ef4ba5 100644 --- a/js/net/src/connection/accept.ts +++ b/js/net/src/connection/accept.ts @@ -25,7 +25,7 @@ export interface AcceptProps { /** Abort the handshake and release the transport; ignored after acceptance completes. */ signal?: AbortSignal; - /** The moq-lite version to select in a `moql` SETUP, instead of the client's first. */ + /** The only moq-lite version to accept in a `moql` SETUP, instead of the client's first; refused unless the client offers it. */ version?: number; /** @@ -185,7 +185,7 @@ async function acceptNegotiated( if (!stream) throw new Error("no incoming bidi stream for SETUP"); const client = await Lite.ClientSetup.decode(stream.reader); - const selected = version ?? client.versions.find(Lite.isNegotiated); + const selected = client.versions.find((v) => (version === undefined ? Lite.isNegotiated(v) : v === version)); if (selected === undefined || !Lite.isNegotiated(selected)) { throw new Error( `no common version found; client offered: ${client.versions.map((v) => v.toString(16)).join(", ")}`, diff --git a/js/net/src/connection/connect.test.ts b/js/net/src/connection/connect.test.ts index 0f516a9ed4f..d569941687f 100644 --- a/js/net/src/connection/connect.test.ts +++ b/js/net/src/connection/connect.test.ts @@ -279,9 +279,9 @@ test("connect logs the relay URL without its credentials", async () => { restoreTransport(); } - // The diagnostics must still identify the relay, just without the query. + // The diagnostics must still identify the relay, just without the path or query. expect(captured.lines.length).toBeGreaterThan(0); - expect(captured.lines.every((line) => line.includes("https://example.com/test"))).toBe(true); + expect(captured.lines.every((line) => line.includes("https://example.com:443"))).toBe(true); for (const line of captured.lines) { expect(line).not.toContain(SECRET); @@ -559,20 +559,34 @@ test("SETUP refuses a version the client did not name", async () => { const pair = createMockTransportPair(""); const restore = stubWebTransport(pair.client); try { - const server = accept({ url, transport: pair.server, version: Lite.DRAFT_05 }).catch(() => undefined); const connecting = connect(url, { versions: ["moq-lite-07-wip", "moq-lite-06"], websocket: { enabled: false }, }); + // Handled now, since the refusal can land while the write below yields. + connecting.catch(() => {}); + const stream = await Stream.accept(pair.server, Lite.DRAFT_02); + if (!stream) throw new Error("no SETUP stream"); + await ClientSetup.decode(stream.reader); + await new ServerSetup(Lite.DRAFT_05).encode(stream.writer); // The refusal waits out the grace a peer's close code gets. await driveUntil(clock, connecting); await expect(connecting).rejects.toThrow("unsupported server version: 0xff0dad05"); - (await server)?.abort(); } finally { restore(); } }); +test("a server pinned to a version the client did not offer refuses the SETUP", async () => { + const pair = createMockTransportPair(""); + const accepting = accept({ url, transport: pair.server, version: Lite.DRAFT_05 }); + // Handled now, since the refusal can land while the write below yields. + accepting.catch(() => {}); + const stream = await Stream.open(pair.client, { version: Lite.DRAFT_02 }); + await new ClientSetup([Lite.DRAFT_07, Lite.DRAFT_06]).encode(stream.writer); + await expect(accepting).rejects.toThrow("no common version found"); +}); + test("a peer without an ALPN is refused when no named version negotiates in SETUP", async () => { const pair = createMockTransportPair(""); const restore = stubWebTransport(pair.client); diff --git a/js/net/src/connection/connect.ts b/js/net/src/connection/connect.ts index 3e32c75efc3..29562262dc3 100644 --- a/js/net/src/connection/connect.ts +++ b/js/net/src/connection/connect.ts @@ -11,11 +11,11 @@ import * as Lite from "../lite/index.ts"; import type { Consumer as OriginConsumer, Producer as OriginProducer } from "../origin.ts"; import { Stream } from "../stream.ts"; import * as Hex from "../util/hex.ts"; -import { redact } from "../util/log.ts"; import { after } from "../util/timer.ts"; import { isWebTransportSupported } from "./browser.ts"; import type { Established } from "./established.ts"; import * as Extensions from "./extensions.ts"; +import { parse, show } from "./endpoint.ts"; import { DISCOVERY_REMOVED, forwardAnnounced } from "./forward.ts"; import { DEFAULT_TIMEOUT, exchangeSetup, handsOff } from "./handshake.ts"; import { inspect } from "./stats.ts"; @@ -332,8 +332,8 @@ const websocketWon = new Set(); /** The {@link websocketWon} key for the URL the WebSocket fallback dials. */ function websocketKey(url: URL): string { - const port = url.port || (url.protocol === "http:" || url.protocol === "ws:" ? "80" : "443"); - return `${url.hostname}:${port}`; + const endpoint = parse(url); + return `${endpoint.url.hostname}:${endpoint.port}`; } /** The default connect signal: never aborts. */ @@ -393,17 +393,6 @@ export async function connect({ url, ...props }: ConnectProps): Promise { const offered = offer(props.versions); const dial = credential(raw, tokens, offered.setupToken); - const url = dialable(dial.url); + const url = parse(dial.url).url; const fallbackDial = props.websocket?.url && fallback(raw, props.websocket.url, tokens, offered.setupToken); const wiring = (presented: Presentation): SessionProps => ({ publish: props.publish, @@ -493,10 +482,10 @@ async function connectInner( // Record who won the race to this server, so QUIC's next head start follows the last result. if (session instanceof Session) { - console.debug(redact(url), "connected via WebSocket"); + console.debug(show(parse(url)), "connected via WebSocket"); websocketWon.add(server); } else { - console.debug(redact(url), "connected via WebTransport"); + console.debug(show(parse(url)), "connected via WebTransport"); websocketWon.delete(server); } @@ -561,7 +550,7 @@ async function negotiate( // The DOM lib has no `protocol` property yet. It is "" when none was negotiated, and // undefined in a browser that predates subprotocols (Firefox before 155). const protocol: string | undefined = (session as { protocol?: string }).protocol || undefined; - console.debug(redact(url), "negotiated ALPN:", protocol ?? "(none)"); + console.debug(show(parse(url)), "negotiated ALPN:", protocol ?? "(none)"); const ietf = protocol === Ietf.ALPN.DRAFT_22 @@ -719,7 +708,7 @@ async function hedgeWebTransport( (err: unknown) => err instanceof Elapsed, ); if (!hedge) return first; - console.debug(redact(url), `WebTransport not open after ${WEBTRANSPORT_HEDGE}ms; dialing a second`); + console.debug(show(parse(url)), `WebTransport not open after ${WEBTRANSPORT_HEDGE}ms; dialing a second`); const dials = [first, connectWebTransport(url, cancel, alpns, options)]; try { @@ -766,7 +755,7 @@ async function connectWebTransport( // Dev-only path: http:// can't be a real WebTransport origin, so we fetch the // self-signed cert's hash over plain HTTP and pin it. Production uses https:// // and never reaches here. Keep this at debug so it doesn't read as a problem. - console.debug(redact(fingerprintUrl), "performing an insecure fingerprint fetch; use https:// in production"); + console.debug(show(parse(fingerprintUrl)), "performing an insecure fingerprint fetch; use https:// in production"); const fingerprint = await fetchFingerprint(fingerprintUrl, cancel); if (!fingerprint) return undefined; @@ -883,7 +872,7 @@ async function connectWebSocket( if (outcome === "open") return quic; quic.close(); if (outcome !== "redial") return undefined; - console.debug(redact(url), `WebSocket not open after ${wait}ms; dialing again`); + console.debug(show(parse(url)), `WebSocket not open after ${wait}ms; dialing again`); } finally { disarm.abort(); } diff --git a/js/net/src/connection/endpoint.test.ts b/js/net/src/connection/endpoint.test.ts new file mode 100644 index 00000000000..6ac2dddcc28 --- /dev/null +++ b/js/net/src/connection/endpoint.test.ts @@ -0,0 +1,73 @@ +import { expect, test } from "bun:test"; +import { isLocal, parse, sameHost, show } from "./endpoint.ts"; + +const local = (url: string) => isLocal(parse(new URL(url))); + +test("local literals are recognized in every spelling the dial accepts", () => { + const spellings = [ + "https://127.0.0.1/", + "https://localhost/", + "https://localhost./", + "https://a.localhost/", + "https://[::1]/", + "https://[::]/", + "https://10.0.0.1/", + "https://172.16.0.1/", + "https://192.168.1.1/", + "https://169.254.1.1/", + "https://0.0.0.0/", + "https://[::ffff:10.0.0.1]/", + "https://[fe80::1]/", + "https://[fc00::1]/", + "moqt://127.0.0.1/", + "moqt://[::ffff:127.0.0.1]/", + // Shorthand, hex, and decimal IPv4, which raw QUIC dials as 127.0.0.1. + "moql://127.1/", + "moql://0x7f000001/", + "moql://2130706433/", + "moql://0177.0.0.1/", + "moql://LOCALHOST/", + "moql://0/", + ]; + for (const url of spellings) expect(local(url), url).toBe(true); + + for (const url of ["https://example.com/", "https://8.8.8.8/", "https://172.32.0.1/", "https://[2606:4700::1]/"]) { + expect(local(url), url).toBe(false); + } + expect(local("moql://8.8.8.8/")).toBe(false); +}); + +test("a URL with no host is refused, since nothing here dials one", () => { + expect(() => parse(new URL("unix:///tmp/moq.sock"))).toThrow(TypeError); + expect(() => parse(new URL("moql:relay.example"))).toThrow(TypeError); +}); + +test("a raw QUIC URL dials over https at the same host, port, and path", () => { + const endpoint = parse(new URL("moql://user:pass@127.1:4443/room?jwt=secret")); + expect(endpoint.scheme).toBe("moql"); + expect(endpoint.host).toEqual({ kind: "ipv4", octets: [127, 0, 0, 1] }); + expect(endpoint.port).toBe(4443); + expect(endpoint.url.href).toBe("https://user:pass@127.0.0.1:4443/room?jwt=secret"); + + const plain = new URL("https://relay.example/room"); + expect(parse(plain).url).toBe(plain); + expect(parse(new URL("moqt://relay.example")).port).toBe(443); + expect(parse(new URL("http://relay.example")).port).toBe(80); +}); + +test("hosts compare as dialed, whatever the scheme or spelling", () => { + const at = (url: string) => parse(new URL(url)); + expect(sameHost(at("moql://127.1/"), at("https://127.0.0.1:4443/"))).toBe(true); + expect(sameHost(at("moqt://[::FFFF:7F00:1]/"), at("https://[::ffff:127.0.0.1]/"))).toBe(true); + expect(sameHost(at("moql://Relay.Example/"), at("wss://relay.example/"))).toBe(true); + expect(sameHost(at("https://relay.example/"), at("https://relay.example.com/"))).toBe(false); +}); + +test("an endpoint shows only its scheme, host, and port", () => { + const shown = (url: string) => show(parse(new URL(url))); + expect(shown("https://user:password@relay.example.com/anon/room?jwt=secret#frag")).toBe( + "https://relay.example.com:443", + ); + expect(shown("moql://relay.example:4443/secret-token/room")).toBe("moql://relay.example:4443"); + expect(shown("http://localhost?jwt=secret")).toBe("http://localhost:80"); +}); diff --git a/js/net/src/connection/endpoint.ts b/js/net/src/connection/endpoint.ts new file mode 100644 index 00000000000..3ba394affed --- /dev/null +++ b/js/net/src/connection/endpoint.ts @@ -0,0 +1,144 @@ +/** + * Where a URL dials, parsed once so every decision about it reads the host the transport + * connects to: GOAWAY redirect checks, the dial itself, and what logs show. + * + * Mirrors `rs/moq-net/src/reconnect/redirect.rs`. + * + * @module + */ + +/** A host as a dial reads it: an IPv4 or IPv6 literal, or a name left to DNS. */ +export type Host = + | { readonly kind: "ipv4"; readonly octets: readonly number[] } + | { readonly kind: "ipv6"; readonly segments: readonly number[] } + | { readonly kind: "name"; readonly name: string }; + +/** Where a URL dials: its scheme, its host, and its port, which defaults by scheme. */ +export interface Endpoint { + /** The scheme without its colon, as written (`moql`, not the `https` a browser dials it over). */ + readonly scheme: string; + readonly host: Host; + readonly port: number; + /** + * The URL a browser transport dials. A raw QUIC `moqt:` or `moql:` URL is reached over + * WebTransport with its scheme swapped for https (draft-ietf-moq-transport-18 §3.1.3); the + * CONNECT carries the scheme, so a server refuses the raw one. + */ + readonly url: URL; +} + +/** + * Parse where `url` dials. Throws a `TypeError` for a URL with no host, which no transport + * here can dial. + * + * Only the special schemes (`http`, `https`, `ws`, `wss`) have their host parsed by the URL + * parser; any other scheme keeps it opaque, so `moql://127.1` reads `127.1` while the dial, + * made over https, connects to 127.0.0.1. Reading the host back through https makes both the + * same: an address in any spelling the dial accepts is that address here. + */ +export function parse(url: URL): Endpoint { + if (url.host === "") throw new TypeError(`${url.protocol} URL has no host`); + const scheme = url.protocol.slice(0, -1); + const special = SPECIAL.has(scheme); + // Rebuilt rather than assigned, since the URL setter refuses a change from a non-special + // scheme to a special one. + const dial = special ? url : new URL(`https:${url.href.slice(url.protocol.length)}`); + const port = url.port === "" ? defaultPort(scheme) : Number(url.port); + return { scheme, host: parseHost(dial.hostname), port, url: dial }; +} + +const SPECIAL = new Set(["http", "https", "ws", "wss"]); + +function defaultPort(scheme: string): number { + return scheme === "http" || scheme === "ws" ? 80 : 443; +} + +// The URL parser leaves a special scheme's host canonical: an IPv4 address as a dotted quad, +// an IPv6 one bracketed in lowercase hex without a zone or dotted tail, and a name lowercased. +function parseHost(hostname: string): Host { + if (hostname.startsWith("[")) { + const segments = parseIpv6(hostname.slice(1, -1)); + if (!segments) throw new TypeError(`unparsable IPv6 host: ${hostname}`); + return { kind: "ipv6", segments }; + } + const parts = hostname.split("."); + if (parts.length === 4 && parts.every((part) => /^\d{1,3}$/.test(part))) { + return { kind: "ipv4", octets: parts.map(Number) }; + } + return { kind: "name", name: hostname }; +} + +function parseIpv6(text: string): number[] | undefined { + const halves = text.split("::"); + const words = (part: string) => (part === "" ? [] : part.split(":")); + const head = words(halves[0] ?? ""); + const rest = halves.length === 2 ? words(halves[1] ?? "") : []; + const all = [...head, ...Array(8 - head.length - rest.length).fill("0"), ...rest]; + const segments = all.map((word) => Number.parseInt(word, 16)); + return segments.length === 8 && !segments.some(Number.isNaN) ? segments : undefined; +} + +/** Whether two endpoints dial the same host, whatever their scheme or port. */ +export function sameHost(a: Endpoint, b: Endpoint): boolean { + // The dial URL's host is canonical, so equal hosts spell it the same. + return a.url.hostname === b.url.hostname; +} + +/** + * Formats an endpoint for logs and errors as scheme, host, and port only. + * + * A URL can carry a credential in its userinfo, query, or path (raw QUIC has no headers, so a + * token can ride as a path segment). Dropping all three rather than redacting known-secret + * spellings is deliberate: a denylist only covers the credentials that exist today. + */ +export function show(endpoint: Endpoint): string { + return `${endpoint.scheme}://${endpoint.url.hostname}:${endpoint.port}`; +} + +/** + * Whether an endpoint says it names something only reachable from this host or network. A + * judgement about the address it spells, not about where a dial lands: a name is dialed, + * never resolved here, so `false` means "not local on its face", never "verified remote". + */ +export function isLocal({ host }: Endpoint): boolean { + switch (host.kind) { + case "ipv4": + return isLocalV4(host.octets); + case "ipv6": + return isLocalV6(host.segments); + case "name": { + // A trailing dot names the same host from the root. + const name = host.name.endsWith(".") ? host.name.slice(0, -1) : host.name; + return name === "localhost" || name.endsWith(".localhost"); + } + } +} + +function isLocalV4([a, b, c, d]: readonly number[]): boolean { + return ( + a === 127 || + a === 10 || + (a === 172 && b >= 16 && b <= 31) || + (a === 192 && b === 168) || + (a === 169 && b === 254) || + (a === 0 && b === 0 && c === 0 && d === 0) + ); +} + +function isLocalV6(segments: readonly number[]): boolean { + // An IPv4-mapped address reaches the same host as the v4 it wraps. + if (segments.slice(0, 5).every((s) => s === 0) && segments[5] === 0xffff) { + const [hi = 0, lo = 0] = segments.slice(6); + return isLocalV4([hi >> 8, hi & 0xff, lo >> 8, lo & 0xff]); + } + const first = segments[0] ?? 0; + const zeroPrefix = segments.slice(0, 7).every((s) => s === 0); + const last = segments[7] ?? 0; + return ( + // Loopback (::1) and unspecified (::). + (zeroPrefix && (last === 1 || last === 0)) || + // Unique local (fc00::/7) and link local (fe80::/10). + (first & 0xfe00) === 0xfc00 || + (first & 0xffc0) === 0xfe80 + ); +} diff --git a/js/net/src/connection/goaway.test.ts b/js/net/src/connection/goaway.test.ts index c9515e47f06..c0dd7191132 100644 --- a/js/net/src/connection/goaway.test.ts +++ b/js/net/src/connection/goaway.test.ts @@ -1,7 +1,7 @@ import { expect, test } from "bun:test"; import { Milli } from "@moq/clock"; import { RefusedRedirect } from "../error.ts"; -import { dialed, handover, isLocal, pinnedTransport, type Redirect, target } from "./goaway.ts"; +import { dialed, handover, pinnedTransport, type Redirect, target } from "./goaway.ts"; const current = new URL("https://relay.example/room?jwt=secret"); @@ -22,6 +22,11 @@ test("an explicit URI the policy will not follow is refused, not ignored", () => ["follow", "https://[::ffff:127.0.0.1]/"], ["follow", "https://[::ffff:7f00:1]/"], ["follow", "moqt://169.254.169.254/"], + // Raw QUIC dials over https, which reads each of these as 127.0.0.1. + ["follow", "moql://127.1/"], + ["follow", "moql://0x7f000001/"], + ["follow", "moql://2130706433/"], + ["follow", "moqt://[::FFFF:127.0.0.1]/"], ]; for (const [policy, uri] of refused) { expect(() => target(policy, uri, current, false), `${policy}: ${uri}`).toThrow(RefusedRedirect); @@ -61,30 +66,11 @@ test("a certificate pin holds the host even under follow", () => { expect(target("follow", "https://relay.example:5443/", current, true)?.port).toBe("5443"); }); -test("local literals are recognized in every spelling", () => { - const local = [ - "https://127.0.0.1/", - "https://localhost/", - "https://a.localhost/", - "https://[::1]/", - "https://[::]/", - "https://10.0.0.1/", - "https://172.16.0.1/", - "https://192.168.1.1/", - "https://169.254.1.1/", - "https://0.0.0.0/", - "https://[::ffff:10.0.0.1]/", - "https://[fe80::1]/", - "https://[fc00::1]/", - "moqt://127.0.0.1/", - "moqt://[::ffff:127.0.0.1]/", - "unix:///tmp/moq.sock", - ]; - for (const url of local) expect(isLocal(new URL(url)), url).toBe(true); - - for (const url of ["https://example.com/", "https://8.8.8.8/", "https://172.32.0.1/", "https://[2606:4700::1]/"]) { - expect(isLocal(new URL(url)), url).toBe(false); - } +test("same-host compares the host a raw QUIC URL dials", () => { + const raw = new URL("moql://relay.example/room"); + expect(target("same-host", "moql://RELAY.example:4443/room", raw, false)?.port).toBe("4443"); + expect(target("same-host", "https://relay.example/room", raw, false)?.protocol).toBe("https:"); + expect(() => target("same-host", "moql://other.example/", raw, false)).toThrow(RefusedRedirect); }); test("a WebSocket fallback that connected is the host a redirect is judged against", () => { diff --git a/js/net/src/connection/goaway.ts b/js/net/src/connection/goaway.ts index 73e0f2b0f9b..8c4f062ed4d 100644 --- a/js/net/src/connection/goaway.ts +++ b/js/net/src/connection/goaway.ts @@ -7,6 +7,7 @@ import { Milli } from "@moq/clock"; import { RefusedRedirect } from "../error.ts"; +import { type Endpoint, isLocal, parse, sameHost } from "./endpoint.ts"; import type { Transport } from "./transport.ts"; /** A peer's GOAWAY as a session received it. */ @@ -94,31 +95,34 @@ export function target(policy: Redirect, uri: string, current: URL, pinned: bool // Parse before `ignore`: a malformed redirect is terminal even when the policy // would otherwise stay on the current URL. let next: URL; + let to: Endpoint; try { next = new URL(uri); + to = parse(next); } catch { throw new RefusedRedirect("the GOAWAY URI is malformed"); } if (policy === "ignore") return undefined; + const from = parse(current); - if (schemeTier(next.protocol) < schemeTier(current.protocol)) { + if (schemeTier(to.scheme) < schemeTier(from.scheme)) { throw new RefusedRedirect("the GOAWAY redirect downgrades the scheme"); } // Only as far as the URL itself says: a name is dialed, never resolved here, so this // refuses a peer naming a local address outright, not one hiding it behind a hostname. // That gap is why `same-host` is the default. - if (isLocal(next) && !isLocal(current)) { + if (isLocal(to) && !isLocal(from)) { throw new RefusedRedirect("the GOAWAY redirect widens reachability to a local address"); } // Host only, not the full authority: the port is what a peer legitimately moves us // across when it hands off to a sibling process on the same box. - const sameHost = next.hostname === current.hostname; - if (policy === "same-host" && !sameHost) { + const same = sameHost(to, from); + if (policy === "same-host" && !same) { throw new RefusedRedirect("the GOAWAY redirect leaves the current host"); } - if (pinned && !sameHost) { + if (pinned && !same) { throw new RefusedRedirect("the GOAWAY redirect leaves the host a certificate pin verifies"); } @@ -126,102 +130,18 @@ export function target(policy: Redirect, uri: string, current: URL, pinned: bool } /** Rank a scheme so a redirect cannot silently drop encryption; unknown schemes rank lowest. */ -function schemeTier(protocol: string): number { - switch (protocol) { - case "https:": - case "wss:": - case "moqt:": - case "moql:": +function schemeTier(scheme: string): number { + switch (scheme) { + case "https": + case "wss": + case "moqt": + case "moql": return 2; - case "http:": - case "ws:": - case "tcp:": + case "http": + case "ws": + case "tcp": return 1; default: return 0; } } - -/** - * Whether a URL says it names something only reachable from this host or network. A judgement - * about the URL, not about where a dial lands: `false` means "not local on its face". - * - * @internal - */ -export function isLocal(url: URL): boolean { - const host = url.hostname.toLowerCase(); - // No host at all, e.g. a `unix:` socket path. - if (host === "") return true; - if (host === "localhost" || host.endsWith(".localhost")) return true; - - if (host.startsWith("[") && host.endsWith("]")) { - const segments = parseIpv6(host.slice(1, -1)); - return segments !== undefined && isLocalV6(segments); - } - - const v4 = parseIpv4(host); - return v4 !== undefined && isLocalV4(v4); -} - -function parseIpv4(host: string): number[] | undefined { - const parts = host.split("."); - if (parts.length !== 4) return undefined; - const octets = parts.map((part) => (/^\d{1,3}$/.test(part) ? Number(part) : Number.NaN)); - return octets.every((octet) => octet <= 255) ? octets : undefined; -} - -function isLocalV4([a, b, c, d]: number[]): boolean { - return ( - a === 127 || - a === 10 || - (a === 172 && b >= 16 && b <= 31) || - (a === 192 && b === 168) || - (a === 169 && b === 254) || - (a === 0 && b === 0 && c === 0 && d === 0) - ); -} - -/** Parse an IPv6 literal (without brackets) into its eight 16-bit segments. */ -function parseIpv6(host: string): number[] | undefined { - // Drop a zone id; it scopes the address without changing it. - let text = host.split("%")[0] ?? ""; - - // A trailing dotted quad (`::ffff:127.0.0.1`) spells the last two segments. - const lastColon = text.lastIndexOf(":"); - const quad = parseIpv4(text.slice(lastColon + 1)); - if (quad) { - const [a = 0, b = 0, c = 0, d = 0] = quad; - const word = (hi: number, lo: number) => ((hi << 8) | lo).toString(16); - text = `${text.slice(0, lastColon + 1)}${word(a, b)}:${word(c, d)}`; - } - - const halves = text.split("::"); - if (halves.length > 2) return undefined; - const words = (part: string) => (part === "" ? [] : part.split(":")); - const head = words(halves[0] ?? ""); - const rest = halves.length === 2 ? words(halves[1] ?? "") : []; - const missing = 8 - head.length - rest.length; - if (halves.length === 2 ? missing < 0 : missing !== 0) return undefined; - - const all = [...head, ...Array(missing).fill("0"), ...rest]; - const segments = all.map((word) => (/^[0-9a-f]{1,4}$/i.test(word) ? Number.parseInt(word, 16) : Number.NaN)); - return segments.some(Number.isNaN) ? undefined : segments; -} - -function isLocalV6(segments: number[]): boolean { - // An IPv4-mapped address reaches the same host as the v4 it wraps. - if (segments.slice(0, 5).every((s) => s === 0) && segments[5] === 0xffff) { - const [hi = 0, lo = 0] = segments.slice(6); - return isLocalV4([hi >> 8, hi & 0xff, lo >> 8, lo & 0xff]); - } - const first = segments[0] ?? 0; - const zeroPrefix = segments.slice(0, 7).every((s) => s === 0); - const last = segments[7] ?? 0; - return ( - // Loopback (::1) and unspecified (::). - (zeroPrefix && (last === 1 || last === 0)) || - // Unique local (fc00::/7) and link local (fe80::/10). - (first & 0xfe00) === 0xfc00 || - (first & 0xffc0) === 0xfe80 - ); -} diff --git a/js/net/src/connection/reload.ts b/js/net/src/connection/reload.ts index ba80ace3f60..6ca7327d64c 100644 --- a/js/net/src/connection/reload.ts +++ b/js/net/src/connection/reload.ts @@ -16,6 +16,7 @@ import { type WebSocketProps, type WebTransportProps, } from "./connect.ts"; +import { parse } from "./endpoint.ts"; import type { Established } from "./established.ts"; import { DISCOVERY_REMOVED } from "./forward.ts"; import { DEFAULT_HANDOVER, type Drain, dialed, type GoawayProps, handover, pinnedTransport, target } from "./goaway.ts"; @@ -626,8 +627,8 @@ export class Reload { if (lived >= Nano.fromMilli(settled)) this.#redirects.reset(); // Only a redirect this GOAWAY named is a move. An empty or ignored one reconnects // in place, even when that reruns the race a WebSocket fallback won. - const from = endpoint(at); - const to = after && after !== before ? endpoint(after) : from; + const from = destination(at); + const to = after && after !== before ? destination(after) : from; if (to !== from && this.#redirects.move(from, to)) { this.#retry(effect, undefined, new Error("redirect loop")); return; @@ -962,10 +963,11 @@ class Draining { /** * Where `url` dials, without its userinfo, query, or fragment, where a peer may mint fresh - * credentials on every redirect. Two URLs that differ only there reach the same endpoint. + * credentials on every redirect, and with its host as the dial reads it. Two URLs that differ + * only there reach the same place. */ -function endpoint(url: URL): string { - const bare = new URL(url); +function destination(url: URL): string { + const bare = new URL(parse(url).url); bare.username = ""; bare.password = ""; bare.search = ""; diff --git a/js/net/src/datagram.ts b/js/net/src/datagram.ts index 0f7cdde831f..85c6b016107 100644 --- a/js/net/src/datagram.ts +++ b/js/net/src/datagram.ts @@ -8,7 +8,7 @@ import { StreamCode, StreamError } from "./error.ts"; import { hooks } from "./internal.ts"; import { rescale } from "./rescale.ts"; import { Timescale, type Timestamp } from "./time.ts"; -import { checkSequence, max, UNBOUNDED } from "./util/sequence.ts"; +import { checkSequence, max } from "./util/sequence.ts"; export { rescale } from "./rescale.ts"; @@ -160,7 +160,6 @@ export class Producer { const properties = state.info.peek(); if (!properties) throw new Error("datagram track has not been accepted"); const sequence = checkSequence(datagram.sequence); - if (sequence >= UNBOUNDED) throw new RangeError("datagram sequence exhausted"); if (datagram.payload.byteLength > MAX_PAYLOAD) throw new Error("datagram payload too large"); const timestamp = rescale(properties, datagram.timestamp); // A small view must not pin a peer's larger receive buffer. diff --git a/js/net/src/open.test.ts b/js/net/src/open.test.ts index 20c69ce8ac1..b62789991be 100644 --- a/js/net/src/open.test.ts +++ b/js/net/src/open.test.ts @@ -192,3 +192,30 @@ test("an open ranked above an impatient one makes room for it at once", async () installed.close(); } }); + +test("an RTT of 0 reads as no sample, so an open still waits 100 ms", async () => { + const clock = new Manual(); + const installed = clock.install(); + const { client, server } = qmuxPair(1n); + // A transport may report a zero smoothed RTT before its first sample. + Object.assign(client, { getStats: async () => ({ smoothedRtt: 0 }) }); + try { + const low = await openGroup(client, 1); + await low.write(new Uint8Array(16)); + + const high = openGroup(client, 5); + await clock.advance(Nano.fromMilli(Milli(99))); + expect(orders(client)).toEqual([1]); + await clock.advance(Nano.fromMilli(Milli(1))); + await expect(low.closed).rejects.toThrow("lagged"); + + const incoming = server.incomingUnidirectionalStreams.getReader(); + const { value } = await incoming.read(); + await value?.cancel(); + expect((await high).sendOrder).toBe(5); + } finally { + client.close(); + server.close(); + installed.close(); + } +}); diff --git a/js/net/src/open.ts b/js/net/src/open.ts index 807491e94c3..032e01347b4 100644 --- a/js/net/src/open.ts +++ b/js/net/src/open.ts @@ -298,8 +298,8 @@ export function lines(quic: WebTransport): Lines { const options = (sendOrder: number) => sendOrder === 0 ? { waitUntilAvailable: true } : { sendOrder, waitUntilAvailable: true }; const streams = new OpenStreams(transportOf(quic) === "websocket"); - // Before any RTT sample, wait 100 ms. - const patience = async () => (await transportStats(quic)).rtt ?? session.probe?.peek().rtt ?? Milli(100); + // Before any RTT sample, wait 100 ms. A transport may report 0 until its first sample. + const patience = async () => (await transportStats(quic)).rtt || session.probe?.peek().rtt || Milli(100); const session: Lines = { uni: new Line( (sendOrder) => quic.createUnidirectionalStream(options(sendOrder)) as Promise, diff --git a/js/net/src/track.test.ts b/js/net/src/track.test.ts index 2f41c0e8004..f783f6f8855 100644 --- a/js/net/src/track.test.ts +++ b/js/net/src/track.test.ts @@ -4662,3 +4662,10 @@ test("reopening stale drops reports again what is stale at the max age bound", ( expect(hooks.reofferStale(reader)).toEqual([{ start: 1n, end: 3n }]); expect(drain()).toEqual([[1n, 3n, 1500]]); }); + +test("group sequences stop at 2^64-1, as a u64 does", () => { + const producer = new TrackProducer("test").accept({}); + expect(() => producer.createGroup(1n << 64n)).toThrow(RangeError); + producer.createGroup((1n << 64n) - 1n).finish(); + expect(() => producer.appendGroup()).toThrow(RangeError); +}); diff --git a/js/net/src/util/log.test.ts b/js/net/src/util/log.test.ts deleted file mode 100644 index e1fcb00dd77..00000000000 --- a/js/net/src/util/log.test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { expect, test } from "bun:test"; -import { redact } from "./log.ts"; - -test("redact drops credentials, query, and fragment", () => { - expect(redact(new URL("https://user:password@relay.example.com/anon/room?jwt=secret#frag"))).toBe( - "https://relay.example.com/anon/room", - ); -}); - -test("redact keeps the port and an empty path", () => { - expect(redact(new URL("http://localhost:4443?jwt=secret"))).toBe("http://localhost:4443/"); -}); diff --git a/js/net/src/util/log.ts b/js/net/src/util/log.ts deleted file mode 100644 index 4a810eee1fa..00000000000 --- a/js/net/src/util/log.ts +++ /dev/null @@ -1,4 +0,0 @@ -/** Renders a relay URL without user credentials, query parameters, or fragment. */ -export function redact(url: URL): string { - return `${url.origin}${url.pathname}`; -} diff --git a/js/net/src/util/sequence.ts b/js/net/src/util/sequence.ts index 03ba83a4585..89acbab4e4d 100644 --- a/js/net/src/util/sequence.ts +++ b/js/net/src/util/sequence.ts @@ -18,9 +18,10 @@ export function saturatingSub(a: bigint, b: bigint): bigint { /** An exclusive end past every group a wire can carry (2^64), which an open run ends at. */ export const UNBOUNDED = 1n << 64n; -/** Refuse a group sequence that is not a non-negative bigint, which a plain JS caller can pass. */ +/** Refuse a group sequence a u64 cannot hold, or that is not a bigint, either of which a plain JS caller can pass. */ export function checkSequence(sequence: bigint): bigint { if (typeof sequence !== "bigint") throw new TypeError(`group sequence must be a bigint: ${String(sequence)}`); if (sequence < 0n) throw new RangeError(`group sequence must be non-negative: ${sequence}`); + if (sequence >= UNBOUNDED) throw new RangeError(`group sequence exceeds 2^64-1: ${sequence}`); return sequence; } From 04a6f30f71b383af8f4a086b2ab1a864457f0774 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 16:19:59 -0800 Subject: [PATCH 03/10] test(net): Rust and JS replay one moq-lite corpus Co-Authored-By: Claude Opus 5.5 --- js/net/src/connection/accept.ts | 23 +++- js/net/src/lite/announce.ts | 14 ++- js/net/src/lite/corpus.test.ts | 85 +++++++++++++ js/net/src/lite/message.test.ts | 8 +- js/net/src/lite/subscriber.ts | 6 +- js/net/src/util/limits.ts | 5 + rs/moq-net/corpus/README.md | 34 ++++++ .../corpus/lite/announce-active-lite05.json | 6 + .../corpus/lite/announce-end-id-lite06.json | 6 + .../lite/announce-init-over-budget.json | 7 ++ .../lite/announce-init-over-size-cap.json | 6 + .../lite/announce-init-within-budget.json | 7 ++ .../lite/announce-short-body-lite05.json | 6 + .../lite/announce-short-body-lite06.json | 6 + .../lite/announce-short-body-lite07.json | 6 + .../corpus/lite/announce-start-lite06.json | 6 + .../lite/client-setup-pinned-not-offered.json | 7 ++ .../lite/client-setup-pinned-offered.json | 7 ++ .../lite/group-sequence-max-lite06.json | 6 + .../lite/group-sequence-max-lite07.json | 6 + rs/moq-net/fuzz/README.md | 5 +- rs/moq-net/fuzz/regressions/README.md | 2 +- .../regressions/lite/complete-announce-lite05 | 1 - .../regressions/lite/complete-announce-lite06 | Bin 5 -> 0 bytes .../regressions/lite/complete-announce-lite07 | Bin 5 -> 0 bytes rs/moq-net/src/lite/corpus.rs | 112 ++++++++++++++++++ rs/moq-net/src/lite/mod.rs | 2 + rs/moq-net/src/server.rs | 10 +- rs/moq-net/src/setup.rs | 16 +++ 29 files changed, 376 insertions(+), 29 deletions(-) create mode 100644 js/net/src/lite/corpus.test.ts create mode 100644 rs/moq-net/corpus/README.md create mode 100644 rs/moq-net/corpus/lite/announce-active-lite05.json create mode 100644 rs/moq-net/corpus/lite/announce-end-id-lite06.json create mode 100644 rs/moq-net/corpus/lite/announce-init-over-budget.json create mode 100644 rs/moq-net/corpus/lite/announce-init-over-size-cap.json create mode 100644 rs/moq-net/corpus/lite/announce-init-within-budget.json create mode 100644 rs/moq-net/corpus/lite/announce-short-body-lite05.json create mode 100644 rs/moq-net/corpus/lite/announce-short-body-lite06.json create mode 100644 rs/moq-net/corpus/lite/announce-short-body-lite07.json create mode 100644 rs/moq-net/corpus/lite/announce-start-lite06.json create mode 100644 rs/moq-net/corpus/lite/client-setup-pinned-not-offered.json create mode 100644 rs/moq-net/corpus/lite/client-setup-pinned-offered.json create mode 100644 rs/moq-net/corpus/lite/group-sequence-max-lite06.json create mode 100644 rs/moq-net/corpus/lite/group-sequence-max-lite07.json delete mode 100644 rs/moq-net/fuzz/regressions/lite/complete-announce-lite05 delete mode 100644 rs/moq-net/fuzz/regressions/lite/complete-announce-lite06 delete mode 100644 rs/moq-net/fuzz/regressions/lite/complete-announce-lite07 create mode 100644 rs/moq-net/src/lite/corpus.rs diff --git a/js/net/src/connection/accept.ts b/js/net/src/connection/accept.ts index 7bb37ef4ba5..a0b5ad99254 100644 --- a/js/net/src/connection/accept.ts +++ b/js/net/src/connection/accept.ts @@ -185,12 +185,7 @@ async function acceptNegotiated( if (!stream) throw new Error("no incoming bidi stream for SETUP"); const client = await Lite.ClientSetup.decode(stream.reader); - const selected = client.versions.find((v) => (version === undefined ? Lite.isNegotiated(v) : v === version)); - if (selected === undefined || !Lite.isNegotiated(selected)) { - throw new Error( - `no common version found; client offered: ${client.versions.map((v) => v.toString(16)).join(", ")}`, - ); - } + const selected = select(client, version); await new Lite.ServerSetup(selected).encode(stream.writer); if (handsOff(selected)) { @@ -199,3 +194,19 @@ async function acceptNegotiated( } return new Lite.Connection({ url, quic: transport, version: selected, session: stream, ...wiring }); } + +/** + * The moq-lite version a server answers a `moql` SETUP with: the client's first, or `pinned` + * only when the client offered it. Mirrors `setup::Client::select` in moq-net. + * + * @internal + */ +export function select(client: Lite.ClientSetup, pinned?: number): Lite.Version { + const selected = client.versions.find((v) => (pinned === undefined ? Lite.isNegotiated(v) : v === pinned)); + if (selected === undefined || !Lite.isNegotiated(selected)) { + throw new Error( + `no common version found; client offered: ${client.versions.map((v) => v.toString(16)).join(", ")}`, + ); + } + return selected; +} diff --git a/js/net/src/lite/announce.ts b/js/net/src/lite/announce.ts index c9fad00621c..46652a702ab 100644 --- a/js/net/src/lite/announce.ts +++ b/js/net/src/lite/announce.ts @@ -586,8 +586,10 @@ export class AnnounceInit { } } - static async #decode(r: Reader): Promise { + static async #decode(r: Reader, budget: number): Promise { const count = await r.u53(); + // Refused before decoding any, so the set grows no larger than what may be announced. + if (count > budget) throw new Error(`announce init lists ${count} broadcasts with ${budget} slots left`); const suffixes: Path.Valid[] = []; for (let i = 0; i < count; i++) { suffixes.push(Path.decode(await r.string())); @@ -595,17 +597,19 @@ export class AnnounceInit { return new AnnounceInit(suffixes); } - // The whole initial set in one message, so it scales with the publisher's broadcasts. - static readonly MAX_SIZE = 64 * 1024 * 1024; + // The whole initial set in one message, capped like Rust's so it fits one storage segment + // (1 MiB) with its type and size prefixes. A larger set is refused on both ends. + static readonly MAX_SIZE = 1024 * 1024 - 16; async encode(w: Writer, version: Version): Promise { AnnounceInit.#guard(version); return Message.encode(w, this.#encode.bind(this), { max: AnnounceInit.MAX_SIZE }); } - static async decode(r: Reader, version: Version): Promise { + /** Decode the initial set, refusing one that lists more than `budget` broadcasts. */ + static async decode(r: Reader, version: Version, budget: number): Promise { AnnounceInit.#guard(version); - return Message.decode(r, AnnounceInit.#decode, AnnounceInit.MAX_SIZE); + return Message.decode(r, (r) => AnnounceInit.#decode(r, budget), AnnounceInit.MAX_SIZE); } } diff --git a/js/net/src/lite/corpus.test.ts b/js/net/src/lite/corpus.test.ts new file mode 100644 index 00000000000..8fe18a2224d --- /dev/null +++ b/js/net/src/lite/corpus.test.ts @@ -0,0 +1,85 @@ +// Replays the moq-lite corpus in `rs/moq-net/corpus/lite/`, which moq-net replays too, so a +// decoder that drifts from the other language fails a test on both sides. + +import { expect, test } from "bun:test"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { select } from "../connection/accept.ts"; +import { Reader, UnexpectedEnd, Writer } from "../stream.ts"; +import { isDecodeError } from "../util/decode_error.ts"; +import { AnnounceInit, decodeAnnounceBroadcast, encodeAnnounceBroadcast } from "./announce.ts"; +import { ClientSetup } from "./compat.ts"; +import { Group } from "./group.ts"; +import { Version, versionName } from "./version.ts"; + +const DIR = join(import.meta.dir, "../../../../rs/moq-net/corpus/lite"); + +interface Case { + version: string; + message: "announce" | "announce_init" | "group" | "client_setup"; + hex: string; + /** `announce_init`: the announce slots left, unbounded when absent. */ + budget?: number; + /** `client_setup`: the one version the server accepts. */ + server?: string; + expect: "decoded" | "refused"; +} + +const VERSIONS = new Map(Object.values(Version).map((v) => [versionName(v), v])); + +function version(name: string): Version { + const v = VERSIONS.get(name); + if (v === undefined) throw new Error(`unknown moq-lite version: ${name}`); + return v; +} + +// Decode `r` the way a session does, returning how to encode what it decoded. +async function decode(c: Case, r: Reader, v: Version): Promise<(w: Writer) => Promise> { + switch (c.message) { + case "announce": { + const msg = await decodeAnnounceBroadcast(r, v); + return (w) => encodeAnnounceBroadcast(w, msg, v); + } + case "announce_init": { + const msg = await AnnounceInit.decode(r, v, c.budget ?? Number.POSITIVE_INFINITY); + return (w) => msg.encode(w, v); + } + case "group": { + const msg = await Group.decode(r, v); + return (w) => msg.encode(w, v); + } + case "client_setup": { + const msg = await ClientSetup.decode(r); + if (c.server !== undefined) select(msg, version(c.server)); + return (w) => msg.encode(w); + } + } +} + +// What a decode came to: our own encoding of what it decoded, as hex, or why it did not. +async function outcome(c: Case): Promise { + const v = version(c.version); + const r = new Reader(undefined, Buffer.from(c.hex, "hex"), v); + let encode: (w: Writer) => Promise; + try { + encode = await decode(c, r, v); + } catch (err) { + // Running out past every message body asks for more bytes, which no complete input should. + return err instanceof UnexpectedEnd && !isDecodeError(err) ? "short" : "refused"; + } + if (!(await r.done())) return "left bytes"; + return Buffer.from(await Writer.collect(v, encode)).toString("hex"); +} + +const files = readdirSync(DIR).filter((file) => file.endsWith(".json")); + +test("the corpus has cases", () => { + expect(files.length).toBeGreaterThan(0); +}); + +for (const file of files) { + const c = JSON.parse(readFileSync(join(DIR, file), "utf8")) as Case; + test(file, async () => { + expect(await outcome(c)).toBe(c.expect === "decoded" ? c.hex : "refused"); + }); +} diff --git a/js/net/src/lite/message.test.ts b/js/net/src/lite/message.test.ts index 3e385e347f4..4a8d7aa9123 100644 --- a/js/net/src/lite/message.test.ts +++ b/js/net/src/lite/message.test.ts @@ -22,11 +22,13 @@ test("control messages past 65,535 bytes are refused at the length prefix", asyn await expect(Subscribe.decode(new Reader(undefined, wire, version), version)).rejects.toThrow("too large"); }); -test("ANNOUNCE_INIT keeps room for a large initial set", async () => { +test("ANNOUNCE_INIT keeps room for an initial set up to its cap", async () => { const version = Version.DRAFT_02; - const wire = await prefix(1024 * 1024, version); + const wire = await prefix(AnnounceInit.MAX_SIZE, version); // Past the size check, so it fails waiting for a body that never arrives instead. - await expect(AnnounceInit.decode(new Reader(undefined, wire, version), version)).rejects.not.toThrow("too large"); + await expect(AnnounceInit.decode(new Reader(undefined, wire, version), version, 1)).rejects.not.toThrow( + "too large", + ); }); test("control message length 65,535 passes the prefix check", async () => { diff --git a/js/net/src/lite/subscriber.ts b/js/net/src/lite/subscriber.ts index 051672e0dee..a4fc8f5b47d 100644 --- a/js/net/src/lite/subscriber.ts +++ b/js/net/src/lite/subscriber.ts @@ -523,8 +523,10 @@ export class Subscriber { switch (this.version) { case Version.DRAFT_01: case Version.DRAFT_02: { - // Receive ANNOUNCE_INIT first - const init = await race([AnnounceInit.decode(stream.reader, this.version), announced.closed]); + // Receive ANNOUNCE_INIT first. Each suffix takes an announce slot, so a set past + // what is left of the budget is refused before it is decoded. + const budget = this.#announces.available(); + const init = await race([AnnounceInit.decode(stream.reader, this.version, budget), announced.closed]); if (!(init instanceof AnnounceInit)) { stream.close(); return; diff --git a/js/net/src/util/limits.ts b/js/net/src/util/limits.ts index dec295b45c6..274e2c043c8 100644 --- a/js/net/src/util/limits.ts +++ b/js/net/src/util/limits.ts @@ -57,6 +57,11 @@ export class Slots { return true; } + /** How many slots are left to take. */ + available(): number { + return this.#max - this.#live; + } + /** Give back `count` slots. */ release(count = 1) { this.#live -= count; diff --git a/rs/moq-net/corpus/README.md b/rs/moq-net/corpus/README.md new file mode 100644 index 00000000000..d1f945ed212 --- /dev/null +++ b/rs/moq-net/corpus/README.md @@ -0,0 +1,34 @@ +# Corpus + +Wire inputs with the outcome both implementations must reach. `rs/moq-net` +(`lite::corpus`) and `js/net` (`src/lite/corpus.test.ts`) replay every case under +`just check`, so a decoder that drifts from the other language fails on both sides. + +## Cases + +One JSON file per case in `lite/`, named for what it pins: + +```json +{ + "version": "moq-lite-02", + "message": "announce_init", + "budget": 1, + "hex": "050201610162", + "expect": "refused" +} +``` + +- `version`: the negotiated version, by its handshake name (`moq-lite-01` to `moq-lite-07-wip`). +- `message`: what the bytes are, length prefix and any type included: + - `announce`: one announcement on the announce stream. + - `announce_init`: a lite-01/02 ANNOUNCE_INIT. `budget` is the announce slots left, unbounded when absent. + - `group`: a group stream header. + - `client_setup`: a `moql` CLIENT_SETUP. `server` is the one version the server accepts, and refusing to pick it refuses the case. +- `hex`: the input. +- `expect`: `decoded`, where our own encoding of the decoded value must equal `hex`, so a case + also pins the value, or `refused`, where the input is rejected without asking for more bytes. + +Every input is complete: asking for more bytes fails either expectation. + +A fuzz crash on a moq-lite message (`fuzz/regressions/`) belongs here instead, with +`expect` set, so `js/net` replays it too. diff --git a/rs/moq-net/corpus/lite/announce-active-lite05.json b/rs/moq-net/corpus/lite/announce-active-lite05.json new file mode 100644 index 00000000000..6d25f2e8480 --- /dev/null +++ b/rs/moq-net/corpus/lite/announce-active-lite05.json @@ -0,0 +1,6 @@ +{ + "version": "moq-lite-05", + "message": "announce", + "hex": "0d010a726f6f6d2f616c69636500", + "expect": "decoded" +} diff --git a/rs/moq-net/corpus/lite/announce-end-id-lite06.json b/rs/moq-net/corpus/lite/announce-end-id-lite06.json new file mode 100644 index 00000000000..67c50d4faad --- /dev/null +++ b/rs/moq-net/corpus/lite/announce-end-id-lite06.json @@ -0,0 +1,6 @@ +{ + "version": "moq-lite-06", + "message": "announce", + "hex": "010103", + "expect": "decoded" +} diff --git a/rs/moq-net/corpus/lite/announce-init-over-budget.json b/rs/moq-net/corpus/lite/announce-init-over-budget.json new file mode 100644 index 00000000000..00b2bdd575d --- /dev/null +++ b/rs/moq-net/corpus/lite/announce-init-over-budget.json @@ -0,0 +1,7 @@ +{ + "version": "moq-lite-02", + "message": "announce_init", + "budget": 1, + "hex": "050201610162", + "expect": "refused" +} diff --git a/rs/moq-net/corpus/lite/announce-init-over-size-cap.json b/rs/moq-net/corpus/lite/announce-init-over-size-cap.json new file mode 100644 index 00000000000..894f9be21b1 --- /dev/null +++ b/rs/moq-net/corpus/lite/announce-init-over-size-cap.json @@ -0,0 +1,6 @@ +{ + "version": "moq-lite-02", + "message": "announce_init", + "hex": "800ffff1", + "expect": "refused" +} diff --git a/rs/moq-net/corpus/lite/announce-init-within-budget.json b/rs/moq-net/corpus/lite/announce-init-within-budget.json new file mode 100644 index 00000000000..0929869eec3 --- /dev/null +++ b/rs/moq-net/corpus/lite/announce-init-within-budget.json @@ -0,0 +1,7 @@ +{ + "version": "moq-lite-02", + "message": "announce_init", + "budget": 2, + "hex": "050201610162", + "expect": "decoded" +} diff --git a/rs/moq-net/corpus/lite/announce-short-body-lite05.json b/rs/moq-net/corpus/lite/announce-short-body-lite05.json new file mode 100644 index 00000000000..9457de4f59f --- /dev/null +++ b/rs/moq-net/corpus/lite/announce-short-body-lite05.json @@ -0,0 +1,6 @@ +{ + "version": "moq-lite-05", + "message": "announce", + "hex": "0101", + "expect": "refused" +} diff --git a/rs/moq-net/corpus/lite/announce-short-body-lite06.json b/rs/moq-net/corpus/lite/announce-short-body-lite06.json new file mode 100644 index 00000000000..b2545d9cd26 --- /dev/null +++ b/rs/moq-net/corpus/lite/announce-short-body-lite06.json @@ -0,0 +1,6 @@ +{ + "version": "moq-lite-06", + "message": "announce", + "hex": "000105", + "expect": "refused" +} diff --git a/rs/moq-net/corpus/lite/announce-short-body-lite07.json b/rs/moq-net/corpus/lite/announce-short-body-lite07.json new file mode 100644 index 00000000000..edcf58087bd --- /dev/null +++ b/rs/moq-net/corpus/lite/announce-short-body-lite07.json @@ -0,0 +1,6 @@ +{ + "version": "moq-lite-07-wip", + "message": "announce", + "hex": "000105", + "expect": "refused" +} diff --git a/rs/moq-net/corpus/lite/announce-start-lite06.json b/rs/moq-net/corpus/lite/announce-start-lite06.json new file mode 100644 index 00000000000..6e71cb8b330 --- /dev/null +++ b/rs/moq-net/corpus/lite/announce-start-lite06.json @@ -0,0 +1,6 @@ +{ + "version": "moq-lite-06", + "message": "announce", + "hex": "00150a726f6f6d2f616c6963650000ffffffffffffffff", + "expect": "decoded" +} diff --git a/rs/moq-net/corpus/lite/client-setup-pinned-not-offered.json b/rs/moq-net/corpus/lite/client-setup-pinned-not-offered.json new file mode 100644 index 00000000000..7d4fdeae789 --- /dev/null +++ b/rs/moq-net/corpus/lite/client-setup-pinned-not-offered.json @@ -0,0 +1,7 @@ +{ + "version": "moq-lite-02", + "message": "client_setup", + "server": "moq-lite-05", + "hex": "20001202c0000000ff0dad07c0000000ff0dad0600", + "expect": "refused" +} diff --git a/rs/moq-net/corpus/lite/client-setup-pinned-offered.json b/rs/moq-net/corpus/lite/client-setup-pinned-offered.json new file mode 100644 index 00000000000..5ed6e50eb4a --- /dev/null +++ b/rs/moq-net/corpus/lite/client-setup-pinned-offered.json @@ -0,0 +1,7 @@ +{ + "version": "moq-lite-02", + "message": "client_setup", + "server": "moq-lite-05", + "hex": "20001202c0000000ff0dad06c0000000ff0dad0500", + "expect": "decoded" +} diff --git a/rs/moq-net/corpus/lite/group-sequence-max-lite06.json b/rs/moq-net/corpus/lite/group-sequence-max-lite06.json new file mode 100644 index 00000000000..54452fb46fc --- /dev/null +++ b/rs/moq-net/corpus/lite/group-sequence-max-lite06.json @@ -0,0 +1,6 @@ +{ + "version": "moq-lite-06", + "message": "group", + "hex": "0a00ffffffffffffffff00", + "expect": "decoded" +} diff --git a/rs/moq-net/corpus/lite/group-sequence-max-lite07.json b/rs/moq-net/corpus/lite/group-sequence-max-lite07.json new file mode 100644 index 00000000000..b8b3e269fef --- /dev/null +++ b/rs/moq-net/corpus/lite/group-sequence-max-lite07.json @@ -0,0 +1,6 @@ +{ + "version": "moq-lite-07-wip", + "message": "group", + "hex": "0b00ffffffffffffffffff00", + "expect": "decoded" +} diff --git a/rs/moq-net/fuzz/README.md b/rs/moq-net/fuzz/README.md index e3f3817067e..32a34fb144a 100644 --- a/rs/moq-net/fuzz/README.md +++ b/rs/moq-net/fuzz/README.md @@ -82,8 +82,9 @@ libFuzzer writes the input to `artifacts//crash-` and prints the ` command to reproduce it (add the prefix above). Fix the bug, then commit the input: ```bash -cp rs/moq-net/fuzz/artifacts/lite/crash- rs/moq-net/fuzz/regressions/lite/ +cp rs/moq-net/fuzz/artifacts/ingest/crash- rs/moq-net/fuzz/regressions/ingest/ ``` `fuzz::tests::regressions` replays everything under `regressions//` as part of -the normal test suite, so the case stays covered. +the normal test suite, so the case stays covered. A crash on a single moq-lite message +becomes a case in [`../corpus/`](../corpus/README.md) instead, which `js/net` replays too. diff --git a/rs/moq-net/fuzz/regressions/README.md b/rs/moq-net/fuzz/regressions/README.md index 61befbdbfa8..368cc0269e8 100644 --- a/rs/moq-net/fuzz/regressions/README.md +++ b/rs/moq-net/fuzz/regressions/README.md @@ -1,7 +1,7 @@ # Regressions Crash inputs the fuzzer found, one file per input, in a directory named after its -target (`lite/`, `ietf/`, `request/`, and so on). `fuzz::tests::regressions` replays them +target (`ietf/`, `request/`, and so on). `fuzz::tests::regressions` replays them on the stable toolchain as part of `just check`, so a bug found by fuzzing stays fixed without anyone running the fuzzer again. diff --git a/rs/moq-net/fuzz/regressions/lite/complete-announce-lite05 b/rs/moq-net/fuzz/regressions/lite/complete-announce-lite05 deleted file mode 100644 index 0a8cb8c252d..00000000000 --- a/rs/moq-net/fuzz/regressions/lite/complete-announce-lite05 +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/rs/moq-net/fuzz/regressions/lite/complete-announce-lite06 b/rs/moq-net/fuzz/regressions/lite/complete-announce-lite06 deleted file mode 100644 index 2ae928704e6b9a797083c019ad24acb8bbaba938..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5 McmZQ&Wng3l0021v5dZ)H diff --git a/rs/moq-net/fuzz/regressions/lite/complete-announce-lite07 b/rs/moq-net/fuzz/regressions/lite/complete-announce-lite07 deleted file mode 100644 index 1b15c27bc70c5055ae72897f1bfba6139fbf8824..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5 McmZQ$Wng3l002G!5&!@I diff --git a/rs/moq-net/src/lite/corpus.rs b/rs/moq-net/src/lite/corpus.rs new file mode 100644 index 00000000000..f3b5d730102 --- /dev/null +++ b/rs/moq-net/src/lite/corpus.rs @@ -0,0 +1,112 @@ +//! Replays the moq-lite corpus in `corpus/lite/`, which `js/net` replays too, so a decoder +//! that drifts from the other language fails a test on both sides. See `corpus/README.md`. + +use crate::coding::{Decode, DecodeError, Decoder, Encode, Form}; + +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct Case { + version: crate::Version, + message: Message, + hex: String, + /// `announce_init`: the announce slots left, unbounded when absent. + budget: Option, + /// `client_setup`: the one version the server accepts. + server: Option, + expect: Expect, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "snake_case")] +enum Message { + Announce, + AnnounceInit, + Group, + ClientSetup, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "snake_case")] +enum Expect { + Decoded, + Refused, +} + +/// What a decode came to: our own encoding of what it decoded, as hex, or why it did not. +fn outcome, V: Copy + Into
>(data: &[u8], version: V, decoded: Result<(T, usize), DecodeError>) -> String { + match decoded { + Ok((_, used)) if used != data.len() => format!("left {} bytes", data.len() - used), + Ok((value, _)) => match value.encode_bytes(version) { + Ok(bytes) => hex(&bytes), + Err(err) => format!("could not re-encode: {err}"), + }, + // Asking for more bytes is neither outcome: every input is complete. + Err(DecodeError::Short) => "short".to_string(), + Err(_) => "refused".to_string(), + } +} + +/// Decode `data` the way a session does, with what it refuses checked before what it decodes. +fn run(case: &Case, data: &[u8]) -> String { + let crate::Version::Lite(version) = case.version else { + return format!("{} is not a moq-lite version", case.version); + }; + let decoder = || Decoder::new(data, version.into()); + match case.message { + Message::Announce => outcome(data, version, super::AnnounceBroadcast::decode_slice(data, version)), + Message::AnnounceInit => { + let mut r = decoder(); + let decoded = super::AnnounceInit::decode_within(&mut r, version, case.budget.unwrap_or(usize::MAX)); + let used = data.len() - r.remaining(); + outcome(data, version, decoded.map(|init| (init, used))) + } + Message::Group => outcome(data, version, super::Group::decode_slice(data, version)), + Message::ClientSetup => { + let decoded = crate::setup::Client::decode_slice(data, case.version); + if let (Ok((client, _)), Some(server)) = (&decoded, case.server) + && client.select(&server.into()).is_err() + { + return "refused".to_string(); + } + outcome(data, case.version, decoded) + } + } +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn unhex(text: &str) -> Vec { + assert!(text.len() % 2 == 0, "odd hex length"); + (0..text.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&text[i..i + 2], 16).expect("invalid hex")) + .collect() +} + +#[test] +fn corpus() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("corpus/lite"); + let mut failures = Vec::new(); + let mut count = 0; + for entry in std::fs::read_dir(&dir).expect("could not read the corpus") { + let path = entry.expect("could not read the corpus").path(); + if path.extension().is_none_or(|ext| ext != "json") { + continue; + } + let text = std::fs::read_to_string(&path).expect("could not read a corpus case"); + let case: Case = serde_json::from_str(&text).unwrap_or_else(|err| panic!("{}: {err}", path.display())); + let want = match case.expect { + Expect::Decoded => case.hex.clone(), + Expect::Refused => "refused".to_string(), + }; + let got = run(&case, &unhex(&case.hex)); + if got != want { + failures.push(format!("{}: expected {want}, got {got}", path.display())); + } + count += 1; + } + assert!(count > 0, "the corpus is empty"); + assert!(failures.is_empty(), "{}", failures.join("\n")); +} diff --git a/rs/moq-net/src/lite/mod.rs b/rs/moq-net/src/lite/mod.rs index a106b8d54b1..bf34b320e9f 100644 --- a/rs/moq-net/src/lite/mod.rs +++ b/rs/moq-net/src/lite/mod.rs @@ -16,6 +16,8 @@ mod announce; mod auth; mod compress; +#[cfg(test)] +mod corpus; mod datagram; pub(crate) mod error; mod fetch; diff --git a/rs/moq-net/src/server.rs b/rs/moq-net/src/server.rs index ef461cae36e..30c073ea48f 100644 --- a/rs/moq-net/src/server.rs +++ b/rs/moq-net/src/server.rs @@ -725,15 +725,7 @@ impl Handshaking { }; // Stats attach in `ok()`: a caller may still replace them on the handshake. let (client, client_setup_size) = ready!(stream.reader.poll_decode_sized::(waiter))?; - let version = client - .versions - .iter() - .flat_map(|v| Version::try_from(*v).ok()) - .find(|v| supported.contains(v)) - .ok_or(Error::Version)?; - let Version::Lite(version) = version else { - return Poll::Ready(Err(Error::Version)); - }; + let version = client.select(supported)?; let AcceptStep::Negotiate { runtime, session, diff --git a/rs/moq-net/src/setup.rs b/rs/moq-net/src/setup.rs index 3d5f20b2e0a..2e8294880b6 100644 --- a/rs/moq-net/src/setup.rs +++ b/rs/moq-net/src/setup.rs @@ -195,6 +195,22 @@ impl std::fmt::Debug for Client { } } +impl Client { + /// The moq-lite version a server answers with: the first one offered that `supported` holds. + #[cfg_attr(not(any(test, feature = "async")), allow(dead_code, reason = "async-only"))] + pub(crate) fn select(&self, supported: &crate::Versions) -> Result { + let version = self + .versions + .iter() + .flat_map(|v| Version::try_from(*v).ok()) + .find(|v| supported.contains(v)); + match version { + Some(Version::Lite(version)) => Ok(version), + _ => Err(crate::Error::Version), + } + } +} + impl<'a> Decode<'a, Version> for Client { fn decode(r: &mut Decoder<'a>, v: Version) -> Result { r.control = Some(crate::stats::Message::Session); From 0fac86885e4f4d3e4c04b343c9e854af361b8f48 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 17:06:37 -0800 Subject: [PATCH 04/10] style: just fix Co-Authored-By: Claude Opus 5.5 --- js/net/src/connection/connect.ts | 7 +++++-- js/net/src/lite/subscriber.ts | 5 ++++- rs/moq-net/corpus/README.md | 4 ++-- rs/moq-net/src/lite/corpus.rs | 8 ++++++-- 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/js/net/src/connection/connect.ts b/js/net/src/connection/connect.ts index 29562262dc3..7b0c67d9070 100644 --- a/js/net/src/connection/connect.ts +++ b/js/net/src/connection/connect.ts @@ -13,9 +13,9 @@ import { Stream } from "../stream.ts"; import * as Hex from "../util/hex.ts"; import { after } from "../util/timer.ts"; import { isWebTransportSupported } from "./browser.ts"; +import { parse, show } from "./endpoint.ts"; import type { Established } from "./established.ts"; import * as Extensions from "./extensions.ts"; -import { parse, show } from "./endpoint.ts"; import { DISCOVERY_REMOVED, forwardAnnounced } from "./forward.ts"; import { DEFAULT_TIMEOUT, exchangeSetup, handsOff } from "./handshake.ts"; import { inspect } from "./stats.ts"; @@ -755,7 +755,10 @@ async function connectWebTransport( // Dev-only path: http:// can't be a real WebTransport origin, so we fetch the // self-signed cert's hash over plain HTTP and pin it. Production uses https:// // and never reaches here. Keep this at debug so it doesn't read as a problem. - console.debug(show(parse(fingerprintUrl)), "performing an insecure fingerprint fetch; use https:// in production"); + console.debug( + show(parse(fingerprintUrl)), + "performing an insecure fingerprint fetch; use https:// in production", + ); const fingerprint = await fetchFingerprint(fingerprintUrl, cancel); if (!fingerprint) return undefined; diff --git a/js/net/src/lite/subscriber.ts b/js/net/src/lite/subscriber.ts index a4fc8f5b47d..b3b2b944045 100644 --- a/js/net/src/lite/subscriber.ts +++ b/js/net/src/lite/subscriber.ts @@ -526,7 +526,10 @@ export class Subscriber { // Receive ANNOUNCE_INIT first. Each suffix takes an announce slot, so a set past // what is left of the budget is refused before it is decoded. const budget = this.#announces.available(); - const init = await race([AnnounceInit.decode(stream.reader, this.version, budget), announced.closed]); + const init = await race([ + AnnounceInit.decode(stream.reader, this.version, budget), + announced.closed, + ]); if (!(init instanceof AnnounceInit)) { stream.close(); return; diff --git a/rs/moq-net/corpus/README.md b/rs/moq-net/corpus/README.md index d1f945ed212..d085d142615 100644 --- a/rs/moq-net/corpus/README.md +++ b/rs/moq-net/corpus/README.md @@ -21,9 +21,9 @@ One JSON file per case in `lite/`, named for what it pins: - `version`: the negotiated version, by its handshake name (`moq-lite-01` to `moq-lite-07-wip`). - `message`: what the bytes are, length prefix and any type included: - `announce`: one announcement on the announce stream. - - `announce_init`: a lite-01/02 ANNOUNCE_INIT. `budget` is the announce slots left, unbounded when absent. + - `announce_init`: a lite-01/02 ANNOUNCE\_INIT. `budget` is the announce slots left, unbounded when absent. - `group`: a group stream header. - - `client_setup`: a `moql` CLIENT_SETUP. `server` is the one version the server accepts, and refusing to pick it refuses the case. + - `client_setup`: a `moql` CLIENT\_SETUP. `server` is the one version the server accepts, and refusing to pick it refuses the case. - `hex`: the input. - `expect`: `decoded`, where our own encoding of the decoded value must equal `hex`, so a case also pins the value, or `refused`, where the input is rejected without asking for more bytes. diff --git a/rs/moq-net/src/lite/corpus.rs b/rs/moq-net/src/lite/corpus.rs index f3b5d730102..3856c459095 100644 --- a/rs/moq-net/src/lite/corpus.rs +++ b/rs/moq-net/src/lite/corpus.rs @@ -33,7 +33,11 @@ enum Expect { } /// What a decode came to: our own encoding of what it decoded, as hex, or why it did not. -fn outcome, V: Copy + Into>(data: &[u8], version: V, decoded: Result<(T, usize), DecodeError>) -> String { +fn outcome, V: Copy + Into>( + data: &[u8], + version: V, + decoded: Result<(T, usize), DecodeError>, +) -> String { match decoded { Ok((_, used)) if used != data.len() => format!("left {} bytes", data.len() - used), Ok((value, _)) => match value.encode_bytes(version) { @@ -78,7 +82,7 @@ fn hex(bytes: &[u8]) -> String { } fn unhex(text: &str) -> Vec { - assert!(text.len() % 2 == 0, "odd hex length"); + assert!(text.len().is_multiple_of(2), "odd hex length"); (0..text.len()) .step_by(2) .map(|i| u8::from_str_radix(&text[i..i + 2], 16).expect("invalid hex")) From 0abf35afacba4e2a7637a984869a6bf56f05fb4e Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 17:20:53 -0800 Subject: [PATCH 05/10] test(net): the moq-lite corpus follows the shared fixtures convention Co-Authored-By: Claude Opus 5.5 --- js/net/src/lite/corpus.test.ts | 19 ++-- rs/moq-net/corpus/README.md | 34 ------- .../corpus/lite/announce-active-lite05.json | 6 -- .../corpus/lite/announce-end-id-lite06.json | 6 -- .../lite/announce-init-over-budget.json | 7 -- .../lite/announce-init-over-size-cap.json | 6 -- .../lite/announce-init-within-budget.json | 7 -- .../lite/announce-short-body-lite05.json | 6 -- .../lite/announce-short-body-lite06.json | 6 -- .../lite/announce-short-body-lite07.json | 6 -- .../corpus/lite/announce-start-lite06.json | 6 -- .../lite/client-setup-pinned-not-offered.json | 7 -- .../lite/client-setup-pinned-offered.json | 7 -- .../lite/group-sequence-max-lite06.json | 6 -- .../lite/group-sequence-max-lite07.json | 6 -- rs/moq-net/fixtures/lite.json | 97 +++++++++++++++++++ rs/moq-net/fuzz/README.md | 2 +- rs/moq-net/src/lite/corpus.rs | 34 ++++--- 18 files changed, 125 insertions(+), 143 deletions(-) delete mode 100644 rs/moq-net/corpus/README.md delete mode 100644 rs/moq-net/corpus/lite/announce-active-lite05.json delete mode 100644 rs/moq-net/corpus/lite/announce-end-id-lite06.json delete mode 100644 rs/moq-net/corpus/lite/announce-init-over-budget.json delete mode 100644 rs/moq-net/corpus/lite/announce-init-over-size-cap.json delete mode 100644 rs/moq-net/corpus/lite/announce-init-within-budget.json delete mode 100644 rs/moq-net/corpus/lite/announce-short-body-lite05.json delete mode 100644 rs/moq-net/corpus/lite/announce-short-body-lite06.json delete mode 100644 rs/moq-net/corpus/lite/announce-short-body-lite07.json delete mode 100644 rs/moq-net/corpus/lite/announce-start-lite06.json delete mode 100644 rs/moq-net/corpus/lite/client-setup-pinned-not-offered.json delete mode 100644 rs/moq-net/corpus/lite/client-setup-pinned-offered.json delete mode 100644 rs/moq-net/corpus/lite/group-sequence-max-lite06.json delete mode 100644 rs/moq-net/corpus/lite/group-sequence-max-lite07.json create mode 100644 rs/moq-net/fixtures/lite.json diff --git a/js/net/src/lite/corpus.test.ts b/js/net/src/lite/corpus.test.ts index 8fe18a2224d..49210f28a98 100644 --- a/js/net/src/lite/corpus.test.ts +++ b/js/net/src/lite/corpus.test.ts @@ -1,9 +1,8 @@ -// Replays the moq-lite corpus in `rs/moq-net/corpus/lite/`, which moq-net replays too, so a -// decoder that drifts from the other language fails a test on both sides. +// Replays `rs/moq-net/fixtures/lite.json`, the moq-lite corpus moq-net replays too, so a decoder +// that drifts from the other language fails a test on both sides. `rs/moq-net/src/lite/corpus.rs` +// describes the cases. import { expect, test } from "bun:test"; -import { readdirSync, readFileSync } from "node:fs"; -import { join } from "node:path"; import { select } from "../connection/accept.ts"; import { Reader, UnexpectedEnd, Writer } from "../stream.ts"; import { isDecodeError } from "../util/decode_error.ts"; @@ -12,9 +11,8 @@ import { ClientSetup } from "./compat.ts"; import { Group } from "./group.ts"; import { Version, versionName } from "./version.ts"; -const DIR = join(import.meta.dir, "../../../../rs/moq-net/corpus/lite"); - interface Case { + name: string; version: string; message: "announce" | "announce_init" | "group" | "client_setup"; hex: string; @@ -71,15 +69,14 @@ async function outcome(c: Case): Promise { return Buffer.from(await Writer.collect(v, encode)).toString("hex"); } -const files = readdirSync(DIR).filter((file) => file.endsWith(".json")); +const cases = (await Bun.file(new URL("../../../../rs/moq-net/fixtures/lite.json", import.meta.url)).json()) as Case[]; test("the corpus has cases", () => { - expect(files.length).toBeGreaterThan(0); + expect(cases.length).toBeGreaterThan(0); }); -for (const file of files) { - const c = JSON.parse(readFileSync(join(DIR, file), "utf8")) as Case; - test(file, async () => { +for (const c of cases) { + test(c.name, async () => { expect(await outcome(c)).toBe(c.expect === "decoded" ? c.hex : "refused"); }); } diff --git a/rs/moq-net/corpus/README.md b/rs/moq-net/corpus/README.md deleted file mode 100644 index d085d142615..00000000000 --- a/rs/moq-net/corpus/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# Corpus - -Wire inputs with the outcome both implementations must reach. `rs/moq-net` -(`lite::corpus`) and `js/net` (`src/lite/corpus.test.ts`) replay every case under -`just check`, so a decoder that drifts from the other language fails on both sides. - -## Cases - -One JSON file per case in `lite/`, named for what it pins: - -```json -{ - "version": "moq-lite-02", - "message": "announce_init", - "budget": 1, - "hex": "050201610162", - "expect": "refused" -} -``` - -- `version`: the negotiated version, by its handshake name (`moq-lite-01` to `moq-lite-07-wip`). -- `message`: what the bytes are, length prefix and any type included: - - `announce`: one announcement on the announce stream. - - `announce_init`: a lite-01/02 ANNOUNCE\_INIT. `budget` is the announce slots left, unbounded when absent. - - `group`: a group stream header. - - `client_setup`: a `moql` CLIENT\_SETUP. `server` is the one version the server accepts, and refusing to pick it refuses the case. -- `hex`: the input. -- `expect`: `decoded`, where our own encoding of the decoded value must equal `hex`, so a case - also pins the value, or `refused`, where the input is rejected without asking for more bytes. - -Every input is complete: asking for more bytes fails either expectation. - -A fuzz crash on a moq-lite message (`fuzz/regressions/`) belongs here instead, with -`expect` set, so `js/net` replays it too. diff --git a/rs/moq-net/corpus/lite/announce-active-lite05.json b/rs/moq-net/corpus/lite/announce-active-lite05.json deleted file mode 100644 index 6d25f2e8480..00000000000 --- a/rs/moq-net/corpus/lite/announce-active-lite05.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "version": "moq-lite-05", - "message": "announce", - "hex": "0d010a726f6f6d2f616c69636500", - "expect": "decoded" -} diff --git a/rs/moq-net/corpus/lite/announce-end-id-lite06.json b/rs/moq-net/corpus/lite/announce-end-id-lite06.json deleted file mode 100644 index 67c50d4faad..00000000000 --- a/rs/moq-net/corpus/lite/announce-end-id-lite06.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "version": "moq-lite-06", - "message": "announce", - "hex": "010103", - "expect": "decoded" -} diff --git a/rs/moq-net/corpus/lite/announce-init-over-budget.json b/rs/moq-net/corpus/lite/announce-init-over-budget.json deleted file mode 100644 index 00b2bdd575d..00000000000 --- a/rs/moq-net/corpus/lite/announce-init-over-budget.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "version": "moq-lite-02", - "message": "announce_init", - "budget": 1, - "hex": "050201610162", - "expect": "refused" -} diff --git a/rs/moq-net/corpus/lite/announce-init-over-size-cap.json b/rs/moq-net/corpus/lite/announce-init-over-size-cap.json deleted file mode 100644 index 894f9be21b1..00000000000 --- a/rs/moq-net/corpus/lite/announce-init-over-size-cap.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "version": "moq-lite-02", - "message": "announce_init", - "hex": "800ffff1", - "expect": "refused" -} diff --git a/rs/moq-net/corpus/lite/announce-init-within-budget.json b/rs/moq-net/corpus/lite/announce-init-within-budget.json deleted file mode 100644 index 0929869eec3..00000000000 --- a/rs/moq-net/corpus/lite/announce-init-within-budget.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "version": "moq-lite-02", - "message": "announce_init", - "budget": 2, - "hex": "050201610162", - "expect": "decoded" -} diff --git a/rs/moq-net/corpus/lite/announce-short-body-lite05.json b/rs/moq-net/corpus/lite/announce-short-body-lite05.json deleted file mode 100644 index 9457de4f59f..00000000000 --- a/rs/moq-net/corpus/lite/announce-short-body-lite05.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "version": "moq-lite-05", - "message": "announce", - "hex": "0101", - "expect": "refused" -} diff --git a/rs/moq-net/corpus/lite/announce-short-body-lite06.json b/rs/moq-net/corpus/lite/announce-short-body-lite06.json deleted file mode 100644 index b2545d9cd26..00000000000 --- a/rs/moq-net/corpus/lite/announce-short-body-lite06.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "version": "moq-lite-06", - "message": "announce", - "hex": "000105", - "expect": "refused" -} diff --git a/rs/moq-net/corpus/lite/announce-short-body-lite07.json b/rs/moq-net/corpus/lite/announce-short-body-lite07.json deleted file mode 100644 index edcf58087bd..00000000000 --- a/rs/moq-net/corpus/lite/announce-short-body-lite07.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "version": "moq-lite-07-wip", - "message": "announce", - "hex": "000105", - "expect": "refused" -} diff --git a/rs/moq-net/corpus/lite/announce-start-lite06.json b/rs/moq-net/corpus/lite/announce-start-lite06.json deleted file mode 100644 index 6e71cb8b330..00000000000 --- a/rs/moq-net/corpus/lite/announce-start-lite06.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "version": "moq-lite-06", - "message": "announce", - "hex": "00150a726f6f6d2f616c6963650000ffffffffffffffff", - "expect": "decoded" -} diff --git a/rs/moq-net/corpus/lite/client-setup-pinned-not-offered.json b/rs/moq-net/corpus/lite/client-setup-pinned-not-offered.json deleted file mode 100644 index 7d4fdeae789..00000000000 --- a/rs/moq-net/corpus/lite/client-setup-pinned-not-offered.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "version": "moq-lite-02", - "message": "client_setup", - "server": "moq-lite-05", - "hex": "20001202c0000000ff0dad07c0000000ff0dad0600", - "expect": "refused" -} diff --git a/rs/moq-net/corpus/lite/client-setup-pinned-offered.json b/rs/moq-net/corpus/lite/client-setup-pinned-offered.json deleted file mode 100644 index 5ed6e50eb4a..00000000000 --- a/rs/moq-net/corpus/lite/client-setup-pinned-offered.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "version": "moq-lite-02", - "message": "client_setup", - "server": "moq-lite-05", - "hex": "20001202c0000000ff0dad06c0000000ff0dad0500", - "expect": "decoded" -} diff --git a/rs/moq-net/corpus/lite/group-sequence-max-lite06.json b/rs/moq-net/corpus/lite/group-sequence-max-lite06.json deleted file mode 100644 index 54452fb46fc..00000000000 --- a/rs/moq-net/corpus/lite/group-sequence-max-lite06.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "version": "moq-lite-06", - "message": "group", - "hex": "0a00ffffffffffffffff00", - "expect": "decoded" -} diff --git a/rs/moq-net/corpus/lite/group-sequence-max-lite07.json b/rs/moq-net/corpus/lite/group-sequence-max-lite07.json deleted file mode 100644 index b8b3e269fef..00000000000 --- a/rs/moq-net/corpus/lite/group-sequence-max-lite07.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "version": "moq-lite-07-wip", - "message": "group", - "hex": "0b00ffffffffffffffffff00", - "expect": "decoded" -} diff --git a/rs/moq-net/fixtures/lite.json b/rs/moq-net/fixtures/lite.json new file mode 100644 index 00000000000..68601218265 --- /dev/null +++ b/rs/moq-net/fixtures/lite.json @@ -0,0 +1,97 @@ +[ + { + "name": "an active announce with no hops", + "version": "moq-lite-05", + "message": "announce", + "hex": "0d010a726f6f6d2f616c69636500", + "expect": "decoded" + }, + { + "name": "an ANNOUNCE_START carries its cost and the retired second field at the ceiling", + "version": "moq-lite-06", + "message": "announce", + "hex": "00150a726f6f6d2f616c6963650000ffffffffffffffff", + "expect": "decoded" + }, + { + "name": "an ANNOUNCE_END retracts by id", + "version": "moq-lite-06", + "message": "announce", + "hex": "010103", + "expect": "decoded" + }, + { + "name": "a body too short for its fields is malformed, not a wait for more (fuzz regression)", + "version": "moq-lite-05", + "message": "announce", + "hex": "0101", + "expect": "refused" + }, + { + "name": "a lite-06 body too short for its path is malformed, not a wait for more (fuzz regression)", + "version": "moq-lite-06", + "message": "announce", + "hex": "000105", + "expect": "refused" + }, + { + "name": "a lite-07 body too short for its path base is malformed, not a wait for more (fuzz regression)", + "version": "moq-lite-07-wip", + "message": "announce", + "hex": "000105", + "expect": "refused" + }, + { + "name": "an ANNOUNCE_INIT within the announce budget", + "version": "moq-lite-02", + "message": "announce_init", + "budget": 2, + "hex": "050201610162", + "expect": "decoded" + }, + { + "name": "an ANNOUNCE_INIT listing more broadcasts than the budget is refused before its paths decode", + "version": "moq-lite-02", + "message": "announce_init", + "budget": 1, + "hex": "050201610162", + "expect": "refused" + }, + { + "name": "an ANNOUNCE_INIT one byte past one storage segment is refused at its length prefix", + "version": "moq-lite-02", + "message": "announce_init", + "hex": "800ffff1", + "expect": "refused" + }, + { + "name": "a group sequence at 2^62-1, the largest a QUIC varint holds", + "version": "moq-lite-06", + "message": "group", + "hex": "0a00ffffffffffffffff00", + "expect": "decoded" + }, + { + "name": "a group sequence at 2^64-1, the largest a u64 holds", + "version": "moq-lite-07-wip", + "message": "group", + "hex": "0b00ffffffffffffffffff00", + "expect": "decoded" + }, + { + "name": "a server pinned to a version the client offered selects it", + "version": "moq-lite-02", + "message": "client_setup", + "server": "moq-lite-05", + "hex": "20001202c0000000ff0dad06c0000000ff0dad0500", + "expect": "decoded" + }, + { + "name": "a server pinned to a version the client did not offer refuses", + "version": "moq-lite-02", + "message": "client_setup", + "server": "moq-lite-05", + "hex": "20001202c0000000ff0dad07c0000000ff0dad0600", + "expect": "refused" + } +] diff --git a/rs/moq-net/fuzz/README.md b/rs/moq-net/fuzz/README.md index 32a34fb144a..f4b4b4809ab 100644 --- a/rs/moq-net/fuzz/README.md +++ b/rs/moq-net/fuzz/README.md @@ -87,4 +87,4 @@ cp rs/moq-net/fuzz/artifacts/ingest/crash- rs/moq-net/fuzz/regressions/ing `fuzz::tests::regressions` replays everything under `regressions//` as part of the normal test suite, so the case stays covered. A crash on a single moq-lite message -becomes a case in [`../corpus/`](../corpus/README.md) instead, which `js/net` replays too. +becomes a case in `../fixtures/lite.json` instead, which `js/net` replays too. diff --git a/rs/moq-net/src/lite/corpus.rs b/rs/moq-net/src/lite/corpus.rs index 3856c459095..04578862508 100644 --- a/rs/moq-net/src/lite/corpus.rs +++ b/rs/moq-net/src/lite/corpus.rs @@ -1,11 +1,19 @@ -//! Replays the moq-lite corpus in `corpus/lite/`, which `js/net` replays too, so a decoder -//! that drifts from the other language fails a test on both sides. See `corpus/README.md`. +//! Replays `fixtures/lite.json`, the moq-lite corpus `js/net` replays too +//! (`src/lite/corpus.test.ts`), so a decoder that drifts from the other language fails a test +//! on both sides. +//! +//! Each case is one complete wire input at a negotiated `version` (its handshake name), with +//! the outcome both must reach: `decoded`, where our own encoding of the decoded value must +//! equal the input, so a case also pins the value, or `refused`, where the input is rejected +//! without asking for more bytes. A fuzz crash on a single moq-lite message belongs here +//! rather than in `fuzz/regressions/`, so JS replays it too. use crate::coding::{Decode, DecodeError, Decoder, Encode, Form}; #[derive(serde::Deserialize)] #[serde(deny_unknown_fields)] struct Case { + name: String, version: crate::Version, message: Message, hex: String, @@ -19,9 +27,13 @@ struct Case { #[derive(serde::Deserialize)] #[serde(rename_all = "snake_case")] enum Message { + /// One announcement on the announce stream, type and length prefix included. Announce, + /// A lite-01/02 ANNOUNCE_INIT, length prefix included. AnnounceInit, + /// A group stream header, length prefix included. Group, + /// A `moql` CLIENT_SETUP. ClientSetup, } @@ -91,26 +103,18 @@ fn unhex(text: &str) -> Vec { #[test] fn corpus() { - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("corpus/lite"); + let cases: Vec = serde_json::from_str(include_str!("../../fixtures/lite.json")).expect("a malformed corpus"); + assert!(!cases.is_empty(), "the corpus is empty"); let mut failures = Vec::new(); - let mut count = 0; - for entry in std::fs::read_dir(&dir).expect("could not read the corpus") { - let path = entry.expect("could not read the corpus").path(); - if path.extension().is_none_or(|ext| ext != "json") { - continue; - } - let text = std::fs::read_to_string(&path).expect("could not read a corpus case"); - let case: Case = serde_json::from_str(&text).unwrap_or_else(|err| panic!("{}: {err}", path.display())); + for case in &cases { let want = match case.expect { Expect::Decoded => case.hex.clone(), Expect::Refused => "refused".to_string(), }; - let got = run(&case, &unhex(&case.hex)); + let got = run(case, &unhex(&case.hex)); if got != want { - failures.push(format!("{}: expected {want}, got {got}", path.display())); + failures.push(format!("{}: expected {want}, got {got}", case.name)); } - count += 1; } - assert!(count > 0, "the corpus is empty"); assert!(failures.is_empty(), "{}", failures.join("\n")); } From e059d8680a0fdf70b44ef42bcb3a294d6ae0f65f Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 17:35:53 -0800 Subject: [PATCH 06/10] quest: finish js-net-input-checks Co-Authored-By: Claude Opus 5.5 --- quest/m1/README.md | 1 - quest/m1/js-net-input-checks.md | 15 --------------- 2 files changed, 16 deletions(-) delete mode 100644 quest/m1/js-net-input-checks.md diff --git a/quest/m1/README.md b/quest/m1/README.md index 897602cde36..198419fb88f 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -34,7 +34,6 @@ moves what remains of them once their claims merge. - [JS cache pool](/quest/m1/js-cache-pool.md) - `js/net` bills cached frames and drop-set runs to a per-broadcast byte pool ported from Rust - [Drop set](/quest/m1/drop-set.md) - the drop set's track and cursor runs are billed to the cache pool, so fragmenting drops costs what the pool holds; eviction folds final runs or ends the cursor with `TooFarBehind` - [Only the relay's own stats publisher uses the stats prefix](/quest/m1/stats-prefix.md) - a broad grant can no longer publish unmetered media or spoof node stats under `.stats` -- [js/net and moq-net decode the same inputs the same way](/quest/m1/js-net-input-checks.md) - a shared input corpus pins both decoders, and a typed endpoint stops loopback spellings from slipping past GOAWAY checks - [Rust and JS run one token and key-set corpus](/quest/m1/token-parse-strict.md) - a shared corpus pins both parsers, so a null `exp` no longer means never-expiring in Rust - [Resetting a kio sleep to its deadline does not wake it](/quest/m1/kio-reset-same-deadline.md) - a caller that resets on every poll no longer spins the simulator - [A refused lite SUBSCRIBE_UPDATE ends the subscription](/quest/m1/lite-update-refused.md) - the publisher no longer serves a removed range or reports the wrong start after the model refuses an update diff --git a/quest/m1/js-net-input-checks.md b/quest/m1/js-net-input-checks.md deleted file mode 100644 index b2ef492063b..00000000000 --- a/quest/m1/js-net-input-checks.md +++ /dev/null @@ -1,15 +0,0 @@ -# [M] js/net and moq-net decode the same inputs the same way - -## Goal - -Rust and JS cannot drift apart on what they accept, because both run one shared corpus, and URLs are parsed once into a typed endpoint: - -- A shared corpus of moq-lite inputs, each with its expected outcome (decoded value, or refused), is replayed by `rs/moq-net` and `js/net` tests. It starts from the fuzz regressions in `rs/moq-net/fuzz/regressions` plus hand cases for every difference this audit found: the lite-01/02 ANNOUNCE_INIT size and count budget (JS allows 64 MiB and checks the announce budget only after building the array), group sequences at 2^64 (`checkSequence` accepts them), and a pinned server version the client did not offer (`accept.ts`). -- JS parses a dial target once into a typed endpoint (scheme, host as an IP or a name, port), the way `rs/moq-net/src/reconnect/redirect.rs` does, and GOAWAY classification, redirect checks, dialing and log redaction all use it. Today `isLocal` (`js/net/src/connection/goaway.ts`) reads the opaque `moql:` host, so `127.1`, `0x7f000001` and `2130706433` pass as non-local while `dialable()` turns them into 127.0.0.1, which lets a relay steer a `redirect: "follow"` client and its tokens to loopback. `redact` logs `null/` for `moql:` URLs, path tokens included. -- `open.ts` `patience` treats an RTT of 0 as unknown. - -## Plan - -Found by the 2026-11-07 invariant audit (js-2, js-5 to js-9). - -Decided 2026-11-07 (maintainer, invariant-audit root causes): the cause is two hand-written decoders with no shared inputs; the corpus makes any divergence a failing test on both sides. Pick the corpus location and format to suit both test runners (a directory of JSON or hex cases is the obvious start). The single-implementation route stays [Evaluate WASM-to-JS for @moq/net](/quest/m5/rs2ts-wasm2js.md). js-1 (announce queue growth) is [JS announced coalescing](/quest/m3/js-announced-coalesce.md). From f6db8579669859b4798b251ec83e50eb2d3d394a Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 17:42:36 -0800 Subject: [PATCH 07/10] fix(net): a run of groups may end at 2^64 Co-Authored-By: Claude Opus 5.5 --- js/net/src/fill.ts | 6 +++--- js/net/src/track.test.ts | 3 +++ js/net/src/track.ts | 4 ++-- js/net/src/util/sequence.ts | 8 ++++++++ 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/js/net/src/fill.ts b/js/net/src/fill.ts index 8f2ef577977..c866f1f3520 100644 --- a/js/net/src/fill.ts +++ b/js/net/src/fill.ts @@ -16,7 +16,7 @@ import { NotFound } from "./error.ts"; import type { Producer as GroupProducer } from "./group.ts"; import { insertRun, NO_MAX_DELAY, runGaps } from "./internal.ts"; import type { Info, Order } from "./track.ts"; -import { checkSequence, max, min } from "./util/sequence.ts"; +import { checkEnd, checkSequence, max, min } from "./util/sequence.ts"; // A half-open run of group sequences, as `internal.ts` has it, kept local so the published // declarations never reach the package internals. @@ -533,7 +533,7 @@ export class Fill { */ dropGroups(start: bigint, end: bigint): void { checkSequence(start); - checkSequence(end); + checkEnd(end); fillOps.drop(this.#state, this.#pending, start, end); } @@ -544,7 +544,7 @@ export class Fill { */ refuseGroups(start: bigint, end: bigint, error: Error): void { checkSequence(start); - checkSequence(end); + checkEnd(end); fillOps.refuse(this.#state, this.#pending, start, end, error); } diff --git a/js/net/src/track.test.ts b/js/net/src/track.test.ts index f783f6f8855..f341790ed97 100644 --- a/js/net/src/track.test.ts +++ b/js/net/src/track.test.ts @@ -4668,4 +4668,7 @@ test("group sequences stop at 2^64-1, as a u64 does", () => { expect(() => producer.createGroup(1n << 64n)).toThrow(RangeError); producer.createGroup((1n << 64n) - 1n).finish(); expect(() => producer.appendGroup()).toThrow(RangeError); + // A run's exclusive end may sit just past the last group. + producer.skipGroups(1n << 63n, 1n << 64n); + expect(() => producer.skipGroups(0n, (1n << 64n) + 1n)).toThrow(RangeError); }); diff --git a/js/net/src/track.ts b/js/net/src/track.ts index 1d6f689f9d4..e9df5df8be7 100644 --- a/js/net/src/track.ts +++ b/js/net/src/track.ts @@ -46,7 +46,7 @@ import { import { CACHE_EXPIRY, grace, Ledger } from "./ledger.ts"; import { rescale } from "./rescale.ts"; import { Timescale, type Timestamp } from "./time.ts"; -import { checkSequence, max, min, UNBOUNDED } from "./util/sequence.ts"; +import { checkEnd, checkSequence, max, min, UNBOUNDED } from "./util/sequence.ts"; import { bounded, type Holdings, @@ -1861,7 +1861,7 @@ export class Producer { */ skipGroups(start: bigint, end: bigint): void { checkSequence(start); - checkSequence(end); + checkEnd(end); this.#skipReceived(start, end); } diff --git a/js/net/src/util/sequence.ts b/js/net/src/util/sequence.ts index 89acbab4e4d..6077d3e057f 100644 --- a/js/net/src/util/sequence.ts +++ b/js/net/src/util/sequence.ts @@ -25,3 +25,11 @@ export function checkSequence(sequence: bigint): bigint { if (sequence >= UNBOUNDED) throw new RangeError(`group sequence exceeds 2^64-1: ${sequence}`); return sequence; } + +/** Refuse an exclusive end of a run of group sequences that is not a bigint in `[0, 2^64]`, so a run may end past group 2^64-1. */ +export function checkEnd(end: bigint): bigint { + if (typeof end !== "bigint") throw new TypeError(`group end must be a bigint: ${String(end)}`); + if (end < 0n) throw new RangeError(`group end must be non-negative: ${end}`); + if (end > UNBOUNDED) throw new RangeError(`group end exceeds 2^64: ${end}`); + return end; +} From 9e0720c9136cd07deeba4218191b3518a5ecd77e Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 21:03:15 -0800 Subject: [PATCH 08/10] fix(net): derive the announce-init cap from SEGMENT_BYTES like Rust Co-Authored-By: Claude Opus 5.5 --- js/net/src/lite/announce.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/js/net/src/lite/announce.ts b/js/net/src/lite/announce.ts index 46652a702ab..08905df4329 100644 --- a/js/net/src/lite/announce.ts +++ b/js/net/src/lite/announce.ts @@ -4,6 +4,7 @@ import type * as Instance from "../instance.ts"; import * as Path from "../path.ts"; import type { Reader, Writer } from "../stream.ts"; import { decodeRoute, encodeRoute } from "./instance.ts"; +import { SEGMENT_BYTES } from "../util/limits.ts"; import * as Message from "./message.ts"; import { hasAnnounceCompression, @@ -599,7 +600,7 @@ export class AnnounceInit { // The whole initial set in one message, capped like Rust's so it fits one storage segment // (1 MiB) with its type and size prefixes. A larger set is refused on both ends. - static readonly MAX_SIZE = 1024 * 1024 - 16; + static readonly MAX_SIZE = SEGMENT_BYTES - 16; async encode(w: Writer, version: Version): Promise { AnnounceInit.#guard(version); From fa7f323482ee9b18787d78ceeb862622a4dd83d1 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 21:18:14 -0800 Subject: [PATCH 09/10] style(net): sort imports Co-Authored-By: Claude Opus 5.5 --- js/net/src/lite/announce.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/net/src/lite/announce.ts b/js/net/src/lite/announce.ts index 08905df4329..b5e0605dccf 100644 --- a/js/net/src/lite/announce.ts +++ b/js/net/src/lite/announce.ts @@ -3,8 +3,8 @@ import { type Cost, type Hop, HopSchema, MAX_HOPS, UNKNOWN_HOP, wireHop } from " import type * as Instance from "../instance.ts"; import * as Path from "../path.ts"; import type { Reader, Writer } from "../stream.ts"; -import { decodeRoute, encodeRoute } from "./instance.ts"; import { SEGMENT_BYTES } from "../util/limits.ts"; +import { decodeRoute, encodeRoute } from "./instance.ts"; import * as Message from "./message.ts"; import { hasAnnounceCompression, From 6efc8866bed9097e4b54153d19cfc25494ab0ec4 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 7 Nov 2026 21:37:50 -0800 Subject: [PATCH 10/10] test(net): stop the ticker test's last subscriber so the loop dies with its clock Co-Authored-By: Claude Opus 5.5 --- js/net/src/connection/ticker.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/js/net/src/connection/ticker.test.ts b/js/net/src/connection/ticker.test.ts index c87600b4f76..85ba053da87 100644 --- a/js/net/src/connection/ticker.test.ts +++ b/js/net/src/connection/ticker.test.ts @@ -25,9 +25,11 @@ test("subscribers share one tick and the loop stops with the last", async () => expect(ticks).toEqual(["a", "b", "b"]); // A stopped loop restarts for a later subscriber, rather than leaving the page unsampled. - tick(period, () => ticks.push("c")); + const c = tick(period, () => ticks.push("c")); await clock.advance(period); expect(ticks).toEqual(["a", "b", "b", "c"]); + // Stopped, so the page-wide loop does not outlive this test's clock. + c(); } finally { installed.close(); }