From 7b6c848773086be6c79688a40a91560889a0a7b8 Mon Sep 17 00:00:00 2001 From: Ryan Yang Date: Thu, 15 Oct 2026 13:22:50 -0700 Subject: [PATCH 1/2] fix(writer): reject invalid inputs instead of silently coercing --- src/core/helpers.ts | 12 +++++ src/core/writer.ts | 34 ++++++++++++- test/unit/writer.test.ts | 100 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 143 insertions(+), 3 deletions(-) diff --git a/src/core/helpers.ts b/src/core/helpers.ts index 123488f..99496c5 100644 --- a/src/core/helpers.ts +++ b/src/core/helpers.ts @@ -56,6 +56,18 @@ export function assertNumber( } } +// Reads the internal [[TypedArrayName]] slot. Unlike `instanceof`, this works +// for typed arrays from other realms, and unlike `Object.prototype.toString`, +// an object can't fake it with its own `Symbol.toStringTag`. +const typedArrayName = Object.getOwnPropertyDescriptor( + Object.getPrototypeOf(Uint8Array.prototype), + Symbol.toStringTag +)!.get!; + +export function isUint8Array(value: unknown): value is Uint8Array { + return typedArrayName.call(value) === 'Uint8Array'; +} + export function assertUint8Array( value: unknown, path: string diff --git a/src/core/writer.ts b/src/core/writer.ts index 70c9b87..3be7c42 100644 --- a/src/core/writer.ts +++ b/src/core/writer.ts @@ -1,8 +1,16 @@ import { XdrError } from './error.js'; -import { paddingLength } from './helpers.js'; +import { + assertBigIntRange, + assertLength, + isUint8Array, + paddingLength +} from './helpers.js'; import { DEFAULT_MAX_DEPTH } from './reader.js'; const INITIAL_BUFFER_SIZE = 8192; +const INT64_MIN = -(1n << 63n); +const INT64_MAX = (1n << 63n) - 1n; +const UINT64_MAX = (1n << 64n) - 1n; /** * Low-level writer for raw XDR bytes. @@ -50,12 +58,19 @@ export class Writer { } writeBytes(bytes: Uint8Array): void { + // `bytes.length` drives the cursor, so a forged object with a negative + // length would rewind it, and a wider typed array or DataView would be + // copied by element instead of by byte. + if (!isUint8Array(bytes)) { + throw new XdrError('writeBytes: expected Uint8Array'); + } this.#ensureCapacity(bytes.length); this.#buffer.set(bytes, this.#offset); this.#offset += bytes.length; } writePadding(length: number): void { + assertLength(length, 'writePadding'); const padding = paddingLength(length); if (padding > 0) { this.#ensureCapacity(padding); @@ -64,25 +79,42 @@ export class Writer { } } + // The integer writers check their own range rather than rely on DataView, + // which silently wraps or truncates out-of-range and fractional values. + // The 32-bit checks use the bitwise round trip: it holds only for integers + // already in range, and it is cheaper than the general range helpers on + // this hot path. writeInt32(value: number): void { + if ((value | 0) !== value) { + throw new XdrError( + 'writeInt32: expected integer in range -2147483648..2147483647' + ); + } const offset = this.#prepareScalar(4); this.#view.setInt32(offset, value, false); this.#offset += 4; } writeUint32(value: number): void { + if (value >>> 0 !== value) { + throw new XdrError( + 'writeUint32: expected integer in range 0..4294967295' + ); + } const offset = this.#prepareScalar(4); this.#view.setUint32(offset, value, false); this.#offset += 4; } writeBigInt64(value: bigint): void { + assertBigIntRange(value, INT64_MIN, INT64_MAX, 'writeBigInt64'); const offset = this.#prepareScalar(8); this.#view.setBigInt64(offset, value, false); this.#offset += 8; } writeBigUint64(value: bigint): void { + assertBigIntRange(value, 0n, UINT64_MAX, 'writeBigUint64'); const offset = this.#prepareScalar(8); this.#view.setBigUint64(offset, value, false); this.#offset += 8; diff --git a/test/unit/writer.test.ts b/test/unit/writer.test.ts index 2533b3b..f2fb61f 100644 --- a/test/unit/writer.test.ts +++ b/test/unit/writer.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect } from 'vitest'; -import { Writer } from '../../src/index.js'; +import { runInNewContext } from 'node:vm'; +import { Writer, XdrError } from '../../src/index.js'; import { bytes, toArray } from './_helpers.js'; describe('Writer', () => { @@ -100,13 +101,108 @@ describe('Writer', () => { it('does not advance after a scalar write fails', () => { const writer = new Writer(); expect(() => writer.writeBigInt64(1 as unknown as bigint)).toThrow( - TypeError + XdrError ); writer.writeUint32(7); expect(toArray(writer.toUint8Array())).toEqual([0, 0, 0, 7]); }); + describe('input validation', () => { + // Each case must throw XdrError and leave the writer untouched, so a + // following valid write lands at offset 0. + function expectRejected(write: (writer: Writer) => void): void { + const writer = new Writer(); + expect(() => write(writer)).toThrow(XdrError); + expect(writer.offset).toBe(0); + writer.writeUint32(7); + expect(toArray(writer.toUint8Array())).toEqual([0, 0, 0, 7]); + } + + it('rejects out-of-range and non-integer 32-bit values', () => { + for (const value of [2 ** 31, -(2 ** 31) - 1, 1000.75, NaN, Infinity]) { + expectRejected((w) => w.writeInt32(value)); + } + for (const value of [2 ** 32, -1, 0.5, NaN, Infinity]) { + expectRejected((w) => w.writeUint32(value)); + } + expectRejected((w) => w.writeUint32('1' as unknown as number)); + }); + + it('accepts 32-bit range edges', () => { + const writer = new Writer(); + writer.writeInt32(-(2 ** 31)); + writer.writeInt32(2 ** 31 - 1); + writer.writeUint32(0); + writer.writeUint32(2 ** 32 - 1); + expect(toArray(writer.toUint8Array())).toEqual([ + 128, 0, 0, 0, 127, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255 + ]); + }); + + it('rejects out-of-range 64-bit values', () => { + expectRejected((w) => w.writeBigInt64(1n << 63n)); + expectRejected((w) => w.writeBigInt64(-(1n << 63n) - 1n)); + expectRejected((w) => w.writeBigUint64(1n << 64n)); + expectRejected((w) => w.writeBigUint64(-1n)); + expectRejected((w) => w.writeBigUint64(1 as unknown as bigint)); + }); + + it('accepts 64-bit range edges', () => { + const writer = new Writer(); + writer.writeBigInt64(-(1n << 63n)); + writer.writeBigInt64((1n << 63n) - 1n); + writer.writeBigUint64(0n); + writer.writeBigUint64((1n << 64n) - 1n); + expect(writer.offset).toBe(32); + }); + + it('rejects padding lengths that are not nonnegative integers', () => { + for (const length of [1.5, -1, NaN, Infinity]) { + expectRejected((w) => w.writePadding(length)); + } + }); + + it('rejects byte inputs that are not Uint8Arrays', () => { + const forged = [ + { length: -4 }, + { length: 4, [Symbol.toStringTag]: 'Uint8Array' }, + Object.create(Uint8Array.prototype), + new DataView(new ArrayBuffer(4)), + new Uint16Array(2), + new Int8Array(4), + new Uint8ClampedArray(4), + [1, 2, 3, 4] + ]; + for (const value of forged) { + expectRejected((w) => w.writeBytes(value as unknown as Uint8Array)); + } + }); + + it('does not let a forged length rewind the cursor', () => { + const writer = new Writer(); + writer.writeUint32(0xaaaaaaaa); + writer.writeUint32(0xbbbbbbbb); + expect(() => + writer.writeBytes({ length: -4 } as unknown as Uint8Array) + ).toThrow(XdrError); + writer.writeUint32(0xcccccccc); + expect(toArray(writer.toUint8Array())).toEqual([ + 0xaa, 0xaa, 0xaa, 0xaa, 0xbb, 0xbb, 0xbb, 0xbb, 0xcc, 0xcc, 0xcc, 0xcc + ]); + }); + + it('accepts Buffer and Uint8Arrays from another realm', () => { + const foreign = runInNewContext('new Uint8Array([1, 2, 3])'); + expect(foreign instanceof Uint8Array).toBe(false); + + const writer = new Writer(); + writer.writeBytes(foreign); + writer.writeBytes(Buffer.from([4, 5])); + expect(toArray(writer.toUint8Array())).toEqual([1, 2, 3, 4, 5]); + }); + }); + it('pads to the next 4-byte boundary based on length', () => { const cases: Array<[number, number[]]> = [ [0, []], From e0dbe4bdbbeee9e3028706ebf6462913cb31d3d1 Mon Sep 17 00:00:00 2001 From: Ryan Yang Date: Thu, 15 Oct 2026 17:02:50 -0700 Subject: [PATCH 2/2] fix(helpers): accept Uint8Array values from other realms --- src/core/helpers.ts | 2 +- test/unit/opaque.test.ts | 7 +++++++ test/unit/string.test.ts | 9 +++++++++ test/unit/struct.test.ts | 12 +++++++++++- test/unit/var-opaque.test.ts | 20 ++++++++++++++++++++ 5 files changed, 48 insertions(+), 2 deletions(-) diff --git a/src/core/helpers.ts b/src/core/helpers.ts index 99496c5..54004b5 100644 --- a/src/core/helpers.ts +++ b/src/core/helpers.ts @@ -72,7 +72,7 @@ export function assertUint8Array( value: unknown, path: string ): asserts value is Uint8Array { - if (!(value instanceof Uint8Array)) { + if (!isUint8Array(value)) { throw new XdrError(`${path}: expected Uint8Array`); } // Check if the Uint8Array is detached or out of bounds by attempting to access an element. diff --git a/test/unit/opaque.test.ts b/test/unit/opaque.test.ts index f568c13..388a757 100644 --- a/test/unit/opaque.test.ts +++ b/test/unit/opaque.test.ts @@ -1,3 +1,4 @@ +import { runInNewContext } from 'node:vm'; import { describe, it, expect } from 'vitest'; import { opaque } from '../../src/index.js'; import { bytes, toArray, encodeInvalid } from './_helpers.js'; @@ -27,6 +28,12 @@ describe('opaque (fixed-length)', () => { /expected Uint8Array/i ); }); + + it('accepts a Uint8Array from another realm', () => { + const foreign = runInNewContext('new Uint8Array([1, 2, 3, 4])'); + expect(toArray(opaque(4).encode(foreign))).toEqual([1, 2, 3, 4]); + expect(opaque(4).validate(foreign)).toBe(true); + }); }); describe('decode', () => { diff --git a/test/unit/string.test.ts b/test/unit/string.test.ts index a9e3a6f..74d9e00 100644 --- a/test/unit/string.test.ts +++ b/test/unit/string.test.ts @@ -1,3 +1,4 @@ +import { runInNewContext } from 'node:vm'; import { describe, it, expect } from 'vitest'; import { string } from '../../src/index.js'; import { bytes, toArray, roundTrip, encodeInvalid } from './_helpers.js'; @@ -32,6 +33,14 @@ describe('string', () => { expect(() => encodeInvalid(schema, 'Hi')).toThrow(/expected Uint8Array/i); expect(() => encodeInvalid(schema, 123)).toThrow(/expected Uint8Array/i); }); + + it('accepts a Uint8Array from another realm', () => { + const foreign = runInNewContext('new Uint8Array([104, 105])'); + expect(toArray(schema.encode(foreign))).toEqual([ + 0, 0, 0, 2, 104, 105, 0, 0 + ]); + expect(schema.validate(foreign)).toBe(true); + }); }); describe('decode', () => { diff --git a/test/unit/struct.test.ts b/test/unit/struct.test.ts index 091a2d3..082ce8f 100644 --- a/test/unit/struct.test.ts +++ b/test/unit/struct.test.ts @@ -1,5 +1,6 @@ +import { runInNewContext } from 'node:vm'; import { describe, it, expect } from 'vitest'; -import { struct, int32, bool } from '../../src/index.js'; +import { struct, int32, bool, varOpaque } from '../../src/index.js'; import { bytes, toArray, roundTrip, encodeInvalid } from './_helpers.js'; const Range = struct('Range', { @@ -61,6 +62,15 @@ describe('struct', () => { Range.encode({ begin: 2147483648, end: 0, inclusive: false }) ).toThrow(/range/i); }); + + it('accepts a byte field holding a Uint8Array from another realm', () => { + const Blob = struct('Blob', { data: varOpaque(10) }); + const foreign = runInNewContext('new Uint8Array([1, 2, 3])'); + expect(toArray(Blob.encode({ data: foreign }))).toEqual([ + 0, 0, 0, 3, 1, 2, 3, 0 + ]); + expect(Blob.validate({ data: foreign })).toBe(true); + }); }); describe('decode', () => { diff --git a/test/unit/var-opaque.test.ts b/test/unit/var-opaque.test.ts index 40b3645..4044cac 100644 --- a/test/unit/var-opaque.test.ts +++ b/test/unit/var-opaque.test.ts @@ -1,3 +1,4 @@ +import { runInNewContext } from 'node:vm'; import { describe, it, expect } from 'vitest'; import { varOpaque } from '../../src/index.js'; import { bytes, toArray, encodeInvalid } from './_helpers.js'; @@ -30,6 +31,25 @@ describe('varOpaque (variable-length)', () => { /expected Uint8Array/i ); }); + + it('accepts a Uint8Array from another realm', () => { + const foreign = runInNewContext('new Uint8Array([1, 2, 3])'); + expect(toArray(schema.encode(foreign))).toEqual([0, 0, 0, 3, 1, 2, 3, 0]); + expect(schema.validate(foreign)).toBe(true); + }); + + it('rejects values that only look like a Uint8Array', () => { + const spoof = { [Symbol.toStringTag]: 'Uint8Array', length: 0 }; + expect(() => encodeInvalid(schema, spoof)).toThrow( + /expected Uint8Array/i + ); + expect(() => encodeInvalid(schema, new Proxy(bytes([1]), {}))).toThrow( + /expected Uint8Array/i + ); + expect(() => + encodeInvalid(schema, runInNewContext('new Uint16Array(1)')) + ).toThrow(/expected Uint8Array/i); + }); }); describe('decode', () => {