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..f52e6a0 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); @@ -491,18 +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; - this.sql` - UPDATE command_journal - SET state = 'completed', result_json = ${JSON.stringify(event)}, - updated_at = ${now} - WHERE attempt_id = ${frame.attemptId} AND state = 'granted' - AND execution_deadline_at > ${now} - `; - this.notifyAttempt(frame.attemptId); + 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); + } } else if ( row?.state === "granted" && row.execution_deadline_at !== null && @@ -617,6 +634,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 +691,28 @@ 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) || + (isWriteCommand(command) && command.origin !== 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 && @@ -818,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 }); @@ -951,7 +993,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 +1337,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 +1352,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..24eab7b 100644 --- a/apps/backend/test/session.test.ts +++ b/apps/backend/test/session.test.ts @@ -928,6 +928,154 @@ 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(); + 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 2b8b7e1..bf52f04 100644 --- a/apps/extension/scripts/e2e.mjs +++ b/apps/extension/scripts/e2e.mjs @@ -127,9 +127,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); @@ -178,6 +179,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")); @@ -210,6 +212,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(url.searchParams.get("challenge"))); + 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"); }); @@ -378,6 +398,78 @@ function semanticFramePage(kind) { return ``; } +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 + + `; +} + function closureFence(frame) { return { sessionId: frame.sessionId, @@ -387,7 +479,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 = { @@ -406,6 +498,7 @@ async function provisionScenario(service, label, url) { type: "provision", ...closureFence(scenario), allowedOrigins: [service.origin], + ...(pageRequestWrites === undefined ? {} : { pageRequestWrites }), policyVersion: 1, sessionTicket: `session-ticket-${sequence}`, }); @@ -463,6 +556,108 @@ 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, current = elements) => { + const value = current.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-cvv", ref: ref("Enter security code"), 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: imageSubmit } = await writeCommand(service, scenario, { + type: "key", commandId: "checkout-image-submit", keys: "Enter", + ref: ref("Delivery instructions", await captureCheckout()), + }, service.cursor()); + assert(imageSubmit.event.reason === "payment_refused", "Enter did not refuse the image submit control"); + const { frame: tab } = await writeCommand(service, scenario, { + type: "key", commandId: "checkout-tab-to-card", keys: "Tab", ref: ref("Billing note", await captureCheckout()), + }, service.cursor()); + assert(tab.event.ok === true, "Tab from a regular input did not dispatch"); + const { frame: focusedCard } = await writeCommand(service, scenario, { + type: "key", commandId: "checkout-focused-card", keys: "Backspace", + }, service.cursor()); + assert(focusedCard.event.reason === "payment_refused", "Backspace did not refuse the focused card field"); + + 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", origin: service.origin, 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", origin: service.origin, 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"); + + const { frame: controls } = await writeCommand(service, scenario, { + type: "navigate", commandId: "checkout-controls", url: `${service.origin}/checkout-fixture?challenge=controls`, + }, service.cursor()); + assert(controls.event.ok === true, "could not open the checkout control fixture"); + for (const [label, reason] of [ + ["Covered button", "payment_refused"], + ["Obscured button", "target_changed"], + ["Product Cash on delivery available", undefined], + ["ادفع على راحتك لمنتج اليوم", undefined], + ["خيار ادفع الآن متاح", undefined], + ["Button with child content", undefined], + ]) { + const { frame } = await writeCommand(service, scenario, { + type: "click", commandId: `checkout-hit-${service.cursor()}`, ref: ref(label, await captureCheckout()), + }, service.cursor()); + assert(frame.event.ok === (reason === undefined) && frame.event.reason === reason, + `unexpected click result for ${label}: ${JSON.stringify(frame.event)}`); + } + assert((await captureCheckout()).some((element) => element.name === "Order presses: 0"), + "click dispatch pressed the order overlay"); + + for (const challenge of ["split", "prompt", "digits", "frame", "hcaptcha"]) { + const { frame: navigation } = await writeCommand(service, scenario, { + type: "navigate", commandId: `challenge-${challenge}`, + url: `${service.origin}/checkout-fixture?challenge=${challenge}`, + }, service.cursor()); + assert(navigation.event.ok === true, `could not open the ${challenge} fixture`); + const { frame } = await readCommand(service, scenario, { + type: "capture_elements", commandId: `capture-${challenge}`, scope: "document", view: "all", limit: 10, changesOnly: false, + }); + assert(frame.event.status === "error" && frame.event.reason === "security_check", + `did not stop for the ${challenge} verification prompt`); + } + 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, @@ -748,6 +943,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..ba8fa78 100644 --- a/apps/extension/src/core/session-manager.ts +++ b/apps/extension/src/core/session-manager.ts @@ -1,4 +1,11 @@ -import type { AssignmentInventory, OwnedWindow, TabInfo } from "@understudy/protocol"; +import { + PageRequestWritePolicySchema, + resolvePageRequestUrl, + type AssignmentInventory, + type OwnedWindow, + type PageRequestWritePolicy, + type TabInfo, +} from "@understudy/protocol"; import type { Browser } from "wxt/browser"; import { controlledTabInfo } from "../tabs"; import { @@ -25,6 +32,7 @@ export interface ProvisionInput { leaseEpoch: number; browserEpoch: string; allowedOrigins: string[]; + pageRequestWrites?: PageRequestWritePolicy; policyVersion: number; sessionTicket: string; } @@ -155,6 +163,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 +407,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 +560,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 +934,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 +1050,26 @@ 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]; + const options = { canonicalQuery: true }; + const url = resolvePageRequestUrl(rule.origin, rule.path, rule.query, options); + return other !== undefined && rule.method === other.method && + url !== null && url.href === resolvePageRequestUrl(other.origin, other.path, other.query, options)?.href; + }); +} + function cloneAssignment(assignment: ManagedAssignment): ManagedAssignment { return { ...assignment, allowedOrigins: [...assignment.allowedOrigins], + ...(assignment.pageRequestWrites === undefined ? {} : { + pageRequestWrites: assignment.pageRequestWrites.map((rule) => ({ + ...rule, + ...(rule.query === undefined ? {} : { query: { ...rule.query } }), + })), + }), }; } diff --git a/apps/extension/src/core/session-runtime.test.ts b/apps/extension/src/core/session-runtime.test.ts index 3d8f1a0..63bf4fe 100644 --- a/apps/extension/src/core/session-runtime.test.ts +++ b/apps/extension/src/core/session-runtime.test.ts @@ -278,6 +278,71 @@ 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", origin: "https://shop.example", + } 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("journals an ambiguous page request write as unknown and blocks another grant", async () => { + // #given + const { values } = stubWriteStorage(); + const runtime = new SessionRuntime(ASSIGNMENT, host()); + const prepared = { ...attempt, commandType: "page_request" } as const; + const command = { + type: "page_request", commandId: attempt.commandId, path: "/orders", method: "POST", origin: "https://shop.example", + } as const; + const response = { + type: "action_result", commandId: command.commandId, ok: false, reason: "outcome_unknown", + } 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 }; + await runtime.journal.prepare(prepared); + + // #when + await runtime["onServerFrame"](grant); + const next = { ...prepared, attemptId: "attempt-2", commandId: "command-2" }; + await runtime.journal.prepare(next); + await runtime["onServerFrame"]({ + ...grant, attemptId: next.attemptId, command: { ...command, commandId: next.commandId }, + }); + + // #then + expect(values[journalKey]).toMatchObject([ + { ...prepared, state: "unknown" }, + { ...next, state: "prepared" }, + ]); + expect(peerSend.mock.calls).toEqual([[{ ...result, event: response }]]); + expect(pageRequest).toHaveBeenCalledOnce(); + }); + 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..7363111 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,51 @@ 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; + } + if (event.type === "action_result" && event.reason === "outcome_unknown") { + await this.journal.markUnknown(frame.attemptId); + this.writesBlocked = true; + } else { + 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 +471,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..6f21dc7 100644 --- a/apps/extension/src/driver/cdp.test.ts +++ b/apps/extension/src/driver/cdp.test.ts @@ -1,6 +1,8 @@ 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 { normalizePageString } from "./semantic/normalize"; import type { RefRecord } from "./semantic/types"; const TEST_SCOPE = "test"; @@ -80,6 +82,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 +292,208 @@ describe("CdpSession.resolveRefCheck", () => { }); describe("CdpSession keyboard dispatch", () => { + it.each([ + "Pay now", "Confirm order", "تأكيد الطلب", "الدفع عند الاستلام", + "Pay AED 250", "Pay USD 20", "Pay ١٠٠", "Pay ۱۰۰", "Confirm & Pay", "Order now", + "Confirm purchase", "Complete payment", "Submit payment", "Make payment", "الدفع عند التوصيل", + "تاكيد الطلب", "اطلب الآن", "إرسال الطلب", "تأكيد الدفع", "Pla\u200bce \u202eorder\u202c", + ])( + "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: normalizePageString(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(["generic", "checkbox"])("refuses a captured %s click action labelled Place order", async (role) => { + // #given + const sendCommand = stubActionBrowser(); + sendCommand.mockImplementation((_target, method: string, params) => { + const response = liveRefResponse(method, params); + if (method === "Accessibility.getPartialAXTree") { + const { nodes } = response as Protocol.Accessibility.GetPartialAXTreeResponse; + nodes[0]!.role = { type: "role", value: role }; + nodes[0]!.name = { type: "computedString", value: "Place order" }; + } + return Promise.resolve(response); + }); + const session = await CdpSession.create(7, TEST_SCOPE); + seedTestRefs(session, [[testRef(0, 1), 42]], { role, name: "Place order" }); + + // #when + const result = await session.click("custom-order", testRef(0, 1)); + + // #then + expect(result).toMatchObject({ ok: false, reason: "payment_refused" }); + expect(sendCommand.mock.calls.some((call) => call[1] === "Input.dispatchMouseEvent")).toBe(false); + }); + + it.each(["4", "Tab", "Backspace", "ArrowLeft"])("refuses %s on a card field before focus", async (keys) => { + // #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", "cc-exp"]; + } + return Promise.resolve(response); + }); + const session = await CdpSession.create(7, TEST_SCOPE); + seedTestRefs(session, [[testRef(0, 1), 42]]); + + // #when + const result = await session.key("card-key", keys, testRef(0, 1)); + + // #then + expect(result).toMatchObject({ ok: false, reason: "payment_refused" }); + expect(sendCommand.mock.calls.some((call) => call[1] === "DOM.focus" || call[1] === "Input.dispatchKeyEvent")).toBe(false); + }); + + it.each(["Alt+p", "Ctrl+Enter", "Meta+a", "Shift+Space"])("refuses the %s chord before dispatch", async (keys) => { + // #given + const sendCommand = stubActionBrowser(); + const session = await CdpSession.create(7, TEST_SCOPE); + session.mainFrameId = "frame-1"; + + // #when + const result = await session.key("chord", keys); + + // #then + expect(result).toMatchObject({ ok: false, reason: "unsupported" }); + expect(sendCommand.mock.calls.some((call) => call[1] === "Input.dispatchKeyEvent")).toBe(false); + }); + + it("dispatches Shift+Tab on a non-payment target", async () => { + // #given + const sendCommand = stubActionBrowser(); + const session = await CdpSession.create(7, TEST_SCOPE); + session.mainFrameId = "frame-1"; + + // #when + const result = await session.key("reverse-focus", "Shift+Tab"); + + // #then + expect(result).toMatchObject({ ok: true }); + expect(sendCommand.mock.calls).toContainEqual([ + { tabId: 7 }, "Input.dispatchKeyEvent", expect.objectContaining({ type: "rawKeyDown", key: "Tab", modifiers: 8 }), + ]); + }); + + it.each(["Enter", "Space"])("reports a missing focused target for %s", async (keys) => { + // #given + const sendCommand = stubActionBrowser(); + sendCommand.mockImplementation(async (_target, method: string) => + method === "Runtime.evaluate" ? { result: { value: null } } : liveRefResponse(method)); + const session = await CdpSession.create(7, TEST_SCOPE); + session.mainFrameId = "frame-1"; + + // #when + const result = await session.key("no-focus", keys); + + // #then + expect(result).toMatchObject({ ok: false, reason: "target_changed" }); + expect(sendCommand.mock.calls.some((call) => call[1] === "Input.dispatchKeyEvent")).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.each(["type", "key"] as const)("refuses %s in a payment-provider iframe before focus", async (action) => { + // #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 = action === "type" + ? await session.type("provider", testRef(0, 1), "synthetic input") + : await session.key("provider", "Tab", testRef(0, 1)); + + // #then + expect(result).toMatchObject({ ok: false, reason: "payment_refused" }); + expect(sendCommand.mock.calls.some((call) => call[1] === "DOM.focus" || String(call[1]).startsWith("Input."))) + .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); @@ -720,6 +930,8 @@ describe("CdpSession snapshot target identity", () => { }); } if (method === "Accessibility.getFullAXTree") return Promise.resolve({ nodes: [] }); + if (method === "Page.createIsolatedWorld") return Promise.resolve({ executionContextId: 1 }); + if (method === "Runtime.evaluate") return Promise.resolve({ result: { value: "clear" } }); return Promise.resolve({}); }); stubSnapshotBrowser(sendCommand); @@ -738,6 +950,8 @@ describe("CdpSession snapshot target identity", () => { "Page.getFrameTree", "Accessibility.getFullAXTree", "Page.getFrameTree", + "Page.createIsolatedWorld", + "Runtime.evaluate", ]); }); @@ -1242,6 +1456,209 @@ describe("CdpSession unattended containment", () => { }); }); +describe("CdpSession page_request", () => { + const origin = "https://shop.example"; + const request = { type: "page_request", commandId: "request", path: "/orders" } as const; + const write = { ...request, origin, method: "POST" } 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"', page: "2" } }); + + // #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&page=2`, + 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({ ...write, method: "DELETE" }); + const deniedPath = await session.pageRequest({ ...write, path: "/orders/other" }); + const deniedQuery = await session.pageRequest({ ...write, query: { action: "submit" } }); + const permitted = await session.pageRequest({ ...write, body: { operation: "example" } }); + + // #then + expect(deniedMethod).toMatchObject({ ok: false, reason: "navigation_blocked" }); + expect(deniedPath).toMatchObject({ ok: false, reason: "navigation_blocked" }); + expect(deniedQuery).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("requires the write rule's exact query and the granted origin", async () => { + // #given + const otherOrigin = "https://other.example"; + const { session, fetchPage } = await requestSession({ + allowedOrigins: [origin, otherOrigin], + writes: [{ origin, path: "/orders", method: "POST", query: { shop: "1", view: "full" } }], + }); + + // #when + const noQuery = await session.pageRequest(write); + const extraQuery = await session.pageRequest({ ...write, query: { shop: "1", view: "full", next: "yes" } }); + const moved = await session.pageRequest({ ...write, origin: otherOrigin, query: { shop: "1", view: "full" } }); + const allowed = await session.pageRequest({ ...write, query: { view: "full", shop: "1" } }); + + // #then + expect([noQuery, extraQuery, moved]).toEqual(Array(3).fill( + expect.objectContaining({ ok: false, reason: "navigation_blocked" }), + )); + expect(allowed).toMatchObject({ type: "page_request_result", status: 200 }); + expect(fetchPage.mock.calls).toEqual([[ + `${origin}/orders?shop=1&view=full`, expect.objectContaining({ method: "POST" }), + ]]); + }); + + it.each([ + ["a redirect", () => Response.redirect("https://other.example/orders")], + ["an empty 201", () => new Response(null, { status: 201, headers: { "content-type": "application/json" } })], + ["an empty 204", () => new Response(null, { status: 204 })], + ["non-JSON", () => new Response("ok")], + ["invalid JSON", () => new Response("{", { headers: { "content-type": "application/json" } })], + ["an oversized response", () => Response.json({ orders: "é".repeat(PAGE_REQUEST_BODY_MAX_BYTES / 2) })], + ["a network failure", () => { throw new TypeError("network error"); }], + ["an abort", () => { throw new DOMException("aborted", "AbortError"); }], + ] as const)("reports an unknown write outcome after %s", async (_description, reply) => { + // #given + const fetchPage = vi.fn(async (_url: string, _init: RequestInit) => reply()); + const { session } = await requestSession({ fetchPage, writes: [{ origin, path: "/orders", method: "POST" }] }); + + // #when + const result = await session.pageRequest(write); + + // #then + expect(result).toMatchObject({ ok: false, reason: "outcome_unknown" }); + expect(fetchPage).toHaveBeenCalledOnce(); + }); + + it("reports an unknown write outcome when the deadline elapses after fetch starts", async () => { + // #given + vi.useFakeTimers(); + const fetchPage = vi.fn((_url: string, init: RequestInit) => new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), { once: true }); + })); + const { session } = await requestSession({ fetchPage, writes: [{ origin, path: "/orders", method: "POST" }] }); + + // #when + const result = session.pageRequest(write, Date.now() + 50); + await vi.advanceTimersByTimeAsync(50); + + // #then + await expect(result).resolves.toMatchObject({ ok: false, reason: "outcome_unknown" }); + expect(fetchPage).toHaveBeenCalledOnce(); + }); + + 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 +1685,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 +1714,10 @@ describe("CdpSession OOPIF routing", () => { if (method === "DOM.getBoxModel") { return { model: { content: [0, 0, 10, 0, 10, 10, 0, 10] } }; } - return {}; + if (method === "DOM.getNodeForLocation") { + return { frameId: "child-frame", backendNodeId: 42 }; + } + return liveRefResponse(method, params); }, ); vi.stubGlobal("browser", { @@ -1331,7 +1751,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,7 +1776,11 @@ describe("CdpSession OOPIF routing", () => { [ "Accessibility.getPartialAXTree", "DOM.describeNode", + "Page.createIsolatedWorld", + "DOM.resolveNode", + "Runtime.callFunctionOn", "DOM.getBoxModel", + "DOM.getNodeForLocation", "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..4d74fc9 100644 --- a/apps/extension/src/driver/cdp.ts +++ b/apps/extension/src/driver/cdp.ts @@ -2,6 +2,11 @@ import { ELEMENTS_RESULT_MAX_BYTES, MAX_ELEMENT_DESCRIPTORS, MAX_SEMANTIC_NODES, + PAGE_REQUEST_BODY_MAX_BYTES, + PageRequestBodySchema, + hasPageRequestMethodOverride, + isWriteCommand, + resolvePageRequestUrl, utf8ByteLength, type ActionFailureReason, type ElementAction, @@ -9,11 +14,27 @@ 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, + ONSCREEN_ELEMENT_PROBE, + PAGE_SECURITY_EXPRESSION, + PAYMENT_PROBE_RULES, + PAYMENT_TARGET_PROBE, + isCardField, + isOrderPlacementControl, + isPaymentProviderFrame, + isSecurityCheck, + type PaymentProbeMode, + type PaymentProbeResult, +} from "./payment-guard"; import { buildSemanticCache, deltaDescriptors, @@ -54,6 +75,9 @@ 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"; +const NAVIGATION_KEYS = new Set(["Tab", "Escape", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Home", "End"]); interface ElementCursor { token: string; @@ -214,6 +238,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 +333,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 +358,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 +450,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 +825,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({ @@ -913,7 +946,9 @@ export class CdpSession { { backendNodeId }, debuggerSessionId, ); - const { x, y } = quadCenter(model.content); + const center = quadCenter(model.content); + const x = Math.round(center.x); + const y = Math.round(center.y); await this.sendInSession( "Input.dispatchMouseEvent", { type: "mouseMoved", x, y }, @@ -986,6 +1021,201 @@ 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, + expectedObjectId?: string, + ): Promise { + const response = await this.sendInSession( + "Runtime.callFunctionOn", + { + objectId, + functionDeclaration: PAYMENT_TARGET_PROBE, + arguments: [ + { value: PAYMENT_PROBE_RULES }, { value: mode }, { value: requireFocused }, + ...(expectedObjectId === undefined ? [] : [{ objectId: expectedObjectId }]), + ], + 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 resolveAutomationNode( + backendNodeId: number, + contextId: number, + debuggerSessionId?: string, + ): Promise { + const { object } = await this.sendInSession( + "DOM.resolveNode", + { backendNodeId, executionContextId: contextId }, + debuggerSessionId, + ); + return object?.objectId; + } + + private async clickPointFailure( + record: RefRecord, + point: { x: number; y: number }, + ): Promise { + try { + const hit = await this.sendInSession( + "DOM.getNodeForLocation", + point, + record.debuggerSessionId, + ); + if (!hit.frameId || !hit.backendNodeId) return "target_changed"; + const sameFrame = hit.frameId === record.frameId; + const sessionId = sameFrame ? record.debuggerSessionId : this.frameSessions.get(hit.frameId)?.sessionId; + const contextId = await this.automationWorld(hit.frameId, sessionId); + const objectId = await this.resolveAutomationNode(hit.backendNodeId, contextId, sessionId); + if (objectId === undefined) return "target_changed"; + let expectedObjectId: string | undefined; + try { + if (sameFrame && hit.backendNodeId !== record.backendNodeId) { + expectedObjectId = await this.resolveAutomationNode(record.backendNodeId, contextId, sessionId); + if (expectedObjectId === undefined) return "target_changed"; + } + const failure = await this.probeInputTarget(objectId, "activate", sessionId, false, expectedObjectId); + if (failure === "payment_refused") return failure; + if (!sameFrame || record.generation !== this.generation) return "target_changed"; + return failure; + } finally { + this.releaseObject(objectId, sessionId); + if (expectedObjectId !== undefined) this.releaseObject(expectedObjectId, sessionId); + } + } catch { + return "target_changed"; + } + } + + private async inputRefFailure( + record: RefRecord, + action: "click" | "key" | "type", + mode: PaymentProbeMode, + 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 (isCardField(element) || + (mode !== "type" && isOrderPlacementControl(element, record.actions.has("click"))) || + (frame?.targetType === "iframe" && frame.url !== undefined && isPaymentProviderFrame(frame.url))) { + return "payment_refused"; + } + const contextId = await this.automationWorld(record.frameId, record.debuggerSessionId); + const objectId = await this.resolveAutomationNode(record.backendNodeId, contextId, record.debuggerSessionId); + if (objectId === undefined) return "target_changed"; + try { + const failure = await this.probeInputTarget( + objectId, + mode, + record.debuggerSessionId, + requireFocused, + ); + if (record.generation !== this.generation) return "target_changed"; + return failure; + } finally { + this.releaseObject(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(); + if (frameId === "" && mode === "type") return {}; + 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, + ); + if (result.exceptionDetails !== undefined || result.result === undefined) { + return { failure: "target_changed" }; + } + const objectId = result.result?.objectId; + if (objectId === undefined) { + if (generation === this.generation && frameId === this.mainFrameId) { + if (await this.documentSecurityState(contextId) === "security") return { failure: "security_check" }; + if (generation === this.generation && mode === "type") return {}; + } + 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 (isCardField(decoded) || (mode !== "type" && isOrderPlacementControl(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?.url !== undefined && isPaymentProviderFrame(frame.url)) { + return { failure: "payment_refused" }; + } + if (frame?.ready !== true) break; + frameId = frameOwner; + sessionId = frame.sessionId; + } + return { failure: "target_changed" }; + } + snapshotA11y(commandId: string): Promise { const deadlineAt = Date.now() + SNAPSHOT_DEADLINE_MS; return this.run( @@ -999,6 +1229,13 @@ export class CdpSession { ), true, ); + const securityCheck = await this.hasSecurityCheck(deadlineAt); + if (this.generation !== generation) { + return this.actionFailure(commandId, "page_changed", true, true); + } + if (securityCheck) { + return this.actionFailure(commandId, "security_check", true, false); + } const { tree, refMap } = buildA11ySnapshot(captured.nodes, { scopeId: this.refScopeId, generation, @@ -1090,6 +1327,89 @@ export class CdpSession { }; } + private async documentSecurityState( + contextId: number, + sessionId?: string, + ): Promise<"security" | "passive" | "clear"> { + const result = await this.sendInSession( + "Runtime.evaluate", + { contextId, expression: PAGE_SECURITY_EXPRESSION, returnByValue: true }, + sessionId, + ); + const value = result.result?.value; + return value === "security" || value === "passive" ? value : "clear"; + } + + private async elementIsOnscreen( + backendNodeId: number, + contextId: number, + sessionId?: string, + ): Promise { + const objectId = await this.resolveAutomationNode(backendNodeId, contextId, sessionId); + if (objectId === undefined) return false; + try { + const result = await this.sendInSession( + "Runtime.callFunctionOn", + { objectId, functionDeclaration: ONSCREEN_ELEMENT_PROBE, returnByValue: true }, + sessionId, + ); + return result.result?.value === true; + } finally { + this.releaseObject(objectId, sessionId); + } + } + + private async frameIsOnscreen(frameId: string): Promise { + const visited = new Set(); + while (frameId !== this.mainFrameId && !visited.has(frameId)) { + visited.add(frameId); + const parentSessionId = this.frameSessions.get(frameId)?.parentSessionId; + const parentId = this.frameParents.get(frameId) ?? + (parentSessionId === undefined ? this.mainFrameId : + [...this.frameSessions.values()].find((entry) => entry.sessionId === parentSessionId)?.frameId); + if (!parentId) return false; + const sessionId = this.frameSessions.get(parentId)?.sessionId; + const [owner, contextId] = await Promise.all([ + this.sendInSession("DOM.getFrameOwner", { frameId }, sessionId), + this.automationWorld(parentId, sessionId), + ]); + if (!await this.elementIsOnscreen(owner.backendNodeId, contextId, sessionId)) return false; + frameId = parentId; + } + return frameId === this.mainFrameId; + } + + private hasSecurityCheck(deadlineAt: number, cache?: SemanticCache): Promise { + return this.withSnapshotDeadline(deadlineAt, async () => { + const nodes = cache?.nodes ?? []; + const cardContext = nodes.some(({ descriptor }) => isCardField(descriptor)); + const candidates = nodes.filter(({ descriptor, backendNodeId }) => + backendNodeId !== undefined && descriptor.visibility !== "hidden" && + descriptor.visibility !== "offscreen" && isSecurityCheck(descriptor, cardContext), + ); + const check = (frameId: string, sessionId?: string): Promise => + this.optional((async () => { + const contextId = await this.automationWorld(frameId, sessionId); + const signal = await this.documentSecurityState(contextId, sessionId); + if (signal === "passive") return false; + if (signal === "security") return this.frameIsOnscreen(frameId); + for (const node of candidates) { + if (node.frameId === frameId && node.backendNodeId !== undefined && + await this.elementIsOnscreen(node.backendNodeId, contextId, sessionId)) { + return this.frameIsOnscreen(frameId); + } + } + return false; + })()); + if (await check(this.mainFrameId)) return true; + const frames = [...this.frameSessions.values()].filter((frame) => + frame.frameId !== this.mainFrameId && frame.ready, + ); + const nestedChecks = await Promise.all(frames.map((frame) => check(frame.frameId, frame.sessionId))); + return nestedChecks.some((signal) => signal === true); + }); + } + private topologyKey(frames: readonly FrameTopologyEntry[]): string { return frames .map( @@ -1249,6 +1569,11 @@ export class CdpSession { view, deadlineAt, ); + const securityCheck = await this.hasSecurityCheck(deadlineAt, cache); + if (cache.snapshot.generation !== this.generation) throw new SemanticCaptureError("page_changed"); + if (securityCheck) { + return this.semanticFailure(commandId, "snapshot", "security_check"); + } if ( changesOnly && previous !== null && @@ -1320,9 +1645,15 @@ export class CdpSession { commandId, async () => { try { + const existing = this.semanticCache; const cache = - this.semanticCache ?? + existing ?? (await this.captureFreshSemantic("document", "all", deadlineAt)).cache; + const securityCheck = await this.hasSecurityCheck(deadlineAt, existing === null ? cache : undefined); + if (cache.snapshot.generation !== this.generation) throw new SemanticCaptureError("page_changed"); + if (securityCheck) { + return this.semanticFailure(commandId, "find", "security_check"); + } return this.elementsPage( commandId, "find", @@ -1639,22 +1970,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"); + const failureBeforePress = (await this.clickPointFailure(record, point)) ?? afterPointerMove; + if (failureBeforePress !== undefined) { + return this.actionFailure(commandId, failureBeforePress, true, true); } await this.dispatchPreparedClick(point, record.debuggerSessionId); return this.actionSuccess(commandId, false, true); @@ -1667,14 +1994,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 +2010,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 +2024,19 @@ export class CdpSession { key(commandId: string, keys: string, ref?: string): Promise { return this.run(commandId, async () => { const parsed = parseKeys(keys); + if (parsed.modifiers !== 0 && !NAVIGATION_KEYS.has(parsed.key)) { + return this.actionFailure(commandId, "unsupported", false, false); + } + const mode = parsed.key === "Enter" ? "submit" : parsed.key === " " ? "activate" : "type"; 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 +2044,88 @@ 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 { + 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, method = "GET" } = command; + const write = isWriteCommand(command) ? command : undefined; + 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 postSendFailure = (reason: ActionFailureReason): Event => + failure(write === undefined ? reason : "outcome_unknown"); + const allowedOrigins = this.allowedOrigins; + if (allowedOrigins === null) return failure("navigation_blocked"); + let dispatched = false; + try { + const page = await this.mainFrameIdentity(deadlineAt); + const origin = new URL(page.url).origin; + const options = { canonicalQuery: write !== undefined }; + const url = resolvePageRequestUrl(origin, path, query, options); + if (url === null || !allowedOrigins.has(origin)) return failure("navigation_blocked"); + if (write !== undefined && ( + write.origin !== origin || hasPageRequestMethodOverride(write.body) || + !this.pageRequestWrites.some((rule) => + rule.origin === origin && rule.method === method && rule.path === url.pathname && + resolvePageRequestUrl(rule.origin, rule.path, rule.query, options)?.href === url.href, + ) + )) { + return failure("navigation_blocked"); + } + const executionContextId = await this.withSnapshotDeadline(deadlineAt, () => + this.automationWorld(page.frameId), + ); + if (this.allowedOrigins !== allowedOrigins) return failure("navigation_blocked"); + const body = write?.body === undefined ? undefined : JSON.stringify(write.body); + const response = await this.withSnapshotDeadline(deadlineAt, () => { + dispatched = true; + return this.send("Runtime.callFunctionOn", { + executionContextId, + functionDeclaration: PAGE_REQUEST_FUNCTION, + arguments: [{ value: { + origin, + url: url.href, + method, + ...(body === undefined ? {} : { 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" | "outcome_unknown"; + status?: number; + json?: string; + } | undefined; + if (result?.reason !== undefined) return failure(result.reason); + if (result?.status === undefined || typeof result.json !== "string") return postSendFailure("action_failed"); + const parsed = PageRequestBodySchema.safeParse(JSON.parse(result.json)); + if (!parsed.success) return postSendFailure("action_failed"); + return { type: "page_request_result", commandId, status: result.status, body: parsed.data }; + } catch { + const reason = Date.now() >= deadlineAt ? "timeout" : "action_failed"; + return dispatched ? postSendFailure(reason) : failure(reason); + } + }, 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..180300e --- /dev/null +++ b/apps/extension/src/driver/page-request.ts @@ -0,0 +1,55 @@ +// 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 failure = (reason) => ({ reason: request.method === "GET" ? reason : "outcome_unknown" }); + 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 failure("navigation_blocked"); + } + if (response.url && new URL(response.url).origin !== request.origin) { + return failure("navigation_blocked"); + } + if (response.status === 204 || response.status === 205) { + return request.method === "GET" ? { status: response.status, json: "null" } : failure("action_failed"); + } + const contentType = response.headers.get("content-type") ?? ""; + if (!/^\s*application\/(?:json|[\w.+-]+\+json)(?:\s*;|\s*$)/i.test(contentType) || response.body === null) { + return failure("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 failure("result_too_large"); + json += decoder.decode(chunk.value, { stream: true }); + } + return { status: response.status, json: json + decoder.decode() }; + } catch { + return failure(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..3f44384 --- /dev/null +++ b/apps/extension/src/driver/payment-guard.ts @@ -0,0 +1,276 @@ +import type { ElementDescriptor } from "@understudy/protocol"; +import { CLICK_ROLES } from "./semantic/normalize"; + +// 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|(?:[a-z]{3}\s*)?(?:\p{Sc}|\+?[.,٫]?\d)))|\b(?:(?:place|confirm|submit|complete|finalize)\s+(?:(?:your|my|the)\s+)?order|order now|confirm\s*(?:and|&)\s*pay|(?:confirm|complete)\s+(?:your\s+)?purchase|(?:complete|submit|make|confirm)\s+(?:your\s+)?payment)\b|^(?:cash on delivery|الدفع عند (?:الاستلام|التوصيل)|(?:الدفع|دفع) الان)\p{P}*$|^ادفع(?:\p{P}*$|\s+(?:الان|نقدا|عند (?:الاستلام|التوصيل)|بالبطاقه)(?:\p{P}*$|\s+\d)|\s+(?:(?:[a-z]{3}|درهم)\s+)?(?:\p{Sc}|\d))|(?:اطلب الان|(?:تاكيد|اتمام|اكمال|تقديم|ارسال) (?:الطلب|طلبك|الشراء|الدفع))/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|confirmation|authenticator|2fa)\s+(?:passcode|password|code)|otp|(?:enter|type)\s+(?:(?:the|your|a)\s+)?(?:\d+\s+digits?\s+)?(?:(?:sms|email|login|sign in)\s+)?(?:passcode|code))\b|(?:رمز التحقق|رمز المصادقه|(?:رمز|كلمه المرور) لمره واحده|(?:ادخل|ادخلي|اكتب|يرجي ادخال) (?:الرمز|رمز))/iu; +const SECURITY_PROMPT_NAME = /^(?:captcha|recaptcha|hcaptcha)$|\b(?:security check|two (?:step|factor) verification|verify (?:that )?you(?:['’]re| are) (?:a )?human|human verification)\b|(?:تحقق امني|التحقق الامني|تحقق من انك انسان)/iu; +const AMBIGUOUS_SECURITY_CODE = /\bsecurity code\b|رمز الامان/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}\p{Cf}\u0640]/gu, "") + .replace(/[أإآٱ]/gu, "ا").replace(/ى/gu, "ي").replace(/ة/gu, "ه") + .replace(/[٠-٩۰-۹]/gu, (digit) => String(digit.charCodeAt(0) & 0xf)) + .replace(/[\s_\p{Dash}]+/gu, " ").trim(); +} + +export function isOrderPlacementControl(element: ElementFacts, clickable = false): boolean { + return (clickable || CLICK_ROLES.has(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 (isCardField(element)) return false; + const code = labels.some((label) => SECURITY_CODE_NAME.test(label) || + (!cardContext && AMBIGUOUS_SECURITY_CODE.test(label))); + if (["textbox", "searchbox", "spinbutton"].some((role) => role === element.role)) { + return code; + } + if (["heading", "dialog", "alert", "alertdialog", "StaticText"].some((role) => role === element.role)) { + return code || labels.some((label) => SECURITY_PROMPT_NAME.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, + ambiguousCode: AMBIGUOUS_SECURITY_CODE.source, + clickRoles: [...CLICK_ROLES], + 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 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 ONSCREEN_ELEMENT_PROBE = String.raw`function () { + const element = this instanceof Text ? this.parentElement : this; + if (!(element instanceof Element) || !element.isConnected || + !element.checkVisibility({ opacityProperty: true, visibilityProperty: true, contentVisibilityAuto: true })) { + return false; + } + const { left, top, right, bottom, width, height } = element.getBoundingClientRect(); + const viewport = window.visualViewport; + const x = viewport?.offsetLeft ?? 0; + const y = viewport?.offsetTop ?? 0; + return width > 0 && height > 0 && right > x && bottom > y && + left < x + (viewport?.width ?? window.innerWidth) && top < y + (viewport?.height ?? window.innerHeight); +}`; + +const PAYMENT_PROBE_HELPERS = String.raw` + const label = (value) => (value ?? "").normalize("NFKC") + .replace(/[\p{Mark}\p{Cf}\u0640]/gu, "") + .replace(/[أإآٱ]/gu, "ا").replace(/ى/gu, "ي").replace(/ة/gu, "ه") + .replace(/[٠-٩۰-۹]/gu, (digit) => String(digit.charCodeAt(0) & 0xf)) + .replace(/[\s_\p{Dash}]+/gu, " ").trim(); + const card = new RegExp(rules.card, "iu"); + const code = new RegExp(rules.code, "iu"); + const challenge = new RegExp(rules.challenge, "iu"); + const ambiguousCode = new RegExp(rules.ambiguousCode, "iu"); + const visible = (element) => (${ONSCREEN_ELEMENT_PROBE}).call(element); + const hostMatches = (host, domain) => host === domain || host.endsWith("." + domain); + const captchaFrameKind = (value) => { + if (!value) return undefined; + try { + const url = new URL(value, location.href); + const host = url.hostname.replace(/\.$/u, ""); + if (hostMatches(host, "google.com") || hostMatches(host, "recaptcha.net")) { + if (/\/recaptcha\/(?:api2|enterprise)\/bframe$/.test(url.pathname)) return "challenge"; + if (/\/recaptcha\/(?:api2|enterprise)\/anchor$/.test(url.pathname)) { + return url.searchParams.get("size")?.toLowerCase() === "invisible" ? "passive" : "challenge"; + } + } + if (hostMatches(host, "hcaptcha.com")) { + const frame = new URLSearchParams(url.hash.slice(1)).get("frame"); + if (frame === "challenge") return "challenge"; + if (frame === "checkbox") return "passive"; + } + if (host === "challenges.cloudflare.com") return "challenge"; + } catch { + return undefined; + } + }; + 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"), attr(element, "alt"), + ...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 isCodeLabel = (value, cardContext) => { + const name = label(value); + return code.test(name) || (!cardContext && ambiguousCode.test(name)); + }; + const isDigitField = (element) => element?.matches('input[maxlength="1"]:not([type="hidden" i])') && + visible(element); + const isSplitCode = (first) => { + if (!isDigitField(first) || isDigitField(first.previousElementSibling)) return false; + let count = 1; + for (let field = first.nextElementSibling; count <= 8 && isDigitField(field); field = field.nextElementSibling) { + count++; + } + return count >= 4 && count <= 8; + }; + const pageHasSecurityCheck = (root) => { + const pending = [root]; + while (pending.length > 0) { + const scope = pending.pop(); + const fields = [...scope.querySelectorAll(inputSelector)]; + const cardContext = fields.some(isCardField); + if (fields.some((field) => visible(field) && ( + autocomplete(field).includes("one-time-code") || + isSplitCode(field) || + !isCardField(field) && [...labels(field), attr(field, "placeholder")] + .some((value) => isCodeLabel(value, cardContext)) + ))) return true; + const prompts = 'h1, h2, h3, h4, h5, h6, p, label, legend, div, span, [role="heading"], dialog, [role="dialog"], [role="alert"], [role="alertdialog"]'; + if (Array.from(scope.querySelectorAll(prompts)).some((element) => { + const text = element.textContent; + if (!text || text.length > 256 || !(challenge.test(label(text)) || isCodeLabel(text, cardContext))) return false; + if (!visible(element)) return false; + const rendered = element.innerText ?? text; + return challenge.test(label(rendered)) || isCodeLabel(rendered, cardContext); + })) return true; + if (Array.from(scope.querySelectorAll("iframe, frame")).some((frame) => + captchaFrameKind(frame.src) === "challenge" && visible(frame) + )) return true; + for (const element of scope.querySelectorAll("*")) { + if (element.shadowRoot) pending.push(element.shadowRoot); + } + } + return false; + }; +`; + +export const PAGE_SECURITY_EXPRESSION = String.raw`(() => { + const rules = ${JSON.stringify(PAYMENT_PROBE_RULES)}; + ${PAYMENT_PROBE_HELPERS} + const frame = window === window.top ? undefined : captchaFrameKind(location.href); + if (frame === "passive") return "passive"; + return frame === "challenge" || pageHasSecurityCheck(document) ? "security" : "clear"; +})()`; + +export const PAYMENT_TARGET_PROBE = String.raw`function (rules, mode, requireFocused, expected) { + ${PAYMENT_PROBE_HELPERS} + const order = new RegExp(rules.order, "iu"); + const isPaymentUrl = (value) => { + try { + const hostname = new URL(value).hostname.replace(/\.$/u, ""); + return rules.paymentHosts.some((host) => hostMatches(hostname, host)); + } catch { + return false; + } + }; + const isOrderControl = (element, isTarget = false) => { + if (element.matches("html, body, form")) return false; + const affordance = isTarget || + element.matches('button, a, input[type="submit" i], input[type="button" i], input[type="image" i], [onclick], [tabindex]') || + typeof element.onclick === "function" || rules.clickRoles.includes(attr(element, "role")) || + getComputedStyle(element).cursor === "pointer"; + const text = element.textContent; + if (!affordance) { + // A listener registered through addEventListener need not expose a DOM affordance. + const name = text.length <= 128 ? label(text) : ""; + return name !== "" && name.match(order)?.[0] === name; + } + return [...labels(element), text.length <= 512 ? text : "", + element instanceof HTMLInputElement ? attr(element, "value") : ""] + .some((value) => order.test(label(value))); + }; + const formElements = (form) => + Array.from(Object.getOwnPropertyDescriptor(HTMLFormElement.prototype, "elements").get.call(form)); + const isCardTarget = (element) => isCardField(element) || + element.matches(inputSelector) && element.form instanceof HTMLFormElement && + !autocomplete(element).includes("one-time-code") && + [...labels(element), attr(element, "placeholder")].some((value) => ambiguousCode.test(label(value))) && + formElements(element.form).some(isCardField); + const ancestors = function* (element) { + for (let node = element; node instanceof Element;) { + yield node; + node = node.assignedSlot ?? node.parentElement ?? node.getRootNode().host; + } + }; + + const target = this instanceof Text ? this.parentElement : 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((node) => isCardTarget(node) || (mode !== "type" && isOrderControl(node, node === target)))) { + return { target: "payment" }; + } + if (expected !== undefined && !chain.includes(expected) && !expected.contains(target)) return { target: "missing" }; + if (captchaFrameKind(location.href) !== "passive" && pageHasSecurityCheck(document)) { + 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))) + : formElements(owner); + const imageSubmits = mode === "submit" && owner !== undefined + ? Array.from(owner.getRootNode().querySelectorAll('input[type="image" i]')).filter((field) => field.form === owner) + : []; + if (fields.some(isCardField) || mode === "submit" && owner !== undefined && + [...fields, ...imageSubmits].some((field) => isOrderControl(field))) { + 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..3436dfe 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; @@ -136,6 +143,9 @@ function semanticBrowser(): ReturnType { if (method === "DOM.getBoxModel") { return { model: { content: [10, 10, 110, 10, 110, 40, 10, 40] } }; } + if (method === "Page.createIsolatedWorld") return { executionContextId: 1 }; + if (method === "DOM.resolveNode") return { object: { objectId: "visible-challenge" } }; + if (method === "Runtime.callFunctionOn") return { result: { value: true } }; return {}; }, ); @@ -164,6 +174,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/normalize.ts b/apps/extension/src/driver/semantic/normalize.ts index 0180a79..e7df59a 100644 --- a/apps/extension/src/driver/semantic/normalize.ts +++ b/apps/extension/src/driver/semantic/normalize.ts @@ -15,7 +15,7 @@ const MAX_ELEMENT_STRING_BYTES = 512; const CONTROL_AND_BIDI = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu; -const CLICK_ROLES = new Set([ +export const CLICK_ROLES: ReadonlySet = new Set([ "button", "link", "checkbox", 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..7637cc6 100644 --- a/packages/connector/src/index.test.ts +++ b/packages/connector/src/index.test.ts @@ -21,6 +21,7 @@ import { callBrowserWrite, callConnector, createBrowserConnectors, + pollUnderstudyCommand, UnderstudyCommandNotStartedError, UnderstudyCommandOutcomeUnknownError, UnderstudyCommandPendingError, @@ -106,6 +107,30 @@ 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", origin: "https://shop.example", + } }; + + // #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/" }), @@ -133,6 +158,50 @@ describe("act", () => { expect(commandId).toMatch(/^ik_[0-9a-f]{64}$/); }); + it("requires the act approval grant for a credentialed page request GET", async () => { + // #given + const fetchSpy = vi.fn().mockResolvedValue(eventResponse({ + type: "page_request_result", commandId: "reply", status: 200, body: { records: [1] }, + })); + vi.stubGlobal("fetch", fetchSpy); + const { act, observe } = createBrowserConnectors(ENV, stores()); + const action = { type: "page_request", path: "/orders", method: "GET" } as const; + const input: ActInput = { sessionId: "s-1", action }; + + // #when + await expect(callConnector(observe, { + sessionId: "s-1", read: action as unknown as ObserveInput["read"], + }, undefined)).rejects.toThrow(/input validation failed/); + await expect(callBrowserWrite(act, input, undefined, "get")).rejects.toThrowError(ConnectorPolicyError); + expect(fetchSpy).not.toHaveBeenCalled(); + const output = await callBrowserWrite(act, input, grantFor(BROWSER_ACT_CONNECTOR), "get"); + + // #then + const commandId = output.pageResponse?.commandId; + expect(commandId).toMatch(/^ik_[0-9a-f]{64}$/); + expect(output).toEqual({ ok: true, pageResponse: { status: 200, bodyUnavailable: true, commandId } }); + expect(sentRequest(fetchSpy).body).toMatchObject({ command: { ...action, commandId } }); + }); + + it("retrieves approved GET JSON through the command receipt", async () => { + // #given + const commandId = "ik_get"; + const event = { type: "page_request_result", commandId, status: 200, body: { records: [1] } }; + const fetchSpy = vi.fn().mockResolvedValue(eventResponse({ + commandId, event, safeToRetry: false, status: "completed", + })); + + // #when + const result = await pollUnderstudyCommand({ fetch: fetchSpy }, ENV, "s-1", commandId); + + // #then + expect(result.event).toEqual(event); + expect(fetchSpy).toHaveBeenCalledExactlyOnceWith( + "https://understudy.example.com/v1/sessions/s-1/commands/ik_get", + expect.objectContaining({ method: "GET" }), + ); + }); + it("dry-run needs no grant, sends dryRun:true, and marks the output simulated", async () => { const fetchSpy = vi.fn().mockResolvedValue( eventResponse({ type: "action_result", commandId: "c1", ok: true, simulated: true }), @@ -519,7 +588,13 @@ describe("write-classification sync with @understudy/protocol", () => { it("act's runtime schema gates the same set the types promise", () => { // #given the literal action types the act schema actually accepts - const gated = new Set(actInput.shape.action.options.map((option) => option.shape.type.value)); + const gated = new Set( + actInput.shape.action.options.flatMap((option) => + "shape" in option + ? [option.shape.type.value] + : option.options.map((member) => member.shape.type.value), + ), + ); const expected = new Set(WRITE_COMMAND_TYPES); expect(gated).toEqual(expected); diff --git a/packages/connector/src/index.ts b/packages/connector/src/index.ts index a4e33b1..236eb9f 100644 --- a/packages/connector/src/index.ts +++ b/packages/connector/src/index.ts @@ -5,8 +5,7 @@ * * 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 + * act - write. Fails closed unless the request carries a * flowsafe-minted grant in * requestContext['breakwater.approvedConnectors']. * @@ -30,6 +29,7 @@ import { } from "@proofoftech/breakwater/connector-sdk"; import { A11yNodeSchema, + ActionFailureReasonSchema, type Command, CommandStatusResponseSchema, type DialogRecord, @@ -37,6 +37,7 @@ import { type Event, parseCommand, parseEvent, + PageRequestInputSchema, PendingCommandResponseSchema, type PendingCommandResponse, type CommandStatusResponse, @@ -157,6 +158,7 @@ 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(), }).strict(); export type ObserveOutput = z.infer; @@ -187,6 +189,7 @@ export const actInput = z.object({ dy: z.number().finite(), }).strict(), z.object({ type: z.literal("switch_tab"), tabId: ConnectorTabIdSchema }).strict(), + PageRequestInputSchema, ]), }).strict(); export type ActInput = z.infer; @@ -195,7 +198,13 @@ 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), + commandId: ConnectorIdSchema.optional(), + }).strict().optional(), }).strict(); export type ActOutput = z.infer; @@ -422,7 +431,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, or wait. Read-only.", inputSchema: observeInput, outputSchema: observeOutput, permissions: { sideEffect: "read", egress }, @@ -447,7 +456,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": @@ -466,8 +475,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. " + + "NEVER put passwords, API keys, card numbers, card security codes, or other credentials in any command input.", inputSchema: actInput, outputSchema: actOutput, permissions: { @@ -481,7 +490,20 @@ 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, + ...(command.method === undefined || command.method === "GET" ? { commandId: command.commandId } : {}), + }, + }; + } throw new Error(`act: unexpected event '${ev.type}'`); }, // Simulation: the service checks the ref still resolves (via its internal @@ -495,7 +517,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..625f187 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", origin: "https://shop.example", 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,69 @@ 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, origin: "https://shop.example", 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", origin: "https://shop.example", code: "synthetic" }], + ["an oversized JSON body", { method: "POST", origin: "https://shop.example", body: "é".repeat(PAGE_REQUEST_BODY_MAX_BYTES / 2) }], + ["a write with no origin", { method: "POST" }], + ["a write with an origin that includes a path", { method: "POST", origin: "https://shop.example/checkout" }], + ["a query method override", { method: "POST", origin: "https://shop.example", query: { _method: "DELETE" } }], + ["a body method override", { method: "POST", origin: "https://shop.example", body: { _method: "DELETE" } }], + ] 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", query: { scope: "local" } }; + + // #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..1393249 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,9 @@ export const ActionFailureReasonSchema = z.enum([ "timeout", "action_failed", "result_too_large", + "payment_refused", + "security_check", + "outcome_unknown", ]); export type ActionFailureReason = z.infer; @@ -273,6 +278,145 @@ const CommandBase = { commandId: IdSchema, }; +export const PageRequestWriteMethodSchema = z.enum(["POST", "PUT", "PATCH", "DELETE"]); +export type PageRequestWriteMethod = z.infer; + +// 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) { + 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 PageRequestQuerySchema = 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" }); + } + if (hasPageRequestMethodOverride(value)) { + ctx.addIssue({ code: "custom", message: "page request method overrides are forbidden" }); + } +}); + +export function hasPageRequestMethodOverride(value: unknown): boolean { + return value !== null && typeof value === "object" && + Object.keys(value).some((key) => /^_method(?:\[|$)/i.test(key.trim())); +} + +const PageRequestOriginSchema = AllowedOriginSchema.refine( + (origin) => resolvePageRequestUrl(origin, "/") !== null, + { message: "page request requires a canonical HTTP(S) origin" }, +); + +const PageRequestFields = { + type: z.literal("page_request"), + path: UrlStringSchema, + query: PageRequestQuerySchema.optional(), +}; + +export const PageRequestReadInputSchema = strictObject({ + ...PageRequestFields, + method: z.literal("GET").optional(), +}); +export const PageRequestWriteInputSchema = strictObject({ + ...PageRequestFields, + origin: PageRequestOriginSchema, + method: PageRequestWriteMethodSchema, + body: PageRequestBodySchema.refine( + (value) => !hasPageRequestMethodOverride(value), + { message: "page request method overrides are forbidden" }, + ).optional(), +}); + +export const PageRequestInputSchema = z.discriminatedUnion("method", [ + PageRequestReadInputSchema, + PageRequestWriteInputSchema, +]); + +const PageRequestCommandSchema = z.discriminatedUnion("method", [ + strictObject({ ...PageRequestReadInputSchema.shape, ...CommandBase }), + strictObject({ ...PageRequestWriteInputSchema.shape, ...CommandBase }), +]); +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; sort(): 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"], + options?: { canonicalQuery: boolean }, +): ResolvedPageRequestUrl | null { + if (!path.startsWith("/") || path.startsWith("//") || /[\\?#\s\p{Cc}]/u.test(path) || + hasPageRequestMethodOverride(query)) { + return null; + } + try { + const url = new WhatwgURL(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); + if (options?.canonicalQuery) url.searchParams.sort(); + return utf8ByteLength(url.href) <= 8 * 1024 ? url : null; + } catch { + return null; + } +} + +export const PageRequestWritePolicySchema = z.array(strictObject({ + origin: PageRequestOriginSchema, + method: PageRequestWriteMethodSchema, + path: UrlStringSchema, + query: PageRequestQuerySchema.optional(), +}).superRefine((rule, ctx) => { + const url = resolvePageRequestUrl(rule.origin, rule.path, rule.query); + 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 +502,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 +514,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 }> + | Extract +) => command.type === "page_request" + ? command.method !== undefined && command.method !== "GET" + : WRITE_COMMANDS.has(command.type); export const PROTOCOL_CAPABILITIES = [ "safe-write-v3", @@ -384,6 +535,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 +603,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 +647,7 @@ export const EventSchema = z.union([ }), ActionResultSchema, ElementsResultSchema, + PageRequestResultSchema, strictObject({ type: z.literal("page_event"), kind: z.enum(["navigated", "load"]), @@ -500,6 +675,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 +714,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 +980,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"),