diff --git a/.changeset/protocol-three-hard-cut.md b/.changeset/protocol-three-hard-cut.md index fb15f9f..2159b19 100644 --- a/.changeset/protocol-three-hard-cut.md +++ b/.changeset/protocol-three-hard-cut.md @@ -8,6 +8,4 @@ and add the `semantic-elements-v1` capability. Add bounded semantic capture, deterministic find, inspect, continuation, same-document deltas, fixed action failures, device-policy, physical-window -inventory, suspended-session adoption, attended-idle, and extension-local -payment-card command contracts. Card submission returns only fixed not-started -or outcome-unknown results. +inventory, suspended-session adoption, and attended-idle. diff --git a/.claude/skills/understudy-browser/SKILL.md b/.claude/skills/understudy-browser/SKILL.md index 20f05ca..2bca3c1 100644 --- a/.claude/skills/understudy-browser/SKILL.md +++ b/.claude/skills/understudy-browser/SKILL.md @@ -1,6 +1,6 @@ --- name: understudy-browser -description: Drive the user's real, logged-in Chrome through Understudy MCP: open sessions, find and inspect bounded semantic elements, click, type non-sensitive text, submit an extension-local payment card, and diagnose device or origin-policy failures. +description: Drive the user's real, logged-in Chrome through Understudy MCP: open sessions, find and inspect bounded semantic elements, click, type non-sensitive text, and diagnose device or origin-policy failures. --- # Drive a real browser with Understudy @@ -46,10 +46,6 @@ include `https://www.example.com`. Dashboard edits are pushed to the device: removals fence affected sessions immediately; additions become usable after the extension acknowledges the new policy. Re-pairing is not required. -Payment origins are a second, extension-local allowlist. A card can be used -only when both the general session policy and the local payment policy permit -the exact top-level origin. - ## Browser loop ```text @@ -79,32 +75,16 @@ validation. Never invent, parse, or modify a ref. Commands are serialized per account. Do not issue browser actions in parallel. If a result is pending, use `browser_get_result`; do not resubmit the action. -## Sensitive data and payments - -`browser_type` is for non-sensitive text only. Never send passwords, API keys, -payment-card data, or government identifiers through it. Understudy has no -server-side secret vault and no generic credential-fill tool. - -Cards are enrolled, edited, and deleted only in the extension side panel. The -model can see aliases and approved payment origins through -`browser_list_cards`; PAN, expiry, CVV, ciphertext, masked card data, and key -material never leave the extension. - -To submit a card: - -1. Snapshot the checkout form. -2. Map distinct refs for number, expiry, CVV, optional cardholder name, and the - submit control. -3. Call `browser_submit_card` once with the local alias and those refs. -4. Treat `outcome_unknown` as final. Never retry it automatically and never - inspect the destroyed payment tab to infer approval. A fresh session may - inspect a separate receipt or order-status page. +## Sensitive data -`not_started` means no card byte was inserted. Take a fresh snapshot before a -manual retry. Once any byte is inserted, every result is `outcome_unknown`. +`browser_type` is for non-sensitive text only. NEVER send passwords, API keys, +card numbers, card security codes, other credentials, or government identifiers +through it. Understudy has no server-side secret vault and no generic +credential-fill tool. -Stop before any other irreversible action: purchase, send, delete, publish, or -an OAuth grant. Obtain the user's explicit approval for that exact action. +Stop before any irreversible action, including a purchase, message, deletion, +publication, or OAuth grant. Obtain the user's explicit approval for that exact +action. ## Failure handling @@ -114,7 +94,6 @@ an OAuth grant. Obtain the user's explicit approval for that exact action. | Device offline or unavailable | Chrome is closed, reconciling policy/inventory, or the extension is disconnected | Ask the user to open Chrome and check the side panel; use `browser_status`. | | At capacity | Other active sessions hold the device's slots | Ask the user to close another controlled session. | | Origin refused | The exact origin is absent from current session/device policy | Ask the user to edit dashboard origins and wait for policy acknowledgement. | -| Payment origin refused | General policy or extension-local payment policy is missing the exact origin | Ask the user to update the relevant policy; do not bypass it. | | Stale ref | Navigation or a newer snapshot invalidated the ref | Snapshot again and remap. | | Command still running | The original request remains authoritative | Use `browser_get_result`. | | OUTCOME UNKNOWN | The write may have executed | Never retry automatically; observe later from a fresh safe context. | @@ -131,7 +110,5 @@ an OAuth grant. Obtain the user's explicit approval for that exact action. | `browser_navigate`, `browser_click`, `browser_type` | General navigation and non-sensitive input | | `browser_press_key`, `browser_scroll`, `browser_wait` | Interaction and waiting | | `browser_get_result` | Collect a pending command without retrying it | -| `browser_list_cards` | Return local aliases and exact payment origins only | -| `browser_submit_card` | Atomic local-card fill and submit with fixed outcomes | There is no `browser_fill_secret` or `browser_list_secrets` tool. diff --git a/DEFERRED.md b/DEFERRED.md index bd29dbf..8f3a13b 100644 --- a/DEFERRED.md +++ b/DEFERRED.md @@ -2,39 +2,8 @@ # Track deferred work -## API-credential vault +## Website credential storage -Understudy 0.2.0 deliberately removes the cloud secret vault and generic -`fill_secret` capability. The extension-local payment-card vault is not an -API-credential vault and must not be generalized into one. +Understudy stores no website passwords, API tokens, or payment data in the extension or the service. Sign in to each website in your own browser so agents can reuse that session. Consumers may store usernames. They must never store passwords. -A future API-credential feature requires a separate design and security review -before implementation. The review starts from these constraints: - -- Use separate IndexedDB records and a separate object store from payment - cards. Do not overload the card schema, aliases, key-purpose AAD, handlers, or - UI. -- Support only reviewed, service-specific adapters. Each adapter fixes the - service identity, exact destination origin, credential type, injection point, - and permitted operation. -- Do not expose generic header injection, form/ref injection, arbitrary fetch, - arbitrary DOM/runtime evaluation, or a plaintext-returning API. -- Do not share a plaintext API, decrypted value type, generic executor, or - message shape with the card vault. -- Keep plaintext, ciphertext, key material, masked values, and recovery data - inside the extension boundary. Define key loss, corruption, deletion, - migration, update, and uninstall behavior explicitly. -- Preserve the intersection of backend-authoritative device/session policy and - a local exact-origin approval. Revocation and policy narrowing must fence - active use. -- Specify page-derived output suppression and fixed result enums for each - adapter. Do not infer remote success from an untrusted page. -- Threat-model the controlling agent, approved service origin, extension/update - authority, operating system, logs, crash reports, sync, backups, clipboard, - downloads, network tooling, and other extensions. -- Add adversarial unit and real-Chrome tests proving no credential marker - appears outside the adapter and approved destination. - -Out of scope until that design is accepted: password storage, bearer tokens, -API keys, OAuth refresh tokens, SSH keys, arbitrary login automation, and -migration from any retired cloud-vault data. +Owner decision, 2 December 2026 (Dubai time). diff --git a/README.md b/README.md index 08386e2..be77ddc 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Read [`docs/technical-plan.md`](docs/technical-plan.md) for the architecture, sa | `packages/protocol` | Published Zod 4 command, event, control-frame, and status contracts | | `packages/connector` | Published Breakwater connectors for browser observation and governed non-secret actions | | `apps/backend` | Hono Worker, session and device Agents, tenant coordinator, quotas, and telemetry | -| `apps/extension` | WXT and React extension with attended control, two-session unattended hosting, and a local payment-card vault | +| `apps/extension` | WXT and React extension with attended control and two-session unattended hosting | | `apps/cdp-spike` | Historical Manifest V3 CDP capability harness | `@understudy/protocol@0.8.0` and `@understudy/connector@0.5.1` are the current published versions. The pending coordinated changeset releases protocol 0.9.0 and connector 0.6.0; a local build does not publish them. @@ -31,7 +31,7 @@ Understudy never: - Records video, GIF, Document Object Model history, or session content - Replaces consumer approval or durable audit -Protocol 3 provides at-most-once write execution with explicit pending and unknown outcomes. It removes the cloud secret oracle. Payment cards remain encrypted inside the extension and are submitted through a dedicated sensitive boundary that returns no page-derived result. +Protocol 3 provides at-most-once write execution with explicit pending and unknown outcomes. It removes the cloud secret oracle. ## Develop the repository diff --git a/apps/backend/CHANGELOG.md b/apps/backend/CHANGELOG.md index 6bfed29..5ad65dc 100644 --- a/apps/backend/CHANGELOG.md +++ b/apps/backend/CHANGELOG.md @@ -5,7 +5,7 @@ ### Minor Changes - Remove the cloud vault and secret-fill oracle; reject legacy API and OAuth credentials through the protocol-3 authentication hard cut. -- Add device-bound MCP/OAuth credentials, mandatory S256 PKCE, direct pairing offers, versioned per-device origin policy, OAuth connection revocation, and extension-local card MCP tools. +- Add device-bound MCP/OAuth credentials, mandatory S256 PKCE, direct pairing offers, versioned per-device origin policy, and OAuth connection revocation. - Add physical-window inventory, exact orphan cleanup, suspended-session adoption, attended idle detach, HSTS, and Worker deployment provenance. - Add structured MCP output schemas, bounded semantic find/inspect/pagination tools, same-document deltas, fixed failure rendering, and exact snapshot diff --git a/apps/backend/CLAUDE.md b/apps/backend/CLAUDE.md index 822cd50..cd7e43d 100644 --- a/apps/backend/CLAUDE.md +++ b/apps/backend/CLAUDE.md @@ -17,7 +17,7 @@ The backend is a Hono Cloudflare Worker with Durable Objects for accounts, devic | `src/auth.ts` | Caller authentication, HMAC session ownership, `udt_v2` device credentials, and connect tickets | Changing credentials, session ownership, or WebSocket tickets | | `src/dashboard/app.ts` | Sign-in, CSRF, direct pairing, policy, browser-bound tokens, OAuth grants, and revocation | Changing dashboard actions, authentication, policy, or consent | | `src/dashboard/pages.ts` | Nonce-bearing dashboard, consent, privacy, and onboarding HTML | Changing dashboard rendering, content security policy, or onboarding copy | -| `src/mcp/tools.ts` | Protocol-3 browser tools and fixed local-card contracts | Adding or changing MCP tools, schemas, or tool guidance | +| `src/mcp/tools.ts` | Protocol-3 browser tools | Adding or changing MCP tools, schemas, or tool guidance | | `src/mcp/props.ts` | Current OAuth/token props: device, auth epoch, and contract version | Changing MCP credential claims or connection state | | `src/mcp/static-auth.ts` | `usk_v2` request authentication with current device/epoch validation | Changing static MCP authentication or revocation behavior | | `src/validation.ts` | Bounded strict input and exact-origin canonicalization | Adding request validation or changing origin handling | diff --git a/apps/backend/README.md b/apps/backend/README.md index 32e53a7..45b41ab 100644 --- a/apps/backend/README.md +++ b/apps/backend/README.md @@ -2,7 +2,7 @@ # Operate the Understudy backend -The backend is a Cloudflare Worker with Hono, OAuth Provider, Agents SDK Durable Objects, SQLite coordination, Analytics Engine telemetry, and a rate-limit backstop. It coordinates browser work but never runs Chromium or stores payment cards. +The backend is a Cloudflare Worker with Hono, OAuth Provider, Agents SDK Durable Objects, SQLite coordination, Analytics Engine telemetry, and a rate-limit backstop. It coordinates work in the paired browser. ## Object topology @@ -132,7 +132,7 @@ The canonical host is `https://understudy.proofof.tech`. Canonical HTTP requests ## Telemetry boundary -Telemetry is content-free. Never add page URL, title, content, dialog text, screenshot data, refs, card aliases, card values, credentials, tickets, or complete socket URLs. +Telemetry is content-free. Never add page URL, title, content, dialog text, screenshot data, refs, credentials, tickets, or complete socket URLs. ## Verify diff --git a/apps/backend/src/account-agent.ts b/apps/backend/src/account-agent.ts index 8579187..365c08e 100644 --- a/apps/backend/src/account-agent.ts +++ b/apps/backend/src/account-agent.ts @@ -738,10 +738,6 @@ export class AccountAgent extends DurableObject { } if (result.kind !== "terminal") return; const event = result.event; - if (input.draft.type === "submit_card" && event.type === "card_submission_result") { - await this.applyCardResultBookkeeping(actor, event); - return; - } if (await this.applySnapshotResultBookkeeping(actor, event)) return; if (event.type !== "action_result") return; const snapshot = await this.snapshotState(actor); @@ -809,10 +805,6 @@ export class AccountAgent extends DurableObject { } private async applyPolledEventBookkeeping(actor: McpActorRef, event: Event): Promise { - if (event.type === "card_submission_result") { - await this.applyCardResultBookkeeping(actor, event); - return; - } if (await this.applySnapshotResultBookkeeping(actor, event)) return; if (event.type !== "action_result") return; const snapshot = await this.snapshotState(actor); @@ -883,15 +875,4 @@ export class AccountAgent extends DurableObject { }); return true; } - - private async applyCardResultBookkeeping( - actor: McpActorRef, - event: Extract, - ): Promise { - if (event.status === "outcome_unknown") { - await this.clearBinding(actor); - return; - } - await this.invalidateSnapshot(actor); - } } diff --git a/apps/backend/src/dashboard/pages.ts b/apps/backend/src/dashboard/pages.ts index 1e5fdfc..70e3426 100644 --- a/apps/backend/src/dashboard/pages.ts +++ b/apps/backend/src/dashboard/pages.ts @@ -131,7 +131,7 @@ export function privacyPage(): Fragment {

Local extension storage

-

The extension stores device credentials, profile configuration, and locally encrypted payment-card records in extension-owned storage. Card plaintext, ciphertext, and encryption keys are not sent to the service. Browser-session storage may contain lease assignments, owned-window identifiers, recovery state, write-journal status, and pending dialog records.

+

The extension stores device credentials and profile configuration in extension-owned storage. Browser-session storage may contain lease assignments, owned-window identifiers, recovery state, write-journal status, and pending dialog records.

The extension does not persist command bodies, typed text, secret plaintext, secret references, screenshots, accessibility trees, or general navigation history in local extension storage. A pending dialog record includes the page URL where the dialog appeared until the service acknowledges that record.

