diff --git a/.changeset/browser-pay-fill-card.md b/.changeset/browser-pay-fill-card.md new file mode 100644 index 000000000..a051facb8 --- /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, never types into a field whose name or id names an address or contact part unless its `autocomplete` says it is a card field (a billing- or shipping-prefixed field counts when its name or id names a card field), counts a bare `number`/`name` field only inside a card iframe on another origin (so on the page itself an unrecognised number field is reported missing, not guessed at), 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 697752587..580bf2359 100644 --- a/packages/browser-pay/README.md +++ b/packages/browser-pay/README.md @@ -13,6 +13,42 @@ Browser Pay for Sapiom Pay. The agent types a governance placeholder into checko 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 { + // `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. Without `autocomplete`, a field whose name or id names an address or contact part (`street`, `cardholder_phone`) is never a card field; one that names only a form section (`billing_number`) is a card field only when its name or id also names a card field (`billing_card_number`); and a field named only `number` or `name` counts only inside a card iframe on another origin; on the page itself such a field is reported missing rather than guessed at. 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; 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 `POST /v1/transactions/{transactionId}/payment/relay` with `x-api-key`. `transactionId` is only in the path. The JSON body is: @@ -140,7 +176,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..f544f104d --- /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) { + // Never press Pay half-filled. Read the purchase before retrying the fill or cancelling. + 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..286d7d3a4 --- /dev/null +++ b/packages/browser-pay/src/fill-card.integration.test.ts @@ -0,0 +1,880 @@ +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", + ), + // Like Shopify's card vault: every card input is in the frame, only one is on screen. + "/vault/number": `Field container for: Card number + + + +`, + // A copy parked to the right, where scrolling sideways could reach it, before the real input. + "/vault/right": `Field container for: Card number + +`, + // One frame with stacked fields, shorter than its content, so expiry and CVC start below its fold. + "/card-stack": `Card details + + +`, + // A copy parked below the frame's fold, before the real input that is in view. + "/vault/below": `Field container for: Card number + +`, + // A card-number input at the top of its own frame; used where the frame sits below the page's fold. + "/lone-number": `Card +`, + // A scrollbox whose real input sits below its fold, followed closely by a duplicate. + "/box-card": `Card +
+
+ + +
+
+ +`, + // The real input is bare `number`; a stronger-attributed cc-number copy sits below the fold. + "/vault/strong-copy": `Field container for: Card number + +`, + // A payment frame with a visible billing house number above its below-fold card number. + "/vault/billing": `Secure payment input frame + + + +`, + // A card frame whose only number field is a billing number labelled just "Number". + "/vault/billing-id": `Secure payment input frame + + +`, + // The real input is a genuinely bare `number`; a cc-number copy sits below the fold before it. + "/vault/bare-real": `Field container for: Card number + +`, + // A payment frame with a visible purchase-order number above its below-fold card number. + "/vault/po": `Secure payment input frame + + + +`, + "/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}`, + "/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} + + + +`, + "/four-digit": `Checkout + + + +`, + "/pattern-four": `Checkout + + +`, + "/srcdoc": `Checkout +`, + "/mmyy-pattern": `Checkout + + + +`, + "/yy-placeholder-four-pattern": `Checkout + + +`, + "/autofill-copies": `Checkout + +${frame("/shopify/expiry")}${frame("/shopify/cvc")}`, + "/below-fold": `Checkout + +
+ + +`, + "/month-names": `Checkout + + + +`, + "/compact": `Checkout + + +`, + "/copy-right": `Checkout + +${frame("/shopify/expiry")}${frame("/shopify/cvc")}`, + "/smooth": `Checkout + +
+ + +`, + "/stacked-frame": `Checkout +`, + "/copy-below": `Checkout + +${frame("/shopify/expiry")}${frame("/shopify/cvc")}`, + "/form-then-frame": `Checkout +
+ + + +
+`, + "/scrollbox-frame": `Checkout +`, + "/vault-below-fold": `Checkout +
+ +${frame("/shopify/expiry")}${frame("/shopify/cvc")}`, + "/address-number": `Checkout + +
+ + +`, + "/strong-copy": `Checkout + +${frame("/shopify/expiry")}${frame("/shopify/cvc")}`, + // QA's page (Baptiste, Nov 8): a billing "Number" before a card number labelled in another + // language with no autocomplete, on the page's own origin. + "/billing-number": `Checkout + + + +`, + "/billing-card-number": `Checkout + + +`, + // The cardholder's address before the cardholder's name, neither with autocomplete. + "/cardholder-address": `Checkout + + + + + +`, + // A sandboxed frame replacing its own `parent` global to look same-origin. + "/sandboxed-spoof": `Checkout +`, + // Month names over zero-based values: March is value 2, and April's value is 3. + "/zero-based-months": `Checkout + + + +`, + "/billing-id-frame": `Checkout +`, + "/billing-frame": `Checkout +`, + "/bare-real": `Checkout + +${frame("/shopify/expiry")}${frame("/shopify/cvc")}`, + "/po-frame": `Checkout +`, + "/sandboxed": `Checkout +`, +}; + +/** The same lookup as the interceptor tests: CI has system Chrome, not Playwright's bundled build. */ +function findChromium(): string | undefined { + const candidates = [ + process.env.CHROME_PATH, + "/usr/local/bin/google-chrome", + "/usr/bin/google-chrome", + "/usr/bin/chromium", + "/usr/bin/chromium-browser", + ].filter((candidate): candidate is string => Boolean(candidate)); + const found = candidates.find((candidate) => existsSync(candidate)); + if (found) return found; + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const path = require("playwright").chromium.executablePath() as string; + return path && existsSync(path) ? path : undefined; + } catch { + return undefined; + } +} + +const chromiumPath = findChromium(); +if (!chromiumPath) { + process.stderr.write( + "browser-pay: skipping fillCard integration tests. Install Google Chrome or Chromium, or set CHROME_PATH.\n", + ); +} + +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)); + }); +} + +(chromiumPath ? describe : describe.skip)( + "fillCard (Chromium, cross-origin card iframes)", + () => { + // A test types into real frames; on a shared CI runner the first one after launch can take >5s. + jest.setTimeout(30_000); + + 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]); + // Same host, different hostname spelling: localhost vs 127.0.0.1 are different origins. + 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({ executablePath: chromiumPath }); + }, 60_000); + + afterAll(async () => { + await browser?.close(); + // Keep-alive sockets from the frames hold the servers (and Jest) open after close(). + for (const server of [top, frames, other]) { + server?.closeAllConnections(); + server?.close(); + } + }, 30_000); + + 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 fill(page); + expect(result).toMatchObject({ + ok: true, + missing: [], + unconfirmed: [], + untrusted: [], + }); + 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).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 fill(page); + 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 fill(page); + 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 fill(page); + 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 fill(page); + 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 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("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("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("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("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("ignores an autofill copy parked to the right of a card-vault frame", async () => { + const page = await open("/copy-right"); + const result = await fill(page); + expect(result.ok).toBe(true); + const vault = page + .frames() + .find((f) => f.url().includes("/vault/right"))!; + expect(await vault.locator("#real").inputValue()).toBe(CARD.number); + expect(await vault.locator("#copy").inputValue()).toBe(""); + await page.close(); + }); + + it("fills below-the-fold fields on a page with smooth scrolling", async () => { + const page = await open("/smooth"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#ccnum").inputValue()).toBe(CARD.number); + await page.close(); + }); + + it("stops typing into a srcdoc card frame that navigated to a data: URL", async () => { + const page = await open("/srcdoc"); + // Navigate the frame away the moment the number is typed; expiry and CVC must not follow it. + await page.evaluate(`(() => { + const f = document.querySelector("iframe"); + f.contentDocument.querySelector("[autocomplete=cc-number]").addEventListener("input", () => { + f.removeAttribute("srcdoc"); + f.src = "data:text/html,"; + }); + })()`); + const result = await fill(page, { timeoutMs: 1000 }); + expect(page.frames()[1].url()).toMatch(/^data:/); + expect(result.ok).toBe(false); + expect(result.filled).not.toContain("cvc"); + await page.close(); + }); + + it("prefers the in-view field over an autofill copy parked below a frame's fold", async () => { + const page = await open("/copy-below"); + const result = await fill(page); + expect(result.ok).toBe(true); + const vault = page + .frames() + .find((f) => f.url().includes("/vault/below"))!; + expect(await vault.locator("#real").inputValue()).toBe(CARD.number); + expect(await vault.locator("#copy").inputValue()).toBe(""); + await page.close(); + }); + + it("prefers a vault frame's in-view field over its copy when the frame is below the page fold", async () => { + const page = await open("/vault-below-fold"); + const result = await fill(page); + expect(result.ok).toBe(true); + const vault = page + .frames() + .find((f) => f.url().includes("/vault/below"))!; + expect(await vault.locator("#real").inputValue()).toBe(CARD.number); + expect(await vault.locator("#copy").inputValue()).toBe(""); + await page.close(); + }); + + it("prefers a vault frame's visible field over a stronger-attributed copy below its fold", async () => { + const page = await open("/strong-copy"); + const result = await fill(page); + expect(result.ok).toBe(true); + const vault = page + .frames() + .find((f) => f.url().includes("/vault/strong-copy"))!; + expect(await vault.locator("#real").inputValue()).toBe(CARD.number); + expect(await vault.locator("#copy").inputValue()).toBe(""); + await page.close(); + }); + + it("prefers a vault frame's visible bare number over a cc-number copy below its fold", async () => { + const page = await open("/bare-real"); + const result = await fill(page); + expect(result.ok).toBe(true); + const vault = page + .frames() + .find((f) => f.url().includes("/vault/bare-real"))!; + expect(await vault.locator("#real").inputValue()).toBe(CARD.number); + expect(await vault.locator("#copy").inputValue()).toBe(""); + await page.close(); + }); + + it("keeps a payment frame's purchase-order number out of the card number", async () => { + const page = await open("/po-frame"); + const result = await fill(page); + expect(result.ok).toBe(true); + const vault = page.frames().find((f) => f.url().includes("/vault/po"))!; + expect(await vault.locator("#ccnum").inputValue()).toBe(CARD.number); + expect(await vault.locator("#po").inputValue()).toBe(""); + await page.close(); + }); + + it("keeps a payment frame's visible billing house number out of the card number", async () => { + const page = await open("/billing-frame"); + const result = await fill(page); + expect(result.ok).toBe(true); + const vault = page + .frames() + .find((f) => f.url().includes("/vault/billing"))!; + expect(await vault.locator("#ccnum").inputValue()).toBe(CARD.number); + expect(await vault.locator("#house").inputValue()).toBe(""); + await page.close(); + }); + + it("keeps a visible address field named number out of the card number", async () => { + const page = await open("/address-number"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#ccnum").inputValue()).toBe(CARD.number); + expect(await page.locator("#house").inputValue()).toBe(""); + await page.close(); + }); + + it("reports the number missing instead of typing it into a billing Number on the page", async () => { + const page = await open("/billing-number"); + const result = await fill(page, { timeoutMs: 1000 }); + expect(result).toMatchObject({ ok: false, missing: ["number"] }); + expect(result.filled).not.toContain("number"); + expect(await page.locator("#billing_number").inputValue()).toBe(""); + expect(await page.locator("#kn").inputValue()).toBe(""); + await page.close(); + }); + + it("never types the number into a field whose name or id says billing, even in a card frame", async () => { + const page = await open("/billing-id-frame"); + const result = await fill(page, { timeoutMs: 1000 }); + expect(result).toMatchObject({ ok: false, missing: ["number"] }); + expect(await valueIn(page, "/vault/billing-id", "#billing_number")).toBe( + "", + ); + await page.close(); + }); + + it("fills a card number whose billing-prefixed name says it is the card number", async () => { + const page = await open("/billing-card-number"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#billing_card_number").inputValue()).toBe( + CARD.number, + ); + await page.close(); + }); + + it("types the name into the name field, never a cardholder address or phone field", async () => { + const page = await open("/cardholder-address"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#cardholder_name").inputValue()).toBe( + CARD.name, + ); + expect( + await page.locator("#billing_cardholder_address").inputValue(), + ).toBe(""); + expect(await page.locator("#cardholder_phone").inputValue()).toBe(""); + await page.close(); + }); + + it("never trusts a sandboxed frame that replaces its own parent global", async () => { + const page = await open("/sandboxed-spoof"); + const result = await fill(page, { timeoutMs: 1000 }); + expect(result).toMatchObject({ + ok: false, + filled: [], + untrusted: ["null"], + }); + await page.close(); + }); + + it("picks the month by its name when option values count from zero", async () => { + const page = await open("/zero-based-months"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#m").inputValue()).toBe("2"); + await page.close(); + }); + + it("prefers the page's own below-fold form over a later off-screen iframe", async () => { + const page = await open("/form-then-frame"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await page.locator("#ccnum").inputValue()).toBe(CARD.number); + expect(await valueIn(page, "/lone-number", "#other")).toBe(""); + await page.close(); + }); + + it("measures a duplicate inside a scrollbox from the box's original position", async () => { + const page = await open("/scrollbox-frame"); + const result = await fill(page); + expect(result.ok).toBe(true); + expect(await valueIn(page, "/box-card", "#real")).toBe(CARD.number); + expect(await valueIn(page, "/box-card", "#dup")).toBe(""); + await page.close(); + }); + + it("fills stacked fields below the fold of a short card frame", async () => { + const page = await open("/stacked-frame"); + const result = await fill(page); + expect(result).toMatchObject({ + ok: true, + filled: ["number", "expiry", "cvc"], + }); + expect(await valueIn(page, "/card-stack", "[name=cvc]")).toBe(CARD.cvc); + 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 }); + 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 new file mode 100644 index 000000000..ab0511a4a --- /dev/null +++ b/packages/browser-pay/src/fill-card.ts @@ -0,0 +1,854 @@ +/** + * 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>; + /** + * 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 { + /** 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; + /** + * 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. */ +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; + boundingBox(): Promise<{ + x: number; + y: number; + width: number; + height: number; + } | null>; + 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; + options?: ArrayLike<{ value: string; text: string }>; +} + +/** The parts of a Playwright `ElementHandle` for an `