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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/gold-llamas-eat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"hyperfly": patch
---

Encode bytes subclasses using their actual bytes and lengths across row, columnar and packed encodings. Safely wrap hostile error proxies with coded errors when checking options and profiles.
4 changes: 2 additions & 2 deletions packages/hyperfly/src/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { defaultPackHooks } from "./pack.js";
import { checkedProfile, indexProfile, type Profile } from "./profile.js";
import { decodeNode } from "./decode.js";
import { checkByteBudget, checkItemBudget, encodeNode, type EncodeCtx } from "./encode.js";
import { DecodeError, FingerprintMismatchError, HyperflyError, isInstance } from "./errors.js";
import { DecodeError, FingerprintMismatchError, hasErrorCode, HyperflyError } from "./errors.js";
import { validateIR, withinStack, type IRNode } from "./ir.js";
import { DEFAULT_LIMITS, Reader, type Limits } from "./reader.js";
import { Writer } from "./writer.js";
Expand Down Expand Up @@ -153,7 +153,7 @@ export function checkedOptions(options: CompileOptions & { validate?: boolean })
}
return { limits: checkedLimits, plan: plan ?? "row", pack: checkedPack, profile, validate };
} catch (cause) {
if (isInstance(cause, HyperflyError) && cause.code === "options") throw cause;
if (hasErrorCode(cause, "options")) throw cause;
throw new HyperflyError("options", "options: could not read compile options", { cause });
}
}
Expand Down
14 changes: 8 additions & 6 deletions packages/hyperfly/src/columnar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { DecodeError, EncodeError } from "./errors.js";
import { literalBytes, utf8Length, utf8Lengths, type IRField, type IRNode } from "./ir.js";
import type { GrammarToken, ProfileIndex } from "./profile.js";
import type { Reader } from "./reader.js";
import { isUint8Array } from "./typed-array.js";
import { byteLengthOf, copyBytes, isUint8Array } from "./typed-array.js";
import { INT_MAX, INT_MIN, readUleb, ulebLen, unzigzag, writeUleb, zigzag } from "./varint.js";
import { Writer } from "./writer.js";

Expand Down Expand Up @@ -783,6 +783,7 @@ function encodeStringColumn(
}