diff --git a/apps/backend/src/mcp/outcomes.ts b/apps/backend/src/mcp/outcomes.ts index 421cc62..833cf9c 100644 --- a/apps/backend/src/mcp/outcomes.ts +++ b/apps/backend/src/mcp/outcomes.ts @@ -332,47 +332,6 @@ function mapTerminalEvent( }, }; } - case "cards_result": { - const result = textResult( - `Local card aliases: ${event.aliases.length === 0 ? "(none)" : event.aliases.join(", ")}.\n` + - `Locally approved payment origins: ${ - event.approvedOrigins.length === 0 - ? "(none)" - : event.approvedOrigins.join(", ") - }. Card values and masked card data remain inside the extension.`, - ); - return { - ...result, - structuredContent: { - source: "understudy", - result: { - aliases: event.aliases, - approvedOrigins: event.approvedOrigins, - }, - }, - }; - } - case "card_submission_result": { - const result = - event.status === "not_started" - ? errorResult( - `Card submission did not start (${event.reason}). Take a new browser_snapshot before retrying.`, - event.reason, - ) - : errorResult( - `OUTCOME UNKNOWN (${event.reason}): card data may have been submitted. ` + - "Do not retry automatically. Open a fresh session to inspect a receipt or status page.", - event.reason, - ); - return { - ...result, - structuredContent: { - source: "understudy", - error: { reason: event.reason, retryable: false }, - result: { status: event.status }, - }, - }; - } default: return textResult(`Completed with a ${event.type} event.`); } diff --git a/apps/backend/src/mcp/tools.ts b/apps/backend/src/mcp/tools.ts index ab8b704..91fac3a 100644 --- a/apps/backend/src/mcp/tools.ts +++ b/apps/backend/src/mcp/tools.ts @@ -1,5 +1,5 @@ /** - * The MCP catalog: browser execution plus the extension-local card vault. + * The MCP catalog for browser execution. * resolve_ref (internal dry-run probe), switch_tab (protocol-3 no-op), and * snapshot mode:"dom" (extension returns unsupported) are deliberately not * tools, because a tool that can only fail teaches the model wrong @@ -14,7 +14,7 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { z } from "zod"; -import { CardAliasSchema, utf8ByteLength } from "@understudy/protocol"; +import { utf8ByteLength } from "@understudy/protocol"; import type { CommandDraft, McpActorRef, @@ -421,7 +421,7 @@ export function registerTools(server: McpServer, host: McpToolHost): void { title: "Type text", description: "Type non-sensitive text into the element behind a ref. NEVER type passwords, API keys, " + - "payment-card data, or other credentials with this tool.", + "card numbers, card security codes, or other credentials with this tool.", inputSchema: { ref: REF_INPUT, text: z.string().max(65536), @@ -452,73 +452,6 @@ export function registerTools(server: McpServer, host: McpToolHost): void { ), ); - server.registerTool( - "browser_list_cards", - { - title: "List local payment cards", - description: - "List card aliases and exact payment origins approved inside this Chrome extension. " + - "Card numbers, expiry values, CVVs, and masked card data are never returned.", - inputSchema: {}, - outputSchema: BROWSER_OUTPUT_SCHEMA, - annotations: { readOnlyHint: true }, - }, - () => - withProps((props) => - runCommand(props, "browser_list_cards", { type: "list_cards" }, { - write: false, - usesRef: false, - }), - ), - ); - - server.registerTool( - "browser_submit_card", - { - title: "Submit a local payment card", - description: - "Use a locally enrolled card to fill model-selected refs and invoke submitRef as one " + - "atomic sensitive operation. The current top-level origin must be allowed by both the " + - "session policy and the extension's local payment policy. Once any card byte is inserted, " + - "the outcome is always OUTCOME UNKNOWN and must never be retried automatically.", - inputSchema: { - cardAlias: CardAliasSchema, - numberRef: REF_INPUT, - expiry: z.discriminatedUnion("kind", [ - z.object({ kind: z.literal("combined"), ref: REF_INPUT }).strict(), - z.object({ - kind: z.literal("split"), - monthRef: REF_INPUT, - yearRef: REF_INPUT, - }).strict(), - ]), - cvvRef: REF_INPUT, - cardholderNameRef: REF_INPUT.optional(), - submitRef: REF_INPUT, - }, - outputSchema: BROWSER_OUTPUT_SCHEMA, - }, - (args) => - withProps((props) => - runCommand( - props, - "browser_submit_card", - { - type: "submit_card", - cardAlias: args.cardAlias, - numberRef: args.numberRef, - expiry: args.expiry, - cvvRef: args.cvvRef, - ...(args.cardholderNameRef === undefined - ? {} - : { cardholderNameRef: args.cardholderNameRef }), - submitRef: args.submitRef, - }, - { write: true, usesRef: true }, - ), - ), - ); - server.registerTool( "browser_press_key", { diff --git a/apps/backend/src/session.ts b/apps/backend/src/session.ts index 1481930..7fdad33 100644 --- a/apps/backend/src/session.ts +++ b/apps/backend/src/session.ts @@ -353,8 +353,6 @@ export class SessionAgent extends Agent { case "screenshot_result": case "tabs_result": case "action_result": - case "cards_result": - case "card_submission_result": case "pong": this.coordinator.resolvePending(ev); return; @@ -681,12 +679,6 @@ export class SessionAgent extends Agent { ) { return { kind: "unsupported", commandId: command.commandId }; } - if ( - (command.type === "list_cards" || command.type === "submit_card") && - !(this.state.capabilities ?? []).includes("local-card-vault-v1") - ) { - return { kind: "unsupported", commandId: command.commandId }; - } if ( [ "capture_elements", diff --git a/apps/backend/test/coordinator.test.ts b/apps/backend/test/coordinator.test.ts index 9997baf..133498a 100644 --- a/apps/backend/test/coordinator.test.ts +++ b/apps/backend/test/coordinator.test.ts @@ -191,19 +191,10 @@ describe("CfSessionCoordinator", () => { }); it("does not log command metadata, refs, or plaintext", async () => { - // #given a spy on console.log and two sensitive commands + // #given a spy on console.log and a command with typed text const host = createFakeHost(); const coordinator = new CfSessionCoordinator(host); const logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); - const submitCard: Command = { - type: "submit_card", - commandId: "c4", - cardAlias: "work", - numberRef: "s1e2", - expiry: { kind: "combined", ref: "s1e3" }, - cvvRef: "s1e4", - submitRef: "s1e5", - }; const typeCmd: Command = { type: "type", commandId: "c5", @@ -211,18 +202,9 @@ describe("CfSessionCoordinator", () => { text: "hunter2-plaintext", }; - let second: Promise | undefined; + let pending: Promise | undefined; try { - // #when both commands are sent one at a time - const first = send(coordinator, submitCard); - coordinator.resolvePending({ - type: "card_submission_result", - commandId: "c4", - status: "outcome_unknown", - reason: "submission_attempted", - }); - await first; - second = send(coordinator, typeCmd); + pending = send(coordinator, typeCmd); // #then command execution emits no ad hoc logs. The HTTP boundary owns // bounded, pseudonymized command telemetry through the shared emitter. @@ -230,7 +212,7 @@ describe("CfSessionCoordinator", () => { } finally { logSpy.mockRestore(); coordinator.resolvePending({ type: "action_result", commandId: "c5", ok: true }); - if (second !== undefined) await second; + if (pending !== undefined) await pending; } }); diff --git a/apps/backend/test/mcp-tools.test.ts b/apps/backend/test/mcp-tools.test.ts index 589dc4a..e3ef7ab 100644 --- a/apps/backend/test/mcp-tools.test.ts +++ b/apps/backend/test/mcp-tools.test.ts @@ -7,7 +7,6 @@ import { env, exports } from "cloudflare:workers"; import { runInDurableObject } from "cloudflare:test"; import { describe, expect, it } from "vitest"; -import type { Event } from "@understudy/protocol"; import type { AccountAgent, McpActorRef, @@ -124,7 +123,7 @@ async function callTool( } describe("MCP tool catalog over streamable HTTP", () => { - it("lists exactly the 17 designed tools with input and output schemas", async () => { + it("lists exactly the 15 designed tools with input and output schemas", async () => { const minted = await mintUserToken(); const sessionId = await mcpHandshake(minted.token); const res = await mcpPost( @@ -137,14 +136,13 @@ describe("MCP tool catalog over streamable HTTP", () => { const tools = (parsed.result as { tools: { name: string; inputSchema?: unknown; outputSchema?: unknown }[]; }).tools; - expect(tools).toHaveLength(17); + expect(tools).toHaveLength(15); expect(tools.map((tool) => tool.name).sort()).toEqual([ "browser_click", "browser_close", "browser_find", "browser_get_result", "browser_inspect", - "browser_list_cards", "browser_navigate", "browser_open", "browser_press_key", @@ -153,7 +151,6 @@ describe("MCP tool catalog over streamable HTTP", () => { "browser_snapshot", "browser_snapshot_next", "browser_status", - "browser_submit_card", "browser_type", "browser_wait", ]); @@ -450,10 +447,6 @@ describe("AccountAgent ref-staleness guard", () => { input: RunCommandInput, result: RunCommandResult, ): Promise; - applyPolledEventBookkeeping( - actor: McpActorRef, - event: Extract, - ): Promise; }; const clickInput: RunCommandInput = { tool: "browser_click", @@ -523,49 +516,6 @@ describe("AccountAgent ref-staleness guard", () => { `snapshotBinding:${actor.deviceId}`, ), ).toMatchObject({ valid: false }); - - const cardInput: RunCommandInput = { - tool: "browser_submit_card", - draft: { - type: "submit_card", - cardAlias: "work", - numberRef: "a1:s0e1", - expiry: { kind: "combined", ref: "a1:s0e2" }, - cvvRef: "a1:s0e3", - submitRef: "a1:s0e4", - }, - write: true, - usesRef: true, - }; - const preflightResult = { - type: "card_submission_result", - commandId: "c4", - status: "not_started", - reason: "stale_ref", - } as const; - await internals.applyRefBookkeeping(actor, cardInput, { - kind: "terminal", - event: preflightResult, - }); - expect(await internals.ctx.storage.get(`binding:${actor.deviceId}`)).toBeDefined(); - expect( - await internals.ctx.storage.get<{ valid: boolean }>( - `snapshotBinding:${actor.deviceId}`, - ), - ).toMatchObject({ valid: false }); - - await internals.applyPolledEventBookkeeping(actor, preflightResult); - expect(await internals.ctx.storage.get(`binding:${actor.deviceId}`)).toBeDefined(); - - // A card result collected after the synchronous poll budget closes the - // binding just like a result returned by the original tool call. - await internals.applyPolledEventBookkeeping(actor, { - type: "card_submission_result", - commandId: "c5", - status: "outcome_unknown", - reason: "submission_attempted", - }); - expect(await internals.ctx.storage.get(`binding:${actor.deviceId}`)).toBeUndefined(); }); }); diff --git a/apps/backend/test/session.test.ts b/apps/backend/test/session.test.ts index 332a87b..29d1bb3 100644 --- a/apps/backend/test/session.test.ts +++ b/apps/backend/test/session.test.ts @@ -1011,14 +1011,14 @@ describe("protocol-v3 command result correlation", () => { }); }); - it("keeps a card submission pending when the result type does not match", async () => { + it("keeps a write pending when the result type does not match", async () => { const stub = await getSessionStub(crypto.randomUUID()); await runInDurableObject(stub, async (instance: SessionAgent) => { setAuthoritative(instance); const attempt = seedAttempt(instance, { state: "granted", - commandType: "submit_card", + commandType: "click", dryRun: false, isWrite: true, }); @@ -1030,9 +1030,9 @@ describe("protocol-v3 command result correlation", () => { attemptId: attempt.attemptId, commandId: attempt.commandId, event: { - type: "action_result", + type: "tabs_result", commandId: attempt.commandId, - ok: true, + tabs: [], }, }), ); @@ -1045,19 +1045,17 @@ describe("protocol-v3 command result correlation", () => { attemptId: attempt.attemptId, commandId: attempt.commandId, event: { - type: "card_submission_result", + type: "action_result", commandId: attempt.commandId, - status: "not_started", - reason: "card_not_found", + ok: true, }, }), ); await expect(instance.getCommandStatus(attempt.commandId)).resolves.toMatchObject({ status: "completed", event: { - type: "card_submission_result", - status: "not_started", - reason: "card_not_found", + type: "action_result", + ok: true, }, }); }); diff --git a/apps/extension/CHANGELOG.md b/apps/extension/CHANGELOG.md index 49e8cda..731196f 100644 --- a/apps/extension/CHANGELOG.md +++ b/apps/extension/CHANGELOG.md @@ -4,7 +4,6 @@ ### Minor Changes -- Add the extension-local AES-GCM payment-card vault, enrollment UI, exact payment-origin policy, and atomic card submission boundary. - Add direct dashboard pairing offers, versioned origin-policy acknowledgement, complete assignment and owned-window reconciliation, suspended-session adoption, and attended idle detach fencing. - Remove every cloud-vault and secret-fill interface. - Add Stagehand-derived multi-frame AX/DOM capture, bounded semantic caches, diff --git a/apps/extension/CLAUDE.md b/apps/extension/CLAUDE.md index 255b9e6..476f3e2 100644 --- a/apps/extension/CLAUDE.md +++ b/apps/extension/CLAUDE.md @@ -3,8 +3,7 @@ ## Overview WXT + React MV3 extension driving protocol-3 commands into attended tabs and -extension-owned unattended windows through `chrome.debugger` CDP. The same -extension owns the local encrypted payment-card vault. +extension-owned unattended windows through `chrome.debugger` CDP. ## Index @@ -16,7 +15,7 @@ extension owns the local encrypted payment-card vault. | `wxt.config.ts` | WXT config: `srcDir`, React module, `@understudy/protocol` source alias, manifest (`minimum_chrome_version`, permissions) | Changing manifest permissions, resolving protocol from source vs dist | | `tsconfig.json` | TS project config (extends WXT-generated `.wxt/tsconfig.json`) | Adjusting compiler options | | `scripts/stub-server.mjs` | Throwaway M2 WS peer: validates every Event with real protocol schemas, sends Commands from stdin | Driving/debugging the extension over the real WS wire | -| `scripts/e2e.mjs` | Local-Chrome store-build test for semantic capture, frame/shadow traversal, ref fencing, local-vault persistence, and marker non-egress | Changing semantic discovery, the vault boundary, service-worker restart behavior, or the store manifest | +| `scripts/e2e.mjs` | Local-Chrome store-build test for semantic capture, frame/shadow traversal, ref fencing, and worker-eviction recovery | Changing semantic discovery, service-worker restart behavior, or the store manifest | | `scripts/store-release.mjs` | Published store-artifact recorder and normalized-content deployment gate | Building, submitting, recording, or promoting a store release | | `scripts/verify-build-target.mjs` | Staging manifest authority and pinned-ID verifier | Changing staging mode, origin, permissions, or key | | `src/events.ts` | `errorMessage`, `actionError`: shared error-to-`action_result` helpers | Adding an executor that can fail | @@ -56,20 +55,15 @@ extension owns the local encrypted payment-card vault. | `src/core/startup-gate.test.ts` | Unit tests for startup coalescing, downstream blocking, and retry | Verifying store startup gating | | `src/core/router.ts` | `routeCommand`: dispatches a parsed `Command` to a `CdpSession` executor or tab handler | Adding a new protocol Command type | | `src/core/router.test.ts` | Unit tests for `routeCommand` (one Event per Command, error paths) | Verifying command routing | -| `src/core/session-manager.ts` | Unattended assignment lifecycle, owned-window registry, cleanup outboxes, policy reconciliation, and payment sensitive-mode teardown | Changing physical-window ownership or unattended convergence | -| `src/core/session-runtime.ts` | Per-lease protocol-3 runtime, ref fencing, card-list/submit handlers, and fixed-result sensitive execution | Changing unattended commands or payment submission | +| `src/core/session-manager.ts` | Unattended assignment lifecycle, owned-window registry, cleanup outboxes, and policy reconciliation | Changing physical-window ownership or unattended convergence | +| `src/core/session-runtime.ts` | Per-lease protocol-3 runtime and ref fencing | Changing unattended commands | | `src/core/profile-client.ts` | Device-control connection, durable alarm reconnect, full inventory reconciliation, policy ack, and session adoption | Changing hosted-profile control-plane behavior | -| `src/core/write-journal.ts` | Durable write handshake state containing only scrubbed action results or fixed payment result enums | Changing crash/retry semantics for writes | +| `src/core/write-journal.ts` | Durable write handshake state and scrubbed action results | Changing crash/retry semantics for writes | | `src/core/dedupe.ts` | `WriteDedupe`: `claim()` (execute / replay a completed write / drop an in-flight duplicate) + `remember`/`release`/`clear`; idempotent-retry contract, storage.session-mirrored, cap 100 | Changing write replay/dedupe/in-flight behavior | | `src/core/dedupe.test.ts` | Unit tests for `WriteDedupe` (claim decisions, concurrent-claim atomicity, in-flight drop, cap, eviction survival, clear-on-session-change) | Verifying dedupe behavior | -| `src/payment/card-validation.ts` | Alias, PAN/Luhn, future-expiration, CVV, and exact payment-origin validation | Changing card enrollment rules | -| `src/payment/indexeddb-card-store.ts` | Extension-origin IndexedDB stores for the non-extractable AES key, encrypted records, and payment origins | Changing local persistence or migrations | -| `src/payment/card-vault.ts` | Serialized AES-256-GCM card operations with unique IVs and record-bound AAD | Changing encryption, corruption, or key-loss behavior | | `src/service-origin.ts` | Build-target-specific service origin validation shared by background and pairing flows | Changing local, staging, or production service authority | | `src/entrypoints/background.ts` | MV3 service worker: attended and hosted WS lifecycle, external pairing, CDP ownership, write journal, wake reconciliation, alarm keepalive, and panel host | Debugging eviction/reconnect, attach/detach, pairing, or panel messaging | | `src/entrypoints/sidepanel/index.html` | Sidepanel HTML entry | Changing the sidepanel document shell | | `src/entrypoints/sidepanel/main.tsx` | React root mount for the sidepanel | Changing sidepanel bootstrap | -| `src/entrypoints/sidepanel/App.tsx` | Pairing/hosting status, local-card enrollment/deletion, payment-origin editor, internal attended controls, and `Port` reconnect | Changing sidepanel UI or panel↔SW messaging | -| `src/entrypoints/sidepanel/card-save.ts` | Correlated card-save requests, acknowledgements, disconnect rejection, and post-commit form reset | Changing card enrollment acknowledgement or form-clearing behavior | -| `src/entrypoints/sidepanel/card-save.test.ts` | Card-save acknowledgement, failure, disconnect, and form-preservation tests | Verifying card enrollment UI commit behavior | +| `src/entrypoints/sidepanel/App.tsx` | Pairing, hosting status, internal attended controls, and `Port` reconnect | Changing sidepanel UI or panel↔SW messaging | | `src/entrypoints/sidepanel/style.css` | Sidepanel styling | Changing sidepanel appearance | diff --git a/apps/extension/README.md b/apps/extension/README.md index 19c1f3b..ba7dae5 100644 --- a/apps/extension/README.md +++ b/apps/extension/README.md @@ -2,7 +2,7 @@ # Host Understudy sessions in Chrome -The Manifest V3 extension controls one attended user tab or at most two extension-owned unattended windows. It also owns the local encrypted payment-card vault. Unattended profiles are tenant-dedicated because sessions share cookies, browser storage, installed extensions, and the extension update authority. +The Manifest V3 extension controls one attended user tab or at most two extension-owned unattended windows. Unattended profiles are tenant-dedicated because sessions share cookies, browser storage, installed extensions, and the extension update authority. ## Runtime modules @@ -10,12 +10,10 @@ The Manifest V3 extension controls one attended user tab or at most two extensio |---|---| | `core/profile-client.ts` | Pairing credential, browser epoch, control tickets, policy acknowledgement, and reconciliation | | `core/session-manager.ts` | Assignment maps, owned-window registry, closure outbox, and exact orphan cleanup | -| `core/session-runtime.ts` | One controlled tab, CDP session, command queue, journal, dialog outbox, and sensitive payment boundary | -| `payment/card-vault.ts` | AES-GCM envelope format and vault operations | -| `payment/indexeddb-card-store.ts` | Extension-origin IndexedDB records, key, schema, and local payment origins | -| `driver/cdp.ts` | CDP queue, deadlines, frame sessions, actions, ref validation, navigation containment, and atomic card-field insertion | +| `core/session-runtime.ts` | One controlled tab, CDP session, command queue, journal, and dialog outbox | +| `driver/cdp.ts` | CDP queue, deadlines, frame sessions, actions, ref validation, and navigation containment | | `driver/semantic/` | Multi-frame hybrid capture, safe normalization, bounded immutable cache, projections, search, inspect, pagination, and deltas | -| `entrypoints/sidepanel/` | Pairing, hosting state, card enrollment, and local payment-origin editor | +| `entrypoints/sidepanel/` | Pairing and hosting status | Each unattended lease creates a new unfocused `about:blank` window. The extension never adopts an existing tab for unattended work. @@ -63,10 +61,7 @@ pnpm --filter @understudy/extension zip:store `test:e2e` launches local Chrome with the store build. It verifies bounded semantic capture on a 10,000-element document, offscreen find, inspect, pagination, same-process and OOPIF frames, shadow DOM, structured deltas, and -stale refs. It also enrolls and submits a synthetic card through semantic refs, -verifies a non-extractable persisted key and encrypted envelope, reloads the -extension, deletes the vault, and checks that the synthetic marker did not -appear in network, console, or exception events. +stale refs. It also verifies that worker eviction expires refs and cursors. Load `.output/chrome-mv3/` for internal testing, `.output/chrome-mv3-staging/` for hosted staging, or `.output/chrome-mv3-store/` for store acceptance. The staging build has the stable extension ID `ebpcldlibljfjhcfknagjcdmhggeknfc` and connects only to `https://staging.understudy.proofof.tech`. The store build connects only to `https://understudy.proofof.tech` and has no pinned key. @@ -101,26 +96,6 @@ After a full Chrome restart, exact closure records from the old browser epoch ar Same-epoch inventory can recover a suspended lease. A browser restart creates a new epoch; accepted adoption carries a bumped lease fence and always starts in a fresh blank window. Old URLs, refs, and tasks are not restored. -## Card vault - -The vault uses extension-origin IndexedDB, one locally persisted non-extractable AES-256-GCM key, a fresh 96-bit IV per write, and AAD containing schema version, record UUID, and `payment-card`. It encrypts cardholder name, PAN, expiration, and CVV. - -The vault has no sync, export, backup, recovery, backend copy, analytics copy, or content-script API. Removing the extension or selecting **Delete vault** destroys recovery. There is no unlock prompt because unattended operation requires the persisted key to remain usable after worker and browser restart. - -Enrollment validates alias, Luhn checksum, PAN length, future expiration, and 3–4 digit CVV before encryption. Payment origins are exact HTTPS origins maintained only in the extension. - -`browser_submit_card` validates distinct current refs and the intersection of the server session policy with the local payment policy. It then enters sensitive mode before decryption, stops ordinary command and page-event ingress, and obtains a local authorization revision for the selected card and payment origin. It rechecks that revision and card expiration immediately before the first byte is inserted. A card edit, deletion, vault deletion, or payment-origin edit during preparation therefore fails before insertion. The operation fills every mapped field, invokes submit, closes the tab, and returns only a fixed result. It never reads a receipt or infers payment success. - -Alias, origin-policy, distinct-ref, and current-generation checks are a non-sensitive preflight. A rejected preflight returns a fixed `not_started` result without decrypting card data or tearing down the session. Once sensitive mode begins, every exit closes the controlled tab. - -See [local card-vault requirements](../../docs/local-card-vault-security-requirements.md) for the trust and risk contract. - -## Sensitive-mode containment - -After sensitive mode begins, suppress snapshots, screenshots, URLs, titles, dialogs, tab metadata, page errors, console/network artifacts, ordinary commands, and arbitrary logs. On success, failure, timeout, worker interruption, tab closure, or extension update, close the controlled tab and clear its runtime. - -Once insertion may have begun, every outcome is `outcome_unknown`; never retry automatically. - ## Attended detach Each attended attachment has a UUID incarnation. Deliberate or debugger-driven detach sends that UUID and tab ID. The backend ignores stale frames, clears browser-derived artifacts for the current attachment, and reports `idle`. Socket loss reports `detached`. Detaching never closes the user’s tab. diff --git a/apps/extension/RUNBOOK.md b/apps/extension/RUNBOOK.md index 8097589..a5de37a 100644 --- a/apps/extension/RUNBOOK.md +++ b/apps/extension/RUNBOOK.md @@ -3,9 +3,8 @@ # Verify the Understudy extension in Chrome This runbook covers the protocol-3 extension, pairing, policy reconciliation, -owned-window recovery, and the extension-local payment-card vault. Use a -dedicated Chrome profile. Chrome's debugger banner is process-wide and cannot -be suppressed; dismissing it can detach a controlled tab. +and owned-window recovery. Use a dedicated Chrome profile. Dismissing Chrome's +process-wide debugger banner can detach a controlled tab. ## Automated gate @@ -23,11 +22,8 @@ pnpm --filter @understudy/extension zip:store ``` `test:e2e` uses local Chrome and the existing `ws` package. It loads the store -build, exercises bounded semantic discovery across large pages, frames, and -shadow DOM, then exercises the real panel message boundary and IndexedDB. It -verifies a non-extractable persisted key and encrypted record, reloads the -extension, and deletes the vault. No card marker may appear in protocol frames, -network, console, exception, storage, journal, or ordinary log output. +build, configures hosting through the side panel, and exercises bounded +semantic discovery across large pages, frames, and shadow DOM. ## Verify semantic discovery @@ -49,11 +45,8 @@ network, console, exception, storage, journal, or ordinary log output. target-changed reason and must never dispatch to a replacement. 8. Evict the extension worker. Old cursors must return `cursor_expired`; old refs must not revive from the persisted generation. -9. Confirm editable, password, and synthetic card values never appear in +9. Confirm editable and password values never appear in protocol events, WSS, MCP output, logs, journals, storage, or analytics. -10. Enter payment sensitive mode. Semantic capture, find, inspect, - continuation, screenshots, page-derived errors, and automatic retry remain - unavailable before any page data is read. ## Load the release build @@ -129,31 +122,6 @@ The extension must send the current attachment UUID and tab ID. The backend enters `idle`, clears browser data, tabs, URL, and dialogs, and ignores a stale detach from an older attachment. Socket loss remains `detached`. -## Enroll and submit a synthetic card - -Use test data only. - -1. In the side panel, add a card alias containing only letters, digits, `.`, - `_`, or `-`. The alias must contain no card digits. -2. Confirm invalid Luhn data, expired dates, and a CVV outside three or four - digits are rejected before storage. -3. Save a valid synthetic card. Confirm the form is cleared. -4. Add the checkout's exact top-level origin to the local payment-origin list. -5. Open a session whose general policy includes the same origin. -6. Call `browser_list_cards`. It may return only aliases and approved origins. -7. Snapshot the form and map distinct refs for PAN, combined or split expiry, - CVV, optional cardholder name, and submit. -8. Call `browser_submit_card` once. From sensitive-mode entry onward, no - snapshot, screenshot, dialog, URL, title, tab metadata, page error, console, - network artifact, generic command, clipboard, download, or arbitrary log may - escape. The payment tab closes on every exit path. -9. A failure before any card byte is inserted returns `not_started`. Any later - result is `outcome_unknown`, including a completed submit. Never retry the - latter automatically or inspect the destroyed tab for approval. -10. Delete the card, then delete the whole vault. Repeating deletion must be - harmless. Losing the key while records exist must fail closed as key loss, - not silently create a new key. - ## Network-blip diagnosis Run `scripts/network-blip-harness.sh` from the repository root. The credential @@ -188,8 +156,7 @@ Do not add a secondary control origin. Use the result table in Record the source SHA, extension version, browser version, device ID, policy version, session/lease fences, observed timestamps, and fixed outcome enums. -Keep card data, raw credentials, and raw outage evidence outside Git. +Keep raw credentials and raw outage evidence outside Git. -Release only when automated checks pass, the physical-window and sensitive-mode -negative paths pass in real Chrome, and all three independent review lanes are -clean. +Release only when automated checks pass, the physical-window negative paths +pass in real Chrome, and all three independent review lanes are clean. diff --git a/apps/extension/WEBSTORE.md b/apps/extension/WEBSTORE.md index cd52a25..09019e5 100644 --- a/apps/extension/WEBSTORE.md +++ b/apps/extension/WEBSTORE.md @@ -44,11 +44,9 @@ Understudy pairs a dedicated Chrome profile with the hosted Understudy service. Pairing is approved directly between the Understudy dashboard and the installed extension. The side panel shows device and policy state, controlled-window inventory, connection recovery, an emergency stop, and a local troubleshooting log. -The optional payment-card vault is stored only in this extension's local IndexedDB. Card fields are encrypted with a non-extractable local key and are never sent to the Understudy backend. Card submission requires both the dashboard origin policy and a separate local payment-origin approval. After card data is inserted, Understudy reports only that the outcome is unknown and closes the controlled tab. +Understudy does not choose tasks or approve actions. Your connected AI client selects bounded semantic page elements and requests actions. Element references are opaque and checked again before use; the extension does not expose selectors or automatically redirect an action to a changed target. You control pairing, allowed origins, API or OAuth connections, and device revocation. -Understudy does not choose tasks or approve actions. Your connected AI client selects bounded semantic page elements and requests actions. Element references are opaque and checked again before use; the extension does not expose selectors or automatically redirect an action to a changed target. You control pairing, allowed origins, local cards, API or OAuth connections, and device revocation. - -For ordinary browser work the service may handle controlled-tab URLs and titles, bounded semantic website content, screenshots, dialogs, requested input actions, browser metadata, status, errors, and command results. The extension excludes editable values, raw HTML, selectors, scripts, and arbitrary DOM attributes from semantic results. From payment sensitive-mode entry onward those observation channels are suppressed. +For browser work the service may handle controlled-tab URLs and titles, bounded semantic website content, screenshots, dialogs, requested input actions, browser metadata, status, errors, and command results. The extension excludes editable values, raw HTML, selectors, scripts, and arbitrary DOM attributes from semantic results. Use a dedicated Chrome profile. Controlled tabs in one profile share that profile's cookies and browser storage. Chrome's debugger banner is process-wide and cannot be suppressed by an extension. ``` @@ -62,7 +60,7 @@ Privacy: `https://understudy.proofof.tech/privacy` Single purpose: ```text -Pair Chrome with Understudy so an AI client the user authorizes can operate extension-owned tabs only on website origins the user allows, including optional submission of locally encrypted cards on separately approved payment origins. +Pair Chrome with Understudy so an AI client the user authorizes can operate extension-owned tabs only on website origins the user allows. ``` ## Permissions @@ -70,12 +68,10 @@ Pair Chrome with Understudy so an AI client the user authorizes can operate exte - `debugger`: attach CDP only to extension-owned controlled tabs for requested page observation and actions. - `storage`: retain the device credential and policy state, the physical-window - and recovery registry, and the encrypted local card vault with its - non-extractable key. + and recovery registry. - `alarms`: provide a Manifest V3 wake-up backstop for connection recovery, policy/inventory reconciliation, and exact controlled-window cleanup. -- `sidePanel`: pair, show connection and policy state, stop hosting, and manage - local cards and payment origins. +- `sidePanel`: pair, show connection and policy state, and stop hosting. - `https://understudy.proofof.tech/*`: receive direct one-time pairing offers, request short-lived connect tickets, and exchange validated control/session frames over HTTPS and WSS. @@ -89,21 +85,17 @@ Declare, conservatively: - Personally identifiable information - Authentication information -- Financial and payment information - Web history - User activity - Website content - Personal communications -The local card vault handles payment information even though its plaintext, -ciphertext, and key do not cross the extension boundary. Do not claim that -local-only storage removes the category. Confirm the privacy policy states that -Understudy does not sell data, use it for advertising, or permit routine human -review. +Confirm the privacy policy states that Understudy does not sell data, use it +for advertising, or permit routine human review. ## Reviewer flow -Do not provide a shared API token, pairing offer, mailbox password, card, or +Do not provide a shared API token, pairing offer, mailbox password, or personal login. The reviewer uses temporary data. ```text @@ -113,9 +105,8 @@ personal login. The reviewer uses temporary data. 4. Choose Pair this browser. The installed extension receives and redeems the one-time offer directly; no code is copied. 5. Create a browser-bound API token or connect an OAuth-capable MCP client to https://understudy.proofoftech/mcp and select this device at consent. 6. Ask the client to open https://example.com. The panel reports one controlled window. -7. Add a synthetic test card in the side panel and approve https://example.com as a payment origin. Card details stay in local encrypted extension storage. -8. Delete the card. Choose Stop hosting and confirm that the controlled window closes. -9. Revoke the device in the dashboard. Existing API and OAuth access for that device fails immediately. +7. Choose Stop hosting and confirm that the controlled window closes. +8. Revoke the device in the dashboard. Existing API and OAuth access for that device fails immediately. Chrome's debugger banner is process-wide. Dismissing it can detach a controlled tab and does not identify which tab is controlled. ``` diff --git a/apps/extension/scripts/e2e.mjs b/apps/extension/scripts/e2e.mjs index 4144142..2f38c5f 100644 --- a/apps/extension/scripts/e2e.mjs +++ b/apps/extension/scripts/e2e.mjs @@ -63,7 +63,7 @@ const profileDir = path.join(testDir, "chrome-profile"); await generateCertificate(testDir); const localService = await startLocalService(testDir); let chromeStderr = ""; -let chrome = launchChrome(); +const chrome = launchChrome(); function launchChrome() { const child = spawn(chromePath, [ @@ -91,16 +91,12 @@ function launchChrome() { } let client; -const observedEvents = []; try { const debuggerUrl = await devtoolsUrl(profileDir, chrome); client = await CdpClient.connect(debuggerUrl); - let worker = await attachWorker(client); - let panel = await attachExtensionPage(client, worker.url); - const rawPage = await attachExtensionPage(client, worker.url, "unattended-bootstrap.html"); + const worker = await attachWorker(client); + const panel = await attachExtensionPage(client, worker.url); await client.call("Runtime.enable", {}, worker.sessionId); - await client.call("Network.enable", {}, worker.sessionId).catch(() => {}); - await client.call("Network.enable", {}, panel.sessionId).catch(() => {}); const loadedManifest = await evaluate(client, worker.sessionId, "chrome.runtime.getManifest()"); assert(loadedManifest.version === "0.2.0", "loaded extension has wrong version"); @@ -110,66 +106,6 @@ try { "externally_connectable widened beyond the canonical dashboard origin", ); - ({ worker, panel } = await verifyVaultSchemaCompatibility( - client, - worker, - panel, - rawPage, - )); - - const marker = `UNDERSTUDY_E2E_${Date.now()}`; - const initial = await panelCommand(client, panel.sessionId, { type: "getState" }, - "state.cardVault.revision === 0"); - assert(initial.cardVault.aliases.length === 0, "vault was not empty in a fresh Chrome profile"); - - const saved = await panelCardSave( - client, - panel.sessionId, - { - alias: "e2e-card", - cardholderName: marker, - pan: "4111111111111111", - expiryMonth: "12", - expiryYear: "2099", - cvv: "123", - }, - ); - assert(!JSON.stringify(saved).includes(marker), "card marker escaped through extension state"); - await panelCommand( - client, - panel.sessionId, - { type: "setPaymentOrigins", origins: [localService.origin] }, - `state.cardVault.approvedOrigins.includes(${JSON.stringify(localService.origin)})`, - ); - - const beforeRestart = await inspectVault(client, panel.sessionId); - assert(beforeRestart.cards === 1, "encrypted record was not persisted"); - assert(beforeRestart.keyExtractable === false, "persisted AES key is extractable"); - assert(beforeRestart.ivBytes === 12, "persisted AES-GCM IV is not 96 bits"); - assert(!JSON.stringify(beforeRestart).includes(marker), "card marker escaped through vault metadata"); - - observedEvents.push(...client.events); - client.close(); - await stopChrome(chrome); - chromeStderr = ""; - chrome = launchChrome(); - client = await CdpClient.connect(await devtoolsUrl(profileDir, chrome)); - worker = await attachWorker(client); - panel = await attachExtensionPage(client, worker.url); - await client.call("Runtime.enable", {}, worker.sessionId); - await client.call("Network.enable", {}, panel.sessionId).catch(() => {}); - const restored = await panelCommand( - client, - panel.sessionId, - { type: "getState" }, - "state.cardVault.aliases.includes('e2e-card')", - ); - assert(restored.cardVault.approvedOrigins.includes(localService.origin), - "payment-origin policy did not survive extension restart"); - const afterRestart = await inspectVault(client, panel.sessionId); - assert(afterRestart.cards === 1 && afterRestart.keyExtractable === false, - "vault key or record did not survive extension restart"); - await panelCommand( client, panel.sessionId, @@ -190,28 +126,8 @@ try { const browser = { client, worker, panel }; await runSemanticElements(browser, localService); - await runInterruptedPayment(browser, localService, marker, "before-insertion"); - await runInterruptedPayment(browser, localService, marker, "after-insertion"); - await runCheckpointedPayment(browser, localService, marker); - worker = browser.worker; - - await panelCommand( - client, - panel.sessionId, - { type: "deleteCardVault" }, - "state.cardVault.aliases.length === 0 && state.cardVault.approvedOrigins.length === 0", - ); - const deleted = await inspectVault(client, panel.sessionId); - assert(deleted.cards === 0 && deleted.hasKey === false, - "explicit vault deletion left records or key material behind"); - - const leaked = [...observedEvents, ...client.events].some((event) => - /^(Network\.|Runtime\.consoleAPICalled|Runtime\.exceptionThrown)/.test(event.method) && - JSON.stringify(event.params).includes(marker), - ); - assert(!leaked, "card marker escaped through network, console, or exception events"); process.stdout.write( - "extension E2E passed: bounded semantic discovery, frame/shadow capture, deltas, vault restart, real CDP submission, worker-eviction recovery, deletion, and marker non-egress\n", + "extension E2E passed: bounded semantic discovery, frame/shadow capture, deltas, ref fencing, and worker-eviction recovery\n", ); } catch (error) { if (chromeStderr.length > 0) process.stderr.write(chromeStderr); @@ -276,14 +192,6 @@ async function startLocalService(directory) { })); return; } - if (url.pathname === "/checkout") { - response.writeHead(200, { - "content-type": "text/html; charset=utf-8", - "cache-control": "no-store", - }); - response.end(checkoutPage(url.searchParams.get("stage") ?? "checkpoint")); - return; - } if (url.pathname === "/semantic") { response.writeHead(200, { "content-type": "text/html; charset=utf-8", @@ -300,12 +208,6 @@ async function startLocalService(directory) { response.end(semanticFramePage(url.searchParams.get("kind") ?? "same")); return; } - if (url.pathname === "/signal" && request.method === "POST") { - emit({ kind: "signal", stage: url.searchParams.get("stage") }); - response.writeHead(204); - response.end(); - return; - } response.writeHead(404); response.end("not found"); }); @@ -354,7 +256,6 @@ async function startLocalService(directory) { emit({ kind: "control_open" }); websocket.on("message", (raw) => { const text = raw.toString(); - assert(!text.includes("UNDERSTUDY_E2E_"), "card marker escaped over control WSS"); const frame = JSON.parse(text); if (frame.type === "device_hello") browserEpoch = frame.browserEpoch; emit({ kind: "control", frame }); @@ -379,7 +280,6 @@ async function startLocalService(directory) { emit({ kind: "session_open", sessionId }); websocket.on("message", (raw) => { const text = raw.toString(); - assert(!text.includes("UNDERSTUDY_E2E_"), "card marker escaped over session WSS"); emit({ kind: "session", sessionId, frame: JSON.parse(text) }); }); websocket.on("close", () => { @@ -422,7 +322,7 @@ async function startLocalService(directory) { reject(new Error( `local-service event timeout after index ${after}: ${events .slice(after) - .map((event) => `${event.index}:${event.kind}:${JSON.stringify(event.frame ?? event.stage ?? "")}`) + .map((event) => `${event.index}:${event.kind}:${JSON.stringify(event.frame ?? "")}`) .join(" | ")}\n${requestedAt}`, )); }, timeoutMs); @@ -431,35 +331,6 @@ async function startLocalService(directory) { } } -function checkoutPage(stage) { - const signal = stage === "before-insertion" - ? `for (const field of document.querySelectorAll("input")) { - field.addEventListener("focus", signalAndBlock, { once: true }); - }` - : stage === "after-insertion" - ? `document.querySelector("#number").addEventListener("input", signalAndBlock, { once: true });` - : ""; - return ` - - - - - - - - `; -} - function semanticPage(origin) { const port = new URL(origin).port; const elements = Array.from( @@ -556,7 +427,7 @@ async function provisionScenario(service, label, url) { commandId: `navigate-${sequence}`, tabId: hello.frame.tabs[0].tabId, url, - }, cursor, true); + }, cursor); await readCommand(service, scenario, { type: "wait", commandId: `wait-idle-${sequence}`, @@ -677,7 +548,7 @@ async function runSemanticElements(browser, service) { type: "click", commandId: `semantic-click-late-${scenario.sequence}`, ref: lateRef, - }, service.cursor(), true); + }, service.cursor()); assert(clickLate.frame.event.ok === true, "find/inspect/next did not preserve a usable ref"); for (const query of [ @@ -717,7 +588,7 @@ async function runSemanticElements(browser, service) { type: "click", commandId: `semantic-click-updater-${scenario.sequence}`, ref: updater, - }, service.cursor(), true); + }, service.cursor()); assert(updateResult.frame.event.ok === true, "custom click handler did not execute"); await new Promise((resolve) => setTimeout(resolve, 100)); @@ -741,7 +612,7 @@ async function runSemanticElements(browser, service) { type: "click", commandId: `semantic-click-stale-${scenario.sequence}`, ref: lateRef, - }, service.cursor(), true); + }, service.cursor()); assert( stale.frame.event.ok === false && stale.frame.event.reason === "stale_ref", "fresh semantic capture did not stale the prior ref", @@ -764,7 +635,7 @@ async function runSemanticElements(browser, service) { type: "click", commandId: `semantic-click-replaced-${scenario.sequence}`, ref: replaceable, - }, service.cursor(), true); + }, service.cursor()); assert( replaced.frame.event.ok === false && replaced.frame.event.reason === "target_changed", "a target replaced after pointer movement was not rejected as target_changed", @@ -887,205 +758,7 @@ async function runSemanticElements(browser, service) { await waitForManagerIdle(browser.client, browser.panel.sessionId); } -async function runInterruptedPayment(browser, service, marker, stage) { - const scenario = await preparePaymentScenario(service, stage); - const cursor = service.cursor(); - sendSubmitCard(service, scenario); - await service.waitFor( - (event) => event.kind === "signal" && event.stage === stage, - cursor, - ); - const restartCursor = service.cursor(); - await stopExtensionWorker(browser.client, browser.worker, browser.panel.sessionId); - await panelCommand(browser.client, browser.panel.sessionId, { type: "getState" }, "true"); - browser.worker = await attachWorker(browser.client); - await browser.client.call("Runtime.enable", {}, browser.worker.sessionId); - await service.waitFor( - (event) => event.kind === "control" && event.frame.type === "device_hello", - restartCursor, - ); - await triggerBackstop(browser.client, browser.panel.sessionId); - await service.waitFor( - (event) => - event.kind === "control" && - event.frame.type === "closed" && - event.frame.sessionId === scenario.sessionId, - restartCursor, - ); - await panelCommand( - browser.client, - browser.panel.sessionId, - { type: "getState" }, - "state.controlledTabs === 0", - ); - await waitForManagerIdle(browser.client, browser.panel.sessionId); - await assertCheckoutClosed(browser.client, scenario.checkoutUrl); - const results = service.events.filter( - (event) => - event.kind === "session" && - event.sessionId === scenario.sessionId && - event.frame.type === "command_result" && - event.frame.commandId === scenario.submitCommand.commandId, - ); - assert(results.length === 0, `${stage} interruption emitted a retryable payment result`); - const journal = await readJournal( - browser.client, - browser.panel.sessionId, - scenario.sessionId, - ); - const record = journal.find((entry) => entry.attemptId === scenario.submitAttemptId); - assert( - record?.state === "started" || record?.state === "unknown", - `${stage} interruption lost its no-retry journal fence`, - ); - assert(!JSON.stringify(journal).includes(marker), `${stage} journal leaked the card marker`); -} - -async function runCheckpointedPayment(browser, service, marker) { - const scenario = await preparePaymentScenario(service, "checkpoint"); - const cursor = service.cursor(); - sendSubmitCard(service, scenario); - const result = await service.waitFor( - (event) => - event.kind === "session" && - event.sessionId === scenario.sessionId && - event.frame.type === "command_result" && - event.frame.commandId === scenario.submitCommand.commandId, - cursor, - ); - assert( - result.frame.event.status === "outcome_unknown" && - result.frame.event.reason === "submission_attempted", - "real CDP card submission did not return the fixed unknown-outcome result", - ); - const restartCursor = service.cursor(); - await stopExtensionWorker(browser.client, browser.worker, browser.panel.sessionId); - await panelCommand(browser.client, browser.panel.sessionId, { type: "getState" }, "true"); - browser.worker = await attachWorker(browser.client); - await browser.client.call("Runtime.enable", {}, browser.worker.sessionId); - await service.waitFor( - (event) => event.kind === "control" && event.frame.type === "device_hello", - restartCursor, - ); - await triggerBackstop(browser.client, browser.panel.sessionId); - await service.waitFor( - (event) => - event.kind === "control" && - event.frame.type === "closed" && - event.frame.sessionId === scenario.sessionId, - restartCursor, - ); - await panelCommand( - browser.client, - browser.panel.sessionId, - { type: "getState" }, - "state.controlledTabs === 0", - ); - await waitForManagerIdle(browser.client, browser.panel.sessionId); - await assertCheckoutClosed(browser.client, scenario.checkoutUrl); - const journal = await readJournal( - browser.client, - browser.panel.sessionId, - scenario.sessionId, - ); - const record = journal.find((entry) => entry.attemptId === scenario.submitAttemptId); - assert(record?.state === "completed_unacked", "checkpointed fixed result was not durable"); - assert(record.event?.status === "outcome_unknown", "durable result changed after worker eviction"); - assert(!JSON.stringify(journal).includes(marker), "checkpointed journal leaked the card marker"); - const results = service.events.filter( - (event) => - event.kind === "session" && - event.sessionId === scenario.sessionId && - event.frame.type === "command_result" && - event.frame.commandId === scenario.submitCommand.commandId, - ); - assert(results.length === 1, "checkpointed card submission was automatically retried or replayed"); -} - -async function preparePaymentScenario(service, stage) { - const checkoutUrl = `${service.origin}/checkout?stage=${encodeURIComponent(stage)}`; - const { scenario } = await provisionScenario( - service, - `payment-${stage}`, - checkoutUrl, - ); - scenario.checkoutUrl = checkoutUrl; - const sequence = scenario.sequence; - const cursor = service.cursor(); - const snapshotAttemptId = `snapshot-attempt-${sequence}`; - const snapshotCommandId = `snapshot-${sequence}`; - service.sendSession(scenario.sessionId, { - type: "command", - ...commandFence(scenario, snapshotAttemptId), - command: { - type: "capture_elements", - commandId: snapshotCommandId, - scope: "document", - view: "all", - limit: 80, - changesOnly: false, - }, - }); - const snapshot = await service.waitFor( - (event) => - event.kind === "session" && - event.sessionId === scenario.sessionId && - event.frame.type === "command_result" && - event.frame.commandId === snapshotCommandId, - cursor, - ); - const semanticSnapshot = requireElementsResult(snapshot, "snapshot"); - const refs = {}; - for (const name of ["Expiration", "Cardholder name", "Card number", "CVV", "Submit payment"]) { - const requiredAction = name === "Submit payment" ? "click" : "type"; - const element = semanticSnapshot.elements.find( - (candidate) => candidate.name === name && candidate.actions.includes(requiredAction), - ); - assert( - typeof element?.ref === "string", - `snapshot did not expose an actionable ${name}`, - ); - refs[name] = element.ref; - } - scenario.submitAttemptId = `submit-attempt-${sequence}`; - scenario.submitCommand = { - type: "submit_card", - commandId: `submit-${sequence}`, - cardAlias: "e2e-card", - numberRef: refs["Card number"], - expiry: { kind: "combined", ref: refs.Expiration }, - cvvRef: refs.CVV, - cardholderNameRef: refs["Cardholder name"], - submitRef: refs["Submit payment"], - }; - const prepareCursor = service.cursor(); - service.sendSession(scenario.sessionId, { - type: "write_prepare", - ...commandFence(scenario, scenario.submitAttemptId), - commandId: scenario.submitCommand.commandId, - commandType: "submit_card", - requestFingerprint: "b".repeat(64), - }); - await service.waitFor( - (event) => - event.kind === "session" && - event.sessionId === scenario.sessionId && - event.frame.type === "write_ready" && - event.frame.attemptId === scenario.submitAttemptId, - prepareCursor, - ); - return scenario; -} - -function sendSubmitCard(service, scenario) { - service.sendSession(scenario.sessionId, { - type: "write_grant", - ...commandFence(scenario, scenario.submitAttemptId), - command: scenario.submitCommand, - }); -} - -async function writeCommand(service, scenario, command, after, acknowledge) { +async function writeCommand(service, scenario, command, after) { const attemptId = `${command.commandId}-attempt`; const fingerprint = "a".repeat(64); service.sendSession(scenario.sessionId, { @@ -1116,13 +789,11 @@ async function writeCommand(service, scenario, command, after, acknowledge) { event.frame.commandId === command.commandId, ready.index + 1, ); - if (acknowledge) { - service.sendSession(scenario.sessionId, { - type: "result_ack", - attemptId, - commandId: command.commandId, - }); - } + service.sendSession(scenario.sessionId, { + type: "result_ack", + attemptId, + commandId: command.commandId, + }); return result; } @@ -1171,15 +842,6 @@ async function waitForCdpEvent(client, predicate) { throw new Error("expected CDP event did not arrive"); } -function readJournal(client, sessionId, controlledSessionId) { - const key = `understudy:journal:${controlledSessionId}`; - return evaluate( - client, - sessionId, - `chrome.storage.session.get(${JSON.stringify(key)}).then((value) => value[${JSON.stringify(key)}] ?? [])`, - ); -} - async function waitForManagerIdle(client, sessionId) { for (let attempt = 0; attempt < 100; attempt += 1) { const state = await evaluate( @@ -1201,23 +863,6 @@ async function waitForManagerIdle(client, sessionId) { throw new Error("extension session manager did not converge to an idle inventory"); } -async function triggerBackstop(client, sessionId) { - await evaluate( - client, - sessionId, - `chrome.alarms.create("ws-backstop", { when: Date.now() + 50 })`, - ); -} - -async function assertCheckoutClosed(client, checkoutUrl) { - for (let attempt = 0; attempt < 100; attempt += 1) { - const { targetInfos } = await client.call("Target.getTargets"); - if (!targetInfos.some((target) => target.url === checkoutUrl)) return; - await new Promise((resolve) => setTimeout(resolve, 50)); - } - throw new Error(`owned checkout target remained open: ${checkoutUrl}`); -} - async function stopChrome(child) { signalChromeGroup(child, "SIGTERM"); if (child.exitCode === null) { @@ -1319,9 +964,9 @@ async function attachWorker(client) { ); } -async function attachExtensionPage(client, workerUrl, document = "sidepanel.html") { +async function attachExtensionPage(client, workerUrl) { const extensionUrl = new URL(workerUrl); - const pageUrl = `${extensionUrl.protocol}//${extensionUrl.host}/${document}`; + const pageUrl = `${extensionUrl.protocol}//${extensionUrl.host}/sidepanel.html`; const { targetId } = await client.call("Target.createTarget", { url: pageUrl }); const { sessionId } = await client.call("Target.attachToTarget", { targetId, @@ -1338,169 +983,6 @@ async function attachExtensionPage(client, workerUrl, document = "sidepanel.html throw new Error("extension side panel did not load"); } -async function verifyVaultSchemaCompatibility(client, worker, panel, rawPage) { - await client.call("Target.closeTarget", { targetId: panel.targetId }); - await stopExtensionWorker(client, worker, rawPage.sessionId); - await seedVersionOneVault(client, rawPage.sessionId); - - panel = await attachExtensionPage(client, worker.url); - worker = await attachWorker(client); - const migratedState = await panelCommand( - client, - panel.sessionId, - { type: "getState" }, - "state.cardVault.aliases.includes('legacy-card')", - ); - assert( - migratedState.cardVault.approvedOrigins.includes("https://legacy.example"), - "version-1 payment origins were not preserved during migration", - ); - const migrated = await inspectVault(client, rawPage.sessionId); - assert(migrated.databaseVersion === 2, "version-1 vault did not upgrade to version 2"); - assert(migrated.metadataVersion === 2, "vault migration did not persist schema metadata"); - assert(migrated.cards === 1 && migrated.hasKey, "vault migration lost a card or key"); - - await panelCommand( - client, - panel.sessionId, - { type: "deleteCardVault" }, - "state.cardVault.aliases.length === 0 && state.cardVault.approvedOrigins.length === 0", - ); - - await client.call("Target.closeTarget", { targetId: panel.targetId }); - await stopExtensionWorker(client, worker, rawPage.sessionId); - await seedFutureVault(client, rawPage.sessionId); - - panel = await attachExtensionPage(client, worker.url); - worker = await attachWorker(client); - const futureState = await panelCommand( - client, - panel.sessionId, - { type: "getState" }, - "typeof state.cardVault.error === 'string'", - ); - assert(futureState.cardVault.aliases.length === 0, "future vault schema was exposed"); - const future = await inspectVaultVersion(client, rawPage.sessionId); - assert( - future.databaseVersion === 3 && future.metadataVersion === 3, - "opening a future vault schema modified or downgraded it", - ); - - await client.call("Target.closeTarget", { targetId: panel.targetId }); - await stopExtensionWorker(client, worker, rawPage.sessionId); - await deleteVaultDatabase(client, rawPage.sessionId); - panel = await attachExtensionPage(client, worker.url); - worker = await attachWorker(client); - await panelCommand( - client, - panel.sessionId, - { type: "getState" }, - "state.cardVault.aliases.length === 0 && state.cardVault.error === undefined", - ); - return { worker, panel }; -} - -function seedVersionOneVault(client, sessionId) { - return evaluate(client, sessionId, `(async () => { - const databaseName = "understudy-payment-card-vault"; - await new Promise((resolve, reject) => { - const request = indexedDB.deleteDatabase(databaseName); - request.onerror = () => reject(request.error); - request.onblocked = () => reject(new Error("version-1 seed deletion blocked")); - request.onsuccess = () => resolve(); - }); - const key = await crypto.subtle.generateKey( - { name: "AES-GCM", length: 256 }, - false, - ["encrypt", "decrypt"], - ); - await new Promise((resolve, reject) => { - const request = indexedDB.open(databaseName, 1); - request.onupgradeneeded = () => { - const database = request.result; - database.createObjectStore("keys", { keyPath: "id" }); - const cards = database.createObjectStore("cards", { keyPath: "id" }); - cards.createIndex("alias", "alias", { unique: true }); - database.createObjectStore("settings", { keyPath: "id" }); - }; - request.onerror = () => reject(request.error); - request.onsuccess = () => { - const database = request.result; - const transaction = database.transaction(["keys", "cards", "settings"], "readwrite"); - transaction.objectStore("keys").put({ id: "payment-card-key", key }); - transaction.objectStore("cards").put({ - id: "00000000-0000-4000-8000-0000000000a1", - alias: "legacy-card", - schemaVersion: 1, - purpose: "payment-card", - iv: new Uint8Array(12).buffer, - ciphertext: new Uint8Array(17).buffer, - }); - transaction.objectStore("settings").put({ - id: "payment-origins", - origins: ["https://legacy.example"], - }); - transaction.onerror = () => reject(transaction.error); - transaction.oncomplete = () => { database.close(); resolve(); }; - }; - }); - return true; - })()`); -} - -function seedFutureVault(client, sessionId) { - return evaluate(client, sessionId, `(async () => { - const databaseName = "understudy-payment-card-vault"; - await new Promise((resolve, reject) => { - const request = indexedDB.deleteDatabase(databaseName); - request.onerror = () => reject(request.error); - request.onblocked = () => reject(new Error("future-schema seed deletion blocked")); - request.onsuccess = () => resolve(); - }); - await new Promise((resolve, reject) => { - const request = indexedDB.open(databaseName, 3); - request.onupgradeneeded = () => { - const database = request.result; - database.createObjectStore("keys", { keyPath: "id" }); - const cards = database.createObjectStore("cards", { keyPath: "id" }); - cards.createIndex("alias", "alias", { unique: true }); - database.createObjectStore("settings", { keyPath: "id" }); - const metadata = database.createObjectStore("metadata", { keyPath: "id" }); - metadata.put({ id: "schema", version: 3 }); - }; - request.onerror = () => reject(request.error); - request.onsuccess = () => { request.result.close(); resolve(); }; - }); - return true; - })()`); -} - -function deleteVaultDatabase(client, sessionId) { - return evaluate(client, sessionId, `new Promise((resolve, reject) => { - const request = indexedDB.deleteDatabase("understudy-payment-card-vault"); - request.onerror = () => reject(request.error); - request.onblocked = () => reject(new Error("vault deletion blocked")); - request.onsuccess = () => resolve(true); - })`); -} - -function inspectVaultVersion(client, sessionId) { - return evaluate(client, sessionId, `new Promise((resolve, reject) => { - const request = indexedDB.open("understudy-payment-card-vault"); - request.onerror = () => reject(request.error); - request.onsuccess = () => { - const database = request.result; - const transaction = database.transaction("metadata", "readonly"); - const metadata = transaction.objectStore("metadata").get("schema"); - transaction.onerror = () => reject(transaction.error); - transaction.oncomplete = () => { - resolve({ databaseVersion: database.version, metadataVersion: metadata.result?.version }); - database.close(); - }; - }; - })`); -} - async function evaluate(client, sessionId, expression) { const result = await client.call("Runtime.evaluate", { expression, @@ -1530,70 +1012,6 @@ function panelCommand(client, sessionId, message, condition) { })`); } -function panelCardSave(client, sessionId, card) { - const requestId = `e2e-save-${Date.now()}`; - return evaluate(client, sessionId, `new Promise((resolve, reject) => { - const port = chrome.runtime.connect({name: "panel"}); - const timer = setTimeout(() => { port.disconnect(); reject(new Error("card save timeout")); }, 10000); - let savedState; - let acknowledged = false; - const finish = () => { - if (savedState === undefined || !acknowledged) return; - clearTimeout(timer); - port.disconnect(); - resolve(savedState); - }; - port.onMessage.addListener((message) => { - if (message?.type === "state" && message.cardVault.aliases.includes(${JSON.stringify(card.alias)})) { - savedState = message; - finish(); - } - if (message?.type === "cardVaultSaveResult" && message.requestId === ${JSON.stringify(requestId)}) { - if (!message.ok) { - clearTimeout(timer); - port.disconnect(); - reject(new Error(message.error)); - return; - } - acknowledged = true; - finish(); - } - }); - port.postMessage(${JSON.stringify({ type: "saveCard", requestId, card })}); - })`); -} - -function inspectVault(client, sessionId) { - return evaluate(client, sessionId, `new Promise((resolve, reject) => { - const request = indexedDB.open("understudy-payment-card-vault", 2); - request.onerror = () => reject(request.error); - request.onsuccess = () => { - const database = request.result; - const transaction = database.transaction(["keys", "cards", "metadata"], "readonly"); - const keyRequest = transaction.objectStore("keys").get("payment-card-key"); - const cardsRequest = transaction.objectStore("cards").getAll(); - const metadataRequest = transaction.objectStore("metadata").get("schema"); - transaction.onerror = () => reject(transaction.error); - transaction.oncomplete = () => { - const cards = cardsRequest.result; - resolve({ - databaseVersion: database.version, - metadataVersion: metadataRequest.result?.version, - hasKey: keyRequest.result?.key instanceof CryptoKey, - keyExtractable: keyRequest.result?.key?.extractable ?? null, - cards: cards.length, - ivBytes: cards[0]?.iv?.byteLength ?? null, - envelopes: cards.map(({id, alias, schemaVersion, purpose, iv, ciphertext}) => ({ - id, alias, schemaVersion, purpose, ivBytes: iv.byteLength, - ciphertextBytes: ciphertext.byteLength, - })), - }); - database.close(); - }; - }; - })`); -} - function assert(condition, message) { if (!condition) throw new Error(message); } diff --git a/apps/extension/src/core/delete-obsolete-database.test.ts b/apps/extension/src/core/delete-obsolete-database.test.ts new file mode 100644 index 0000000..b3aaf79 --- /dev/null +++ b/apps/extension/src/core/delete-obsolete-database.test.ts @@ -0,0 +1,46 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { deleteObsoleteDatabase } from "./delete-obsolete-database"; + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe("deleteObsoleteDatabase", () => { + it("requests deletion of exactly the obsolete database once", () => { + const deleteDatabase = vi.fn(() => ({})); + vi.stubGlobal("indexedDB", { deleteDatabase }); + + deleteObsoleteDatabase(); + + expect(deleteDatabase.mock.calls).toEqual([["understudy-payment-card-vault"]]); + }); + + it("logs a synchronous deletion failure without throwing into startup", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const deleteDatabase = vi.fn(() => { + throw new Error("IndexedDB unavailable"); + }); + vi.stubGlobal("indexedDB", { deleteDatabase }); + + deleteObsoleteDatabase(); + + expect(warn.mock.calls).toEqual([[expect.stringContaining("failed")]]); + }); + + it.each([ + ["onerror", "failed"], + ["onblocked", "blocked"], + ] as const)("handles %s without retrying on the same start", (handler, status) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const request: { onerror?: () => void; onblocked?: () => void } = {}; + const deleteDatabase = vi.fn(() => request); + vi.stubGlobal("indexedDB", { deleteDatabase }); + + deleteObsoleteDatabase(); + request[handler]?.(); + + expect(warn.mock.calls).toEqual([[expect.stringContaining(status)]]); + expect(deleteDatabase).toHaveBeenCalledOnce(); + }); +}); diff --git a/apps/extension/src/core/delete-obsolete-database.ts b/apps/extension/src/core/delete-obsolete-database.ts new file mode 100644 index 0000000..1454798 --- /dev/null +++ b/apps/extension/src/core/delete-obsolete-database.ts @@ -0,0 +1,19 @@ +export function deleteObsoleteDatabase(): Promise { + return new Promise((resolve) => { + const fail = () => { + console.warn("understudy: obsolete database deletion failed"); + resolve(); + }; + + try { + const request = indexedDB.deleteDatabase("understudy-payment-card-vault"); + request.onsuccess = () => resolve(); + request.onerror = fail; + request.onblocked = () => { + console.warn("understudy: obsolete database deletion blocked"); + }; + } catch { + fail(); + } + }); +} diff --git a/apps/extension/src/core/profile-client.test.ts b/apps/extension/src/core/profile-client.test.ts index a1a1f27..1039b8c 100644 --- a/apps/extension/src/core/profile-client.test.ts +++ b/apps/extension/src/core/profile-client.test.ts @@ -324,30 +324,6 @@ describe("ProfileClient generation fencing", () => { expect(FakeWebSocket.instances).toHaveLength(1); }); - it("sends neither hello nor heartbeat inventory while sensitive mode is active", async () => { - installBrowser(); - vi.stubGlobal("fetch", vi.fn(async () => ticketResponse())); - const client = new ProfileClient(); - const inventory = vi.spyOn(client.sessions, "controlInventory").mockReturnValue(null); - - await client.configure(CONFIG); - const first = FakeWebSocket.instances[0]; - first?.open(); - expect(first?.sent).toEqual([]); - expect(first?.closeCount).toBe(1); - - inventory.mockReturnValue({ assignments: [], ownedWindows: [] }); - await vi.advanceTimersByTimeAsync(500); - const second = FakeWebSocket.instances[1]; - second?.open(); - expect(second?.sent).toContainEqual(expect.objectContaining({ type: "device_hello" })); - - inventory.mockReturnValue(null); - const sentBeforeHeartbeat = second?.sent.length; - await vi.advanceTimersByTimeAsync(22_000); - expect(second?.sent).toHaveLength(sentBeforeHeartbeat ?? 0); - }); - it("treats permanent ticket errors and replacement close as terminal", async () => { installBrowser(); const fetchMock = vi @@ -1312,8 +1288,8 @@ describe("ProfileClient startup cleanup", () => { const hosting = FakeWebSocket.instances[0]; hosting?.open(); const closure = { - sessionId: "session-payment", - leaseId: "lease-payment", + sessionId: "session-closed", + leaseId: "lease-closed", leaseEpoch: 1, browserEpoch: EPOCH, }; diff --git a/apps/extension/src/core/profile-client.ts b/apps/extension/src/core/profile-client.ts index f72eb7a..8932acc 100644 --- a/apps/extension/src/core/profile-client.ts +++ b/apps/extension/src/core/profile-client.ts @@ -20,7 +20,6 @@ import { withRequestDeadline, } from "./request-deadline"; import { ReconnectingWs } from "./ws-client"; -import type { CardVault } from "../payment/card-vault"; const BROWSER_EPOCH_KEY = "understudy:browserEpoch"; const STAGED_CONFIG_KEY = "understudy:stagedProfile"; @@ -236,10 +235,6 @@ export class ProfileClient { ); } - paymentVault(): CardVault { - return this.sessions.paymentVault(); - } - configure(config: ProfileConfig): Promise { return this.configureWithTransition(config, false, false); } @@ -676,14 +671,6 @@ export class ProfileClient { }, onOpen: () => { if (!this.isPeerCurrent(attempt, peer)) return; - const inventory = this.sessions.controlInventory(); - if (inventory === null) { - peer.stop(); - if (this.control === peer) this.control = null; - if (this.controlAttempt === attempt) this.controlAttempt = null; - this.scheduleRetry(attempt); - return; - } this.ticketBackoffMs = TICKET_BACKOFF_BASE_MS; this.setStatus("connected"); if ( @@ -701,6 +688,7 @@ export class ProfileClient { return; } attempt.helloSent = true; + const inventory = this.sessions.controlInventory(); peer.send({ type: "device_hello", protocolVersion: PROTOCOL_VERSION, @@ -763,15 +751,13 @@ export class ProfileClient { } if (!attempt.helloSent) return null; const inventory = this.sessions.controlInventory(); - return inventory === null - ? null - : { - type: "heartbeat", - deviceId: config.deviceId, - browserEpoch: this.epoch, - assignments: inventory.assignments, - ownedWindows: inventory.ownedWindows, - }; + return { + type: "heartbeat", + deviceId: config.deviceId, + browserEpoch: this.epoch, + assignments: inventory.assignments, + ownedWindows: inventory.ownedWindows, + }; }, }, DEVICE_CONTROL_FRAME_MAX_BYTES, diff --git a/apps/extension/src/core/session-manager.test.ts b/apps/extension/src/core/session-manager.test.ts index ecb4212..cbf647d 100644 --- a/apps/extension/src/core/session-manager.test.ts +++ b/apps/extension/src/core/session-manager.test.ts @@ -1,6 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { SessionManager } from "./session-manager"; -import type { SessionRuntime } from "./session-runtime"; import { ownedWindowBootstrapUrl } from "./owned-window-marker"; const EPOCH = "browser-epoch-1"; @@ -979,7 +978,7 @@ describe("SessionManager cleanup ownership", () => { }); }); - it("withholds the complete control inventory while any assignment is sensitive", async () => { + it("releases a window marked sensitive without reattaching to it", async () => { const sessionState: Record = { "understudy:assignments": { version: 4, @@ -989,33 +988,6 @@ describe("SessionManager cleanup ownership", () => { vacatedLeases: [], }, }; - installBrowser( - sessionState, - async () => { - throw new Error("tab close failed"); - }, - async () => ({ id: ASSIGNMENT.tabId }), - ); - const manager = new SessionManager( - () => "https://service.example", - () => EPOCH, - ); - - await manager.restoreSameEpoch(); - - expect(manager.controlInventory()).toBeNull(); - }); - - it("keeps control inventory suppressed when the sensitive-state write fails", async () => { - const sessionState: Record = { - "understudy:assignments": { - version: 4, - assignments: [{ ...ASSIGNMENT, policyVersion: 1 }], - ownedWindows: [{ ...ASSIGNMENT }], - closedOutbox: [], - vacatedLeases: [], - }, - }; const fixture = installBrowser( sessionState, async () => { @@ -1027,62 +999,13 @@ describe("SessionManager cleanup ownership", () => { () => "https://service.example", () => EPOCH, ); - await manager.restoreSameEpoch(); - const runtime = ( - manager as unknown as { byLease: Map } - ).byLease.get(ASSIGNMENT.leaseId); - if (runtime === undefined) throw new Error("restored runtime missing"); - fixture.sessionSet.mockRejectedValueOnce(new Error("persist failed")); - - await expect(manager.enterSensitive(runtime)).rejects.toThrow("persist failed"); - - expect(manager.assignments()).toEqual([ - expect.objectContaining({ sensitive: true }), - ]); - expect(manager.controlInventory()).toBeNull(); - }); - it("persists release intent before closing a sensitive window", async () => { - const assignment = { ...ASSIGNMENT, policyVersion: 1 }; - const sessionState: Record = { - "understudy:assignments": { - version: 4, - assignments: [assignment], - ownedWindows: [assignment], - closedOutbox: [], - vacatedLeases: [], - }, - }; - const fixture = installBrowser( - sessionState, - async () => {}, - async (tabId) => ({ id: tabId }), - ); - const manager = new SessionManager( - () => "https://service.example", - () => EPOCH, - ); await manager.restoreSameEpoch(); - const runtime = ( - manager as unknown as { byLease: Map } - ).byLease.get(ASSIGNMENT.leaseId); - if (runtime === undefined) throw new Error("restored runtime missing"); - await manager.enterSensitive(runtime); - const generalCleanup = vi.spyOn(runtime, "beginCleanup"); - fixture.sessionSet.mockRejectedValueOnce(new Error("release checkpoint failed")); - - await expect(manager.prepareSensitiveComplete(runtime)).rejects.toThrow( - "release checkpoint failed", - ); - expect(runtime.assignment.cleanupIntent).toBe("release"); - expect(generalCleanup).not.toHaveBeenCalled(); - expect(fixture.windowRemove).not.toHaveBeenCalled(); - await manager.retryCleanup(); expect(fixture.windowRemove).toHaveBeenCalledWith(ASSIGNMENT.windowId); - expect(manager.assignments()).toEqual([]); - expect(manager.closureOutbox()).toEqual([ - expect.objectContaining({ leaseId: ASSIGNMENT.leaseId }), + expect(fixture.sendCommand).not.toHaveBeenCalled(); + expect(manager.assignments()).toEqual([ + expect.objectContaining({ cleanupIntent: "release" }), ]); }); }); diff --git a/apps/extension/src/core/session-manager.ts b/apps/extension/src/core/session-manager.ts index 8774bef..e45fdd0 100644 --- a/apps/extension/src/core/session-manager.ts +++ b/apps/extension/src/core/session-manager.ts @@ -1,8 +1,6 @@ import type { AssignmentInventory, OwnedWindow, TabInfo } from "@understudy/protocol"; import type { Browser } from "wxt/browser"; import { controlledTabInfo } from "../tabs"; -import { CardVault } from "../payment/card-vault"; -import { IndexedDbCardVaultStore } from "../payment/indexeddb-card-store"; import { ownedWindowBootstrapUrl, ownedWindowFromBootstrapUrl, @@ -79,7 +77,6 @@ export class SessionManager implements RuntimeHost { private vacated: ClosureRecord[] = []; private persistTail: Promise = Promise.resolve(); private mutationTail: Promise = Promise.resolve(); - private readonly cards = new CardVault(new IndexedDbCardVaultStore()); constructor( private readonly getServiceOrigin: () => string, @@ -94,10 +91,6 @@ export class SessionManager implements RuntimeHost { return this.getBrowserEpoch(); } - paymentVault(): CardVault { - return this.cards; - } - isCurrent(runtime: SessionRuntime): boolean { return ( runtime.assignment.browserEpoch === this.browserEpoch() && @@ -302,7 +295,6 @@ export class SessionManager implements RuntimeHost { if (!this.ownedWindowRegistry.some((owned) => sameOwnedWindow(raw, owned))) continue; const runtime = new SessionRuntime({ ...raw }, this); this.install(runtime); - if (raw.sensitive === true) runtime.beginCleanup("release"); restored.push(runtime); } // Checkpoint discovered markers before physical cleanup. If the worker is @@ -430,10 +422,7 @@ export class SessionManager implements RuntimeHost { controlInventory(): { assignments: AssignmentInventory[]; ownedWindows: OwnedWindow[]; - } | null { - if ([...this.byLease.values()].some((runtime) => runtime.assignment.sensitive === true)) { - return null; - } + } { return { assignments: this.inventory(), ownedWindows: this.ownedWindows(), @@ -533,48 +522,6 @@ export class SessionManager implements RuntimeHost { // URLs and titles are intentionally not persisted. } - async prepareSensitiveComplete(runtime: SessionRuntime): Promise { - if (!this.isCurrent(runtime)) return false; - runtime.beginSensitiveCompletion(); - await this.serializeMutation(() => this.persist()); - if (!(await runtime.closeSensitiveTab())) { - return false; - } - return this.mutateAndPersist(() => { - if (!this.isCurrent(runtime)) return false; - runtime.assignment.cleanupIntent = "release"; - this.enqueueClosure(runtime.assignment); - this.ownedWindowRegistry = this.ownedWindowRegistry.filter( - (owned) => !sameOwnedWindow(owned, runtime.assignment), - ); - return true; - }, Boolean); - } - - finalizeSensitiveComplete(runtime: SessionRuntime): Promise { - runtime.finishSensitive(); - return this.mutateAndPersist(() => { - if (!this.isCurrent(runtime)) return false; - this.uninstall(runtime); - return true; - }, Boolean).then(() => undefined); - } - - async abortSensitive(runtime: SessionRuntime): Promise { - if (!this.isCurrent(runtime)) return; - await this.cleanup(runtime, "release"); - } - - enterSensitive(runtime: SessionRuntime): Promise { - return this.serializeMutation(async () => { - if (!this.isCurrent(runtime)) throw new Error("session runtime is no longer current"); - runtime.assignment.sensitive = true; - // Persistence is the gate before decryption, but the in-memory suppression - // latch must fail closed until teardown confirms that the tab is gone. - await this.persist(); - }); - } - private install(runtime: SessionRuntime): void { this.bySession.set(runtime.sessionId, runtime); this.byLease.set(runtime.leaseId, runtime); @@ -980,11 +927,16 @@ function emptyManagerState(): PersistedManagerState { function parseManagedAssignments(values: unknown[]): ManagedAssignment[] { return values.flatMap((value) => { if (!isAssignmentShape(value)) return []; - const item = value as Omit & { + const { sensitive, ...item } = value as Omit & { policyVersion?: unknown; + sensitive?: true; }; + // A stored assignment from an earlier development build can flag a window with payment card input. return [{ ...item, + ...(sensitive === true && item.cleanupIntent !== "discard" + ? { cleanupIntent: "release" as const } + : {}), policyVersion: typeof item.policyVersion === "number" && Number.isInteger(item.policyVersion) && @@ -997,7 +949,7 @@ function parseManagedAssignments(values: unknown[]): ManagedAssignment[] { function isAssignmentShape(value: unknown): boolean { if (typeof value !== "object" || value === null) return false; - const item = value as Partial; + const item = value as Partial & { sensitive?: unknown }; return ( typeof item.sessionId === "string" && typeof item.leaseId === "string" && @@ -1099,7 +1051,6 @@ function restoreAssignment( snapshot: ManagedAssignment, ): void { delete target.cleanupIntent; - delete target.sensitive; Object.assign(target, cloneAssignment(snapshot)); } diff --git a/apps/extension/src/core/session-runtime.test.ts b/apps/extension/src/core/session-runtime.test.ts index f4c8a05..3d8f1a0 100644 --- a/apps/extension/src/core/session-runtime.test.ts +++ b/apps/extension/src/core/session-runtime.test.ts @@ -1,10 +1,6 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; -import type { Command, Event, SessionServerFrame } from "@understudy/protocol"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { SessionStorageArea } from "./dedupe"; import { SessionRuntime, type RuntimeAssignment, type RuntimeHost } from "./session-runtime"; -import type { CdpSession } from "../driver/cdp"; -import { CardVaultExpiredError } from "../payment/card-vault"; -import type { ValidatedPaymentCard } from "../payment/card-validation"; const ASSIGNMENT: RuntimeAssignment = { sessionId: "session-1", @@ -24,11 +20,6 @@ function host(): RuntimeHost & { onFenced: ReturnType } { isCurrent: () => true, onFenced: vi.fn(async () => {}), onTabChanged: vi.fn(async () => {}), - paymentVault: () => ({}) as ReturnType, - enterSensitive: vi.fn(async () => {}), - prepareSensitiveComplete: vi.fn(async () => true), - finalizeSensitiveComplete: vi.fn(async () => {}), - abortSensitive: vi.fn(async () => {}), }; } @@ -44,6 +35,9 @@ function stubBrowser( vi.stubGlobal("browser", { storage: { session: storage }, windows: { remove: vi.fn(remove), getAll }, + debugger: { sendCommand: vi.fn(async () => ({})) }, + runtime: { getManifest: () => ({ version: "0.1.0" }) }, + tabs: { get: vi.fn(async () => ({ active: true })) }, }); } @@ -52,74 +46,6 @@ afterEach(() => { vi.unstubAllGlobals(); }); -type SubmitCardCommand = Extract; - -function executeCard( - runtime: SessionRuntime, - command: Extract, - cdp: CdpSession, - deadlineAt = Date.now() + 10_000, -): Promise { - return ( - runtime as unknown as { - executeCardCommand( - command: Extract, - cdp: CdpSession, - deadlineAt: number, - ): Promise; - } - ).executeCardCommand(command, cdp, deadlineAt); -} - -const SUBMIT_CARD: SubmitCardCommand = { - type: "submit_card", - commandId: "card-command", - cardAlias: "work", - numberRef: "number", - expiry: { kind: "split", monthRef: "month", yearRef: "year" }, - cvvRef: "cvv", - cardholderNameRef: "name", - submitRef: "submit", -}; - -const STORED_CARD = { - alias: "work", - cardholderName: "Ada Lovelace", - pan: "4111111111111111", - expiryMonth: "12", - expiryYear: "2099", - cvv: "123", -} as ValidatedPaymentCard; - -function paymentHost(options: { - aliases?: string[]; - origins?: string[]; - read?: () => Promise; -} = {}): RuntimeHost & { enterSensitive: ReturnType } { - const runtimeHost = host(); - const enterSensitive = vi.fn(async (runtime: SessionRuntime) => { - runtime.assignment.sensitive = true; - }); - const read = options.read ?? vi.fn(async () => STORED_CARD); - return { - ...runtimeHost, - paymentVault: () => ({ - summary: vi.fn(async () => ({ - aliases: options.aliases ?? ["work"], - approvedOrigins: options.origins ?? ["https://example.com"], - })), - authorizePayment: vi.fn(async (alias: string, origin: string) => { - const card = await read(); - return card === null || alias !== "work" || origin !== "https://example.com" - ? null - : { alias, origin, revision: 0, card }; - }), - paymentAuthorizationStillValid: vi.fn(async () => true), - }), - enterSensitive, - }; -} - describe("SessionRuntime close fencing", () => { it("never downgrades release or discard cleanup ownership", () => { stubBrowser(async () => {}); @@ -156,7 +82,7 @@ describe("SessionRuntime close fencing", () => { await expect(closing).resolves.toBe(true); }); - it("uses one physical-window closure for concurrent sensitive teardown", async () => { + it("uses one physical-window closure for concurrent session cleanup", async () => { let confirmRemoval!: () => void; let markRemovalStarted!: () => void; const removalStarted = new Promise((resolve) => { @@ -172,9 +98,9 @@ describe("SessionRuntime close fencing", () => { stubBrowser(remove); const runtime = new SessionRuntime(ASSIGNMENT, host()); - const first = runtime.closeSensitiveTab(); + const first = runtime.close(true); await removalStarted; - const second = runtime.closeSensitiveTab(); + const second = runtime.close(true); expect(remove).toHaveBeenCalledOnce(); confirmRemoval(); @@ -268,10 +194,29 @@ describe("SessionRuntime dialog handling", () => { }); }); -describe("SessionRuntime payment boundary", () => { - it("returns preflight not-started results without entering sensitive teardown", async () => { +describe("SessionRuntime write journal", () => { + const journalKey = `understudy:journal:${ASSIGNMENT.sessionId}`; + const { leaseId, leaseEpoch, browserEpoch } = ASSIGNMENT; + const fence = { leaseId, leaseEpoch, browserEpoch }; + const clickCommand = { type: "click", commandId: "command-1", ref: "ref-1" } as const; + const attempt = { + ...fence, + attemptId: "attempt-1", + commandId: clickCommand.commandId, + requestFingerprint: "a".repeat(64), + }; + const event = { type: "action_result", commandId: "command-1", ok: true } as const; + const result = { + type: "command_result", + ...fence, + attemptId: "attempt-1", + commandId: "command-1", + event, + }; + + function stubWriteStorage() { const values: Record = {}; - const storage: SessionStorageArea = { + const storage = { get: vi.fn(async (key: string) => ({ [key]: values[key] })), set: vi.fn(async (items: Record) => { Object.assign(values, items); @@ -281,598 +226,116 @@ describe("SessionRuntime payment boundary", () => { }), }; stubBrowser(async () => {}, vi.fn(), storage); - const runtimeHost = paymentHost(); - const runtime = new SessionRuntime(ASSIGNMENT, runtimeHost); - const peerSend = vi.fn(() => true); - Object.assign(runtime, { - cdp: { - currentUrl: "https://example.com/checkout", - }, - peer: { send: peerSend }, - }); - const command = { ...SUBMIT_CARD, cvvRef: SUBMIT_CARD.numberRef }; - await runtime.journal.prepare({ - attemptId: "preflight-attempt", - commandId: command.commandId, - requestFingerprint: "c".repeat(64), - leaseId: ASSIGNMENT.leaseId, - leaseEpoch: ASSIGNMENT.leaseEpoch, - browserEpoch: ASSIGNMENT.browserEpoch, - }); + vi.stubGlobal("navigator", { userAgent: "test-browser" }); + return { storage, values }; + } - await ( - runtime as unknown as { - executeWrite(frame: Extract): Promise; - } - ).executeWrite({ + function createClickRuntime() { + const runtime = new SessionRuntime(ASSIGNMENT, host()); + const click = vi.fn(async (_commandId: string, _ref: string) => event); + const peerSend = vi.fn((_frame: unknown) => true); + Object.assign(runtime, { cdp: { click }, peer: { send: peerSend } }); + return { runtime, click, peerSend }; + } + + function writeGrant() { + return { type: "write_grant", - attemptId: "preflight-attempt", + ...fence, + attemptId: attempt.attemptId, deadlineAt: new Date(Date.now() + 10_000).toISOString(), - leaseId: ASSIGNMENT.leaseId, - leaseEpoch: ASSIGNMENT.leaseEpoch, - browserEpoch: ASSIGNMENT.browserEpoch, - command, - }); - - expect(runtimeHost.enterSensitive).not.toHaveBeenCalled(); - expect(runtimeHost.prepareSensitiveComplete).not.toHaveBeenCalled(); - expect(peerSend).toHaveBeenCalledWith( - expect.objectContaining({ - event: expect.objectContaining({ - type: "card_submission_result", - status: "not_started", - reason: "invalid_mapping", - }), - }), - ); - await expect(runtime.journal.get("preflight-attempt")).resolves.toMatchObject({ - state: "completed_unacked", - }); - }); - - it("updates internal navigation fences without emitting page data in sensitive mode", async () => { - stubBrowser(async () => {}); - const runtimeHost = paymentHost(); - const runtime = new SessionRuntime(ASSIGNMENT, runtimeHost); - const bumpGeneration = vi.fn(async () => 2); - const peerSend = vi.fn(); - const cdp = { - currentUrl: "https://example.com/checkout", - mainFrameId: "main", - markLoadStarted: vi.fn(), - bumpGeneration, - notifyLoadEventFired: vi.fn(), + command: clickCommand, }; - Object.assign(runtime, { - sensitive: true, - cdp, - peer: { send: peerSend }, - }); - - await runtime.onCdpEvent({ tabId: 7 }, "Page.frameNavigated", { - frame: { id: "main", url: "https://example.com/changed" }, - }); - - expect(cdp.currentUrl).toBe("https://example.com/changed"); - expect(bumpGeneration).toHaveBeenCalledOnce(); - expect(peerSend).not.toHaveBeenCalled(); - expect(runtimeHost.onTabChanged).not.toHaveBeenCalled(); - }); - - it("does not inspect AX mutation payloads or advance generation in sensitive mode", async () => { - stubBrowser(async () => {}); - const runtime = new SessionRuntime(ASSIGNMENT, paymentHost()); - const cdp = { - hasMeaningfulAccessibilityUpdate: vi.fn(() => true), - bumpGeneration: vi.fn(async () => 2), - }; - Object.assign(runtime, { sensitive: true, cdp }); - - await runtime.onCdpEvent( - { tabId: 7 }, - "Accessibility.nodesUpdated", - { nodes: [{ name: { value: "must not be read" } }] }, - ); + } - expect(cdp.hasMeaningfulAccessibilityUpdate).not.toHaveBeenCalled(); - expect(cdp.bumpGeneration).not.toHaveBeenCalled(); - }); - - it("rejects duplicate mappings, unapproved origins, and stale refs before sensitive mode", async () => { - stubBrowser(async () => {}); - const runtimeHost = paymentHost(); - const runtime = new SessionRuntime(ASSIGNMENT, runtimeHost); - const cdp = { - currentUrl: "https://example.com/checkout", - hasCurrentRefs: vi.fn(() => true), - preflightSensitiveRefs: vi.fn(async () => true), - } as unknown as CdpSession; - - await expect( - executeCard(runtime, { ...SUBMIT_CARD, cvvRef: SUBMIT_CARD.numberRef }, cdp), - ).resolves.toMatchObject({ status: "not_started", reason: "invalid_mapping" }); - await expect( - executeCard( - new SessionRuntime(ASSIGNMENT, paymentHost({ origins: ["https://other.example"] })), - SUBMIT_CARD, - cdp, - ), - ).resolves.toMatchObject({ status: "not_started", reason: "origin_not_approved" }); - await expect( - executeCard( - new SessionRuntime(ASSIGNMENT, paymentHost()), - SUBMIT_CARD, - { ...cdp, hasCurrentRefs: vi.fn(() => false) } as unknown as CdpSession, - ), - ).resolves.toMatchObject({ status: "not_started", reason: "stale_ref" }); - expect(runtimeHost.enterSensitive).not.toHaveBeenCalled(); + beforeEach(() => { + vi.useFakeTimers(); }); - it("enters sensitive mode before decrypting, fills split expiry, and stops observation", async () => { - const removed = vi.fn(async () => {}); - stubBrowser(removed); - const order: string[] = []; - const runtimeHost = paymentHost({ - read: vi.fn(async () => { - order.push("decrypt"); - return STORED_CARD; - }), + it("executes a granted click once and persists its result before replying", async () => { + const { values } = stubWriteStorage(); + const { runtime, click, peerSend } = createClickRuntime(); + let recordsAtClick: unknown; + let recordsAtReply: unknown; + click.mockImplementationOnce(async () => { + recordsAtClick = values[journalKey]; + return event; }); - runtimeHost.enterSensitive.mockImplementation(async () => { - order.push("sensitive"); - }); - const submitSensitiveFields = vi.fn( - async ( - fields: Array<{ ref: string; text: string }>, - submitRef: string, - expectedOrigin: string, - onBeforeInsert: () => void, - onBeforeSubmit: () => void, - ) => { - order.push("fill"); - expect(fields).toEqual([ - { ref: "name", text: "Ada Lovelace" }, - { ref: "number", text: "4111111111111111" }, - { ref: "month", text: "12" }, - { ref: "year", text: "2099" }, - { ref: "cvv", text: "123" }, - ]); - expect(submitRef).toBe("submit"); - expect(expectedOrigin).toBe("https://example.com"); - onBeforeInsert(); - onBeforeSubmit(); - return { - stale: false, - originMismatch: false, - cardBytesMayHaveBeenInserted: true, - submissionAttempted: true, - }; - }, - ); - const detach = vi.fn(async () => {}); - const cdp = { - currentUrl: "https://example.com/checkout", - hasCurrentRefs: vi.fn(() => true), - preflightSensitiveRefs: vi.fn(async () => true), - pinSensitiveOrigin: vi.fn(() => order.push("pin")), - stopPendingSensitiveNavigation: vi.fn(async () => { - order.push("stop-navigation"); - return true; - }), - submitSensitiveFields, - detach, - } as unknown as CdpSession; - - await expect( - executeCard(new SessionRuntime(ASSIGNMENT, runtimeHost), SUBMIT_CARD, cdp), - ).resolves.toEqual({ - type: "card_submission_result", - commandId: "card-command", - status: "outcome_unknown", - reason: "submission_attempted", + peerSend.mockImplementation(() => { + recordsAtReply = values[journalKey]; + return true; }); - expect(order).toEqual([ - "pin", - "sensitive", - "stop-navigation", - "decrypt", - "fill", - ]); - expect(detach).toHaveBeenCalledOnce(); - expect(removed).not.toHaveBeenCalled(); - }); + await runtime.journal.prepare(attempt); + const grant = writeGrant(); - it("closes the tab and never starts filling when the grant expires during decryption", async () => { - vi.useFakeTimers(); - const removed = vi.fn(async () => {}); - stubBrowser(removed); - let markReadStarted!: () => void; - const readStarted = new Promise((resolve) => { - markReadStarted = resolve; - }); - let releaseRead!: (card: typeof STORED_CARD) => void; - const pendingRead = new Promise((resolve) => { - releaseRead = resolve; - }); - const runtimeHost = paymentHost({ - read: vi.fn(() => { - markReadStarted(); - return pendingRead; - }), - }); - const submitSensitiveFields = vi.fn(); - const detach = vi.fn(async () => {}); - const cdp = { - currentUrl: "https://example.com/checkout", - hasCurrentRefs: vi.fn(() => true), - preflightSensitiveRefs: vi.fn(async () => true), - pinSensitiveOrigin: vi.fn(), - stopPendingSensitiveNavigation: vi.fn(async () => true), - submitSensitiveFields, - detach, - } as unknown as CdpSession; - const runtime = new SessionRuntime(ASSIGNMENT, runtimeHost); - const result = executeCard( - runtime, - SUBMIT_CARD, - cdp, - Date.now() + 100, - ); - await readStarted; - - await vi.advanceTimersByTimeAsync(100); - await expect(result).resolves.toEqual({ - type: "card_submission_result", - commandId: "card-command", - status: "not_started", - reason: "input_failed", - }); - expect(removed).toHaveBeenCalledWith(ASSIGNMENT.windowId); - await expect(runtime.closeSensitiveTab()).resolves.toBe(true); - expect(removed).toHaveBeenCalledOnce(); - expect(submitSensitiveFields).not.toHaveBeenCalled(); - - releaseRead(STORED_CARD); - await Promise.resolve(); - await Promise.resolve(); - expect(submitSensitiveFields).not.toHaveBeenCalled(); - expect(detach).toHaveBeenCalledOnce(); - expect(removed).toHaveBeenCalledOnce(); - }); + await runtime["onServerFrame"](grant); + await runtime["onServerFrame"](grant); - it("rejects a card that expires while its sensitive submission waits in the CDP queue", async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date("2026-08-31T23:59:59.999Z")); - stubBrowser(async () => {}); - const expiringCard = { - ...STORED_CARD, - expiryMonth: "08", - expiryYear: "2026", - } as ValidatedPaymentCard; - const cdp = { - currentUrl: "https://example.com/checkout", - hasCurrentRefs: vi.fn(() => true), - preflightSensitiveRefs: vi.fn(async () => true), - pinSensitiveOrigin: vi.fn(), - stopPendingSensitiveNavigation: vi.fn(async () => true), - submitSensitiveFields: vi.fn( - async ( - _fields: unknown, - _submitRef: string, - _expectedOrigin: string, - _onBeforeInsert: () => void, - _onBeforeSubmit: () => void, - canBeginInsertion: () => boolean | Promise, - ) => { - await vi.advanceTimersByTimeAsync(1); - await expect(canBeginInsertion()).resolves.toBe(false); - return { - stale: false, - originMismatch: false, - cardBytesMayHaveBeenInserted: false, - submissionAttempted: false, - insertionRefused: true as const, - }; - }, - ), - detach: vi.fn(async () => {}), - } as unknown as CdpSession; - - await expect( - executeCard( - new SessionRuntime( - ASSIGNMENT, - paymentHost({ read: vi.fn(async () => expiringCard) }), - ), - SUBMIT_CARD, - cdp, - ), - ).resolves.toMatchObject({ status: "not_started", reason: "card_not_found" }); + expect(click).toHaveBeenCalledOnce(); + expect(click).toHaveBeenCalledWith("command-1", "ref-1"); + expect(recordsAtClick).toEqual([{ ...attempt, state: "started" }]); + expect(recordsAtReply).toEqual([{ ...attempt, state: "completed_unacked", event }]); + expect(peerSend.mock.calls).toEqual([[result]]); }); - it("distinguishes failures before insertion from failures after insertion", async () => { - stubBrowser(async () => {}); - const before = { - currentUrl: "https://example.com/checkout", - hasCurrentRefs: vi.fn(() => true), - preflightSensitiveRefs: vi.fn(async () => true), - pinSensitiveOrigin: vi.fn(), - stopPendingSensitiveNavigation: vi.fn(async () => true), - submitSensitiveFields: vi.fn(async () => ({ - stale: false, - originMismatch: false, - cardBytesMayHaveBeenInserted: false, - submissionAttempted: false, - })), - detach: vi.fn(async () => {}), - } as unknown as CdpSession; - await expect( - executeCard(new SessionRuntime(ASSIGNMENT, paymentHost()), SUBMIT_CARD, before), - ).resolves.toMatchObject({ status: "not_started", reason: "input_failed" }); - vi.mocked(before.submitSensitiveFields).mockClear(); - await expect( - executeCard( - new SessionRuntime( - ASSIGNMENT, - paymentHost({ - read: vi.fn(async () => { - throw new CardVaultExpiredError("expired"); - }), - }), - ), - SUBMIT_CARD, - before, - ), - ).resolves.toMatchObject({ status: "not_started", reason: "card_not_found" }); - expect(before.submitSensitiveFields).not.toHaveBeenCalled(); - - const changedOrigin = { - ...before, - submitSensitiveFields: vi.fn(async () => ({ - stale: false, - originMismatch: true, - cardBytesMayHaveBeenInserted: false, - submissionAttempted: false, - })), - } as unknown as CdpSession; - await expect( - executeCard( - new SessionRuntime(ASSIGNMENT, paymentHost()), - SUBMIT_CARD, - changedOrigin, - ), - ).resolves.toMatchObject({ - status: "not_started", - reason: "origin_not_approved", - }); - - const after = { - currentUrl: "https://example.com/checkout", - hasCurrentRefs: vi.fn(() => true), - preflightSensitiveRefs: vi.fn(async () => true), - submitSensitiveFields: vi.fn( - async ( - _fields: unknown, - _submitRef: string, - _expectedOrigin: string, - onBeforeInsert: () => void, - ) => { - onBeforeInsert(); - throw new Error("page-derived synthetic marker"); - }, - ), - pinSensitiveOrigin: vi.fn(), - stopPendingSensitiveNavigation: vi.fn(async () => true), - detach: vi.fn(async () => {}), - } as unknown as CdpSession; - await expect( - executeCard(new SessionRuntime(ASSIGNMENT, paymentHost()), SUBMIT_CARD, after), - ).resolves.toEqual({ - type: "card_submission_result", - commandId: "card-command", - status: "outcome_unknown", - reason: "input_failed", + 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(); + click.mockImplementationOnce(async () => { + storage.set.mockRejectedValueOnce(new Error("journal persist failed")); + return event; }); - }); + await runtime.journal.prepare(attempt); - it("formats combined expiry without returning card data", async () => { - stubBrowser(async () => {}); - let fields: Array<{ ref: string; text: string }> = []; - const cdp = { - currentUrl: "https://example.com/checkout", - hasCurrentRefs: vi.fn(() => true), - preflightSensitiveRefs: vi.fn(async () => true), - pinSensitiveOrigin: vi.fn(), - stopPendingSensitiveNavigation: vi.fn(async () => true), - submitSensitiveFields: vi.fn(async (mapped: Array<{ ref: string; text: string }>) => { - fields = mapped; - return { - stale: false, - originMismatch: false, - cardBytesMayHaveBeenInserted: false, - submissionAttempted: false, - }; - }), - detach: vi.fn(async () => {}), - } as unknown as CdpSession; - const result = await executeCard( - new SessionRuntime(ASSIGNMENT, paymentHost()), - { - ...SUBMIT_CARD, - expiry: { kind: "combined", ref: "expiry" }, - cardholderNameRef: undefined, - }, - cdp, + await expect(runtime["onServerFrame"](writeGrant())).rejects.toThrow( + "journal persist failed", ); - expect(fields).toEqual([ - { ref: "number", text: "4111111111111111" }, - { ref: "expiry", text: "12/99" }, - { ref: "cvv", text: "123" }, - ]); - expect(JSON.stringify(result)).not.toContain("4111111111111111"); - expect(JSON.stringify(result)).not.toContain("123"); - }); - - it("persists the fixed result and closes the tab before replying", async () => { - const values: Record = {}; - const storage: SessionStorageArea = { - get: vi.fn(async (key: string) => ({ [key]: values[key] })), - set: vi.fn(async (items: Record) => { - Object.assign(values, items); - }), - remove: vi.fn(async (key: string) => { - delete values[key]; - }), - }; - const removed = vi.fn(async () => {}); - stubBrowser(removed, vi.fn(), storage); - const order: string[] = []; - const runtimeHost = paymentHost(); - runtimeHost.prepareSensitiveComplete = vi.fn(async (runtime: SessionRuntime) => { - expect((await runtime.journal.get("attempt-1"))?.state).toBe("completed_unacked"); - order.push("durable-cleanup"); - return runtime.closeSensitiveTab(); - }); - runtimeHost.finalizeSensitiveComplete = vi.fn(async () => { - order.push("finalize"); - }); - const runtime = new SessionRuntime(ASSIGNMENT, runtimeHost); - const peerSend = vi.fn(() => { - order.push("reply"); - return true; - }); - Object.assign(runtime, { - cdp: { - currentUrl: "https://example.com/checkout", - hasCurrentRefs: vi.fn(() => true), - preflightSensitiveRefs: vi.fn(async () => true), - pinSensitiveOrigin: vi.fn(), - stopPendingSensitiveNavigation: vi.fn(async () => true), - submitSensitiveFields: vi.fn( - async ( - _fields: unknown, - _submitRef: string, - _expectedOrigin: string, - onBeforeInsert: () => void, - onBeforeSubmit: () => void, - ) => { - onBeforeInsert(); - onBeforeSubmit(); - return { - stale: false, - originMismatch: false, - cardBytesMayHaveBeenInserted: true, - submissionAttempted: true, - }; - }, - ), - detach: vi.fn(async () => {}), - }, - peer: { send: peerSend }, - }); - await runtime.journal.prepare({ - attemptId: "attempt-1", - commandId: SUBMIT_CARD.commandId, - requestFingerprint: "a".repeat(64), - leaseId: ASSIGNMENT.leaseId, - leaseEpoch: ASSIGNMENT.leaseEpoch, - browserEpoch: ASSIGNMENT.browserEpoch, - }); - - await ( - runtime as unknown as { - executeWrite(frame: Extract): Promise; - } - ).executeWrite({ - type: "write_grant", - attemptId: "attempt-1", - deadlineAt: new Date(Date.now() + 10_000).toISOString(), - leaseId: ASSIGNMENT.leaseId, - leaseEpoch: ASSIGNMENT.leaseEpoch, - browserEpoch: ASSIGNMENT.browserEpoch, - command: SUBMIT_CARD, + expect(click).toHaveBeenCalledOnce(); + expect(peerSend).not.toHaveBeenCalled(); + expect(values[journalKey]).toEqual([{ ...attempt, state: "started" }]); + + const restored = createClickRuntime(); + await restored.runtime["onOpen"](); + const grant = writeGrant(); + await restored.runtime["onServerFrame"](grant); + await restored.runtime["onServerFrame"]({ + type: "write_prepare", + ...fence, + attemptId: "attempt-2", + commandId: "command-2", + commandType: "click", + deadlineAt: grant.deadlineAt, + requestFingerprint: "b".repeat(64), }); - expect(order).toEqual(["durable-cleanup", "reply", "finalize"]); - expect(removed).toHaveBeenCalledWith(ASSIGNMENT.windowId); - expect(peerSend).toHaveBeenCalledWith( - expect.objectContaining({ - event: expect.objectContaining({ - type: "card_submission_result", - status: "outcome_unknown", - }), - }), - ); + expect(values[journalKey]).toEqual([{ ...attempt, state: "unknown" }]); + expect(restored.click).not.toHaveBeenCalled(); + expect(restored.peerSend.mock.calls).toEqual([ + [expect.objectContaining({ type: "hello" })], + ]); }); - it("forces sensitive cleanup when fixed-result journaling fails", async () => { - const values: Record = {}; - const storage: SessionStorageArea = { - get: vi.fn(async (key: string) => ({ [key]: values[key] })), - set: vi.fn(async (items: Record) => { - const records = Object.values(items)[0]; - if ( - Array.isArray(records) && - records.some((record) => - typeof record === "object" && - record !== null && - (record as { state?: unknown }).state === "completed_unacked" - ) - ) { - throw new Error("journal persist failed"); - } - Object.assign(values, items); - }), - remove: vi.fn(async () => {}), - }; - stubBrowser(async () => {}, vi.fn(), storage); - const runtimeHost = paymentHost(); - const runtime = new SessionRuntime(ASSIGNMENT, runtimeHost); - const peerSend = vi.fn(); - Object.assign(runtime, { - cdp: { - currentUrl: "https://example.com/checkout", - hasCurrentRefs: vi.fn(() => true), - preflightSensitiveRefs: vi.fn(async () => true), - pinSensitiveOrigin: vi.fn(), - stopPendingSensitiveNavigation: vi.fn(async () => true), - submitSensitiveFields: vi.fn(async () => ({ - stale: false, - originMismatch: false, - cardBytesMayHaveBeenInserted: false, - submissionAttempted: false, - })), - detach: vi.fn(async () => {}), - }, - peer: { send: peerSend }, - }); - await runtime.journal.prepare({ - attemptId: "attempt-journal-failure", - commandId: SUBMIT_CARD.commandId, - requestFingerprint: "b".repeat(64), - leaseId: ASSIGNMENT.leaseId, - leaseEpoch: ASSIGNMENT.leaseEpoch, - browserEpoch: ASSIGNMENT.browserEpoch, - }); - - await ( - runtime as unknown as { - executeWrite(frame: Extract): Promise; - } - ).executeWrite({ - type: "write_grant", - attemptId: "attempt-journal-failure", - deadlineAt: new Date(Date.now() + 10_000).toISOString(), - leaseId: ASSIGNMENT.leaseId, - leaseEpoch: ASSIGNMENT.leaseEpoch, - browserEpoch: ASSIGNMENT.browserEpoch, - command: SUBMIT_CARD, + it("replays a completed click result on open without executing the click", async () => { + stubWriteStorage(); + const previous = new SessionRuntime(ASSIGNMENT, host()); + await previous.journal.prepare(attempt); + await previous.journal.markStarted(attempt.attemptId); + await previous.journal.markCompleted(attempt.attemptId, event); + const { runtime, click, peerSend } = createClickRuntime(); + + await runtime["onOpen"](); + + const hello = expect.objectContaining({ type: "hello" }); + expect(peerSend.mock.calls).toEqual([[hello], [result]]); + peerSend.mockClear(); + await runtime["onServerFrame"]({ + type: "result_ack", + attemptId: attempt.attemptId, + commandId: clickCommand.commandId, }); + await runtime["onOpen"](); - expect(runtimeHost.abortSensitive).toHaveBeenCalledWith(runtime); - expect(peerSend).not.toHaveBeenCalled(); - await expect(runtime.journal.get("attempt-journal-failure")).resolves.toMatchObject({ - state: "unknown", - }); + expect(peerSend.mock.calls).toEqual([[hello]]); + expect(click).not.toHaveBeenCalled(); }); }); diff --git a/apps/extension/src/core/session-runtime.ts b/apps/extension/src/core/session-runtime.ts index d4e0a09..68a8a71 100644 --- a/apps/extension/src/core/session-runtime.ts +++ b/apps/extension/src/core/session-runtime.ts @@ -16,11 +16,6 @@ import { DialogOutbox, handleDialogWithOutbox } from "./dialog-outbox"; import { CdpSession } from "../driver/cdp"; import { classifyCdpEvent, type CdpDecision } from "../driver/cdp-events"; import { controlledTabInfo } from "../tabs"; -import { CardVaultExpiredError, type CardVault } from "../payment/card-vault"; -import { - storedPaymentCardExpired, - type ValidatedPaymentCard, -} from "../payment/card-validation"; import { closeWindowAndConfirm } from "./window-lifecycle"; export interface RuntimeAssignment { @@ -36,14 +31,8 @@ export interface RuntimeAssignment { export type CleanupIntent = "recover" | "release" | "discard"; -export type PaymentVaultAccess = Pick< - CardVault, - "summary" | "authorizePayment" | "paymentAuthorizationStillValid" ->; - export interface ManagedAssignment extends RuntimeAssignment { cleanupIntent?: CleanupIntent; - sensitive?: boolean; } export interface RuntimeHost { @@ -52,11 +41,6 @@ export interface RuntimeHost { isCurrent(runtime: SessionRuntime): boolean; onFenced(runtime: SessionRuntime): Promise; onTabChanged(runtime: SessionRuntime): Promise; - paymentVault(): PaymentVaultAccess; - enterSensitive(runtime: SessionRuntime): Promise; - prepareSensitiveComplete(runtime: SessionRuntime): Promise; - finalizeSensitiveComplete(runtime: SessionRuntime): Promise; - abortSensitive(runtime: SessionRuntime): Promise; } export class SessionRuntime { @@ -67,7 +51,6 @@ export class SessionRuntime { private accepting: boolean; private writesBlocked = false; private closing = false; - private sensitive = false; private windowClosure: Promise | null = null; constructor( @@ -184,13 +167,6 @@ export class SessionRuntime { return closed; } - async closeSensitiveTab(): Promise { - const cdp = this.cdp; - this.cdp = null; - await cdp?.detach().catch(() => {}); - return this.closeOwnedWindow(); - } - private closeOwnedWindow(): Promise { if (this.windowClosure !== null) return this.windowClosure; const closure = closeWindowAndConfirm(this.assignment.windowId); @@ -206,25 +182,6 @@ export class SessionRuntime { return closure; } - finishSensitive(): void { - this.accepting = false; - this.closing = true; - this.peer?.stop(); - this.peer = null; - } - - beginSensitiveCompletion(): void { - if (this.assignment.sensitive !== true || !this.accepting || this.closing) { - throw new Error("sensitive completion is not active"); - } - // The release fence must survive worker eviction before tab closure, while - // the socket remains alive long enough to emit the one fixed result. - this.assignment.cleanupIntent = mergeCleanupIntent( - this.assignment.cleanupIntent, - "release", - ); - } - beginCleanup(intent: CleanupIntent): void { this.assignment.cleanupIntent = mergeCleanupIntent( this.assignment.cleanupIntent, @@ -256,10 +213,7 @@ export class SessionRuntime { return; } if (method === "Accessibility.nodesUpdated") { - if ( - !this.sensitive && - cdp.hasMeaningfulAccessibilityUpdate(params, source.sessionId) - ) { + if (cdp.hasMeaningfulAccessibilityUpdate(params, source.sessionId)) { await cdp.bumpGeneration(true); } return; @@ -270,14 +224,6 @@ export class SessionRuntime { isRootSession: source.sessionId === undefined, }); await this.applyCdpDecision(cdp, decision); - if (this.sensitive) { - if (decision.dialog !== undefined) { - await cdp.send("Page.handleJavaScriptDialog", { - accept: decision.dialog.accept, - }).catch(() => {}); - } - return; - } if (!this.host.isCurrent(this)) return; if (decision.pageEvent !== undefined) { this.send({ @@ -330,7 +276,7 @@ export class SessionRuntime { async onDebuggerDetach(): Promise { this.cdp = null; - if (this.closing || this.sensitive) return; + if (this.closing) return; this.accepting = false; this.peer?.stop(); this.peer = null; @@ -439,7 +385,7 @@ export class SessionRuntime { frame: Extract, ): Promise { const event = await this.executeWithDeadline(frame.command, deadline(frame.deadlineAt)); - if (event !== null && this.canReply()) { + if (event !== null && this.canAccept()) { this.send({ type: "command_result", attemptId: frame.attemptId, @@ -473,48 +419,20 @@ export class SessionRuntime { await this.journal.markStarted(frame.attemptId); if (!this.canAccept()) return; const event = await this.executeWithDeadline(frame.command, deadline(frame.deadlineAt)); - const sensitivePayment = - frame.command.type === "submit_card" && this.assignment.sensitive === true; - if (event === null || !(sensitivePayment ? this.canReply() : this.canAccept())) { + if (event === null || !this.canAccept()) { await this.journal.markUnknown(frame.attemptId); this.writesBlocked = true; return; } - if (!sensitivePayment) { - 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, - }); - return; - } - let finalized = false; - try { - await this.journal.markCompleted(frame.attemptId, event); - if (!this.canReply() || !(await this.host.prepareSensitiveComplete(this))) return; - this.send({ - type: "command_result", - attemptId: frame.attemptId, - commandId: frame.command.commandId, - ...this.resultFence(), - event, - }); - await this.host.finalizeSensitiveComplete(this); - finalized = true; - } catch { - // Sensitive failures are represented only by durable journal state and - // cleanup; neither extension/storage errors nor page data cross the wire. - } finally { - if (!finalized) { - await this.journal.markUnknown(frame.attemptId).catch(() => {}); - this.writesBlocked = true; - await this.host.abortSensitive(this).catch(() => {}); - } - } + 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( @@ -532,17 +450,11 @@ export class SessionRuntime { } const remaining = deadlineAt - Date.now(); if (remaining <= 0) return null; - if (command.type === "submit_card") { - return this.executeCardCommand(command, cdp, deadlineAt); - } let timer: ReturnType; const timedOut = new Promise((resolve) => { timer = setTimeout(() => resolve(null), remaining); }); - const execution = command.type === "list_cards" - ? this.executeCardCommand(command, cdp, deadlineAt) - : routeCommand(command, cdp); - const event = await Promise.race([execution, timedOut]); + const event = await Promise.race([routeCommand(command, cdp), timedOut]); clearTimeout(timer!); if (event !== null) return event; await cdp.detach().catch(() => {}); @@ -580,10 +492,6 @@ export class SessionRuntime { } private canAccept(): boolean { - return this.canReply() && !this.sensitive; - } - - private canReply(): boolean { return ( this.accepting && !this.closing && @@ -592,174 +500,6 @@ export class SessionRuntime { ); } - private async executeCardCommand( - command: Extract, - cdp: CdpSession, - deadlineAt: number, - ): Promise { - const vault = this.host.paymentVault(); - if (command.type === "list_cards") { - try { - const summary = await vault.summary(); - return { type: "cards_result", commandId: command.commandId, ...summary }; - } catch { - return { - type: "cards_result", - commandId: command.commandId, - aliases: [], - approvedOrigins: [], - }; - } - } - - const remainingAtStart = deadlineAt - Date.now(); - if (remainingAtStart <= 0) { - return cardResult(command.commandId, "not_started", "input_failed"); - } - let deadlineExpired = false; - let bytesMayHaveBeenInserted = false; - let submissionAttempted = false; - const expired = () => deadlineExpired || Date.now() >= deadlineAt; - const deadlineResult = () => - cardResult( - command.commandId, - bytesMayHaveBeenInserted ? "outcome_unknown" : "not_started", - submissionAttempted ? "submission_attempted" : "input_failed", - ); - let deadlineOutcome: Promise | null = null; - const expirePayment = (): Promise => { - deadlineExpired = true; - if (deadlineOutcome !== null) return deadlineOutcome; - const wasSensitive = this.sensitive; - deadlineOutcome = this.closeSensitiveTab().then((closed) => { - if (wasSensitive && !closed) bytesMayHaveBeenInserted = true; - return deadlineResult(); - }); - return deadlineOutcome; - }; - - const execution = (async (): Promise => { - const refs = paymentRefs(command); - if (new Set(refs).size !== refs.length) { - return cardResult(command.commandId, "not_started", "invalid_mapping"); - } - let origin: string; - try { - origin = new URL(cdp.currentUrl).origin; - } catch { - return cardResult(command.commandId, "not_started", "origin_not_approved"); - } - let summary; - try { - summary = await vault.summary(); - } catch { - return expired() - ? expirePayment() - : cardResult(command.commandId, "not_started", "card_not_found"); - } - if (expired()) return expirePayment(); - if (!summary.aliases.includes(command.cardAlias)) { - return cardResult(command.commandId, "not_started", "card_not_found"); - } - if ( - !this.assignment.allowedOrigins.includes(origin) || - !summary.approvedOrigins.includes(origin) - ) { - return cardResult(command.commandId, "not_started", "origin_not_approved"); - } - if (!cdp.hasCurrentRefs(refs)) { - return cardResult(command.commandId, "not_started", "stale_ref"); - } - if (expired()) return expirePayment(); - if ( - !(await cdp.preflightSensitiveRefs( - paymentFieldRefs(command), - command.submitRef, - )) - ) { - return cardResult(command.commandId, "not_started", "stale_ref"); - } - if (expired()) return expirePayment(); - - cdp.pinSensitiveOrigin(origin); - this.sensitive = true; - try { - await this.host.enterSensitive(this); - if (expired()) return expirePayment(); - if (!(await cdp.stopPendingSensitiveNavigation(origin))) { - return expired() - ? expirePayment() - : cardResult(command.commandId, "not_started", "origin_not_approved"); - } - if (expired()) return expirePayment(); - let authorization; - try { - authorization = await vault.authorizePayment(command.cardAlias, origin); - } catch (error) { - if (expired()) return expirePayment(); - if (error instanceof CardVaultExpiredError) { - return cardResult(command.commandId, "not_started", "card_not_found"); - } - throw error; - } - if (expired()) return expirePayment(); - if (authorization === null) { - return cardResult(command.commandId, "not_started", "card_not_found"); - } - const card = authorization.card; - const fields = paymentFields(command, card); - if (expired()) return expirePayment(); - const result = await cdp.submitSensitiveFields( - fields, - command.submitRef, - origin, - () => { - bytesMayHaveBeenInserted = true; - }, - () => { - submissionAttempted = true; - }, - async () => - !storedPaymentCardExpired(card.expiryMonth, card.expiryYear) && - (await vault.paymentAuthorizationStillValid(authorization)), - ); - bytesMayHaveBeenInserted ||= result.cardBytesMayHaveBeenInserted; - submissionAttempted ||= result.submissionAttempted; - if (expired()) return expirePayment(); - if (result.insertionRefused === true) { - return cardResult(command.commandId, "not_started", "card_not_found"); - } - if (result.originMismatch) { - return cardResult(command.commandId, "not_started", "origin_not_approved"); - } - if (result.stale) { - return cardResult(command.commandId, "not_started", "stale_ref"); - } - if (submissionAttempted) { - return cardResult(command.commandId, "outcome_unknown", "submission_attempted"); - } - return cardResult( - command.commandId, - bytesMayHaveBeenInserted ? "outcome_unknown" : "not_started", - "input_failed", - ); - } catch { - return expired() ? expirePayment() : deadlineResult(); - } finally { - await cdp.detach().catch(() => {}); - this.cdp = null; - } - })(); - - let timer!: ReturnType; - const timedOut = new Promise((resolve) => { - timer = setTimeout(() => { - void expirePayment().then(resolve); - }, remainingAtStart); - }); - return Promise.race([execution, timedOut]).finally(() => clearTimeout(timer)); - } - private send(frame: unknown): void { this.peer?.send(frame); } @@ -777,58 +517,3 @@ function mergeCleanupIntent( function deadline(value: string): number { return Date.parse(value); } - -function paymentRefs(command: Extract): string[] { - return [...paymentFieldRefs(command), command.submitRef]; -} - -function paymentFieldRefs( - command: Extract, -): string[] { - return [ - command.numberRef, - ...(command.expiry.kind === "combined" - ? [command.expiry.ref] - : [command.expiry.monthRef, command.expiry.yearRef]), - command.cvvRef, - ...(command.cardholderNameRef === undefined ? [] : [command.cardholderNameRef]), - ]; -} - -function paymentFields( - command: Extract, - card: ValidatedPaymentCard, -): Array<{ ref: string; text: string }> { - return [ - ...(command.cardholderNameRef === undefined - ? [] - : [{ ref: command.cardholderNameRef, text: card.cardholderName }]), - { ref: command.numberRef, text: card.pan }, - ...(command.expiry.kind === "combined" - ? [ - { - ref: command.expiry.ref, - text: `${card.expiryMonth}/${card.expiryYear.slice(-2)}`, - }, - ] - : [ - { ref: command.expiry.monthRef, text: card.expiryMonth }, - { ref: command.expiry.yearRef, text: card.expiryYear }, - ]), - { ref: command.cvvRef, text: card.cvv }, - ]; -} - -function cardResult( - commandId: string, - status: "not_started" | "outcome_unknown", - reason: - | "card_not_found" - | "origin_not_approved" - | "stale_ref" - | "invalid_mapping" - | "input_failed" - | "submission_attempted", -): Event { - return { type: "card_submission_result", commandId, status, reason }; -} diff --git a/apps/extension/src/core/write-journal.test.ts b/apps/extension/src/core/write-journal.test.ts index 0994f44..fcbd749 100644 --- a/apps/extension/src/core/write-journal.test.ts +++ b/apps/extension/src/core/write-journal.test.ts @@ -108,30 +108,44 @@ describe("WriteJournal", () => { expect(JSON.stringify(storage.values)).not.toContain("prior-url.example"); }); - it("persists only the fixed payment result after a sensitive write", async () => { + it("excludes obsolete completed results from recovery while retaining current records", async () => { const storage = new MemoryStorage(); + const prepared = { ...PREPARED, state: "prepared" }; + const started = { + ...PREPARED, + attemptId: "attempt-2", + commandId: "command-2", + state: "started", + }; + const unknown = { + ...PREPARED, + attemptId: "attempt-3", + commandId: "command-3", + state: "unknown", + }; + const completed = { + ...PREPARED, + attemptId: "attempt-4", + commandId: "command-4", + state: "completed_unacked", + event: { type: "action_result", commandId: "command-4", ok: true }, + }; + const obsolete = { + ...PREPARED, + attemptId: "attempt-5", + commandId: "command-5", + attachmentId: "attachment-1", + state: "completed_unacked", + event: { + type: "card_submission_result", + commandId: "command-5", + status: "outcome_unknown", + reason: "submission_attempted", + }, + }; + storage.values.journal = [prepared, started, obsolete, unknown, completed]; const journal = new WriteJournal(storage, "journal"); - await journal.prepare({ ...PREPARED, attachmentId: "attachment-1" }); - await journal.markStarted(PREPARED.attemptId); - await journal.markCompleted(PREPARED.attemptId, { - type: "card_submission_result", - commandId: PREPARED.commandId, - status: "outcome_unknown", - reason: "submission_attempted", - }); - expect(await journal.recover()).toEqual([ - { - ...PREPARED, - attachmentId: "attachment-1", - state: "completed_unacked", - event: { - type: "card_submission_result", - commandId: PREPARED.commandId, - status: "outcome_unknown", - reason: "submission_attempted", - }, - }, - ]); + expect(await journal.recover()).toEqual([prepared, started, unknown, completed]); }); }); diff --git a/apps/extension/src/core/write-journal.ts b/apps/extension/src/core/write-journal.ts index 2883bb7..d9f2dc3 100644 --- a/apps/extension/src/core/write-journal.ts +++ b/apps/extension/src/core/write-journal.ts @@ -136,7 +136,13 @@ export class WriteJournal { if (this.records !== null) return; const stored = await this.storage.get(this.storageKey); const value = stored[this.storageKey]; - this.records = Array.isArray(value) ? (value as WriteJournalRecord[]) : []; + this.records = Array.isArray(value) + ? (value as WriteJournalRecord[]).filter( + (record) => + record.state !== "completed_unacked" || + record.event?.type === "action_result", + ) + : []; } private async persist(records: WriteJournalRecord[]): Promise { @@ -146,14 +152,6 @@ export class WriteJournal { } function journalSafeEvent(event: Event): Event { - if (event.type === "card_submission_result") { - return { - type: "card_submission_result", - commandId: event.commandId, - status: event.status, - reason: event.reason, - }; - } if (event.type !== "action_result") throw new Error("unsupported write result"); return { type: "action_result", diff --git a/apps/extension/src/driver/cdp.test.ts b/apps/extension/src/driver/cdp.test.ts index 98a00eb..61addab 100644 --- a/apps/extension/src/driver/cdp.test.ts +++ b/apps/extension/src/driver/cdp.test.ts @@ -688,283 +688,6 @@ describe("CdpSession keyboard dispatch", () => { }); }); -describe("CdpSession sensitive payment submission", () => { - it("prevalidates every ref before issuing any CDP command", async () => { - const sendCommand = stubActionBrowser(); - const session = await CdpSession.create(7, TEST_SCOPE); - seedTestRefs(session, [[testRef(0, 1), 41]]); - - await expect( - session.submitSensitiveFields( - [ - { ref: testRef(0, 1), text: "4111111111111111" }, - { ref: testRef(0, 2), text: "123" }, - ], - testRef(0, 3), - "https://approved.example", - vi.fn(), - vi.fn(), - ), - ).resolves.toEqual({ - stale: true, - originMismatch: false, - cardBytesMayHaveBeenInserted: false, - submissionAttempted: false, - }); - expect(sendCommand).not.toHaveBeenCalled(); - }); - - it("fills all mapped fields and invokes submit without reading the page afterward", async () => { - const sendCommand = stubActionBrowser(); - sendCommand.mockImplementation((_target, method: string) => { - if (method === "Page.getFrameTree") { - return Promise.resolve({ - frameTree: { - frame: { - id: "main", - loaderId: "loader", - url: "https://approved.example/checkout", - }, - }, - }); - } - if (method === "DOM.getBoxModel") { - return Promise.resolve({ model: { content: [0, 0, 10, 0, 10, 10, 0, 10] } }); - } - return Promise.resolve({}); - }); - const session = await CdpSession.create(7, TEST_SCOPE); - seedTestRefs(session, [ - [testRef(0, 1), 41], - [testRef(0, 2), 42], - [testRef(0, 3), 43], - ]); - const beforeInsert = vi.fn(); - const beforeSubmit = vi.fn(); - - await expect( - session.submitSensitiveFields( - [ - { ref: testRef(0, 1), text: "4111111111111111" }, - { ref: testRef(0, 2), text: "123" }, - ], - testRef(0, 3), - "https://approved.example", - beforeInsert, - beforeSubmit, - ), - ).resolves.toEqual({ - stale: false, - originMismatch: false, - cardBytesMayHaveBeenInserted: true, - submissionAttempted: true, - }); - expect(beforeInsert).toHaveBeenCalledTimes(2); - expect(beforeSubmit).toHaveBeenCalledOnce(); - expect( - sendCommand.mock.calls.filter((call) => call[1] === "Input.insertText").map((call) => call[2]), - ).toEqual([ - { text: "4111111111111111" }, - { text: "123" }, - ]); - expect( - sendCommand.mock.calls.some((call) => - ["Accessibility.getFullAXTree", "Page.captureScreenshot", "Runtime.evaluate"].includes( - call[1] as string, - ), - ), - ).toBe(false); - }); - - it("rechecks use-time eligibility inside the queue before the first insertion", async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date("2026-08-31T23:59:59.999Z")); - let releaseBlocker!: () => void; - let blocked = false; - const sendCommand = vi.fn().mockImplementation((_target, method: string, params) => { - if (method === "DOM.focus" && !blocked) { - blocked = true; - return new Promise((resolve) => { - releaseBlocker = resolve; - }); - } - if (method === "Page.getFrameTree") { - return Promise.resolve({ - frameTree: { - frame: { - id: "main", - loaderId: "loader", - url: "https://approved.example/checkout", - }, - }, - }); - } - return Promise.resolve(liveRefResponse(method, params)); - }); - vi.stubGlobal("browser", { - storage: { - session: { - get: vi.fn().mockResolvedValue({}), - set: vi.fn().mockResolvedValue(undefined), - }, - }, - debugger: { sendCommand }, - }); - const session = await CdpSession.create(7, TEST_SCOPE); - seedTestRefs(session, [ - [testRef(0, 1), 41], - [testRef(0, 2), 42], - [testRef(0, 3), 43], - ]); - const blocker = session.type("queue-blocker", testRef(0, 1), "not-card-data"); - await vi.waitFor(() => expect(blocked).toBe(true)); - const submission = session.submitSensitiveFields( - [{ ref: testRef(0, 2), text: "synthetic marker" }], - testRef(0, 3), - "https://approved.example", - vi.fn(), - vi.fn(), - () => new Date().getUTCMonth() === 7, - ); - - await vi.advanceTimersByTimeAsync(1); - releaseBlocker(); - await blocker; - - await expect(submission).resolves.toEqual({ - stale: false, - originMismatch: false, - cardBytesMayHaveBeenInserted: false, - submissionAttempted: false, - insertionRefused: true, - }); - expect( - sendCommand.mock.calls - .filter((call) => call[1] === "Input.insertText") - .map((call) => call[2]), - ).toEqual([{ text: "not-card-data" }]); - }); - - it("returns a fixed insertion-unknown signal when CDP fails during input", async () => { - const sendCommand = stubActionBrowser(); - sendCommand.mockImplementation((_target, method: string) => { - if (method === "Page.getFrameTree") { - return Promise.resolve({ - frameTree: { - frame: { - id: "main", - loaderId: "loader", - url: "https://approved.example/checkout", - }, - }, - }); - } - if (method === "Input.insertText") return Promise.reject(new Error("synthetic marker")); - return Promise.resolve({}); - }); - const session = await CdpSession.create(7, TEST_SCOPE); - seedTestRefs(session, [ - [testRef(0, 1), 41], - [testRef(0, 2), 42], - ]); - - await expect( - session.submitSensitiveFields( - [{ ref: testRef(0, 1), text: "synthetic marker" }], - testRef(0, 2), - "https://approved.example", - vi.fn(), - vi.fn(), - ), - ).resolves.toEqual({ - stale: false, - originMismatch: false, - cardBytesMayHaveBeenInserted: true, - submissionAttempted: false, - }); - }); - - it("refuses insertion when the live top-level origin changed after approval", async () => { - const sendCommand = stubActionBrowser(); - sendCommand.mockImplementation((_target, method: string) => { - if (method === "Page.getFrameTree") { - return Promise.resolve({ - frameTree: { - frame: { - id: "main", - loaderId: "loader", - url: "https://other.example/checkout", - }, - }, - }); - } - return Promise.resolve({}); - }); - const session = await CdpSession.create(7, TEST_SCOPE); - seedTestRefs(session, [ - [testRef(0, 1), 41], - [testRef(0, 2), 42], - ]); - - await expect( - session.submitSensitiveFields( - [{ ref: testRef(0, 1), text: "synthetic marker" }], - testRef(0, 2), - "https://approved.example", - vi.fn(), - vi.fn(), - ), - ).resolves.toEqual({ - stale: false, - originMismatch: true, - cardBytesMayHaveBeenInserted: false, - submissionAttempted: false, - }); - expect(sendCommand.mock.calls.some((call) => call[1] === "Input.insertText")).toBe(false); - }); - - it("invalidates a sensitive fill when navigation changes its ref generation", async () => { - const sendCommand = stubActionBrowser(); - let session!: CdpSession; - sendCommand.mockImplementation((_target, method: string) => { - if (method === "Page.getFrameTree") { - return Promise.resolve({ - frameTree: { - frame: { - id: "main", - loaderId: "loader", - url: "https://approved.example/checkout", - }, - }, - }); - } - if (method === "DOM.focus") void session.bumpGeneration(); - return Promise.resolve({}); - }); - session = await CdpSession.create(7, TEST_SCOPE); - seedTestRefs(session, [ - [testRef(0, 1), 41], - [testRef(0, 2), 42], - ]); - - await expect( - session.submitSensitiveFields( - [{ ref: testRef(0, 1), text: "synthetic marker" }], - testRef(0, 2), - "https://approved.example", - vi.fn(), - vi.fn(), - ), - ).resolves.toEqual({ - stale: true, - originMismatch: false, - cardBytesMayHaveBeenInserted: false, - submissionAttempted: false, - }); - expect(sendCommand.mock.calls.some((call) => call[1] === "Input.insertText")).toBe(false); - }); -}); - describe("CdpSession snapshot target identity", () => { function stubSnapshotBrowser( sendCommand: ReturnType, @@ -1500,74 +1223,6 @@ describe("CdpSession unattended containment", () => { ]); }); - it("blocks navigation from the approved payment origin to another session-approved origin", async () => { - const { session, sendCommand } = await containmentSession(); - session.mainFrameId = "main-frame"; - await session.enableUnattendedContainment([ - "https://approved.example", - "https://other.example", - ]); - session.pinSensitiveOrigin("https://approved.example"); - - await session.handleFetchRequestPaused({ - requestId: "payment-redirect", - request: { url: "https://other.example/submit" }, - frameId: "main-frame", - resourceType: "Document", - }); - - expect(sendCommand.mock.calls).toContainEqual([ - { tabId: 7 }, - "Fetch.failRequest", - { requestId: "payment-redirect", errorReason: "BlockedByClient" }, - ]); - }); - - it("stops an already-continued navigation and blocks all new navigation until submission", async () => { - const { session, sendCommand } = await containmentSession(); - session.mainFrameId = "main-frame"; - await session.enableUnattendedContainment(["https://approved.example"]); - session.pinSensitiveOrigin("https://approved.example"); - sendCommand.mockImplementation((_target, method: string) => { - if (method === "Page.getFrameTree") { - return Promise.resolve({ - frameTree: { - frame: { - id: "main-frame", - loaderId: "loader", - url: "https://approved.example/checkout", - }, - }, - }); - } - return Promise.resolve({}); - }); - - await expect( - session.stopPendingSensitiveNavigation("https://approved.example"), - ).resolves.toBe(true); - await session.handleFetchRequestPaused({ - requestId: "same-origin-before-submit", - request: { url: "https://approved.example/redirect" }, - frameId: "main-frame", - resourceType: "Document", - }); - - expect(sendCommand.mock.calls).toContainEqual([ - { tabId: 7 }, - "Page.stopLoading", - undefined, - ]); - expect(sendCommand.mock.calls).toContainEqual([ - { tabId: 7 }, - "Fetch.failRequest", - { - requestId: "same-origin-before-submit", - errorReason: "BlockedByClient", - }, - ]); - }); - it("closes a paused related page target before resuming it", async () => { const { session, sendCommand } = await containmentSession(); diff --git a/apps/extension/src/driver/cdp.ts b/apps/extension/src/driver/cdp.ts index 1a1a87f..24bd54c 100644 --- a/apps/extension/src/driver/cdp.ts +++ b/apps/extension/src/driver/cdp.ts @@ -214,8 +214,6 @@ export class CdpSession { // in order instead of racing to overwrite browser.storage.session. private genPersistChain: Promise = Promise.resolve(); private allowedOrigins: Set | null = null; - private sensitiveOrigin: string | null = null; - private sensitiveSubmissionArmed = false; private semanticCache: SemanticCache | null = null; private deltaBaseline: SemanticCache | null = null; private readonly cursors = new Map(); @@ -310,8 +308,6 @@ export class CdpSession { async detach(): Promise { this.enabled = false; - this.sensitiveOrigin = null; - this.sensitiveSubmissionArmed = false; this.frameSessions.clear(); this.frameParents.clear(); this.semanticCache = null; @@ -556,9 +552,7 @@ export class CdpSession { const url = event.request?.url; if ( isMainDocument && - (typeof url !== "string" || - !this.isAllowedTopLevelUrl(url) || - !this.isSensitiveTopLevelUrl(url)) + (typeof url !== "string" || !this.isAllowedTopLevelUrl(url)) ) { await this.send("Fetch.failRequest", { requestId: event.requestId, @@ -580,20 +574,6 @@ export class CdpSession { } } - pinSensitiveOrigin(origin: string): void { - this.sensitiveOrigin = origin; - this.sensitiveSubmissionArmed = false; - } - - async stopPendingSensitiveNavigation(expectedOrigin: string): Promise { - await this.send("Page.stopLoading"); - try { - return new URL((await this.mainFrameIdentity()).url).origin === expectedOrigin; - } catch { - return false; - } - } - async reconcile(): Promise { this.enabled = false; await this.enableDomains(); @@ -612,144 +592,6 @@ export class CdpSession { return record?.generation === this.generation ? record : null; } - hasCurrentRefs(refs: readonly string[]): boolean { - return refs.every((ref) => this.resolveRef(ref) !== null); - } - - preflightSensitiveRefs( - fieldRefs: readonly string[], - submitRef: string, - ): Promise { - return this.enqueue(async () => { - for (const ref of fieldRefs) { - const record = this.resolveRef(ref); - if (record === null || !(await this.validateRef(record, "type")).ok) { - return false; - } - } - const submit = this.resolveRef(submitRef); - return submit !== null && (await this.validateRef(submit, "click")).ok; - }); - } - - submitSensitiveFields( - fields: ReadonlyArray<{ ref: string; text: string }>, - submitRef: string, - expectedOrigin: string, - onBeforeInsert: () => void, - onBeforeSubmit: () => void, - canBeginInsertion: () => boolean | Promise = () => true, - ): Promise<{ - stale: boolean; - originMismatch: boolean; - cardBytesMayHaveBeenInserted: boolean; - submissionAttempted: boolean; - insertionRefused?: true; - }> { - return this.enqueue(async () => { - const expectedGeneration = this.generation; - const resolvedFields = fields.map((field) => ({ - ...field, - record: this.resolveRef(field.ref), - })); - const submitRecord = this.resolveRef(submitRef); - if ( - resolvedFields.some((field) => field.record === null) || - submitRecord === null - ) { - return { - stale: true, - originMismatch: false, - cardBytesMayHaveBeenInserted: false, - submissionAttempted: false, - }; - } - let currentOrigin: string; - try { - currentOrigin = new URL((await this.mainFrameIdentity()).url).origin; - } catch { - currentOrigin = ""; - } - if (currentOrigin !== expectedOrigin) { - return { - stale: false, - originMismatch: true, - cardBytesMayHaveBeenInserted: false, - submissionAttempted: false, - }; - } - let cardBytesMayHaveBeenInserted = false; - let submissionAttempted = false; - try { - for (const field of resolvedFields) { - if (this.generation !== expectedGeneration) break; - await this.focus( - field.record!.backendNodeId, - field.record!.debuggerSessionId, - ); - await this.dispatchKey( - parseKeys("Ctrl+a"), - field.record!.debuggerSessionId, - ); - if (this.generation !== expectedGeneration) break; - if (!cardBytesMayHaveBeenInserted && !(await canBeginInsertion())) { - return { - stale: false, - originMismatch: false, - cardBytesMayHaveBeenInserted: false, - submissionAttempted: false, - insertionRefused: true, - }; - } - cardBytesMayHaveBeenInserted = true; - onBeforeInsert(); - await this.sendInSession( - "Input.insertText", - { text: field.text }, - field.record!.debuggerSessionId, - ); - } - if ( - this.generation !== expectedGeneration || - resolvedFields.length === 0 || - !cardBytesMayHaveBeenInserted - ) { - return { - stale: !cardBytesMayHaveBeenInserted, - originMismatch: false, - cardBytesMayHaveBeenInserted, - submissionAttempted: false, - }; - } - submissionAttempted = true; - this.sensitiveSubmissionArmed = true; - onBeforeSubmit(); - await this.dispatchClick( - submitRecord.backendNodeId, - submitRecord.debuggerSessionId, - ); - } catch { - // The fixed result exposes only whether insertion or submission may have started. - } - return { - stale: false, - originMismatch: false, - cardBytesMayHaveBeenInserted, - submissionAttempted, - }; - }); - } - - private isSensitiveTopLevelUrl(value: string): boolean { - if (this.sensitiveOrigin === null) return true; - if (!this.sensitiveSubmissionArmed) return false; - try { - return new URL(value).origin === this.sensitiveOrigin; - } catch { - return false; - } - } - invalidateRefsForSessionChange(nextScopeId: string = crypto.randomUUID()): Promise { return this.enqueue(async () => { this.refScopeId = nextScopeId; @@ -1401,9 +1243,6 @@ export class CdpSession { return this.run( commandId, async () => { - if (this.sensitiveOrigin !== null) { - return this.semanticFailure(commandId, "snapshot", "sensitive_mode"); - } try { const { cache, previous } = await this.captureFreshSemantic( scope, @@ -1480,9 +1319,6 @@ export class CdpSession { return this.run( commandId, async () => { - if (this.sensitiveOrigin !== null) { - return this.semanticFailure(commandId, "find", "sensitive_mode"); - } try { const cache = this.semanticCache ?? @@ -1519,9 +1355,6 @@ export class CdpSession { return this.run( commandId, async () => { - if (this.sensitiveOrigin !== null) { - return this.semanticFailure(commandId, "inspect", "sensitive_mode"); - } const cache = this.semanticCache; if (cache === null) { return this.semanticFailure(commandId, "inspect", "snapshot_expired"); @@ -1560,9 +1393,6 @@ export class CdpSession { return this.run( commandId, async () => { - if (this.sensitiveOrigin !== null) { - return this.semanticFailure(commandId, "next", "sensitive_mode"); - } if (!/^[0-9a-f]{32}$/.test(token)) { return this.semanticFailure(commandId, "next", "invalid_cursor"); } @@ -1782,9 +1612,6 @@ export class CdpSession { return this.run( commandId, async () => { - if (this.sensitiveOrigin !== null) { - return this.actionFailure(commandId, "sensitive_mode", true, false); - } const { captured, url } = await this.captureStableSnapshot(deadlineAt, () => this.send( "Page.captureScreenshot", diff --git a/apps/extension/src/driver/semantic/cdp-semantic.test.ts b/apps/extension/src/driver/semantic/cdp-semantic.test.ts index 03d2812..52b2524 100644 --- a/apps/extension/src/driver/semantic/cdp-semantic.test.ts +++ b/apps/extension/src/driver/semantic/cdp-semantic.test.ts @@ -316,22 +316,4 @@ describe("CdpSession semantic results", () => { reason: "snapshot_expired", }); }); - - it("rejects every semantic read before touching page data in sensitive mode", async () => { - const sendCommand = semanticBrowser(); - const session = await CdpSession.create(7, "semantic"); - session.pinSensitiveOrigin("https://example.test"); - - await expect( - session.captureElements("snapshot", "viewport", "interactive", 80, false), - ).resolves.toMatchObject({ status: "error", reason: "sensitive_mode" }); - await expect( - session.findElements("find", "Pay", [], "contains", false, 20), - ).resolves.toMatchObject({ status: "error", reason: "sensitive_mode" }); - await expect(session.inspectElements("inspect", "ref", 3, 80, false)) - .resolves.toMatchObject({ status: "error", reason: "sensitive_mode" }); - await expect(session.continueElements("next", "0".repeat(32))) - .resolves.toMatchObject({ status: "error", reason: "sensitive_mode" }); - expect(sendCommand).not.toHaveBeenCalled(); - }); }); diff --git a/apps/extension/src/entrypoints/background.ts b/apps/extension/src/entrypoints/background.ts index 6e624b7..ff228ab 100644 --- a/apps/extension/src/entrypoints/background.ts +++ b/apps/extension/src/entrypoints/background.ts @@ -28,6 +28,7 @@ import { redeemPairingOffer, } from "../core/pairing-client"; import { ReconnectingWs } from "../core/ws-client"; +import { deleteObsoleteDatabase } from "../core/delete-obsolete-database"; import { ProfileClient } from "../core/profile-client"; import { WriteJournal, type WriteJournalRecord } from "../core/write-journal"; import { CdpSession } from "../driver/cdp"; @@ -35,7 +36,6 @@ import { classifyCdpEvent } from "../driver/cdp-events"; import { errorMessage } from "../events"; import type { AttachedTab, - CardVaultSaveResultMsg, LogEntry, LogLevel, LogMsg, @@ -87,11 +87,6 @@ let attachmentId: string | null = null; let pairingState: StateMsg["pairing"]; let hostingStopRequested = false; let hostingStopRequest = 0; -let cardVaultState: StateMsg["cardVault"] = { - aliases: [], - approvedOrigins: [], - revision: 0, -}; interface AttendedRuntime { dedupe: WriteDedupe; @@ -138,6 +133,8 @@ function internalRuntime(): AttendedRuntime { export default defineBackground({ type: "module", main() { + fireAndForget("obsolete database cleanup", deleteObsoleteDatabase); + // Register synchronously (before any await) so the listeners are in place // the instant the SW is revived and survive across restarts. browser.alarms.onAlarm.addListener(onAlarm); @@ -167,7 +164,6 @@ export default defineBackground({ fireAndForget("ensureConnection", ensureConnection); fireAndForget("reconcileAttachment", reconcileAttachment); fireAndForget("profileClient", () => profileClient.start()); - fireAndForget("card vault", refreshCardVaultState); fireAndForget("pairing recovery", () => recoverPendingPairing(pairingRecoveryRequest), ); @@ -197,7 +193,6 @@ async function startStoreRuntime(): Promise { browser.storage.local.remove(WS_URL_KEY), ]); await profileClient.start(); - await refreshCardVaultState(); } // ── WebSocket lifecycle ────────────────────────────────────────────────────── @@ -1044,43 +1039,6 @@ function handlePanelMsg(msg: PanelMsg, port: Browser.runtime.Port): void { }); return; } - if (msg.type === "saveCard") { - fireAndForget("saveCard", async () => { - const saved = await mutateCardVault(() => - profileClient.paymentVault().save(msg.card), - ); - const result: CardVaultSaveResultMsg = saved - ? { type: "cardVaultSaveResult", requestId: msg.requestId, ok: true } - : { - type: "cardVaultSaveResult", - requestId: msg.requestId, - ok: false, - error: "The local card-vault operation failed.", - }; - postToPort(port, result); - }); - return; - } - if (msg.type === "deleteCard") { - fireAndForget("deleteCard", async () => { - await mutateCardVault(() => profileClient.paymentVault().delete(msg.alias)); - }); - return; - } - if (msg.type === "deleteCardVault") { - fireAndForget("deleteCardVault", async () => { - await mutateCardVault(() => profileClient.paymentVault().deleteAll()); - }); - return; - } - if (msg.type === "setPaymentOrigins") { - fireAndForget("setPaymentOrigins", async () => { - await mutateCardVault(() => - profileClient.paymentVault().setApprovedOrigins(msg.origins).then(() => undefined), - ); - }); - return; - } if (__UNDERSTUDY_STORE__) return; switch (msg.type) { @@ -1264,54 +1222,11 @@ function buildState(): StateMsg { ? { ...profileConfig, unattendedEnabled: false } : profileConfig, ...(pairingState === undefined ? {} : { pairing: pairingState }), - cardVault: { - ...cardVaultState, - aliases: [...cardVaultState.aliases], - approvedOrigins: [...cardVaultState.approvedOrigins], - }, ...(blockedReason === null ? {} : { profileStatusReason: blockedReason }), logs: [...logBuffer], }; } -async function refreshCardVaultState(): Promise { - try { - const summary = await profileClient.paymentVault().summary(); - cardVaultState = { - ...summary, - revision: cardVaultState.revision, - }; - } catch { - cardVaultState = { - aliases: [], - approvedOrigins: [], - revision: cardVaultState.revision, - error: "The local card vault is unavailable. Delete it to create a new key.", - }; - } - broadcastState(); -} - -async function mutateCardVault(operation: () => Promise): Promise { - try { - await operation(); - const summary = await profileClient.paymentVault().summary(); - cardVaultState = { - ...summary, - revision: cardVaultState.revision + 1, - }; - broadcastState(); - return true; - } catch { - cardVaultState = { - ...cardVaultState, - error: "The local card-vault operation failed.", - }; - broadcastState(); - return false; - } -} - function pushState(port: Browser.runtime.Port): void { postToPort(port, buildState()); } diff --git a/apps/extension/src/entrypoints/sidepanel/App.tsx b/apps/extension/src/entrypoints/sidepanel/App.tsx index 3a93773..09d8f45 100644 --- a/apps/extension/src/entrypoints/sidepanel/App.tsx +++ b/apps/extension/src/entrypoints/sidepanel/App.tsx @@ -9,9 +9,7 @@ import type { ProfileBlockReason, SwMsg, } from "../../messaging"; -import type { PaymentCardInput } from "../../payment/card-validation"; import { DASHBOARD_URL, PRIVACY_URL } from "../../service-origin"; -import { CardSaveRequests, commitCardEnrollment } from "./card-save"; const SUPPORT_URL = "https://github.com/ProofOfTechOrg/understudy/issues"; const RECONNECT_DELAY_MS = 500; @@ -27,16 +25,6 @@ type HostStatus = export function App(): ReactElement { const [swState, setSwState] = useState(null); const portRef = useRef(null); - const cardSaveRequestsRef = useRef(null); - if (cardSaveRequestsRef.current === null) { - cardSaveRequestsRef.current = new CardSaveRequests((message) => { - const port = portRef.current; - if (port === null) { - throw new Error("The background service is reconnecting. Try again."); - } - port.postMessage(message); - }); - } const send = (msg: PanelMsg): void => { try { @@ -56,9 +44,7 @@ export function App(): ReactElement { portRef.current = port; port.onMessage.addListener((raw) => { const msg = raw as SwMsg; - if (msg.type === "cardVaultSaveResult") { - cardSaveRequestsRef.current?.settle(msg); - } else if (msg.type === "state") { + if (msg.type === "state") { setSwState(msg); } else { setSwState((previous) => @@ -70,9 +56,6 @@ export function App(): ReactElement { }); port.onDisconnect.addListener(() => { if (portRef.current === port) portRef.current = null; - cardSaveRequestsRef.current?.rejectAll( - "The background service disconnected before the card was saved. Review the form and try again.", - ); if (disposed) return; reconnectTimer = setTimeout(connect, RECONNECT_DELAY_MS); }); @@ -83,9 +66,6 @@ export function App(): ReactElement { return () => { disposed = true; clearTimeout(reconnectTimer); - cardSaveRequestsRef.current?.rejectAll( - "The side panel closed before the card was saved.", - ); portRef.current?.disconnect(); portRef.current = null; }; @@ -201,12 +181,6 @@ export function App(): ReactElement { - cardSaveRequestsRef.current!.save(card)} - send={send} - /> - {__UNDERSTUDY_STORE__ ? null : ( Promise; - send: (message: PanelMsg) => void; -}): ReactElement { - const [isSaving, setIsSaving] = useState(false); - const [saveError, setSaveError] = useState(null); - const savingRef = useRef(false); - - const saveCard = async (event: FormEvent): Promise => { - event.preventDefault(); - if (savingRef.current) return; - const form = event.currentTarget; - const data = new FormData(form); - const card = { - alias: String(data.get("alias") ?? ""), - cardholderName: String(data.get("cardholderName") ?? ""), - pan: String(data.get("pan") ?? ""), - expiryMonth: String(data.get("expiryMonth") ?? ""), - expiryYear: String(data.get("expiryYear") ?? ""), - cvv: String(data.get("cvv") ?? ""), - }; - savingRef.current = true; - setIsSaving(true); - setSaveError(null); - try { - await commitCardEnrollment(card, save, () => form.reset()); - } catch (cause) { - setSaveError( - cause instanceof Error - ? cause.message - : "The local card-vault operation failed.", - ); - } finally { - savingRef.current = false; - setIsSaving(false); - } - }; - - const saveOrigins = (event: FormEvent): void => { - event.preventDefault(); - const data = new FormData(event.currentTarget); - const origins = String(data.get("paymentOrigins") ?? "") - .split(/\r?\n/) - .map((origin) => origin.trim()) - .filter((origin) => origin.length > 0); - send({ type: "setPaymentOrigins", origins }); - }; - - const deleteVault = (): void => { - if ( - window.confirm( - "Delete every local card, the encryption key, and payment origins? Recovery is impossible.", - ) - ) { - send({ type: "deleteCardVault" }); - } - }; - - return ( -
-
-
-

03 / Local cards

-

Payment vault

-
- This device -
-

- Card values and the non-exportable encryption key stay inside this - extension. Only aliases are exposed to an authorized agent. -

- {saveError === null && vault?.error === undefined ? null : ( -

{saveError ?? vault?.error}

- )} -
- - - -
- - - -
- -
- -
-

Saved aliases

- {vault === null || vault.aliases.length === 0 ? ( -

No local cards enrolled.

- ) : ( -
    - {vault.aliases.map((alias) => ( -
  • - {alias} - -
  • - ))} -
- )} -
- -
-