From c5ddaf31c95c9ba5e3a734b975e5d49ebc246d9f Mon Sep 17 00:00:00 2001 From: gcharang <21151592+gcharang@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:17:32 +0400 Subject: [PATCH 1/7] feat: refuse payment actions, signal security checks, add page_request The driver refuses click, Enter, NumpadEnter, Space and type with submit on the final order-placement control or its form (cash on delivery included, English and Arabic), and typing into cc-* fields or payment-provider frames, before any input event (payment_refused). Captures and input checks report CAPTCHA and verification-code pages as security_check. page_request makes one packaged, credentialed, same-origin fetch inside the lease's origins: GET by default, writes only where the lease policy lists the exact origin, method and path, redirects refused, JSON capped at 32 KiB. Co-Authored-By: Claude Opus 5.5 --- .../page-request-and-payment-refusal.md | 12 + apps/backend/src/index.ts | 2 +- apps/backend/src/session.ts | 58 +++- apps/backend/src/types.ts | 2 +- apps/backend/test/session.test.ts | 58 ++++ apps/extension/scripts/e2e.mjs | 103 +++++- apps/extension/src/core/router.ts | 11 +- apps/extension/src/core/session-manager.ts | 34 +- .../src/core/session-runtime.test.ts | 29 ++ apps/extension/src/core/session-runtime.ts | 68 ++-- apps/extension/src/core/write-journal.ts | 10 +- apps/extension/src/driver/cdp.test.ts | 254 ++++++++++++++- apps/extension/src/driver/cdp.ts | 301 ++++++++++++++++-- apps/extension/src/driver/keymap.ts | 4 +- apps/extension/src/driver/page-request.ts | 54 ++++ apps/extension/src/driver/payment-guard.ts | 184 +++++++++++ .../src/driver/semantic/cdp-semantic.test.ts | 40 ++- apps/extension/src/driver/semantic/types.ts | 1 + packages/connector/src/index.test.ts | 33 ++ packages/connector/src/index.ts | 54 +++- packages/protocol/src/index.test.ts | 71 ++++- packages/protocol/src/index.ts | 141 +++++++- 22 files changed, 1425 insertions(+), 99 deletions(-) create mode 100644 .changeset/page-request-and-payment-refusal.md create mode 100644 apps/extension/src/driver/page-request.ts create mode 100644 apps/extension/src/driver/payment-guard.ts diff --git a/.changeset/page-request-and-payment-refusal.md b/.changeset/page-request-and-payment-refusal.md new file mode 100644 index 0000000..ae211ef --- /dev/null +++ b/.changeset/page-request-and-payment-refusal.md @@ -0,0 +1,12 @@ +--- +"@understudy/protocol": minor +"@understudy/connector": minor +--- + +Add the `page-request-v1` capability for declarative same-origin JSON requests +in unattended sessions. GET uses the read path. An explicitly permitted write +uses prepare and grant. Durable command and connector records retain the HTTP +status and omit the response body. + +Report `payment_refused` for blocked payment input and `security_check` when the +browser encounters a CAPTCHA or verification-code prompt. diff --git a/apps/backend/src/index.ts b/apps/backend/src/index.ts index 421ab74..ccffdf1 100644 --- a/apps/backend/src/index.ts +++ b/apps/backend/src/index.ts @@ -477,7 +477,7 @@ function v2Outcome( case "legacy_snapshot_required": return c.json({ error: "legacy extension requires snapshot compatibility" }, 426); case "unsupported": - return c.json({ error: "extension lacks safe-write-v3" }, 426); + return c.json({ error: `extension lacks ${outcome.capability ?? "safe-write-v3"}` }, 426); case "terminal_session": return c.json({ error: "session is terminal" }, 410); } diff --git a/apps/backend/src/session.ts b/apps/backend/src/session.ts index 7fdad33..eb26361 100644 --- a/apps/backend/src/session.ts +++ b/apps/backend/src/session.ts @@ -10,6 +10,8 @@ import { isCommandType, isCommandResultEvent, isWriteCommand, + pageRequestReceipt, + resolvePageRequestUrl, safeParseEvent, safeParseSessionClientFrame, utf8ByteLength, @@ -18,6 +20,7 @@ import type { Command, CommandState, Event, + PageRequestResult, SessionClientFrame, SessionServerFrame, TabInfo, @@ -68,6 +71,8 @@ const RECENT_DIALOGS_CAP = 50; const PREPARE_DEADLINE_MS = 5_000; const EXECUTION_DEADLINE_MS = 25_000; const SYNCHRONOUS_WAIT_MS = 20_000; +const PAGE_REQUEST_BODY_TTL_MS = 60_000; +const MAX_PAGE_REQUEST_BODIES = 16; const LegacyDialogEventSchema = z .object({ type: z.literal("dialog"), @@ -122,6 +127,7 @@ export class SessionAgent extends Agent { private readonly coordinator: CfSessionCoordinator; private readonly stateWaiters = new Map void>>(); private readonly connectionWaiters = new Set<(connected: boolean) => void>(); + private readonly pageRequestBodies = new Map(); constructor(ctx: AgentContext, env: Env) { super(ctx, env); @@ -495,13 +501,17 @@ export class SessionAgent extends Agent { row.dry_run === 1 && row.is_write === 1 && frame.event.type === "action_result" ? { ...frame.event, simulated: true } : frame.event; + const recorded = event.type === "page_request_result" ? pageRequestReceipt(event) : event; this.sql` UPDATE command_journal - SET state = 'completed', result_json = ${JSON.stringify(event)}, + SET state = 'completed', result_json = ${JSON.stringify(recorded)}, updated_at = ${now} WHERE attempt_id = ${frame.attemptId} AND state = 'granted' AND execution_deadline_at > ${now} `; + if (event.type === "page_request_result" && event.body !== undefined) { + this.rememberPageRequestBody(row.attempt_id, event); + } this.notifyAttempt(frame.attemptId); } else if ( row?.state === "granted" && @@ -617,6 +627,9 @@ export class SessionAgent extends Agent { async dispatch(command: Command, dryRun?: boolean): Promise { try { if (this.isTerminalSession()) return this.terminalDispatchOutcome(); + if (command.type === "page_request") { + return { ok: true, event: { type: "action_result", commandId: command.commandId, ok: false, reason: "unsupported" } }; + } const fingerprint = await requestFingerprint(command, dryRun === true); if (this.isTerminalSession()) return this.terminalDispatchOutcome(); const tombstone = legacyTombstone(command, fingerprint); @@ -671,6 +684,27 @@ export class SessionAgent extends Agent { ) { return { kind: "not_connected", commandId: command.commandId }; } + if (command.type === "page_request") { + const lease = this.state.unattended; + if ( + lease === undefined || + this.state.protocolVersion !== PROTOCOL_VERSION || + !(this.state.capabilities ?? []).includes("page-request-v1") + ) { + return { kind: "unsupported", commandId: command.commandId, capability: "page-request-v1" }; + } + const pageUrl = this.state.currentUrl ?? this.state.tabs[0]?.url; + const origin = pageUrl === undefined ? null : URL.parse(pageUrl)?.origin; + if (!origin || !lease.allowedOrigins.includes(origin) || + resolvePageRequestUrl(origin, command.path, command.query) === null) { + return { kind: "terminal", event: { + type: "action_result", + commandId: command.commandId, + ok: false, + reason: "navigation_blocked", + } }; + } + } if ( isWriteCommand(command) && !dryRun && @@ -951,7 +985,7 @@ export class SessionAgent extends Agent { return { commandId, status: row.state, - ...(row.result_json === null ? {} : { event: JSON.parse(row.result_json) as Event }), + ...(row.result_json === null ? {} : { event: this.completedEvent(row) }), safeToRetry: row.state === "not_started" || row.state === "timed_out", }; } @@ -1295,8 +1329,7 @@ export class SessionAgent extends Agent { private outcomeForRow(row: CommandRow, statusUrl: string): V2DispatchOutcome { switch (row.state) { case "completed": { - if (row.result_json === null) throw new Error("completed command is missing its result"); - return { kind: "terminal", event: JSON.parse(row.result_json) as Event }; + return { kind: "terminal", event: this.completedEvent(row) }; } case "not_started": return { kind: "not_started", commandId: row.command_id, safeToRetry: true }; @@ -1311,6 +1344,23 @@ export class SessionAgent extends Agent { } } + private completedEvent(row: CommandRow): Event { + if (row.result_json === null) throw new Error("completed command is missing its result"); + const body = this.pageRequestBodies.get(row.attempt_id); + if (body !== undefined && body.expiresAt > Date.now()) return body.event; + this.pageRequestBodies.delete(row.attempt_id); + return JSON.parse(row.result_json) as Event; + } + + private rememberPageRequestBody(attemptId: string, event: PageRequestResult): void { + if (this.pageRequestBodies.size >= MAX_PAGE_REQUEST_BODIES) { + const oldest = this.pageRequestBodies.keys().next().value; + if (oldest !== undefined) this.pageRequestBodies.delete(oldest); + } + this.pageRequestBodies.set(attemptId, { event, expiresAt: Date.now() + PAGE_REQUEST_BODY_TTL_MS }); + setTimeout(() => this.pageRequestBodies.delete(attemptId), PAGE_REQUEST_BODY_TTL_MS); + } + private continuationOutcome( attemptId: string, expected: CommandState, diff --git a/apps/backend/src/types.ts b/apps/backend/src/types.ts index bab3df8..588f091 100644 --- a/apps/backend/src/types.ts +++ b/apps/backend/src/types.ts @@ -177,7 +177,7 @@ export type V2DispatchOutcome = | { kind: "busy"; commandId: string } | { kind: "not_connected"; commandId: string } | { kind: "legacy_snapshot_required"; commandId: string } - | { kind: "unsupported"; commandId: string } + | { kind: "unsupported"; commandId: string; capability?: "page-request-v1" } | { kind: "terminal_session"; commandId: string }; export interface CommandStatusRecord { diff --git a/apps/backend/test/session.test.ts b/apps/backend/test/session.test.ts index 29d1bb3..b77490f 100644 --- a/apps/backend/test/session.test.ts +++ b/apps/backend/test/session.test.ts @@ -928,6 +928,64 @@ describe("hello resync", () => { }); describe("protocol-v3 command result correlation", () => { + it("requires the page-request capability before dispatching a request", async () => { + // #given + const sessionId = crypto.randomUUID(); + const stub = await getSessionStub(sessionId); + await runInDurableObject(stub, async (instance: SessionAgent) => { + await instance.initializeUnattended("tenantA", unattendedLease(sessionId)); + setAuthoritative(instance); + instance.setState({ ...instance.state, protocolVersion: 3, capabilities: ["safe-write-v3"] }); + Object.assign(instance, { getConnections: () => [FAKE_CONNECTION] }); + + // #then + await expect(instance.dispatchV2( + { type: "page_request", commandId: "page-request", path: "/orders" }, + false, + "actor", + "https://example.test/status", + )).resolves.toEqual({ kind: "unsupported", commandId: "page-request", capability: "page-request-v1" }); + }); + }); + + it("returns page request JSON during polling and persists only the response receipt", async () => { + // #given + const sessionId = crypto.randomUUID(); + const stub = await getSessionStub(sessionId); + await runInDurableObject(stub, async (instance: SessionAgent) => { + const lease = unattendedLease(sessionId); + const { leaseId, leaseEpoch, browserEpoch } = lease; + await instance.initializeUnattended("tenantA", lease); + setAuthoritative(instance); + const attempt = seedAttempt(instance, { state: "granted", commandType: "page_request", dryRun: false, isWrite: true }); + const event = { + type: "page_request_result", + commandId: attempt.commandId, + status: 201, + body: { records: [1] }, + }; + + // #when + await instance.onMessage(FAKE_CONNECTION, JSON.stringify({ + type: "command_result", + attemptId: attempt.attemptId, + commandId: attempt.commandId, + leaseId, leaseEpoch, browserEpoch, event, + })); + + // #then + await expect(instance.getCommandStatus(attempt.commandId)).resolves.toEqual({ + commandId: attempt.commandId, status: "completed", safeToRetry: false, event, + }); + const row = instance.sql<{ result_json: string }>` + SELECT result_json FROM command_journal WHERE command_id = ${attempt.commandId} + `[0]; + expect(JSON.parse(row!.result_json)).toEqual({ + type: "page_request_result", commandId: attempt.commandId, status: 201, bodyUnavailable: true, + }); + }); + }); + it("permits legacy snapshot fallback only for a protocol-1/2 peer", async () => { const stub = await getSessionStub(crypto.randomUUID()); await runInDurableObject(stub, async (instance: SessionAgent) => { diff --git a/apps/extension/scripts/e2e.mjs b/apps/extension/scripts/e2e.mjs index 2f38c5f..c85a924 100644 --- a/apps/extension/scripts/e2e.mjs +++ b/apps/extension/scripts/e2e.mjs @@ -125,9 +125,10 @@ try { ); const browser = { client, worker, panel }; + await runCheckoutStop(browser, localService); await runSemanticElements(browser, localService); process.stdout.write( - "extension E2E passed: bounded semantic discovery, frame/shadow capture, deltas, ref fencing, and worker-eviction recovery\n", + "extension E2E passed: checkout refusal, page requests, bounded semantic discovery, frame/shadow capture, deltas, ref fencing, and worker-eviction recovery\n", ); } catch (error) { if (chromeStderr.length > 0) process.stderr.write(chromeStderr); @@ -176,6 +177,7 @@ async function startLocalService(directory) { const sessionSockets = new Map(); let controlSocket = null; let browserEpoch = null; + let checkoutWrites = 0; const deviceId = "00000000-0000-4000-8000-0000000000e2"; const key = await readFile(path.join(directory, "localhost.key")); const cert = await readFile(path.join(directory, "localhost.crt")); @@ -208,6 +210,24 @@ async function startLocalService(directory) { response.end(semanticFramePage(url.searchParams.get("kind") ?? "same")); return; } + if (url.pathname === "/checkout-fixture") { + response.writeHead(200, { + "content-type": "text/html; charset=utf-8", + "set-cookie": "fixture=present; Secure; HttpOnly; SameSite=Strict", + }); + response.end(checkoutPage()); + return; + } + if (url.pathname === "/checkout-fixture-json") { + if (request.method === "POST") checkoutWrites += 1; + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ + signedIn: request.headers.cookie?.includes("fixture=present") === true, + query: url.searchParams.get("search"), + writes: checkoutWrites, + })); + return; + } response.writeHead(404); response.end("not found"); }); @@ -376,6 +396,27 @@ function semanticFramePage(kind) { return ``; } +function checkoutPage() { + return ` +
+
+ + +
+ 0 + + `; +} + function closureFence(frame) { return { sessionId: frame.sessionId, @@ -385,7 +426,7 @@ function closureFence(frame) { }; } -async function provisionScenario(service, label, url) { +async function provisionScenario(service, label, url, pageRequestWrites) { await service.waitForControl(); const sequence = service.events.filter((event) => event.kind === "session_open").length + 1; const scenario = { @@ -404,6 +445,7 @@ async function provisionScenario(service, label, url) { type: "provision", ...closureFence(scenario), allowedOrigins: [service.origin], + ...(pageRequestWrites === undefined ? {} : { pageRequestWrites }), policyVersion: 1, sessionTicket: `session-ticket-${sequence}`, }); @@ -461,6 +503,59 @@ function requireElementsResult(result, operation) { return event; } +async function runCheckoutStop(browser, service) { + const path = "/checkout-fixture-json"; + const { scenario } = await provisionScenario( + service, + "checkout", + `${service.origin}/checkout-fixture`, + [{ origin: service.origin, method: "POST", path }], + ); + const elements = await captureCheckout(); + const ref = (label) => { + const value = elements.find((element) => element.name === label)?.ref; + assert(typeof value === "string", `checkout fixture did not expose ${label}`); + return value; + }; + for (const command of [ + { type: "key", commandId: "checkout-focused", keys: "Enter" }, + { type: "click", commandId: "checkout-cash", ref: ref("Confirm order") }, + { type: "type", commandId: "checkout-card", ref: ref("Card number"), text: "fixture" }, + { type: "type", commandId: "checkout-submit", ref: ref("Billing note"), text: "fixture", submit: true }, + ]) { + const { frame } = await writeCommand(service, scenario, command, service.cursor()); + assert(frame.event.ok === false && frame.event.reason === "payment_refused", `checkout did not refuse ${command.commandId}`); + } + const after = await captureCheckout(); + assert(after.some((element) => element.name === "Input events: 0"), "checkout refusal dispatched an input event"); + + const { frame: read } = await readCommand(service, scenario, { + type: "page_request", commandId: "checkout-read", path, query: { search: "a & b" }, + }); + assert(read.event.type === "page_request_result" && read.event.body?.signedIn === true && + read.event.body.query === "a & b" && read.event.body.writes === 0, "authenticated checkout JSON read failed"); + const { frame: denied } = await writeCommand(service, scenario, { + type: "page_request", commandId: "checkout-denied", path, method: "DELETE", + }, service.cursor()); + assert(denied.event.reason === "navigation_blocked", "unlisted checkout request method was accepted"); + const { frame: written } = await writeCommand(service, scenario, { + type: "page_request", commandId: "checkout-write", path, method: "POST", body: { source: "fixture" }, + }, service.cursor()); + assert(written.event.type === "page_request_result" && written.event.body?.writes === 1, "approved checkout request did not run once"); + await closeScenario(browser, service, scenario); + + async function captureCheckout() { + return requireElementsResult(await readCommand(service, scenario, { + type: "capture_elements", + commandId: `checkout-capture-${service.cursor()}`, + scope: "document", + view: "all", + limit: 30, + changesOnly: false, + }), "snapshot").elements; + } +} + async function runSemanticElements(browser, service) { const { scenario } = await provisionScenario( service, @@ -746,6 +841,10 @@ async function runSemanticElements(browser, service) { `semantic median output reduction was below 70%: ${JSON.stringify(reductions)}`, ); + await closeScenario(browser, service, scenario); +} + +async function closeScenario(browser, service, scenario) { const closeCursor = service.cursor(); service.sendControl({ type: "close_lease", ...closureFence(scenario) }); await service.waitFor( diff --git a/apps/extension/src/core/router.ts b/apps/extension/src/core/router.ts index 3fbbb49..3576eb6 100644 --- a/apps/extension/src/core/router.ts +++ b/apps/extension/src/core/router.ts @@ -92,8 +92,12 @@ async function routeSwitchTab( return { type: "action_result", commandId, ok: true }; } -export async function routeCommand(cmd: Command, session: CdpSession | null): Promise { - const event = await routeCommandUnchecked(cmd, session); +export async function routeCommand( + cmd: Command, + session: CdpSession | null, + deadlineAt?: number, +): Promise { + const event = await routeCommandUnchecked(cmd, session, deadlineAt); const parsed = safeParseEvent(event); if ( parsed.success && @@ -111,6 +115,7 @@ export async function routeCommand(cmd: Command, session: CdpSession | null): Pr async function routeCommandUnchecked( cmd: Command, session: CdpSession | null, + deadlineAt?: number, ): Promise { try { switch (cmd.type) { @@ -201,6 +206,8 @@ async function routeCommandUnchecked( const { for: waitFor, value } = cmd; return await withSession(session, cmd.commandId, (s) => s.wait(cmd.commandId, waitFor, value)); } + case "page_request": + return await withSession(session, cmd.commandId, (s) => s.pageRequest(cmd, deadlineAt)); case "resolve_ref": { const { ref } = cmd; return await withSession(session, cmd.commandId, (s) => diff --git a/apps/extension/src/core/session-manager.ts b/apps/extension/src/core/session-manager.ts index e45fdd0..755da9e 100644 --- a/apps/extension/src/core/session-manager.ts +++ b/apps/extension/src/core/session-manager.ts @@ -1,4 +1,10 @@ -import type { AssignmentInventory, OwnedWindow, TabInfo } from "@understudy/protocol"; +import { + PageRequestWritePolicySchema, + type AssignmentInventory, + type OwnedWindow, + type PageRequestWritePolicy, + type TabInfo, +} from "@understudy/protocol"; import type { Browser } from "wxt/browser"; import { controlledTabInfo } from "../tabs"; import { @@ -25,6 +31,7 @@ export interface ProvisionInput { leaseEpoch: number; browserEpoch: string; allowedOrigins: string[]; + pageRequestWrites?: PageRequestWritePolicy; policyVersion: number; sessionTicket: string; } @@ -155,6 +162,7 @@ export class SessionManager implements RuntimeHost { leaseEpoch: input.leaseEpoch, browserEpoch: input.browserEpoch, allowedOrigins: [...input.allowedOrigins], + ...(input.pageRequestWrites === undefined ? {} : { pageRequestWrites: input.pageRequestWrites }), policyVersion: input.policyVersion, tabId: tab.id, windowId: createdWindow.id, @@ -398,10 +406,7 @@ export class SessionManager implements RuntimeHost { } assignments(): ManagedAssignment[] { - return [...this.byLease.values()].map((runtime) => ({ - ...runtime.assignment, - allowedOrigins: [...runtime.assignment.allowedOrigins], - })); + return [...this.byLease.values()].map((runtime) => cloneAssignment(runtime.assignment)); } inventory(): AssignmentInventory[] { @@ -554,7 +559,8 @@ export class SessionManager implements RuntimeHost { existing.assignment.browserEpoch !== input.browserEpoch || existing.assignment.policyVersion !== input.policyVersion || existing.assignment.cleanupIntent !== undefined || - !sameOrigins(existing.assignment.allowedOrigins, input.allowedOrigins) + !sameOrigins(existing.assignment.allowedOrigins, input.allowedOrigins) || + !samePageRequestWrites(existing.assignment.pageRequestWrites, input.pageRequestWrites) ) { throw new Error("lease assignment conflict"); } @@ -927,13 +933,17 @@ function emptyManagerState(): PersistedManagerState { function parseManagedAssignments(values: unknown[]): ManagedAssignment[] { return values.flatMap((value) => { if (!isAssignmentShape(value)) return []; - const { sensitive, ...item } = value as Omit & { + const { sensitive, pageRequestWrites, ...item } = value as Omit & { policyVersion?: unknown; sensitive?: true; }; + const writePolicy = PageRequestWritePolicySchema.safeParse(pageRequestWrites); // A stored assignment from an earlier development build can flag a window with payment card input. return [{ ...item, + ...(writePolicy.success && writePolicy.data.every((rule) => item.allowedOrigins.includes(rule.origin)) + ? { pageRequestWrites: writePolicy.data } + : {}), ...(sensitive === true && item.cleanupIntent !== "discard" ? { cleanupIntent: "release" as const } : {}), @@ -1039,10 +1049,20 @@ function sameOrigins(left: readonly string[], right: readonly string[]): boolean return left.length === right.length && left.every((origin, index) => origin === right[index]); } +function samePageRequestWrites(left: PageRequestWritePolicy = [], right: PageRequestWritePolicy = []): boolean { + return left.length === right.length && left.every((rule, index) => { + const other = right[index]; + return other !== undefined && rule.origin === other.origin && rule.method === other.method && rule.path === other.path; + }); +} + function cloneAssignment(assignment: ManagedAssignment): ManagedAssignment { return { ...assignment, allowedOrigins: [...assignment.allowedOrigins], + ...(assignment.pageRequestWrites === undefined ? {} : { + pageRequestWrites: assignment.pageRequestWrites.map((rule) => ({ ...rule })), + }), }; } diff --git a/apps/extension/src/core/session-runtime.test.ts b/apps/extension/src/core/session-runtime.test.ts index 3d8f1a0..7dc4f94 100644 --- a/apps/extension/src/core/session-runtime.test.ts +++ b/apps/extension/src/core/session-runtime.test.ts @@ -278,6 +278,35 @@ describe("SessionRuntime write journal", () => { expect(peerSend.mock.calls).toEqual([[result]]); }); + it("executes a page request write once after a matching prepare and concurrent grants", async () => { + // #given + const { values } = stubWriteStorage(); + const runtime = new SessionRuntime(ASSIGNMENT, host()); + const command = { type: "page_request", commandId: attempt.commandId, path: "/orders", method: "POST" } as const; + const response = { type: "page_request_result", commandId: command.commandId, status: 201, body: { count: 1 } } as const; + const pageRequest = vi.fn(async () => response); + const peerSend = vi.fn((_frame: unknown) => true); + Object.assign(runtime, { cdp: { pageRequest }, peer: { send: peerSend } }); + const grant = { ...writeGrant(), command }; + + // #when + await runtime["onServerFrame"]({ type: "command", ...fence, attemptId: attempt.attemptId, deadlineAt: grant.deadlineAt, command }); + await runtime["onServerFrame"](grant); + expect(pageRequest).not.toHaveBeenCalled(); + await runtime["onServerFrame"]({ type: "write_prepare", ...attempt, deadlineAt: grant.deadlineAt, commandType: "page_request" }); + await Promise.all([runtime["onServerFrame"](grant), runtime["onServerFrame"](grant)]); + + // #then + expect(pageRequest).toHaveBeenCalledExactlyOnceWith(command, Date.parse(grant.deadlineAt)); + expect(peerSend.mock.calls.at(-1)).toEqual([{ ...result, event: response }]); + expect(values[journalKey]).toEqual([{ + ...attempt, + commandType: "page_request", + state: "completed_unacked", + event: { type: "page_request_result", commandId: command.commandId, status: 201, bodyUnavailable: true }, + }]); + }); + it("marks a click with no durable result unknown after eviction without retrying or replaying it", async () => { const { storage, values } = stubWriteStorage(); const { runtime, click, peerSend } = createClickRuntime(); diff --git a/apps/extension/src/core/session-runtime.ts b/apps/extension/src/core/session-runtime.ts index 68a8a71..21cf976 100644 --- a/apps/extension/src/core/session-runtime.ts +++ b/apps/extension/src/core/session-runtime.ts @@ -5,6 +5,7 @@ import { safeParseSessionServerFrame, type Command, type Event, + type PageRequestWritePolicy, type SessionServerFrame, type TabInfo, } from "@understudy/protocol"; @@ -24,6 +25,7 @@ export interface RuntimeAssignment { leaseEpoch: number; browserEpoch: string; allowedOrigins: string[]; + pageRequestWrites?: PageRequestWritePolicy; policyVersion: number; tabId: number; windowId: number; @@ -50,6 +52,7 @@ export class SessionRuntime { private cdp: CdpSession | null = null; private accepting: boolean; private writesBlocked = false; + private writeInFlight = false; private closing = false; private windowClosure: Promise | null = null; @@ -97,7 +100,7 @@ export class SessionRuntime { await cdp.attach(); try { await cdp.enableDomains(); - await cdp.enableUnattendedContainment(this.assignment.allowedOrigins); + await cdp.enableUnattendedContainment(this.assignment.allowedOrigins, this.assignment.pageRequestWrites); } catch (error) { await cdp.detach().catch(() => {}); throw error; @@ -108,7 +111,7 @@ export class SessionRuntime { async reconcileSameEpoch(): Promise { const cdp = await CdpSession.create(this.tabId, this.sessionId); await cdp.reconcile(); - await cdp.enableUnattendedContainment(this.assignment.allowedOrigins); + await cdp.enableUnattendedContainment(this.assignment.allowedOrigins, this.assignment.pageRequestWrites); this.cdp = cdp; } @@ -347,6 +350,7 @@ export class SessionRuntime { await this.journal.prepare({ attemptId: frame.attemptId, commandId: frame.commandId, + commandType: frame.commandType, requestFingerprint: frame.requestFingerprint, leaseId: frame.leaseId, leaseEpoch: frame.leaseEpoch, @@ -401,38 +405,46 @@ export class SessionRuntime { ): Promise { if ( this.writesBlocked || + this.writeInFlight || !this.matchesFence(frame) || deadline(frame.deadlineAt) <= Date.now() || !isWriteCommand(frame.command) ) { return; } - const record = await this.journal.get(frame.attemptId); - if (!this.canAccept()) return; - if ( - record === undefined || - record.state !== "prepared" || - record.commandId !== frame.command.commandId - ) { - return; - } - await this.journal.markStarted(frame.attemptId); - if (!this.canAccept()) return; - const event = await this.executeWithDeadline(frame.command, deadline(frame.deadlineAt)); - if (event === null || !this.canAccept()) { - await this.journal.markUnknown(frame.attemptId); - this.writesBlocked = true; - return; + this.writeInFlight = true; + try { + const record = await this.journal.get(frame.attemptId); + if (!this.canAccept()) return; + if ( + record === undefined || + record.state !== "prepared" || + record.commandId !== frame.command.commandId || + ((frame.command.type === "page_request" || record.commandType === "page_request") && + frame.command.type !== record.commandType) + ) { + return; + } + await this.journal.markStarted(frame.attemptId); + if (!this.canAccept()) return; + const event = await this.executeWithDeadline(frame.command, deadline(frame.deadlineAt)); + if (event === null || !this.canAccept()) { + await this.journal.markUnknown(frame.attemptId); + this.writesBlocked = true; + return; + } + await this.journal.markCompleted(frame.attemptId, event); + if (!this.canAccept()) return; + this.send({ + type: "command_result", + attemptId: frame.attemptId, + commandId: frame.command.commandId, + ...this.resultFence(), + event, + }); + } finally { + this.writeInFlight = false; } - await this.journal.markCompleted(frame.attemptId, event); - if (!this.canAccept()) return; - this.send({ - type: "command_result", - attemptId: frame.attemptId, - commandId: frame.command.commandId, - ...this.resultFence(), - event, - }); } private async executeWithDeadline( @@ -454,7 +466,7 @@ export class SessionRuntime { const timedOut = new Promise((resolve) => { timer = setTimeout(() => resolve(null), remaining); }); - const event = await Promise.race([routeCommand(command, cdp), timedOut]); + const event = await Promise.race([routeCommand(command, cdp, deadlineAt), timedOut]); clearTimeout(timer!); if (event !== null) return event; await cdp.detach().catch(() => {}); diff --git a/apps/extension/src/core/write-journal.ts b/apps/extension/src/core/write-journal.ts index d9f2dc3..e7bc3ae 100644 --- a/apps/extension/src/core/write-journal.ts +++ b/apps/extension/src/core/write-journal.ts @@ -1,4 +1,4 @@ -import type { Event } from "@understudy/protocol"; +import { pageRequestReceipt, type Event, type WriteCommandType } from "@understudy/protocol"; import type { SessionStorageArea } from "./dedupe"; export type WriteJournalState = @@ -10,6 +10,7 @@ export type WriteJournalState = export interface WriteJournalRecord { attemptId: string; commandId: string; + commandType?: WriteCommandType; requestFingerprint: string; state: WriteJournalState; leaseId?: string; @@ -33,6 +34,8 @@ export class WriteJournal { if (existing !== undefined) { if ( existing.commandId !== record.commandId || + ((existing.commandType === "page_request" || record.commandType === "page_request") && + existing.commandType !== record.commandType) || existing.requestFingerprint !== record.requestFingerprint ) { throw new Error("attempt journal conflict"); @@ -140,7 +143,8 @@ export class WriteJournal { ? (value as WriteJournalRecord[]).filter( (record) => record.state !== "completed_unacked" || - record.event?.type === "action_result", + record.event?.type === "action_result" || + (record.event?.type === "page_request_result" && record.event.bodyUnavailable === true), ) : []; } @@ -152,11 +156,13 @@ export class WriteJournal { } function journalSafeEvent(event: Event): Event { + if (event.type === "page_request_result") return pageRequestReceipt(event); if (event.type !== "action_result") throw new Error("unsupported write result"); return { type: "action_result", commandId: event.commandId, ok: event.ok, + ...(event.reason === undefined ? {} : { reason: event.reason }), ...(event.error === undefined ? {} : { error: "browser action failed" }), ...(event.simulated === undefined ? {} : { simulated: event.simulated }), }; diff --git a/apps/extension/src/driver/cdp.test.ts b/apps/extension/src/driver/cdp.test.ts index 61addab..38ac4a8 100644 --- a/apps/extension/src/driver/cdp.test.ts +++ b/apps/extension/src/driver/cdp.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect, vi, afterEach } from "vitest"; +import { PAGE_REQUEST_BODY_MAX_BYTES, type PageRequestWritePolicy } from "@understudy/protocol"; import type { Protocol } from "devtools-protocol"; import { CdpSession } from "./cdp"; import type { RefRecord } from "./semantic/types"; @@ -80,6 +81,12 @@ function liveRefResponse(method: string, params?: { backendNodeId?: number }): u }, }; } + if (method === "Page.createIsolatedWorld") return { executionContextId: 1 }; + if (method === "DOM.resolveNode" || method === "Runtime.evaluate") { + const object = { objectId: "focused-node" }; + return { object, result: object }; + } + if (method === "Runtime.callFunctionOn") return { result: { value: { target: "allowed" } } }; return {}; } @@ -284,6 +291,107 @@ describe("CdpSession.resolveRefCheck", () => { }); describe("CdpSession keyboard dispatch", () => { + it.each(["Pay now", "Confirm order", "تأكيد الطلب", "الدفع عند الاستلام"])( + "refuses a click on the order control %s before input dispatch", + async (name) => { + // #given + const sendCommand = stubActionBrowser(); + sendCommand.mockImplementation((_target, method: string, params) => { + const response = liveRefResponse(method, params); + if (method === "Accessibility.getPartialAXTree") { + const tree = response as Protocol.Accessibility.GetPartialAXTreeResponse; + tree.nodes[0]!.role = { type: "role", value: "button" }; + tree.nodes[0]!.name = { type: "computedString", value: name }; + } + return Promise.resolve(response); + }); + const session = await CdpSession.create(7, TEST_SCOPE); + seedTestRefs(session, [[testRef(0, 1), 42]], { role: "button", name }); + + // #when + const result = await session.click("order", testRef(0, 1)); + + // #then + expect(result).toMatchObject({ ok: false, reason: "payment_refused" }); + expect(sendCommand.mock.calls.some((call) => String(call[1]).startsWith("Input."))) + .toBe(false); + }, + ); + + it.each(["cc-number", "billing cc-exp-month", "cc-csc"])( + "refuses typing into %s before focusing the field", + async (autocomplete) => { + // #given + const sendCommand = stubActionBrowser(); + sendCommand.mockImplementation((_target, method: string, params) => { + const response = liveRefResponse(method, params); + if (method === "DOM.describeNode") { + const { node } = response as Protocol.DOM.DescribeNodeResponse; + node.attributes = ["type", "text", "autocomplete", autocomplete]; + } + return Promise.resolve(response); + }); + const session = await CdpSession.create(7, TEST_SCOPE); + seedTestRefs(session, [[testRef(0, 1), 42]]); + + // #when + const result = await session.type("card", testRef(0, 1), "synthetic input"); + + // #then + expect(result).toMatchObject({ ok: false, reason: "payment_refused" }); + expect(sendCommand.mock.calls.some((call) => call[1] === "DOM.focus" || call[1] === "Input.insertText")) + .toBe(false); + }, + ); + + it.each(["Enter", "NumpadEnter", "Space", " "])( + "refuses %j on the focused order-placement control without a ref", + async (keys) => { + // #given + const sendCommand = stubActionBrowser(); + sendCommand.mockImplementation((_target, method: string, params) => { + const response = liveRefResponse(method, params); + if (method === "Accessibility.getPartialAXTree") { + const tree = response as Protocol.Accessibility.GetPartialAXTreeResponse; + tree.nodes[0]!.role = { type: "role", value: "button" }; + tree.nodes[0]!.name = { type: "computedString", value: "Place order" }; + } + return Promise.resolve(response); + }); + const session = await CdpSession.create(7, TEST_SCOPE); + session.mainFrameId = "frame-1"; + + // #when + const result = await session.key("focused-order", keys); + + // #then + expect(result).toMatchObject({ ok: false, reason: "payment_refused" }); + expect(sendCommand.mock.calls.some((call) => call[1] === "Input.dispatchKeyEvent")).toBe(false); + }, + ); + + it("refuses typing in a payment-provider iframe before focus", async () => { + // #given + const sendCommand = stubActionBrowser(); + const session = await CdpSession.create(7, TEST_SCOPE); + seedTestRefs(session, [[testRef(0, 1), 42]]); + session.frameSessions.set("frame-1", { + targetId: "frame-1", + frameId: "frame-1", + targetType: "iframe", + ready: true, + url: "https://js.stripe.com/embedded/field", + }); + + // #when + const result = await session.type("provider", testRef(0, 1), "synthetic input"); + + // #then + expect(result).toMatchObject({ ok: false, reason: "payment_refused" }); + expect(sendCommand.mock.calls.some((call) => call[1] === "DOM.focus" || call[1] === "Input.insertText")) + .toBe(false); + }); + it("submits typed text with Enter's carriage-return key event", async () => { const sendCommand = stubActionBrowser(); const session = await CdpSession.create(7, TEST_SCOPE); @@ -1242,6 +1350,143 @@ describe("CdpSession unattended containment", () => { }); }); +describe("CdpSession page_request", () => { + const origin = "https://shop.example"; + const request = { type: "page_request", commandId: "request", path: "/orders" } as const; + + async function requestSession({ + allowedOrigins = [origin], + writes = [], + liveOrigin = origin, + fetchPage = vi.fn(async (_url: string, _init: RequestInit) => Response.json({ orders: [] })), + }: { + allowedOrigins?: string[]; + writes?: PageRequestWritePolicy; + liveOrigin?: string; + fetchPage?: ReturnType Promise>>; + } = {}) { + const sendCommand = stubActionBrowser(); + sendCommand.mockImplementation(async (_target, method: string, params: unknown) => { + if (method === "Page.getFrameTree") { + return { frameTree: { frame: { id: "frame-1", loaderId: "loader", url: `${origin}/checkout` } } }; + } + if (method === "Runtime.callFunctionOn") { + const call = params as { functionDeclaration: string; arguments: [{ value: unknown }] }; + const run = new Function("fetch", "self", "location", `return (${call.functionDeclaration});`)( + fetchPage, + { origin: liveOrigin }, + { origin: liveOrigin }, + ) as (data: unknown) => Promise; + return { result: { value: await run(call.arguments[0].value) } }; + } + return liveRefResponse(method); + }); + const session = await CdpSession.create(7, TEST_SCOPE); + await session.enableUnattendedContainment(allowedOrigins, writes); + return { session, fetchPage }; + } + + it("uses one credentialed same-origin GET with a data-only query and returns JSON", async () => { + // #given + const { session, fetchPage } = await requestSession(); + + // #when + const result = await session.pageRequest({ ...request, query: { search: 'a&b="c"' } }); + + // #then + expect(result).toEqual({ type: "page_request_result", commandId: "request", status: 200, body: { orders: [] } }); + expect(fetchPage.mock.calls).toEqual([[ + `${origin}/orders?search=a%26b%3D%22c%22`, + expect.objectContaining({ method: "GET", mode: "same-origin", credentials: "same-origin", redirect: "manual" }), + ]]); + }); + + it.each(["https://other.example/orders", "//other.example/orders", "/\\other.example/orders"])( + "refuses a cross-origin target %s even when both origins are allowed", + async (path) => { + // #given + const { session, fetchPage } = await requestSession({ allowedOrigins: [origin, "https://other.example"] }); + + // #when + const result = await session.pageRequest({ ...request, path }); + + // #then + expect(result).toMatchObject({ ok: false, reason: "navigation_blocked" }); + expect(fetchPage).not.toHaveBeenCalled(); + }, + ); + + it("refuses requests from a page outside the session origins", async () => { + // #given + const { session, fetchPage } = await requestSession({ allowedOrigins: ["https://other.example"] }); + + // #when + const result = await session.pageRequest(request); + + // #then + expect(result).toMatchObject({ ok: false, reason: "navigation_blocked" }); + expect(fetchPage).not.toHaveBeenCalled(); + }); + + it("rechecks the live document origin before fetch", async () => { + // #given + const { session, fetchPage } = await requestSession({ liveOrigin: "https://other.example" }); + + // #when + const result = await session.pageRequest(request); + + // #then + expect(result).toMatchObject({ ok: false, reason: "navigation_blocked" }); + expect(fetchPage).not.toHaveBeenCalled(); + }); + + it("enforces the write policy by exact method and endpoint before fetch", async () => { + // #given + const { session, fetchPage } = await requestSession({ writes: [{ origin, path: "/orders", method: "POST" }] }); + + // #when + const deniedMethod = await session.pageRequest({ ...request, method: "DELETE" }); + const deniedPath = await session.pageRequest({ ...request, path: "/orders/other", method: "POST" }); + const permitted = await session.pageRequest({ ...request, method: "POST", body: { operation: "example" } }); + + // #then + expect(deniedMethod).toMatchObject({ ok: false, reason: "navigation_blocked" }); + expect(deniedPath).toMatchObject({ ok: false, reason: "navigation_blocked" }); + expect(permitted).toMatchObject({ type: "page_request_result", status: 200 }); + expect(fetchPage.mock.calls).toEqual([[ + `${origin}/orders`, + expect.objectContaining({ method: "POST", body: '{"operation":"example"}' }), + ]]); + }); + + it("refuses a redirect response without issuing another fetch", async () => { + // #given + const fetchPage = vi.fn(async (_url: string, _init: RequestInit) => Response.redirect("https://other.example/orders")); + const { session } = await requestSession({ fetchPage }); + + // #when + const result = await session.pageRequest(request); + + // #then + expect(result).toMatchObject({ ok: false, reason: "navigation_blocked" }); + expect(fetchPage).toHaveBeenCalledOnce(); + }); + + it("rejects a streamed JSON body larger than the result limit", async () => { + // #given + const fetchPage = vi.fn(async (_url: string, _init: RequestInit) => + Response.json({ orders: "é".repeat(PAGE_REQUEST_BODY_MAX_BYTES / 2) }), + ); + const { session } = await requestSession({ fetchPage }); + + // #when + const result = await session.pageRequest(request); + + // #then + expect(result).toMatchObject({ ok: false, reason: "result_too_large" }); + }); +}); + describe("CdpSession OOPIF routing", () => { it("initializes nested iframe sessions and routes ref validation and actions through them", async () => { const sendCommand = vi.fn( @@ -1268,7 +1513,7 @@ describe("CdpSession OOPIF routing", () => { nodeId: "live-button", ignored: false, role: { type: "role", value: "button" }, - name: { type: "computedString", value: "Pay" }, + name: { type: "computedString", value: "Buy now" }, backendDOMNodeId: params?.backendNodeId, properties: [ { @@ -1297,7 +1542,7 @@ describe("CdpSession OOPIF routing", () => { if (method === "DOM.getBoxModel") { return { model: { content: [0, 0, 10, 0, 10, 10, 0, 10] } }; } - return {}; + return liveRefResponse(method, params); }, ); vi.stubGlobal("browser", { @@ -1331,7 +1576,7 @@ describe("CdpSession OOPIF routing", () => { actions: new Set(["click", "inspect"]), fingerprint: { role: "button", - name: "Pay", + name: "Buy now", tagName: "button", domMetadataKnown: true, hidden: false, @@ -1356,6 +1601,9 @@ describe("CdpSession OOPIF routing", () => { [ "Accessibility.getPartialAXTree", "DOM.describeNode", + "Page.createIsolatedWorld", + "DOM.resolveNode", + "Runtime.callFunctionOn", "DOM.getBoxModel", "Input.dispatchMouseEvent", ].includes(call[1] as string), diff --git a/apps/extension/src/driver/cdp.ts b/apps/extension/src/driver/cdp.ts index 24bd54c..dac1b14 100644 --- a/apps/extension/src/driver/cdp.ts +++ b/apps/extension/src/driver/cdp.ts @@ -2,6 +2,9 @@ import { ELEMENTS_RESULT_MAX_BYTES, MAX_ELEMENT_DESCRIPTORS, MAX_SEMANTIC_NODES, + PAGE_REQUEST_BODY_MAX_BYTES, + PageRequestBodySchema, + resolvePageRequestUrl, utf8ByteLength, type ActionFailureReason, type ElementAction, @@ -9,11 +12,26 @@ import { type ElementsFailureReason, type ElementsResult, type Event, + type PageRequestCommand, + type PageRequestWritePolicy, } from "@understudy/protocol"; import type { Protocol } from "devtools-protocol"; import { errorMessage } from "../events"; import { a11yRefPrefix, buildA11ySnapshot } from "./a11y"; import { parseKeys } from "./keymap"; +import { PAGE_REQUEST_FUNCTION } from "./page-request"; +import { + FOCUSED_ELEMENT_EXPRESSION, + PAYMENT_PROBE_RULES, + PAYMENT_TARGET_PROBE, + isCaptchaFrame, + isCardField, + isOrderPlacementControl, + isPaymentProviderFrame, + isSecurityCheck, + type PaymentProbeMode, + type PaymentProbeResult, +} from "./payment-guard"; import { buildSemanticCache, deltaDescriptors, @@ -54,6 +72,8 @@ const IDLE_QUIET_MS = 500; const SNAPSHOT_DEADLINE_MS = 25_000; const CURSOR_TTL_MS = 10 * 60 * 1_000; const MAX_ACTIVE_CURSORS = 16; +const PAGE_REQUEST_TIMEOUT_MS = 12_000; +const AUTOMATION_WORLD = "understudy"; interface ElementCursor { token: string; @@ -214,6 +234,7 @@ export class CdpSession { // in order instead of racing to overwrite browser.storage.session. private genPersistChain: Promise = Promise.resolve(); private allowedOrigins: Set | null = null; + private pageRequestWrites: PageRequestWritePolicy = []; private semanticCache: SemanticCache | null = null; private deltaBaseline: SemanticCache | null = null; private readonly cursors = new Map(); @@ -308,6 +329,8 @@ export class CdpSession { async detach(): Promise { this.enabled = false; + if (this.allowedOrigins !== null) this.allowedOrigins = new Set(); + this.pageRequestWrites = []; this.frameSessions.clear(); this.frameParents.clear(); this.semanticCache = null; @@ -331,8 +354,12 @@ export class CdpSession { this.enabled = true; } - async enableUnattendedContainment(allowedOrigins: readonly string[]): Promise { + async enableUnattendedContainment( + allowedOrigins: readonly string[], + pageRequestWrites: PageRequestWritePolicy = [], + ): Promise { this.allowedOrigins = new Set(allowedOrigins); + this.pageRequestWrites = pageRequestWrites; await this.send("Fetch.enable", { patterns: [ { @@ -419,6 +446,7 @@ export class CdpSession { tracked.frameId = identity.frameId; this.frameSessions.set(identity.frameId, tracked); } + tracked.url = identity.url; tracked.ready = true; } catch { this.frameSessions.delete(tracked.frameId); @@ -793,6 +821,7 @@ export class CdpSession { : { parentSessionId: existing.parentSessionId }), targetType: parentFrameId === undefined ? "page" : "iframe", ready: existing?.ready ?? debuggerSessionId === undefined, + url: tree.frame.url, }); this.frameParents.set(tree.frame.id, parentFrameId); topology.push({ @@ -986,6 +1015,147 @@ export class CdpSession { ); } + private async automationWorld(frameId: string, debuggerSessionId?: string): Promise { + const world = await this.sendInSession( + "Page.createIsolatedWorld", + { frameId, worldName: AUTOMATION_WORLD }, + debuggerSessionId, + ); + if (!Number.isInteger(world.executionContextId)) throw new Error("missing automation world"); + return world.executionContextId; + } + + private async probeInputTarget( + objectId: string, + mode: PaymentProbeMode, + debuggerSessionId?: string, + requireFocused = false, + ): Promise { + const response = await this.sendInSession( + "Runtime.callFunctionOn", + { + objectId, + functionDeclaration: PAYMENT_TARGET_PROBE, + arguments: [{ value: PAYMENT_PROBE_RULES }, { value: mode }, { value: requireFocused }], + returnByValue: true, + }, + debuggerSessionId, + ); + const result = response.result?.value as PaymentProbeResult | undefined; + switch (result?.target) { + case "allowed": return undefined; + case "payment": return "payment_refused"; + case "security": return "security_check"; + default: return "target_changed"; + } + } + + private releaseObject(objectId: string, debuggerSessionId?: string): void { + void this.sendInSession("Runtime.releaseObject", { objectId }, debuggerSessionId).catch(() => {}); + } + + private async inputRefFailure( + record: RefRecord, + action: "click" | "key" | "type", + mode: PaymentProbeMode | undefined, + requireFocused = false, + ): Promise { + const validation = await this.validateRef(record, action, false, requireFocused); + if (!validation.ok) return validation.reason; + const element = validation.descriptor; + const frame = this.frameSessions.get(record.frameId); + if ( + mode !== undefined && ( + isCardField(element) || + (mode !== "type" && isOrderPlacementControl(element)) || + (frame?.targetType === "iframe" && frame.url !== undefined && isPaymentProviderFrame(frame.url)) + ) + ) { + return "payment_refused"; + } + if (isSecurityCheck(element)) return "security_check"; + if (mode === undefined) return undefined; + const contextId = await this.automationWorld(record.frameId, record.debuggerSessionId); + const { object } = await this.sendInSession( + "DOM.resolveNode", + { backendNodeId: record.backendNodeId, executionContextId: contextId }, + record.debuggerSessionId, + ); + if (object?.objectId === undefined) return "target_changed"; + try { + const failure = await this.probeInputTarget( + object.objectId, + mode, + record.debuggerSessionId, + requireFocused, + ); + if (record.generation !== this.generation) return "target_changed"; + return failure; + } finally { + this.releaseObject(object.objectId, record.debuggerSessionId); + } + } + + private async focusedInput( + mode: PaymentProbeMode, + ): Promise<{ failure?: ActionFailureReason; sessionId?: string }> { + let frameId = this.mainFrameId; + let sessionId: string | undefined; + const generation = this.generation; + const visited = new Set(); + while (frameId !== "" && !visited.has(frameId)) { + visited.add(frameId); + const contextId = await this.automationWorld(frameId, sessionId); + const result = await this.sendInSession( + "Runtime.evaluate", + { contextId, expression: FOCUSED_ELEMENT_EXPRESSION }, + sessionId, + ); + const objectId = result.result?.objectId; + if (objectId === undefined) break; + let frameOwner: string | undefined; + try { + const { node } = await this.sendInSession( + "DOM.describeNode", + { objectId, depth: 0, pierce: true }, + sessionId, + ); + if (node.localName === "iframe" || node.localName === "frame") { + frameOwner = node.frameId; + } else { + if (node.shadowRoots?.some((root) => root.shadowRootType === "closed")) break; + const [partial, failure] = await Promise.all([ + this.sendInSession( + "Accessibility.getPartialAXTree", + { backendNodeId: node.backendNodeId, fetchRelatives: false }, + sessionId, + ), + this.probeInputTarget(objectId, mode, sessionId, true), + ]); + if (generation !== this.generation) return { failure: "target_changed" }; + const ax = partial.nodes.find((entry) => entry.backendDOMNodeId === node.backendNodeId); + if (ax !== undefined) { + const decoded = decodeAxNode(ax); + if (isSecurityCheck(decoded)) return { failure: "security_check" }; + if (isOrderPlacementControl(decoded) || isCardField(decoded)) { + return { failure: "payment_refused" }; + } + } + return { failure, sessionId }; + } + } finally { + this.releaseObject(objectId, sessionId); + } + if (frameOwner === undefined) break; + await this.refreshFrameTopology(); + const frame = this.frameSessions.get(frameOwner); + if (frame?.ready !== true) break; + frameId = frameOwner; + sessionId = frame.sessionId; + } + return { failure: "payment_refused" }; + } + snapshotA11y(commandId: string): Promise { const deadlineAt = Date.now() + SNAPSHOT_DEADLINE_MS; return this.run( @@ -999,6 +1169,9 @@ export class CdpSession { ), true, ); + if (captured.nodes.some((node) => !node.ignored && isSecurityCheck(decodeAxNode(node)))) { + return this.actionFailure(commandId, "security_check", true, false); + } const { tree, refMap } = buildA11ySnapshot(captured.nodes, { scopeId: this.refScopeId, generation, @@ -1090,6 +1263,15 @@ export class CdpSession { }; } + private hasSecurityCheck(cache: SemanticCache): boolean { + const cardContext = cache.nodes.some(({ descriptor }) => isCardField(descriptor)); + return cache.nodes.some(({ descriptor }) => + descriptor.visibility !== "hidden" && isSecurityCheck(descriptor, cardContext), + ) || [...this.frameSessions.values()].some((frame) => + frame.targetType === "iframe" && frame.url !== undefined && isCaptchaFrame(frame.url), + ); + } + private topologyKey(frames: readonly FrameTopologyEntry[]): string { return frames .map( @@ -1249,6 +1431,9 @@ export class CdpSession { view, deadlineAt, ); + if (this.hasSecurityCheck(cache)) { + return this.semanticFailure(commandId, "snapshot", "security_check"); + } if ( changesOnly && previous !== null && @@ -1323,6 +1508,9 @@ export class CdpSession { const cache = this.semanticCache ?? (await this.captureFreshSemantic("document", "all", deadlineAt)).cache; + if (this.hasSecurityCheck(cache)) { + return this.semanticFailure(commandId, "find", "security_check"); + } return this.elementsPage( commandId, "find", @@ -1639,22 +1827,18 @@ export class CdpSession { if (record === null) { return this.actionFailure(commandId, "stale_ref", true, true); } - const validation = await this.validateRef(record, "click"); - if (!validation.ok) { - return this.actionFailure(commandId, validation.reason, true, true); + const failure = await this.inputRefFailure(record, "click", "activate"); + if (failure !== undefined) { + return this.actionFailure(commandId, failure, true, true); } const point = await this.prepareClick( record.backendNodeId, record.debuggerSessionId, ); - const afterPointerMove = await this.validateRef(record, "click"); - if (!afterPointerMove.ok) { - return this.actionFailure( - commandId, - afterPointerMove.reason, - true, - true, - ); + const afterPointerMove = await this.inputRefFailure(record, "click", "activate"); + if (afterPointerMove !== undefined) { + const reason = afterPointerMove === "payment_refused" ? "target_changed" : afterPointerMove; + return this.actionFailure(commandId, reason, true, true); } await this.dispatchPreparedClick(point, record.debuggerSessionId); return this.actionSuccess(commandId, false, true); @@ -1667,14 +1851,15 @@ export class CdpSession { if (record === null) { return this.actionFailure(commandId, "stale_ref", true, true); } - const validation = await this.validateRef(record, "type"); - if (!validation.ok) { - return this.actionFailure(commandId, validation.reason, true, true); + const mode = submit === true ? "submit" : "type"; + const failure = await this.inputRefFailure(record, "type", mode); + if (failure !== undefined) { + return this.actionFailure(commandId, failure, true, true); } await this.focus(record.backendNodeId, record.debuggerSessionId); - const afterFocus = await this.validateRef(record, "type", false, true); - if (!afterFocus.ok) { - return this.actionFailure(commandId, afterFocus.reason, true, true); + const afterFocus = await this.inputRefFailure(record, "type", mode, true); + if (afterFocus !== undefined) { + return this.actionFailure(commandId, afterFocus, true, true); } await this.sendInSession( "Input.insertText", @@ -1682,9 +1867,10 @@ export class CdpSession { record.debuggerSessionId, ); if (submit === true) { - const beforeSubmit = await this.validateRef(record, "type", false, true); - if (!beforeSubmit.ok) { - return this.actionFailure(commandId, beforeSubmit.reason, true, true); + const beforeSubmit = await this.inputRefFailure(record, "type", "submit", true); + if (beforeSubmit !== undefined) { + const reason = beforeSubmit === "payment_refused" ? "target_changed" : beforeSubmit; + return this.actionFailure(commandId, reason, true, true); } await this.dispatchKey(parseKeys("Enter"), record.debuggerSessionId); } @@ -1695,15 +1881,16 @@ export class CdpSession { key(commandId: string, keys: string, ref?: string): Promise { return this.run(commandId, async () => { const parsed = parseKeys(keys); + const mode = parsed.key === "Enter" ? "submit" : parsed.key === " " ? "activate" : undefined; let debuggerSessionId: string | undefined; if (ref !== undefined) { const record = this.resolveRef(ref); if (record === null) { return this.actionFailure(commandId, "stale_ref", true, true); } - const validation = await this.validateRef(record, "key"); - if (!validation.ok) { - return this.actionFailure(commandId, validation.reason, true, true); + const failure = await this.inputRefFailure(record, "key", mode); + if (failure !== undefined) { + return this.actionFailure(commandId, failure, true, true); } debuggerSessionId = record.debuggerSessionId; await this.sendInSession( @@ -1711,16 +1898,76 @@ export class CdpSession { { backendNodeId: record.backendNodeId }, debuggerSessionId, ); - const afterFocus = await this.validateRef(record, "key", false, true); - if (!afterFocus.ok) { - return this.actionFailure(commandId, afterFocus.reason, true, true); + const afterFocus = await this.inputRefFailure(record, "key", mode, true); + if (afterFocus !== undefined) { + return this.actionFailure(commandId, afterFocus, true, true); + } + } else if (mode !== undefined) { + const focused = await this.focusedInput(mode); + if (focused.failure !== undefined) { + return this.actionFailure(commandId, focused.failure, true, true); } + debuggerSessionId = focused.sessionId; } await this.dispatchKey(parsed, debuggerSessionId); return this.actionSuccess(commandId, false, parsed.key === "Enter"); }); } + pageRequest(command: PageRequestCommand, executionDeadlineAt = Infinity): Promise { + const { commandId, path, query, body, method = "GET" } = command; + const deadlineAt = Math.min(executionDeadlineAt, Date.now() + PAGE_REQUEST_TIMEOUT_MS); + return this.run(commandId, async () => { + const failure = (reason: ActionFailureReason): Event => + this.actionFailure(commandId, reason, false, false); + const allowedOrigins = this.allowedOrigins; + if (allowedOrigins === null) return failure("navigation_blocked"); + try { + const page = await this.mainFrameIdentity(deadlineAt); + const origin = new URL(page.url).origin; + const url = resolvePageRequestUrl(origin, path, query); + if (url === null || !allowedOrigins.has(origin)) return failure("navigation_blocked"); + if (method !== "GET" && !this.pageRequestWrites.some((rule) => + rule.origin === origin && rule.path === url.pathname && rule.method === method, + )) { + return failure("navigation_blocked"); + } + const executionContextId = await this.withSnapshotDeadline(deadlineAt, () => + this.automationWorld(page.frameId), + ); + if (this.allowedOrigins !== allowedOrigins) return failure("navigation_blocked"); + const response = await this.withSnapshotDeadline(deadlineAt, () => + this.send("Runtime.callFunctionOn", { + executionContextId, + functionDeclaration: PAGE_REQUEST_FUNCTION, + arguments: [{ value: { + origin, + url: url.href, + method, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + deadlineAt, + maxBytes: PAGE_REQUEST_BODY_MAX_BYTES, + } }], + awaitPromise: true, + returnByValue: true, + }), + ); + const result = response.result?.value as { + reason?: "timeout" | "navigation_blocked" | "result_too_large" | "action_failed"; + status?: number; + json?: string; + } | undefined; + if (result?.reason !== undefined) return failure(result.reason); + if (result?.status === undefined || typeof result.json !== "string") return failure("action_failed"); + const parsed = PageRequestBodySchema.safeParse(JSON.parse(result.json)); + if (!parsed.success) return failure("action_failed"); + return { type: "page_request_result", commandId, status: result.status, body: parsed.data }; + } catch { + return failure(Date.now() >= deadlineAt ? "timeout" : "action_failed"); + } + }, deadlineAt); + } + scroll(commandId: string, dy: number, ref?: string): Promise { return this.run(commandId, async () => { if (ref === undefined) { diff --git a/apps/extension/src/driver/keymap.ts b/apps/extension/src/driver/keymap.ts index 9b9a5f7..536e094 100644 --- a/apps/extension/src/driver/keymap.ts +++ b/apps/extension/src/driver/keymap.ts @@ -56,7 +56,9 @@ interface NamedKey { const NAMED_KEYS: Record = { enter: { key: "Enter", code: "Enter", windowsVirtualKeyCode: 13, text: "\r" }, + numpadenter: { key: "Enter", code: "NumpadEnter", windowsVirtualKeyCode: 13, text: "\r" }, return: { key: "Enter", code: "Enter", windowsVirtualKeyCode: 13, text: "\r" }, + space: { key: " ", code: "Space", windowsVirtualKeyCode: 32, text: " " }, tab: { key: "Tab", code: "Tab", windowsVirtualKeyCode: 9 }, escape: { key: "Escape", code: "Escape", windowsVirtualKeyCode: 27 }, esc: { key: "Escape", code: "Escape", windowsVirtualKeyCode: 27 }, @@ -76,7 +78,7 @@ const NAMED_KEYS: Record = { }; export function parseKeys(spec: string): ParsedKey { - const tokens = spec.split("+").map((token) => token.trim()); + const tokens = (spec === " " ? "Space" : spec).split("+").map((token) => token.trim()); const keyToken = tokens.pop(); if (keyToken === undefined || keyToken === "") { throw new Error(`Invalid key spec: "${spec}"`); diff --git a/apps/extension/src/driver/page-request.ts b/apps/extension/src/driver/page-request.ts new file mode 100644 index 0000000..9060257 --- /dev/null +++ b/apps/extension/src/driver/page-request.ts @@ -0,0 +1,54 @@ +// CDP receives a packaged function declaration and passes command data as arguments. +export const PAGE_REQUEST_FUNCTION = String.raw`async function (request) { + if (self.origin !== request.origin || location.origin !== request.origin) { + return { reason: "navigation_blocked" }; + } + const remaining = request.deadlineAt - Date.now(); + if (remaining <= 0) return { reason: "timeout" }; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), remaining); + try { + const response = await fetch(request.url, { + method: request.method, + mode: "same-origin", + credentials: "same-origin", + redirect: "manual", + cache: "no-store", + headers: request.body === undefined + ? { accept: "application/json" } + : { accept: "application/json", "content-type": "application/json" }, + body: request.body, + signal: controller.signal, + }); + if (response.type === "opaqueredirect" || (response.status >= 300 && response.status < 400)) { + return { reason: "navigation_blocked" }; + } + if (response.url && new URL(response.url).origin !== request.origin) { + return { reason: "navigation_blocked" }; + } + if (response.status === 204 || response.status === 205) { + return { status: response.status, json: "null" }; + } + const contentType = response.headers.get("content-type") ?? ""; + if (!/^\s*application\/(?:json|[\w.+-]+\+json)(?:\s*;|\s*$)/i.test(contentType) || response.body === null) { + return { reason: "action_failed" }; + } + const reader = response.body.getReader(); + const decoder = new TextDecoder("utf-8", { fatal: true }); + let size = 0; + let json = ""; + while (true) { + const chunk = await reader.read(); + if (chunk.done) break; + size += chunk.value.byteLength; + if (size > request.maxBytes) return { reason: "result_too_large" }; + json += decoder.decode(chunk.value, { stream: true }); + } + return { status: response.status, json: json + decoder.decode() }; + } catch { + return { reason: controller.signal.aborted ? "timeout" : "action_failed" }; + } finally { + clearTimeout(timer); + controller.abort(); + } +}`; diff --git a/apps/extension/src/driver/payment-guard.ts b/apps/extension/src/driver/payment-guard.ts new file mode 100644 index 0000000..d09a4c5 --- /dev/null +++ b/apps/extension/src/driver/payment-guard.ts @@ -0,0 +1,184 @@ +import type { ElementDescriptor } from "@understudy/protocol"; + +// The deterministic gate follows Nanobrowser's interaction gate design (Apache-2.0). +const ORDER_NAME = /^pay(?:$|\p{P}|\s+(?:now\b|with\b|by\b|on\b|for\b|later\b|\p{Sc}|\d))|\b(?:(?:place|confirm|submit|complete|finalize)\s+(?:(?:your|my|the)\s+)?order|confirm\s+and\s+pay|complete\s+(?:your\s+)?purchase|cash\s+on\s+delivery)\b|(?:[اإ]دفع|دفع الآن|الدفع الآن|تأكيد (?:الطلب|طلبك)|[اإ]تمام (?:الطلب|الشراء)|[اإ]كمال الطلب|تقديم الطلب|الدفع عند الاستلام)/iu; +const CARD_NAME = /\b(?:(?:card|cc)\s*(?:number|no|holder|exp|expiry|expiration|security code)|name on (?:the )?card|(?:expiry|expiration) (?:date|month|year)|mm\s*\/\s*yy(?:yy)?|cvv2?|cvc2?|cvn|csc)\b|(?:رقم البطاقة|اسم حامل البطاقة|تاريخ انتهاء البطاقة|رمز أمان البطاقة)/iu; +const SECURITY_CODE_NAME = /\b(?:(?:one[ -]time|verification|authentication)\s+(?:passcode|password|code)|otp|(?:enter|send|resend)\s+(?:(?:the|your|a|new)\s+)?security code)\b|(?:رمز التحقق|رمز المصادقة|رمز الأمان|رمز لمرة واحدة)/iu; +const SECURITY_PROMPT_NAME = /\b(?:captcha|recaptcha|hcaptcha|security check|two[ -](?:step|factor) verification|verify (?:that )?you(?:'re| are) (?:a )?human|human verification)\b|(?:تحقق أمني|التحقق الأمني|تحقق من أنك إنسان)/iu; +const BARE_SECURITY_CODE = /^security code$/iu; +const PAYMENT_PROVIDER_HOSTS = [ + "adyen.com", + "amazonpaymentservices.com", + "braintreegateway.com", + "checkout.com", + "payfort.com", + "paypal.com", + "stripe.com", +]; + +type ElementFacts = Pick, "role" | "name" | "description" | "form">; + +function normalizedLabel(value: string | undefined): string { + return (value ?? "").normalize("NFKC").replace(/[\p{Mark}\u0640]/gu, "").replace(/[\s_-]+/gu, " ").trim(); +} + +export function isOrderPlacementControl(element: ElementFacts): boolean { + return ["button", "link", "menuitem"].some((role) => role === element.role) && + [element.name, element.description].some((label) => ORDER_NAME.test(normalizedLabel(label))); +} + +export function isCardField(element: ElementFacts): boolean { + const autocomplete = element.form?.autocomplete?.toLowerCase().split(/\s+/) ?? []; + return autocomplete.some((token) => token.startsWith("cc-")) || + (["textbox", "searchbox", "spinbutton", "combobox"].some((role) => role === element.role) && + [element.name, element.form?.placeholder].some((label) => CARD_NAME.test(normalizedLabel(label)))); +} + +export function isSecurityCheck(element: ElementFacts, cardContext = false): boolean { + const labels = [element.name, element.description, element.form?.placeholder].map(normalizedLabel); + if (element.form?.autocomplete?.toLowerCase().split(/\s+/).includes("one-time-code")) { + return true; + } + if (["textbox", "searchbox", "spinbutton"].some((role) => role === element.role)) { + return labels.some((label) => SECURITY_CODE_NAME.test(label) || (!cardContext && BARE_SECURITY_CODE.test(label))); + } + if (["heading", "dialog", "alert", "alertdialog", "iframe", "Iframe"].some((role) => role === element.role)) { + return labels.some((label) => SECURITY_PROMPT_NAME.test(label) || SECURITY_CODE_NAME.test(label) || + (!cardContext && BARE_SECURITY_CODE.test(label))); + } + return false; +} + +export const PAYMENT_PROBE_RULES = { + order: ORDER_NAME.source, + card: CARD_NAME.source, + code: SECURITY_CODE_NAME.source, + challenge: SECURITY_PROMPT_NAME.source, + bareCode: BARE_SECURITY_CODE.source, + paymentHosts: PAYMENT_PROVIDER_HOSTS, +}; + +export function isPaymentProviderFrame(value: string): boolean { + try { + const hostname = new URL(value).hostname.replace(/\.$/u, ""); + return PAYMENT_PROVIDER_HOSTS.some((host) => hostname === host || hostname.endsWith(`.${host}`)); + } catch { + return false; + } +} + +export function isCaptchaFrame(value: string): boolean { + try { + const { hostname, pathname } = new URL(value); + return (hostname === "www.google.com" || hostname === "www.recaptcha.net") && + /\/recaptcha\/(?:api2|enterprise)\/bframe$/.test(pathname) || + hostname.endsWith(".hcaptcha.com") && pathname.includes("/challenge"); + } catch { + return false; + } +} + +export type PaymentProbeMode = "type" | "activate" | "submit"; +export interface PaymentProbeResult { + target: "allowed" | "payment" | "security" | "missing"; +} + +export const FOCUSED_ELEMENT_EXPRESSION = `(() => { + let target = document.activeElement; + while (target?.shadowRoot?.activeElement) target = target.shadowRoot.activeElement; + return target === document.body || target === document.documentElement ? null : target; +})()`; + +export const PAYMENT_TARGET_PROBE = String.raw`function (rules, mode, requireFocused) { + const label = (value) => (value ?? "").normalize("NFKC") + .replace(/[\p{Mark}\u0640]/gu, "").replace(/[\s_-]+/gu, " ").trim(); + const order = new RegExp(rules.order, "iu"); + const card = new RegExp(rules.card, "iu"); + const code = new RegExp(rules.code, "iu"); + const challenge = new RegExp(rules.challenge, "iu"); + const bareCode = new RegExp(rules.bareCode, "iu"); + const hostMatches = (host, domain) => host === domain || host.endsWith("." + domain); + const isPaymentUrl = (value) => { + try { + const hostname = new URL(value).hostname.replace(/\.$/u, ""); + return rules.paymentHosts.some((host) => hostMatches(hostname, host)); + } catch { + return false; + } + }; + const isCaptchaFrame = (frame) => { + if (challenge.test(label(frame.title))) return true; + try { + const url = new URL(frame.src || "about:blank", location.href); + return (hostMatches(url.hostname, "google.com") || hostMatches(url.hostname, "recaptcha.net")) && + /\/recaptcha\/(?:api2|enterprise)\/(?:anchor|bframe)$/.test(url.pathname) || + hostMatches(url.hostname, "hcaptcha.com") || url.hostname === "challenges.cloudflare.com"; + } catch { + return false; + } + }; + const visible = (element) => { + const bounds = element.getBoundingClientRect(); + return bounds.width > 0 && bounds.height > 0 && getComputedStyle(element).visibility === "visible"; + }; + const attr = (element, name) => element.getAttribute(name) ?? ""; + const autocomplete = (field) => attr(field, "autocomplete").toLowerCase().split(/\s+/); + const labels = (element) => { + const root = element.getRootNode(); + const associated = (kind) => attr(element, kind).split(/\s+/) + .map((id) => id ? root.getElementById?.(id)?.textContent : "").join(" "); + return [attr(element, "aria-label"), attr(element, "aria-description"), + associated("aria-labelledby"), associated("aria-describedby"), attr(element, "title"), + ...Array.from(element.labels ?? [], (item) => item.textContent)]; + }; + const inputSelector = 'input:not([type="hidden" i]), select, textarea, [role="textbox"], [contenteditable="true"]'; + const isCardField = (field) => field.matches(inputSelector) && + (autocomplete(field).some((token) => token.startsWith("cc-")) || + [...labels(field), attr(field, "placeholder"), + attr(field, "name").replace(/([a-z])([A-Z])/g, "$1 $2"), + field.id.replace(/([a-z])([A-Z])/g, "$1 $2")].some((value) => card.test(label(value)))); + const orderSelector = 'button, a[href], input[type="submit" i], input[type="button" i], [role="button"], [role="link"], [role="menuitem"]'; + const isOrderControl = (element) => element.matches(orderSelector) && + [...labels(element), element.textContent, element instanceof HTMLInputElement && attr(element, "value") || ""] + .some((value) => order.test(label(value))); + const ancestors = function* (element) { + for (let node = element; node instanceof Element;) { + yield node; + node = node.assignedSlot ?? node.parentElement ?? node.getRootNode().host; + } + }; + + const target = this; + if (!(target instanceof Element) || !target.isConnected) return { target: "missing" }; + if (requireFocused && target.getRootNode().activeElement !== target) return { target: "missing" }; + + if (window !== window.top && [location.href, ...Array.from(location.ancestorOrigins)].some(isPaymentUrl)) { + return { target: "payment" }; + } + const chain = [...ancestors(target)]; + if (chain.some(isCardField) || (mode !== "type" && chain.some(isOrderControl))) { + return { target: "payment" }; + } + if (chain.some((node) => autocomplete(node).includes("one-time-code") || + node.matches(inputSelector) && [...labels(node), attr(node, "placeholder")].some((value) => { + const name = label(value); + return code.test(name) || bareCode.test(name); + }))) { + return { target: "security" }; + } + if (Array.from(document.querySelectorAll('input[autocomplete~="one-time-code" i], iframe')).some((node) => + visible(node) && (!(node instanceof HTMLIFrameElement) || isCaptchaFrame(node)))) { + return { target: "security" }; + } + if (mode !== "type") { + const form = chain.find((node) => node instanceof HTMLFormElement || node.form instanceof HTMLFormElement); + const owner = form instanceof HTMLFormElement ? form : form?.form; + const fields = owner === undefined + ? [...new Set([target.getRootNode(), document])].flatMap((root) => Array.from(root.querySelectorAll(inputSelector))) + : Array.from(Object.getOwnPropertyDescriptor(HTMLFormElement.prototype, "elements").get.call(owner)); + if (fields.some(isCardField) || mode === "submit" && owner !== undefined && fields.some(isOrderControl)) { + return { target: "payment" }; + } + } + return { target: "allowed" }; +}`; diff --git a/apps/extension/src/driver/semantic/cdp-semantic.test.ts b/apps/extension/src/driver/semantic/cdp-semantic.test.ts index 52b2524..ccf8d77 100644 --- a/apps/extension/src/driver/semantic/cdp-semantic.test.ts +++ b/apps/extension/src/driver/semantic/cdp-semantic.test.ts @@ -3,9 +3,9 @@ import type { Protocol } from "devtools-protocol"; import type { ElementsResult } from "@understudy/protocol"; import { CdpSession } from "../cdp"; -function domSnapshot() { +function domSnapshot(challenge?: "code" | "captcha") { return { - strings: ["main", "HTML", "BUTTON"], + strings: ["main", "HTML", "BUTTON", "INPUT", "autocomplete", "one-time-code"], documents: [ { frameId: 0, @@ -13,9 +13,9 @@ function domSnapshot() { scrollOffsetY: 0, nodes: { backendNodeId: [1, 11, 12, 13, 14], - nodeName: [1, 2, 2, 2, 2], + nodeName: [1, challenge === "code" ? 3 : 2, 2, 2, 2], parentIndex: [-1, 0, 0, 0, 0], - attributes: [[], [], [], [], []], + attributes: [[], challenge === "code" ? [4, 5] : [], [], [], []], isClickable: { index: [1, 2, 3, 4] }, }, layout: { @@ -61,7 +61,7 @@ function fullAxTree(capture: number): { nodes: Protocol.Accessibility.AXNode[] } }; } -function semanticBrowser(): ReturnType { +function semanticBrowser(challenge?: "code" | "captcha"): ReturnType { let capture = 0; const sendCommand = vi.fn( async (_target, method: string, params?: { backendNodeId?: number }) => { @@ -76,7 +76,7 @@ function semanticBrowser(): ReturnType { }, }; } - if (method === "DOMSnapshot.captureSnapshot") return domSnapshot(); + if (method === "DOMSnapshot.captureSnapshot") return domSnapshot(challenge); if (method === "Page.getLayoutMetrics") { return { cssVisualViewport: { @@ -93,7 +93,14 @@ function semanticBrowser(): ReturnType { } if (method === "Accessibility.getFullAXTree") { capture += 1; - return fullAxTree(capture); + const tree = fullAxTree(capture); + const signal = tree.nodes[1]!; + if (challenge === "code") signal.role = { type: "role", value: "textbox" }; + if (challenge === "captcha") { + signal.role = { type: "role", value: "heading" }; + signal.name = { type: "computedString", value: "Verify you are human" }; + } + return tree; } if (method === "Accessibility.getPartialAXTree") { const backendNodeId = params?.backendNodeId ?? 11; @@ -164,6 +171,25 @@ afterEach(() => { }); describe("CdpSession semantic results", () => { + it.each(["code", "captcha"] as const)("reports a %s challenge as a nonretryable security check", async (challenge) => { + // #given + semanticBrowser(challenge); + const session = await CdpSession.create(7, "semantic"); + + // #when + const result = await session.captureElements("check", "document", "interactive", 2, false); + + // #then + expect(result).toEqual({ + type: "elements_result", + commandId: "check", + operation: "snapshot", + status: "error", + reason: "security_check", + retryable: false, + }); + }); + it("paginates immutable results and keeps find, inspect, and next capture-free", async () => { const sendCommand = semanticBrowser(); const session = await CdpSession.create(7, "semantic"); diff --git a/apps/extension/src/driver/semantic/types.ts b/apps/extension/src/driver/semantic/types.ts index 8a29d4a..267764d 100644 --- a/apps/extension/src/driver/semantic/types.ts +++ b/apps/extension/src/driver/semantic/types.ts @@ -13,6 +13,7 @@ export interface DebuggerFrameSession { parentSessionId?: string; targetType: "page" | "iframe"; ready: boolean; + url?: string; } export interface FrameTopologyEntry { diff --git a/packages/connector/src/index.test.ts b/packages/connector/src/index.test.ts index 253a5b7..5b14f0f 100644 --- a/packages/connector/src/index.test.ts +++ b/packages/connector/src/index.test.ts @@ -106,6 +106,28 @@ describe("grant gate (fail closed)", () => { }); describe("act", () => { + it("requires approval for a page request write and replays its HTTP receipt without JSON", async () => { + // #given + const fetchSpy = vi.fn().mockResolvedValue(eventResponse({ + type: "page_request_result", commandId: "reply", status: 201, body: { records: [1] }, + })); + vi.stubGlobal("fetch", fetchSpy); + const { act } = createBrowserConnectors(ENV, stores()); + const input: ActInput = { sessionId: "s-1", action: { type: "page_request", path: "/orders", method: "POST" } }; + + // #when + await expect(callBrowserWrite(act, input, undefined, "write")).rejects.toThrowError(ConnectorPolicyError); + const grant = grantFor(BROWSER_ACT_CONNECTOR); + const output = await callBrowserWrite(act, input, grant, "write"); + const replay = await callBrowserWrite(act, input, grant, "write"); + + // #then + const receipt = { ok: true, pageResponse: { status: 201, bodyUnavailable: true } }; + expect(output).toEqual(receipt); + expect(replay).toEqual(receipt); + expect(fetchSpy).toHaveBeenCalledOnce(); + }); + it("executes with the grant: bearer auth, /v1 route, protocol command; replays on the same key", async () => { const fetchSpy = vi.fn().mockResolvedValue( eventResponse({ type: "action_result", commandId: "c1", ok: true, url: "https://portal.example/" }), @@ -160,6 +182,17 @@ describe("observe (read - no grant, no idempotency)", () => { return callConnector(observe, { sessionId: "s-1", read }, undefined); } + it("returns page request JSON on the read path", async () => { + // #when + const output = await observeRead( + { type: "page_request", path: "/orders" }, + { type: "page_request_result", commandId: "reply", status: 200, body: { records: [1] } }, + ); + + // #then + expect(output).toEqual({ pageResponse: { status: 200, body: { records: [1] } } }); + }); + it("snapshot returns the a11y tree", async () => { const tree = [{ ref: "opaque-tree-ref", role: "button", name: "Go" }]; const out = await observeRead( diff --git a/packages/connector/src/index.ts b/packages/connector/src/index.ts index a4e33b1..c63a278 100644 --- a/packages/connector/src/index.ts +++ b/packages/connector/src/index.ts @@ -4,9 +4,8 @@ * agent, approvals, RBAC, and audit live in the CONSUMER importing this). * * Two connectors, one governance class each: - * observe - read (snapshot / get_tabs / wait). No approval. - * act - write (click / type / navigate / key / scroll / - * switch_tab). Fails closed unless the request carries a + * observe - read (snapshot / get_tabs / wait / GET page_request). No approval. + * act - write. Fails closed unless the request carries a * flowsafe-minted grant in * requestContext['breakwater.approvedConnectors']. * @@ -18,6 +17,7 @@ import { RequestContext } from "@mastra/core/request-context"; import type { ToolExecutionContext } from "@mastra/core/tools"; import { + ActionFailureReasonSchema, type ConnectorPolicies, type ConnectorRuntime, createConnector, @@ -37,6 +37,9 @@ import { type Event, parseCommand, parseEvent, + PageRequestBodySchema, + PageRequestReadInputSchema, + PageRequestWriteInputSchema, PendingCommandResponseSchema, type PendingCommandResponse, type CommandStatusResponse, @@ -121,6 +124,7 @@ export const observeInput = z.object({ tabId: ConnectorTabIdSchema.optional(), }).strict(), z.object({ type: z.literal("get_tabs") }).strict(), + PageRequestReadInputSchema, z.object({ type: z.literal("wait"), for: z.enum(["load", "idle", "ms"]), @@ -157,7 +161,12 @@ export const observeOutput = z.object({ dialogs: z.array(DialogRecordSchema).optional(), /** Wait outcome, or `false` when the driver rejects a snapshot. */ ok: z.boolean().optional(), + reason: ActionFailureReasonSchema.optional(), error: z.string().optional(), + pageResponse: z.union([ + z.object({ status: z.number(), body: PageRequestBodySchema }).strict(), + z.object({ status: z.number(), bodyUnavailable: z.literal(true) }).strict(), + ]).optional(), }).strict(); export type ObserveOutput = z.infer; @@ -187,6 +196,7 @@ export const actInput = z.object({ dy: z.number().finite(), }).strict(), z.object({ type: z.literal("switch_tab"), tabId: ConnectorTabIdSchema }).strict(), + PageRequestWriteInputSchema, ]), }).strict(); export type ActInput = z.infer; @@ -195,7 +205,9 @@ export const actOutput = z.object({ ok: z.boolean(), url: z.string().optional(), error: z.string().optional(), + reason: ActionFailureReasonSchema.optional(), simulated: z.boolean().optional(), + pageResponse: z.object({ status: z.number(), bodyUnavailable: z.literal(true) }).strict().optional(), }).strict(); export type ActOutput = z.infer; @@ -422,7 +434,7 @@ export function createBrowserConnectors( const observe = createConnector({ id: BROWSER_OBSERVE_CONNECTOR, description: - "Observe the browser session: a11y-tree/DOM/screenshot snapshot of the page (target elements by the returned refs), list open tabs, read recent page dialogs the browser auto-handled, or wait for load/idle/ms. Read-only.", + "Observe the browser session: snapshot the page, list open tabs, read recent dialogs, wait, or request same-origin JSON with GET. Read-only.", inputSchema: observeInput, outputSchema: observeOutput, permissions: { sideEffect: "read", egress }, @@ -447,7 +459,7 @@ export function createBrowserConnectors( }; } if (ev.type === "action_result" && !ev.ok) { - return { ok: false, error: ev.error }; + return { ok: false, error: ev.error, ...(ev.reason === undefined ? {} : { reason: ev.reason }) }; } break; case "get_tabs": @@ -456,6 +468,15 @@ export function createBrowserConnectors( case "wait": if (ev.type === "action_result") return { ok: ev.ok, error: ev.error }; break; + case "page_request": + if (ev.type === "page_request_result") { + const { status, body } = ev; + return { pageResponse: body === undefined ? { status, bodyUnavailable: true } : { status, body } }; + } + if (ev.type === "action_result") { + return { ok: ev.ok, error: ev.error, ...(ev.reason === undefined ? {} : { reason: ev.reason }) }; + } + break; } throw new Error(`observe: unexpected event '${ev.type}' for read '${read.type}'`); }, @@ -466,8 +487,8 @@ export function createBrowserConnectors( const act = createConnector({ id: BROWSER_ACT_CONNECTOR, description: - "Perform a state-changing browser action (click/type/navigate/key/scroll/switch_tab) in the session. Requires approval. " + - "NEVER put passwords, API keys, card numbers, card security codes, or other credentials in type.text.", + "Perform a state-changing browser action or an approved same-origin page request. Requires approval. " + + "Keep passwords, API keys, card data, and other credentials out of command inputs.", inputSchema: actInput, outputSchema: actOutput, permissions: { @@ -481,7 +502,16 @@ export function createBrowserConnectors( execute: async (input, ctx, runtime): Promise => { const command = toCommand(input.action, await idempotencyCommandId(ctx)); const ev = await callUnderstudy(runtime, env, input.sessionId, command); - if (ev.type === "action_result") return { ok: ev.ok, url: ev.url, error: ev.error }; + if (ev.type === "action_result") { + return { ok: ev.ok, url: ev.url, error: ev.error, ...(ev.reason === undefined ? {} : { reason: ev.reason }) }; + } + if (command.type === "page_request" && ev.type === "page_request_result") { + // The idempotency store persists connector output. + return { + ok: ev.status >= 200 && ev.status < 300, + pageResponse: { status: ev.status, bodyUnavailable: true }, + }; + } throw new Error(`act: unexpected event '${ev.type}'`); }, // Simulation: the service checks the ref still resolves (via its internal @@ -495,7 +525,13 @@ export function createBrowserConnectors( dryRun: true, }); if (ev.type === "action_result") { - return { ok: ev.ok, url: ev.url, error: ev.error, simulated: true }; + return { + ok: ev.ok, + url: ev.url, + error: ev.error, + simulated: true, + ...(ev.reason === undefined ? {} : { reason: ev.reason }), + }; } throw new Error(`act(dryRun): unexpected event '${ev.type}'`); }, diff --git a/packages/protocol/src/index.test.ts b/packages/protocol/src/index.test.ts index 59edde8..aa052eb 100644 --- a/packages/protocol/src/index.test.ts +++ b/packages/protocol/src/index.test.ts @@ -8,6 +8,7 @@ import { DeviceControlServerFrameSchema, DialogRecordSchema, EventSchema, + PAGE_REQUEST_BODY_MAX_BYTES, PROTOCOL_CAPABILITIES, PROTOCOL_VERSION, SessionClientFrameSchema, @@ -40,6 +41,9 @@ describe("command result correlation", () => { expect(isCommandResultEvent("inspect_elements", "elements_result")).toBe(true); expect(isCommandResultEvent("continue_elements", "elements_result")).toBe(true); expect(isCommandResultEvent("get_tabs", "tabs_result")).toBe(true); + expect(isCommandResultEvent("page_request", "page_request_result")).toBe(true); + expect(isCommandResultEvent("page_request", "action_result")).toBe(true); + expect(isCommandResultEvent("click", "page_request_result")).toBe(false); expect(isCommandResultEvent("fill_secret", "action_result")).toBe(false); expect(isCommandType("fill_secret")).toBe(false); }); @@ -273,8 +277,8 @@ describe("isWriteCommand", () => { expect(isWriteCommand(switchTab)).toBe(true); }); - it("agrees with the exported WRITE_COMMAND_TYPES tuple for every command type", () => { - // #given every command type in the union, as a representative command + it("agrees with WRITE_COMMAND_TYPES for fixed command types and a page request write", () => { + // #given representative commands const representatives: Command[] = [ { type: "snapshot", commandId: "c", mode: "a11y" }, { type: "navigate", commandId: "c", url: "https://example.com/" }, @@ -286,10 +290,10 @@ describe("isWriteCommand", () => { { type: "resolve_ref", commandId: "c", ref: "r" }, { type: "get_tabs", commandId: "c" }, { type: "switch_tab", commandId: "c", tabId: 1 }, + { type: "page_request", commandId: "c", path: "/orders", method: "POST" }, ]; - // #then the predicate and the tuple classify identically - the tuple is - // the published source of truth downstream layers build on + // #then for (const cmd of representatives) { expect(isWriteCommand(cmd)).toBe( (WRITE_COMMAND_TYPES as readonly string[]).includes(cmd.type), @@ -299,6 +303,65 @@ describe("isWriteCommand", () => { }); }); +describe("page_request protocol", () => { + const command = { type: "page_request", commandId: "request", path: "/orders" } as const; + const fence = { attemptId: "attempt", deadlineAt: "2030-01-01T00:00:00.000Z" }; + + it.each([undefined, "GET"] as const)("treats method %s as a read and rejects it in a write grant", (method) => { + // #given + const read = parseCommand({ ...command, ...(method === undefined ? {} : { method }) }); + + // #then + expect(isWriteCommand(read)).toBe(false); + expect(SessionServerFrameSchema.safeParse({ type: "command", ...fence, command: read }).success).toBe(true); + expect(SessionServerFrameSchema.safeParse({ type: "write_grant", ...fence, command: read }).success).toBe(false); + }); + + it("requires a write grant for a page_request that changes state", () => { + // #given + const write = { ...command, method: "POST", body: { operation: "example" } }; + + // #then + expect(SessionServerFrameSchema.safeParse({ type: "command", ...fence, command: write }).success).toBe(false); + const grant = { type: "write_grant", ...fence, command: write }; + expect(SessionServerFrameSchema.parse(grant)).toEqual(grant); + expect(SessionServerFrameSchema.safeParse({ + type: "write_prepare", ...fence, commandId: command.commandId, + commandType: "page_request", requestFingerprint: "a".repeat(64), + }).success).toBe(true); + }); + + it.each([ + ["a body with the default method", { body: { operation: "example" } }], + ["a caller-supplied header", { method: "GET", headers: { authorization: "synthetic" } }], + ["a code field", { method: "POST", code: "synthetic" }], + ["an oversized JSON body", { method: "POST", body: "é".repeat(PAGE_REQUEST_BODY_MAX_BYTES / 2) }], + ] as const)("rejects %s", (_label, fields) => { + expect(CommandSchema.safeParse({ ...command, ...fields }).success).toBe(false); + }); + + it("refuses a write rule outside its provisioned lease origins", () => { + // #given + const provision = { + type: "provision", + sessionId: "session", + leaseId: "lease", + browserEpoch: "browser", + leaseEpoch: 1, + policyVersion: 1, + sessionTicket: "synthetic", + allowedOrigins: ["https://shop.example"], + }; + const rule = { origin: "https://shop.example", path: "/orders", method: "POST" }; + + // #then + expect(DeviceControlServerFrameSchema.safeParse({ ...provision, pageRequestWrites: [rule] }).success).toBe(true); + expect(DeviceControlServerFrameSchema.safeParse({ + ...provision, pageRequestWrites: [{ ...rule, origin: "https://other.example" }], + }).success).toBe(false); + }); +}); + describe("EventSchema", () => { it("round-trips an accessibility snapshot with its attached target identity", () => { const ev = { diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts index 16af42d..10859bd 100644 --- a/packages/protocol/src/index.ts +++ b/packages/protocol/src/index.ts @@ -5,6 +5,7 @@ export const COMMAND_HTTP_BODY_MAX_BYTES = 128 * 1024; export const DEVICE_CONTROL_FRAME_MAX_BYTES = 64 * 1024; export const SESSION_RESULT_FRAME_MAX_BYTES = 16 * 1024 * 1024; export const ELEMENTS_RESULT_MAX_BYTES = 32 * 1024; +export const PAGE_REQUEST_BODY_MAX_BYTES = 32 * 1024; export const MAX_ELEMENT_DESCRIPTORS = 200; export const MAX_SEMANTIC_NODES = 20_000; export const MAX_A11Y_NODES = 5_000; @@ -181,6 +182,7 @@ export const ElementsFailureReasonSchema = z.enum([ "cursor_expired", "invalid_cursor", "unsupported", + "security_check", ]); export type ElementsFailureReason = z.infer; @@ -248,6 +250,8 @@ export const ActionFailureReasonSchema = z.enum([ "timeout", "action_failed", "result_too_large", + "payment_refused", + "security_check", ]); export type ActionFailureReason = z.infer; @@ -273,6 +277,100 @@ const CommandBase = { commandId: IdSchema, }; +export const PageRequestWriteMethodSchema = z.enum(["POST", "PUT", "PATCH", "DELETE"]); +export type PageRequestWriteMethod = z.infer; + +export const PageRequestBodySchema: z.ZodType>> = z.unknown().superRefine((value, ctx) => { + const pending = [{ value, depth: 0 }]; + let count = 0; + while (pending.length > 0) { + const item = pending.pop()!; + if (item.depth > 32) { + ctx.addIssue({ code: "custom", message: "page request JSON exceeds depth 32" }); + return; + } + if (typeof item.value === "object" && item.value !== null) { + const children = Object.values(item.value); + count += children.length; + if (count > PAGE_REQUEST_BODY_MAX_BYTES) { + ctx.addIssue({ code: "custom", message: "page request JSON exceeds the body limit" }); + return; + } + for (const child of children) { + pending.push({ value: child, depth: item.depth + 1 }); + } + } + } +}).pipe(z.json().superRefine((value, ctx) => { + if (utf8ByteLength(JSON.stringify(value)) > PAGE_REQUEST_BODY_MAX_BYTES) { + ctx.addIssue({ code: "custom", message: "page request JSON exceeds the body limit" }); + } +})); + +const PageRequestFields = { + type: z.literal("page_request"), + path: UrlStringSchema, + query: z.record(utf8String(256).min(1), utf8String(2048)).superRefine((value, ctx) => { + if (utf8ByteLength(JSON.stringify(value)) > 8 * 1024) { + ctx.addIssue({ code: "custom", message: "page request query exceeds 8192 bytes" }); + } + }).optional(), +}; + +export const PageRequestReadInputSchema = strictObject({ + ...PageRequestFields, + method: z.literal("GET").optional(), +}); +export const PageRequestWriteInputSchema = strictObject({ + ...PageRequestFields, + method: PageRequestWriteMethodSchema, + body: PageRequestBodySchema.optional(), +}); + +const PageRequestCommandSchema = strictObject({ + ...PageRequestFields, + ...CommandBase, + method: z.union([z.literal("GET"), PageRequestWriteMethodSchema]).optional(), + body: PageRequestBodySchema.optional(), +}).superRefine((command, ctx) => { + if ((command.method === undefined || command.method === "GET") && command.body !== undefined) { + ctx.addIssue({ code: "custom", path: ["body"], message: "GET cannot carry a body" }); + } +}); +export type PageRequestCommand = z.infer; + +export function resolvePageRequestUrl( + origin: string, + path: string, + query?: PageRequestCommand["query"], +): URL | null { + if (!path.startsWith("/") || path.startsWith("//") || /[\\?#\s\p{Cc}]/u.test(path)) { + return null; + } + try { + const url = new URL(path, origin); + if ((url.protocol !== "https:" && url.protocol !== "http:") || url.origin !== origin) { + return null; + } + for (const [key, value] of Object.entries(query ?? {})) url.searchParams.append(key, value); + return utf8ByteLength(url.href) <= 8 * 1024 ? url : null; + } catch { + return null; + } +} + +export const PageRequestWritePolicySchema = z.array(strictObject({ + origin: AllowedOriginSchema, + method: PageRequestWriteMethodSchema, + path: UrlStringSchema, +}).superRefine((rule, ctx) => { + const url = resolvePageRequestUrl(rule.origin, rule.path); + if (url === null || url.pathname !== rule.path) { + ctx.addIssue({ code: "custom", message: "page request write rule requires a canonical origin and path" }); + } +})).max(32); +export type PageRequestWritePolicy = z.infer; + const WaitCommandSchema = strictObject({ type: z.literal("wait"), ...CommandBase, @@ -358,6 +456,7 @@ export const CommandSchema = z.discriminatedUnion("type", [ strictObject({ type: z.literal("resolve_ref"), ...CommandBase, ref: RefSchema }), strictObject({ type: z.literal("get_tabs"), ...CommandBase }), strictObject({ type: z.literal("switch_tab"), ...CommandBase, tabId: NonnegativeIntSchema }), + PageRequestCommandSchema, ]); export type Command = z.infer; export type CommandType = Command["type"]; @@ -369,12 +468,18 @@ export const WRITE_COMMAND_TYPES = [ "navigate", "scroll", "switch_tab", + "page_request", ] as const satisfies readonly CommandType[]; export type WriteCommandType = (typeof WRITE_COMMAND_TYPES)[number]; const WRITE_COMMANDS = new Set(WRITE_COMMAND_TYPES); export const isWriteCommand = ( command: Command, -): command is Extract => WRITE_COMMANDS.has(command.type); +): command is ( + | Extract }> + | (PageRequestCommand & { method: PageRequestWriteMethod }) +) => command.type === "page_request" + ? command.method !== undefined && command.method !== "GET" + : WRITE_COMMANDS.has(command.type); export const PROTOCOL_CAPABILITIES = [ "safe-write-v3", @@ -384,6 +489,7 @@ export const PROTOCOL_CAPABILITIES = [ "device-policy-v1", "owned-window-inventory-v1", "semantic-elements-v1", + "page-request-v1", ] as const; export const ProtocolCapabilitySchema = z.enum(PROTOCOL_CAPABILITIES); export type ProtocolCapability = z.infer; @@ -451,6 +557,28 @@ const ActionResultSchema = strictObject({ } }); +const PageRequestResultSchema = strictObject({ + type: z.literal("page_request_result"), + ...CommandBase, + status: z.number().int().min(200).max(599), + body: PageRequestBodySchema.optional(), + bodyUnavailable: z.literal(true).optional(), +}).superRefine((event, ctx) => { + if ((event.body === undefined) === (event.bodyUnavailable === undefined)) { + ctx.addIssue({ code: "custom", message: "page request result requires a body or a receipt" }); + } +}); +export type PageRequestResult = z.infer; + +export function pageRequestReceipt(event: PageRequestResult): PageRequestResult { + return { + type: "page_request_result", + commandId: event.commandId, + status: event.status, + bodyUnavailable: true, + }; +} + export const EventSchema = z.union([ HelloEventSchema, strictObject({ @@ -473,6 +601,7 @@ export const EventSchema = z.union([ }), ActionResultSchema, ElementsResultSchema, + PageRequestResultSchema, strictObject({ type: z.literal("page_event"), kind: z.enum(["navigated", "load"]), @@ -500,6 +629,7 @@ const COMMAND_RESULT_EVENT_TYPES = { resolve_ref: ["action_result"], get_tabs: ["tabs_result", "action_result"], switch_tab: ["action_result"], + page_request: ["page_request_result", "action_result"], } as const satisfies Record; export function isCommandResultEvent( @@ -538,6 +668,10 @@ export const SessionServerFrameSchema = z.discriminatedUnion("type", [ type: z.literal("command"), ...CommandFenceShape, command: CommandSchema, + }).superRefine((frame, ctx) => { + if (frame.command.type === "page_request" && isWriteCommand(frame.command)) { + ctx.addIssue({ code: "custom", path: ["command"], message: "page request write requires a grant" }); + } }), strictObject({ type: z.literal("write_prepare"), @@ -800,8 +934,13 @@ export const DeviceControlServerFrameSchema = z.discriminatedUnion("type", [ leaseEpoch: NonnegativeIntSchema, browserEpoch: IdSchema, allowedOrigins: z.array(AllowedOriginSchema).min(1).max(32), + pageRequestWrites: PageRequestWritePolicySchema.optional(), policyVersion: NonnegativeIntSchema, sessionTicket: z.string().min(1).max(4 * 1024), + }).superRefine((frame, ctx) => { + if (frame.pageRequestWrites?.some((rule) => !frame.allowedOrigins.includes(rule.origin))) { + ctx.addIssue({ code: "custom", path: ["pageRequestWrites"], message: "write origins must be allowed for the lease" }); + } }), strictObject({ type: z.literal("policy_update"), From b331ae01bea9144a1b7ebc773dbc181c9cc52b1f Mon Sep 17 00:00:00 2001 From: gcharang <21151592+gcharang@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:51:13 +0400 Subject: [PATCH 2/7] fix(protocol): resolve page_request URLs without the DOM lib The protocol package compiles against ES2022 alone, so the global URL type is missing there. It takes the runtime's WHATWG URL from globalThis through a local type and returns only the fields callers read. Co-Authored-By: Claude Opus 5.5 --- packages/protocol/src/index.ts | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts index 10859bd..c5a72f5 100644 --- a/packages/protocol/src/index.ts +++ b/packages/protocol/src/index.ts @@ -339,16 +339,30 @@ const PageRequestCommandSchema = strictObject({ }); export type PageRequestCommand = z.infer; +export interface ResolvedPageRequestUrl { + readonly href: string; + readonly origin: string; + readonly pathname: string; +} + +interface WhatwgUrl extends ResolvedPageRequestUrl { + readonly protocol: string; + readonly searchParams: { append(name: string, value: string): void }; +} + +// The package compiles against ES2022 alone; every runtime it ships to (browsers, Workers, Node) provides WHATWG URL. +const WhatwgURL = (globalThis as unknown as { URL: new (input: string, base: string) => WhatwgUrl }).URL; + export function resolvePageRequestUrl( origin: string, path: string, query?: PageRequestCommand["query"], -): URL | null { +): ResolvedPageRequestUrl | null { if (!path.startsWith("/") || path.startsWith("//") || /[\\?#\s\p{Cc}]/u.test(path)) { return null; } try { - const url = new URL(path, origin); + const url = new WhatwgURL(path, origin); if ((url.protocol !== "https:" && url.protocol !== "http:") || url.origin !== origin) { return null; } From 9b6331bdf7f53849e7c0ed018c007a336858b8e5 Mon Sep 17 00:00:00 2001 From: gcharang <21151592+gcharang@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:53:46 +0400 Subject: [PATCH 3/7] fix(connector): import ActionFailureReasonSchema from the protocol Co-Authored-By: Claude Opus 5.5 --- packages/connector/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/connector/src/index.ts b/packages/connector/src/index.ts index c63a278..2a31d7a 100644 --- a/packages/connector/src/index.ts +++ b/packages/connector/src/index.ts @@ -17,7 +17,6 @@ import { RequestContext } from "@mastra/core/request-context"; import type { ToolExecutionContext } from "@mastra/core/tools"; import { - ActionFailureReasonSchema, type ConnectorPolicies, type ConnectorRuntime, createConnector, @@ -30,6 +29,7 @@ import { } from "@proofoftech/breakwater/connector-sdk"; import { A11yNodeSchema, + ActionFailureReasonSchema, type Command, CommandStatusResponseSchema, type DialogRecord, From 264769f560300278046ab3dde4a03cac6f646e5c Mon Sep 17 00:00:00 2001 From: gcharang <21151592+gcharang@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:03:11 +0400 Subject: [PATCH 4/7] fix(protocol): type page_request bodies through named JSON interfaces Cloudflare's Durable Object RPC types expand a recursive type alias without bound, so the backend typecheck hit TS2589 once Event carried the z.json() body. Named interfaces keep the same JSON shape and leave runtime validation by z.json() unchanged. Co-Authored-By: Claude Opus 5.5 --- packages/protocol/src/index.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts index c5a72f5..8c34a7e 100644 --- a/packages/protocol/src/index.ts +++ b/packages/protocol/src/index.ts @@ -280,7 +280,16 @@ const CommandBase = { export const PageRequestWriteMethodSchema = z.enum(["POST", "PUT", "PATCH", "DELETE"]); export type PageRequestWriteMethod = z.infer; -export const PageRequestBodySchema: z.ZodType>> = z.unknown().superRefine((value, ctx) => { +// Named interfaces bound type expansion in Cloudflare RPC signatures. +type PageRequestBody = string | number | boolean | null | PageRequestBodyArray | PageRequestBodyObject; + +export interface PageRequestBodyArray extends Array {} + +export interface PageRequestBodyObject { + [key: string]: PageRequestBody; +} + +export const PageRequestBodySchema: z.ZodType = z.unknown().superRefine((value, ctx) => { const pending = [{ value, depth: 0 }]; let count = 0; while (pending.length > 0) { From ccf99a428472731e045a90f455cca588c4ef3fe0 Mon Sep 17 00:00:00 2001 From: gcharang <21151592+gcharang@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:25:28 +0400 Subject: [PATCH 5/7] fix: close the order, card-key and unknown-write gaps in U3 The driver hit-tests the click point, checks every clickable role the capture offers, matches more English and Arabic order and pay labels after normalising digits and invisible characters, refuses any key on a card field and modifier chords outside a navigation allowlist, and reports only visible challenges as security checks. A page_request write that may have reached the site ends unknown and unsafe to retry; write rules bind origin, path and query; credentialed GET needs act approval. Co-Authored-By: Claude Opus 5.5 --- apps/backend/src/session.ts | 40 +-- apps/backend/test/session.test.ts | 90 ++++++ apps/extension/scripts/e2e.mjs | 112 +++++++- apps/extension/src/core/session-manager.ts | 11 +- .../src/core/session-runtime.test.ts | 38 ++- apps/extension/src/core/session-runtime.ts | 7 +- apps/extension/src/driver/cdp.test.ts | 190 ++++++++++++- apps/extension/src/driver/cdp.ts | 264 ++++++++++++++---- apps/extension/src/driver/page-request.ts | 13 +- apps/extension/src/driver/payment-guard.ts | 220 ++++++++++----- .../src/driver/semantic/cdp-semantic.test.ts | 3 + .../src/driver/semantic/normalize.ts | 2 +- packages/connector/src/index.test.ts | 60 +++- packages/connector/src/index.ts | 38 +-- packages/protocol/src/index.test.ts | 14 +- packages/protocol/src/index.ts | 65 +++-- 16 files changed, 947 insertions(+), 220 deletions(-) diff --git a/apps/backend/src/session.ts b/apps/backend/src/session.ts index eb26361..f52e6a0 100644 --- a/apps/backend/src/session.ts +++ b/apps/backend/src/session.ts @@ -497,22 +497,29 @@ export class SessionAgent extends Agent { isCommandResultEvent(row.command_type, frame.event.type) && this.frameMatchesCurrentLease(frame) ) { - const event = - row.dry_run === 1 && row.is_write === 1 && frame.event.type === "action_result" - ? { ...frame.event, simulated: true } - : frame.event; - const recorded = event.type === "page_request_result" ? pageRequestReceipt(event) : event; - this.sql` - UPDATE command_journal - SET state = 'completed', result_json = ${JSON.stringify(recorded)}, - updated_at = ${now} - WHERE attempt_id = ${frame.attemptId} AND state = 'granted' - AND execution_deadline_at > ${now} - `; - if (event.type === "page_request_result" && event.body !== undefined) { - this.rememberPageRequestBody(row.attempt_id, event); + if ( + row.command_type === "page_request" && row.is_write === 1 && row.dry_run === 0 && + frame.event.type === "action_result" && frame.event.reason === "outcome_unknown" + ) { + this.terminalizeAttempt(row, "unknown"); + } else { + const event = + row.dry_run === 1 && row.is_write === 1 && frame.event.type === "action_result" + ? { ...frame.event, simulated: true } + : frame.event; + const recorded = event.type === "page_request_result" ? pageRequestReceipt(event) : event; + this.sql` + UPDATE command_journal + SET state = 'completed', result_json = ${JSON.stringify(recorded)}, + updated_at = ${now} + WHERE attempt_id = ${frame.attemptId} AND state = 'granted' + AND execution_deadline_at > ${now} + `; + if (event.type === "page_request_result" && event.body !== undefined) { + this.rememberPageRequestBody(row.attempt_id, event); + } + this.notifyAttempt(frame.attemptId); } - this.notifyAttempt(frame.attemptId); } else if ( row?.state === "granted" && row.execution_deadline_at !== null && @@ -696,6 +703,7 @@ export class SessionAgent extends Agent { const pageUrl = this.state.currentUrl ?? this.state.tabs[0]?.url; const origin = pageUrl === undefined ? null : URL.parse(pageUrl)?.origin; if (!origin || !lease.allowedOrigins.includes(origin) || + (isWriteCommand(command) && command.origin !== origin) || resolvePageRequestUrl(origin, command.path, command.query) === null) { return { kind: "terminal", event: { type: "action_result", @@ -852,7 +860,7 @@ export class SessionAgent extends Agent { } } - if (dryRun && isWriteCommand(command)) { + if (dryRun && (isWriteCommand(command) || command.type === "page_request")) { const ref = this.commandRef(command); if (ref === undefined) { const event = this.simulatedResult(command.commandId, { ok: true }); diff --git a/apps/backend/test/session.test.ts b/apps/backend/test/session.test.ts index b77490f..24eab7b 100644 --- a/apps/backend/test/session.test.ts +++ b/apps/backend/test/session.test.ts @@ -928,6 +928,96 @@ describe("hello resync", () => { }); describe("protocol-v3 command result correlation", () => { + it("simulates a credentialed page request GET without sending it to the browser", async () => { + // #given + const sessionId = crypto.randomUUID(); + const stub = await getSessionStub(sessionId); + await runInDurableObject(stub, async (instance: SessionAgent) => { + const lease = unattendedLease(sessionId); + const peer = fakeConnection({ authorized: true }); + await instance.initializeUnattended("tenantA", lease); + setAuthoritative(instance, peer.connection); + instance.setState({ + ...instance.state, protocolVersion: 3, capabilities: ["page-request-v1"], currentUrl: lease.allowedOrigins[0]!, + }); + Object.assign(instance, { + getConnections: () => [peer.connection], + tenantCoordinator: () => ({ + authorizeCommand: async () => ({ ok: true, idleExpiresAt: lease.idleExpiresAt }), + }), + }); + + // #when + const result = await instance.dispatchV2( + { type: "page_request", commandId: "preview", path: "/orders", method: "GET" }, + true, "actor", "https://example.test/status", + ); + + // #then + expect(result).toEqual({ kind: "terminal", event: { + type: "action_result", commandId: "preview", ok: true, simulated: true, + } }); + expect(peer.send).not.toHaveBeenCalled(); + }); + }); + + it("rejects a page request write whose approved origin differs from the current allowed origin", async () => { + // #given + const sessionId = crypto.randomUUID(); + const stub = await getSessionStub(sessionId); + await runInDurableObject(stub, async (instance: SessionAgent) => { + const lease = unattendedLease(sessionId); + const currentOrigin = lease.allowedOrigins[0]!; + const origin = "https://previous.example"; + await instance.initializeUnattended("tenantA", { + ...lease, allowedOrigins: [currentOrigin, origin], + }); + setAuthoritative(instance); + instance.setState({ + ...instance.state, protocolVersion: 3, capabilities: ["page-request-v1", "safe-write-v3"], currentUrl: currentOrigin, + }); + Object.assign(instance, { getConnections: () => [FAKE_CONNECTION] }); + + // #when + const result = await instance.dispatchV2( + { type: "page_request", commandId: "moved", path: "/orders", origin, method: "POST" }, + false, "actor", "https://example.test/status", + ); + + // #then + expect(result).toEqual({ kind: "terminal", event: { + type: "action_result", commandId: "moved", ok: false, reason: "navigation_blocked", + } }); + }); + }); + + it("terminalizes an ambiguous page request write as unsafe to retry", async () => { + // #given + const sessionId = crypto.randomUUID(); + const stub = await getSessionStub(sessionId); + await runInDurableObject(stub, async (instance: SessionAgent) => { + const lease = unattendedLease(sessionId); + const { leaseId, leaseEpoch, browserEpoch } = lease; + await instance.initializeUnattended("tenantA", lease); + setAuthoritative(instance); + const attempt = seedAttempt(instance, { state: "granted", commandType: "page_request", dryRun: false, isWrite: true }); + + // #when + await instance.onMessage(FAKE_CONNECTION, JSON.stringify({ + type: "command_result", + attemptId: attempt.attemptId, + commandId: attempt.commandId, + leaseId, leaseEpoch, browserEpoch, + event: { type: "action_result", commandId: attempt.commandId, ok: false, reason: "outcome_unknown" }, + })); + + // #then + await expect(instance.getCommandStatus(attempt.commandId)).resolves.toEqual({ + commandId: attempt.commandId, status: "unknown", safeToRetry: false, + }); + }); + }); + it("requires the page-request capability before dispatching a request", async () => { // #given const sessionId = crypto.randomUUID(); diff --git a/apps/extension/scripts/e2e.mjs b/apps/extension/scripts/e2e.mjs index c85a924..31907c6 100644 --- a/apps/extension/scripts/e2e.mjs +++ b/apps/extension/scripts/e2e.mjs @@ -215,7 +215,7 @@ async function startLocalService(directory) { "content-type": "text/html; charset=utf-8", "set-cookie": "fixture=present; Secure; HttpOnly; SameSite=Strict", }); - response.end(checkoutPage()); + response.end(checkoutPage(url.searchParams.get("challenge"))); return; } if (url.pathname === "/checkout-fixture-json") { @@ -396,12 +396,63 @@ function semanticFramePage(kind) { return ``; } -function checkoutPage() { +function checkoutPage(challenge) { + // srcdoc supplies the frame contents locally while src exposes the provider URL to the probe. + if (challenge === "split") { + return ` + + + `; + } + if (challenge === "prompt") { + return `

أدخل الرمز

`; + } + if (challenge === "digits") { + return `
Enter the 6‑digit code we sent you
`; + } + if (challenge === "frame") { + return ``; + } + if (challenge === "hcaptcha") { + return ` + + `; + } + if (challenge === "controls") return ` + + + + Product Cash on delivery available + ادفع على راحتك لمنتج اليوم + خيار ادفع الآن متاح + 0 +
+ + + Confirm & Pay + +
+
+ +
Ordinary overlay
+
+ + `; return `
+ +
+
+ +
0