From c7c825e859c385b16b29d2d57eb42961fa9d0af5 Mon Sep 17 00:00:00 2001 From: David Witwer Date: Sat, 7 Nov 2026 13:19:05 -0800 Subject: [PATCH 01/22] feat(browser-pay): add fillCard to type the placeholder into checkout card forms Find card fields in every frame by autocomplete, name, label and provider attributes, ignore the off-screen autofill copies card vaults keep in each field's iframe, type a combined or split expiry, and read each field back. Never log or return a card value; never press Pay. Also reword three README passages that used internal names. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WdZFvXR4NZW6VFeY1xKWMp --- .changeset/browser-pay-fill-card.md | 5 + packages/browser-pay/README.md | 38 +- packages/browser-pay/examples/fill-card.ts | 33 ++ .../src/fill-card.integration.test.ts | 266 ++++++++++++ packages/browser-pay/src/fill-card.ts | 380 ++++++++++++++++++ packages/browser-pay/src/index.ts | 11 + 6 files changed, 730 insertions(+), 3 deletions(-) create mode 100644 .changeset/browser-pay-fill-card.md create mode 100644 packages/browser-pay/examples/fill-card.ts create mode 100644 packages/browser-pay/src/fill-card.integration.test.ts create mode 100644 packages/browser-pay/src/fill-card.ts diff --git a/.changeset/browser-pay-fill-card.md b/.changeset/browser-pay-fill-card.md new file mode 100644 index 000000000..67d7f4dc4 --- /dev/null +++ b/.changeset/browser-pay-fill-card.md @@ -0,0 +1,5 @@ +--- +"@sapiom/browser-pay": minor +--- + +Add `fillCard`, which types the purchase's placeholder card into a checkout's card form over a Playwright page without an LLM. It finds the fields in every frame by `autocomplete`, name, label and provider attributes (Shopify's card vault, Stripe Elements, Braintree hosted fields, Adyen secured fields, plain inputs and expiry selects), ignores the off-screen autofill copies card vaults put in each field's iframe, handles a combined MM/YY field or split month and year, and reads each field back. It never logs or returns a card value and never presses Pay. Reword three README passages that used internal names. diff --git a/packages/browser-pay/README.md b/packages/browser-pay/README.md index f7afff056..41cdf9617 100644 --- a/packages/browser-pay/README.md +++ b/packages/browser-pay/README.md @@ -1,6 +1,6 @@ # @sapiom/browser-pay -Browser-side payment interceptor. The agent types a governance placeholder into checkout. This package pauses that request over CDP and hands it to David's relay. The browser is fulfilled with the processor's response, or the request fails. The placeholder is never continued. +Browser-side payment interceptor. The agent types a governance placeholder into checkout. This package pauses that request over CDP and hands it to Sapiom's relay. The browser is fulfilled with the processor's response, or the request fails. The placeholder is never continued. ## Sequence @@ -13,6 +13,38 @@ Browser-side payment interceptor. The agent types a governance placeholder into An agent that gives up before paying cancels the purchase, which revokes the placeholder: a UCP checkout with `POST /v1/transactions/{transactionId}/ucp/checkout/cancel`, a browser-checkout purchase with `POST /v1/transactions/{transactionId}/cancel`. The browser-checkout cancel answers 409 `card_relayed` once the card was relayed; the payment is spent, and the agent completes the transaction instead. +## Filling the card form + +`fillCard(page, card)` types the placeholder into the checkout's card form, so the agent does not have to find and type into card fields itself. `page` is a Playwright page connected to the same browser with `chromium.connectOverCDP(cdpUrl)`; `card` is the placeholder's `number`, `expMonth`, `expYear` and `cvc`, plus an optional cardholder `name`. + +```typescript +import { + attachInterceptor, + fillCard, + httpPaymentRelay, +} from "@sapiom/browser-pay"; + +const handle = await attachInterceptor(cdpUrl, { + relay, + placeholder: { number, injectionRef }, +}); +// … the agent reaches the payment step … +const filled = await fillCard(page, { number, expMonth, expYear, cvc }); +if (filled.ok) { + await page + .getByRole("button", { name: /pay now|place order|complete order/i }) + .click(); +} else { + // Nothing was sent. `filled.missing` names the fields it could not fill. +} +``` + +It looks in every frame, including one cross-origin iframe per field (Shopify's card vault, Braintree hosted fields, Adyen secured fields) and one iframe for all fields (Stripe Elements), and classifies inputs and selects by `autocomplete` (`cc-number`, `cc-exp`, `cc-exp-month`, `cc-exp-year`, `cc-csc`, `cc-name`), name, id, placeholder, label and provider attributes. A card vault puts a copy of every card input in each field's iframe for autofill; `fillCard` types only into the copy a person could click (its centre is in the frame's viewport and nothing covers it). It types a combined expiry as `MM/YY` (`MM/YYYY` when the field asks for four digits), or fills split month and year inputs or selects. It waits up to `timeoutMs` (default 15 seconds) for card iframes that load after the page, types with a short delay so input masks keep up, and reads each field back. + +The result is `{ ok, filled, missing, unconfirmed, origins }`. `ok` is true when the number, the security code and the expiry were each typed and read back. `missing` lists `number`, `expiry` or `cvc` when one was not found or did not read back; `unconfirmed` lists fields found whose read-back differed; `origins` names the frame origin each field was filled in. The result never contains a card value, and `fillCard` never logs one. + +`fillCard` does not press Pay. Pressing it is the step that sends the card, so the caller keeps that decision and always knows whether it happened. If `ok` is false, nothing has been sent: retry the fill, or cancel the purchase so its placeholder is revoked. + ## Relay contract The existing browser/relay integration also carries managed bank verification for supported @@ -156,7 +188,7 @@ No answer after the send: The injection is consumed. The paused request fails and the same body is not sent again. -A redirect, a non-2xx HTTP status other than 502, 503, or 504, or an unreadable body fails the paused browser request. David's relay returns HTTP 200 for every outcome, so a 401 or 500 is not read as `unknown` or `refused`. It is not fulfilled with the error JSON. A transport error, a per-attempt timeout, and a router HTTP 502, 503, or 504 are posted again with the same idempotency key. If fulfill fails, the paused request is failed and the agent event is `relayed_unfulfilled`. +A redirect, a non-2xx HTTP status other than 502, 503, or 504, or an unreadable body fails the paused browser request. Sapiom's relay returns HTTP 200 for every outcome, so a 401 or 500 is not read as `unknown` or `refused`. It is not fulfilled with the error JSON. A transport error, a per-attempt timeout, and a router HTTP 502, 503, or 504 are posted again with the same idempotency key. If fulfill fails, the paused request is failed and the agent event is `relayed_unfulfilled`. ## What an agent does @@ -193,7 +225,7 @@ Call `handle.on` after `attachInterceptor` resolves. Events emitted while attach An optional `logger` receives `browser step failed` when arming `Fetch.enable` fails, and when a nested auto-attach, resume, `Target.getTargets`, existing-frame attach, or close fails. -A request is relayed when the held placeholder number appears in the URL or body. An exact match counts, and so do digits split by spaces or dashes, including the URL-encoded and JSON-escaped forms of those separators. `placeholder` is `{ number, injectionRef }`. `injectionRef` is a UUID. The backend's `checkPlaceholderUse` decides whether the number is valid. A paused request that does not hold the placeholder is continued. +A request is relayed when the held placeholder number appears in the URL or body. An exact match counts, and so do digits split by spaces or dashes, including the URL-encoded and JSON-escaped forms of those separators. `placeholder` is `{ number, injectionRef }`. `injectionRef` is a UUID. Sapiom decides whether the number is valid when the relay receives it. A paused request that does not hold the placeholder is continued. A relayed response fails the paused request only when that response contains the held placeholder number. diff --git a/packages/browser-pay/examples/fill-card.ts b/packages/browser-pay/examples/fill-card.ts new file mode 100644 index 000000000..c0c253218 --- /dev/null +++ b/packages/browser-pay/examples/fill-card.ts @@ -0,0 +1,33 @@ +/** + * Type the purchase's placeholder into the checkout's card form, then decide yourself + * whether to press Pay. Attach the interceptor first (see attach.ts) on the same CDP URL. + * + * CDP_URL=… PLACEHOLDER_NUMBER=… PLACEHOLDER_EXP_MONTH=… PLACEHOLDER_EXP_YEAR=… \ + * PLACEHOLDER_CVC=… npx tsx examples/fill-card.ts + */ +import { chromium } from "playwright"; +import { fillCard, type PageLike } from "../src/index.js"; + +async function main(): Promise { + const cdpUrl = process.env.CDP_URL; + if (!cdpUrl) throw new Error("CDP_URL is required"); + const browser = await chromium.connectOverCDP(cdpUrl); + const page = browser.contexts()[0]?.pages()[0]; + if (!page) throw new Error("no open page on that browser"); + + const result = await fillCard(page as unknown as PageLike, { + number: process.env.PLACEHOLDER_NUMBER ?? "", + expMonth: Number(process.env.PLACEHOLDER_EXP_MONTH), + expYear: Number(process.env.PLACEHOLDER_EXP_YEAR), + cvc: process.env.PLACEHOLDER_CVC ?? "", + }); + // Only field kinds and frame origins: safe to log. + process.stdout.write(`${JSON.stringify(result)}\n`); + if (!result.ok) { + // Nothing was sent. Cancel the purchase or retry the fill; never press Pay half-filled. + process.exitCode = 1; + } + await browser.close(); +} + +void main(); diff --git a/packages/browser-pay/src/fill-card.integration.test.ts b/packages/browser-pay/src/fill-card.integration.test.ts new file mode 100644 index 000000000..e03decda9 --- /dev/null +++ b/packages/browser-pay/src/fill-card.integration.test.ts @@ -0,0 +1,266 @@ +import http from "node:http"; +import { existsSync } from "node:fs"; +import type { AddressInfo } from "node:net"; +import type { Browser, Page } from "playwright"; +import { fillCard, type CardToFill, type PageLike } from "./fill-card"; + +const CARD: CardToFill = { + number: "4000000000000002", + expMonth: 3, + expYear: 2029, + cvc: "321", + name: "Test Buyer", +}; + +/** Formats digits as the page types them, like Shopify's and Stripe's masks. */ +const MASKS = ``; + +function field(attrs: string, title: string, mask = ""): string { + return `${title}${MASKS} +`; +} + +/** Card-iframe documents, served from the second origin. */ +const FRAMES: Record = { + "/shopify/number": field( + 'id="number" name="number" autocomplete="cc-number" placeholder="Card number"', + "Field container for: Card number", + "maskCard(document.querySelector('input'))", + ), + "/shopify/expiry": field( + 'id="expiry" name="expiry" autocomplete="cc-exp" placeholder="Expiration date (MM / YY)"', + "Field container for: Expiration date (MM / YY)", + "maskExpiry(document.querySelector('input'))", + ), + "/shopify/cvc": field( + 'id="verification_value" name="verification_value" autocomplete="cc-csc" placeholder="Security code"', + "Field container for: Security code", + ), + "/shopify/name": field( + 'id="name" name="name" autocomplete="cc-name" placeholder="Name on card"', + "Field container for: Name on card", + ), + "/stripe/card": `Secure card payment input frame${MASKS} + + + + +`, + "/braintree/number": field( + 'id="credit-card-number" name="credit-card-number"', + "Secure Credit Card Frame - Credit Card Number", + ), + "/braintree/month": field( + 'id="expiration-month" name="expiration-month" maxlength="2"', + "Secure Credit Card Frame - Expiration Month", + ), + "/braintree/year": field( + 'id="expiration-year" name="expiration-year" maxlength="4"', + "Secure Credit Card Frame - Expiration Year", + ), + "/braintree/cvv": field( + 'id="cvv" name="cvv"', + "Secure Credit Card Frame - CVV", + ), + "/adyen/number": field( + 'data-fieldtype="encryptedCardNumber"', + "Iframe for card number", + ), + "/adyen/expiry": field( + 'data-fieldtype="encryptedExpiryDate" placeholder="MM/YY"', + "Iframe for expiry date", + "maskExpiry(document.querySelector('input'))", + ), + "/adyen/cvc": field( + 'data-fieldtype="encryptedSecurityCode"', + "Iframe for security code", + ), +}; + +/** Top-level checkout pages; FRAME_ORIGIN is replaced with the card-iframe origin. */ +const DECOYS = ` + + +`; + +const frame = (path: string) => + ``; + +const PAGES: Record = { + "/shopify": `Checkout - Example Store${DECOYS} +${frame("/shopify/number")}${frame("/shopify/expiry")}${frame("/shopify/cvc")}${frame("/shopify/name")}`, + "/stripe": `Checkout${DECOYS}`, + "/braintree": `Checkout${DECOYS} +${frame("/braintree/number")}${frame("/braintree/month")}${frame("/braintree/year")}${frame("/braintree/cvv")}`, + "/adyen": `Checkout${DECOYS}${frame("/adyen/number")}${frame("/adyen/expiry")}${frame("/adyen/cvc")}`, + "/plain": `Checkout${DECOYS} + + + +`, + "/delayed": `Checkout${DECOYS} +`, + "/none": `Checkout${DECOYS}`, +}; + +function findChromium(): boolean { + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const path = require("playwright").chromium.executablePath() as string; + return Boolean(path && existsSync(path)); + } catch { + return false; + } +} + +function serve( + handler: (path: string) => string | undefined, +): Promise { + return new Promise((resolve) => { + const server = http.createServer((req, res) => { + const body = handler(req.url ?? "/"); + res.writeHead(body ? 200 : 404, { "content-type": "text/html" }); + res.end(body ?? "not found"); + }); + server.listen(0, "127.0.0.1", () => resolve(server)); + }); +} + +(findChromium() ? describe : describe.skip)( + "fillCard (Chromium, cross-origin card iframes)", + () => { + let browser: Browser; + let top: http.Server; + let frames: http.Server; + let topUrl: string; + + beforeAll(async () => { + frames = await serve((p) => FRAMES[p]); + const framePort = (frames.address() as AddressInfo).port; + // Same host, different hostname spelling: localhost vs 127.0.0.1 are different origins. + const frameOrigin = `http://localhost:${framePort}`; + top = await serve((p) => PAGES[p]?.replace(/FRAME_ORIGIN/g, frameOrigin)); + topUrl = `http://127.0.0.1:${(top.address() as AddressInfo).port}`; + const { chromium } = await import("playwright"); + browser = await chromium.launch(); + }, 60_000); + + afterAll(async () => { + await browser?.close(); + top?.close(); + frames?.close(); + }); + + async function open(path: string): Promise { + const page = await browser.newPage(); + await page.goto(`${topUrl}${path}`, { waitUntil: "load" }); + return page; + } + + const valueIn = async (page: Page, urlPart: string, selector = "input") => { + const f = page.frames().find((fr) => fr.url().includes(urlPart)); + return f!.locator(selector).first().inputValue(); + }; + + it("fills Shopify's one-iframe-per-field card form, masks included, and skips decoys", async () => { + const page = await open("/shopify"); + const result = await fillCard(page as unknown as PageLike, CARD, { + keyDelayMs: 5, + }); + expect(result).toMatchObject({ ok: true, missing: [], unconfirmed: [] }); + expect(result.filled).toEqual(["number", "expiry", "cvc", "name"]); + expect(await valueIn(page, "/shopify/number")).toBe( + "4000 0000 0000 0002", + ); + expect(await valueIn(page, "/shopify/expiry")).toBe("03 / 29"); + expect(await valueIn(page, "/shopify/cvc")).toBe("321"); + expect(await page.locator('[name="phone"]').inputValue()).toBe(""); + expect(await page.locator('[name="email"]').inputValue()).toBe(""); + expect(result.origins.number).toMatch(/^http:\/\/localhost:\d+$/); + await page.close(); + }); + + it("fills Stripe Elements' single iframe and leaves the postal code alone", async () => { + const page = await open("/stripe"); + const result = await fillCard(page as unknown as PageLike, CARD, { + keyDelayMs: 5, + }); + expect(result.ok).toBe(true); + expect(result.filled).toEqual(["number", "expiry", "cvc"]); + expect(await valueIn(page, "/stripe/card", "[name=exp-date]")).toBe( + "03 / 29", + ); + expect(await valueIn(page, "/stripe/card", "[name=postal]")).toBe(""); + await page.close(); + }); + + it("fills Braintree hosted fields with split month and year", async () => { + const page = await open("/braintree"); + const result = await fillCard(page as unknown as PageLike, CARD, { + keyDelayMs: 5, + }); + expect(result.ok).toBe(true); + expect(result.filled).toEqual(["number", "expMonth", "expYear", "cvc"]); + expect(await valueIn(page, "/braintree/month")).toBe("03"); + expect(await valueIn(page, "/braintree/year")).toBe("2029"); + await page.close(); + }); + + it("fills Adyen secured fields by their data-fieldtype", async () => { + const page = await open("/adyen"); + const result = await fillCard(page as unknown as PageLike, CARD, { + keyDelayMs: 5, + }); + expect(result.ok).toBe(true); + expect(result.filled).toEqual(["number", "expiry", "cvc"]); + await page.close(); + }); + + it("fills plain inputs and expiry selects on the page itself", async () => { + const page = await open("/plain"); + const result = await fillCard(page as unknown as PageLike, CARD, { + keyDelayMs: 5, + }); + expect(result.ok).toBe(true); + expect(result.filled).toEqual(["number", "expMonth", "expYear", "cvc"]); + expect(await page.locator("#m").inputValue()).toBe("03"); + expect(await page.locator("#y").inputValue()).toBe("2029"); + await page.close(); + }); + + it("waits for card iframes that load after the page", async () => { + const page = await open("/delayed"); + const result = await fillCard(page as unknown as PageLike, CARD, { + keyDelayMs: 5, + }); + expect(result).toMatchObject({ ok: true, missing: [] }); + await page.close(); + }, 20_000); + + it("reports what is missing, without values, when there is no card form", async () => { + const page = await open("/none"); + const result = await fillCard(page as unknown as PageLike, CARD, { + timeoutMs: 1000, + }); + expect(result).toEqual({ + ok: false, + filled: [], + missing: ["number", "expiry", "cvc"], + unconfirmed: [], + origins: {}, + }); + expect(JSON.stringify(result)).not.toContain(CARD.number); + await page.close(); + }); + }, +); diff --git a/packages/browser-pay/src/fill-card.ts b/packages/browser-pay/src/fill-card.ts new file mode 100644 index 000000000..13cf58c92 --- /dev/null +++ b/packages/browser-pay/src/fill-card.ts @@ -0,0 +1,380 @@ +/** + * Types the governance placeholder into a checkout's card form without an LLM. + * + * Card forms put each field in a different place: a plain input, one cross-origin iframe per + * field (Shopify's card vault, Braintree hosted fields, Adyen secured fields), or one iframe for + * all of them (Stripe Elements). `fillCard` looks at every frame of a Playwright page, classifies + * the visible inputs and selects by their `autocomplete`, name, id, placeholder, label and + * provider attributes, types the card the way a person would, and reads each field back. + * + * It never logs, returns or throws a card value. The result names only field kinds and frame + * origins. It does not press Pay: submitting stays with the caller, so the caller always knows + * whether it sent the card. + */ + +/** The card to type: the placeholder's fields, plus an optional cardholder name. */ +export interface CardToFill { + number: string; + expMonth: number; + expYear: number; + cvc: string; + /** Typed only when the form has a cardholder-name field. */ + name?: string; +} + +/** A card form field `fillCard` recognises. */ +export type CardField = + | "number" + | "expiry" + | "expMonth" + | "expYear" + | "cvc" + | "name"; + +export interface FillCardResult { + /** + * The number, the security code and the expiry (one combined field, or month and year) were + * each typed and read back. Pressing Pay is still the caller's step. + */ + ok: boolean; + /** Fields typed and read back, in the order they were filled. */ + filled: CardField[]; + /** + * Fields the card needs that were not found or did not read back: `number`, `cvc`, and + * `expiry` (standing for the combined field or either of month and year). + */ + missing: Array<"number" | "expiry" | "cvc">; + /** Fields found but whose read-back did not match what was typed. */ + unconfirmed: CardField[]; + /** Origin of each frame a field was filled in, keyed by field. */ + origins: Partial>; +} + +export interface FillCardOptions { + /** Delay between keystrokes, in milliseconds. Defaults to 25. */ + keyDelayMs?: number; + /** How long to wait for card fields to appear, in milliseconds. Defaults to 15000. */ + timeoutMs?: number; +} + +/** The parts of a Playwright `Locator` this helper uses. */ +export interface LocatorLike { + nth(index: number): LocatorLike; + click(options?: { timeout?: number }): Promise; + fill(value: string, options?: { timeout?: number }): Promise; + pressSequentially( + text: string, + options?: { delay?: number; timeout?: number }, + ): Promise; + press(key: string, options?: { timeout?: number }): Promise; + inputValue(options?: { timeout?: number }): Promise; + selectOption( + values: Array<{ value?: string; label?: string }>, + options?: { timeout?: number }, + ): Promise; +} + +/** The parts of a Playwright `Frame` this helper uses. */ +export interface FrameLike { + url(): string; + locator(selector: string): LocatorLike; + evaluate(expression: string): Promise; +} + +/** The parts of a Playwright `Page` this helper uses. */ +export interface PageLike { + frames(): FrameLike[]; + waitForTimeout(ms: number): Promise; +} + +/** What the page reports about one input or select. Values are never read here. */ +interface Candidate { + index: number; + tag: "input" | "select"; + type: string; + autocomplete: string; + hints: string; + /** A person could click it: its centre is in the frame's viewport and nothing covers it. */ + hit: boolean; + maxLength: number; + placeholder: string; +} + +interface Match { + frame: FrameLike; + origin: string; + candidate: Candidate; + field: CardField; + score: number; +} + +const SELECTOR = "input, select"; + +/** + * Runs in the page (a string, since this package has no DOM types): the visible, editable inputs + * and selects with the attributes that name them. It never reads a field's value. + */ +const DESCRIBE_FIELDS = `(() => { + const skip = new Set(["hidden","checkbox","radio","submit","button","image","file","reset"]); + const out = []; + Array.from(document.querySelectorAll("input, select")).forEach((el, index) => { + const tag = el.tagName.toLowerCase(); + const type = tag === "input" ? (el.type || "text").toLowerCase() : "select"; + if (skip.has(type) || el.disabled || (tag === "input" && el.readOnly)) return; + const rect = el.getBoundingClientRect(); + const style = window.getComputedStyle(el); + if (rect.width < 2 || rect.height < 2 || style.visibility === "hidden" || style.display === "none" || Number(style.opacity) === 0) return; + // Card vaults put a copy of every card input in each field's iframe for autofill; only the + // one a person can click is real. Hit-test its centre inside its own frame's viewport. + const cx = rect.left + rect.width / 2, cy = rect.top + rect.height / 2; + const inView = cx >= 0 && cy >= 0 && cx <= window.innerWidth && cy <= window.innerHeight; + const top = inView ? document.elementFromPoint(cx, cy) : null; + const hit = !!top && (top === el || el.contains(top) || (top.tagName === "LABEL" && top.control === el)); + const labels = Array.from(el.labels || []).map((l) => l.textContent || "").join(" "); + const named = (el.getAttribute("aria-labelledby") || "").split(/\\s+/) + .map((id) => (id && document.getElementById(id) ? document.getElementById(id).textContent || "" : "")).join(" "); + const hints = [el.getAttribute("name"), el.id, el.getAttribute("placeholder"), el.getAttribute("aria-label"), + el.getAttribute("data-fieldtype"), el.getAttribute("data-elements-stable-field-name"), + el.getAttribute("data-braintree-name"), labels, named, document.title] + .filter(Boolean).join(" | ").toLowerCase(); + out.push({ index, tag, type, autocomplete: (el.getAttribute("autocomplete") || "").toLowerCase().trim(), + hints, hit, maxLength: tag === "input" ? el.maxLength : -1, placeholder: (el.getAttribute("placeholder") || "").toLowerCase() }); + }); + return out; +})()`; + +const AUTOCOMPLETE: Record = { + "cc-number": "number", + "cc-exp": "expiry", + "cc-exp-month": "expMonth", + "cc-exp-year": "expYear", + "cc-csc": "cvc", + "cc-name": "name", +}; + +/** Field names that say "card" on their own, from the providers this was tested against. */ +const PATTERNS: Array<[CardField, RegExp]> = [ + [ + "cvc", + /\b(cvc|cvv2?|csc|cvn|cid)\b|security.?code|verification.?value|card.?code|encryptedsecuritycode/, + ], + [ + "expMonth", + /exp\w*.?month|encryptedexpirymonth|\bcc.?month\b|expiration-month|card.?month/, + ], + [ + "expYear", + /exp\w*.?year|encryptedexpiryyear|\bcc.?year\b|expiration-year|card.?year/, + ], + [ + "expiry", + /\bexp(iry|iration)?\b|exp.?date|expiration|encryptedexpirydate|mm\s*\/\s*yy/, + ], + [ + "number", + /card.?number|cardnumber|credit.?card.?number|\bcc.?num|encryptedcardnumber|\bpan\b/, + ], + ["name", /name.?on.?card|card.?holder|holder.?name|cardholder|\bcc.?name\b/], +]; + +/** A bare `number`/`name` field (Shopify's card vault, Stripe's Payment Element) counts only in a card frame. */ +const BARE: Array<[CardField, RegExp]> = [ + ["number", /^number\b/], + ["name", /^name\b/], + ["expiry", /^expiry\b/], +]; + +function classify( + c: Candidate, + cardFrame: boolean, +): { field: CardField; score: number } | null { + // Maestro's issue date and number look like an expiry and a card number; never type into them. + if (/\bissue[_ ](date|number)\b/.test(c.hints)) return null; + const ac = AUTOCOMPLETE[c.autocomplete.split(/\s+/).pop() ?? ""]; + if (ac) return { field: ac, score: 3 }; + for (const [field, re] of PATTERNS) + if (re.test(c.hints)) return { field, score: 2 }; + if (cardFrame) + for (const [field, re] of BARE) + if (re.test(c.hints)) return { field, score: 1 }; + return null; +} + +function originOf(url: string): string { + try { + return new URL(url).origin; + } catch { + return ""; + } +} + +async function scan(page: PageLike): Promise { + const top = originOf(page.frames()[0]?.url() ?? ""); + const matches: Match[] = []; + for (const frame of page.frames()) { + let candidates: Candidate[]; + try { + candidates = await frame.evaluate(DESCRIBE_FIELDS); + } catch { + continue; // detached or navigating frame + } + // Off-screen or covered copies are autofill decoys whenever the frame shows a real field. + if (candidates.some((c) => c.hit)) + candidates = candidates.filter((c) => c.hit); + const origin = originOf(frame.url()); + // A frame on another origin holding few inputs is a card iframe; so is one with any field + // that already names itself a card field. + const strong = candidates.some((c) => classify(c, false)); + const cardFrame = + strong || + (origin !== top && candidates.length > 0 && candidates.length <= 4); + for (const candidate of candidates) { + const hit = classify(candidate, cardFrame); + if (hit) + matches.push({ + frame, + origin, + candidate, + field: hit.field, + score: hit.score, + }); + } + } + return matches; +} + +/** The best match per field: highest score, then document order. */ +function choose(matches: Match[]): Map { + const best = new Map(); + for (const m of matches) { + const cur = best.get(m.field); + if (!cur || m.score > cur.score) best.set(m.field, m); + } + return best; +} + +const digits = (s: string) => s.replace(/\D/g, ""); +const two = (n: number) => String(n % 100).padStart(2, "0"); + +function expiryText(c: Candidate, card: CardToFill): string { + const mm = two(card.expMonth); + const long = /yyyy/.test(c.placeholder) || c.maxLength >= 9; + return `${mm}/${long ? String(card.expYear) : two(card.expYear)}`; +} + +async function typeInto( + m: Match, + text: string, + expectDigits: boolean, + delay: number, +): Promise { + const el = m.frame.locator(SELECTOR).nth(m.candidate.index); + const read = async () => { + const v = await el.inputValue({ timeout: 2000 }); + return expectDigits ? digits(v) : v.trim(); + }; + const want = expectDigits ? digits(text) : text.trim(); + await el.click({ timeout: 5000 }); + await el.fill("", { timeout: 5000 }).catch(() => undefined); + await el.pressSequentially(text, { delay, timeout: 15000 }); + if ((await read().catch(() => "")) === want) return true; + // Some masks drop keystrokes typed too fast; a direct fill is the fallback. + await el.fill(text, { timeout: 5000 }).catch(() => undefined); + return (await read().catch(() => "")) === want; +} + +async function chooseOption(m: Match, options: string[]): Promise { + const el = m.frame.locator(SELECTOR).nth(m.candidate.index); + for (const o of options) { + for (const spec of [{ value: o }, { label: o }]) { + try { + const picked = await el.selectOption([spec], { timeout: 2000 }); + if (picked.length) return true; + } catch { + // try the next spelling + } + } + } + return false; +} + +/** + * Types `card` into the checkout's card form on `page` (a Playwright page connected over CDP). + * Call it after `attachInterceptor`, with the placeholder the purchase returned, once the payment + * form is on screen. It does not press Pay. + */ +export async function fillCard( + page: PageLike, + card: CardToFill, + options: FillCardOptions = {}, +): Promise { + const delay = options.keyDelayMs ?? 25; + const deadline = Date.now() + (options.timeoutMs ?? 15000); + + let best = choose(await scan(page)); + // Card iframes load after the page; wait until a number field shows up or time runs out. + const complete = () => + best.has("number") && + best.has("cvc") && + (best.has("expiry") || (best.has("expMonth") && best.has("expYear"))); + while (!complete() && Date.now() < deadline) { + await page.waitForTimeout(500); + best = choose(await scan(page)); + } + + const filled: CardField[] = []; + const unconfirmed: CardField[] = []; + const origins: Partial> = {}; + const record = (field: CardField, ok: boolean) => { + const m = best.get(field)!; + origins[field] = m.origin; + (ok ? filled : unconfirmed).push(field); + }; + + const order: CardField[] = [ + "number", + "expiry", + "expMonth", + "expYear", + "cvc", + "name", + ]; + for (const field of order) { + const m = best.get(field); + if (!m) continue; + if (field === "name" && !card.name) continue; + if (field === "expiry" && (best.has("expMonth") || best.has("expYear"))) + continue; + let ok: boolean; + if (field === "expMonth" && m.candidate.tag === "select") { + ok = await chooseOption(m, [two(card.expMonth), String(card.expMonth)]); + } else if (field === "expYear" && m.candidate.tag === "select") { + ok = await chooseOption(m, [String(card.expYear), two(card.expYear)]); + } else { + const text = + field === "number" + ? card.number + : field === "cvc" + ? card.cvc + : field === "name" + ? card.name! + : field === "expiry" + ? expiryText(m.candidate, card) + : field === "expMonth" + ? two(card.expMonth) + : m.candidate.maxLength === 2 + ? two(card.expYear) + : String(card.expYear); + ok = await typeInto(m, text, field !== "name", delay).catch(() => false); + } + record(field, ok); + } + + const has = (f: CardField) => filled.includes(f); + const missing: FillCardResult["missing"] = []; + if (!has("number")) missing.push("number"); + if (!has("expiry") && !(has("expMonth") && has("expYear"))) + missing.push("expiry"); + if (!has("cvc")) missing.push("cvc"); + return { ok: missing.length === 0, filled, missing, unconfirmed, origins }; +} diff --git a/packages/browser-pay/src/index.ts b/packages/browser-pay/src/index.ts index 75765d712..d279a9a2a 100644 --- a/packages/browser-pay/src/index.ts +++ b/packages/browser-pay/src/index.ts @@ -9,6 +9,17 @@ export type { RefusalReason, } from "./interceptor.js"; +export { fillCard } from "./fill-card.js"; +export type { + CardField, + CardToFill, + FillCardOptions, + FillCardResult, + FrameLike, + LocatorLike, + PageLike, +} from "./fill-card.js"; + export { httpPaymentRelay } from "./relay.js"; export type { HttpRelayOptions, From f7528189c6c963dd11df6f12ca6df15b13ff51d2 Mon Sep 17 00:00:00 2001 From: David Witwer Date: Sat, 7 Nov 2026 14:48:13 -0800 Subject: [PATCH 02/22] fix(browser-pay): fillCard types only into trusted frames and confirms every field Use a frame's title to mark a card frame, not as a field label. Type only into frames on the page origin, a built-in card-vault host, or frameOrigins, and report other card frames in untrusted. Read selects back after change handlers. Prefer the combined expiry unless both split fields exist, and pick the expiry year width from the placeholder, falling back between two and four digits on read-back. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WdZFvXR4NZW6VFeY1xKWMp --- .changeset/browser-pay-fill-card.md | 2 +- packages/browser-pay/README.md | 6 +- .../src/fill-card.integration.test.ts | 148 +++++++++++++++--- packages/browser-pay/src/fill-card.ts | 137 +++++++++++++--- 4 files changed, 244 insertions(+), 49 deletions(-) diff --git a/.changeset/browser-pay-fill-card.md b/.changeset/browser-pay-fill-card.md index 67d7f4dc4..8901680c6 100644 --- a/.changeset/browser-pay-fill-card.md +++ b/.changeset/browser-pay-fill-card.md @@ -2,4 +2,4 @@ "@sapiom/browser-pay": minor --- -Add `fillCard`, which types the purchase's placeholder card into a checkout's card form over a Playwright page without an LLM. It finds the fields in every frame by `autocomplete`, name, label and provider attributes (Shopify's card vault, Stripe Elements, Braintree hosted fields, Adyen secured fields, plain inputs and expiry selects), ignores the off-screen autofill copies card vaults put in each field's iframe, handles a combined MM/YY field or split month and year, and reads each field back. It never logs or returns a card value and never presses Pay. Reword three README passages that used internal names. +Add `fillCard`, which types the purchase's placeholder card into a checkout's card form over a Playwright page without an LLM. It finds the fields in every frame by `autocomplete`, name, label and provider attributes (Shopify's card vault, Stripe Elements, Braintree hosted fields, Adyen secured fields, plain inputs and expiry selects), ignores the off-screen autofill copies card vaults put in each field's iframe, handles a combined MM/YY field or split month and year, types only into frames on the page origin, a built-in card-vault host or caller-listed origins, and reads each field back. It never logs or returns a card value and never presses Pay. Reword three README passages that used internal names. diff --git a/packages/browser-pay/README.md b/packages/browser-pay/README.md index 41cdf9617..00fccc512 100644 --- a/packages/browser-pay/README.md +++ b/packages/browser-pay/README.md @@ -39,9 +39,11 @@ if (filled.ok) { } ``` -It looks in every frame, including one cross-origin iframe per field (Shopify's card vault, Braintree hosted fields, Adyen secured fields) and one iframe for all fields (Stripe Elements), and classifies inputs and selects by `autocomplete` (`cc-number`, `cc-exp`, `cc-exp-month`, `cc-exp-year`, `cc-csc`, `cc-name`), name, id, placeholder, label and provider attributes. A card vault puts a copy of every card input in each field's iframe for autofill; `fillCard` types only into the copy a person could click (its centre is in the frame's viewport and nothing covers it). It types a combined expiry as `MM/YY` (`MM/YYYY` when the field asks for four digits), or fills split month and year inputs or selects. It waits up to `timeoutMs` (default 15 seconds) for card iframes that load after the page, types with a short delay so input masks keep up, and reads each field back. +It looks in every frame, including one cross-origin iframe per field (Shopify's card vault, Braintree hosted fields, Adyen secured fields) and one iframe for all fields (Stripe Elements), and classifies inputs and selects by `autocomplete` (`cc-number`, `cc-exp`, `cc-exp-month`, `cc-exp-year`, `cc-csc`, `cc-name`), name, id, placeholder, label and provider attributes. A card vault puts a copy of every card input in each field's iframe for autofill; `fillCard` types only into the copy a person could click (its centre is in the frame's viewport and nothing covers it). It types a combined expiry as `MM/YY`, or `MM/YYYY` when the placeholder asks for a four-digit year (with no year in the placeholder it tries two digits, then four, and keeps the one that reads back). It fills split month and year inputs or selects only when both exist, and reads a select back after its change handlers run. It waits up to `timeoutMs` (default 15 seconds) for card iframes that load after the page, types with a short delay so input masks keep up, and reads each field back. -The result is `{ ok, filled, missing, unconfirmed, origins }`. `ok` is true when the number, the security code and the expiry were each typed and read back. `missing` lists `number`, `expiry` or `cvc` when one was not found or did not read back; `unconfirmed` lists fields found whose read-back differed; `origins` names the frame origin each field was filled in. The result never contains a card value, and `fillCard` never logs one. +It types only into frames on the page's own origin, on a built-in card-vault host over https (Shopify, Stripe, Braintree, Adyen, PayPal, Square, Checkout.com, Recurly, Chargebee, Spreedly, Authorize.net), or on an origin listed in `frameOrigins`. A frame on any other origin that holds card fields is not typed into and is named in `untrusted`, so an unrelated embedded iframe advertising card fields never receives the placeholder. + +The result is `{ ok, filled, missing, unconfirmed, origins, untrusted }`. `ok` is true when the number, the security code and the expiry were each typed and read back. `missing` lists `number`, `expiry` or `cvc` when one was not found or did not read back; `unconfirmed` lists fields found whose read-back differed; `origins` names the frame origin each field was filled in. The result never contains a card value, and `fillCard` never logs one. `fillCard` does not press Pay. Pressing it is the step that sends the card, so the caller keeps that decision and always knows whether it happened. If `ok` is false, nothing has been sent: retry the fill, or cancel the purchase so its placeholder is revoked. diff --git a/packages/browser-pay/src/fill-card.integration.test.ts b/packages/browser-pay/src/fill-card.integration.test.ts index e03decda9..1d001b37f 100644 --- a/packages/browser-pay/src/fill-card.integration.test.ts +++ b/packages/browser-pay/src/fill-card.integration.test.ts @@ -111,6 +111,31 @@ ${frame("/braintree/number")}${frame("/braintree/month")}${frame("/braintree/yea } }, 1500)`, "/none": `Checkout${DECOYS}`, + "/untrusted": `Checkout${DECOYS} + +${frame("/shopify/number")}${frame("/shopify/expiry")}${frame("/shopify/cvc")}`, + "/titled": `Card Number + + + +`, + "/select-reset": `Checkout + + + + +`, + "/stray-month": `Checkout${MASKS} + + + + +`, + "/padded": `Checkout${MASKS} + + + +`, }; function findChromium(): boolean { @@ -142,14 +167,38 @@ function serve( let browser: Browser; let top: http.Server; let frames: http.Server; + let other: http.Server; let topUrl: string; + let frameOrigin: string; + let otherOrigin: string; + + // The fixture card iframes are on plain-http localhost, not a built-in card-vault host. + const fill = (page: Page, opts: { timeoutMs?: number } = {}) => + fillCard(page as unknown as PageLike, CARD, { + keyDelayMs: 5, + frameOrigins: [frameOrigin], + ...opts, + }); beforeAll(async () => { frames = await serve((p) => FRAMES[p]); - const framePort = (frames.address() as AddressInfo).port; // Same host, different hostname spelling: localhost vs 127.0.0.1 are different origins. - const frameOrigin = `http://localhost:${framePort}`; - top = await serve((p) => PAGES[p]?.replace(/FRAME_ORIGIN/g, frameOrigin)); + frameOrigin = `http://localhost:${(frames.address() as AddressInfo).port}`; + // An unrelated embedded iframe that advertises card fields. + other = await serve((p) => + p === "/evil" + ? `Card + + +` + : undefined, + ); + otherOrigin = `http://localhost:${(other.address() as AddressInfo).port}`; + top = await serve((p) => + PAGES[p] + ?.replace(/FRAME_ORIGIN/g, frameOrigin) + .replace(/OTHER_ORIGIN/g, otherOrigin), + ); topUrl = `http://127.0.0.1:${(top.address() as AddressInfo).port}`; const { chromium } = await import("playwright"); browser = await chromium.launch(); @@ -159,6 +208,7 @@ function serve( await browser?.close(); top?.close(); frames?.close(); + other?.close(); }); async function open(path: string): Promise { @@ -174,10 +224,13 @@ function serve( it("fills Shopify's one-iframe-per-field card form, masks included, and skips decoys", async () => { const page = await open("/shopify"); - const result = await fillCard(page as unknown as PageLike, CARD, { - keyDelayMs: 5, + const result = await fill(page); + expect(result).toMatchObject({ + ok: true, + missing: [], + unconfirmed: [], + untrusted: [], }); - expect(result).toMatchObject({ ok: true, missing: [], unconfirmed: [] }); expect(result.filled).toEqual(["number", "expiry", "cvc", "name"]); expect(await valueIn(page, "/shopify/number")).toBe( "4000 0000 0000 0002", @@ -186,15 +239,13 @@ function serve( expect(await valueIn(page, "/shopify/cvc")).toBe("321"); expect(await page.locator('[name="phone"]').inputValue()).toBe(""); expect(await page.locator('[name="email"]').inputValue()).toBe(""); - expect(result.origins.number).toMatch(/^http:\/\/localhost:\d+$/); + expect(result.origins.number).toBe(frameOrigin); await page.close(); }); it("fills Stripe Elements' single iframe and leaves the postal code alone", async () => { const page = await open("/stripe"); - const result = await fillCard(page as unknown as PageLike, CARD, { - keyDelayMs: 5, - }); + const result = await fill(page); expect(result.ok).toBe(true); expect(result.filled).toEqual(["number", "expiry", "cvc"]); expect(await valueIn(page, "/stripe/card", "[name=exp-date]")).toBe( @@ -206,9 +257,7 @@ function serve( it("fills Braintree hosted fields with split month and year", async () => { const page = await open("/braintree"); - const result = await fillCard(page as unknown as PageLike, CARD, { - keyDelayMs: 5, - }); + const result = await fill(page); expect(result.ok).toBe(true); expect(result.filled).toEqual(["number", "expMonth", "expYear", "cvc"]); expect(await valueIn(page, "/braintree/month")).toBe("03"); @@ -218,9 +267,7 @@ function serve( it("fills Adyen secured fields by their data-fieldtype", async () => { const page = await open("/adyen"); - const result = await fillCard(page as unknown as PageLike, CARD, { - keyDelayMs: 5, - }); + const result = await fill(page); expect(result.ok).toBe(true); expect(result.filled).toEqual(["number", "expiry", "cvc"]); await page.close(); @@ -228,9 +275,7 @@ function serve( it("fills plain inputs and expiry selects on the page itself", async () => { const page = await open("/plain"); - const result = await fillCard(page as unknown as PageLike, CARD, { - keyDelayMs: 5, - }); + const result = await fill(page); expect(result.ok).toBe(true); expect(result.filled).toEqual(["number", "expMonth", "expYear", "cvc"]); expect(await page.locator("#m").inputValue()).toBe("03"); @@ -240,24 +285,77 @@ function serve( it("waits for card iframes that load after the page", async () => { const page = await open("/delayed"); - const result = await fillCard(page as unknown as PageLike, CARD, { - keyDelayMs: 5, - }); + const result = await fill(page); expect(result).toMatchObject({ ok: true, missing: [] }); await page.close(); }, 20_000); + it("never types into an iframe on an origin it was not given, and names it", async () => { + const page = await open("/untrusted"); + const result = await fill(page); + expect(result).toMatchObject({ ok: true, untrusted: [otherOrigin] }); + expect(Object.values(result.origins)).toEqual([ + frameOrigin, + frameOrigin, + frameOrigin, + ]); + const evil = page.frames().find((f) => f.url().startsWith(otherOrigin))!; + for (const ac of ["cc-number", "cc-exp", "cc-csc"]) + expect(await evil.locator(`[autocomplete=${ac}]`).inputValue()).toBe( + "", + ); + await page.close(); + }); + + it("does not read the page title as a field's label", async () => { + const page = await open("/titled"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator('[name="email"]').inputValue()).toBe(""); + expect(await page.locator('[name="cardnumber"]').inputValue()).toBe( + CARD.number, + ); + await page.close(); + }); + + it("reports a select its change handler reset as unconfirmed", async () => { + const page = await open("/select-reset"); + const result = await fill(page); + expect(result).toMatchObject({ ok: false, missing: ["expiry"] }); + expect(result.unconfirmed).toContain("expMonth"); + await page.close(); + }); + + it("uses the combined expiry when only one split field exists", async () => { + const page = await open("/stray-month"); + const result = await fill(page); + expect(result).toMatchObject({ + ok: true, + filled: ["number", "expiry", "cvc"], + }); + expect(await page.locator("#exp").inputValue()).toBe("03 / 29"); + expect(await page.locator("#month").inputValue()).toBe(""); + await page.close(); + }); + + it("types a two-digit year into a padded MM / YY mask with a long maxlength", async () => { + const page = await open("/padded"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#exp").inputValue()).toBe("03 / 29"); + await page.close(); + }); + it("reports what is missing, without values, when there is no card form", async () => { const page = await open("/none"); - const result = await fillCard(page as unknown as PageLike, CARD, { - timeoutMs: 1000, - }); + const result = await fill(page, { timeoutMs: 1000 }); expect(result).toEqual({ ok: false, filled: [], missing: ["number", "expiry", "cvc"], unconfirmed: [], origins: {}, + untrusted: [], }); expect(JSON.stringify(result)).not.toContain(CARD.number); await page.close(); diff --git a/packages/browser-pay/src/fill-card.ts b/packages/browser-pay/src/fill-card.ts index 13cf58c92..ce63b9313 100644 --- a/packages/browser-pay/src/fill-card.ts +++ b/packages/browser-pay/src/fill-card.ts @@ -48,6 +48,11 @@ export interface FillCardResult { unconfirmed: CardField[]; /** Origin of each frame a field was filled in, keyed by field. */ origins: Partial>; + /** + * Origins of frames that hold card fields but were not typed into, because they are neither the + * page's origin, a built-in card-vault origin, nor in `frameOrigins`. + */ + untrusted: string[]; } export interface FillCardOptions { @@ -55,6 +60,11 @@ export interface FillCardOptions { keyDelayMs?: number; /** How long to wait for card fields to appear, in milliseconds. Defaults to 15000. */ timeoutMs?: number; + /** + * Extra frame origins allowed to receive the card, such as a payment provider not in the built-in + * list. The page's own origin and the built-in card-vault origins are always allowed. + */ + frameOrigins?: string[]; } /** The parts of a Playwright `Locator` this helper uses. */ @@ -135,12 +145,12 @@ const DESCRIBE_FIELDS = `(() => { .map((id) => (id && document.getElementById(id) ? document.getElementById(id).textContent || "" : "")).join(" "); const hints = [el.getAttribute("name"), el.id, el.getAttribute("placeholder"), el.getAttribute("aria-label"), el.getAttribute("data-fieldtype"), el.getAttribute("data-elements-stable-field-name"), - el.getAttribute("data-braintree-name"), labels, named, document.title] + el.getAttribute("data-braintree-name"), labels, named] .filter(Boolean).join(" | ").toLowerCase(); out.push({ index, tag, type, autocomplete: (el.getAttribute("autocomplete") || "").toLowerCase().trim(), hints, hit, maxLength: tag === "input" ? el.maxLength : -1, placeholder: (el.getAttribute("placeholder") || "").toLowerCase() }); }); - return out; + return { title: (document.title || "").toLowerCase(), fields: out }; })()`; const AUTOCOMPLETE: Record = { @@ -200,6 +210,45 @@ function classify( return null; } +/** + * Hosts of card vaults and payment providers that serve card-field iframes. A frame on any other + * origin than the page's own gets the card only when the caller lists it in `frameOrigins`, so an + * unrelated embedded iframe advertising card fields is never typed into. + */ +const CARD_VAULT_HOSTS = [ + "shopifyinc.com", + "shopifycs.com", + "stripe.com", + "braintreegateway.com", + "braintree-api.com", + "adyen.com", + "adyenpayments.com", + "paypal.com", + "squareup.com", + "squarecdn.com", + "checkout.com", + "recurly.com", + "chargebee.com", + "spreedly.com", + "authorize.net", +]; + +/** Frame titles that mark a card iframe, where a bare `number`/`name`/`expiry` input is a card field. */ +const CARD_TITLE = /card|credit|payment|security code|cvv|cvc|expir/; + +function trusted(origin: string, top: string, extra: Set): boolean { + if (origin === top || extra.has(origin)) return true; + try { + const { protocol, hostname } = new URL(origin); + return ( + protocol === "https:" && + CARD_VAULT_HOSTS.some((h) => hostname === h || hostname.endsWith(`.${h}`)) + ); + } catch { + return false; + } +} + function originOf(url: string): string { try { return new URL(url).origin; @@ -208,13 +257,23 @@ function originOf(url: string): string { } } -async function scan(page: PageLike): Promise { +async function scan( + page: PageLike, + extra: Set, + untrusted: Set, +): Promise { const top = originOf(page.frames()[0]?.url() ?? ""); const matches: Match[] = []; for (const frame of page.frames()) { let candidates: Candidate[]; + let title: string; try { - candidates = await frame.evaluate(DESCRIBE_FIELDS); + const described = await frame.evaluate<{ + title: string; + fields: Candidate[]; + }>(DESCRIBE_FIELDS); + candidates = described.fields; + title = described.title; } catch { continue; // detached or navigating frame } @@ -224,13 +283,18 @@ async function scan(page: PageLike): Promise { const origin = originOf(frame.url()); // A frame on another origin holding few inputs is a card iframe; so is one with any field // that already names itself a card field. + // The title marks the frame, never a field: it is not one input's own label. const strong = candidates.some((c) => classify(c, false)); const cardFrame = strong || - (origin !== top && candidates.length > 0 && candidates.length <= 4); + (origin !== top && + candidates.length > 0 && + (candidates.length <= 4 || CARD_TITLE.test(title))); + const allowed = trusted(origin, top, extra); for (const candidate of candidates) { const hit = classify(candidate, cardFrame); - if (hit) + if (hit && !allowed) untrusted.add(origin); + else if (hit) matches.push({ frame, origin, @@ -256,10 +320,18 @@ function choose(matches: Match[]): Map { const digits = (s: string) => s.replace(/\D/g, ""); const two = (n: number) => String(n % 100).padStart(2, "0"); -function expiryText(c: Candidate, card: CardToFill): string { +/** + * What to type into a combined expiry, in order of preference. A placeholder that spells the year + * decides; otherwise two-digit first, then four-digit if the field did not read back. Length limits + * are not a hint: masks pad `MM / YY` with spaces. + */ +function expiryTexts(c: Candidate, card: CardToFill): string[] { const mm = two(card.expMonth); - const long = /yyyy/.test(c.placeholder) || c.maxLength >= 9; - return `${mm}/${long ? String(card.expYear) : two(card.expYear)}`; + const short = `${mm}/${two(card.expYear)}`; + const long = `${mm}/${card.expYear}`; + if (/yyyy/.test(c.placeholder)) return [long]; + if (/\byy\b/.test(c.placeholder)) return [short]; + return [short, long]; } async function typeInto( @@ -289,7 +361,12 @@ async function chooseOption(m: Match, options: string[]): Promise { for (const spec of [{ value: o }, { label: o }]) { try { const picked = await el.selectOption([spec], { timeout: 2000 }); - if (picked.length) return true; + // Read the field back after its change handlers ran; a handler may have reset it. + if ( + picked.length && + (await el.inputValue({ timeout: 2000 })) === picked[0] + ) + return true; } catch { // try the next spelling } @@ -311,7 +388,9 @@ export async function fillCard( const delay = options.keyDelayMs ?? 25; const deadline = Date.now() + (options.timeoutMs ?? 15000); - let best = choose(await scan(page)); + const extra = new Set(options.frameOrigins ?? []); + const untrusted = new Set(); + let best = choose(await scan(page, extra, untrusted)); // Card iframes load after the page; wait until a number field shows up or time runs out. const complete = () => best.has("number") && @@ -319,7 +398,7 @@ export async function fillCard( (best.has("expiry") || (best.has("expMonth") && best.has("expYear"))); while (!complete() && Date.now() < deadline) { await page.waitForTimeout(500); - best = choose(await scan(page)); + best = choose(await scan(page, extra, untrusted)); } const filled: CardField[] = []; @@ -343,13 +422,24 @@ export async function fillCard( const m = best.get(field); if (!m) continue; if (field === "name" && !card.name) continue; - if (field === "expiry" && (best.has("expMonth") || best.has("expYear"))) + if (field === "expiry" && best.has("expMonth") && best.has("expYear")) + continue; + if ( + (field === "expMonth" || field === "expYear") && + !(best.has("expMonth") && best.has("expYear")) + ) continue; let ok: boolean; if (field === "expMonth" && m.candidate.tag === "select") { ok = await chooseOption(m, [two(card.expMonth), String(card.expMonth)]); } else if (field === "expYear" && m.candidate.tag === "select") { ok = await chooseOption(m, [String(card.expYear), two(card.expYear)]); + } else if (field === "expiry") { + ok = false; + for (const text of expiryTexts(m.candidate, card)) { + ok = await typeInto(m, text, true, delay).catch(() => false); + if (ok) break; + } } else { const text = field === "number" @@ -358,13 +448,11 @@ export async function fillCard( ? card.cvc : field === "name" ? card.name! - : field === "expiry" - ? expiryText(m.candidate, card) - : field === "expMonth" - ? two(card.expMonth) - : m.candidate.maxLength === 2 - ? two(card.expYear) - : String(card.expYear); + : field === "expMonth" + ? two(card.expMonth) + : m.candidate.maxLength === 2 + ? two(card.expYear) + : String(card.expYear); ok = await typeInto(m, text, field !== "name", delay).catch(() => false); } record(field, ok); @@ -376,5 +464,12 @@ export async function fillCard( if (!has("expiry") && !(has("expMonth") && has("expYear"))) missing.push("expiry"); if (!has("cvc")) missing.push("cvc"); - return { ok: missing.length === 0, filled, missing, unconfirmed, origins }; + return { + ok: missing.length === 0, + filled, + missing, + unconfirmed, + origins, + untrusted: [...untrusted], + }; } From b9ba2ce7dd34db5dbc16094260b0798d89e2908a Mon Sep 17 00:00:00 2001 From: David Witwer Date: Sat, 7 Nov 2026 14:54:11 -0800 Subject: [PATCH 03/22] fix(browser-pay): check expiry year width against the field and trust same-origin inline frames Pick a four-digit year from the field's pattern or placeholder; otherwise try two digits, then four, accepting only a value the field reads back without marking itself invalid. Treat an about:srcdoc/about:blank frame as its parent's origin only when it can read the parent's document. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WdZFvXR4NZW6VFeY1xKWMp --- packages/browser-pay/README.md | 4 +- .../src/fill-card.integration.test.ts | 52 +++++++++++++++ packages/browser-pay/src/fill-card.ts | 66 ++++++++++++++++--- 3 files changed, 112 insertions(+), 10 deletions(-) diff --git a/packages/browser-pay/README.md b/packages/browser-pay/README.md index 00fccc512..f6373baa2 100644 --- a/packages/browser-pay/README.md +++ b/packages/browser-pay/README.md @@ -39,9 +39,9 @@ if (filled.ok) { } ``` -It looks in every frame, including one cross-origin iframe per field (Shopify's card vault, Braintree hosted fields, Adyen secured fields) and one iframe for all fields (Stripe Elements), and classifies inputs and selects by `autocomplete` (`cc-number`, `cc-exp`, `cc-exp-month`, `cc-exp-year`, `cc-csc`, `cc-name`), name, id, placeholder, label and provider attributes. A card vault puts a copy of every card input in each field's iframe for autofill; `fillCard` types only into the copy a person could click (its centre is in the frame's viewport and nothing covers it). It types a combined expiry as `MM/YY`, or `MM/YYYY` when the placeholder asks for a four-digit year (with no year in the placeholder it tries two digits, then four, and keeps the one that reads back). It fills split month and year inputs or selects only when both exist, and reads a select back after its change handlers run. It waits up to `timeoutMs` (default 15 seconds) for card iframes that load after the page, types with a short delay so input masks keep up, and reads each field back. +It looks in every frame, including one cross-origin iframe per field (Shopify's card vault, Braintree hosted fields, Adyen secured fields) and one iframe for all fields (Stripe Elements), and classifies inputs and selects by `autocomplete` (`cc-number`, `cc-exp`, `cc-exp-month`, `cc-exp-year`, `cc-csc`, `cc-name`), name, id, placeholder, label and provider attributes. A card vault puts a copy of every card input in each field's iframe for autofill; `fillCard` types only into the copy a person could click (its centre is in the frame's viewport and nothing covers it). It types a combined expiry as `MM/YY`, or `MM/YYYY` when the field's `pattern` or placeholder asks for a four-digit year. With neither, it tries two digits, then four, and keeps the first one the field reads back without marking itself invalid (constraint validation, or `aria-invalid` after blur). It fills split month and year inputs or selects only when both exist, and reads a select back after its change handlers run. It waits up to `timeoutMs` (default 15 seconds) for card iframes that load after the page, types with a short delay so input masks keep up, and reads each field back. -It types only into frames on the page's own origin, on a built-in card-vault host over https (Shopify, Stripe, Braintree, Adyen, PayPal, Square, Checkout.com, Recurly, Chargebee, Spreedly, Authorize.net), or on an origin listed in `frameOrigins`. A frame on any other origin that holds card fields is not typed into and is named in `untrusted`, so an unrelated embedded iframe advertising card fields never receives the placeholder. +It types only into frames on the page's own origin (including a `srcdoc` or `about:blank` frame the browser lets read its parent's document), on a built-in card-vault host over https (Shopify, Stripe, Braintree, Adyen, PayPal, Square, Checkout.com, Recurly, Chargebee, Spreedly, Authorize.net), or on an origin listed in `frameOrigins`. A frame on any other origin that holds card fields is not typed into and is named in `untrusted`, so an unrelated embedded iframe advertising card fields never receives the placeholder. The result is `{ ok, filled, missing, unconfirmed, origins, untrusted }`. `ok` is true when the number, the security code and the expiry were each typed and read back. `missing` lists `number`, `expiry` or `cvc` when one was not found or did not read back; `unconfirmed` lists fields found whose read-back differed; `origins` names the frame origin each field was filled in. The result never contains a card value, and `fillCard` never logs one. diff --git a/packages/browser-pay/src/fill-card.integration.test.ts b/packages/browser-pay/src/fill-card.integration.test.ts index 1d001b37f..90f0063ab 100644 --- a/packages/browser-pay/src/fill-card.integration.test.ts +++ b/packages/browser-pay/src/fill-card.integration.test.ts @@ -136,6 +136,23 @@ ${frame("/shopify/number")}${frame("/shopify/expiry")}${frame("/shopify/cvc")}`, `, + "/four-digit": `Checkout + + + +`, + "/pattern-four": `Checkout + + +`, + "/srcdoc": `Checkout +`, + "/sandboxed": `Checkout +`, }; function findChromium(): boolean { @@ -346,6 +363,41 @@ function serve( await page.close(); }); + it("retries a four-digit year when the field marks two digits invalid", async () => { + const page = await open("/four-digit"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#exp").inputValue()).toBe("03 / 2029"); + await page.close(); + }); + + it("types a four-digit year when the field's pattern requires one", async () => { + const page = await open("/pattern-four"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#exp").inputValue()).toBe("03/2029"); + await page.close(); + }); + + it("fills a same-origin srcdoc card frame as the page's own origin", async () => { + const page = await open("/srcdoc"); + const result = await fill(page); + expect(result).toMatchObject({ ok: true, untrusted: [] }); + expect(result.origins.number).toBe(topUrl); + await page.close(); + }); + + it("never types into a sandboxed srcdoc frame, whose origin is opaque", async () => { + const page = await open("/sandboxed"); + const result = await fill(page, { timeoutMs: 1000 }); + expect(result).toMatchObject({ + ok: false, + filled: [], + untrusted: ["null"], + }); + await page.close(); + }); + it("reports what is missing, without values, when there is no card form", async () => { const page = await open("/none"); const result = await fill(page, { timeoutMs: 1000 }); diff --git a/packages/browser-pay/src/fill-card.ts b/packages/browser-pay/src/fill-card.ts index ce63b9313..bbf0b1148 100644 --- a/packages/browser-pay/src/fill-card.ts +++ b/packages/browser-pay/src/fill-card.ts @@ -78,15 +78,24 @@ export interface LocatorLike { ): Promise; press(key: string, options?: { timeout?: number }): Promise; inputValue(options?: { timeout?: number }): Promise; + evaluate(fn: (el: FieldElement) => R): Promise; selectOption( values: Array<{ value?: string; label?: string }>, options?: { timeout?: number }, ): Promise; } +/** The parts of a form field read inside the page to check its validity. */ +export interface FieldElement { + validity?: { valid: boolean }; + getAttribute(name: string): string | null; + blur?(): void; +} + /** The parts of a Playwright `Frame` this helper uses. */ export interface FrameLike { url(): string; + parentFrame(): FrameLike | null; locator(selector: string): LocatorLike; evaluate(expression: string): Promise; } @@ -108,6 +117,8 @@ interface Candidate { hit: boolean; maxLength: number; placeholder: string; + /** The input's `pattern` attribute, which can require a four-digit year. */ + pattern: string; } interface Match { @@ -148,9 +159,13 @@ const DESCRIBE_FIELDS = `(() => { el.getAttribute("data-braintree-name"), labels, named] .filter(Boolean).join(" | ").toLowerCase(); out.push({ index, tag, type, autocomplete: (el.getAttribute("autocomplete") || "").toLowerCase().trim(), - hints, hit, maxLength: tag === "input" ? el.maxLength : -1, placeholder: (el.getAttribute("placeholder") || "").toLowerCase() }); + hints, hit, maxLength: tag === "input" ? el.maxLength : -1, placeholder: (el.getAttribute("placeholder") || "").toLowerCase(), pattern: el.getAttribute("pattern") || "" }); }); - return { title: (document.title || "").toLowerCase(), fields: out }; + // The browser lets a frame read its parent's document only when they share an origin, so this + // cannot be spoofed by the frame's own script. + let parentAccessible = false; + try { parentAccessible = parent !== self && !!parent.document; } catch (e) { parentAccessible = false; } + return { title: (document.title || "").toLowerCase(), fields: out, parentAccessible }; })()`; const AUTOCOMPLETE: Record = { @@ -264,23 +279,37 @@ async function scan( ): Promise { const top = originOf(page.frames()[0]?.url() ?? ""); const matches: Match[] = []; + const effective = new Map(); for (const frame of page.frames()) { let candidates: Candidate[]; let title: string; + let parentAccessible: boolean; try { const described = await frame.evaluate<{ title: string; fields: Candidate[]; + parentAccessible: boolean; }>(DESCRIBE_FIELDS); candidates = described.fields; title = described.title; + parentAccessible = described.parentAccessible; } catch { continue; // detached or navigating frame } + // An `about:srcdoc` or `about:blank` frame has no origin in its URL. It shares its parent's + // origin when the browser lets it read the parent's document; otherwise it is opaque. + let origin = originOf(frame.url()); + if (origin === "" || origin === "null") { + const parentFrame = frame.parentFrame(); + origin = + parentAccessible && parentFrame + ? (effective.get(parentFrame) ?? originOf(parentFrame.url())) + : "null"; + } + effective.set(frame, origin); // Off-screen or covered copies are autofill decoys whenever the frame shows a real field. if (candidates.some((c) => c.hit)) candidates = candidates.filter((c) => c.hit); - const origin = originOf(frame.url()); // A frame on another origin holding few inputs is a card iframe; so is one with any field // that already names itself a card field. // The title marks the frame, never a field: it is not one input's own label. @@ -321,19 +350,38 @@ const digits = (s: string) => s.replace(/\D/g, ""); const two = (n: number) => String(n % 100).padStart(2, "0"); /** - * What to type into a combined expiry, in order of preference. A placeholder that spells the year - * decides; otherwise two-digit first, then four-digit if the field did not read back. Length limits - * are not a hint: masks pad `MM / YY` with spaces. + * What to type into a combined expiry, in order of preference. A `pattern` or placeholder that + * spells the year width decides. Otherwise two digits first, then four, and a candidate counts only + * if the field reads it back and does not mark itself invalid. Length limits are not a hint: masks + * pad `MM / YY` with spaces. */ function expiryTexts(c: Candidate, card: CardToFill): string[] { const mm = two(card.expMonth); const short = `${mm}/${two(card.expYear)}`; const long = `${mm}/${card.expYear}`; - if (/yyyy/.test(c.placeholder)) return [long]; + if ( + /\\d\{4\}|\[0-9\]\{4\}|(\\d){4}/.test(c.pattern) || + /yyyy/.test(c.placeholder) + ) + return [long]; if (/\byy\b/.test(c.placeholder)) return [short]; return [short, long]; } +/** Whether the field rejects what was typed: its constraint validation, or `aria-invalid` after blur. */ +async function invalid(m: Match): Promise { + const el = m.frame.locator(SELECTOR).nth(m.candidate.index); + await el.evaluate((e) => e.blur?.()).catch(() => undefined); + await new Promise((r) => setTimeout(r, 150)); + return el + .evaluate( + (e) => + (!!e.validity && !e.validity.valid) || + e.getAttribute("aria-invalid") === "true", + ) + .catch(() => false); +} + async function typeInto( m: Match, text: string, @@ -437,7 +485,9 @@ export async function fillCard( } else if (field === "expiry") { ok = false; for (const text of expiryTexts(m.candidate, card)) { - ok = await typeInto(m, text, true, delay).catch(() => false); + ok = + (await typeInto(m, text, true, delay).catch(() => false)) && + !(await invalid(m)); if (ok) break; } } else { From 4014b0cdd1c29bcf99cb9e6c9f34e55f3cf11213 Mon Sep 17 00:00:00 2001 From: David Witwer Date: Sat, 7 Nov 2026 14:56:29 -0800 Subject: [PATCH 04/22] fix(browser-pay): let validation, not the pattern text, pick the expiry year width A pattern of four digits can mean MMYY. Try two digits, then four, and let the field's constraint validation (which includes its pattern) reject the wrong one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WdZFvXR4NZW6VFeY1xKWMp --- packages/browser-pay/README.md | 2 +- .../src/fill-card.integration.test.ts | 16 ++++++++++++++++ packages/browser-pay/src/fill-card.ts | 19 +++++++------------ 3 files changed, 24 insertions(+), 13 deletions(-) diff --git a/packages/browser-pay/README.md b/packages/browser-pay/README.md index f6373baa2..b1e10ce82 100644 --- a/packages/browser-pay/README.md +++ b/packages/browser-pay/README.md @@ -39,7 +39,7 @@ if (filled.ok) { } ``` -It looks in every frame, including one cross-origin iframe per field (Shopify's card vault, Braintree hosted fields, Adyen secured fields) and one iframe for all fields (Stripe Elements), and classifies inputs and selects by `autocomplete` (`cc-number`, `cc-exp`, `cc-exp-month`, `cc-exp-year`, `cc-csc`, `cc-name`), name, id, placeholder, label and provider attributes. A card vault puts a copy of every card input in each field's iframe for autofill; `fillCard` types only into the copy a person could click (its centre is in the frame's viewport and nothing covers it). It types a combined expiry as `MM/YY`, or `MM/YYYY` when the field's `pattern` or placeholder asks for a four-digit year. With neither, it tries two digits, then four, and keeps the first one the field reads back without marking itself invalid (constraint validation, or `aria-invalid` after blur). It fills split month and year inputs or selects only when both exist, and reads a select back after its change handlers run. It waits up to `timeoutMs` (default 15 seconds) for card iframes that load after the page, types with a short delay so input masks keep up, and reads each field back. +It looks in every frame, including one cross-origin iframe per field (Shopify's card vault, Braintree hosted fields, Adyen secured fields) and one iframe for all fields (Stripe Elements), and classifies inputs and selects by `autocomplete` (`cc-number`, `cc-exp`, `cc-exp-month`, `cc-exp-year`, `cc-csc`, `cc-name`), name, id, placeholder, label and provider attributes. A card vault puts a copy of every card input in each field's iframe for autofill; `fillCard` types only into the copy a person could click (its centre is in the frame's viewport and nothing covers it). It types a combined expiry as `MM/YY`, or `MM/YYYY` when the placeholder asks for a four-digit year. Otherwise it tries two digits, then four, and keeps the first one the field reads back without marking itself invalid (constraint validation, including the field's `pattern`, or `aria-invalid` after blur). It fills split month and year inputs or selects only when both exist, and reads a select back after its change handlers run. It waits up to `timeoutMs` (default 15 seconds) for card iframes that load after the page, types with a short delay so input masks keep up, and reads each field back. It types only into frames on the page's own origin (including a `srcdoc` or `about:blank` frame the browser lets read its parent's document), on a built-in card-vault host over https (Shopify, Stripe, Braintree, Adyen, PayPal, Square, Checkout.com, Recurly, Chargebee, Spreedly, Authorize.net), or on an origin listed in `frameOrigins`. A frame on any other origin that holds card fields is not typed into and is named in `untrusted`, so an unrelated embedded iframe advertising card fields never receives the placeholder. diff --git a/packages/browser-pay/src/fill-card.integration.test.ts b/packages/browser-pay/src/fill-card.integration.test.ts index 90f0063ab..31b9945fe 100644 --- a/packages/browser-pay/src/fill-card.integration.test.ts +++ b/packages/browser-pay/src/fill-card.integration.test.ts @@ -151,6 +151,14 @@ exp.addEventListener("blur", () => { const y = exp.value.split("/")[1] || ""; ex `, "/srcdoc": `Checkout `, + "/mmyy-pattern": `Checkout + + + +`, "/sandboxed": `Checkout `, }; @@ -379,6 +387,14 @@ function serve( await page.close(); }); + it("types MMYY into a field whose pattern is four digits in total", async () => { + const page = await open("/mmyy-pattern"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#exp").inputValue()).toBe("0329"); + await page.close(); + }); + it("fills a same-origin srcdoc card frame as the page's own origin", async () => { const page = await open("/srcdoc"); const result = await fill(page); diff --git a/packages/browser-pay/src/fill-card.ts b/packages/browser-pay/src/fill-card.ts index bbf0b1148..1fe1e47a8 100644 --- a/packages/browser-pay/src/fill-card.ts +++ b/packages/browser-pay/src/fill-card.ts @@ -117,8 +117,6 @@ interface Candidate { hit: boolean; maxLength: number; placeholder: string; - /** The input's `pattern` attribute, which can require a four-digit year. */ - pattern: string; } interface Match { @@ -159,7 +157,7 @@ const DESCRIBE_FIELDS = `(() => { el.getAttribute("data-braintree-name"), labels, named] .filter(Boolean).join(" | ").toLowerCase(); out.push({ index, tag, type, autocomplete: (el.getAttribute("autocomplete") || "").toLowerCase().trim(), - hints, hit, maxLength: tag === "input" ? el.maxLength : -1, placeholder: (el.getAttribute("placeholder") || "").toLowerCase(), pattern: el.getAttribute("pattern") || "" }); + hints, hit, maxLength: tag === "input" ? el.maxLength : -1, placeholder: (el.getAttribute("placeholder") || "").toLowerCase() }); }); // The browser lets a frame read its parent's document only when they share an origin, so this // cannot be spoofed by the frame's own script. @@ -350,20 +348,17 @@ const digits = (s: string) => s.replace(/\D/g, ""); const two = (n: number) => String(n % 100).padStart(2, "0"); /** - * What to type into a combined expiry, in order of preference. A `pattern` or placeholder that - * spells the year width decides. Otherwise two digits first, then four, and a candidate counts only - * if the field reads it back and does not mark itself invalid. Length limits are not a hint: masks - * pad `MM / YY` with spaces. + * What to type into a combined expiry, in order of preference. A placeholder that spells the year + * width decides. Otherwise two digits first, then four, and a candidate counts only if the field + * reads it back and does not mark itself invalid; the field's own `pattern` takes part through + * constraint validation. Length limits and patterns are not read as a year width: masks pad + * `MM / YY` with spaces, and `\\d{4}` can mean MMYY. */ function expiryTexts(c: Candidate, card: CardToFill): string[] { const mm = two(card.expMonth); const short = `${mm}/${two(card.expYear)}`; const long = `${mm}/${card.expYear}`; - if ( - /\\d\{4\}|\[0-9\]\{4\}|(\\d){4}/.test(c.pattern) || - /yyyy/.test(c.placeholder) - ) - return [long]; + if (/yyyy/.test(c.placeholder)) return [long]; if (/\byy\b/.test(c.placeholder)) return [short]; return [short, long]; } From 61c69d09b41213df626bf14ad7b089fe8a8b57bd Mon Sep 17 00:00:00 2001 From: David Witwer Date: Sat, 7 Nov 2026 14:58:36 -0800 Subject: [PATCH 05/22] fix(browser-pay): always try both expiry year widths A YY placeholder can sit on an MM/YYYY pattern. The placeholder now only orders the attempts; validation picks the width. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WdZFvXR4NZW6VFeY1xKWMp --- packages/browser-pay/README.md | 2 +- .../browser-pay/src/fill-card.integration.test.ts | 12 ++++++++++++ packages/browser-pay/src/fill-card.ts | 14 ++++++-------- 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/packages/browser-pay/README.md b/packages/browser-pay/README.md index b1e10ce82..779fc83cb 100644 --- a/packages/browser-pay/README.md +++ b/packages/browser-pay/README.md @@ -39,7 +39,7 @@ if (filled.ok) { } ``` -It looks in every frame, including one cross-origin iframe per field (Shopify's card vault, Braintree hosted fields, Adyen secured fields) and one iframe for all fields (Stripe Elements), and classifies inputs and selects by `autocomplete` (`cc-number`, `cc-exp`, `cc-exp-month`, `cc-exp-year`, `cc-csc`, `cc-name`), name, id, placeholder, label and provider attributes. A card vault puts a copy of every card input in each field's iframe for autofill; `fillCard` types only into the copy a person could click (its centre is in the frame's viewport and nothing covers it). It types a combined expiry as `MM/YY`, or `MM/YYYY` when the placeholder asks for a four-digit year. Otherwise it tries two digits, then four, and keeps the first one the field reads back without marking itself invalid (constraint validation, including the field's `pattern`, or `aria-invalid` after blur). It fills split month and year inputs or selects only when both exist, and reads a select back after its change handlers run. It waits up to `timeoutMs` (default 15 seconds) for card iframes that load after the page, types with a short delay so input masks keep up, and reads each field back. +It looks in every frame, including one cross-origin iframe per field (Shopify's card vault, Braintree hosted fields, Adyen secured fields) and one iframe for all fields (Stripe Elements), and classifies inputs and selects by `autocomplete` (`cc-number`, `cc-exp`, `cc-exp-month`, `cc-exp-year`, `cc-csc`, `cc-name`), name, id, placeholder, label and provider attributes. A card vault puts a copy of every card input in each field's iframe for autofill; `fillCard` types only into the copy a person could click (its centre is in the frame's viewport and nothing covers it). For a combined expiry it tries `MM/YY` and `MM/YYYY` (four digits first when the placeholder spells YYYY) and keeps the first one the field reads back without marking itself invalid (constraint validation, including the field's `pattern`, or `aria-invalid` after blur). It fills split month and year inputs or selects only when both exist, and reads a select back after its change handlers run. It waits up to `timeoutMs` (default 15 seconds) for card iframes that load after the page, types with a short delay so input masks keep up, and reads each field back. It types only into frames on the page's own origin (including a `srcdoc` or `about:blank` frame the browser lets read its parent's document), on a built-in card-vault host over https (Shopify, Stripe, Braintree, Adyen, PayPal, Square, Checkout.com, Recurly, Chargebee, Spreedly, Authorize.net), or on an origin listed in `frameOrigins`. A frame on any other origin that holds card fields is not typed into and is named in `untrusted`, so an unrelated embedded iframe advertising card fields never receives the placeholder. diff --git a/packages/browser-pay/src/fill-card.integration.test.ts b/packages/browser-pay/src/fill-card.integration.test.ts index 31b9945fe..a188770d4 100644 --- a/packages/browser-pay/src/fill-card.integration.test.ts +++ b/packages/browser-pay/src/fill-card.integration.test.ts @@ -159,6 +159,10 @@ exp.addEventListener("blur", () => { const y = exp.value.split("/")[1] || ""; ex const e = document.getElementById("exp"); e.addEventListener("input", () => { e.value = e.value.replace(/\\D/g, "").slice(0, 4); }); `, + "/yy-placeholder-four-pattern": `Checkout + + +`, "/sandboxed": `Checkout `, }; @@ -395,6 +399,14 @@ function serve( await page.close(); }); + it("falls back to a four-digit year behind a YY placeholder when the pattern needs it", async () => { + const page = await open("/yy-placeholder-four-pattern"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#exp").inputValue()).toBe("03/2029"); + await page.close(); + }); + it("fills a same-origin srcdoc card frame as the page's own origin", async () => { const page = await open("/srcdoc"); const result = await fill(page); diff --git a/packages/browser-pay/src/fill-card.ts b/packages/browser-pay/src/fill-card.ts index 1fe1e47a8..ad016c825 100644 --- a/packages/browser-pay/src/fill-card.ts +++ b/packages/browser-pay/src/fill-card.ts @@ -348,19 +348,17 @@ const digits = (s: string) => s.replace(/\D/g, ""); const two = (n: number) => String(n % 100).padStart(2, "0"); /** - * What to type into a combined expiry, in order of preference. A placeholder that spells the year - * width decides. Otherwise two digits first, then four, and a candidate counts only if the field - * reads it back and does not mark itself invalid; the field's own `pattern` takes part through - * constraint validation. Length limits and patterns are not read as a year width: masks pad - * `MM / YY` with spaces, and `\\d{4}` can mean MMYY. + * What to type into a combined expiry, in order: two-digit year first, unless the placeholder spells + * YYYY. Both are always tried, and a candidate counts only if the field reads it back and does not + * mark itself invalid; the field's own `pattern` takes part through constraint validation. Hints only + * order the attempts: a `YY` placeholder can sit on an `MM/YYYY` pattern, masks pad `MM / YY` with + * spaces, and `\\d{4}` can mean MMYY. */ function expiryTexts(c: Candidate, card: CardToFill): string[] { const mm = two(card.expMonth); const short = `${mm}/${two(card.expYear)}`; const long = `${mm}/${card.expYear}`; - if (/yyyy/.test(c.placeholder)) return [long]; - if (/\byy\b/.test(c.placeholder)) return [short]; - return [short, long]; + return /yyyy/.test(c.placeholder) ? [long, short] : [short, long]; } /** Whether the field rejects what was typed: its constraint validation, or `aria-invalid` after blur. */ From 18262a62bb17fbab17f654cfefbafa168584d446 Mon Sep 17 00:00:00 2001 From: David Witwer Date: Sat, 7 Nov 2026 15:13:21 -0800 Subject: [PATCH 06/22] fix(browser-pay): harden fillCard per review Reject an unusable card before touching fields. Scroll a field into view before the decoy hit-test so real fields below the fold are kept. Re-read every field after the last one; check a frame's origin before typing; pass a blocked click to the next match. Match month-name selects, add a compact MMYY fallback, try both widths for a split year input, and re-read the expiry after blur. README no longer says ok: false proves nothing was sent. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WdZFvXR4NZW6VFeY1xKWMp --- packages/browser-pay/README.md | 8 +- packages/browser-pay/examples/fill-card.ts | 2 +- .../src/fill-card.integration.test.ts | 82 +++++ packages/browser-pay/src/fill-card.ts | 329 ++++++++++++------ 4 files changed, 318 insertions(+), 103 deletions(-) diff --git a/packages/browser-pay/README.md b/packages/browser-pay/README.md index 779fc83cb..62352565d 100644 --- a/packages/browser-pay/README.md +++ b/packages/browser-pay/README.md @@ -35,17 +35,19 @@ if (filled.ok) { .getByRole("button", { name: /pay now|place order|complete order/i }) .click(); } else { - // Nothing was sent. `filled.missing` names the fields it could not fill. + // `filled.missing` names the fields it could not fill. Read the purchase before retrying or cancelling. } ``` -It looks in every frame, including one cross-origin iframe per field (Shopify's card vault, Braintree hosted fields, Adyen secured fields) and one iframe for all fields (Stripe Elements), and classifies inputs and selects by `autocomplete` (`cc-number`, `cc-exp`, `cc-exp-month`, `cc-exp-year`, `cc-csc`, `cc-name`), name, id, placeholder, label and provider attributes. A card vault puts a copy of every card input in each field's iframe for autofill; `fillCard` types only into the copy a person could click (its centre is in the frame's viewport and nothing covers it). For a combined expiry it tries `MM/YY` and `MM/YYYY` (four digits first when the placeholder spells YYYY) and keeps the first one the field reads back without marking itself invalid (constraint validation, including the field's `pattern`, or `aria-invalid` after blur). It fills split month and year inputs or selects only when both exist, and reads a select back after its change handlers run. It waits up to `timeoutMs` (default 15 seconds) for card iframes that load after the page, types with a short delay so input masks keep up, and reads each field back. +It looks in every frame, including one cross-origin iframe per field (Shopify's card vault, Braintree hosted fields, Adyen secured fields) and one iframe for all fields (Stripe Elements), and classifies inputs and selects by `autocomplete` (`cc-number`, `cc-exp`, `cc-exp-month`, `cc-exp-year`, `cc-csc`, `cc-name`), name, id, placeholder, label and provider attributes. A card vault puts a copy of every card input in each field's iframe for autofill; `fillCard` types only into the copy a person could click (its centre is in the frame's viewport and nothing covers it). For a combined expiry it tries `MM/YY` and `MM/YYYY` (four digits first when the placeholder spells YYYY), then `MMYY`, and keeps the first one the field reads back without marking itself invalid (constraint validation, including the field's `pattern`, or `aria-invalid` after blur). It fills split month and year inputs or selects (numbers or month names) only when both exist, and reads a select back after its change handlers run. It waits up to `timeoutMs` (default 15 seconds) for card iframes that load after the page, types with a short delay so input masks keep up, and reads each field back. It types only into frames on the page's own origin (including a `srcdoc` or `about:blank` frame the browser lets read its parent's document), on a built-in card-vault host over https (Shopify, Stripe, Braintree, Adyen, PayPal, Square, Checkout.com, Recurly, Chargebee, Spreedly, Authorize.net), or on an origin listed in `frameOrigins`. A frame on any other origin that holds card fields is not typed into and is named in `untrusted`, so an unrelated embedded iframe advertising card fields never receives the placeholder. The result is `{ ok, filled, missing, unconfirmed, origins, untrusted }`. `ok` is true when the number, the security code and the expiry were each typed and read back. `missing` lists `number`, `expiry` or `cvc` when one was not found or did not read back; `unconfirmed` lists fields found whose read-back differed; `origins` names the frame origin each field was filled in. The result never contains a card value, and `fillCard` never logs one. -`fillCard` does not press Pay. Pressing it is the step that sends the card, so the caller keeps that decision and always knows whether it happened. If `ok` is false, nothing has been sent: retry the fill, or cancel the purchase so its placeholder is revoked. +`fillCard` does not press Pay; the caller keeps that step. A checkout's own field scripts can still send card data while it types, so `ok: false` does not prove nothing was sent: read the purchase (`payment_submitted` means the card may have reached the merchant) before retrying the fill or cancelling the purchase. + +It throws a `TypeError`, whose message carries no card values, before touching any field when the number, security code or expiry is not usable. Before typing into a frame it checks the frame is still on the origin it was found on, and after the last field it reads every field back once more, so a field a later handler reset is reported in `unconfirmed`. A field whose click is blocked (covered or detached) passes to the next matching field. ## Relay contract diff --git a/packages/browser-pay/examples/fill-card.ts b/packages/browser-pay/examples/fill-card.ts index c0c253218..f544f104d 100644 --- a/packages/browser-pay/examples/fill-card.ts +++ b/packages/browser-pay/examples/fill-card.ts @@ -24,7 +24,7 @@ async function main(): Promise { // Only field kinds and frame origins: safe to log. process.stdout.write(`${JSON.stringify(result)}\n`); if (!result.ok) { - // Nothing was sent. Cancel the purchase or retry the fill; never press Pay half-filled. + // Never press Pay half-filled. Read the purchase before retrying the fill or cancelling. process.exitCode = 1; } await browser.close(); diff --git a/packages/browser-pay/src/fill-card.integration.test.ts b/packages/browser-pay/src/fill-card.integration.test.ts index a188770d4..ad29e3021 100644 --- a/packages/browser-pay/src/fill-card.integration.test.ts +++ b/packages/browser-pay/src/fill-card.integration.test.ts @@ -43,6 +43,12 @@ const FRAMES: Record = { 'id="name" name="name" autocomplete="cc-name" placeholder="Name on card"', "Field container for: Name on card", ), + // Like Shopify's card vault: every card input is in the frame, only one is on screen. + "/vault/number": `Field container for: Card number + + + +`, "/stripe/card": `Secure card payment input frame${MASKS} @@ -162,6 +168,24 @@ e.addEventListener("input", () => { e.value = e.value.replace(/\\D/g, "").slice( "/yy-placeholder-four-pattern": `Checkout +`, + "/autofill-copies": `Checkout + +${frame("/shopify/expiry")}${frame("/shopify/cvc")}`, + "/below-fold": `Checkout + +
+ + +`, + "/month-names": `Checkout + + + +`, + "/compact": `Checkout + + `, "/sandboxed": `Checkout `, @@ -407,6 +431,64 @@ function serve( await page.close(); }); + it("types into the on-screen field of a card-vault frame, not its autofill copies", async () => { + const page = await open("/autofill-copies"); + const result = await fill(page); + expect(result.ok).toBe(true); + const vault = page + .frames() + .find((f) => f.url().includes("/vault/number"))!; + expect(await vault.locator("#real").inputValue()).toBe(CARD.number); + for (const name of ["name", "expiry", "verification_value"]) + expect(await vault.locator(`[name=${name}]`).inputValue()).toBe(""); + await page.close(); + }); + + it("fills card fields below the fold on the page itself", async () => { + const page = await open("/below-fold"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#ccnum").inputValue()).toBe(CARD.number); + expect(await page.locator('[name="email"]').inputValue()).toBe(""); + await page.close(); + }); + + it("picks an expiry month select that uses month names", async () => { + const page = await open("/month-names"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#m").inputValue()).toBe("March"); + await page.close(); + }); + + it("falls back to compact MMYY for an unmasked four-character expiry", async () => { + const page = await open("/compact"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#exp").inputValue()).toBe("0329"); + await page.close(); + }); + + it("refuses an unusable card before touching any field, without echoing it", async () => { + const page = await open("/plain"); + await expect( + fillCard( + page as unknown as PageLike, + { ...CARD, expMonth: Number.NaN }, + { frameOrigins: [frameOrigin] }, + ), + ).rejects.toThrow(/not usable/); + await expect( + fillCard( + page as unknown as PageLike, + { ...CARD, cvc: "" }, + { frameOrigins: [frameOrigin] }, + ), + ).rejects.not.toThrow(new RegExp(CARD.number)); + expect(await page.locator("#ccnum").inputValue()).toBe(""); + await page.close(); + }); + it("fills a same-origin srcdoc card frame as the page's own origin", async () => { const page = await open("/srcdoc"); const result = await fill(page); diff --git a/packages/browser-pay/src/fill-card.ts b/packages/browser-pay/src/fill-card.ts index ad016c825..b5d606e96 100644 --- a/packages/browser-pay/src/fill-card.ts +++ b/packages/browser-pay/src/fill-card.ts @@ -90,6 +90,7 @@ export interface FieldElement { validity?: { valid: boolean }; getAttribute(name: string): string | null; blur?(): void; + options?: ArrayLike<{ value: string; text: string }>; } /** The parts of a Playwright `Frame` this helper uses. */ @@ -145,8 +146,15 @@ const DESCRIBE_FIELDS = `(() => { if (rect.width < 2 || rect.height < 2 || style.visibility === "hidden" || style.display === "none" || Number(style.opacity) === 0) return; // Card vaults put a copy of every card input in each field's iframe for autofill; only the // one a person can click is real. Hit-test its centre inside its own frame's viewport. - const cx = rect.left + rect.width / 2, cy = rect.top + rect.height / 2; - const inView = cx >= 0 && cy >= 0 && cx <= window.innerWidth && cy <= window.innerHeight; + // A real field below the fold scrolls into view; a copy parked outside the document cannot. + const centre = (r) => [r.left + r.width / 2, r.top + r.height / 2]; + const visible = ([x, y]) => x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight; + let [cx, cy] = centre(rect); + if (!visible([cx, cy])) { + el.scrollIntoView({ block: "center", inline: "center" }); + [cx, cy] = centre(el.getBoundingClientRect()); + } + const inView = visible([cx, cy]); const top = inView ? document.elementFromPoint(cx, cy) : null; const hit = !!top && (top === el || el.contains(top) || (top.tagName === "LABEL" && top.control === el)); const labels = Array.from(el.labels || []).map((l) => l.textContent || "").join(" "); @@ -207,6 +215,7 @@ const BARE: Array<[CardField, RegExp]> = [ ["expiry", /^expiry\b/], ]; +/** The card field a candidate is, and how sure: 3 by `autocomplete`, 2 by a card-specific name, 1 bare. */ function classify( c: Candidate, cardFrame: boolean, @@ -249,6 +258,7 @@ const CARD_VAULT_HOSTS = [ /** Frame titles that mark a card iframe, where a bare `number`/`name`/`expiry` input is a card field. */ const CARD_TITLE = /card|credit|payment|security code|cvv|cvc|expir/; +/** Whether a frame on `origin` may receive the card. */ function trusted(origin: string, top: string, extra: Set): boolean { if (origin === top || extra.has(origin)) return true; try { @@ -262,6 +272,7 @@ function trusted(origin: string, top: string, extra: Set): boolean { } } +/** The origin of a URL, or "" when it has none. */ function originOf(url: string): string { try { return new URL(url).origin; @@ -270,6 +281,7 @@ function originOf(url: string): string { } } +/** Every allowed card-field match in every frame; origins of disallowed card frames go to `untrusted`. */ async function scan( page: PageLike, extra: Set, @@ -334,36 +346,91 @@ async function scan( return matches; } -/** The best match per field: highest score, then document order. */ -function choose(matches: Match[]): Map { - const best = new Map(); - for (const m of matches) { - const cur = best.get(m.field); - if (!cur || m.score > cur.score) best.set(m.field, m); - } - return best; +/** Matches per field, best first: highest score, then document order. */ +function rank(matches: Match[]): Map { + const ranked = new Map(); + for (const m of matches) + ranked.set(m.field, [...(ranked.get(m.field) ?? []), m]); + for (const list of ranked.values()) list.sort((a, b) => b.score - a.score); + return ranked; } +/** Only the digits of `s`. */ const digits = (s: string) => s.replace(/\D/g, ""); +/** The last two digits of `n`, zero-padded. */ const two = (n: number) => String(n % 100).padStart(2, "0"); +const MONTHS = [ + "january", + "february", + "march", + "april", + "may", + "june", + "july", + "august", + "september", + "october", + "november", + "december", +]; + /** * What to type into a combined expiry, in order: two-digit year first, unless the placeholder spells - * YYYY. Both are always tried, and a candidate counts only if the field reads it back and does not - * mark itself invalid; the field's own `pattern` takes part through constraint validation. Hints only - * order the attempts: a `YY` placeholder can sit on an `MM/YYYY` pattern, masks pad `MM / YY` with - * spaces, and `\\d{4}` can mean MMYY. + * YYYY, then the compact `MMYY`. Every spelling is tried, and one counts only if the field reads it + * back and does not mark itself invalid; the field's own `pattern` takes part through constraint + * validation. Hints only order the attempts: a `YY` placeholder can sit on an `MM/YYYY` pattern, + * masks pad `MM / YY` with spaces, and `\\d{4}` can mean MMYY. */ function expiryTexts(c: Candidate, card: CardToFill): string[] { const mm = two(card.expMonth); const short = `${mm}/${two(card.expYear)}`; const long = `${mm}/${card.expYear}`; - return /yyyy/.test(c.placeholder) ? [long, short] : [short, long]; + const ordered = /yyyy/.test(c.placeholder) ? [long, short] : [short, long]; + return [...ordered, `${mm}${two(card.expYear)}`]; +} + +/** Rejects a card that cannot be typed, before any field is touched. Messages carry no values. */ +function assertCard(card: CardToFill): void { + const n = digits(card.number ?? ""); + const cvc = digits(card.cvc ?? ""); + const ok = + n.length >= 12 && + n.length <= 19 && + n === card.number.replace(/[\s-]/g, "") && + cvc.length >= 3 && + cvc.length <= 4 && + cvc === card.cvc && + Number.isInteger(card.expMonth) && + card.expMonth >= 1 && + card.expMonth <= 12 && + Number.isInteger(card.expYear) && + card.expYear >= 2000 && + card.expYear <= 2099; + if (!ok) + throw new TypeError( + "fillCard: the card's number, security code or expiry is not usable", + ); +} + +/** The field a match points at. */ +const fieldOf = (m: Match) => m.frame.locator(SELECTOR).nth(m.candidate.index); + +/** The field's current value, as digits or trimmed text. */ +async function readBack(m: Match, expectDigits: boolean): Promise { + const v = await fieldOf(m).inputValue({ timeout: 2000 }); + return expectDigits ? digits(v) : v.trim(); +} + +/** Whether the frame still shows the document the match was found in, judged by its origin. */ +function sameDocumentOrigin(m: Match): boolean { + const now = originOf(m.frame.url()); + return now === "" || now === "null" || now === m.origin; } /** Whether the field rejects what was typed: its constraint validation, or `aria-invalid` after blur. */ async function invalid(m: Match): Promise { - const el = m.frame.locator(SELECTOR).nth(m.candidate.index); + const el = fieldOf(m); await el.evaluate((e) => e.blur?.()).catch(() => undefined); await new Promise((r) => setTimeout(r, 150)); return el @@ -375,130 +442,194 @@ async function invalid(m: Match): Promise { .catch(() => false); } +/** Types `text` like a person and reads it back; a direct fill is the fallback for masks that drop keys. */ async function typeInto( m: Match, text: string, expectDigits: boolean, delay: number, ): Promise { - const el = m.frame.locator(SELECTOR).nth(m.candidate.index); - const read = async () => { - const v = await el.inputValue({ timeout: 2000 }); - return expectDigits ? digits(v) : v.trim(); - }; + // A frame that navigated away may now hold someone else's document: never type into it. + if (!sameDocumentOrigin(m)) return false; + const el = fieldOf(m); const want = expectDigits ? digits(text) : text.trim(); await el.click({ timeout: 5000 }); await el.fill("", { timeout: 5000 }).catch(() => undefined); await el.pressSequentially(text, { delay, timeout: 15000 }); - if ((await read().catch(() => "")) === want) return true; - // Some masks drop keystrokes typed too fast; a direct fill is the fallback. + if ((await readBack(m, expectDigits).catch(() => "")) === want) return true; + if (!sameDocumentOrigin(m)) return false; await el.fill(text, { timeout: 5000 }).catch(() => undefined); - return (await read().catch(() => "")) === want; + return (await readBack(m, expectDigits).catch(() => "")) === want; } -async function chooseOption(m: Match, options: string[]): Promise { - const el = m.frame.locator(SELECTOR).nth(m.candidate.index); - for (const o of options) { - for (const spec of [{ value: o }, { label: o }]) { - try { - const picked = await el.selectOption([spec], { timeout: 2000 }); - // Read the field back after its change handlers ran; a handler may have reset it. - if ( - picked.length && - (await el.inputValue({ timeout: 2000 })) === picked[0] - ) - return true; - } catch { - // try the next spelling - } +/** + * Tries each spelling in turn. With `validate`, a spelling counts only if the field is valid after + * blur and still holds it. Returns the digits or text that stuck, or null. + */ +async function typeFirst( + m: Match, + texts: string[], + expectDigits: boolean, + validate: boolean, + delay: number, +): Promise { + for (const text of texts) { + const want = expectDigits ? digits(text) : text.trim(); + if (!(await typeInto(m, text, expectDigits, delay).catch(() => false))) + continue; + if (!validate) return want; + if (await invalid(m)) continue; + // A blur handler may clear or rewrite the field. + if ((await readBack(m, expectDigits).catch(() => "")) === want) return want; + } + return null; +} + +/** Picks the first option that matches a spelling and survives the select's change handlers. */ +async function chooseOption( + m: Match, + spellings: string[], +): Promise { + const el = fieldOf(m); + const options = await el + .evaluate((e) => + Array.from(e.options ?? []).map((o) => [o.value, o.text.trim()]), + ) + .catch(() => [] as string[][]); + const lower = (s: string) => s.toLowerCase(); + for (const s of spellings) { + const hit = options.find( + ([value, text]) => lower(value) === lower(s) || lower(text) === lower(s), + ); + if (!hit) continue; + try { + const picked = await el.selectOption([{ value: hit[0] }], { + timeout: 2000, + }); + // Read the field back after its change handlers ran; a handler may have reset it. + if ( + picked.length && + (await el.inputValue({ timeout: 2000 })) === picked[0] + ) + return picked[0]; + } catch { + // try the next spelling } } - return false; + return null; +} + +/** Spellings of the expiry month an `