From d5e01ace753838288dbde2b4f904c5c02677346a Mon Sep 17 00:00:00 2001 From: Elia <83713217+eliahilse@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:42:38 +0200 Subject: [PATCH] fix(http): harden JSON fallback byte and proxy handling Co-Authored-By: GPT 6.1 Sol --- .changeset/kind-vans-pull.md | 5 + packages/hyperfly/README.md | 3 + packages/hyperfly/benches/json-fallback.ts | 52 ++++ packages/hyperfly/src/http.ts | 193 ++++++++++-- packages/hyperfly/test/http-json.test.ts | 337 +++++++++++++++++++++ 5 files changed, 571 insertions(+), 19 deletions(-) create mode 100644 .changeset/kind-vans-pull.md create mode 100644 packages/hyperfly/benches/json-fallback.ts diff --git a/.changeset/kind-vans-pull.md b/.changeset/kind-vans-pull.md new file mode 100644 index 0000000..0e254ba --- /dev/null +++ b/.changeset/kind-vans-pull.md @@ -0,0 +1,5 @@ +--- +"hyperfly": patch +--- + +JSON fallback handles proxy `toJSON` hooks when runtime detection is available and reports invalid byte storage with value paths. Byte encoding ignores overridden typed-array properties so subclasses produce the bytes they contain. diff --git a/packages/hyperfly/README.md b/packages/hyperfly/README.md index 5a90fe9..26844d0 100644 --- a/packages/hyperfly/README.md +++ b/packages/hyperfly/README.md @@ -108,6 +108,9 @@ was created, including `Buffer` and values from other realms. Raw `ArrayBuffer` views (including `DataView`) raise code `json` with their path, like Python's unsupported `memoryview`; wrap the desired range in a `Uint8Array` to send it as bytes. +On the JSON fallback path an accessor property may be read twice; a getter that returns a different value per read serializes the later one. +Without runtime proxy detection, an empty-target Proxy that supplies `toJSON` through its `get` trap follows native `JSON.stringify` behavior. + A client that holds nothing gets JSON plus a `Hyperfly-Offer` naming an artifact it could fetch; once it has it, the same route can answer in binary. Responses carry `Vary: Hyperfly-Accept, Accept`. `respond` answers HEAD with the headers GET would get and no body, and status 204, 205 or 304 with the negotiated diff --git a/packages/hyperfly/benches/json-fallback.ts b/packages/hyperfly/benches/json-fallback.ts new file mode 100644 index 0000000..02c30e0 --- /dev/null +++ b/packages/hyperfly/benches/json-fallback.ts @@ -0,0 +1,52 @@ +import { encodeFor, negotiate, type JsonNegotiation } from "../src/http.js"; +import { CodecRegistry, compileIR, type IRNode } from "../src/index.js"; + +// Extract origin/main's packages/hyperfly/src into a temporary directory, then +// pass its http.ts path so both versions run on the same Bun process and data. +const baselinePath = Bun.argv[2]; +if (!baselinePath) throw new Error("usage: bun benches/json-fallback.ts /path/to/origin-main/src/http.ts"); +const baseline = await import(baselinePath) as { encodeFor: typeof encodeFor }; +const fields: Extract["fields"] = [ + { name: "id", type: { kind: "int" } }, { name: "name", type: { kind: "string" } }, + { name: "active", type: { kind: "bool" } }, { name: "score", type: { kind: "float64" } }, +]; +const registry = new CodecRegistry([compileIR({ kind: "array", element: { kind: "struct", fields } })]); +const byteRegistry = new CodecRegistry([compileIR({ kind: "array", element: { kind: "struct", fields: [ + ...fields, { name: "data", type: { kind: "bytes" } }, +] } })]); +const rows = Array.from({ length: 10_000 }, (_, id) => ({ id, name: `row ${id}`, active: id % 2 === 0, score: id / 2 })); +const bytes = rows.map((row) => ({ ...row, data: new Uint8Array([0, 127, 128, 255]) })); +const samples = 31; +const iterations = 5; +let consumed = 0; +function time(encode: typeof encodeFor, value: unknown, decision: JsonNegotiation) { + const start = performance.now(); + for (let i = 0; i < iterations; i++) consumed += (encode(decision, value).body as string).length; + return (performance.now() - start) / iterations; +} +function median(values: number[]) { + return values.sort((a, b) => a - b)[Math.floor(values.length / 2)]!; +} +for (const [name, value, codecs] of [["encode no-bytes", rows, registry], ["encode bytes", bytes, byteRegistry]] as const) { + const decision = negotiate(null, codecs); + if (decision.kind !== "json") throw new Error("expected JSON negotiation"); + for (let i = 0; i < 12; i++) { + time(baseline.encodeFor, value, decision); + time(encodeFor, value, decision); + } + const main: number[] = []; + const current: number[] = []; + for (let i = 0; i < samples; i++) { + if (i % 2 === 0) { + main.push(time(baseline.encodeFor, value, decision)); + current.push(time(encodeFor, value, decision)); + } else { + current.push(time(encodeFor, value, decision)); + main.push(time(baseline.encodeFor, value, decision)); + } + } + const before = median(main); + const after = median(current); + console.log(`${name}: origin/main=${before.toFixed(3)}ms current=${after.toFixed(3)}ms ratio=${(after / before).toFixed(3)} (${samples} interleaved samples, ${iterations} encodes/sample)`); +} +console.log(`Bun ${Bun.version}; consumed ${consumed} characters`); diff --git a/packages/hyperfly/src/http.ts b/packages/hyperfly/src/http.ts index 2c92394..592024f 100644 --- a/packages/hyperfly/src/http.ts +++ b/packages/hyperfly/src/http.ts @@ -160,10 +160,25 @@ function jsonAt(cause: unknown, key: string): never { throw cause; } +const jsonTypedArrayToBase64 = Object.getOwnPropertyDescriptor(Uint8Array.prototype, "toBase64")?.value as ((this: Uint8Array) => string) | undefined; +const jsonTypedArrayBuffer = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype) as object, "buffer")!.get!; + function base64(bytes: Uint8Array): string { + // Native encoding reads and validates the typed-array slots directly. + if (typeof jsonTypedArrayToBase64 === "function") return jsonTypedArrayToBase64.call(bytes); + // The copy constructor validates the view and copies slots without reading + // user-provided length, iterator, constructor, or subarray properties. + const copy = new Uint8Array(bytes); + const length = byteLengthOf(copy); + if (length < 32) { + let raw = ""; + for (let i = 0; i < length; i++) raw += String.fromCharCode(copy[i]!); + return btoa(raw); + } + const buffer = jsonTypedArrayBuffer.call(copy) as ArrayBuffer; const chunks: string[] = []; - for (let start = 0; start < bytes.length; start += 0x8000) { - chunks.push(String.fromCharCode(...bytes.subarray(start, start + 0x8000))); + for (let start = 0; start < length; start += 0x8000) { + chunks.push(String.fromCharCode(...new Uint8Array(buffer, start, Math.min(0x8000, length - start)))); } return btoa(chunks.join("")); } @@ -331,9 +346,29 @@ const bufferByteLengths = [ArrayBuffer, globalThis.SharedArrayBuffer] .filter((type) => typeof type === "function") .map((type) => Object.getOwnPropertyDescriptor(type.prototype, "byteLength")!.get!); -/** The intrinsic getters recognize raw storage, shared or not, from other realms without trusting its tag. */ -function isRawArrayBuffer(value: object): boolean { - if (!("byteLength" in value)) return false; +interface JsonIntrinsics { + isProxy(value: unknown): boolean; + isBoxedPrimitive?(value: unknown): boolean; +} + +/** Runtime slot checks keep the preflight free of observable Proxy traps. */ +function jsonIntrinsics(): JsonIntrinsics | undefined { + const get = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process?.getBuiltinModule; + try { + const types = (get?.("node:util") as { types?: JsonIntrinsics } | undefined)?.types; + if (typeof types?.isProxy === "function") return types; + } catch { + // Native JSON traversal remains available without runtime Proxy detection. + } + return undefined; +} + +const jsonSlots = jsonIntrinsics(); +const TypedArray = Object.getPrototypeOf(Uint8Array) as typeof Uint8Array; + +/** Intrinsic getters also recognize storage with a null prototype and storage from other realms. */ +function isRawArrayBuffer(value: object, prototype: object | null): boolean { + if (prototype === Object.prototype || prototype === Array.prototype) return false; for (const byteLength of bufferByteLengths) { try { byteLength.call(value); @@ -345,14 +380,26 @@ function isRawArrayBuffer(value: object): boolean { return false; } +/** Slot checks run first; a byte prototype without slots identifies a proxied or fabricated receiver. */ +function isProxiedByteStorage(value: object, prototype: object | null): boolean { + return prototype !== Object.prototype && prototype !== Array.prototype && prototype !== null + && (value instanceof TypedArray || value instanceof ArrayBuffer || value instanceof DataView + || (typeof SharedArrayBuffer === "function" && value instanceof SharedArrayBuffer)); +} + /** A bounded preflight keeps ordinary data on the native JSON.stringify fast path. */ -function mayContainBytes(value: object, depth = 0): boolean { - if (depth === 128 || ArrayBuffer.isView(value) || "toJSON" in value || isRawArrayBuffer(value)) return true; +function mayContainBytes(value: object, state: { proxy: boolean }, depth = 0): boolean { + if (jsonSlots?.isProxy(value)) { state.proxy = true; return true; } + if (depth === 128 || ArrayBuffer.isView(value)) return true; + const prototype: object | null = Object.getPrototypeOf(value); + if (isRawArrayBuffer(value, prototype)) return true; + if (isProxiedByteStorage(value, prototype)) { state.proxy = true; return true; } + if ("toJSON" in value) return true; if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) { const item: unknown = value[i]; if (typeof item === "object" && item !== null) { - if (mayContainBytes(item, depth + 1)) return true; + if (mayContainBytes(item, state, depth + 1)) return true; } else if (typeof item === "function" || typeof item === "bigint") return true; } } else { @@ -360,41 +407,141 @@ function mayContainBytes(value: object, depth = 0): boolean { if (!Object.hasOwn(value, key)) continue; const item: unknown = (value as Record)[key]; if (typeof item === "object" && item !== null) { - if (mayContainBytes(item, depth + 1)) return true; + if (mayContainBytes(item, state, depth + 1)) return true; } else if (typeof item === "function" || typeof item === "bigint") return true; } } return false; } +/** JSON unboxes only these four internal-slot types, even across realms or with altered prototypes. */ +function unboxJson(value: object): unknown { + if (jsonSlots?.isBoxedPrimitive?.(value) === false) return value; + let number = false; + try { Number.prototype.valueOf.call(value); number = true; } catch { /* Not a Number wrapper. */ } + if (number) return +(value as unknown as number); + let string = false; + try { String.prototype.valueOf.call(value); string = true; } catch { /* Not a String wrapper. */ } + if (string) return `${value as unknown as string}`; + try { return Boolean.prototype.valueOf.call(value); } catch { /* Not a Boolean wrapper. */ } + try { return BigInt.prototype.valueOf.call(value); } catch { /* Not a BigInt wrapper. */ } + return value; +} + +/** SerializeProperty in JSON order, retaining the single Get before toJSON so bytes cannot be hidden. */ +function stringifyWithBytes(input: unknown): string | undefined { + const ancestors = new Set(); + const path: (string | number)[] = []; + function fail(message: string, cause?: unknown): never { + throw new EncodeError("json", `$${path.map((key) => typeof key === "number" ? `[${key}]` : `.${key}`).join("")}: ${message}`, { cause }); + } + function byteValue(value: object): string | undefined { + if (ArrayBuffer.isView(value)) { + if (isUint8Array(value)) { + try { return base64(value); } catch (cause) { fail("detached or out-of-bounds Uint8Array", cause); } + } + fail("unsupported byte storage or view; use Uint8Array"); + } + const prototype: object | null = Object.getPrototypeOf(value); + if (isRawArrayBuffer(value, prototype)) fail("unsupported byte storage or view; use Uint8Array"); + if (isProxiedByteStorage(value, prototype)) { + fail("proxied byte storage or view; pass the Uint8Array itself"); + } + return undefined; + } + function serialize(original: unknown, key: string): unknown { + let value = original; + // Reject slot-less byte receivers before invoking methods such as Buffer.toJSON. + if (typeof original === "object" && original !== null && !ArrayBuffer.isView(original)) { + const prototype: object | null = Object.getPrototypeOf(original); + if (!isRawArrayBuffer(original, prototype) && isProxiedByteStorage(original, prototype)) { + fail("proxied byte storage or view; pass the Uint8Array itself"); + } + } + if ((typeof value === "object" && value !== null) || typeof value === "function" || typeof value === "bigint") { + const toJSON: unknown = (value as { toJSON?: unknown }).toJSON; + if (typeof toJSON === "function") value = Reflect.apply(toJSON, value, [key]); + if (typeof original === "object" && original !== null) { + const bytes = byteValue(original); + if (bytes !== undefined) return bytes; + } + } + if (typeof value === "object" && value !== null) { + if (value !== original) { + const bytes = byteValue(value); + if (bytes !== undefined) return bytes; + } + value = unboxJson(value); + } + if (typeof value === "function" || typeof value === "symbol") return undefined; + if (typeof value === "bigint") throw new TypeError("Do not know how to serialize a BigInt"); + if (typeof value !== "object" || value === null) return value; + if (ancestors.has(value)) throw new TypeError("Converting circular structure to JSON"); + ancestors.add(value); + if (Array.isArray(value)) { + const length = Math.min(Math.max(Math.trunc(+(value.length as number)), 0) || 0, Number.MAX_SAFE_INTEGER); + const output: unknown[] = new Array(length); + Object.setPrototypeOf(output, null); + for (let i = 0; i < length; i++) { + path.push(i); + output[i] = serialize(value[i], String(i)); + path.pop(); + } + ancestors.delete(value); + return output; + } + const output = Object.create(null) as Record; + for (const name of Object.keys(value)) { + path.push(name); + const item = serialize((value as Record)[name], name); + path.pop(); + output[name] = item; + } + ancestors.delete(value); + return output; + } + return JSON.stringify(serialize(input, "")); +} + /** JSON.stringify owns traversal and toJSON behavior; bytes convert independently of the schema. */ function jsonReplacer() { const parents = new WeakMap(); - function unsupported(holder: object, key: string): never { + function unsupported(holder: object, key: string, proxied = false, cause?: unknown): never { let path = ""; for (let parent = parents.get(holder); parent; parent = parents.get(holder)) { path = (Array.isArray(holder) ? `[${key}]` : `.${key}`) + path; holder = parent.holder; key = parent.key; } - throw new EncodeError("json", `$${path}: unsupported byte storage or view; use Uint8Array`); + const message = cause !== undefined ? "detached or out-of-bounds Uint8Array" + : proxied ? "proxied byte storage or view; pass the Uint8Array itself" + : "unsupported byte storage or view; use Uint8Array"; + throw new EncodeError("json", `$${path}: ${message}`, { cause }); } return function (this: object, key: string, value: unknown): unknown { // toJSON runs first, so inspect the original as well to recognize Buffer and byte subclasses. const original: unknown = Reflect.get(this, key); if (typeof original === "object" && original !== null && original !== value) { if (ArrayBuffer.isView(original)) { - if (isUint8Array(original)) return base64(original); + if (isUint8Array(original)) { + try { return base64(original); } catch (cause) { unsupported(this, key, false, cause); } + } unsupported(this, key); } - if (isRawArrayBuffer(original)) unsupported(this, key); + const prototype: object | null = Object.getPrototypeOf(original); + if (isRawArrayBuffer(original, prototype)) unsupported(this, key); + if (isProxiedByteStorage(original, prototype)) unsupported(this, key, true); } if (typeof value === "object" && value !== null) { if (ArrayBuffer.isView(value)) { - if (isUint8Array(value)) return base64(value); + if (isUint8Array(value)) { + try { return base64(value); } catch (cause) { unsupported(this, key, false, cause); } + } unsupported(this, key); } - if (isRawArrayBuffer(value)) unsupported(this, key); + const prototype: object | null = Object.getPrototypeOf(value); + if (isRawArrayBuffer(value, prototype)) unsupported(this, key); + if (isProxiedByteStorage(value, prototype)) unsupported(this, key, true); parents.set(value, { holder: this, key }); } return value; @@ -416,9 +563,11 @@ function parseJson(text: string, registry: CodecRegistry): T { function jsonBody(value: unknown): string { let body: string | undefined; try { - const needsReplacer = typeof value === "object" && value !== null - ? mayContainBytes(value) : typeof value === "function" || typeof value === "bigint"; - body = needsReplacer ? JSON.stringify(value, jsonReplacer()) : JSON.stringify(value); + const state = { proxy: false }; + const needsConversion = typeof value === "object" && value !== null + ? mayContainBytes(value, state) : typeof value === "function" || typeof value === "bigint"; + body = state.proxy ? stringifyWithBytes(value) + : needsConversion ? JSON.stringify(value, jsonReplacer()) : JSON.stringify(value); } catch (cause) { if (isInstance(cause, EncodeError) && cause.code === "json") throw cause; throw new EncodeError("json", `$: ${messageOf(cause, "value could not be encoded as JSON")}`, { cause }); @@ -427,7 +576,11 @@ function jsonBody(value: unknown): string { return body; } -/** Encode one value according to a negotiation decision; JSON bytes are schema-independent. */ +/** + * Encode one value according to a negotiation decision; JSON bytes are schema-independent. + * On the JSON fallback path an accessor property may be read twice; a getter that + * returns a different value per read serializes the later one. + */ export function encodeFor(decision: Negotiation, value: NoInfer, options: EncodeOptions = {}): Encoded { if (decision.kind === "hyperfly") { try { @@ -735,6 +888,8 @@ export interface RespondOptions extends NegotiateOptions, EncodeOptions { * Answer one request with `value`, in binary when the client can read it. Fetch-API * glue: one function covers Hono, Cloudflare Workers, Bun.serve, Deno and Next route * handlers, because they all speak Request and Response. + * On the JSON fallback path an accessor property may be read twice; a getter that + * returns a different value per read serializes the later one. */ export function respond( request: Request, diff --git a/packages/hyperfly/test/http-json.test.ts b/packages/hyperfly/test/http-json.test.ts index ba1848c..4b6ddd0 100644 --- a/packages/hyperfly/test/http-json.test.ts +++ b/packages/hyperfly/test/http-json.test.ts @@ -220,3 +220,340 @@ test("JSON bytes conversion handles toJSON on byte subclasses and on surrounding expect(encodeFor(negotiate(null, new CodecRegistry()), value).body) .toBe('{"bytes":"/w==","nested":{"data":"/w=="},"numeric":{"0":255}}'); }); + +test.each([false, true])("conservative JSON getters run once in traversal order, bytes=%p", (withBytes) => { + const calls: string[] = []; + let reads = 0; + const value = { + ...(withBytes ? { bytes: new Uint8Array([255]) } : {}), + get first() { + calls.push("first"); + return ++reads === 1 ? { get nested() { calls.push("nested"); return 1; } } : "second read"; + }, + get last() { calls.push("last"); return 2; }, + }; + expect(encodeFor(negotiate(null, new CodecRegistry()), new Proxy(value as object, {})).body) + .toBe(`${withBytes ? '{"bytes":"/w==",' : "{"}"first":{"nested":1},"last":2}`); + expect(reads).toBe(1); + expect(calls).toEqual(["first", "nested", "last"]); +}); + +test("JSON conversion reads getter results before their toJSON exactly once", () => { + const calls: string[] = []; + const value = { + get data() { + calls.push("get data"); + return { get toJSON() { + calls.push("get toJSON"); + return function (this: object, key: string) { + calls.push(`call toJSON ${key}`); + expect(this).toBe(result); + return new Uint8Array([255]); + }; + } }; + }, + }; + const result = value.data; + calls.length = 0; + Object.defineProperty(value, "data", { enumerable: true, get() { calls.push("get data"); return result; } }); + expect(encodeFor(negotiate(null, new CodecRegistry()), new Proxy(value as object, {})).body).toBe('{"data":"/w=="}'); + expect(calls).toEqual(["get data", "get toJSON", "call toJSON data"]); +}); + +test("JSON observes a Proxy's Get-supplied toJSON without consulting has", () => { + for (const nested of [false, true]) { + const calls: string[] = []; + const proxy = new Proxy({}, { + has() { throw new Error("must not use HasProperty"); }, + get(_target, key) { + calls.push(String(key)); + if (key === "toJSON") return function (this: object, key: string) { + expect(this).toBe(proxy); + calls.push(`call ${key}`); + return new Uint8Array([255]); + }; + }, + }); + expect(encodeFor(negotiate(null, new CodecRegistry()), nested ? { data: proxy } : proxy).body) + .toBe(nested ? '{"data":"/w=="}' : '"/w=="'); + expect(calls).toEqual(["toJSON", `call ${nested ? "data" : ""}`]); + } +}); + +test.each([ + new Uint8Array([255]), Buffer.from([255]), new ArrayBuffer(1), new SharedArrayBuffer(1), new DataView(new ArrayBuffer(1)), + new Int8Array([1]), new Uint8ClampedArray([1]), new Uint16Array([1]), new Int16Array([1]), + new Uint32Array([1]), new Int32Array([1]), new Float32Array([1]), new Float64Array([1]), + new BigInt64Array([1n]), new BigUint64Array([1n]), +])("JSON rejects proxies around byte storage or views: %p", (target) => { + const proxy = new Proxy(target, {}); + const decision = negotiate(null, new CodecRegistry()); + for (const [value, path] of [[proxy, "$"], [{ rows: [{ data: proxy }] }, "$.rows[0].data"]] as const) { + expect(() => encodeFor(decision, value)).toThrow(expect.objectContaining({ + code: "json", message: `${path}: proxied byte storage or view; pass the Uint8Array itself`, + })); + } +}); + +test("JSON wraps revoked proxies at root, nested, behind getters and returned by toJSON", () => { + const { proxy, revoke } = Proxy.revocable({}, {}); + revoke(); + for (const value of [proxy, { rows: [proxy] }, { get value() { return proxy; } }, { toJSON: () => proxy }]) { + expect(() => encodeFor(negotiate(null, new CodecRegistry()), value)) + .toThrow(expect.objectContaining({ name: "EncodeError", code: "json", cause: expect.any(TypeError) })); + } +}); + +test.each([new ArrayBuffer(1), new SharedArrayBuffer(1)])("JSON rejects raw storage with a null prototype: %p", (buffer) => { + Object.setPrototypeOf(buffer, null); + const decision = negotiate(null, new CodecRegistry()); + expect(() => encodeFor(decision, buffer)).toThrow(expect.objectContaining({ + code: "json", message: "$: unsupported byte storage or view; use Uint8Array", + })); + expect(() => encodeFor(decision, { rows: [{ data: buffer }] })).toThrow(expect.objectContaining({ + code: "json", message: "$.rows[0].data: unsupported byte storage or view; use Uint8Array", + })); + const dictionary = Object.assign(Object.create(null) as object, { id: 1 }); + expect(encodeFor(decision, dictionary).body).toBe('{"id":1}'); +}); + +test("JSON conversion preserves sparse arrays, inherited indices, key order and scalar representations", () => { + const prototype = Object.create(Array.prototype) as unknown[]; + prototype[1] = new Uint8Array([255]); + const sparse: unknown[] = new Array(4); + sparse[0] = undefined; + Object.setPrototypeOf(sparse, prototype); + Object.defineProperty(sparse, "ignored", { enumerable: true, get() { throw new Error("must not read"); } }); + const value = Object.create({ inherited: "ignored" }) as Record; + for (const [key, item] of [["z", sparse], ["2", -0], ["1", NaN], ["__proto__", "own"], ["unicode", "\ud800\udfff\ud800\n\"\\"], + ["undefined", undefined], ["function", () => {}], ["symbol", Symbol("x")], ["infinity", Infinity]] as const) { + Object.defineProperty(value, key, { enumerable: true, value: item }); + } + expect(encodeFor(negotiate(null, new CodecRegistry()), new Proxy(value as object, {})).body) + .toBe('{"1":null,"2":0,"z":[null,"/w==",null,null],"__proto__":"own","unicode":' + JSON.stringify(value.unicode) + ',"infinity":null}'); +}); + +test("JSON conversion wraps BigInt and cycles as TypeError causes before reading later getters", () => { + const cycle: Record = {}; + cycle.self = cycle; + for (const bad of [1n, Object(1n) as object, cycle]) { + let later = 0; + expect(() => encodeFor(negotiate(null, new CodecRegistry()), { + bytes: new Uint8Array([255]), bad, get later() { later++; return 1; }, + })).toThrow(expect.objectContaining({ code: "json", cause: expect.any(TypeError) })); + expect(later).toBe(0); + } +}); + +test("JSON conversion matches JSON.stringify on 5,000 seeded graphs without bytes", () => { + let seed = 0x51f15e; + const random = (bound: number): number => { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; + return seed % bound; + }; + const decision = negotiate(null, new CodecRegistry()); + for (let iteration = 0; iteration < 5000; iteration++) { + const reads: number[] = []; + const trace: string[] = []; + const shared = { value: iteration }; + const scalar = (): unknown => [null, undefined, true, false, -0, NaN, Infinity, -Infinity, + 1.25, random(100_000), "", "\ud800", "\udfff", "é日本😀\n\t\"\\", Symbol("omitted"), () => {}][random(16)]; + function graph(depth: number): unknown { + if (depth === 0) return scalar(); + switch (random(9)) { + case 0: return scalar(); + case 1: return new Date(random(2) ? random(2_000_000_000) : NaN); + case 2: return Object([true, -0, 3.75, "\ud800", Symbol("boxed")][random(5)]) as object; + case 3: return { toJSON(key: string) { trace.push(`toJSON:${key}`); return { [key]: scalar() }; } }; + case 4: return [shared, shared, graph(depth - 1)]; + case 5: { + const array: unknown[] = new Array(random(5)); + for (let i = 0; i < array.length; i++) if (random(3)) array[i] = graph(depth - 1); + return array; + } + default: { + const object = Object.create(random(2) ? null : { inherited: "ignored" }) as Record; + for (const key of ["2", "0", "__proto__", "odd.[]", "\ud800", "a"]) { + if (random(3) === 0) continue; + const value = graph(depth - 1); + if (random(3) === 0) { + const index = reads.push(0) - 1; + Object.defineProperty(object, key, { enumerable: true, get() { reads[index]!++; trace.push(`get:${index}`); return value; } }); + } else Object.defineProperty(object, key, { enumerable: true, value }); + } + return object; + } + } + } + // A root Proxy selects the conservative path; its accessor records the root Get. + let rootReads = 0; + const value = graph(3); + const input = { get graph() { rootReads++; return value; } }; + const beforeSeed = seed; + const expected = JSON.stringify(input); + const expectedReads = [...reads]; + const expectedTrace = [...trace]; + seed = beforeSeed; + rootReads = 0; + reads.fill(0); + trace.length = 0; + expect(encodeFor(decision, new Proxy(input, {})).body).toBe(expected); + expect(rootReads).toBe(1); + expect(reads).toEqual(expectedReads); + expect(reads.every((count) => count === 1)).toBe(true); + expect(trace).toEqual(expectedTrace); + } +}); + +test("JSON conversion preserves boxed primitive coercion, realms and toJSON results", () => { + const number = Object(1) as { [Symbol.toPrimitive]?: () => number }; + number[Symbol.toPrimitive] = () => 12; + const string = Object("original") as { toString?: () => string }; + string.toString = () => "changed\ud800"; + const boolean = Object(false) as { valueOf?: () => boolean }; + boolean.valueOf = () => true; + const foreign: unknown = runInNewContext('[new Number(-0), new String("foreign"), new Boolean(false), Object(Symbol("x"))]'); + const returned = { toJSON: () => ({ toJSON: "not called", value: 1 }) }; + const functionValue = () => {}; + let calls = 0; + Object.defineProperty(functionValue, "toJSON", { get() { calls++; return undefined; } }); + const value = { number, string, boolean, foreign, returned, functionValue }; + const expected = JSON.stringify(value); + calls = 0; + expect(encodeFor(negotiate(null, new CodecRegistry()), new Proxy(value as object, {})).body).toBe(expected); + expect(calls).toBe(1); +}); + +test("JSON conversion reads inherited toJSON getters once and uses the root and array keys", () => { + const calls: string[] = []; + const prototype = Object.defineProperty({}, "toJSON", { + get() { calls.push("get"); return function (key: string) { calls.push(`call:${key}`); return -0; }; }, + }); + const value: unknown = Object.create(prototype); + expect(encodeFor(negotiate(null, new CodecRegistry()), new Proxy(value as object, {})).body).toBe("0"); + expect(calls).toEqual(["get", "call:"]); + calls.length = 0; + expect(encodeFor(negotiate(null, new CodecRegistry()), [value]).body).toBe("[0]"); + expect(calls).toEqual(["get", "call:0"]); +}); + +test("JSON preserves bytes returned by a getter even when their toJSON hides the view", () => { + let reads = 0; + let conversions = 0; + class Bytes extends Uint8Array { + toJSON() { conversions++; return "hidden"; } + } + expect(encodeFor(negotiate(null, new CodecRegistry()), new Proxy({ + get data() { reads++; return new Bytes([255]); }, + }, {})).body).toBe('{"data":"/w=="}'); + expect(reads).toBe(1); + expect(conversions).toBe(1); +}); + +test.each([false, true])("ordinary JSON fallback retains accessor rereads, bytes=%p", (withBytes) => { + let reads = 0; + const value = { + ...(withBytes ? { bytes: new Uint8Array([255]) } : {}), + get data() { reads++; return withBytes ? new Uint8Array([reads]) : reads; }, + }; + expect(encodeFor(negotiate(null, new CodecRegistry()), value).body) + .toBe(withBytes ? '{"bytes":"/w==","data":"Ag=="}' : '{"data":2}'); + expect(reads).toBe(2); +}); + +test("without runtime Proxy detection, native toJSON behavior and byte-proxy errors remain available", async () => { + const descriptor = Object.getOwnPropertyDescriptor(process, "getBuiltinModule")!; + try { + Object.defineProperty(process, "getBuiltinModule", { ...descriptor, value: undefined }); + const path = "../src/http.ts?without-proxy-detection"; + const native = await import(path) as typeof import("../src/http.js"); + const decision = negotiate(null, new CodecRegistry()); + const proxy = new Proxy({}, { get: (_target, key) => key === "toJSON" ? () => new Uint8Array([255]) : undefined }); + expect(native.encodeFor(decision, proxy).body).toBe(JSON.stringify(proxy)); + expect(native.encodeFor(decision, { data: proxy }).body).toBe(JSON.stringify({ data: proxy })); + for (const target of [new Uint8Array([255]), Buffer.from([255]), new ArrayBuffer(1), new SharedArrayBuffer(1), new DataView(new ArrayBuffer(1)), new Int16Array([1])]) { + const view = new Proxy(target, {}); + expect(() => native.encodeFor(decision, view)).toThrow(expect.objectContaining({ + code: "json", message: "$: proxied byte storage or view; pass the Uint8Array itself", + })); + expect(() => native.encodeFor(decision, { data: view })).toThrow(expect.objectContaining({ + code: "json", message: "$.data: proxied byte storage or view; pass the Uint8Array itself", + })); + } + const { proxy: revoked, revoke } = Proxy.revocable({}, {}); + revoke(); + expect(() => native.encodeFor(decision, { data: revoked })).toThrow(expect.objectContaining({ name: "EncodeError", code: "json" })); + } finally { + Object.defineProperty(process, "getBuiltinModule", descriptor); + } +}); + +test("JSON byte conversion ignores overridden typed-array properties", () => { + class Bytes extends Uint8Array { + get length() { return 0; } + subarray() { return new Uint8Array([65, 65, 65]); } + } + for (const length of [3, 32, 0x8001]) { + const expected = new Uint8Array(length).fill(1); + expected.set([1, 2, 3]); + const value = new Bytes(expected); + for (const key of ["buffer", "byteOffset", "byteLength", "constructor", "toBase64", Symbol.iterator]) { + Object.defineProperty(value, key, { get() { throw new Error(`must not read ${String(key)}`); } }); + } + const decision = negotiate(null, new CodecRegistry()); + const body = JSON.stringify(Buffer.from(expected).toString("base64")); + expect(encodeFor(decision, value).body).toBe(body); + expect(encodeFor(decision, { data: value }).body).toBe(`{"data":${body as string}}`); + expect(encodeFor(decision, new Proxy({ data: value }, {})).body).toBe(`{"data":${body as string}}`); + } +}); + +test("JSON reports detached and out-of-bounds byte views with their path", () => { + const detached = new Uint8Array([1, 2, 3]); + structuredClone(detached.buffer, { transfer: [detached.buffer] }); + const buffer = new ArrayBuffer(4, { maxByteLength: 8 }); + const outOfBounds = new Uint8Array(buffer, 2, 2); + buffer.resize(1); + const decision = negotiate(null, new CodecRegistry()); + for (const bytes of [detached, outOfBounds]) { + for (const [value, path] of [[bytes, "$"], [{ rows: [{ data: bytes }] }, "$.rows[0].data"], + [new Proxy({ rows: [{ data: bytes }] }, {}), "$.rows[0].data"]] as const) { + expect(() => encodeFor(decision, value)).toThrow(expect.objectContaining({ + name: "EncodeError", code: "json", message: `${path}: detached or out-of-bounds Uint8Array`, cause: expect.any(TypeError), + })); + } + } +}); + +test("JSON base64 fallback reads slots when native toBase64 is unavailable", async () => { + const descriptor = Object.getOwnPropertyDescriptor(Uint8Array.prototype, "toBase64"); + try { + Object.defineProperty(Uint8Array.prototype, "toBase64", { configurable: true, value: undefined }); + const path = "../src/http.ts?without-native-base64"; + const fallback = await import(path) as typeof import("../src/http.js"); + const decision = negotiate(null, new CodecRegistry()); + for (const length of [3, 32, 0x8001]) { + const bytes = new Uint8Array(length).fill(1); + bytes.set([1, 2, 3]); + const body = JSON.stringify(Buffer.from(bytes).toString("base64")); + for (const key of ["length", "subarray", "buffer", "byteOffset", "byteLength", "constructor", "toBase64", Symbol.iterator]) { + Object.defineProperty(bytes, key, { get() { throw new Error(`must not read ${String(key)}`); } }); + } + expect(fallback.encodeFor(decision, bytes).body).toBe(body); + expect(fallback.encodeFor(decision, new Proxy({ data: bytes }, {})).body).toBe(`{"data":${body}}`); + } + const detached = new Uint8Array([1]); + structuredClone(detached.buffer, { transfer: [detached.buffer] }); + const buffer = new ArrayBuffer(4, { maxByteLength: 8 }); + const outOfBounds = new Uint8Array(buffer, 2, 2); + buffer.resize(1); + for (const bytes of [detached, outOfBounds]) { + expect(() => fallback.encodeFor(decision, { data: bytes })).toThrow(expect.objectContaining({ + code: "json", message: "$.data: detached or out-of-bounds Uint8Array", cause: expect.any(TypeError), + })); + } + } finally { + if (descriptor) Object.defineProperty(Uint8Array.prototype, "toBase64", descriptor); + else Reflect.deleteProperty(Uint8Array.prototype, "toBase64"); + } +});