app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

commit b77e50537ccbc01fbd35e73cdab6cd3d8c0c3cf4
parent 1e432732c75af10c9e2b516c3f8f3ff6a9dc9e54
Author: triesap <tyson@radroots.org>
Date:   Tue,  6 Oct 2026 08:52:08 +0000

web: Bound HarvestCircle generic event ingress

- Reconstruct signed fields before actual Applesauce verification
- Charge rejected and duplicate deliveries to shared logical budgets
- Stop exact limits and reentrant descriptor work without losing prior proof
- Qualify read-only descriptor admission and actual hostile relay batches

Diffstat:
Mweb/src/lib/config/budgets.ts | 8++++++++
Aweb/src/lib/nostr/ingress.ts | 208+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/src/lib/nostr/verified-envelope.ts | 6+++++-
Aweb/tests/integration/hostile-relay.test.ts | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tests/provenance/source-boundaries.test.mjs | 29+++++++++++++++++++++++++++++
Aweb/tests/unit/ingress.test.ts | 247+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mweb/tools/source-boundaries.mjs | 27++++++++++++++++++++++++++-
7 files changed, 652 insertions(+), 2 deletions(-)

diff --git a/web/src/lib/config/budgets.ts b/web/src/lib/config/budgets.ts @@ -1,3 +1,11 @@ // Browser relay scopes are independent; these are application admission caps, // not a DNS policy, native transport limit or browser memory guarantee. export const RELAY_BUDGETS = Object.freeze({ public: 3, inbox: 3 }); + +// Approved public-run admission limits shared by all primary/auxiliary sources. +// Logical post-parse work accounting; no WebSocket preallocation guarantee. +export const PUBLIC_INGRESS_BUDGETS = Object.freeze({ + deliveries: 2000, + processedBytes: 8388608, + eventBytes: 262144 +}); diff --git a/web/src/lib/nostr/ingress.ts b/web/src/lib/nostr/ingress.ts @@ -0,0 +1,208 @@ +import { PUBLIC_INGRESS_BUDGETS } from '../config/budgets.ts'; +import { boundedEnvelopeNumbers } from './envelope-bounds.ts'; +import { + boundedEnvelopeTags, + verifyEnvelope, + verifiedEnvelopeSnapshot, + type VerifiedEnvelope +} from './verified-envelope.ts'; + +declare const ingressOwner: unique symbol; +export type PublicIngress = Readonly<{ readonly [ingressOwner]: true }>; +export type IngressResult = + | Readonly<{ status: 'accepted'; value: VerifiedEnvelope }> + | Readonly<{ status: 'duplicate' | 'rejected' | 'limit' }>; +export type IngressStats = Readonly<{ + deliveries: number; + chargedBytes: number; + stopped: boolean; +}>; +interface Owner { + readonly admit: (input: unknown) => IngressResult; + readonly stats: () => IngressStats; +} +const owners = new WeakMap<PublicIngress, Owner>(); +const encoder = new TextEncoder(); + +// Read only own data properties. SDK cache symbols, getters, inherited fields, +// toJSON and iterator overrides cannot cross into a verified snapshot. +function ownData( + input: object, + name: string, + assertActive: () => void +): unknown { + assertActive(); + const descriptor = Object.getOwnPropertyDescriptor(input, name); + assertActive(); + if (!descriptor || !('value' in descriptor)) + throw new Error('candidate_invalid'); + return descriptor.value; +} +function freshTags( + input: unknown, + assertActive: () => void +): string[][] | undefined { + if (!Array.isArray(input)) return undefined; + const length = ownData(input, 'length', assertActive); + if ( + typeof length !== 'number' || + !Number.isSafeInteger(length) || + length < 0 || + length > 1024 + ) + return undefined; + let elements = 0; + const tags = Array.from({ length }, (_, index) => { + const row = ownData(input, String(index), assertActive); + if (!Array.isArray(row)) throw new Error('candidate_invalid'); + const width = ownData(row, 'length', assertActive); + if (typeof width !== 'number' || !Number.isSafeInteger(width) || width < 1) + throw new Error('candidate_invalid'); + elements += width; + if (elements > 4096) throw new Error('candidate_invalid'); + return Array.from({ length: width }, (_, column) => { + const element = ownData(row, String(column), assertActive); + if (typeof element !== 'string' || element.length > 4096) + throw new Error('candidate_invalid'); + return element; + }); + }); + return boundedEnvelopeTags(tags) ? tags : undefined; +} +function reconstructedWire( + input: unknown, + assertActive: () => void +): string | undefined { + try { + assertActive(); + if (!input || typeof input !== 'object' || Array.isArray(input)) + return undefined; + const id = ownData(input, 'id', assertActive); + const pubkey = ownData(input, 'pubkey', assertActive); + const sig = ownData(input, 'sig', assertActive); + const kind = ownData(input, 'kind', assertActive); + const createdAt = ownData(input, 'created_at', assertActive); + const content = ownData(input, 'content', assertActive); + if ( + typeof id !== 'string' || + !/^[0-9a-f]{64}$/u.test(id) || + typeof pubkey !== 'string' || + !/^[0-9a-f]{64}$/u.test(pubkey) || + typeof sig !== 'string' || + !/^[0-9a-f]{128}$/u.test(sig) || + !boundedEnvelopeNumbers(kind, createdAt) || + typeof content !== 'string' || + content.length > 131072 + ) + return undefined; + const tags = freshTags(ownData(input, 'tags', assertActive), assertActive); + if (!tags) return undefined; + return JSON.stringify({ + id, + pubkey, + sig, + kind, + created_at: createdAt, + tags, + content + }); + } catch { + return undefined; + } +} + +// One owner is shared by a public run's primary and auxiliary candidates. +// These are post-parse logical application bounds. The selected SDK exposes +// parsed events, not a qualified raw-frame hook or preallocation guarantee. +export function createPublicIngress(): PublicIngress { + const token = Object.freeze({}) as PublicIngress; + const seen = new Map<string, true>(); + let deliveries = 0; + let chargedBytes = 0; + let stopped = false; + let busy = false; + const assertActive = () => { + if (stopped) throw new Error('candidate_invalid'); + }; + const charge = (bytes: number): boolean => { + if (bytes > PUBLIC_INGRESS_BUDGETS.processedBytes - chargedBytes) { + chargedBytes = PUBLIC_INGRESS_BUDGETS.processedBytes; + stopped = true; + return false; + } + chargedBytes += bytes; + if (chargedBytes === PUBLIC_INGRESS_BUDGETS.processedBytes) stopped = true; + return true; + }; + owners.set(token, { + stats: () => + Object.freeze({ + deliveries: deliveries, + chargedBytes: chargedBytes, + stopped: stopped + }), + admit(input) { + if (stopped || deliveries >= PUBLIC_INGRESS_BUDGETS.deliveries) { + stopped = true; + return { status: 'limit' }; + } + deliveries++; + // Reserve entry before descriptor traps can reenter this owner. Refuse + // nested admission without reflecting again; retain bounded charges. + if (busy) { + charge(PUBLIC_INGRESS_BUDGETS.eventBytes + 1); + stopped = true; + return { status: 'limit' }; + } + busy = true; + try { + const rawAvailable = typeof input === 'string'; + const wire = rawAvailable + ? input + : reconstructedWire(input, assertActive); + if (stopped) { + charge(PUBLIC_INGRESS_BUDGETS.eventBytes + 1); + return { status: 'limit' }; + } + // Oversized raw input and unmeasurable rejected objects reserve the + // event ceiling plus one. Decoded fields charge actual reconstructed + // UTF8 JSON including expansion; original SDK frame bytes are unknown. + const bytes = + wire === undefined || + (rawAvailable && wire.length > PUBLIC_INGRESS_BUDGETS.eventBytes) + ? PUBLIC_INGRESS_BUDGETS.eventBytes + 1 + : encoder.encode(wire).length; + if (!charge(bytes)) return { status: 'limit' }; + if (deliveries === PUBLIC_INGRESS_BUDGETS.deliveries) stopped = true; + // The inclusive last reserved candidate may finish. Subsequent entry + // is already blocked by either cap; reentrant interruption aborts above. + if (wire === undefined || bytes > PUBLIC_INGRESS_BUDGETS.eventBytes) + return { status: 'rejected' }; + const result = verifyEnvelope(wire); + if (!result.ok) return { status: 'rejected' }; + const event = verifiedEnvelopeSnapshot(result.value); + if (!event) return { status: 'rejected' }; + if (seen.has(event.id)) return { status: 'duplicate' }; + seen.set(event.id, true); + return { status: 'accepted', value: result.value }; + } finally { + busy = false; + } + } + }); + return token; +} +function ownerOf(token: PublicIngress): Owner { + const owner = owners.get(token); + if (!owner) throw new Error('public_ingress_invalid'); + return owner; +} +export function admitPublicEvent( + token: PublicIngress, + input: unknown +): IngressResult { + return ownerOf(token).admit(input); +} +export function publicIngressStats(token: PublicIngress): IngressStats { + return ownerOf(token).stats(); +} diff --git a/web/src/lib/nostr/verified-envelope.ts b/web/src/lib/nostr/verified-envelope.ts @@ -3,6 +3,7 @@ import { verifyEvent, type NostrEvent } from 'applesauce-core/helpers'; +import { PUBLIC_INGRESS_BUDGETS } from '../config/budgets.ts'; import { boundedEnvelopeNumbers } from './envelope-bounds.ts'; import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; @@ -49,7 +50,10 @@ export function verifyEnvelope( ): | Readonly<{ ok: true; value: VerifiedEnvelope }> | Readonly<{ ok: false; error: EnvelopeFailure }> { - if (typeof raw !== 'string' || !boundedUtf8(raw, 262144)) + if ( + typeof raw !== 'string' || + !boundedUtf8(raw, PUBLIC_INGRESS_BUDGETS.eventBytes) + ) return { ok: false, error: invalid }; try { // Parse a fresh bounded JSON object: caller getters and cached SDK symbols diff --git a/web/tests/integration/hostile-relay.test.ts b/web/tests/integration/hostile-relay.test.ts @@ -0,0 +1,129 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { once } from 'node:events'; +import { readFile } from 'node:fs/promises'; +import WebSocket, { WebSocketServer } from 'ws'; +import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; +import { + getPublicPool, + subscribePublicPool, + closePublicPool +} from '../../src/lib/nostr/public-pool.ts'; +import { + createPublicIngress, + admitPublicEvent, + publicIngressStats +} from '../../src/lib/nostr/ingress.ts'; + +// HC_TEST_ONLY_RELAY: actual SDK sockets map only to an isolated loopback server. +await test('actual relay batch isolates hostile candidates before trusted projection', async () => { + const corpus = JSON.parse( + await readFile( + new URL( + '../../../contracts/interop/food_availability/corpus.v1.json', + import.meta.url + ), + 'utf8' + ) + ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; + const raw = corpus.vectors.find((row) => row.id.endsWith('_014'))! + .signed_wires.event; + const valid = JSON.parse(raw) as Record<string, unknown>; + const candidates = [ + { ...valid, sig: '0'.repeat(128) }, + { ...valid, content: 'untrusted mutation' }, + { ...valid, created_at: Number.MAX_SAFE_INTEGER + 1 }, + valid, + valid, + { ...valid, tags: [['d', 'a'], {}] } + ]; + const server = new WebSocketServer({ + host: '127.0.0.1', + port: 0, + maxPayload: 4096 + }); + server.on('connection', (socket) => + socket.on('message', (bytes) => { + const buffer = Array.isArray(bytes) + ? Buffer.concat(bytes) + : Buffer.isBuffer(bytes) + ? bytes + : Buffer.from(bytes); + const frame: unknown = JSON.parse(buffer.toString('utf8')); + assert.ok(Array.isArray(frame)); + if (frame[0] !== 'REQ') return; + for (const event of candidates) + socket.send(JSON.stringify(['EVENT', frame[1], event])); + socket.send(JSON.stringify(['EOSE', frame[1]])); + }) + ); + await once(server, 'listening'); + const address = server.address(); + assert.ok(address && typeof address !== 'string'); + const port = address.port; + const originalSocket = globalThis.WebSocket; + assert.equal( + Object.getOwnPropertyDescriptor(globalThis, 'window'), + undefined + ); + class FixtureSocket extends WebSocket { + constructor(url: string | URL) { + assert.equal(String(url).replace(/\/$/, ''), 'wss://hostile.example.org'); + super(`ws://127.0.0.1:${port}`); + } + } + Object.defineProperty(globalThis, 'window', { + configurable: true, + value: {} + }); + globalThis.WebSocket = + FixtureSocket as unknown as typeof globalThis.WebSocket; + const policy = validateRelayPolicy( + JSON.stringify({ + schemaVersion: 1, + public: [ + { + origin: 'wss://hostile.example.org', + read: true, + write: false, + nip50: false + } + ], + inbox: [], + postingEnabled: false, + messagingEnabled: false, + operatorDenylist: [] + }) + ); + assert.ok(policy); + const pool = getPublicPool(policy)!; + const owner = createPublicIngress(); + const outcomes: string[] = []; + try { + await new Promise<void>((resolve) => + subscribePublicPool(pool, [{ kinds: [30402], limit: 200 }], (message) => { + if (message.type === 'EVENT') + outcomes.push(admitPublicEvent(owner, message.event).status); + if (message.type === 'EOSE') resolve(); + }) + ); + assert.deepEqual(outcomes, [ + 'rejected', + 'rejected', + 'rejected', + 'accepted', + 'duplicate', + 'rejected' + ]); + assert.equal(publicIngressStats(owner).deliveries, 6); + assert.ok(publicIngressStats(owner).chargedBytes > 0); + assert.equal(publicIngressStats(owner).stopped, false); + } finally { + closePublicPool(pool); + await new Promise<void>((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())) + ); + globalThis.WebSocket = originalSocket; + Reflect.deleteProperty(globalThis, 'window'); + } +}); diff --git a/web/tests/provenance/source-boundaries.test.mjs b/web/tests/provenance/source-boundaries.test.mjs @@ -1854,3 +1854,32 @@ for (const [name, specifier] of [ } ); } + +test('HCP029 admits direct read-only descriptor inspection of unknown data', async () => { + await fixture(async ({ put, execute }) => { + await put( + 'src/routes/+page.ts', + 'export function read(value: object, key: string) { const descriptor = Object.getOwnPropertyDescriptor(value, key); return descriptor && "value" in descriptor ? descriptor.value : undefined; }' + ); + const result = execute(); + assert.equal(result.status, 0, result.stderr); + }); +}); +for (const source of [ + 'const read = Object.getOwnPropertyDescriptor; export function inspect(value: object) { return read(value, "content"); }', + 'export function inspect(value: object) { return Object["getOwnPropertyDescriptor"](value, "content"); }', + 'export function inspect(value: object) { return Object.getOwnPropertyDescriptor.call(Object, value, "content"); }', + 'export function inspect(value: object, Object: { getOwnPropertyDescriptor: (value: object, key: string) => unknown }) { return Object.getOwnPropertyDescriptor(value, "content"); }', + 'declare const fake: typeof Object; Object = fake; export function inspect(value: object) { return Object.getOwnPropertyDescriptor(value, "content"); }', + 'export function inspect(value: object) { return Reflect.getOwnPropertyDescriptor(value, "content"); }', + 'export function inspect(value: object) { return Object.getOwnPropertyDescriptors(value); }', + 'export function inspect(value: object) { return Object.defineProperty(value, "content", { value: "untrusted" }); }', + 'export function inspect(value: object) { const descriptor = Object.getOwnPropertyDescriptor(value, "content"); if (descriptor) descriptor.value = "untrusted"; }', + 'export function inspect() { return Object.getOwnPropertyDescriptor(); }' +]) + test(`HCP029 descriptor admission rejects escaped, shadowed or mutating operation: ${source}`, async () => { + await fixture(async ({ put, execute }) => { + await put('src/routes/+page.ts', source); + reject(execute(), /descriptor|reflection|mutation|owned/); + }); + }); diff --git a/web/tests/unit/ingress.test.ts b/web/tests/unit/ingress.test.ts @@ -0,0 +1,247 @@ +import { describe, expect, it } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { verifiedSymbol, verifyEvent } from 'applesauce-core/helpers'; +import { PUBLIC_INGRESS_BUDGETS } from '../../src/lib/config/budgets.ts'; +import { + createPublicIngress, + admitPublicEvent, + publicIngressStats, + type PublicIngress +} from '../../src/lib/nostr/ingress.ts'; +import { verifiedEnvelopeSnapshot } from '../../src/lib/nostr/verified-envelope.ts'; +const corpus = JSON.parse( + readFileSync( + new URL( + '../../../contracts/interop/food_availability/corpus.v1.json', + import.meta.url + ), + 'utf8' + ) +) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; +const wire = corpus.vectors.find((row) => row.id.endsWith('_014'))!.signed_wires + .event; +const candidate = () => JSON.parse(wire) as Record<string | symbol, unknown>; + +describe('bounded generic public ingress', () => { + it('isolates a bad signature and admits the following valid candidate', () => { + const owner = createPublicIngress(); + expect( + admitPublicEvent(owner, { ...candidate(), sig: '0'.repeat(128) }).status + ).toBe('rejected'); + const good = admitPublicEvent(owner, wire); + expect(good.status).toBe('accepted'); + if (good.status === 'accepted') + expect(verifiedEnvelopeSnapshot(good.value)).toEqual(JSON.parse(wire)); + expect(publicIngressStats(owner).deliveries).toBe(2); + }); + it('rejects a mutated object even when actual SDK verification trusts its cached symbol', () => { + const cached = candidate(); + expect(verifyEvent(cached as Parameters<typeof verifyEvent>[0])).toBe(true); + expect(cached[verifiedSymbol]).toBe(true); + cached.content = 'mutation after verification'; + expect(verifyEvent(cached as Parameters<typeof verifyEvent>[0])).toBe(true); + expect(admitPublicEvent(createPublicIngress(), cached).status).toBe( + 'rejected' + ); + }); + it('reconstructs signed data without cache symbols or caller mutation crossing retained proof', () => { + const input = candidate(); + input[verifiedSymbol] = true; + input[Symbol.for('seen-relays')] = new Set(['wss://untrusted.example.org']); + const result = admitPublicEvent(createPublicIngress(), input); + expect(result.status).toBe('accepted'); + if (result.status !== 'accepted') return; + input.content = 'later mutation'; + const snapshot = verifiedEnvelopeSnapshot(result.value)!; + expect(snapshot).toEqual(JSON.parse(wire)); + expect(Object.getOwnPropertySymbols(snapshot)).toEqual([]); + snapshot.content = 'changed detached snapshot'; + expect(verifiedEnvelopeSnapshot(result.value)).toEqual(JSON.parse(wire)); + }); + it.each([NaN, Infinity, -Infinity, -0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1])( + 'rejects unsupported decoded timestamp %s', + (created_at) => { + expect( + admitPublicEvent(createPublicIngress(), { ...candidate(), created_at }) + .status + ).toBe('rejected'); + } + ); + it('retains numeric lexical checks when actual raw JSON is available', () => { + const altered = wire.replace( + /"created_at":\s*[0-9]+/u, + '"created_at":1700000060.0' + ); + expect(altered).not.toBe(wire); + expect(admitPublicEvent(createPublicIngress(), altered).status).toBe( + 'rejected' + ); + }); + it('never calls own field getters, toJSON or untrusted tag iterators', () => { + let calls = 0; + const input = candidate(); + Object.defineProperty(input, 'content', { + get() { + calls++; + return 'untrusted'; + } + }); + expect(admitPublicEvent(createPublicIngress(), input).status).toBe( + 'rejected' + ); + const safe = candidate(); + safe.toJSON = () => { + calls++; + throw new Error('untrusted'); + }; + const tags = safe.tags as string[][]; + Object.defineProperty(tags, Symbol.iterator, { + value() { + calls++; + throw new Error('untrusted'); + } + }); + expect(admitPublicEvent(createPublicIngress(), safe).status).toBe( + 'accepted' + ); + expect(calls).toBe(0); + }); + it('charges repeated valid candidates before deduplication', () => { + const owner = createPublicIngress(); + expect(admitPublicEvent(owner, wire).status).toBe('accepted'); + expect(admitPublicEvent(owner, wire).status).toBe('duplicate'); + expect(publicIngressStats(owner)).toEqual({ + deliveries: 2, + chargedBytes: new TextEncoder().encode(wire).length * 2, + stopped: false + }); + }); + it('stops a rejected-input storm at the inclusive delivery limit', () => { + const owner = createPublicIngress(); + for (let index = 0; index < PUBLIC_INGRESS_BUDGETS.deliveries; index++) + expect(admitPublicEvent(owner, 'null').status).toBe('rejected'); + const before = publicIngressStats(owner); + expect(before).toEqual({ + deliveries: 2000, + chargedBytes: 8000, + stopped: true + }); + expect(admitPublicEvent(owner, wire).status).toBe('limit'); + expect(publicIngressStats(owner)).toEqual(before); + }); + it('stops an oversized stream at the aggregate byte cap without admitting its payload', () => { + const owner = createPublicIngress(); + const oversized = ' '.repeat(PUBLIC_INGRESS_BUDGETS.eventBytes + 1); + for (let index = 0; index < 32; index++) { + const outcome = admitPublicEvent(owner, oversized); + expect(outcome.status).toBe(index === 31 ? 'limit' : 'rejected'); + } + expect(publicIngressStats(owner)).toEqual({ + deliveries: 32, + chargedBytes: 8388608, + stopped: true + }); + expect(admitPublicEvent(owner, wire).status).toBe('limit'); + }); + it('counts UTF8 expansion and malformed input against one shared owner', () => { + const owner = createPublicIngress(); + const rejected = JSON.stringify({ + ...candidate(), + content: 'é'.repeat(1000) + }); + expect(admitPublicEvent(owner, rejected).status).toBe('rejected'); + expect(publicIngressStats(owner).chargedBytes).toBe( + new TextEncoder().encode(rejected).length + ); + expect(admitPublicEvent(owner, wire).status).toBe('accepted'); + expect(publicIngressStats(owner).deliveries).toBe(2); + }); + it('refuses forged owners and provides detached immutable accounting', () => { + expect(() => admitPublicEvent({} as PublicIngress, wire)).toThrow( + 'public_ingress_invalid' + ); + const owner = createPublicIngress(); + const before = publicIngressStats(owner); + expect(Reflect.set(before, 'deliveries', 99)).toBe(false); + admitPublicEvent(owner, 'null'); + expect(before.deliveries).toBe(0); + expect(publicIngressStats(owner).deliveries).toBe(1); + }); + it('stops at exact aggregate byte equality before inspecting another candidate', () => { + const owner = createPublicIngress(); + const raw = ' '.repeat(PUBLIC_INGRESS_BUDGETS.eventBytes); + for (let index = 0; index < 32; index++) + expect(admitPublicEvent(owner, raw).status).toBe('rejected'); + const before = publicIngressStats(owner); + expect(before).toEqual({ + deliveries: 32, + chargedBytes: 8388608, + stopped: true + }); + let inspected = 0; + const next = new Proxy(candidate(), { + getOwnPropertyDescriptor(target, key) { + inspected++; + return Reflect.getOwnPropertyDescriptor(target, key); + } + }); + expect(admitPublicEvent(owner, next).status).toBe('limit'); + expect(inspected).toBe(0); + expect(publicIngressStats(owner)).toEqual(before); + }); + it('charges and stops reentrant descriptor admission before nested reconstruction', () => { + const owner = createPublicIngress(); + let entered = false; + let descriptors = 0; + let nested: ReturnType<typeof admitPublicEvent> | undefined; + const input = new Proxy(candidate(), { + getOwnPropertyDescriptor(target, key) { + descriptors++; + if (!entered) { + entered = true; + nested = admitPublicEvent(owner, 'null'); + } + return Reflect.getOwnPropertyDescriptor(target, key); + } + }); + const outer = admitPublicEvent(owner, input); + expect(nested?.status).toBe('limit'); + expect(outer.status).toBe('limit'); + expect(descriptors).toBe(1); + const before = publicIngressStats(owner); + expect(before.deliveries).toBe(2); + expect(before.chargedBytes).toBeGreaterThan(0); + expect(before.chargedBytes).toBeLessThanOrEqual(8388608); + expect(before.stopped).toBe(true); + expect(admitPublicEvent(owner, wire).status).toBe('limit'); + expect(publicIngressStats(owner)).toEqual(before); + }); + + it('allows the inclusive final valid event and then stops at exact bytes', () => { + const owner = createPublicIngress(); + const raw = ' '.repeat(PUBLIC_INGRESS_BUDGETS.eventBytes); + for (let index = 0; index < 31; index++) + expect(admitPublicEvent(owner, raw).status).toBe('rejected'); + const final = + wire + + ' '.repeat( + PUBLIC_INGRESS_BUDGETS.eventBytes - + new TextEncoder().encode(wire).length + ); + expect(admitPublicEvent(owner, final).status).toBe('accepted'); + expect(publicIngressStats(owner)).toEqual({ + deliveries: 32, + chargedBytes: 8388608, + stopped: true + }); + }); + + it('isolates revoked object reflection and preserves the next valid candidate', () => { + const owner = createPublicIngress(); + const revoked = Proxy.revocable(candidate(), {}); + revoked.revoke(); + expect(admitPublicEvent(owner, revoked.proxy).status).toBe('rejected'); + expect(admitPublicEvent(owner, wire).status).toBe('accepted'); + expect(publicIngressStats(owner).deliveries).toBe(2); + }); +}); diff --git a/web/tools/source-boundaries.mjs b/web/tools/source-boundaries.mjs @@ -610,6 +610,21 @@ function mutationAdmission(ast, report, identity = () => null) { !!strings(node.arguments[1]) ); } + // HCP029: single-property descriptor reads do not mutate their receiver. + // Admit only the actual builtin's direct call; never an escaped/shadowed + // reader or a descriptor write. Other reflection keeps owned-data rules. + function descriptorRead(node) { + return ( + ts.isPropertyAccessExpression(node) && + node.name.text === 'getOwnPropertyDescriptor' && + global(node.expression, ['Object']) && + !globalWrites.has('Object') && + ts.isCallExpression(node.parent) && + node.parent.expression === node && + node.parent.arguments.length === 2 && + pure(node.parent.arguments[1]) + ); + } function primitiveMethod(node) { const call = node.parent; if ( @@ -801,6 +816,15 @@ function mutationAdmission(ast, report, identity = () => null) { !navigatorLeaf(node) ) report('opaque navigator capabilities cannot expose worker loaders'); + if ( + name === 'getOwnPropertyDescriptor' && + ts.isIdentifier(node.expression) && + node.expression.text === 'Object' && + !descriptorRead(node) + ) + report( + 'descriptor inspection requires a direct unshadowed builtin read' + ); if (['constructor', 'prototype', '__proto__'].includes(name)) report( 'prototype capability access is outside the admitted DOM/model grammar' @@ -969,7 +993,8 @@ function mutationAdmission(ast, report, identity = () => null) { parent.expression !== node || !ts.isCallExpression(parent.parent) || parent.parent.expression !== parent || - !parent.parent.arguments.every((argument) => pure(argument)) + (!descriptorRead(parent) && + !parent.parent.arguments.every((argument) => pure(argument))) ) report( 'reflection/bulk operations require direct calls over owned plain data'