From 9daecdbae6148dfe29146e219b4df7f30c465b4c Mon Sep 17 00:00:00 2001 From: Chayapat Sriwattanachote Date: Thu, 5 Nov 2026 19:43:14 +0700 Subject: [PATCH 01/10] fix(s16): keep armed browser dispatch reconcile-only without wedging recovery Browser reconcile without a read-only verifier returned unknown but left the durable recovery lane active, blocking later verified read-back. Return unknown with finished read settlement instead of throwing before any read, so missing verifiers stay unknown without preventing a later verifier. Invalid payloads follow the same unknown path. Add deterministic coverage: armed dispatch reconciles only through read-only service verification without resend, owner statements do not clear continuity, continuity file stores only action references, and redirect/download refuse without following or arming recovery. --- src/s15/browser/gateway.ts | 7 +++-- tests/s15-browser.test.ts | 62 +++++++++++++++++++++++++++++++++++++- 2 files changed, 65 insertions(+), 4 deletions(-) diff --git a/src/s15/browser/gateway.ts b/src/s15/browser/gateway.ts index 8104bbe8..7a3f9e10 100644 --- a/src/s15/browser/gateway.ts +++ b/src/s15/browser/gateway.ts @@ -231,11 +231,12 @@ export async function registerProtectedBrowser(options: BrowserOptions, factory: } finally { route.close(); } }, async reconcile(action, context) { - if (!options.site.reconcileEffect) throw new BrowserError('reconciliation_unsupported'); + if (!options.site.reconcileEffect) return { outcome: 'unknown', actual: unknownUsage(), transportSettled: false }; const payload = action.payload as Record; - if (payload.contract !== 's15-browser-request/v1') throw new BrowserError('effect_semantics_unknown'); + if (payload.contract !== 's15-browser-request/v1') return { outcome: 'unknown', actual: unknownUsage(), transportSettled: false }; const { contract: _, ...request } = payload; - validateRequest(request as unknown as BrowserRequest); + try { validateRequest(request as unknown as BrowserRequest); } + catch { return { outcome: 'unknown', actual: unknownUsage(), transportSettled: false }; } return options.site.reconcileEffect(Object.freeze(request as unknown as BrowserRequest), context); }, }, diff --git a/tests/s15-browser.test.ts b/tests/s15-browser.test.ts index c7eef9a1..dffed909 100644 --- a/tests/s15-browser.test.ts +++ b/tests/s15-browser.test.ts @@ -6,6 +6,7 @@ import type { BrokerResponse } from '../src/s15/browser'; import type { BrowserEngine, EngineOptions, EngineInputContext } from '../src/s15/browser/engine'; import { denyProxy } from '../src/s15/browser/engine'; import { operation, validateRequest } from '../src/s15/browser/validation'; +import { unknownUsage } from '../src/s15/policy/validation'; import { protectedBrowserTools } from '../src/s15/browser/tools'; import { browserFixture, browserSite } from './fixtures/s15-browser'; @@ -127,9 +128,20 @@ test('current browser continuity survives process loss and never turns an armed const { mkdtempSync, rmSync } = await import('node:fs'); const { tmpdir } = await import('node:os'); const { join } = await import('node:path'); const dir = mkdtempSync(join(tmpdir(), 'jit-browser-continuity-')); cleanup.push(() => rmSync(dir, { recursive: true, force: true })); const path = join(dir, 'current.sqlite'), a = { id: 'armed', revision: 1, actionHash: 'a'.repeat(64) }; + const secretPayload = 'recipient=team&message=Exact+secret-payload-must-not-persist'; const first = browserContinuity(path, true, 'profile_resource'), previous = first.advance(); first.arm(a); first.close(); const recovered = browserContinuity(path, false, 'profile_resource'); - try { expect(recovered.advance()).toBeGreaterThan(previous); expect(recovered.uncertain()).toEqual(a); expect(() => recovered.arm(a)).toThrow('reconciliation_required'); } + try { + expect(recovered.advance()).toBeGreaterThan(previous); expect(recovered.uncertain()).toEqual(a); expect(() => recovered.arm(a)).toThrow('reconciliation_required'); + // The durable file names only the armed action reference: no request bytes, cookies or payloads survive a crash. + const bytes = readFileSync(path); + expect(bytes.includes(Buffer.from(secretPayload))).toBe(false); + expect(bytes.includes(Buffer.from('jit_session'))).toBe(false); + expect(JSON.stringify(recovered.uncertain())).not.toContain('message'); + // Settling requires the exact armed reference; a different revision cannot clear the uncertainty. + expect(() => recovered.settle({ id: 'armed', revision: 2, actionHash: 'a'.repeat(64) })).toThrow('continuity_unavailable'); + recovered.settle(a); expect(recovered.uncertain()).toBeNull(); + } finally { recovered.close(); } expect(() => browserContinuity(path, true, 'profile_resource')).toThrow('continuity_unavailable'); expect(() => browserContinuity(path, false, 'other_resource')).toThrow('continuity_unavailable'); @@ -146,6 +158,42 @@ test('an observed HTTP response without verified business outcome stays unknown expect(f.server.received.filter(r => r.path === '/message')).toHaveLength(1); }); +test('an armed browser dispatch reconciles only through a read-only service verifier and never resends', async () => { + const f = await setup(), original = f.server.site.classify; + f.server.site.classify = (request, mode) => { const meaning = original(request, mode); if (meaning?.kind !== 'effect') return meaning; const { verifyResponse: _, ...unverified } = meaning; return unverified; }; + const body = 'recipient=team&message=Reconcile+exactly+once'; + f.engine.next = post(f.server.origin + '/message', body); + const held = await f.execute({ kind: 'click', target: 'e1_1' }); if (held.state !== 'held') throw Error('expected_hold'); + f.approve(held.action); expect(await f.work.resume(held.action)).toMatchObject({ state: 'unknown', code: 'reconciliation_required' }); + expect(f.server.received.filter(r => r.path === '/message')).toHaveLength(1); + const sentBefore = f.engine.sent; + // Without a read-only verifier the unknown outcome cannot be resolved: no retry, no new dispatch. + expect(await f.gateway.owner.reconcile(f.owner, held.action, 'browser_reconcile_missing')).toMatchObject({ outcome: 'unknown' }); + expect(f.work.state().reconciliation).toEqual(held.action); + expect(f.server.received.filter(r => r.path === '/message')).toHaveLength(1); + // An owner statement records what the owner believes, but it cannot clear the protected browser uncertainty. + f.service.owner.recordStatement(f.owner, held.action, 'browser_statement_1', 'occurred'); + expect(f.work.state().reconciliation).toEqual(held.action); + expect(f.server.received.filter(r => r.path === '/message')).toHaveLength(1); + // A read-only verifier inspects already-received service state; it never resubmits the effect. + f.server.site.reconcileEffect = async (request, context) => { + context.beforeRead(); + expect(request.url).toBe(f.server.origin + '/message'); + expect(Buffer.from(request.bodyBase64, 'base64').toString()).toBe(body); + expect(f.server.received.filter(r => r.path === '/message')).toHaveLength(1); + expect(f.engine.sent).toBe(sentBefore); + return { outcome: 'succeeded', actual: unknownUsage(), transportSettled: true }; + }; + expect(await f.gateway.owner.reconcile(f.owner, held.action, 'browser_reconcile_verified')).toMatchObject({ outcome: 'succeeded' }); + expect(f.work.state().reconciliation).toBeNull(); + expect(f.server.received.filter(r => r.path === '/message')).toHaveLength(1); + expect(f.engine.sent).toBe(sentBefore); + // After verified recovery the browser accepts fresh work, and the old action cannot dispatch again. + expect((await f.execute({ kind: 'read' })).state).toBe('observed'); + expect((await f.work.resume(held.action)).state).toBe('unsupported'); + expect(f.server.received.filter(r => r.path === '/message')).toHaveLength(1); +}); + test('a settled host lease can pass to another work actor while every old closure remains fenced', async () => { const f = await setup(); f.work.release(); const actor = f.admit().actor!, next = f.gateway.open(actor); @@ -161,6 +209,18 @@ test('an automatic document submission cannot borrow a navigation input even whe expect(f.server.received.some(r => r.path === '/edit')).toBe(false); }); +test('redirect and download responses refuse without following, delivering or arming recovery', async () => { + const f = await setup(); + expect(await f.execute({ kind: 'navigate', url: f.server.origin + '/redirect' })).toMatchObject({ state: 'unsupported', code: 'redirect_unsupported' }); + expect(f.server.received.some(r => r.path === '/redirect')).toBe(true); + expect(f.server.received.some(r => r.path.startsWith('/unknown-effect'))).toBe(false); + expect(f.work.state().reconciliation).toBeNull(); + expect(await f.execute({ kind: 'navigate', url: f.server.origin + '/download' })).toMatchObject({ state: 'unsupported', code: 'download_unsupported' }); + expect(f.server.received.some(r => r.path === '/download')).toBe(false); + expect(f.work.state().reconciliation).toBeNull(); + expect((await f.execute({ kind: 'read' })).state).toBe('observed'); +}); + test('reopening with the same durable actor does not resurrect a released closure or its release', async () => { const f = await setup(); f.work.release(); const next = f.gateway.open(f.actor); From e7c6699ace7e271e5d3dc8ac711f3c1b24045749 Mon Sep 17 00:00:00 2001 From: Chayapat Sriwattanachote Date: Thu, 5 Nov 2026 19:45:37 +0700 Subject: [PATCH 02/10] test(browser): limit evidence claims to exercised paths --- tests/s15-browser.test.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/tests/s15-browser.test.ts b/tests/s15-browser.test.ts index dffed909..d4015d02 100644 --- a/tests/s15-browser.test.ts +++ b/tests/s15-browser.test.ts @@ -128,16 +128,10 @@ test('current browser continuity survives process loss and never turns an armed const { mkdtempSync, rmSync } = await import('node:fs'); const { tmpdir } = await import('node:os'); const { join } = await import('node:path'); const dir = mkdtempSync(join(tmpdir(), 'jit-browser-continuity-')); cleanup.push(() => rmSync(dir, { recursive: true, force: true })); const path = join(dir, 'current.sqlite'), a = { id: 'armed', revision: 1, actionHash: 'a'.repeat(64) }; - const secretPayload = 'recipient=team&message=Exact+secret-payload-must-not-persist'; const first = browserContinuity(path, true, 'profile_resource'), previous = first.advance(); first.arm(a); first.close(); const recovered = browserContinuity(path, false, 'profile_resource'); try { expect(recovered.advance()).toBeGreaterThan(previous); expect(recovered.uncertain()).toEqual(a); expect(() => recovered.arm(a)).toThrow('reconciliation_required'); - // The durable file names only the armed action reference: no request bytes, cookies or payloads survive a crash. - const bytes = readFileSync(path); - expect(bytes.includes(Buffer.from(secretPayload))).toBe(false); - expect(bytes.includes(Buffer.from('jit_session'))).toBe(false); - expect(JSON.stringify(recovered.uncertain())).not.toContain('message'); // Settling requires the exact armed reference; a different revision cannot clear the uncertainty. expect(() => recovered.settle({ id: 'armed', revision: 2, actionHash: 'a'.repeat(64) })).toThrow('continuity_unavailable'); recovered.settle(a); expect(recovered.uncertain()).toBeNull(); @@ -209,7 +203,7 @@ test('an automatic document submission cannot borrow a navigation input even whe expect(f.server.received.some(r => r.path === '/edit')).toBe(false); }); -test('redirect and download responses refuse without following, delivering or arming recovery', async () => { +test('redirect responses and classified download requests refuse without following, delivering or arming recovery', async () => { const f = await setup(); expect(await f.execute({ kind: 'navigate', url: f.server.origin + '/redirect' })).toMatchObject({ state: 'unsupported', code: 'redirect_unsupported' }); expect(f.server.received.some(r => r.path === '/redirect')).toBe(true); From 933da27ae63a6d7821a593c00d44933698c45862 Mon Sep 17 00:00:00 2001 From: Chayapat Sriwattanachote Date: Wed, 18 Nov 2026 09:00:02 +0700 Subject: [PATCH 03/10] test(browser): exercise controller crash and exact service read-back with real Chromium --- ops/evidence/s15-controller.ts | 6 +-- tests/fixtures/s15-browser.ts | 9 ++++- tests/fixtures/s16-browser-crash.ts | 61 +++++++++++++++++++++++++++++ tests/s16-browser-crash.test.ts | 48 +++++++++++++++++++++++ 4 files changed, 119 insertions(+), 5 deletions(-) create mode 100644 tests/fixtures/s16-browser-crash.ts create mode 100644 tests/s16-browser-crash.test.ts diff --git a/ops/evidence/s15-controller.ts b/ops/evidence/s15-controller.ts index a47b7d53..314ce74d 100644 --- a/ops/evidence/s15-controller.ts +++ b/ops/evidence/s15-controller.ts @@ -6,7 +6,7 @@ import { FixturePaymentPort, createFixturePaymentAdapter } from '../../src/s15/p import { zero, equal } from '../../src/s15/policy/validation'; import type { PolicyInput, Ref } from '../../src/s15/policy'; import type { ApprovedModelRoute } from '../../src/s15/model'; -import { browserSite } from '../../tests/fixtures/s15-browser'; +import { browserSite, loopbackFixtureEgress } from '../../tests/fixtures/s15-browser'; import type { BrowserOperation, BrowserResult } from '../../src/s15/browser'; // Opt-in paired controller process. Secret relay material arrives over stdin and is never persisted/logged. @@ -15,7 +15,7 @@ const input = JSON.parse(await Bun.stdin.text()) as { relay: string; bootstrap: const ref = (id: string): Ref => ({ id, revision: 1, generation: 1 }), proof = {}, now = Date.now(), until = now + 3600000; const selection = { route: ref('route'), model: ref('model'), effort: 'low' }, modelBound = { ...zero(), calls: 1, steps: 1, activeMs: 10000 }; const route: ApprovedModelRoute = { selection, provider: 'codex', modelId: 'fixture-model', account: ref('provider_account'), billing: ref('subscription'), recipient: ref('provider'), charge: 'subscription', availability: 'available', efforts: ['low'], effortEvidence: 'requested_only', upperBound: modelBound, rank: { ordinary: 0, difficult: 0 } }; -const report: Record = { contract: 's15-arm64-evidence/v1', sha: input.sha, architecture: process.arch, controller: 'jit-s15-arm', workingVm: 'jit-work-arm', modelInference: 'not_run', ownerCredentials: 'not_used', startedAt: new Date().toISOString(), cases: {} }; +const report: Record = { contract: 's15-arm64-evidence/v1', sha: input.sha, architecture: process.arch, controller: 'jit-s15-arm', workingVm: 'jit-work-arm', modelInference: 'not_run', ownerCredentials: 'not_used', controlledLoopbackDnsDial: true, startedAt: new Date().toISOString(), cases: {} }; const cases = report.cases as Record, site = browserSite(), manager = new RemoteVmManagement({ origin: input.relay, credential: () => input.credential, allowLoopback: true }); const catalog = new Map(); for (const [kind, names] of Object.entries({ purpose: ['evidence', 'interpret'], bot: ['bot'], resource: ['computer', 'account'], recipient: ['provider', 'payee', 'other'], route: ['route'], model: ['model'] })) for (const id of names) catalog.set(`${kind}:${id}`, { ref: ref(id), active: true }); @@ -35,7 +35,7 @@ const service = await composeS15({ runtime: 's15', directory: join(input.output, model: { registry: { list: () => [route], current: s => equal(s, selection) ? route : null, pins: () => ({ route: null, model: null, effort: null }) }, limits: { turns: 3, attempts: 1, activeMs: 30000, outputBytes: 32768, contextWindow: 32768, inputChars: 65536 } }, vm: { id: 'arm', resource: ref('computer'), managers: new Map([['remote_lima', manager]]), destination: () => null, upperBound: op => ({ ...zero(), calls: 1, reads: ['read', 'setup'].includes(op.kind) ? 1 : 0, outputBytes: op.outputBytes, activeMs: op.timeoutMs }) }, - browser: { mode: 'general', resource: ref('account'), fences: [], executablePath: input.browser, site: site.site, upperBound: { ...zero(), steps: 1, reads: 1, outputBytes: 2097152, activeMs: 30000 } }, + browser: { mode: 'general', egress: loopbackFixtureEgress, resource: ref('account'), fences: [], executablePath: input.browser, site: site.site, upperBound: { ...zero(), steps: 1, reads: 1, outputBytes: 2097152, activeMs: 30000 } }, adapters: [createFixturePaymentAdapter({ port: payment, currencies: [{ currency: 'USD', minorUnit: 2 }], upperBound: { ...zero(), calls: 1 } })], }); const owner = service.policy.owner.authenticate(proof); service.policy.owner.install(owner, 'evidence_policy', 0, policy); diff --git a/tests/fixtures/s15-browser.ts b/tests/fixtures/s15-browser.ts index 755d0ee3..ee30b436 100644 --- a/tests/fixtures/s15-browser.ts +++ b/tests/fixtures/s15-browser.ts @@ -83,8 +83,13 @@ export function browserSite(options: { delayMs?: number } = {}) { return html('Unknown endpoint', 404); } }); const origin = server.url.origin; + const site = browserSitePolicy(origin); + return { origin, site, received, set beforeResponse(fn: ((path: string, request: Request) => Promise) | null) { beforeResponse = fn; }, password: () => password, code: () => totp(), close: () => server.stop(true) }; +} +/** Trusted controlled-site semantics, reusable by a separate crash/restart process without its server or credentials. */ +export function browserSitePolicy(origin: string): BrowserSitePolicy { const verifyResponse = (r: { status: number; body: Uint8Array }): 'succeeded' | 'unknown' => r.status === 200 && Buffer.from(r.body).includes(Buffer.from('Request accepted')) ? 'succeeded' : 'unknown'; - const site: BrowserSitePolicy = { + return { loginDocuments: [origin + '/login', origin + '/two-factor'], session: { url: origin + '/session', cookie: 'jit_session', signedInStatus: 200, signedOutStatus: 401 }, observable: url => { const u = new URL(url); return u.origin === origin && ['/', '/clean-task', '/message', '/checkout', '/edit', '/attacks', '/dynamic', '/dynamic-tamper', '/dynamic-send'].includes(u.pathname); }, classify(r) { @@ -106,8 +111,8 @@ export function browserSite(options: { delayMs?: number } = {}) { return null; }, }; - return { origin, site, received, set beforeResponse(fn: ((path: string, request: Request) => Promise) | null) { beforeResponse = fn; }, password: () => password, code: () => totp(), close: () => server.stop(true) }; } + /** Real policy service and disposable protected profile shared by deterministic and opt-in engine tests. */ export async function browserFixture(mode: BrowserMode, site: BrowserSitePolicy, factory?: (options: EngineOptions) => Promise, clock?: BrowserClock, egress: BrowserEgressPorts = loopbackFixtureEgress) { const dir = realpathSync(mkdtempSync(join(tmpdir(), 'jit-protected-browser-'))); diff --git a/tests/fixtures/s16-browser-crash.ts b/tests/fixtures/s16-browser-crash.ts new file mode 100644 index 00000000..d7f84e34 --- /dev/null +++ b/tests/fixtures/s16-browser-crash.ts @@ -0,0 +1,61 @@ +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { createHash } from 'node:crypto'; +import { registerProtectedBrowser, type BrowserOperation } from '../../src/s15/browser'; +import type { ActionRef } from '../../src/s15/policy'; +import { unknownUsage } from '../../src/s15/policy/validation'; +import { browserSitePolicy, loopbackFixtureEgress } from './s15-browser'; +import { fixture, ref } from './s15-policy'; + +// Real disposable Chromium/controller process. The parent owns the service effect and kills this process +// after its request was actually received, while the response is withheld outside this process. +if (process.env.JIT_BROWSER_LIVE !== '1') throw Error('explicit_browser_evidence_required'); +const input = JSON.parse(await Bun.stdin.text()) as { phase: 'dispatch' | 'recover'; directory: string; origin: string; readback: string }; +const fresh = input.phase === 'dispatch', site = browserSitePolicy(input.origin); +const gateway = await registerProtectedBrowser({ runtime: 's15', mode: 'general', resource: ref('account'), fences: [], + continuity: { path: join(input.directory, 'continuity.sqlite'), create: fresh }, profilePath: join(input.directory, 'profile'), + executablePath: process.env.JIT_BROWSER_EXECUTABLE ?? '/usr/bin/chromium', site, egress: loopbackFixtureEgress, now: () => 1000, + upperBound: { attempts: 0, steps: 1, calls: 0, reads: 1, outputBytes: 2097152, activeMs: 30000, spendMinor: '0' } }); +const f = fixture({ create: fresh, path: join(input.directory, 'policy.sqlite'), adapters: [gateway.adapter], reads: [gateway.readHandler] }); +gateway.attach(f.service); +const metadataPath = join(input.directory, 'action.json'); +type Metadata = { action: ActionRef; workId: string; generation: number; temporaryDirectory: string }; +const ensure = (condition: unknown, code: string) => { if (!condition) throw Error(code); }; +try { + if (fresh) { + f.input.budget!.ceiling = { attempts: 1000, steps: 1000, calls: 1000, reads: 1000, outputBytes: 2_000_000_000, activeMs: 30_000_000, spendMinor: '100' }; + f.input.rules[0]!.adapters.push('protected_browser'); f.input.rules[0]!.operations.push('browser_request'); f.install(); + const admission = f.admit({ access: 'effect', readLimit: 1000 }), work = gateway.open(admission.actor!); + ensure((await work.execute({ kind: 'navigate', url: input.origin + '/clean-task', generation: work.state().generation })).state === 'ok', 'navigation_failed'); + const page = await work.execute({ kind: 'read', generation: work.state().generation }); + if (page.state !== 'observed') throw Error('observation_failed'); + const target = page.observation.elements.find(e => e.name === 'confirm'); ensure(target, 'target_missing'); + const held = await work.execute({ kind: 'click', target: target!.id, generation: work.state().generation }); + if (held.state !== 'held') throw Error('effect_not_held'); + f.service.owner.decide(f.owner, { requestId: 'crash_exact_approval', action: held.action, decision: 'approve', expiresAt: 20000 }); + writeFileSync(metadataPath, JSON.stringify({ action: held.action, workId: admission.receipt.work!.id, generation: work.state().generation, temporaryDirectory: f.dir } satisfies Metadata), { mode: 0o600 }); + // The parent kills us here; a returned response would invalidate the dispatch-crash experiment. + await work.resume(held.action); throw Error('response_was_not_withheld'); + } + const saved = JSON.parse(readFileSync(metadataPath, 'utf8')) as Metadata, work = gateway.open(f.service.control.bindWork(saved.workId)); + const before = work.state(); ensure(JSON.stringify(before.reconciliation) === JSON.stringify(saved.action), 'lost_continuity'); + const resumeBefore = await work.resume(saved.action); + const navigateBefore = await work.execute({ kind: 'navigate', url: input.origin + '/clean-task', generation: work.state().generation }); + const missing = await gateway.owner.reconcile(f.owner, saved.action, 'crash_missing_verifier'); + f.service.owner.recordStatement(f.owner, saved.action, 'crash_owner_statement', 'occurred'); + const statementUncleared = work.state().reconciliation !== null; + site.reconcileEffect = async (request, context) => { + ensure(request.url === input.origin + '/message' && request.method === 'POST', 'wrong_retained_request'); + const sha256 = createHash('sha256').update(Buffer.from(request.bodyBase64, 'base64')).digest('hex'); + context.beforeRead(); + const response = await fetch(input.readback + '/receipt?sha256=' + sha256, { redirect: 'error', signal: AbortSignal.timeout(5000) }); + const receipt = await response.json() as { sha256?: string; count?: number }; + return { outcome: response.ok && receipt.sha256 === sha256 && receipt.count === 1 ? 'succeeded' : 'unknown', actual: unknownUsage(), transportSettled: true }; + }; + const verified = await gateway.owner.reconcile(f.owner, saved.action, 'crash_service_readback'), after = work.state(); + const resumeAfter = await work.resume(saved.action); + const freshNavigation = await work.execute({ kind: 'navigate', url: input.origin + '/clean-task', generation: work.state().generation } satisfies BrowserOperation); + console.log(JSON.stringify({ recovered: before.reconciliation !== null, generationAdvanced: before.generation > saved.generation, + resumeBefore: resumeBefore.state, navigateBefore: navigateBefore.state, missing: missing.outcome, statementUncleared, + verified: verified.outcome, cleared: after.reconciliation === null, resumeAfter: resumeAfter.state, freshNavigation: freshNavigation.state })); +} finally { await gateway.close(); f.cleanup(); } diff --git a/tests/s16-browser-crash.test.ts b/tests/s16-browser-crash.test.ts new file mode 100644 index 00000000..c70b6444 --- /dev/null +++ b/tests/s16-browser-crash.test.ts @@ -0,0 +1,48 @@ +import { expect, test } from 'bun:test'; +import { createHash } from 'node:crypto'; +import { mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { browserSite } from './fixtures/s15-browser'; + +const native = test.skipIf(process.env.JIT_BROWSER_LIVE !== '1'); +native('SIGKILL after real service dispatch preserves unknown continuity, then exact read-back clears it without replay', async () => { + const directory = realpathSync(mkdtempSync(join(tmpdir(), 'jit-browser-crash-'))), site = browserSite(); + const received = Promise.withResolvers(), response = Promise.withResolvers(); let readbacks = 0; + site.beforeResponse = async path => { if (path === '/message') { received.resolve(); await response.promise; } }; + const readback = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch(request) { + const url = new URL(request.url); if (request.method !== 'GET' || url.pathname !== '/receipt') return new Response(null, { status: 404 }); + readbacks++; const sha256 = url.searchParams.get('sha256'); + const count = site.received.filter(row => row.path === '/message' && row.method === 'POST' && createHash('sha256').update(row.body).digest('hex') === sha256).length; + return Response.json({ sha256, count }); + } }); + const launch = (phase: 'dispatch' | 'recover') => { + const child = Bun.spawn([process.execPath, join(import.meta.dir, 'fixtures/s16-browser-crash.ts')], { stdin: 'pipe', stdout: 'pipe', stderr: 'pipe', env: process.env }); + child.stdin.write(JSON.stringify({ phase, directory, origin: site.origin, readback: readback.url.origin })); child.stdin.end(); return child; + }; + // Kill only this test's exact pipe-controlled browser, never another profile or a system browser. + const stopProfile = () => { + const processes = Bun.spawnSync(['ps', '-eo', 'pid=,args=']); + for (const row of processes.stdout.toString().split('\n')) { + if (row.includes(`--user-data-dir=${join(directory, 'profile')}`) && row.includes('--remote-debugging-pipe')) { + const pid = Number(/^\s*(\d+)\s/.exec(row)?.[1]); if (Number.isSafeInteger(pid) && pid > 1) { try { process.kill(pid, 'SIGKILL'); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error; } } + } + } + }; + let child = launch('dispatch'), timer: ReturnType | undefined, temporaryDirectory: string | undefined; + try { + await Promise.race([received.promise, child.exited.then(async code => { throw Error(`dispatch_child_exited_${code}:` + (await new Response(child.stderr).text()).slice(0, 2000)); }), new Promise((_, reject) => { timer = setTimeout(() => reject(Error('dispatch_barrier_timeout')), 30000); })]); + clearTimeout(timer); expect(site.received.filter(row => row.path === '/message')).toHaveLength(1); expect(readbacks).toBe(0); + const metadata = JSON.parse(readFileSync(join(directory, 'action.json'), 'utf8')) as { temporaryDirectory: string }; + temporaryDirectory = metadata.temporaryDirectory; + child.kill('SIGKILL'); await child.exited; stopProfile(); response.resolve(); + child = launch('recover'); const [code, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect({ code, stderr }).toEqual({ code: 0, stderr: '' }); + expect(JSON.parse(stdout)).toEqual({ recovered: true, generationAdvanced: true, resumeBefore: 'unsupported', navigateBefore: 'unknown', missing: 'unknown', statementUncleared: true, verified: 'succeeded', cleared: true, resumeAfter: 'unsupported', freshNavigation: 'ok' }); + expect(site.received.filter(row => row.path === '/message')).toHaveLength(1); expect(readbacks).toBe(1); + } finally { + clearTimeout(timer); response.resolve(); child.kill(); await child.exited; stopProfile(); site.close(); readback.stop(true); + if (temporaryDirectory?.startsWith(join(tmpdir(), 'jit-s15-policy-'))) rmSync(temporaryDirectory, { recursive: true, force: true }); + rmSync(directory, { recursive: true, force: true }); + } +}, 60000); From 2ce76337582e9f39a3be83344f650aacc35ec957 Mon Sep 17 00:00:00 2001 From: Chayapat Sriwattanachote Date: Wed, 18 Nov 2026 09:27:30 +0700 Subject: [PATCH 04/10] test(browser): probe live protected session custody from the working VM root --- ops/evidence/s15-controller.ts | 31 ++++++++++++- ops/evidence/s16-browser-boundary.ts | 65 ++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 ops/evidence/s16-browser-boundary.ts diff --git a/ops/evidence/s15-controller.ts b/ops/evidence/s15-controller.ts index 314ce74d..fdd89aea 100644 --- a/ops/evidence/s15-controller.ts +++ b/ops/evidence/s15-controller.ts @@ -8,6 +8,7 @@ import type { PolicyInput, Ref } from '../../src/s15/policy'; import type { ApprovedModelRoute } from '../../src/s15/model'; import { browserSite, loopbackFixtureEgress } from '../../tests/fixtures/s15-browser'; import type { BrowserOperation, BrowserResult } from '../../src/s15/browser'; +import { proveProtectedBrowserBoundary } from './s16-browser-boundary'; // Opt-in paired controller process. Secret relay material arrives over stdin and is never persisted/logged. if (process.env.JIT_S15_ARM64_EVIDENCE !== '1') throw Error('explicit_s15_evidence_opt_in_required'); @@ -64,7 +65,35 @@ try { const usage = service.policy.control.usage(); await service.vm.recover(owner, { vmId: 'arm', snapshotId: snapshot.id }); check(equal(usage, service.policy.control.usage()), 'policy_rewound'); await service.vm.start(owner, 'arm'); const restored = await open(); const marker = await restored.session.backend.spawn({ command: 'cat /var/lib/jit-evid15-marker', cwd: restored.session.backend.workspaceRoot }); check(marker.stdout === 'baseline', 'snapshot_restore_failed'); await restored.session.close(); cases.snapshotRecovery = { passed: true, snapshot: snapshot.id, protectedPolicyUnchanged: true, prevention: false }; const { actor } = admit('account'), browser = service.browser!.open(actor); - const run = (operation: Omit, 'generation'> | { kind: 'read' | 'click'; target?: string }) => browser.execute({ ...operation, generation: browser.state().generation } as BrowserOperation); + const run = (operation: Omit, 'generation'> | { kind: 'read' | 'click'; target?: string } | { kind: 'type' | 'select'; target: string; value: string }) => browser.execute({ ...operation, generation: browser.state().generation } as BrowserOperation); + report.stage = 'protected_login'; + check((await run({ kind: 'navigate', url: site.origin + '/login' })).state === 'ok', 'login_navigation_failed'); + check((await run({ kind: 'read' })).state === 'denied', 'login_surface_disclosed'); + const login = await service.browser!.owner.takeover(owner); + await service.browser!.owner.input(owner, login.generation, { kind: 'type', field: 'password', value: site.password() }); + await service.browser!.owner.input(owner, login.generation, { kind: 'click', field: 'confirm' }); + await service.browser!.owner.input(owner, login.generation, { kind: 'type', field: 'otp', value: site.code() }); + await service.browser!.owner.input(owner, login.generation, { kind: 'click', field: 'confirm' }); + check(service.browser!.owner.handBack(owner, login.generation).login === 'checking', 'login_not_checking'); + check(await service.browser!.owner.checkSession(owner) === 'signed_in', 'protected_login_unverified'); + report.stage = 'authenticated_dynamic_task'; + check((await run({ kind: 'navigate', url: site.origin + '/dynamic' })).state === 'ok', 'dynamic_navigation_failed'); + const dynamic = await run({ kind: 'read' }); if (dynamic.state !== 'observed') throw Error('dynamic_observation_failed'); + check(dynamic.observation.text.includes('Launch day: Friday / Launch project'), 'dynamic_hydration_failed'); + const message = dynamic.observation.elements.find(element => element.name === 'message')!, confirm = dynamic.observation.elements.find(element => element.name === 'confirm')!; + check((await run({ kind: 'type', target: message.id, value: 'Exact reference-host browser effect' })).state === 'ok', 'dynamic_edit_failed'); + const dynamicHold = await run({ kind: 'click', target: confirm.id }); if (dynamicHold.state !== 'held') throw Error('dynamic_effect_not_held'); + check(!site.received.some(row => row.path === '/dynamic-send'), 'dynamic_effect_sent_before_approval'); + const action = service.policy.owner.inspect(owner, dynamicHold.action).action; + service.policy.owner.decide(owner, { requestId: 'dynamic_exact_approval', action: dynamicHold.action, decision: 'approve', expiresAt: action.expiresAt }); + check((await browser.resume(dynamicHold.action)).state === 'ok', 'dynamic_effect_unverified'); + check(site.received.filter(row => row.path === '/dynamic-send').length === 1, 'dynamic_effect_not_once'); + check((await browser.resume(dynamicHold.action)).state === 'unsupported', 'dynamic_effect_replayed'); + cases.authenticatedDynamicTask = { passed: true, hydration: 'actual_fetch_and_xhr', login: 'actual_fixture_password_and_totp_protected_owner_port', dispatch: 'exact_approved_once_verified_by_body_hash', credentialsExported: false }; + report.stage = 'protected_browser_guest_boundary'; const boundaryGuest = await open(); + cases.protectedBrowserGuestBoundary = { ...await proveProtectedBrowserBoundary(boundaryGuest.session, join(input.output, 'protected', 'profiles')), externalNetwork: (await manager.inspect()).network }; + await boundaryGuest.session.close(); + report.stage = 'browser_communication_hold'; const nav = await run({ kind: 'navigate', url: site.origin + '/clean-task' }); check(nav.state === 'ok', 'browser_navigation_failed'); const read = await run({ kind: 'read' }); check(read.state === 'observed', 'browser_observation_failed'); if (read.state !== 'observed') throw Error('browser_observation_failed'); diff --git a/ops/evidence/s16-browser-boundary.ts b/ops/evidence/s16-browser-boundary.ts new file mode 100644 index 00000000..6e408cf5 --- /dev/null +++ b/ops/evidence/s16-browser-boundary.ts @@ -0,0 +1,65 @@ +import { randomBytes } from 'node:crypto'; +import { existsSync, rmSync, writeFileSync } from 'node:fs'; +import { networkInterfaces } from 'node:os'; +import { join } from 'node:path'; +import type { VmSession } from '../../src/s15/vm'; +import { vmQuote } from '../../src/s15/vm/host'; + +/** Opt-in reference-host evidence over an actual root VM session and live protected Chromium. + * Combines pipe-only process facts, protected-file/control-network positive canaries and actual guest attempts; + * it does not attest against a hypervisor/browser-engine exploit or certify another installation. */ +export async function proveProtectedBrowserBoundary(session: VmSession, profilePath: string) { + if (process.env.JIT_S15_ARM64_EVIDENCE !== '1' || process.platform !== 'linux') throw Error('explicit_linux_boundary_evidence_required'); + const rows = Bun.spawnSync(['ps', '-eo', 'pid=,args=']); + const browser = rows.stdout.toString().split('\n').filter(row => row.includes(`--user-data-dir=${profilePath}`) && row.includes('--remote-debugging-pipe')); + if (rows.exitCode !== 0 || browser.length !== 1 || browser[0]!.includes('--remote-debugging-port') || existsSync(join(profilePath, 'DevToolsActivePort'))) throw Error('browser_pipe_unproven'); + const cookiePaths = [join(profilePath, 'Default', 'Cookies'), join(profilePath, 'Default', 'Network', 'Cookies')].filter(existsSync); + if (!cookiePaths.length) throw Error('browser_cookie_file_unproven'); + const marker = join(profilePath, 'jit-boundary-canary'); writeFileSync(marker, randomBytes(32), { mode: 0o600 }); + const addresses = [...new Set(Object.values(networkInterfaces()).flatMap(values => values?.filter(value => value.family === 'IPv4' && !value.internal).map(value => value.address) ?? []))]; + if (!addresses.length) throw Error('controller_interface_unproven'); + let requests = 0; + const canary = Bun.serve({ hostname: '0.0.0.0', port: 0, fetch() { requests++; return new Response(null, { status: 204 }); } }); + try { + const positive = await fetch(`http://127.0.0.1:${canary.port}/boundary-canary`, { signal: AbortSignal.timeout(5000) }); await positive.arrayBuffer(); + if (positive.status !== 204 || requests !== 1) throw Error('controller_canary_unproven'); + const targets = [...new Set([...addresses, '192.168.5.2'])].flatMap(host => [canary.port!, 9222].map(port => [host, port])); + const source = `import os,json,socket,subprocess,tempfile,concurrent.futures +paths=${JSON.stringify([marker, ...cookiePaths])} +targets=${JSON.stringify(targets)} +profile=${JSON.stringify(profilePath)}.encode() +def readable(path): + try: + fd=os.open(path,os.O_RDONLY);os.close(fd);return True + except OSError:return False +def dial(target): + s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.settimeout(1) + try: + s.connect(tuple(target));s.sendall(b'GET /json/version HTTP/1.1\\r\\nHost: fixture\\r\\nConnection: close\\r\\n\\r\\n');return True + except OSError:return False + finally:s.close() +visible=False +for name in os.listdir('/proc'): + if not name.isdigit():continue + try: + args=open('/proc/'+name+'/cmdline','rb').read().split(b'\\0') + if b'--remote-debugging-pipe' in args and b'--user-data-dir='+profile in args:visible=True + except OSError:pass +mounted=subprocess.run(['findmnt','-rn','-t','9p,virtiofs'],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,timeout=3) +point=tempfile.mkdtemp(prefix='jit-browser-mount-') +try: + attempted=subprocess.run(['mount','-t','9p','-o','trans=virtio','jit-protected',point],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=3) + accepted=attempted.returncode==0 + if accepted:subprocess.run(['umount',point],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=3) +finally:os.rmdir(point) +with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: + result={'root':os.geteuid()==0,'readable':list(map(readable,paths)),'controllerBrowserVisible':visible,'mountedShares':bool(mounted.stdout.strip()),'mountAccepted':accepted,'reachable':list(pool.map(dial,targets))} +print(json.dumps(result,separators=(',',':'))) +`; + const response = await session.backend.spawn({ command: 'sudo -n python3 -I -c ' + vmQuote(source), cwd: session.backend.workspaceRoot, timeoutMs: 15000 }); + if (response.exitCode !== 0 || response.timedOut) throw Error('guest_boundary_probe_failed'); + const result = JSON.parse(response.stdout) as { root: boolean; readable: boolean[]; controllerBrowserVisible: boolean; mountedShares: boolean; mountAccepted: boolean; reachable: boolean[] }; + if (!result.root || result.readable.length !== 1 + cookiePaths.length || result.readable.some(value => value !== false) || result.controllerBrowserVisible !== false || result.mountedShares !== false || result.mountAccepted !== false || result.reachable.length !== targets.length || result.reachable.some(value => value !== false) || requests !== 1) throw Error('protected_browser_boundary_bypassed'); + return { passed: true, browserControl: 'observed_pipe_only', persistedCookieFiles: cookiePaths.length, protectedCanary: 'controller_positive_guest_denied', controlNetworkCanary: 'controller_positive_zero_guest_requests', guest: result, basis: 'actual_root_attempts_plus_external_manager_inventory', scope: 'paired_reference_host_not_hypervisor_escape_attestation' }; + } finally { canary.stop(true); rmSync(marker, { force: true }); } +} From 426065831b936928ebdf25d42d61b46677c68186 Mon Sep 17 00:00:00 2001 From: Chayapat Sriwattanachote Date: Wed, 18 Nov 2026 09:29:17 +0700 Subject: [PATCH 05/10] test(browser): observe a fresh target after editing the live form --- ops/evidence/s15-controller.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ops/evidence/s15-controller.ts b/ops/evidence/s15-controller.ts index fdd89aea..c9e8bf07 100644 --- a/ops/evidence/s15-controller.ts +++ b/ops/evidence/s15-controller.ts @@ -80,8 +80,10 @@ try { check((await run({ kind: 'navigate', url: site.origin + '/dynamic' })).state === 'ok', 'dynamic_navigation_failed'); const dynamic = await run({ kind: 'read' }); if (dynamic.state !== 'observed') throw Error('dynamic_observation_failed'); check(dynamic.observation.text.includes('Launch day: Friday / Launch project'), 'dynamic_hydration_failed'); - const message = dynamic.observation.elements.find(element => element.name === 'message')!, confirm = dynamic.observation.elements.find(element => element.name === 'confirm')!; + const message = dynamic.observation.elements.find(element => element.name === 'message')!; check((await run({ kind: 'type', target: message.id, value: 'Exact reference-host browser effect' })).state === 'ok', 'dynamic_edit_failed'); + const edited = await run({ kind: 'read' }); if (edited.state !== 'observed') throw Error('dynamic_edited_observation_failed'); + const confirm = edited.observation.elements.find(element => element.name === 'confirm')!; const dynamicHold = await run({ kind: 'click', target: confirm.id }); if (dynamicHold.state !== 'held') throw Error('dynamic_effect_not_held'); check(!site.received.some(row => row.path === '/dynamic-send'), 'dynamic_effect_sent_before_approval'); const action = service.policy.owner.inspect(owner, dynamicHold.action).action; From 4ddbf88aabaec50fb6afe56571cbf6fd9c091f59 Mon Sep 17 00:00:00 2001 From: Chayapat Sriwattanachote Date: Wed, 18 Nov 2026 09:35:00 +0700 Subject: [PATCH 06/10] test(browser): audit exact kernel argv and record reference build hashes --- ops/evidence/s15-arm64.ts | 3 ++- ops/evidence/s15-controller.ts | 5 ++++- ops/evidence/s16-browser-boundary.ts | 12 ++++++++---- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/ops/evidence/s15-arm64.ts b/ops/evidence/s15-arm64.ts index fba596f4..1f228ea4 100644 --- a/ops/evidence/s15-arm64.ts +++ b/ops/evidence/s15-arm64.ts @@ -50,12 +50,13 @@ export async function runS15Arm64Evidence() { writeFileSync(join(directory, 'controller-summary.json'), result, { mode: 0o600 }); await run(['limactl', 'shell', '--workdir', '/', 'jit-s15-arm', 'sudo', '-n', 'sh', '-c', `cp ${output}/results.json /tmp/jit-s15-results.json && chmod 644 /tmp/jit-s15-results.json`]); await run(['limactl', 'copy', 'jit-s15-arm:/tmp/jit-s15-results.json', join(directory, 'results.json')]); + chmodSync(join(directory, 'results.json'), 0o600); if (executed.exitCode !== 0) throw Error('controller_boundary_case_failed'); } finally { tunnel?.kill(); if (tunnel) await tunnel.exited; bootstrap.stop(true); relay.close(); await manager.stop().catch(() => {}); const after = await run(['limactl', 'snapshot', 'list', 'jit-work-arm', '--quiet']); writeFileSync(join(directory, 'snapshots-after.txt'), after, { mode: 0o600 }); const baseline = readFileSync(join(directory, 'snapshots-before.txt'), 'utf8').trim().split('\n').filter(Boolean); if (!baseline.every(tag => after.trim().split('\n').includes(tag))) throw Error('baseline_snapshot_missing'); - writeFileSync(join(directory, 'manifest.json'), JSON.stringify({ sha, controller: 'jit-s15-arm', workingVm: 'jit-work-arm', output, baselineSnapshotsRetained: true, testedAt: new Date().toISOString(), controllerConfigHash: new Bun.CryptoHasher('sha256').update(readFileSync(join(homedir(), '.lima/jit-s15-arm/lima.yaml'))).digest('hex'), workingConfigHash: new Bun.CryptoHasher('sha256').update(readFileSync(join(homedir(), '.lima/jit-work-arm/lima.yaml'))).digest('hex'), schwayTarballHash: new Bun.CryptoHasher('sha256').update(readFileSync((JSON.parse(readFileSync('package.json', 'utf8')) as { dependencies: { schway: string } }).dependencies.schway.replace(/^file:/, ''))).digest('hex') }, null, 2), { mode: 0o600 }); + writeFileSync(join(directory, 'manifest.json'), JSON.stringify({ sha, topology: 'macos_lima_management_linux_controller_separate_qemu_working_vm', controller: 'jit-s15-arm', workingVm: 'jit-work-arm', output, baselineSnapshotsRetained: true, testedAt: new Date().toISOString(), limaVersion: (await run(['limactl', '--version'])).trim(), qemuVersion: (await run(['/opt/homebrew/bin/qemu-system-aarch64', '--version'])).split('\n')[0], qemuSha256: new Bun.CryptoHasher('sha256').update(readFileSync('/opt/homebrew/bin/qemu-system-aarch64')).digest('hex'), wrapperSha256: new Bun.CryptoHasher('sha256').update(readFileSync(wrapper)).digest('hex'), controllerConfigHash: new Bun.CryptoHasher('sha256').update(readFileSync(join(homedir(), '.lima/jit-s15-arm/lima.yaml'))).digest('hex'), workingConfigHash: new Bun.CryptoHasher('sha256').update(readFileSync(join(homedir(), '.lima/jit-work-arm/lima.yaml'))).digest('hex'), schwayTarballHash: new Bun.CryptoHasher('sha256').update(readFileSync((JSON.parse(readFileSync('package.json', 'utf8')) as { dependencies: { schway: string } }).dependencies.schway.replace(/^file:/, ''))).digest('hex') }, null, 2), { mode: 0o600 }); } } if (import.meta.main) await runS15Arm64Evidence(); diff --git a/ops/evidence/s15-controller.ts b/ops/evidence/s15-controller.ts index c9e8bf07..8095b51c 100644 --- a/ops/evidence/s15-controller.ts +++ b/ops/evidence/s15-controller.ts @@ -1,4 +1,4 @@ -import { mkdirSync, writeFileSync } from 'node:fs'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { composeS15 } from '../../src/s15/composition'; import { RemoteVmManagement } from '../../src/s15/vm/remote'; @@ -17,6 +17,9 @@ const ref = (id: string): Ref => ({ id, revision: 1, generation: 1 }), proof = { const selection = { route: ref('route'), model: ref('model'), effort: 'low' }, modelBound = { ...zero(), calls: 1, steps: 1, activeMs: 10000 }; const route: ApprovedModelRoute = { selection, provider: 'codex', modelId: 'fixture-model', account: ref('provider_account'), billing: ref('subscription'), recipient: ref('provider'), charge: 'subscription', availability: 'available', efforts: ['low'], effortEvidence: 'requested_only', upperBound: modelBound, rank: { ordinary: 0, difficult: 0 } }; const report: Record = { contract: 's15-arm64-evidence/v1', sha: input.sha, architecture: process.arch, controller: 'jit-s15-arm', workingVm: 'jit-work-arm', modelInference: 'not_run', ownerCredentials: 'not_used', controlledLoopbackDnsDial: true, startedAt: new Date().toISOString(), cases: {} }; +const buildCommand = (argv: string[]) => { const result = Bun.spawnSync(argv); if (result.exitCode !== 0) throw Error('build_fact_unavailable'); return result.stdout.toString().trim(); }; +const binaryHash = (path: string) => { const hash = buildCommand(['sha256sum', path]).split(/\s/)[0]!; if (!/^[a-f0-9]{64}$/.test(hash)) throw Error('build_hash_unavailable'); return hash; }; +report.build = { bun: { version: process.versions.bun, sha256: binaryHash(process.execPath) }, browser: { version: buildCommand([input.browser, '--version']), sha256: binaryHash(input.browser) }, kernel: buildCommand(['uname', '-r']), playwright: JSON.parse(readFileSync(new URL('../../node_modules/playwright-core/package.json', import.meta.url), 'utf8')).version }; const cases = report.cases as Record, site = browserSite(), manager = new RemoteVmManagement({ origin: input.relay, credential: () => input.credential, allowLoopback: true }); const catalog = new Map(); for (const [kind, names] of Object.entries({ purpose: ['evidence', 'interpret'], bot: ['bot'], resource: ['computer', 'account'], recipient: ['provider', 'payee', 'other'], route: ['route'], model: ['model'] })) for (const id of names) catalog.set(`${kind}:${id}`, { ref: ref(id), active: true }); diff --git a/ops/evidence/s16-browser-boundary.ts b/ops/evidence/s16-browser-boundary.ts index 6e408cf5..c8fc5c8d 100644 --- a/ops/evidence/s16-browser-boundary.ts +++ b/ops/evidence/s16-browser-boundary.ts @@ -1,5 +1,5 @@ import { randomBytes } from 'node:crypto'; -import { existsSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { networkInterfaces } from 'node:os'; import { join } from 'node:path'; import type { VmSession } from '../../src/s15/vm'; @@ -10,9 +10,13 @@ import { vmQuote } from '../../src/s15/vm/host'; * it does not attest against a hypervisor/browser-engine exploit or certify another installation. */ export async function proveProtectedBrowserBoundary(session: VmSession, profilePath: string) { if (process.env.JIT_S15_ARM64_EVIDENCE !== '1' || process.platform !== 'linux') throw Error('explicit_linux_boundary_evidence_required'); - const rows = Bun.spawnSync(['ps', '-eo', 'pid=,args=']); - const browser = rows.stdout.toString().split('\n').filter(row => row.includes(`--user-data-dir=${profilePath}`) && row.includes('--remote-debugging-pipe')); - if (rows.exitCode !== 0 || browser.length !== 1 || browser[0]!.includes('--remote-debugging-port') || existsSync(join(profilePath, 'DevToolsActivePort'))) throw Error('browser_pipe_unproven'); + // Read exact NUL-separated kernel argv, rather than a terminal-width-dependent `ps` rendering. + const browser: string[][] = []; + for (const pid of readdirSync('/proc').filter(name => /^\d+$/.test(name))) { + let args: string[]; try { args = readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0'); } catch { continue; } + if (args.includes(`--user-data-dir=${profilePath}`) && args.includes('--remote-debugging-pipe')) browser.push(args); + } + if (browser.length !== 1 || browser[0]!.some(arg => arg.startsWith('--remote-debugging-port')) || existsSync(join(profilePath, 'DevToolsActivePort'))) throw Error(`browser_pipe_unproven:${browser.length}:${existsSync(join(profilePath, 'DevToolsActivePort'))}`); const cookiePaths = [join(profilePath, 'Default', 'Cookies'), join(profilePath, 'Default', 'Network', 'Cookies')].filter(existsSync); if (!cookiePaths.length) throw Error('browser_cookie_file_unproven'); const marker = join(profilePath, 'jit-boundary-canary'); writeFileSync(marker, randomBytes(32), { mode: 0o600 }); From 4e3629405e176485ad0d2ab54f4d1935c2fc54a9 Mon Sep 17 00:00:00 2001 From: Chayapat Sriwattanachote Date: Wed, 18 Nov 2026 09:47:21 +0700 Subject: [PATCH 07/10] fix(browser): settle cancelled native navigation before takeover completes --- src/s15/browser/engine.ts | 20 ++++++++++++++++---- tests/s16-browser-conformance.test.ts | 20 ++++++++++++++++++-- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/src/s15/browser/engine.ts b/src/s15/browser/engine.ts index 05d3d4da..8b655716 100644 --- a/src/s15/browser/engine.ts +++ b/src/s15/browser/engine.ts @@ -123,9 +123,16 @@ export async function launchProtectedEngine(options: EngineOptions): Promise(promise: Promise, input: EngineInputContext): Promise => { input.guard(); - let cancel!: () => void; - const aborted = new Promise((_, reject) => { cancel = () => reject(new BrowserError('cancelled')); input.signal.addEventListener('abort', cancel, { once: true }); if (input.signal.aborted) cancel(); }); - try { const result = await Promise.race([promise, aborted]); input.guard(); return result; } + let stopped: Promise | null = null; + const cancel = () => { stopped ??= session.send('Page.stopLoading').then(() => {}); void stopped.catch(() => {}); }; + input.signal.addEventListener('abort', cancel, { once: true }); if (input.signal.aborted) cancel(); + // The gateway returns its fenced result immediately, but retains the input lease until this actual + // browser operation settles. An abort race alone would let an old error document interrupt the next + // navigation after takeover. Stop only renderer loading; an already-dispatched broker effect is separate. + try { + let result: T; try { result = await promise; } finally { if (stopped) await stopped; } + input.guard(); return result; + } finally { input.signal.removeEventListener('abort', cancel); } }; const click = async (el: ElementHandle, input: EngineInputContext): Promise => { @@ -148,7 +155,12 @@ export async function launchProtectedEngine(options: EngineOptions): Promise { + // A prevented/aborted navigation may never start a frame. Its navigation wait is finite; + // acknowledged stop completes that path without waiting forever for an absent stop event. + if (error) { await session.send('Page.stopLoading'); return error; } + await stopped.promise; return null; + }), input); if (error) throw new BrowserError('navigation_failed'); } } finally { stopped?.close(); } diff --git a/tests/s16-browser-conformance.test.ts b/tests/s16-browser-conformance.test.ts index 59d2e5a6..678c9644 100644 --- a/tests/s16-browser-conformance.test.ts +++ b/tests/s16-browser-conformance.test.ts @@ -6,8 +6,8 @@ import { launchProtectedEngine } from '../src/s15/browser/engine'; const realBrowser = describe.skipIf(process.env.JIT_BROWSER_LIVE !== '1'); const observation = (result: BrowserResult): BrowserObservation => { if (result.state !== 'observed') throw Error(JSON.stringify(result)); return result.observation; }; -async function scenario(mode: 'static' | 'general') { - const server = browserSite(), trace: { path: string; navigation: boolean; sent: boolean; denied: boolean }[] = [], mutation = Promise.withResolvers(); +async function scenario(mode: 'static' | 'general', delayMs = 0) { + const server = browserSite({ delayMs }), trace: { path: string; navigation: boolean; sent: boolean; denied: boolean }[] = [], mutation = Promise.withResolvers(); const f = await browserFixture(mode, server.site, options => launchProtectedEngine({ ...options, async request(wire) { const path = new URL(wire.request.url).pathname; if (!path.startsWith('/dynamic')) return options.request(wire); @@ -33,6 +33,22 @@ async function scenario(mode: 'static' | 'general') { } realBrowser('S16 protected modern-browser conformance', () => { + for (const mode of ['static', 'general'] as const) test(`${mode}: takeover settles a cancelled held navigation before immediate fresh input`, async () => { + const s = await scenario(mode, 250); + try { + for (let attempt = 0; attempt < 3; attempt++) { + await s.navigate('/clean-task'); + const page = observation(await s.run({ kind: 'read' })), button = page.elements.filter(element => element.name === 'confirm')[1]!; + const held = await s.run({ kind: 'click', target: button.id }); if (held.state !== 'held') throw Error('payment_not_held'); + const owner = await s.f.gateway.owner.takeover(s.f.owner); s.f.gateway.owner.handBack(s.f.owner, owner.generation, true); + // No delay, retry, extra handoff or bypass of the old native operation's settlement. + await s.navigate('/clean-task'); + expect(await s.f.work.resume(held.action)).toMatchObject({ state: 'unsupported' }); + expect(s.server.received.filter(row => row.path === '/checkout')).toHaveLength(0); + } + } finally { await s.close(); } + }, 60000); + test('static negative control cannot obtain or submit the JS-created authenticated task', async () => { const s = await scenario('static'); try { From 9b5a31e1d007001415b7d91cb6c38bcfcb0f8bad Mon Sep 17 00:00:00 2001 From: Chayapat Sriwattanachote Date: Wed, 18 Nov 2026 10:04:29 +0700 Subject: [PATCH 08/10] fix(browser): retain actual native settlement through page transitions and close --- src/s15/browser/engine.ts | 35 ++++++++++++--------------- src/s15/browser/gateway.ts | 11 ++++++++- tests/s15-browser-live.test.ts | 9 +++++-- tests/s15-browser.test.ts | 15 ++++++++++-- tests/s16-browser-conformance.test.ts | 12 +++++++++ 5 files changed, 57 insertions(+), 25 deletions(-) diff --git a/src/s15/browser/engine.ts b/src/s15/browser/engine.ts index 8b655716..9fcdfbff 100644 --- a/src/s15/browser/engine.ts +++ b/src/s15/browser/engine.ts @@ -118,22 +118,17 @@ export async function launchProtectedEngine(options: EngineOptions): Promise void; const promise = new Promise(r => { resolve = r; }); const start = (event: { frameId: string }) => { if (event.frameId === mainFrame) started = true; }; const stop = (event: { frameId: string }) => { if (event.frameId === mainFrame && started) resolve(); }; + const closed = () => resolve(); session.on('Page.frameStartedLoading', start); session.on('Page.frameStoppedLoading', stop); - return { promise, close() { session.off('Page.frameStartedLoading', start); session.off('Page.frameStoppedLoading', stop); } }; + page.on('close', closed); + return { promise, started: () => started, close() { session.off('Page.frameStartedLoading', start); session.off('Page.frameStoppedLoading', stop); page.off('close', closed); } }; }; const checked = async (promise: Promise, input: EngineInputContext): Promise => { input.guard(); - let stopped: Promise | null = null; - const cancel = () => { stopped ??= session.send('Page.stopLoading').then(() => {}); void stopped.catch(() => {}); }; - input.signal.addEventListener('abort', cancel, { once: true }); if (input.signal.aborted) cancel(); // The gateway returns its fenced result immediately, but retains the input lease until this actual // browser operation settles. An abort race alone would let an old error document interrupt the next - // navigation after takeover. Stop only renderer loading; an already-dispatched broker effect is separate. - try { - let result: T; try { result = await promise; } finally { if (stopped) await stopped; } - input.guard(); return result; - } - finally { input.signal.removeEventListener('abort', cancel); } + // navigation after takeover. Browser cancellation is not settlement of a separate broker effect. + const result = await promise; input.guard(); return result; }; const click = async (el: ElementHandle, input: EngineInputContext): Promise => { await checked(el.waitForElementState('visible', { timeout: 5000 }), input); @@ -147,23 +142,20 @@ export async function launchProtectedEngine(options: EngineOptions): Promise null, (error: unknown) => error) : null; + const settled = navigation?.then(async error => { if (stopped?.started()) await stopped.promise; return error; }); + let issued = false; try { - input.guard(); const down = session.send('Input.dispatchMouseEvent', { type: 'mousePressed', button: 'left', buttons: 1, x, y, clickCount: 1 }); + input.guard(); issued = true; const down = session.send('Input.dispatchMouseEvent', { type: 'mousePressed', button: 'left', buttons: 1, x, y, clickCount: 1 }); // Both halves are enqueued in the same synchronous turn; cancellation cannot leave a queued half-click. input.guard(); const up = session.send('Input.dispatchMouseEvent', { type: 'mouseReleased', button: 'left', buttons: 0, x, y, clickCount: 1 }); await Promise.all([down, up]); input.guard(); - if (navigation && stopped) { + if (settled) { // A denied navigation can still commit Chromium's error document after waitForNavigation rejects. // Wait for the frame's real stop event before another input can replace it. - const error = await checked(navigation.then(async error => { - // A prevented/aborted navigation may never start a frame. Its navigation wait is finite; - // acknowledged stop completes that path without waiting forever for an absent stop event. - if (error) { await session.send('Page.stopLoading'); return error; } - await stopped.promise; return null; - }), input); + const error = await checked(settled, input); if (error) throw new BrowserError('navigation_failed'); } - } finally { stopped?.close(); } + } finally { try { if (issued && settled) await settled; } finally { stopped?.close(); } } }; const fill = async (el: ElementHandle, value: string, input: EngineInputContext): Promise => { await checked(el.waitForElementState('editable', { timeout: 5000 }), input); @@ -180,7 +172,10 @@ export async function launchProtectedEngine(options: EngineOptions): Promise { closed = true; generation = continuity.advance(); stop(); await Promise.allSettled([...scopes].map(s => s.completion)); try { await engine.close(); } finally { egress.close(); continuity.close(); } })(); }, + close() { return closing ??= (async () => { + closed = true; generation = continuity.advance(); stop(); + // Closing the native browser settles its pending renderer operations. Keep broker/continuity + // custody until their scopes finish; killing a renderer does not recall a dispatched HTTP effect. + try { + const [native] = await Promise.allSettled([Promise.resolve().then(() => engine.close()), ...[...scopes].map(s => s.completion)]); + if (native.status === 'rejected') throw native.reason; + } + finally { egress.close(); continuity.close(); } + })(); }, }; return registration; } diff --git a/tests/s15-browser-live.test.ts b/tests/s15-browser-live.test.ts index d9c95f99..be27b79f 100644 --- a/tests/s15-browser-live.test.ts +++ b/tests/s15-browser-live.test.ts @@ -4,6 +4,7 @@ import { connect } from 'node:net'; import { join } from 'node:path'; import type { BrowserEgressPorts, BrowserOperation, BrowserResult, BrowserObservation, BrowserSitePolicy } from '../src/s15/browser'; import { browserFixture, browserSite, fixturePublicAddress } from './fixtures/s15-browser'; +import { launchProtectedEngine } from '../src/s15/browser/engine'; const live = describe.skipIf(process.env.JIT_BROWSER_LIVE !== '1'); const observed = (result: BrowserResult): BrowserObservation => { expect(result.state).toBe('observed'); if (result.state !== 'observed') throw Error(JSON.stringify(result)); return result.observation; }; @@ -11,9 +12,13 @@ const observed = (result: BrowserResult): BrowserObservation => { expect(result. live('opt-in real protected browser engine', () => { for (const mode of ['static', 'general'] as const) { test(`${mode}: actual navigation, JS boundary, login/TOTP, exact send/payment/disclosure holds, edit, redirect/popup/download denial`, async () => { - const server = browserSite({ delayMs: 250 }); const f = await browserFixture(mode, server.site); + const server = browserSite({ delayMs: 250 }), nativeFailures: string[] = []; + const f = await browserFixture(mode, server.site, async options => { + const engine = await launchProtectedEngine(options); + return { ...engine, async navigate(...args) { try { return await engine.navigate(...args); } catch (error) { nativeFailures.push((error instanceof Error ? error.message.split('\n')[0]! : 'native_error').replace(/https?:\/\/\S+/g, '')); throw error; } } }; + }); const run = (input: Omit, 'generation'> | { kind: 'read' | 'screenshot' | 'click'; target?: string } | { kind: 'type' | 'select'; target: string; value: string }): Promise => f.work.execute({ ...input, generation: f.work.state().generation } as BrowserOperation); - const nav = async (path: string) => { expect(await run({ kind: 'navigate', url: server.origin + path })).toMatchObject({ state: 'ok' }); }; + const nav = async (path: string) => { expect({ path, result: await run({ kind: 'navigate', url: server.origin + path }), nativeFailures }).toMatchObject({ result: { state: 'ok' } }); }; const click = async (name: string) => { const page = observed(await run({ kind: 'read' })); const target = page.elements.find(e => e.name === name); expect(target).toBeDefined(); return run({ kind: 'click', target: target!.id }); }; const reset = async () => { const owner = await f.gateway.owner.takeover(f.owner); f.gateway.owner.handBack(f.owner, owner.generation, true); await nav('/clean-task'); }; try { diff --git a/tests/s15-browser.test.ts b/tests/s15-browser.test.ts index d4015d02..6b87882d 100644 --- a/tests/s15-browser.test.ts +++ b/tests/s15-browser.test.ts @@ -16,6 +16,7 @@ function fake() { let options!: EngineOptions, url = '', next: BrowserRequest | null = null, cookie: string | null = null; let sent = 0, denied = 0, frames = 0, physicalInputs = 0, noWait = false; let beforeInput: ((input: EngineInputContext) => Promise) | null = null, nextOwner: BrowserRequest | null = null; + let onClose: (() => void | Promise) | null = null; const responses: BrokerResponse[] = []; let afterNavigate: BrowserRequest | null = null; let blockRead: (() => Promise) | null = null; const make = (target: string): BrowserRequest => ({ url: target, method: 'GET', contentType: '', bodyBase64: '', navigation: true }); async function request(r: BrowserRequest, attributable = true) { await options.request({ request: r, cookies: cookie ?? '', main: true, document: true, attributable, async send(response) { sent++; url = r.url; responses.push(response); if (response.setCookies.length) cookie = response.setCookies.map(v => v.split(';')[0]).join('; '); }, async deny() { denied++; } }); } @@ -24,9 +25,9 @@ function fake() { async read(generation) { await blockRead?.(); return { id: 'observation', generation, url, text: 'Observed content', truncated: false, elements: [{ id: 'e1_1', tag: 'button', name: 'Read more', type: 'submit' }] }; }, async image() { frames++; return new Uint8Array([1, 2, 3]); }, async interact(_kind, _target, _value, _generation, input) { await beforeInput?.(input); input.guard(); physicalInputs++; if (next) { const r = next; next = null; const job = request(r); if (noWait) void job.catch(() => {}); else await job; } }, - async ownerInput(_value, input) { await beforeInput?.(input); input.guard(); physicalInputs++; if (nextOwner) { const r = nextOwner; nextOwner = null; const job = request(r); if (noWait) void job.catch(() => {}); else await job; } }, async cookie() { return cookie; }, async close() {}, + async ownerInput(_value, input) { await beforeInput?.(input); input.guard(); physicalInputs++; if (nextOwner) { const r = nextOwner; nextOwner = null; const job = request(r); if (noWait) void job.catch(() => {}); else await job; } }, async cookie() { return cookie; }, async close() { await onClose?.(); }, }; - return { responses, set noWait(value: boolean) { noWait = value; }, set beforeInput(fn: ((input: EngineInputContext) => Promise) | null) { beforeInput = fn; }, set nextOwner(r: BrowserRequest) { nextOwner = r; }, get physicalInputs() { return physicalInputs; }, factory: async (o: EngineOptions) => { options = o; return engine; }, make, request, set afterNavigate(r: BrowserRequest) { afterNavigate = r; }, set next(r: BrowserRequest) { next = r; }, set cookie(v: string | null) { cookie = v; }, set blockRead(v: (() => Promise) | null) { blockRead = v; }, get sent() { return sent; }, get denied() { return denied; }, get frames() { return frames; } }; + return { responses, set onClose(value: (() => void | Promise) | null) { onClose = value; }, set noWait(value: boolean) { noWait = value; }, set beforeInput(fn: ((input: EngineInputContext) => Promise) | null) { beforeInput = fn; }, set nextOwner(r: BrowserRequest) { nextOwner = r; }, get physicalInputs() { return physicalInputs; }, factory: async (o: EngineOptions) => { options = o; return engine; }, make, request, set afterNavigate(r: BrowserRequest) { afterNavigate = r; }, set next(r: BrowserRequest) { next = r; }, set cookie(v: string | null) { cookie = v; }, set blockRead(v: (() => Promise) | null) { blockRead = v; }, get sent() { return sent; }, get denied() { return denied; }, get frames() { return frames; } }; } async function setup(mode: 'static' | 'general' = 'static', clock?: BrowserClock) { const server = browserSite(), engine = fake(); cleanup.push(() => server.close()); @@ -37,6 +38,16 @@ async function setup(mode: 'static' | 'general' = 'static', clock?: BrowserClock } const post = (url: string, data: string): BrowserRequest => ({ method: 'POST', url, contentType: 'application/x-www-form-urlencoded', bodyBase64: Buffer.from(data).toString('base64'), navigation: true }); +test('close initiates native shutdown before awaiting its pending input and never permits that input to reach the service', async () => { + const f = await setup(), entered = Promise.withResolvers(), native = Promise.withResolvers(), closed = Promise.withResolvers(); + f.engine.beforeInput = async () => { entered.resolve(); await native.promise; }; + f.engine.onClose = () => { closed.resolve(); native.resolve(); }; + f.engine.next = post(f.server.origin + '/edit', 'note=Must+not+leave'); + const pending = f.execute({ kind: 'click', target: 'e1_1' }); await entered.promise; + const closing = f.gateway.close(); await closed.promise; await closing; + expect((await pending).state).not.toBe('ok'); expect(f.engine.physicalInputs).toBe(0); expect(f.server.received.some(row => row.path === '/edit')).toBe(false); +}); + describe.each(['static', 'general'] as const)('protected browser %s mode', mode => { test('ordinary navigation/read uses real read claims without per-page approval', async () => { const f = await setup(mode); expect(f.engine.sent).toBe(1); const result = await f.execute({ kind: 'read' }); expect(result.state).toBe('observed'); diff --git a/tests/s16-browser-conformance.test.ts b/tests/s16-browser-conformance.test.ts index 678c9644..de162653 100644 --- a/tests/s16-browser-conformance.test.ts +++ b/tests/s16-browser-conformance.test.ts @@ -33,6 +33,18 @@ async function scenario(mode: 'static' | 'general', delayMs = 0) { } realBrowser('S16 protected modern-browser conformance', () => { + for (const mode of ['static', 'general'] as const) test(`${mode}: denied download and redirect settle before immediate fresh navigation`, async () => { + const s = await scenario(mode, 250); + try { + for (const name of ['Download', 'Redirect']) { + await s.navigate('/clean-task'); + expect((await s.run({ kind: 'click', target: await s.find(name) })).state).toBe('unsupported'); + await s.navigate('/clean-task'); expect(observation(await s.run({ kind: 'read' })).text).toContain('Website task'); + } + expect(s.server.received.some(row => row.path === '/download' || row.path.startsWith('/unknown-effect'))).toBe(false); + } finally { await s.close(); } + }, 60000); + for (const mode of ['static', 'general'] as const) test(`${mode}: takeover settles a cancelled held navigation before immediate fresh input`, async () => { const s = await scenario(mode, 250); try { From 038a18b9f9b5e7a1f7fa385f730214e756d5c7bc Mon Sep 17 00:00:00 2001 From: Chayapat Sriwattanachote Date: Wed, 18 Nov 2026 10:16:43 +0700 Subject: [PATCH 09/10] docs(browser): select reference-proven protected mediation contract --- docs/adr/0079-s16-modern-browser-mediation.md | 14 ++-- docs/contracts/s15-protected-browser-v1.md | 4 +- docs/contracts/s16-modern-browser-v1.md | 18 ++--- .../s16-protected-browser-reference.md | 72 +++++++++++++++++++ 4 files changed, 92 insertions(+), 16 deletions(-) create mode 100644 docs/evidence/s16-protected-browser-reference.md diff --git a/docs/adr/0079-s16-modern-browser-mediation.md b/docs/adr/0079-s16-modern-browser-mediation.md index 4fda0c8c..aa14abbe 100644 --- a/docs/adr/0079-s16-modern-browser-mediation.md +++ b/docs/adr/0079-s16-modern-browser-mediation.md @@ -1,18 +1,20 @@ --- -status: selected for bounded prototype; physical guest-root and product activation acceptance pending +status: selected protected-browser feasibility contract; reference guest-root and dispatch-crash evidence recorded; product activation pending date: 2026-11-05 scope: BROW16-01A; S16-AC06/07; FR-07/10/17/18/35/36/37/38/40/41; NFR-07/10/11/14 --- # Modern browser mediation on the protected host -Keep the existing protected Chromium `general` engine and request broker as the first S16 candidate. Demonstrate an authenticated task whose UI requires real JavaScript, fetch and XMLHttpRequest before a native form exists. Compare its actual server effects with a static-mode negative control. The prototype uses production engine/POLICY ports, disposable profiles and controlled HTTP, not an offline DOM or a screenshot-only mock. +Keep the existing protected Chromium `general` engine and request broker as the selected S16 sensitive-site feasibility architecture. An authenticated task requires real JavaScript, fetch and XMLHttpRequest before its native form exists; the static-mode negative control cannot complete it. The probe uses production engine/POLICY ports, disposable profiles and controlled HTTP. [The reference evidence](../evidence/s16-protected-browser-reference.md) records actual separate-VM guest-root attempts and process-crash/read-back results. This selection does not activate general mode in the provisioned runtime. + +S16-D09 ([ADR 0084](0084-s16-grok-style-default-autonomy.md)) narrows this boundary to sensitive sites. Public and owner-marked trusted sites use the working VM browser delivered by #410/[ADR 0092](0092-s16-agent-use-of-the-working-computer-browser.md); guest access to trusted sessions is the accepted residual. Their product path does not inherit the protected-browser claims below. ## Alternatives and source audit | Candidate | Useful capability | Boundary/cost | Decision | | --- | --- | --- | --- | -| Existing protected general Chromium + host broker | JS rendering, opaque observed targets, actual request bytes, immutable POLICY action/approval/claim, transient owner login, unknown/reconcile continuity | Provisioned runtime is still static; asynchronous mutation attribution, generic safe authenticated observations, downloads and guest-root placement need additional proof | Select for bounded conformance before #409 rollout | +| Existing protected general Chromium + host broker | JS rendering, opaque observed targets, actual request bytes, immutable POLICY action/approval/claim, transient owner login, unknown/reconcile continuity | Separate-controller reference placement and process-crash recovery are demonstrated; provisioned runtime is still static. Asynchronous mutation attribution, generic safe authenticated observations, downloads and installation-specific placement remain delivery obligations | Select bounded contract for #409 implementation | | Rakazo live computer browser | Shared graphical Chrome and CDP page operations on the Bot computer, with explicit fallback to computer input | Jit's root-administrable guest cannot receive a sensitive reusable session/CDP endpoint. Moving the endpoint alone supplies no request semantics or protected approval proof | Reuse experience/adapter ideas; do not copy the guest CDP/session placement | | Separate remote browser service | Explicit process/VM/host boundary and centralized lifecycle | Adds authentication, network protocol, deployment and recovery ownership while still needing request/effect semantics; does not itself solve JS mutation attribution | Retain as a placement alternative if real host proof rejects protected local custody | @@ -32,10 +34,12 @@ The exact selected native form/anchor request may become an immutable held effec The current native binding does not attribute non-document fetch/XHR mutation, even when its endpoint semantics are known. An input timing window cannot supply that authority. #409 must deliver a reviewed protected intent-to-request binding for representative asynchronous applications, or a simpler alternative with equivalent semantics; copying a raw CDP tool is not that contract. Until implemented, report the exact unsupported reason rather than offering an approval that could not make the request safe. This is an unresolved delivery requirement, not a scope reduction of S16. -Protected handlers must classify exact URL/query/body, private data, actual recipient and action class; unknown methods/paths/effects refuse. Generic public rendering can use reviewed destination/content rules without a custom business API, but safe authenticated observation and business outcomes need evidence. #433/#407 own guarded file transfer/collection; browser downloads are not silently enabled. #410 owns authored graphical takeover/client lifecycle; this prototype exercises the existing real transient owner port, with no new UI design. +Protected handlers must classify exact URL/query/body, private data, actual recipient and action class; unknown methods/paths/effects refuse. Generic public rendering can use reviewed destination/content rules without a custom business API, but safe authenticated observation and business outcomes need evidence. #433/#407 own guarded file transfer/collection; browser downloads are not silently enabled. #410 delivered working-computer graphical takeover/client lifecycle. Protected modern-browser integration remains #409; this probe exercises the existing real transient owner port, with no new UI design. ## Recovery, compatibility and acceptance Keep current continuity armed before dispatch. A crash or lost response remains unknown and reconcile-only until protected service evidence resolves the exact action. Restart cannot reconstruct a callable paused request or retry the input. Cancellation/takeover fences new input but cannot claim to recall a released transport. Owner statements do not verify remote outcomes. -This slice changes no runtime default, installed policy, profile/store schema, existing receipts or owner-host configuration. #402's independent memory worktree is untouched. The controlled probe supplies no live account/physical Linux proof. #408 remains open until its review and remaining acceptance evidence are satisfied; #397/#392 cannot close from this bounded result. Exact conformance results and physical proof obligations belong in the linked contract and implementation PR. +An absent reconciliation verifier returns a fulfilled unknown read result: the read lane settles while the original effect remains uncertain, charged and non-replayable. A later protected verifier may read actual service state without resending the effect. Native cancellation retains the input lease until the actual browser operation/frame settles; otherwise an old denied navigation can interrupt the next generation. Closing the browser first unblocks pending renderer input while broker/continuity custody remains until its scopes settle. Renderer closure does not recall an already dispatched HTTP effect. + +This slice changes no runtime default, installed policy, profile/store schema, existing receipts or owner-host configuration. Existing independent worktrees are untouched. The reference proof covers a Linux controller and separate root-administrable QEMU working VM managed from macOS, with synthetic accounts and actual protected ports. It does not certify default nested Linux KVM, a hypervisor/browser exploit boundary, live accounts, power-loss durability or owner-host adoption (#431/#432). #408 delivers this bounded contract and evidence for review; #409 retains asynchronous intent/request binding and protected product integration, and #397/#392 remain open. Exact tested revisions, builds, results and remaining gates are in the linked evidence record and implementation PR. diff --git a/docs/contracts/s15-protected-browser-v1.md b/docs/contracts/s15-protected-browser-v1.md index 8be04a23..ff727247 100644 --- a/docs/contracts/s15-protected-browser-v1.md +++ b/docs/contracts/s15-protected-browser-v1.md @@ -20,7 +20,7 @@ Agent operations are the closed `BrowserOperation` union: navigate, read, find, Text is capped at 32 KiB with explicit truncation, observations expose at most 64 controls, screenshots at 2 MiB and request bodies at 64 KiB. URLs/ordinary input are capped at 4096 bytes. Captures exclude field values, hidden DOM and script text, and refuse password/2FA/file surfaces. A trusted safe-surface policy remains mandatory: field masking cannot certify arbitrary authenticated pages. The actual observed URL must match the admitted safe document. Each network read and each text/image capture has its own policy read claim and final current-authority/publication checks; output cannot renew a lease or grant an effect. -Input completion waits for native command acknowledgement, the expected navigation (including Chromium frame-stop after a refused request), and every intercepted request actually started by that input. A protected 30-second operation deadline reports an unknown outcome rather than inferring completion from elapsed time. `execute` and `resume` accept an optional AbortSignal; final input guards run after readiness waits and immediately before protocol enqueue, and cancellation suppresses later request release and result publication. If an effect's broker request has already been released, cancellation/deadline never aborts that transport or retries it: the original policy claim/capacity and reconcile-only continuity remain until actual settlement. Graceful close waits for retained transports instead of treating cancellation as proof of settlement. +Input completion waits for native command acknowledgement, the expected navigation (including Chromium frame-stop after a refused request), and every intercepted request actually started by that input. A protected 30-second operation deadline reports an unknown outcome rather than inferring completion from elapsed time. `execute` and `resume` accept an optional AbortSignal; final input guards run after readiness waits and immediately before protocol enqueue, and cancellation suppresses later request release and result publication. If an effect's broker request has already been released, cancellation/deadline never aborts that transport or retries it: the original policy claim/capacity and reconcile-only continuity remain until actual settlement. Graceful close starts native browser shutdown to settle pending renderer operations, then waits for retained scopes/transports before closing broker/continuity custody; browser closure is not proof of remote effect settlement. JSON results distinguish observed content, image bytes, held exact action, denied/unsupported reason, unknown outcome and completed input. Completed input does not assert a remote business outcome. Page content is untrusted evidence. The Schway tool uses only the public `ToolDefinition` surface, with its work closure supplied by the host. @@ -59,7 +59,7 @@ Takeover advances the current durable generation, fences agent input/publication The host-only `BrowserWork.settled()` waits for the current lease's already-started native/network scopes. It neither dispatches nor renews authority, and old leases cannot wait on or release a newer lease. The effects/CHAT bridge uses this completion for cancellation/deadline cleanup and releases only after actual settlement; it reaps denied/stopped actions before a new browser admission. Cleanup aborts paused input, never an already-released broker transport. -The additive [effect contract](s15-effects-v1.md) supplies one controlled record-service verifier. `BrowserSitePolicy.reconcileEffect(request, context)` is optional trusted read-only code and calls the original recovery context before actual I/O. `BrowserOwner.reconcile` invokes POLICY's authenticated charged recovery lane and clears only the matching continuity record after conclusive service evidence. Missing verifiers remain unsupported; owner statements never clear uncertainty. +The additive [effect contract](s15-effects-v1.md) supplies one controlled record-service verifier. `BrowserSitePolicy.reconcileEffect(request, context)` is optional trusted read-only code and calls the original recovery context before actual I/O. `BrowserOwner.reconcile` invokes POLICY's authenticated charged recovery lane and clears only the matching continuity record after conclusive service evidence. Missing verifiers or unsupported retained request semantics return a fulfilled unknown read result: the recovery read lane settles while the original effect remains uncertain and charged, allowing a later protected verifier without resending the effect. Owner statements never clear uncertainty. [The S16 reference proof](../evidence/s16-protected-browser-reference.md) exercises actual process loss and service read-back through these ports. A small protected SQLite record outside the browser profile retains monotonic input generation and an armed/uncertain exact action reference. It is armed before action dispatch; crash/restart cannot clear it or reconstruct a callable request context. Unknown business outcomes remain reconcile-only and block fresh effect retries. Owner statements are not verification. The real policy ledger remains the authority for exact payloads, claims, approvals, nonrefundable budget charges and remote observations. Generic business reconciliation is unsupported until its protected verifier exists; opening a new browser/profile is not a retry mechanism. diff --git a/docs/contracts/s16-modern-browser-v1.md b/docs/contracts/s16-modern-browser-v1.md index 1034ba23..7d1c779e 100644 --- a/docs/contracts/s16-modern-browser-v1.md +++ b/docs/contracts/s16-modern-browser-v1.md @@ -1,6 +1,6 @@ # s16-modern-browser/v1 -Status: bounded conformance profile for #408; selected by [ADR 0079](../adr/0079-s16-modern-browser-mediation.md). It extends the evidence for [s15-protected-browser/v1](s15-protected-browser-v1.md), revision 2, without adding an implemented wire API or enabling the provisioned runtime's general mode. This is not full S16-AC06/07 acceptance. +Status: selected bounded feasibility profile for #408, with [reference evidence](../evidence/s16-protected-browser-reference.md); selected by [ADR 0079](../adr/0079-s16-modern-browser-mediation.md). It extends the evidence for [s15-protected-browser/v1](s15-protected-browser-v1.md), revision 2, without adding an implemented wire API or enabling the provisioned runtime's general mode. This is not full S16-AC06/07 acceptance. Under S16-D09 this contract applies to sensitive sites; public and owner-marked trusted sites use the working VM browser and its explicitly accepted session-custody residual ([ADR 0084](../adr/0084-s16-grok-style-default-autonomy.md), [ADR 0092](../adr/0092-s16-agent-use-of-the-working-computer-browser.md)). ## Owning interfaces @@ -29,23 +29,23 @@ Explicit general-mode navigation now uses the same bounded `networkidle` readine | Timers/beacons/background | No inherited input authority; unknown/private egress cannot use public-read labels | Controlled attack fixture reaches no mutation endpoint | | WebSocket/EventSource/service workers/frames/workers | WebSocket close, SW block, restrictive CSP and broker/no active request support | Existing actual-engine attack suite plus deterministic schema/network cases | | Redirect/download/upload | Broker refuses redirects/downloads; engine refuses file input, popup target and download attribute | No follow-up destination, file/partial candidate or alternate uncontrolled input | -| Raw CDP/BiDi/cookies/protocol/socket | No such work API; Chromium control is a host-private pipe; fallback proxy never forwards | Finite-tool/API tests; **physical guest-root/network/mount attempts remain mandatory before activation** | -| Crash after dispatch | Protected continuity armed first, unknown retains ledger claim/budget; no reconstructed paused request | Existing continuity/reconcile fixtures; physical crash at dispatch and real read-back remain pending | +| Raw CDP/BiDi/cookies/protocol/socket | No such work API; Chromium control is a host-private pipe; fallback proxy never forwards | Actual reference guest-root file/mount/process/socket attempts plus external manager/network inventory passed; repeat for the actual installation before activation | +| Crash after dispatch | Protected continuity armed first, unknown retains ledger claim/budget; no reconstructed paused request | Actual controller/browser SIGKILL after a separate service receives the POST; restart stays unknown until protected HTTP read-back verifies exact bytes/count, without replay | Current JS mutations are an implementation gap, not a decision to exclude modern apps from the product. A proposed next contract must bind selected intent, exact request bytes/recipient, current private-source ceiling, generation, one-use nonce, expiry and final commit outside the page/guest. Its semantics cannot be issued by the page/model, inferred from timing or authorized by an unknown payload card. This paragraph is **PROPOSED** input for #409, not an exported method/schema accepted by the current engine. ## Isolation proof and activation gate -The controlled HTTP fixture uses a test-only DNS/dial seam: the loopback site resolves to a public-classified stand-in, and only that checked address dials back to the local server. Production refuses loopback/private destinations. Real Chromium, HTTP bytes, protected cookies, POLICY holds and resulting server state are actual; the fixture is not a public website/account or Linux guest-root demonstration. +The controlled HTTP fixture uses a test-only DNS/dial seam: the loopback site resolves to a public-classified stand-in, and only that checked address dials back to the local server. Production refuses loopback/private destinations. Real Chromium, HTTP bytes, protected cookies, POLICY holds and resulting server state are actual; the fixture is not a public website/account. Separate physical guest-root attempts and their external inventory basis are recorded in the linked reference evidence. Before enabling authenticated general browsing on an owner host, record the exact shipped controller/VM/browser builds and prove from guest root: no profile/cookie or continuity path is mounted/exported; no raw control port/pipe or owner endpoint is reachable; direct shell/socket/proxy/alternate DNS/IPv6/QUIC/WebRTC routes cannot bypass the external boundary; all mediated new-recipient requests receive final DATA15/POLICY checks. Destroy/restart the guest and browser at dispatch barriers and resolve unknown outcomes only through protected service read-back. Capture hashes/outcomes, never sessions or login input. #409/#431 own implementation/live evidence and #432 exact host adoption. Do not infer these facts from this fixture or controller file mode 0700. -## Compatibility and evidence status +Cancellation returns a fenced work result promptly, but retains the native input lease until original browser I/O and any started navigation finish. Stale targets cannot resume after takeover. Browser closure begins before waiting for those input scopes, so actual renderer shutdown can settle them; broker/continuity ownership remains until its scopes finish. This is distinct from remote effect settlement. Missing/unsupported reconciliation semantics return a settled unknown read, leaving original effect uncertainty and charges intact so a later protected read-only verifier can run. Owner statements, page text and controller restart cannot clear it. -The bounded candidate changes no schema, runtime default, standing policy or owner-host configuration. Existing static provisioned behavior remains. No private Schway import, replacement provider loop, live credential, new dependency or copied upstream code is introduced. The authored S16 computer/takeover UI remains #409/#410; this non-UI probe uses actual host ports and keeps current product loading/unsupported/unknown facts intact. +## Compatibility and evidence status -`tests/s16-browser-conformance.test.ts` runs four opt-in real Chromium cases: static negative control, actual authenticated fetch/XHR hydration and edited exact single-dispatch form, changed recipient/new action, actual intercepted JS mutation and submit-time substitution refusal, and an actual dispatched but unverified result staying unknown without replay. Test-only traces record paths/navigation/send-or-deny, never cookies or login input. The controlled service receives the exact approved body once. +The bounded candidate changes no schema, runtime default, standing policy or owner-host configuration. Existing static provisioned behavior remains. No private Schway import, replacement provider loop, live credential, new dependency or copied upstream code is introduced. #410 delivered the working-computer/takeover UI; #409 retains protected modern-browser product integration. This non-UI probe uses actual host ports and keeps current product loading/unsupported/unknown facts intact. -Local engine evidence: macOS arm64, Google Chrome `156.0.8078.80`, Playwright `1.64.1`, Bun `1.4.2`. The four cases passed (56 assertions), together with four existing controlled real-engine regressions (134 assertions) covering both modes, owner login/TOTP, exact effect holds, background/redirect/download/popup denial and DNS/loopback rebinding. The external public Excalidraw case was filtered out. This installed Chrome evidence is not the provisioned Linux Chromium release or physical guest proof. +`tests/s16-browser-conformance.test.ts` runs eight opt-in real Chromium cases: both modes' immediate navigation after denied download/redirect and cancelled held navigation; static negative control; actual authenticated fetch/XHR hydration and edited exact single-dispatch form with changed recipient/new action; actual intercepted JS mutation/submit-time substitution refusal; and a dispatched but unverified result remaining unknown. `tests/s16-browser-crash.test.ts` adds actual process SIGKILL and read-back. Test-only traces record paths/navigation/send-or-deny, never cookies or login input. The controlled service receives the exact approved body once. -Commands: `JIT_BROWSER_LIVE=1 JIT_BROWSER_EXECUTABLE= bun test tests/s16-browser-conformance.test.ts --timeout 60000`; existing controlled regression: `JIT_BROWSER_LIVE=1 JIT_BROWSER_EXECUTABLE= bun test tests/s15-browser-live.test.ts -t 'actual navigation|approved name' --timeout 60000`. Deterministic suite/package/typecheck results and tested head are recorded in the PR. General-browser product parity, physical guest-root isolation, crash/read-back on a real managed host and live account/device acceptance remain unproven here. +At source revision `9b5a31e1d007001415b7d91cb6c38bcfcb0f8bad`, these nine cases passed on macOS arm64 and Linux arm64 (104 assertions each). Four controlled existing real-engine regressions also passed on each platform (134 assertions each), covering both modes, owner login/TOTP, exact effect holds, background/redirect/download/popup denial and DNS/loopback rebinding. The external public Excalidraw case was filtered out. The paired reference-host runner passed all nine physical cases, including live authenticated dynamic work and guest-root attempts while its protected profile/cookies were present. See the evidence record for exact builds, hashes, commands and limits; final PR checks record any later revision. General-browser product parity, live account/device acceptance and exact owner-host adoption remain pending. diff --git a/docs/evidence/s16-protected-browser-reference.md b/docs/evidence/s16-protected-browser-reference.md new file mode 100644 index 00000000..20b5fedf --- /dev/null +++ b/docs/evidence/s16-protected-browser-reference.md @@ -0,0 +1,72 @@ +# S16 protected-browser reference proof + +Date: 2026-11-18. Scope: #408 / BROW16-01A; [ADR 0079](../adr/0079-s16-modern-browser-mediation.md), [s16-modern-browser/v1](../contracts/s16-modern-browser-v1.md). Requirements: S16-AC06/07; FR-07/10/17/18/35/36/37/38/40/41; NFR-07/10/11/14. Source revision: `9b5a31e1d007001415b7d91cb6c38bcfcb0f8bad`. Later PR revisions must distinguish code changes from documentation and record their own checks. + +This is a bounded sensitive-site feasibility proof. S16-D09 leaves public/trusted browsing in the working VM, with its accepted trusted-session residual. It does not enable protected general mode in the provisioned runtime or close #397/#392. #409 owns the remaining protected product integration and asynchronous intent/request binding; #431/#432 retain live account/device and owner-host adoption evidence. + +## Actual topology and builds + +A macOS arm64 management host ran a separate Linux arm64 controller VM and a separate root-administrable QEMU working VM. The controller owned Chromium, POLICY, protected profiles/continuity and the actual authenticated owner port. The working VM had root, sudo and Docker. Its external manager used QEMU restricted networking, IPv6 disabled and no filesystem exports, host credentials or agent forwarding. An authenticated loopback management relay carried the test adapter's finite operations; the guest did not receive its management credential. The controller was not inside the working guest. + +This optional reference topology is not the target default nested Linux KVM deployment. Guest-reported negative probes alone do not prove isolation: the receipt also captured the external manager configuration/network inventory and positive controller canaries. It does not attest against a hypervisor or browser-engine exploit, other installations, hardware power loss or live owner credentials. + +| Component | Observed build / SHA-256 | +| --- | --- | +| Linux controller | aarch64, kernel `6.8.0-147-generic` | +| Bun | `1.4.2`; `616f267a34278ff5ac282df37ffdfba1d7141f4f6926bca99af2cd6ef3ad32b1` | +| Linux Chrome for Testing | `156.0.8078.4`; `2b3a2bb9c4308ce74cb680dcd50305cfae1f79589305dc92b993f876b5a94f65` | +| Playwright | `1.64.1` | +| Lima | `2.2.1` | +| QEMU | `11.1.3`; `a7ace1986bb2af7e706402c3bd36b8450a463409e17a707a4c5a078cc521aba1` | +| Restricted QEMU wrapper | `875a5bef3358ad59e2ee6cfeb3a7aa41ed57da5f656da9472f7e8c4a64664d07` | +| Controller configuration | `84b18fa4cb9fd0ab6eea9425745eba4271332dc212c2aec2d9167de110dcd197` | +| Working-VM configuration | `a68ec48443ca8ad317727a507d8d03bc69a0a479e9acf026d6b1a21ae43fcb7e` | +| Public Schway artifact | `39194f7`; `58c80215fa0d8330c73c07674038ae50aed5dd5e69cc9d95e5d421e689091b8a` | + +The supplied Linux executable was observed directly, not provisioned by this change. The macOS native run used installed Google Chrome `156.0.8078.80`, Bun `1.4.2` and Playwright `1.64.1`. Configuration hashes bind the reference inventory; installation addresses, instance identifiers, paths and raw receipts stay in ignored `.local` records. No owner credential, model inference, paid service or real payment was used. Login used ephemeral synthetic password/TOTP through the actual protected owner port. + +## Observed outcomes + +The reference runner `ops/evidence/s15-arm64.ts` archived the clean source revision, executed the actual composition on the Linux controller and returned **PASSED, nine cases**, then stopped its disposable working VM. The surrounding run stopped the controller too; both final states were verified stopped. Baseline recovery snapshots were retained. + +| Case | Actual evidence | +| --- | --- | +| Guest administration | Actual guest root session, rather than an emulated root flag | +| External egress boundary | Guest firewall flush did not remove the external manager's proxy-only restriction | +| Protected paths | Guest attempts plus external no-export/network inventory | +| Snapshot recovery | Guest marker restored; protected POLICY usage unchanged; recovery is not prevention | +| Authenticated dynamic task | Real password/TOTP login, real fetch and XHR hydration, live field edit, held exact request, one verified service effect/body hash, second resume unsupported | +| Live protected-browser boundary | Exact kernel argv showed pipe-only Chromium control, no TCP debug option/control discovery file; persisted cookie file present. Guest root could not open cookie/canary paths, see the controller browser, find shared mounts, mount a 9p share or reach tested controller/control ports. Controller canary was positive; guest attempts produced zero canary requests | +| Communication hold | Controlled service received no held effect before approval | +| Browser bypass | Background/beacon/socket/events/popup/frame/hidden-submit/worker attack endpoints not reached | +| Payment policy | Synthetic payment remained held; no real settlement | + +While the real profile was live, `ops/evidence/s16-browser-boundary.ts` performed the file/process/mount/socket attempts through the actual VM backend. It combines those negative results with protected process facts and the manager inventory. The finite tested probes do not constitute a universal exploit search. Chromium's deny-only proxy, disabled protocols and semantic request broker remain separate enforcement layers; production still refuses private/loopback destinations. The controlled test alone uses explicit DNS/fixed-dial injection to reach its local HTTP fixture. + +Native conformance ran on both platforms at the source revision above: + +| Suite | macOS arm64 | Linux arm64 | +| --- | --- | --- | +| `s16-browser-conformance.test.ts` + `s16-browser-crash.test.ts` | 9 pass, 0 fail, 104 assertions | 9 pass, 0 fail, 104 assertions | +| Controlled `s15-browser-live.test.ts` | 4 pass, 0 fail, 134 assertions | 4 pass, 0 fail, 134 assertions | + +The static negative control cannot create or submit the authenticated JS task. General mode obtains real fetch/XHR responses, edits the form and dispatches the exact approved bytes once. Changing recipient/body requires new authority; JS mutation and submit-time substitution cannot borrow native input. Both modes can immediately navigate after denied download/redirect and after takeover cancels a held navigation, without sleeps, retries or extra approval. + +The crash fixture keeps its HTTP service in the parent process. After that service actually receives the POST and withholds its response, it SIGKILLs the controller worker and its protected browser. A new controller opens the original POLICY/continuity state. The action remains unknown, cannot resume or replay, and an owner statement does not clear it. Actual protected HTTP read-back verifies the exact body hash and count of one before uncertainty clears; a fresh navigation then works. This is process-loss recovery, not a machine power-loss test. + +The first recovery read without a verifier now fulfills with unknown rather than leaving the reconciliation read lane uncertain. The original effect claim/charge remains uncertain. A later service verifier can therefore run without retrying the original effect. Native settlement also retains its input lease until real pending I/O/frame completion; closing the native browser unblocks pending renderer operations before gateway shutdown waits for scopes. None of these lifecycle steps claims to recall an already dispatched request. + +## Reproduction and remaining gates + +Use the existing opt-in reference runner only with an explicitly configured disposable controller/working VM; see [the runner guide](../../ops/evidence/README.md). `JIT_S15_ARM64_EVIDENCE=1 bun run s15:evidence:arm64` requires a clean source revision and records build/configuration facts. It is not part of ordinary CI or authorization to change a real owner host. + +On each supplied native executable: + +```sh +JIT_BROWSER_LIVE=1 JIT_BROWSER_EXECUTABLE= bun test --timeout 60000 tests/s16-browser-conformance.test.ts tests/s16-browser-crash.test.ts +JIT_BROWSER_LIVE=1 JIT_BROWSER_EXECUTABLE= bun test --timeout 60000 tests/s15-browser-live.test.ts -t 'actual navigation|approved name' +``` + +The external public Excalidraw case is intentionally filtered out. Deterministic, package, typecheck and final-head CI/review results belong in the PR. Earlier failed diagnostic runs remain in private receipts and are not counted as passing evidence. + +#409 must implement reviewed attribution for asynchronous mutations and the protected modern-browser product path; unknown semantics continue to refuse. Guarded downloads/file transfer remain under their owning file contracts. Repeat isolation/network/custody checks for the exact shipped deployment, and obtain real account/device/host acceptance through #431/#432. No schema, installed policy, S14 default, S15 opt-in selection or historical private scope is migrated here. The Rakazo comparison/provenance remains pinned in ADR 0079; this slice copies no upstream source/assets and adds no dependency. From c5f9a6f92b34873d8373df9607e6ac5909cb8172 Mon Sep 17 00:00:00 2001 From: Chayapat Sriwattanachote Date: Wed, 18 Nov 2026 10:38:53 +0700 Subject: [PATCH 10/10] perf(skills): reuse primitive validation within one secret-registry revision --- src/s16/skills/encoding.ts | 12 +++++++++++- src/security/secret-fingerprints.ts | 5 +++++ tests/s16-skills-service.test.ts | 11 +++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/s16/skills/encoding.ts b/src/s16/skills/encoding.ts index 70499fae..a9d00844 100644 --- a/src/s16/skills/encoding.ts +++ b/src/s16/skills/encoding.ts @@ -1,15 +1,25 @@ import { createHash } from "node:crypto"; import { canonical, fail } from "../../s15/policy/validation"; +import { registeredSecretRevision } from "../../security/secret-fingerprints"; /** Package-only JSON envelope: base64 for 2 MiB plus retained instruction bodies/metadata fits within an 8 MiB journal envelope. * Primitive validation, secret refusal, exact ordering and depth/container limits match POLICY. POLICY's * own 128 KiB bound remains unchanged; no caller can supply a larger limit to its canonicalizer. */ export function canonicalSkill(value: unknown): string { const seen = new Set(), parts: string[] = []; let bytes = 0; + // Repeated resource bytes are common in maximum-sized folders. Reuse only synchronous primitive + // validation at the same secret-registry revision; never retain validation across calls or new secrets. + const strings = new Map(); let secrets = registeredSecretRevision(); + const primitive = (value: unknown): string => { + if (typeof value !== "string") return canonical(value); + const current = registeredSecretRevision(); if (current !== secrets) { strings.clear(); secrets = current; } + let encoded = strings.get(value); if (encoded === undefined) { encoded = canonical(value); strings.set(value, encoded); } + return encoded; + }; const append = (part: string) => { bytes += Buffer.byteLength(part); if (bytes > 8 * 1024 * 1024) fail("input_too_large"); parts.push(part); }; const walk = (value: unknown, depth: number): void => { if (depth > 16) fail("invalid_shape"); - if (value === null || typeof value !== "object") { append(canonical(value)); return; } + if (value === null || typeof value !== "object") { append(primitive(value)); return; } if (seen.has(value)) fail("invalid_shape"); seen.add(value); if (Array.isArray(value)) { if (value.length > 256 || Reflect.ownKeys(value).length !== value.length + 1) fail("invalid_shape"); diff --git a/src/security/secret-fingerprints.ts b/src/security/secret-fingerprints.ts index 524d009d..fc8ef646 100644 --- a/src/security/secret-fingerprints.ts +++ b/src/security/secret-fingerprints.ts @@ -16,6 +16,10 @@ const modulus = 67_108_859, base = 131; const minimumLength = 8; /** length → rolling hash → HMAC hex digests */ const registry = new Map> }>(); +let revision = 0; + +/** Process-local invalidation token for synchronous validation caches. Contains no secret/fingerprint value. */ +export const registeredSecretRevision = (): number => revision; const mac = (text: string) => createHmac("sha256", key).update(text, "utf8").digest("hex"); function rolling(text: string, start: number, length: number): number { @@ -42,6 +46,7 @@ function add(piece: string): void { /** Registers one secret value (values shorter than 8 characters are ignored). The value itself is not retained. */ export function registerSecretFingerprint(value: string): void { if (typeof value !== "string") return; + revision++; add(value); if (value.includes("\n")) for (const line of value.split(/\r?\n/)) if (line.trim().length >= 16) add(line.trim()); } diff --git a/tests/s16-skills-service.test.ts b/tests/s16-skills-service.test.ts index 470ce562..9380ea01 100644 --- a/tests/s16-skills-service.test.ts +++ b/tests/s16-skills-service.test.ts @@ -11,6 +11,7 @@ import type { SkillCommand, SkillRecord, SkillUse } from "../src/s16/skills/type import { githubSkillFixture, commit } from "./fixtures/s16-skills"; import { canonicalSkill, skillCommandHash } from "../src/s16/skills/encoding"; import { canonical } from "../src/s15/policy/validation"; +import { registerSecretFingerprint } from "../src/security/secret-fingerprints"; const cleanups: (() => Promise)[] = []; afterEach(async () => { for (const close of cleanups.splice(0).reverse()) await close(); }); @@ -72,6 +73,16 @@ for (const kind of ["skill.import", "skill.update"] as const) test(`revocation f } finally { resume.resolve(); await pending; } }); +test("package encoding never reuses validation across new secrets, including registration during one traversal", () => { + const later = `later_secret_${uid()}`, repeated = `traversal_secret_${uid()}`; + expect(canonicalSkill([later, later])).toBe(canonical([later, later])); + registerSecretFingerprint(later); expect(() => canonicalSkill([later, later])).toThrow("credential_content_refused"); + // A proxy trap can run synchronous application code while an unknown value is inspected. It cannot + // make a newly registered secret borrow the earlier string's validation in this same traversal. + const nested = new Proxy({ value: repeated }, { ownKeys(target) { registerSecretFingerprint(repeated); return Reflect.ownKeys(target); } }); + expect(() => canonicalSkill({ first: repeated, second: nested })).toThrow("credential_content_refused"); +}); + test("package encoding preserves small command identities and accepts a full 2 MiB folder without changing POLICY's limit", async () => { const h = await fixture(), input = folder(), small = { contract: "s16-skill-command/v1", requestId: uid(), kind: "skill.import", input: folder() }; expect(canonicalSkill(small)).toBe(canonical(small)); expect(skillCommandHash(small)).toBe(digest("s16.skills.command.v1", small));