let packed: Uint8Array | null = null;
let packedLength = 0;
let packedCost = Infinity;
const totalBytes = bytes.reduce((n, value) => n + value.length, 0);
// §3: the deflate mode's total length obeys the byte limits, so a
Expand All @@ -792,7 +793,7 @@ function encodeStringColumn(
const concat = new Uint8Array(total);
let offset = 0;
for (const value of bytes) {
concat.set(value, offset);
copyBytes(concat, value, offset);
offset += value.length;
}
try {
Expand All @@ -803,10 +804,11 @@ function encodeStringColumn(
if (!isUint8Array(packed)) {
throw new EncodeError("packed", `${path}: deflate hook must return a Uint8Array`);
}
packedLength = byteLengthOf(packed);
packedCost =
bytes.reduce((n, value) => n + ulebLen(BigInt(value.length)), 0) +
ulebLen(BigInt(packed.length)) +
packed.length;
ulebLen(BigInt(packedLength)) +
packedLength;
}

const grammar = ctx.profile.grammarOf(ordinal);
Expand Down Expand Up @@ -867,8 +869,8 @@ function encodeStringColumn(
}
if (mode === 0x02) {
for (const value of bytes) writeUleb(w, BigInt(value.length));
writeUleb(w, BigInt(packed!.length));
w.bytes(packed!);
writeUleb(w, BigInt(packedLength));
w.bytes(packed!, packedLength);
return;
}
if (mode === 0x03) {
Expand Down
10 changes: 6 additions & 4 deletions packages/hyperfly/src/encode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { columnarEligible, encodeColumnarArray } from "./columnar.js";
import { columnCount, type ProfileIndex } from "./profile.js";
import { EncodeError, type ErrorCode } from "./errors.js";
import { hasPayload, literalBytes, utf8Lengths, type IRNode } from "./ir.js";
import { isUint8Array } from "./typed-array.js";
import { byteLengthOf, isUint8Array } from "./typed-array.js";
import { INT_MAX, INT_MIN, writeUleb, zigzag } from "./varint.js";
import { Writer } from "./writer.js";

Expand All @@ -15,7 +15,7 @@ function fail(code: ErrorCode, path: string, message: string): never {
/** The byte length of a Uint8Array of any realm, or undefined for anything else, a Proxy included. */
function bytesLength(value: unknown): number | undefined {
try {
if (value instanceof Uint8Array || isUint8Array(value)) return value.length;
if (value instanceof Uint8Array || isUint8Array(value)) return byteLengthOf(value);
} catch {
// a proxy, or a value whose prototype cannot be read, is not bytes
}
Expand Down Expand Up @@ -184,8 +184,10 @@ export function encodeNode(
if (length === undefined) fail("type", path, "expected Uint8Array");
if (length > ctx.maxByteLength) fail("limit", path, `bytes of ${length} exceeds the codec limit`);
chargeBytes(length, ctx, path);
writeUleb(w, BigInt(length));
w.bytes(value as Uint8Array);
// Most bytes fields fit in one ULEB byte; avoid a BigInt conversion for that prefix.
if (length < 0x80) w.u8(length);
else writeUleb(w, BigInt(length));
w.bytes(value as Uint8Array, length);
return;
}
case "literal": {
Expand Down
11 changes: 10 additions & 1 deletion packages/hyperfly/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ export type ErrorCode =
| "validation"
| "options";

const createdErrors = new WeakMap<HyperflyError, ErrorCode>();

/** Base error carrying a stable failure code (wire-v0 §9). */
export class HyperflyError extends Error {
/** Machine-readable failure category; message text may vary (wire-v0 §9). */
Expand All @@ -55,12 +57,19 @@ export class HyperflyError extends Error {
super(message, options);
this.name = new.target.name;
this.code = code;
createdErrors.set(this, code);
}
}

/** `instanceof` for caught values: one whose prototype cannot be read, such as a revoked proxy, is not an instance. */
/** Match a locally created error's original code without reading properties or invoking proxy traps. */
export function hasErrorCode(value: unknown, code: ErrorCode): value is HyperflyError {
return createdErrors.get(value as HyperflyError) === code;
}

/** Only locally created Hyperfly errors may pass; uninspectable caught values are not instances. */
export function isInstance<T>(value: unknown, type: abstract new (...args: never[]) => T): value is T {
try {
if ((type.prototype === HyperflyError.prototype || type.prototype instanceof HyperflyError) && !createdErrors.has(value as HyperflyError)) return false;
return value instanceof type;
} catch {
return false;
Expand Down
4 changes: 2 additions & 2 deletions packages/hyperfly/src/profile.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { columnarEligible, flattenLeaves } from "./columnar.js";
import { HyperflyError, isInstance } from "./errors.js";
import { hasErrorCode, HyperflyError } from "./errors.js";
import { describeValue, hasLoneSurrogate, validateIR, withinStack } from "./ir.js";
import type { IRNode } from "./ir.js";

Expand Down Expand Up @@ -189,7 +189,7 @@ function snapshotProfile(profile: Profile): Profile {
}
return result;
} catch (cause) {
if (isInstance(cause, HyperflyError) && cause.code === "ir") throw cause;
if (hasErrorCode(cause, "ir")) throw cause;
throw new HyperflyError("ir", "profile: could not read JSON data", { cause });
}
}
Expand Down
10 changes: 2 additions & 8 deletions packages/hyperfly/src/train.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { columnarEligible, flattenLeaves, intColumnEncodedLength, matchGrammar } from "./columnar.js";
import { HyperflyError } from "./errors.js";
import { hasErrorCode, HyperflyError } from "./errors.js";
import { defaultPackHooks } from "./pack.js";
import { hasLoneSurrogate, validateIR, withinStack, type IRNode } from "./ir.js";
import {
Expand Down Expand Up @@ -60,13 +60,7 @@ function checkedTrainOptions(options: TrainOptions): Required<TrainOptions> {
maxEntries: Math.min(MAX_DICT_ENTRIES, maxEntries ?? MAX_DICT_ENTRIES),
};
} catch (cause) {
let isOurs = false;
try {
isOurs = cause instanceof HyperflyError && cause.code === "options";
} catch {
isOurs = false;
}
if (isOurs) throw cause;
if (hasErrorCode(cause, "options")) throw cause;
throw new HyperflyError("options", "options: could not read train options", { cause });
}
}
Expand Down
6 changes: 6 additions & 0 deletions packages/hyperfly/src/typed-array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
const TYPED_ARRAY_PROTOTYPE = Object.getPrototypeOf(Uint8Array.prototype) as object;
const typedArrayTag = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTOTYPE, Symbol.toStringTag)!.get!;
const typedArrayByteLength = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTOTYPE, "byteLength")!.get!;
const typedArraySet = Uint8Array.prototype.set;

/** Whether `value` is a Uint8Array of any realm, subclasses included. */
export function isUint8Array(value: unknown): value is Uint8Array {
Expand All @@ -12,3 +13,8 @@ export function isUint8Array(value: unknown): value is Uint8Array {
export function byteLengthOf(value: Uint8Array): number {
return typedArrayByteLength.call(value) as number;
}

/** Copy internal bytes, ignoring subclass accessors, iterators and methods in either realm. */
export function copyBytes(target: Uint8Array, source: Uint8Array, offset: number): void {
typedArraySet.call(target, source, offset);
}
12 changes: 7 additions & 5 deletions packages/hyperfly/src/writer.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { byteLengthOf, copyBytes } from "./typed-array.js";

export class Writer {
private buf: Uint8Array;
private len = 0;
Expand All @@ -17,7 +19,7 @@ export class Writer {
let next = this.buf.length * 2;
while (next < this.len + extra) next *= 2;
const grown = new Uint8Array(next);
grown.set(this.buf.subarray(0, this.len));
copyBytes(grown, this.buf.subarray(0, this.len), 0);
this.buf = grown;
this.view = new DataView(grown.buffer);
}
Expand All @@ -27,10 +29,10 @@ export class Writer {
this.buf[this.len++] = byte;
}

bytes(data: Uint8Array): void {
this.ensure(data.length);
this.buf.set(data, this.len);
this.len += data.length;
bytes(data: Uint8Array, length = byteLengthOf(data)): void {
this.ensure(length);
copyBytes(this.buf, data, this.len);
this.len += length;
}

f64le(value: number): void {
Expand Down
26 changes: 26 additions & 0 deletions packages/hyperfly/test/bytes-subclasses.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { runInNewContext } from "node:vm";

/** Hostile accessors and methods must never be consulted when measuring or copying bytes. */
export const bytesSubclasses: [string, (bytes: Uint8Array) => Uint8Array][] = [
...["length", "byteLength", "byteOffset", "buffer", "subarray", "set"].map((key): [string, (bytes: Uint8Array) => Uint8Array] => [
key,
(bytes) => {
class Hostile extends Uint8Array {}
Object.defineProperty(Hostile.prototype, key, {
get() { throw new Error(`must not read ${key}`); },
});
// Include surrounding bytes so reading the wrong offset or buffer corrupts the result.
const backing = new Uint8Array(bytes.length + 2);
backing.set(bytes, 1);
return new Hostile(backing.buffer, 1, bytes.length);
},
]),
["cross-realm subclass", runInNewContext(`(bytes) => new (class extends Uint8Array {
get length() { throw new Error("length"); }
get byteLength() { throw new Error("byteLength"); }
get byteOffset() { throw new Error("byteOffset"); }
get buffer() { throw new Error("buffer"); }
subarray() { throw new Error("subarray"); }
set() { throw new Error("set"); }
})(bytes)`) as (bytes: Uint8Array) => Uint8Array],
];
25 changes: 25 additions & 0 deletions packages/hyperfly/test/bytes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,31 @@ import { compileIR, DEFAULT_LIMITS, type Limits, type IRNode, type Profile } fro
import { toHex } from "../src/canonical.js";
import { HyperflyError } from "../src/errors.js";
import { fromHex, revive } from "./vector-values.js";
import { bytesSubclasses } from "./bytes-subclasses.js";

describe.each(["row", "columnar"] as const)("%s bytes subclasses", (plan) => {
test.each(bytesSubclasses)("ignores overridden %s", (_, make) => {
const plain = new Uint8Array([1, 2]);
const hostile = make(plain);
const shapes: [IRNode, (bytes: Uint8Array) => unknown][] = [
[{ kind: "bytes" }, (b) => b],
[{ kind: "array", element: { kind: "bytes" } }, (b) => [b, b]],
[{ kind: "array", element: { kind: "struct", fields: [{ name: "b", type: { kind: "bytes" } }] } }, (b) => [{ b }, { b }]],
[{ kind: "array", element: { kind: "struct", fields: [{ name: "b", type: { kind: "bytes" }, optional: true, nullable: true }] } }, (b) => [{}, { b: null }, { b }]],
];
for (const [ir, value] of shapes) {
const codec = compileIR(ir, { plan });
expect(codec.encodeBody(value(hostile))).toEqual(codec.encodeBody(value(plain)));
expect(codec.decode(codec.encode(value(hostile)))).toEqual(value(plain));
for (const limits of [{ maxByteLength: 1 }, { maxTotalBytes: 1 }]) {
expect(() => compileIR(ir, { plan, limits }).encodeBody(value(hostile)))
.toThrow(expect.objectContaining({ code: "limit" }));
}
}
const codec = compileIR({ kind: "bytes" }, { plan });
expect(codec.encodeBody(make(new Uint8Array()))).toEqual(new Uint8Array([0]));
});
});

interface ByteVector {
name: string;
Expand Down
87 changes: 87 additions & 0 deletions packages/hyperfly/test/caught-errors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { expect, test } from "bun:test";
import { z } from "zod";
import { CodecRegistry, compileIR, serializeArtifact, train, type IRNode } from "../src/index.js";
import { DecodeError, EncodeError, HyperflyError, isInstance, type ErrorCode } from "../src/errors.js";
import { decodeResponse, encodeFor, negotiate } from "../src/http.js";
import { compile } from "../src/zod.js";

const rows: IRNode = {
kind: "array",
element: { kind: "struct", fields: [{ name: "s", type: { kind: "string" } }] },
};

function revokingError(error: HyperflyError) {
let codeReads = 0;
const { proxy, revoke } = Proxy.revocable(error, {
get(target, key, receiver) {
if (key === "code") {
codeReads++;
revoke();
// Reading the revoked receiver would leak a native TypeError from an unsafe code check.
return Reflect.get(receiver, key);
}
return Reflect.get(target, key, receiver);
},
});
return { proxy, codeReads: () => codeReads };
}

const entries: [string, ErrorCode, (cause: HyperflyError) => unknown][] = [
["compileIR options prototype", "options", (cause) => compileIR(rows, new Proxy({}, { getPrototypeOf() { throw cause; } }))],
["compileIR limits keys", "options", (cause) => compileIR(rows, { limits: new Proxy({}, { ownKeys() { throw cause; } }) })],
["Zod compile options", "options", (cause) => compile(z.string(), new Proxy({}, { getPrototypeOf() { throw cause; } }))],
["train options prototype", "options", (cause) => train(rows, [], new Proxy({}, { getPrototypeOf() { throw cause; } }))],
["train options keys", "options", (cause) => train(rows, [], new Proxy({}, { ownKeys() { throw cause; } }))],
["compileIR profile", "ir", (cause) => compileIR(rows, {
plan: "columnar", profile: { version: 1, shared: { columns: [] }, hints: { get value() { throw cause; } } },
})],
["serializeArtifact profile", "ir", (cause) => serializeArtifact(rows, "columnar", {
shared: { get columns(): never { throw cause; } },
})],
["JSON encoding", "json", (cause) => encodeFor(negotiate(null, new CodecRegistry([compileIR(rows)])), {
toJSON() { throw cause; },
})],
["JSON decoding", "json", (cause) => decodeResponse("application/json", "[]", new CodecRegistry([{
...compileIR(rows), get ir(): never { throw cause; },
}]))],
];

test.each(entries)("%s wraps a revoking error proxy with %s", (name, code, run) => {
const ErrorClass = name === "JSON encoding" ? EncodeError : name === "JSON decoding" ? DecodeError : HyperflyError;
const hostile = revokingError(new ErrorClass(code, "hostile"));
let caught: unknown;
try { run(hostile.proxy); } catch (error) { caught = error; }
expect(caught).toBeInstanceOf(HyperflyError);
expect((caught as HyperflyError).code).toBe(code);
expect((caught as HyperflyError).cause).toBe(hostile.proxy);
expect(hostile.codeReads()).toBe(0);
});

test.each(["encode", "encodeBody", "decode", "decodeBody"] as const)("Zod %s wraps a revoking parse error", (method) => {
const hostile = revokingError(new HyperflyError("validation", "hostile"));
const schema = z.string();
const codec = compile(schema, { validate: true });
const plain = compileIR({ kind: "string" });
schema.parse = () => { throw hostile.proxy; };
let caught: unknown;
try {
if (method === "encode" || method === "encodeBody") codec[method]("value");
else codec[method](method === "decode" ? plain.encode("value") : plain.encodeBody("value"));
} catch (error) { caught = error; }
expect(caught).toBeInstanceOf(method.startsWith("encode") ? EncodeError : DecodeError);
expect((caught as HyperflyError).code).toBe("validation");
expect((caught as HyperflyError).cause).toBe(hostile.proxy);
expect(hostile.codeReads()).toBe(0);
});

test("caught Hyperfly error classification never inspects proxies or forged prototypes", () => {
for (const ErrorClass of [HyperflyError, EncodeError, DecodeError]) {
const original = new ErrorClass("json", "original");
let prototypeReads = 0;
const proxy = new Proxy(original, { getPrototypeOf() { prototypeReads++; throw new Error("must not inspect prototype"); } });
expect(isInstance(original, ErrorClass)).toBe(true);
expect(isInstance(proxy, ErrorClass)).toBe(false);
expect(isInstance(Object.create(ErrorClass.prototype), ErrorClass)).toBe(false);
expect(prototypeReads).toBe(0);
}
});
14 changes: 13 additions & 1 deletion packages/hyperfly/test/codec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -751,14 +751,26 @@ describe("struct values", () => {
expect(() => bytes.encode(make() as never)).toThrow(expect.objectContaining({ code: "type", message: "$: expected Uint8Array" }));
});

test.todo("a bytes subclass with an overridden length is measured by its real length (deferred: PR #85 Deferred)", () => {
test("a bytes subclass with an overridden length is measured by its real length", () => {
class Lying extends Uint8Array {
override get length(): number { return 0; }
}
const bytes = compileIR({ kind: "bytes" });
expect(bytes.decode(bytes.encode(new Lying([1, 2])))).toEqual(new Uint8Array([1, 2]));
});

test.each([
[127, [0x7f]], [128, [0x80, 0x01]], [16383, [0xff, 0x7f]], [16384, [0x80, 0x80, 0x01]],
] as const)("bytes subclasses preserve ULEB length boundaries at %i", (length, prefix) => {
class Lying extends Uint8Array {
override get length(): number { return 0; }
}
const codec = compileIR({ kind: "bytes" });
const encoded = codec.encodeBody(new Lying(length).fill(7));
expect(encoded.subarray(0, prefix.length)).toEqual(new Uint8Array(prefix));
expect(codec.decodeBody(encoded)).toEqual(new Uint8Array(length).fill(7));
});

test("encodes a bytes value from another realm", () => {
const foreign = runInNewContext("new Uint8Array([1, 2])") as Uint8Array;
expect(foreign instanceof Uint8Array).toBe(false);
Expand Down
Loading
Loading