From 961e27cbf5c02db942228fc3bfb4aad439b56f1e Mon Sep 17 00:00:00 2001 From: Ewan Date: Tue, 17 Nov 2026 01:48:37 +0100 Subject: [PATCH 1/6] feat(browser-pay): pay Adyen secured-fields checkouts via BT re-encryption (SAP-5180) Adyen secured fields encrypt the typed card in Adyen's iframes, so the placeholder never appears in the payment request and cannot be relayed. The interceptor now holds a JSON request carrying paymentMethod.encryptedCardNumber (merchant /payments or Adyen /sessions/{id}/payments), asks POST /v1/transactions/{id}/payment/adyen/encrypt for the authorized card's own encrypted fields, swaps the four encrypted* fields and continues the request. Client key: secured-field iframe URL, else page config. Gated by the backend: its adyen_encryption_not_enabled answer, a relay without adyenEncrypt, or disableAdyenEncryption fail the payment closed (adyen_not_enabled); the stand-in ciphertext is never sent. fillCard takes the handle as `adyen` and types nothing on Adyen secured fields unless the backend returned fields (used once for the payment). Co-Authored-By: Claude Opus 5.5 --- .changeset/browser-pay-adyen-reencrypt.md | 5 + packages/browser-pay/README.md | 14 +- packages/browser-pay/src/contract.ts | 53 ++ packages/browser-pay/src/detect.test.ts | 110 +++- packages/browser-pay/src/detect.ts | 133 ++++ .../browser-pay/src/fill-card.adyen.test.ts | 246 +++++++ packages/browser-pay/src/fill-card.ts | 76 +++ packages/browser-pay/src/index.ts | 11 +- .../browser-pay/src/interceptor.adyen.test.ts | 602 ++++++++++++++++++ .../src/interceptor.integration.test.ts | 77 +++ packages/browser-pay/src/interceptor.ts | 306 ++++++++- packages/browser-pay/src/relay.test.ts | 129 ++++ packages/browser-pay/src/relay.ts | 131 ++-- packages/browser-pay/test/cdp-stub.ts | 142 +++++ 14 files changed, 1980 insertions(+), 55 deletions(-) create mode 100644 .changeset/browser-pay-adyen-reencrypt.md create mode 100644 packages/browser-pay/src/fill-card.adyen.test.ts create mode 100644 packages/browser-pay/src/interceptor.adyen.test.ts create mode 100644 packages/browser-pay/test/cdp-stub.ts diff --git a/.changeset/browser-pay-adyen-reencrypt.md b/.changeset/browser-pay-adyen-reencrypt.md new file mode 100644 index 000000000..a4efac6b4 --- /dev/null +++ b/.changeset/browser-pay-adyen-reencrypt.md @@ -0,0 +1,5 @@ +--- +"@sapiom/browser-pay": minor +--- + +Pay Adyen secured-fields checkouts by re-encrypting the card in the card vault (SAP-5180). The interceptor holds an outgoing Adyen payment (`paymentMethod.encryptedCardNumber`, on the merchant's `/payments` call or Adyen's `/sessions/{id}/payments`), asks `POST /v1/transactions/{id}/payment/adyen/encrypt` for the card's own encrypted fields, swaps the four `encrypted*` fields and sends the request on. It runs only when the backend answers with fields: its `adyen_encryption_not_enabled` answer, a relay without `adyenEncrypt`, or `disableAdyenEncryption: true` fail the payment closed (`adyen_not_enabled`). `fillCard(page, card, { adyen: handle })` asks first and types nothing on Adyen secured fields unless the payment will be re-encrypted (`blocked`). diff --git a/packages/browser-pay/README.md b/packages/browser-pay/README.md index 580bf2359..6663de243 100644 --- a/packages/browser-pay/README.md +++ b/packages/browser-pay/README.md @@ -49,6 +49,16 @@ The result is `{ ok, filled, missing, unconfirmed, origins, untrusted }`. `ok` i 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. +## Adyen secured fields + +Adyen secured fields encrypt the typed card inside Adyen's iframes, so the placeholder never shows in the payment request. When the backend has Adyen encryption switched on, the interceptor holds any request whose JSON body has a string `paymentMethod.encryptedCardNumber` (the merchant's own `/payments` call, or Adyen's `/sessions/{id}/payments`), asks `POST /v1/transactions/{transactionId}/payment/adyen/encrypt` with `x-api-key` and `{ "injectionRef", "clientKey", "pageOrigin" }` for the authorized card's own `encryptedCardNumber`, `encryptedExpiryMonth`, `encryptedExpiryYear` and `encryptedSecurityCode`, replaces those four fields and sends the request on. Every other key is kept. The event is `reencrypted`. + +The client key comes from the secured-field iframe URL (`…/securedfields/{clientKey}/{version}/securedFields.html`), else from the page (`#clientKey`, `data-client-key`, or a `clientKey: "test_…"` literal in an inline script). Two different keys on one page give none. + +It is off unless the backend says otherwise. A payment fails closed, and the placeholder's ciphertext is never sent, with `adyen_not_enabled` when the backend answers `adyen_encryption_not_enabled` (as `code` or `reason`), when the relay has no `adyenEncrypt`, or when `AttachOptions.disableAdyenEncryption` is `true`; with `adyen_client_key` when no single key is found; and with `adyen_encrypt` when the call fails or outlasts `attemptTimeoutMs`. No option turns it on past the backend. + +Pass the interceptor handle to `fillCard` so it asks before typing: `fillCard(page, card, { adyen: handle })`. On a page with Adyen secured-field iframes it types nothing, and returns `ok: false` with `blocked` (`adyen_not_enabled`, `adyen_client_key`, or `adyen_encrypt`), unless the backend returned fields; those fields are then used once for the payment, within 10 minutes. Without `adyen` it never types into Adyen secured fields. The placeholder typed into the iframes must be the authorized card's brand, since Adyen reads the brand from what was typed. + ## Relay contract `POST /v1/transactions/{transactionId}/payment/relay` with `x-api-key`. `transactionId` is only in the path. The JSON body is: @@ -168,7 +178,7 @@ const handle = await attachInterceptor(cdpUrl, { }); ``` -The relay records every request it is asked to send (host, path, header names, the body's shape and where the card fields were, never a value). It refuses `destination_not_allowed` for a URL that isn't https to a public host or a method other than POST, and `card_fields_invalid` when the placeholder's number isn't in the body exactly once, a card field can't be told apart from another holding the same value, or a card number shows up in the URL or headers. A form that encrypts card fields in the page (Adyen client-side encryption and similar) never shows the placeholder, so it can't be paid this way. A provider may decline a card sent from the card vault's servers rather than the user's browser. +The relay records every request it is asked to send (host, path, header names, the body's shape and where the card fields were, never a value). It refuses `destination_not_allowed` for a URL that isn't https to a public host or a method other than POST, and `card_fields_invalid` when the placeholder's number isn't in the body exactly once, a card field can't be told apart from another holding the same value, or a card number shows up in the URL or headers. A form that encrypts card fields in the page never shows the placeholder, so it can't be relayed; Adyen secured fields are paid by re-encryption instead (see below). A provider may decline a card sent from the card vault's servers rather than the user's browser. `baseUrl` must be https, or plain http to a loopback host (`localhost`, `*.localhost`, `127.0.0.1`, `[::1]`). Any other `http://` URL makes `httpPaymentRelay` throw a `CredentialChannelError` before a request is sent. On a trusted private network, set `SAPIOM_ALLOW_INSECURE_HTTP=1`. Redirects from the relay are always refused. @@ -186,6 +196,6 @@ Captcha widgets, extension pages, and workers are not paused. A blank iframe, in Child iframes are auto-attached with `waitForDebuggerOnStart`. `Fetch.enable` runs on each child session before it is resumed. An iframe that already exists is attached before `attachInterceptor` resolves. A paused request whose CDP session was never attached is failed. -`detach()` fails in-flight paused requests before it disables Fetch. A process crash or a dropped CDP socket can still let Chrome continue those requests. WebSocket frames, client-side-encrypted card payloads, and worklet targets are not visible to this check. +`detach()` fails in-flight paused requests before it disables Fetch. A process crash or a dropped CDP socket can still let Chrome continue those requests. WebSocket frames, client-side-encrypted card payloads other than Adyen's, and worklet targets are not visible to this check. `examples/attach.ts` is the agent-side script. It is not published. diff --git a/packages/browser-pay/src/contract.ts b/packages/browser-pay/src/contract.ts index 7e107bf78..42ae57510 100644 --- a/packages/browser-pay/src/contract.ts +++ b/packages/browser-pay/src/contract.ts @@ -111,3 +111,56 @@ export function parseRelayResponse(value: unknown): RelayResponse { }, }; } + +/** The four fields Adyen secured fields put on `paymentMethod`, each one encrypted blob. */ +export const ADYEN_ENCRYPTED_FIELDS = [ + "encryptedCardNumber", + "encryptedExpiryMonth", + "encryptedExpiryYear", + "encryptedSecurityCode", +] as const; + +export type AdyenEncryptedField = (typeof ADYEN_ENCRYPTED_FIELDS)[number]; + +export type AdyenEncryptedFields = Record; + +export interface AdyenEncryptRequest { + injectionRef: string; + /** The merchant's Adyen client key, read from the page. The backend fetches the public key from Adyen itself. */ + clientKey: string; + pageOrigin: string; +} + +/** + * The backend's typed answer when Adyen card encryption is switched off for + * this deployment. It arrives as `code` (an error body) or `reason`. + */ +export const ADYEN_ENCRYPTION_NOT_ENABLED = "adyen_encryption_not_enabled"; + +export type AdyenEncryptResult = + | { outcome: "encrypted"; fields: AdyenEncryptedFields } + | { outcome: "not_enabled" }; + +export function isAdyenNotEnabled(value: unknown): boolean { + return ( + isRecord(value) && + (value.code === ADYEN_ENCRYPTION_NOT_ENABLED || + value.reason === ADYEN_ENCRYPTION_NOT_ENABLED) + ); +} + +export function parseAdyenEncryptResponse(value: unknown): AdyenEncryptResult { + if (isAdyenNotEnabled(value)) return { outcome: "not_enabled" }; + if (!isRecord(value)) { + throw new Error("Adyen re-encryption returned an unreadable response"); + } + const fields = {} as AdyenEncryptedFields; + for (const field of ADYEN_ENCRYPTED_FIELDS) { + const blob = value[field]; + if (typeof blob !== "string" || blob.length === 0) { + throw new Error("Adyen re-encryption returned an unreadable response"); + } + fields[field] = blob; + } + return { outcome: "encrypted", fields }; +} diff --git a/packages/browser-pay/src/detect.test.ts b/packages/browser-pay/src/detect.test.ts index d351b7816..fe721969e 100644 --- a/packages/browser-pay/src/detect.test.ts +++ b/packages/browser-pay/src/detect.test.ts @@ -1,4 +1,11 @@ -import { redactHeld, textHoldsPlaceholderNumber } from "./detect"; +import { + adyenClientKeyFromFrameUrl, + isAdyenSecuredFieldsFrameUrl, + isAdyenSecuredFieldsPayment, + redactHeld, + textHoldsPlaceholderNumber, + withAdyenEncryptedFields, +} from "./detect"; const NUMBER = "4242424242424242"; @@ -37,3 +44,104 @@ describe("redactHeld", () => { expect(textHoldsPlaceholderNumber(url, NUMBER)).toBe(false); }); }); + +describe("adyenClientKeyFromFrameUrl", () => { + it("reads the key from a secured-field iframe on an adyen.com host", () => { + expect( + adyenClientKeyFromFrameUrl( + "https://checkoutshopper-test.adyen.com/checkoutshopper/securedfields/test_ABC123XYZ/6.4.1/securedFields.html?type=card&d=aHR0cA", + ), + ).toBe("test_ABC123XYZ"); + expect( + adyenClientKeyFromFrameUrl( + "https://checkoutshopper-live-us.adyen.com/checkoutshopper/securedfields/live_Q1W2E3/5.0.0/securedFields.html", + ), + ).toBe("live_Q1W2E3"); + }); + + it("ignores other hosts, plain http, other paths and malformed keys", () => { + for (const url of [ + "https://adyen.com.evil.example/checkoutshopper/securedfields/test_ABC/6.4.1/securedFields.html", + "https://evil-adyen.com/checkoutshopper/securedfields/test_ABC/6.4.1/securedFields.html", + "http://checkoutshopper-test.adyen.com/checkoutshopper/securedfields/test_ABC/6.4.1/securedFields.html", + "https://checkoutshopper-test.adyen.com/checkoutshopper/v1/clientKeys/test_ABC", + "https://checkoutshopper-test.adyen.com/checkoutshopper/securedfields/test_abc/6.4.1/securedFields.html", + "https://checkoutshopper-test.adyen.com/checkoutshopper/securedfields/pub.v2.ABC/6.4.1/securedFields.html", + "not a url", + "", + ]) { + expect(adyenClientKeyFromFrameUrl(url)).toBeUndefined(); + } + }); + it("tells a secured-field iframe apart from other frames even without a readable key", () => { + expect( + isAdyenSecuredFieldsFrameUrl( + "https://checkoutshopper-live.adyen.com/checkoutshopper/securedfields/pub.v2.ABC/6.4.1/securedFields.html", + ), + ).toBe(true); + for (const url of [ + "https://js.stripe.com/v3/elements-inner-card.html", + "https://checkoutshopper-test.adyen.com/checkoutshopper/v3/analytics", + "http://checkoutshopper-test.adyen.com/checkoutshopper/securedfields/test_ABC/6.4.1/securedFields.html", + "https://adyen.com.evil.example/checkoutshopper/securedfields/test_ABC/6.4.1/securedFields.html", + "https://shop.example/checkout", + ]) { + expect(isAdyenSecuredFieldsFrameUrl(url)).toBe(false); + } + }); +}); + +describe("Adyen secured-fields payment bodies", () => { + const BODY = JSON.stringify({ + amount: { currency: "EUR", value: 1000 }, + reference: "order-1", + paymentMethod: { + type: "scheme", + holderName: "J. Smith", + encryptedCardNumber: "eyJ.standin-number", + encryptedExpiryMonth: "eyJ.standin-month", + encryptedExpiryYear: "eyJ.standin-year", + encryptedSecurityCode: "eyJ.standin-cvc", + checkoutAttemptId: "attempt-1", + }, + browserInfo: { userAgent: "x" }, + }); + + it("recognises only JSON with paymentMethod.encryptedCardNumber", () => { + expect(isAdyenSecuredFieldsPayment(BODY)).toBe(true); + for (const body of [ + "", + "encryptedCardNumber=eyJ", + JSON.stringify({ encryptedCardNumber: "eyJ" }), + JSON.stringify({ paymentMethod: { encryptedCardNumber: "" } }), + JSON.stringify({ paymentMethod: { encryptedCardNumber: 1 } }), + JSON.stringify({ paymentMethod: { type: "scheme" } }), + JSON.stringify([{ paymentMethod: { encryptedCardNumber: "eyJ" } }]), + ]) { + expect(isAdyenSecuredFieldsPayment(body)).toBe(false); + } + }); + + it("replaces the four encrypted fields and keeps everything else", () => { + const swapped = JSON.parse( + withAdyenEncryptedFields(BODY, { + encryptedCardNumber: "eyJ.real-number", + encryptedExpiryMonth: "eyJ.real-month", + encryptedExpiryYear: "eyJ.real-year", + encryptedSecurityCode: "eyJ.real-cvc", + }), + ); + const original = JSON.parse(BODY); + expect(swapped).toStrictEqual({ + ...original, + paymentMethod: { + ...original.paymentMethod, + encryptedCardNumber: "eyJ.real-number", + encryptedExpiryMonth: "eyJ.real-month", + encryptedExpiryYear: "eyJ.real-year", + encryptedSecurityCode: "eyJ.real-cvc", + }, + }); + expect(Object.keys(swapped)).toStrictEqual(Object.keys(original)); + }); +}); diff --git a/packages/browser-pay/src/detect.ts b/packages/browser-pay/src/detect.ts index 5c6b0d2dc..2d35a02f6 100644 --- a/packages/browser-pay/src/detect.ts +++ b/packages/browser-pay/src/detect.ts @@ -1,3 +1,6 @@ +import type { AdyenEncryptedFields } from "./contract.js"; +import { isRecord } from "./guards.js"; + export interface HeldPlaceholder { number: string; injectionRef: string; @@ -112,3 +115,133 @@ export function redactHeld(value: string, number: string): string { if (!digits) return value.split(number).join("••••"); return maskHeldSpans(value, digits); } + +const ADYEN_CLIENT_KEY = /^(test|live)_[A-Z0-9]+$/; +const ADYEN_SECURED_FIELDS_PATH = + /\/securedfields\/([^/]+)\/[^/]+\/securedFields\.html$/; + +/** An Adyen client key: `test_` or `live_` and upper-case letters and digits. */ +export function isAdyenClientKey(value: unknown): value is string { + return typeof value === "string" && ADYEN_CLIENT_KEY.test(value); +} + +/** + * The client key in an Adyen secured-field iframe URL + * (`https://checkoutshopper-test.adyen.com/checkoutshopper/securedfields/{clientKey}/{version}/securedFields.html`), + * or `undefined` for any other URL. + */ +export function adyenClientKeyFromFrameUrl(url: string): string | undefined { + const parsed = adyenSecuredFieldsUrl(url); + if (!parsed) return undefined; + const match = ADYEN_SECURED_FIELDS_PATH.exec(parsed.pathname); + const key = match ? safeDecode(match[1]) : undefined; + return isAdyenClientKey(key) ? key : undefined; +} + +/** + * True for an Adyen secured-field iframe URL (https, an `adyen.com` host, a + * `/securedfields/` path), whether or not its client key can be read. + */ +export function isAdyenSecuredFieldsFrameUrl(url: string): boolean { + return adyenSecuredFieldsUrl(url) !== undefined; +} + +function adyenSecuredFieldsUrl(url: string): URL | undefined { + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return undefined; + } + const host = parsed.hostname.toLowerCase(); + if (parsed.protocol !== "https:") return undefined; + if (host !== "adyen.com" && !host.endsWith(".adyen.com")) return undefined; + return parsed.pathname.includes("/securedfields/") ? parsed : undefined; +} + +function safeDecode(value: string): string | undefined { + try { + return decodeURIComponent(value); + } catch { + return undefined; + } +} + +/** + * Evaluated in the checkout page when no secured-field iframe was seen as a + * target: the key in a secured-field iframe `src` in the DOM, then adyen-web + * config the page renders (`#clientKey`, `data-client-key`, or a + * `clientKey: "test_…"` literal in an inline script). Returns a string or + * `null`; the caller validates it. + */ +export const ADYEN_DOM_CLIENT_KEY_EXPRESSION = `(() => { + const shape = ${ADYEN_CLIENT_KEY.toString()}; + const ok = (value) => { + const text = typeof value === "string" ? value.trim() : ""; + return shape.test(text) ? text : null; + }; + for (const frame of document.querySelectorAll("iframe[src*='securedfields']")) { + const match = ${ADYEN_SECURED_FIELDS_PATH.toString()}.exec(new URL(frame.src, location.href).pathname); + const key = match && ok(decodeURIComponent(match[1])); + if (key) return key; + } + const element = document.getElementById("clientKey"); + const fromElement = element && ok(element.value || element.textContent); + if (fromElement) return fromElement; + for (const node of document.querySelectorAll("[data-client-key],[data-clientkey]")) { + const key = ok(node.getAttribute("data-client-key") || node.getAttribute("data-clientkey")); + if (key) return key; + } + for (const script of document.querySelectorAll("script:not([src])")) { + const match = /clientKey["']?\\s*[:=]\\s*["']((?:test|live)_[A-Z0-9]+)["']/.exec(script.textContent || ""); + if (match) return match[1]; + } + return null; +})()`; + +/** + * True when the body is JSON whose top-level `paymentMethod.encryptedCardNumber` + * is a non-empty string: an Adyen secured-fields payment, on the merchant's + * own `/payments` call or on Adyen's `/sessions/{id}/payments`. + */ +export function isAdyenSecuredFieldsPayment(body: string): boolean { + return adyenPaymentMethod(parseJson(body)) !== undefined; +} + +/** + * The body with the four `paymentMethod.encrypted*` fields replaced. Every + * other key keeps its value and order. + */ +export function withAdyenEncryptedFields( + body: string, + fields: AdyenEncryptedFields, +): string { + const parsed = parseJson(body); + const method = adyenPaymentMethod(parsed); + if (!method || !isRecord(parsed)) { + throw new Error("Not an Adyen secured-fields payment body"); + } + return JSON.stringify({ + ...parsed, + paymentMethod: { ...method, ...fields }, + }); +} + +function parseJson(body: string): unknown { + try { + return JSON.parse(body); + } catch { + return undefined; + } +} + +function adyenPaymentMethod( + value: unknown, +): Record | undefined { + if (!isRecord(value) || !isRecord(value.paymentMethod)) return undefined; + const method = value.paymentMethod; + return typeof method.encryptedCardNumber === "string" && + method.encryptedCardNumber.length > 0 + ? method + : undefined; +} diff --git a/packages/browser-pay/src/fill-card.adyen.test.ts b/packages/browser-pay/src/fill-card.adyen.test.ts new file mode 100644 index 000000000..576ea9e78 --- /dev/null +++ b/packages/browser-pay/src/fill-card.adyen.test.ts @@ -0,0 +1,246 @@ +import { ADYEN_DOM_CLIENT_KEY_EXPRESSION } from "./detect"; +import { + fillCard, + type CardToFill, + type FrameLike, + type LocatorLike, + type PageLike, +} from "./fill-card"; +import type { AdyenGate, AdyenReadiness } from "./interceptor"; + +const CARD: CardToFill = { + number: "4000000000000002", + expMonth: 3, + expYear: 2029, + cvc: "321", +}; + +const PAGE = "https://shop.example/checkout"; +const KEY = "test_FRAMEKEY123"; +const DOM_KEY = "test_DOMKEY456"; +const securedField = (key: string | null, field: string) => + `https://checkoutshopper-test.adyen.com/checkoutshopper/securedfields/${ + key ?? "x" + }/6.4.1/securedFields.html?type=card&d=${field}`; + +/** One visible input per frame, named the way Adyen's secured fields name theirs. */ +function candidate(hint: string) { + return { + index: 0, + tag: "input", + type: "tel", + autocomplete: "", + hints: hint, + ids: "", + label: "", + hit: true, + reachable: false, + maxLength: -1, + placeholder: "", + }; +} + +interface FakePage { + page: PageLike; + /** Every click, fill or keystroke sequence sent to any field. */ + touched: string[]; +} + +function fakePage( + frames: { url: string; hint?: string }[], + domKey: string | null = null, +): FakePage { + const touched: string[] = []; + const built: FrameLike[] = []; + const main: FrameLike = makeFrame(PAGE, undefined); + built.push(main); + for (const frame of frames) built.push(makeFrame(frame.url, frame.hint)); + + function makeFrame(url: string, hint: string | undefined): FrameLike { + let value = ""; + const locator: LocatorLike = { + nth: () => locator, + click: async () => { + touched.push(`click ${hint}`); + }, + fill: async (text) => { + if (text) touched.push(`fill ${hint}`); + value = text; + }, + pressSequentially: async (text) => { + touched.push(`type ${hint}`); + value = text; + }, + press: async () => {}, + inputValue: async () => value, + boundingBox: async () => ({ x: 0, y: 0, width: 10, height: 10 }), + evaluate: async (fn) => + fn({ + validity: { valid: true }, + getAttribute: () => null, + blur: () => {}, + }), + selectOption: async () => [], + }; + return { + url: () => url, + parentFrame: () => (url === PAGE ? null : main), + frameElement: async () => ({ evaluate: async () => false as never }), + locator: () => locator, + evaluate: async (expression: string): Promise => { + if (expression === ADYEN_DOM_CLIENT_KEY_EXPRESSION) { + return (url === PAGE ? domKey : null) as R; + } + if (expression.includes("innerWidth") && !expression.includes("=>")) { + return { w: 1000, h: 800 } as R; + } + return { + title: "", + fields: hint ? [candidate(hint)] : [], + } as R; + }, + }; + } + + return { + page: { frames: () => built, waitForTimeout: async () => {} }, + touched, + }; +} + +const ADYEN_FIELDS = (key: string | null) => [ + { + url: securedField(key, "encryptedCardNumber"), + hint: "encryptedcardnumber", + }, + { + url: securedField(key, "encryptedExpiryDate"), + hint: "encryptedexpirydate", + }, + { + url: securedField(key, "encryptedSecurityCode"), + hint: "encryptedsecuritycode", + }, +]; + +function gate(answer: AdyenReadiness | Error): AdyenGate & { + calls: { clientKey: string; pageOrigin: string }[]; +} { + const calls: { clientKey: string; pageOrigin: string }[] = []; + return { + calls, + async prepareAdyen(input) { + calls.push(input); + if (answer instanceof Error) throw answer; + return answer; + }, + }; +} + +const NOT_TYPED = { + ok: false, + filled: [], + missing: ["number", "expiry", "cvc"], + unconfirmed: [], + origins: {}, + untrusted: [], +}; + +describe("fillCard on Adyen secured fields", () => { + it("types nothing without a gate: Adyen is off by default", async () => { + const { page, touched } = fakePage(ADYEN_FIELDS(KEY)); + const result = await fillCard(page, CARD, { timeoutMs: 50 }); + expect(result).toStrictEqual({ + ...NOT_TYPED, + blocked: "adyen_not_enabled", + }); + expect(touched).toStrictEqual([]); + }); + + it("types nothing when the backend says Adyen encryption is not enabled", async () => { + const { page, touched } = fakePage(ADYEN_FIELDS(KEY)); + const adyen = gate({ enabled: false, reason: "adyen_not_enabled" }); + const result = await fillCard(page, CARD, { timeoutMs: 50, adyen }); + expect(result).toStrictEqual({ + ...NOT_TYPED, + blocked: "adyen_not_enabled", + }); + expect(adyen.calls).toStrictEqual([ + { clientKey: KEY, pageOrigin: "https://shop.example" }, + ]); + expect(touched).toStrictEqual([]); + }); + + it("types the stand-in when the backend will re-encrypt the card", async () => { + const { page, touched } = fakePage(ADYEN_FIELDS(KEY)); + const adyen = gate({ enabled: true }); + const result = await fillCard(page, CARD, { + timeoutMs: 50, + keyDelayMs: 0, + adyen, + }); + expect(result).toMatchObject({ + ok: true, + filled: ["number", "expiry", "cvc"], + }); + expect(result.blocked).toBeUndefined(); + expect(touched).toContain("type encryptedcardnumber"); + expect(adyen.calls).toHaveLength(1); + }); + + it("reads the key from the page's config when the frame URLs carry none", async () => { + const { page } = fakePage(ADYEN_FIELDS(null), DOM_KEY); + const adyen = gate({ enabled: false, reason: "adyen_not_enabled" }); + await fillCard(page, CARD, { timeoutMs: 50, adyen }); + expect(adyen.calls).toStrictEqual([ + { clientKey: DOM_KEY, pageOrigin: "https://shop.example" }, + ]); + }); + + it("stops on two different keys, or none, without asking the backend", async () => { + for (const frames of [ + [ + ...ADYEN_FIELDS(KEY).slice(0, 2), + { + url: securedField("test_OTHERKEY789", "encryptedSecurityCode"), + hint: "encryptedsecuritycode", + }, + ], + ADYEN_FIELDS(null), + ]) { + const { page, touched } = fakePage(frames); + const adyen = gate({ enabled: true }); + const result = await fillCard(page, CARD, { timeoutMs: 50, adyen }); + expect(result.blocked).toBe("adyen_client_key"); + expect(adyen.calls).toHaveLength(0); + expect(touched).toStrictEqual([]); + } + }); + + it("stops when the gate itself fails", async () => { + const { page, touched } = fakePage(ADYEN_FIELDS(KEY)); + const result = await fillCard(page, CARD, { + timeoutMs: 50, + adyen: gate(new Error("boom")), + }); + expect(result.blocked).toBe("adyen_encrypt"); + expect(touched).toStrictEqual([]); + }); + + it("never asks the gate on a page without Adyen secured fields", async () => { + const { page } = fakePage([ + { url: "https://js.stripe.com/v3/elements", hint: "cardnumber" }, + { url: "https://js.stripe.com/v3/exp", hint: "exp-date" }, + { url: "https://js.stripe.com/v3/cvc", hint: "cvc" }, + ]); + const adyen = gate({ enabled: false, reason: "adyen_not_enabled" }); + const result = await fillCard(page, CARD, { + timeoutMs: 50, + keyDelayMs: 0, + adyen, + }); + expect(result.ok).toBe(true); + expect(result.blocked).toBeUndefined(); + expect(adyen.calls).toHaveLength(0); + }); +}); diff --git a/packages/browser-pay/src/fill-card.ts b/packages/browser-pay/src/fill-card.ts index ab0511a4a..445a2d604 100644 --- a/packages/browser-pay/src/fill-card.ts +++ b/packages/browser-pay/src/fill-card.ts @@ -12,6 +12,14 @@ * whether it sent the card. */ +import { + ADYEN_DOM_CLIENT_KEY_EXPRESSION, + adyenClientKeyFromFrameUrl, + isAdyenClientKey, + isAdyenSecuredFieldsFrameUrl, +} from "./detect.js"; +import type { AdyenGate, AdyenReadiness } from "./interceptor.js"; + /** The card to type: the placeholder's fields, plus an optional cardholder name. */ export interface CardToFill { number: string; @@ -53,8 +61,19 @@ export interface FillCardResult { * page's origin, a built-in card-vault origin, nor in `frameOrigins`. */ untrusted: string[]; + /** + * Set when nothing was typed because the form is Adyen secured fields and paying it is not + * possible: `adyen_not_enabled` (switched off, or no `adyen` gate given), `adyen_client_key` + * (the page's client key could not be read), `adyen_encrypt` (the backend failed). + */ + blocked?: FillCardBlock; } +/** Why `fillCard` typed nothing. */ +export type FillCardBlock = + | Extract["reason"] + | "adyen_client_key"; + export interface FillCardOptions { /** Delay between keystrokes, in milliseconds. Defaults to 25. */ keyDelayMs?: number; @@ -65,6 +84,12 @@ export interface FillCardOptions { * list. The page's own origin and the built-in card-vault origins are always allowed. */ frameOrigins?: string[]; + /** + * Asked before typing into Adyen secured fields, which encrypt the card in the page: pass the + * interceptor handle. Without it, or when it answers not enabled, nothing is typed and the + * result names the reason in `blocked`. + */ + adyen?: AdyenGate; } /** The parts of a Playwright `Locator` this helper uses. */ @@ -758,6 +783,19 @@ export async function fillCard( ranked = await rank(page, await scan(page, extra, untrusted)); } + const blocked = await adyenBlock(page, options.adyen); + if (blocked) { + return { + ok: false, + filled: [], + missing: ["number", "expiry", "cvc"], + unconfirmed: [], + origins: {}, + untrusted: [...untrusted], + blocked, + }; + } + const split = ranked.has("expMonth") && ranked.has("expYear"); const mm = two(card.expMonth); const plan: Array<[CardField, (m: Match) => Promise]> = [ @@ -852,3 +890,41 @@ export async function fillCard( untrusted: [...untrusted], }; } + +/** + * For a page with Adyen secured-field iframes: why typing must not start, or `undefined` when the + * gate says the payment will be re-encrypted. Pages without them are never blocked here. + * The client key comes from the iframe URLs; a page config is read only when they carry none. + */ +async function adyenBlock( + page: PageLike, + gate: AdyenGate | undefined, +): Promise { + const frames = page.frames(); + const adyenFrames = frames.filter((f) => + isAdyenSecuredFieldsFrameUrl(f.url()), + ); + if (adyenFrames.length === 0) return undefined; + if (!gate) return "adyen_not_enabled"; + const keys = new Set(); + for (const frame of adyenFrames) { + const key = adyenClientKeyFromFrameUrl(frame.url()); + if (key) keys.add(key); + } + let clientKey: string | undefined; + if (keys.size === 1) clientKey = [...keys][0]; + else if (keys.size === 0) { + const fromDom = await frames[0] + ?.evaluate(ADYEN_DOM_CLIENT_KEY_EXPRESSION) + .catch(() => null); + if (isAdyenClientKey(fromDom)) clientKey = fromDom; + } + // Two different keys on one page: never encrypt the card to a guess. + if (!clientKey) return "adyen_client_key"; + const pageOrigin = originOf(frames[0]?.url() ?? ""); + if (!/^https?:\/\//.test(pageOrigin)) return "adyen_client_key"; + const readiness = await gate + .prepareAdyen({ clientKey, pageOrigin }) + .catch((): AdyenReadiness => ({ enabled: false, reason: "adyen_encrypt" })); + return readiness.enabled ? undefined : readiness.reason; +} diff --git a/packages/browser-pay/src/index.ts b/packages/browser-pay/src/index.ts index a68f0d2bb..2403b7150 100644 --- a/packages/browser-pay/src/index.ts +++ b/packages/browser-pay/src/index.ts @@ -1,5 +1,7 @@ export { attachInterceptor } from "./interceptor.js"; export type { + AdyenGate, + AdyenReadiness, AttachOptions, FailureReason, InterceptorEvent, @@ -13,6 +15,7 @@ export { fillCard } from "./fill-card.js"; export type { CardField, CardToFill, + FillCardBlock, FillCardOptions, FillCardResult, FrameLike, @@ -27,7 +30,13 @@ export type { RelayCallOptions, } from "./relay.js"; -export type { RelayRequest, RelayResponse } from "./contract.js"; +export type { + AdyenEncryptedFields, + AdyenEncryptRequest, + AdyenEncryptResult, + RelayRequest, + RelayResponse, +} from "./contract.js"; export type { HeldPlaceholder } from "./detect.js"; diff --git a/packages/browser-pay/src/interceptor.adyen.test.ts b/packages/browser-pay/src/interceptor.adyen.test.ts new file mode 100644 index 000000000..ef8156013 --- /dev/null +++ b/packages/browser-pay/src/interceptor.adyen.test.ts @@ -0,0 +1,602 @@ +import type { + AdyenEncryptedFields, + AdyenEncryptRequest, + AdyenEncryptResult, +} from "./contract"; +import { + ADYEN_DOM_CLIENT_KEY_EXPRESSION, + type HeldPlaceholder, +} from "./detect"; +import { + attachInterceptor, + type InterceptorEvent, + type InterceptorHandle, +} from "./interceptor"; +import type { PayLogger } from "./logger"; +import { + RelayHttpError, + type PaymentRelay, + type RelayCallOptions, +} from "./relay"; +import { + startCdpStub, + waitFor, + type CdpCommand, + type CdpStub, +} from "../test/cdp-stub"; + +const HELD: HeldPlaceholder = { + number: "4242424242424242", + injectionRef: "inj_adyen", +}; +const PAGE_ORIGIN = "https://shop.example"; +const CLIENT_KEY = "test_FRAMEKEY123"; +const DOM_KEY = "test_DOMKEY456"; +const frameUrl = (key: string, field = "encryptedCardNumber") => + `https://checkoutshopper-test.adyen.com/checkoutshopper/securedfields/${key}/6.4.1/securedFields.html?type=card&d=${field}`; + +const STAND_IN = { + encryptedCardNumber: "eyJ.STANDIN_NUMBER_BLOB", + encryptedExpiryMonth: "eyJ.STANDIN_MONTH_BLOB", + encryptedExpiryYear: "eyJ.STANDIN_YEAR_BLOB", + encryptedSecurityCode: "eyJ.STANDIN_CVC_BLOB", +}; +const REAL: AdyenEncryptedFields = { + encryptedCardNumber: "eyJ.REAL_NUMBER_BLOB", + encryptedExpiryMonth: "eyJ.REAL_MONTH_BLOB", + encryptedExpiryYear: "eyJ.REAL_YEAR_BLOB", + encryptedSecurityCode: "eyJ.REAL_CVC_BLOB", +}; + +const ENCRYPTED: AdyenEncryptResult = { outcome: "encrypted", fields: REAL }; +const NOT_ENABLED: AdyenEncryptResult = { outcome: "not_enabled" }; + +const ADVANCED = { + url: "https://shop.example/api/payments", + body: { + amount: { currency: "EUR", value: 1000 }, + reference: "order-1", + paymentMethod: { + type: "scheme", + holderName: "J. Smith", + ...STAND_IN, + checkoutAttemptId: "attempt-1", + }, + browserInfo: { userAgent: "agent" }, + }, +}; +const SESSIONS = { + url: `https://checkoutshopper-test.adyen.com/checkoutshopper/v1/sessions/CS123/payments?clientKey=${CLIENT_KEY}`, + body: { + sessionData: "Ab02b4c0!session", + paymentMethod: { type: "scheme", ...STAND_IN }, + origin: PAGE_ORIGIN, + }, +}; + +interface Harness { + stub: CdpStub; + events: InterceptorEvent[]; + warnings: string[]; + encryptCalls: AdyenEncryptRequest[]; + relayCalls: number; + detach(): Promise; + prepare: InterceptorHandle["prepareAdyen"]; +} + +async function arm(options: { + frames?: { sessionId: string; url: string }[]; + domKey?: string | null; + encrypt?: + | (( + request: AdyenEncryptRequest, + call?: RelayCallOptions, + ) => Promise) + | null; + attemptTimeoutMs?: number; + disableAdyenEncryption?: boolean; +}): Promise { + const domKey = options.domKey === undefined ? null : options.domKey; + const stub = await startCdpStub((command) => { + if (command.method !== "Runtime.evaluate") return undefined; + if (command.params.expression === "location.origin") { + return { result: { type: "string", value: PAGE_ORIGIN } }; + } + if (command.params.expression === ADYEN_DOM_CLIENT_KEY_EXPRESSION) { + return { result: { value: domKey } }; + } + return undefined; + }); + const events: InterceptorEvent[] = []; + const warnings: string[] = []; + const encryptCalls: AdyenEncryptRequest[] = []; + const harness: Harness = { + stub, + events, + warnings, + encryptCalls, + relayCalls: 0, + detach: async () => {}, + prepare: async () => ({ enabled: false, reason: "adyen_not_enabled" }), + }; + const relay: PaymentRelay = { + async relay() { + harness.relayCalls += 1; + return { outcome: "unknown" }; + }, + }; + const encrypt = + options.encrypt === undefined ? async () => ENCRYPTED : options.encrypt; + if (encrypt) { + relay.adyenEncrypt = (request, call) => { + encryptCalls.push(request); + return encrypt(request, call); + }; + } + const logger: PayLogger = { + warn(message, fields) { + warnings.push(JSON.stringify({ message, fields })); + }, + }; + const handle = await attachInterceptor(stub.url, { + relay, + placeholder: HELD, + logger, + ...(options.attemptTimeoutMs + ? { attemptTimeoutMs: options.attemptTimeoutMs } + : {}), + ...(options.disableAdyenEncryption ? { disableAdyenEncryption: true } : {}), + }); + harness.prepare = (input) => handle.prepareAdyen(input); + handle.on((event) => events.push(event)); + harness.detach = () => handle.detach(); + stub.emit({ + method: "Target.attachedToTarget", + params: { + sessionId: "page-1", + waitingForDebugger: true, + targetInfo: { + targetId: "target-page", + type: "page", + url: `${PAGE_ORIGIN}/checkout`, + }, + }, + }); + for (const frame of options.frames ?? []) { + stub.emit({ + method: "Target.attachedToTarget", + sessionId: "page-1", + params: { + sessionId: frame.sessionId, + waitingForDebugger: true, + targetInfo: { + targetId: `target-${frame.sessionId}`, + type: "iframe", + url: frame.url, + }, + }, + }); + } + const sessions = 1 + (options.frames?.length ?? 0); + await waitFor( + () => count(stub.commands, "Fetch.enable") === sessions, + "Fetch.enable on every session", + ); + return harness; +} + +function count(commands: CdpCommand[], method: string): number { + return commands.filter((command) => command.method === method).length; +} + +function pause( + stub: CdpStub, + requestId: string, + request: { url: string; body?: unknown; method?: string }, +): void { + stub.emit({ + method: "Fetch.requestPaused", + sessionId: "page-1", + params: { + requestId, + request: { + url: request.url, + method: request.method ?? "POST", + headers: { "content-type": "application/json" }, + ...(request.body !== undefined + ? { postData: JSON.stringify(request.body), hasPostData: true } + : {}), + }, + }, + }); +} + +function settledWith(stub: CdpStub, requestId: string): CdpCommand | undefined { + return stub.commands.find( + (command) => + (command.method === "Fetch.continueRequest" || + command.method === "Fetch.failRequest") && + command.params.requestId === requestId, + ); +} + +async function settle(stub: CdpStub, requestId: string): Promise { + await waitFor( + () => settledWith(stub, requestId) !== undefined, + `request ${requestId} settled`, + ); + return settledWith(stub, requestId)!; +} + +function sentBody(command: CdpCommand): unknown { + expect(command.method).toBe("Fetch.continueRequest"); + expect(typeof command.params.postData).toBe("string"); + return JSON.parse( + Buffer.from(command.params.postData as string, "base64").toString("utf8"), + ); +} + +const SECRETS = [ + CLIENT_KEY, + DOM_KEY, + "FRAMEKEY", + "DOMKEY", + "STANDIN_", + "REAL_", + "eyJ", +]; + +function assertNothingSecret(harness: Harness): void { + const text = JSON.stringify(harness.events) + harness.warnings.join("\n"); + for (const secret of SECRETS) expect(text).not.toContain(secret); +} + +describe("interceptor on Adyen secured-fields checkouts", () => { + let harness: Harness | undefined; + + afterEach(async () => { + await harness?.detach(); + await harness?.stub.close(); + harness = undefined; + }); + + it("swaps the four encrypted fields on the merchant's /payments call (iframe src key)", async () => { + harness = await arm({ + frames: [ + { sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }, + { + sessionId: "frame-cvc", + url: frameUrl(CLIENT_KEY, "encryptedSecurityCode"), + }, + ], + domKey: DOM_KEY, + }); + pause(harness.stub, "req-advanced", ADVANCED); + const settled = await settle(harness.stub, "req-advanced"); + + expect(settled.sessionId).toBe("page-1"); + expect(sentBody(settled)).toStrictEqual({ + ...ADVANCED.body, + paymentMethod: { ...ADVANCED.body.paymentMethod, ...REAL }, + }); + expect(harness.encryptCalls).toStrictEqual([ + { + injectionRef: HELD.injectionRef, + clientKey: CLIENT_KEY, + pageOrigin: PAGE_ORIGIN, + }, + ]); + expect(harness.relayCalls).toBe(0); + // The frame key wins: the DOM is not consulted. + expect( + harness.stub.commands.some( + (command) => + command.params.expression === ADYEN_DOM_CLIENT_KEY_EXPRESSION, + ), + ).toBe(false); + await waitFor(() => harness!.events.length === 2, "two events"); + expect(harness.events).toStrictEqual([ + { + type: "paused", + url: PAGE_ORIGIN, + method: "POST", + targetType: "page", + }, + { type: "reencrypted", url: PAGE_ORIGIN }, + ]); + assertNothingSecret(harness); + }); + + it("swaps the fields on Adyen's /sessions/{id}/payments call", async () => { + harness = await arm({ + frames: [{ sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }], + }); + pause(harness.stub, "req-sessions", SESSIONS); + const settled = await settle(harness.stub, "req-sessions"); + + expect(sentBody(settled)).toStrictEqual({ + ...SESSIONS.body, + paymentMethod: { ...SESSIONS.body.paymentMethod, ...REAL }, + }); + expect(harness.encryptCalls).toHaveLength(1); + await waitFor(() => harness!.events.length === 2, "two events"); + expect(harness.events[1]).toStrictEqual({ + type: "reencrypted", + url: "https://checkoutshopper-test.adyen.com", + }); + assertNothingSecret(harness); + }); + + it("falls back to the page's adyen-web config when no secured-field frame is a target", async () => { + harness = await arm({ domKey: DOM_KEY }); + pause(harness.stub, "req-dom", ADVANCED); + const settled = await settle(harness.stub, "req-dom"); + + expect(sentBody(settled)).toMatchObject({ paymentMethod: REAL }); + expect(harness.encryptCalls[0]?.clientKey).toBe(DOM_KEY); + const evaluated = harness.stub.commands.find( + (command) => + command.params.expression === ADYEN_DOM_CLIENT_KEY_EXPRESSION, + ); + expect(evaluated?.sessionId).toBe("page-1"); + assertNothingSecret(harness); + }); + + it("continues requests that are not Adyen payments untouched", async () => { + harness = await arm({ + frames: [{ sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }], + }); + pause(harness.stub, "req-analytics", { + url: "https://checkoutshopper-test.adyen.com/checkoutshopper/v3/analytics", + body: { info: [{ type: "rendered" }] }, + }); + pause(harness.stub, "req-other", { + url: "https://shop.example/api/cart", + body: { encryptedCardNumber: "eyJ.top-level-is-not-adyen" }, + }); + pause(harness.stub, "req-form", { + url: "https://shop.example/api/payments", + body: "paymentMethod.encryptedCardNumber=eyJ", + }); + pause(harness.stub, "req-get", { + url: "https://shop.example/api/payments", + method: "GET", + }); + for (const id of ["req-analytics", "req-other", "req-form", "req-get"]) { + const settled = await settle(harness.stub, id); + expect(settled.method).toBe("Fetch.continueRequest"); + expect(settled.params).toStrictEqual({ requestId: id }); + } + expect(harness.encryptCalls).toHaveLength(0); + expect(harness.events).toStrictEqual([]); + }); + + it.each([ + [ + "the backend refuses", + async () => { + throw new RelayHttpError(403); + }, + ], + [ + "the backend is unreachable", + async () => { + throw new Error("connect ECONNREFUSED eyJ.REAL_NUMBER_BLOB"); + }, + ], + ] as const)( + "fails the request closed when %s, never sending the stand-in", + async (_label, encrypt) => { + harness = await arm({ + frames: [{ sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }], + encrypt, + }); + pause(harness.stub, "req-fail", ADVANCED); + const settled = await settle(harness.stub, "req-fail"); + + expect(settled.method).toBe("Fetch.failRequest"); + expect(count(harness.stub.commands, "Fetch.continueRequest")).toBe(0); + await waitFor(() => harness!.events.length === 2, "two events"); + expect(harness.events[1]).toStrictEqual({ + type: "failed", + url: PAGE_ORIGIN, + reason: "adyen_encrypt", + }); + expect(harness.warnings).toHaveLength(1); + expect(harness.warnings[0]).toContain("adyen re-encryption failed"); + assertNothingSecret(harness); + }, + ); + + it("fails the request closed when re-encryption outlasts the attempt timeout", async () => { + let aborted = false; + harness = await arm({ + frames: [{ sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }], + attemptTimeoutMs: 50, + encrypt: (_request, call) => + new Promise(() => { + call?.signal?.addEventListener("abort", () => { + aborted = true; + }); + }), + }); + pause(harness.stub, "req-slow", ADVANCED); + const settled = await settle(harness.stub, "req-slow"); + + expect(settled.method).toBe("Fetch.failRequest"); + expect(aborted).toBe(true); + await waitFor(() => harness!.events.length === 2, "two events"); + expect(harness.events[1]).toMatchObject({ reason: "adyen_encrypt" }); + expect(harness.warnings[0]).toContain('"timedOut":true'); + }); + + it("fails the request closed when no client key is on the page", async () => { + harness = await arm({ domKey: null }); + pause(harness.stub, "req-nokey", ADVANCED); + const settled = await settle(harness.stub, "req-nokey"); + + expect(settled.method).toBe("Fetch.failRequest"); + expect(harness.encryptCalls).toHaveLength(0); + await waitFor(() => harness!.events.length === 2, "two events"); + expect(harness.events[1]).toStrictEqual({ + type: "failed", + url: PAGE_ORIGIN, + reason: "adyen_client_key", + }); + }); + + it("does not guess between two different client keys on one page", async () => { + harness = await arm({ + frames: [ + { sessionId: "frame-a", url: frameUrl(CLIENT_KEY) }, + { sessionId: "frame-b", url: frameUrl("test_OTHERKEY789") }, + ], + domKey: DOM_KEY, + }); + pause(harness.stub, "req-ambiguous", ADVANCED); + const settled = await settle(harness.stub, "req-ambiguous"); + + expect(settled.method).toBe("Fetch.failRequest"); + expect(harness.encryptCalls).toHaveLength(0); + await waitFor(() => harness!.events.length === 2, "two events"); + expect(harness.events[1]).toMatchObject({ reason: "adyen_client_key" }); + }); + + it("rejects a malformed key from the page's config", async () => { + harness = await arm({ domKey: "pub.v2.8115650120946270.aHR0cA" }); + pause(harness.stub, "req-badkey", ADVANCED); + const settled = await settle(harness.stub, "req-badkey"); + + expect(settled.method).toBe("Fetch.failRequest"); + expect(harness.encryptCalls).toHaveLength(0); + }); + + it("relays a body holding the placeholder digits as before, not through Adyen", async () => { + harness = await arm({ + frames: [{ sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }], + }); + pause(harness.stub, "req-held", { + url: "https://shop.example/api/payments", + body: { + paymentMethod: { + encryptedCardNumber: `test_${HELD.number}`, + }, + }, + }); + await waitFor(() => harness!.relayCalls === 1, "relay call"); + expect(harness.encryptCalls).toHaveLength(0); + }); +}); + +describe("Adyen encryption gate", () => { + let harness: Harness | undefined; + + afterEach(async () => { + await harness?.detach(); + await harness?.stub.close(); + harness = undefined; + }); + + async function expectClosed( + id: string, + reason: string, + url = PAGE_ORIGIN, + ): Promise { + const settled = await settle(harness!.stub, id); + expect(settled.method).toBe("Fetch.failRequest"); + expect(count(harness!.stub.commands, "Fetch.continueRequest")).toBe(0); + await waitFor(() => harness!.events.length === 2, "two events"); + expect(harness!.events[1]).toStrictEqual({ type: "failed", url, reason }); + assertNothingSecret(harness!); + } + + it("off by local option: fails closed without asking the backend or reading the key", async () => { + harness = await arm({ + frames: [{ sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }], + disableAdyenEncryption: true, + }); + pause(harness.stub, "req-off", ADVANCED); + await expectClosed("req-off", "adyen_not_enabled"); + expect(harness.encryptCalls).toHaveLength(0); + expect(harness.warnings).toStrictEqual([]); + await expect( + harness.prepare({ clientKey: CLIENT_KEY, pageOrigin: PAGE_ORIGIN }), + ).resolves.toStrictEqual({ enabled: false, reason: "adyen_not_enabled" }); + expect(harness.encryptCalls).toHaveLength(0); + }); + + it("off when the relay cannot encrypt for Adyen", async () => { + harness = await arm({ + frames: [{ sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }], + encrypt: null, + }); + pause(harness.stub, "req-norelay", ADVANCED); + await expectClosed("req-norelay", "adyen_not_enabled"); + expect(harness.warnings).toStrictEqual([]); + }); + + it("off by the backend: its not-enabled answer fails the request closed", async () => { + harness = await arm({ + frames: [{ sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }], + encrypt: async () => NOT_ENABLED, + }); + pause(harness.stub, "req-be-off", SESSIONS); + await expectClosed( + "req-be-off", + "adyen_not_enabled", + "https://checkoutshopper-test.adyen.com", + ); + expect(harness.encryptCalls).toHaveLength(1); + await expect( + harness.prepare({ clientKey: CLIENT_KEY, pageOrigin: PAGE_ORIGIN }), + ).resolves.toStrictEqual({ enabled: false, reason: "adyen_not_enabled" }); + }); + + it("the local option cannot force it on past the backend", async () => { + harness = await arm({ + frames: [{ sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }], + encrypt: async () => NOT_ENABLED, + disableAdyenEncryption: false, + }); + pause(harness.stub, "req-force", ADVANCED); + await expectClosed("req-force", "adyen_not_enabled"); + }); + + it("on: prepareAdyen asks the backend once and the payment uses those fields", async () => { + harness = await arm({ + frames: [{ sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }], + }); + await expect( + harness.prepare({ clientKey: CLIENT_KEY, pageOrigin: PAGE_ORIGIN }), + ).resolves.toStrictEqual({ enabled: true }); + pause(harness.stub, "req-on", ADVANCED); + const settled = await settle(harness.stub, "req-on"); + expect(sentBody(settled)).toStrictEqual({ + ...ADVANCED.body, + paymentMethod: { ...ADVANCED.body.paymentMethod, ...REAL }, + }); + expect(harness.encryptCalls).toHaveLength(1); + + // Prepared fields are used once: a second payment asks again. + pause(harness.stub, "req-again", ADVANCED); + await settle(harness.stub, "req-again"); + expect(harness.encryptCalls).toHaveLength(2); + assertNothingSecret(harness); + }); + + it("prepareAdyen reports a backend failure without throwing or logging values", async () => { + harness = await arm({ + encrypt: async () => { + throw new RelayHttpError(500); + }, + }); + await expect( + harness.prepare({ clientKey: CLIENT_KEY, pageOrigin: PAGE_ORIGIN }), + ).resolves.toStrictEqual({ enabled: false, reason: "adyen_encrypt" }); + await expect( + harness.prepare({ clientKey: "not-a-key", pageOrigin: PAGE_ORIGIN }), + ).resolves.toStrictEqual({ enabled: false, reason: "adyen_encrypt" }); + expect(harness.encryptCalls).toHaveLength(1); + assertNothingSecret(harness); + }); +}); diff --git a/packages/browser-pay/src/interceptor.integration.test.ts b/packages/browser-pay/src/interceptor.integration.test.ts index 9b20c2b98..01f8bdec0 100644 --- a/packages/browser-pay/src/interceptor.integration.test.ts +++ b/packages/browser-pay/src/interceptor.integration.test.ts @@ -764,6 +764,83 @@ if (!chromeBin) { } }, 60_000); + it("sends an Adyen payment on with the backend's encrypted fields, body otherwise intact", async () => { + const standIn = { + encryptedCardNumber: "eyJ.stand-in-number", + encryptedExpiryMonth: "eyJ.stand-in-month", + encryptedExpiryYear: "eyJ.stand-in-year", + encryptedSecurityCode: "eyJ.stand-in-cvc", + }; + const real = { + encryptedCardNumber: `eyJ.${"n".repeat(700)}`, + encryptedExpiryMonth: `eyJ.${"m".repeat(500)}`, + encryptedExpiryYear: `eyJ.${"y".repeat(500)}`, + encryptedSecurityCode: `eyJ.${"c".repeat(500)}`, + }; + const order = { + amount: { currency: "EUR", value: 1000 }, + reference: "order-ü-1", + paymentMethod: { type: "scheme", holderName: "J. Smith", ...standIn }, + }; + const shop = await startServer( + hits, + `adyen shop
test_INTEGRATIONKEY1
`, + "localhost", + ); + const encryptCalls: unknown[] = []; + const handle = await attachInterceptor(cdpUrl, { + relay: { + relay: async () => ({ outcome: "unknown" }), + adyenEncrypt: async (request) => { + encryptCalls.push(request); + return { outcome: "encrypted", fields: real }; + }, + }, + placeholder: PLACEHOLDER, + }); + const events: InterceptorEvent[] = []; + handle.on((event) => events.push(event)); + const { chromium } = await import("playwright"); + const browser = await chromium.connectOverCDP(cdpUrl); + let page: import("playwright").Page | undefined; + try { + const context = browser.contexts()[0]; + page = await context.newPage(); + const origin = `http://localhost:${shop.port}`; + await page.goto(`${origin}/`, { waitUntil: "domcontentloaded" }); + const status = await page.evaluate(async (body) => { + const res = await fetch("/api/payments", { + method: "POST", + headers: { "content-type": "application/json" }, + body, + }); + return res.status; + }, JSON.stringify(order)); + + expect(status).toBe(200); + const hit = hits.find((item) => item.path === "/api/payments"); + expect(JSON.parse(hit?.body ?? "null")).toStrictEqual({ + ...order, + paymentMethod: { ...order.paymentMethod, ...real }, + }); + expect(encryptCalls).toStrictEqual([ + { + injectionRef: PLACEHOLDER.injectionRef, + clientKey: "test_INTEGRATIONKEY1", + pageOrigin: origin, + }, + ]); + expect(events.map((event) => event.type)).toEqual([ + "paused", + "reencrypted", + ]); + } finally { + await page?.close().catch(() => {}); + await handle.detach(); + await new Promise((resolve) => shop.server.close(resolve)); + } + }); + it("refuses a real Playwright browser and page, which have no wsEndpoint()", async () => { const { chromium } = await import("playwright"); const browser = await chromium.connectOverCDP(cdpUrl); diff --git a/packages/browser-pay/src/interceptor.ts b/packages/browser-pay/src/interceptor.ts index 445f26d92..83e0058bb 100644 --- a/packages/browser-pay/src/interceptor.ts +++ b/packages/browser-pay/src/interceptor.ts @@ -1,12 +1,19 @@ import { CdpCommandError, CdpConnection, type CdpEvent } from "./cdp.js"; import { paymentIdempotencyKey, + type AdyenEncryptedFields, + type AdyenEncryptResult, type RelayedHttpResponse, type RelayResponse, } from "./contract.js"; import { + ADYEN_DOM_CLIENT_KEY_EXPRESSION, + adyenClientKeyFromFrameUrl, + isAdyenClientKey, + isAdyenSecuredFieldsPayment, redactHeld, textHoldsPlaceholderNumber, + withAdyenEncryptedFields, type HeldPlaceholder, } from "./detect.js"; import { isRecord } from "./guards.js"; @@ -14,6 +21,7 @@ import { silentLogger, type PayLogger } from "./logger.js"; import { isRelayTimeout, isRetryableRelayError, + RelayHttpError, RelayTimeoutError, type PaymentRelay, } from "./relay.js"; @@ -51,6 +59,33 @@ export interface AttachOptions { attemptTimeoutMs?: number; /** Defaults to a logger that discards every line. */ logger?: PayLogger; + /** + * `true` turns Adyen secured-fields payments off for this attach: such a + * payment fails with `adyen_not_enabled` and the backend is not asked. + * There is no way to force them on: they run only when the backend's + * Adyen encryption answers with fields. + */ + disableAdyenEncryption?: boolean; +} + +/** Whether a page's Adyen secured-fields payment can be paid. */ +export type AdyenReadiness = + | { enabled: true } + | { + enabled: false; + reason: Extract; + }; + +/** + * Asks, before any card is typed, whether an Adyen secured-fields payment on + * `pageOrigin` with `clientKey` will be paid. `fillCard` takes one as + * `adyen`; the interceptor handle is one. + */ +export interface AdyenGate { + prepareAdyen(input: { + clientKey: string; + pageOrigin: string; + }): Promise; } export type FailureReason = @@ -63,7 +98,10 @@ export type FailureReason = | "timeout" | "network" | "response_credential" - | "headers_unrelayable"; + | "headers_unrelayable" + | "adyen_not_enabled" + | "adyen_client_key" + | "adyen_encrypt"; export const KNOWN_REFUSAL_REASONS = [ "unknown_injection", @@ -103,6 +141,8 @@ export type InterceptorEvent = | { type: "paused"; url: string; method: string; targetType: string } | { type: "relayed"; url: string; status: number } | { type: "relayed_unfulfilled"; url: string; status: number } + /** An Adyen secured-fields payment continued with the card's own encrypted fields. */ + | { type: "reencrypted"; url: string } | { type: "refused"; url: string; @@ -119,7 +159,7 @@ type PublicRefusal = Omit< "type" | "url" >; -export interface InterceptorHandle { +export interface InterceptorHandle extends AdyenGate { detach(): Promise; /** Subscribe to outcomes. Returns an unsubscribe function. */ on(listener: (event: InterceptorEvent) => void): () => void; @@ -309,16 +349,21 @@ interface Flight { type HeldRead = | { kind: "unreadable" } - | { kind: "miss" } + | { kind: "miss"; body: string } | { kind: "held"; body: string }; type Decision = | { action: "continue" } + | { action: "reencrypted"; body: string } | { action: "fail"; reason: FailureReason } | { action: "refused"; refusal: PublicRefusal } | { action: "relayed"; response: RelayedHttpResponse }; -type SettleAction = "continue" | "fail" | { fulfill: RelayedHttpResponse }; +type SettleAction = + | "continue" + | "fail" + | { fulfill: RelayedHttpResponse } + | { continueWith: string }; type Listener = (event: InterceptorEvent) => void; @@ -346,6 +391,11 @@ class PaymentInterceptor { private readonly unknownKeys = new Set(); private readonly loggedRefusals = new Set(); private readonly pendingArms = new Set>(); + /** Fields a `prepareAdyen` call fetched, used once by the next matching payment. */ + private readonly preparedAdyen = new Map< + string, + { fields: AdyenEncryptedFields; at: number } + >(); private readonly timeoutMs: number; private readonly attemptTimeoutMs: number; private readonly logger: PayLogger; @@ -384,6 +434,7 @@ class PaymentInterceptor { return { on: (listener) => this.subscribe(listener), detach: () => this.detach(), + prepareAdyen: (input) => this.prepareAdyen(input), }; } @@ -677,7 +728,11 @@ class PaymentInterceptor { if (read.kind === "unreadable") { return { action: "fail", reason: "unreadable_body" }; } - if (read.kind === "miss") return { action: "continue" }; + if (read.kind === "miss") { + return isAdyenSecuredFieldsPayment(read.body) + ? this.reencryptAdyen(entry, request, read.body) + : { action: "continue" }; + } if (this.closed) return { action: "fail", reason: "detached" }; const targetType = this.sessions.get(entry.sessionId)?.type ?? ""; this.emit({ @@ -719,6 +774,183 @@ class PaymentInterceptor { ); } + /** + * Adyen secured fields send only ciphertext of the typed placeholder, so + * there is nothing to relay. The card vault encrypts the real card to the + * merchant's Adyen key instead, and the page's own request goes on with + * those four fields. Any failure fails the request: the placeholder's + * ciphertext is never sent on. + */ + private async reencryptAdyen( + entry: Inflight, + request: PausedRequest, + body: string, + ): Promise { + if (this.closed) return { action: "fail", reason: "detached" }; + this.emit({ + type: "paused", + url: request.url, + method: request.method, + targetType: this.sessions.get(entry.sessionId)?.type ?? "", + }); + const pageOrigin = await readPageOrigin( + this.connection, + this.sessions, + entry.sessionId, + ); + if (!pageOrigin || this.closed) { + return { + action: "fail", + reason: pageOrigin ? "detached" : "page_origin", + }; + } + if (!this.adyenAllowed()) { + return { action: "fail", reason: "adyen_not_enabled" }; + } + const clientKey = await this.adyenClientKey(entry.sessionId); + if (this.closed) return { action: "fail", reason: "detached" }; + if (!clientKey) { + this.logger.warn("adyen client key not found on the page"); + return { action: "fail", reason: "adyen_client_key" }; + } + const prepared = this.takePreparedAdyen(clientKey, pageOrigin); + let result: AdyenEncryptResult; + if (prepared) { + result = { outcome: "encrypted", fields: prepared }; + } else { + try { + result = await this.adyenEncrypt(clientKey, pageOrigin); + } catch (error) { + if (this.closed) return { action: "fail", reason: "detached" }; + this.logAdyenFailure(error); + return { action: "fail", reason: "adyen_encrypt" }; + } + } + if (this.closed) return { action: "fail", reason: "detached" }; + if (result.outcome === "not_enabled") { + return { action: "fail", reason: "adyen_not_enabled" }; + } + return { + action: "reencrypted", + body: withAdyenEncryptedFields(body, result.fields), + }; + } + + /** Off when the caller turned it off or the relay cannot encrypt; otherwise the backend decides. */ + private adyenAllowed(): boolean { + return ( + this.options.disableAdyenEncryption !== true && + typeof this.options.relay.adyenEncrypt === "function" + ); + } + + private async prepareAdyen(input: { + clientKey: string; + pageOrigin: string; + }): Promise { + if (!this.adyenAllowed()) { + return { enabled: false, reason: "adyen_not_enabled" }; + } + if (!isAdyenClientKey(input.clientKey)) { + return { enabled: false, reason: "adyen_encrypt" }; + } + let result: AdyenEncryptResult; + try { + result = await this.adyenEncrypt(input.clientKey, input.pageOrigin); + } catch (error) { + this.logAdyenFailure(error); + return { enabled: false, reason: "adyen_encrypt" }; + } + if (result.outcome === "not_enabled") { + return { enabled: false, reason: "adyen_not_enabled" }; + } + this.preparedAdyen.set(preparedKey(input.clientKey, input.pageOrigin), { + fields: result.fields, + at: Date.now(), + }); + return { enabled: true }; + } + + /** Prepared fields are used once, and only while fresh. */ + private takePreparedAdyen( + clientKey: string, + pageOrigin: string, + ): AdyenEncryptedFields | undefined { + const key = preparedKey(clientKey, pageOrigin); + const prepared = this.preparedAdyen.get(key); + this.preparedAdyen.delete(key); + if (!prepared || Date.now() - prepared.at > PREPARED_ADYEN_TTL_MS) { + return undefined; + } + return prepared.fields; + } + + private logAdyenFailure(error: unknown): void { + this.logger.warn("adyen re-encryption failed", { + ...(error instanceof RelayHttpError ? { status: error.status } : {}), + timedOut: isRelayTimeout(error), + }); + } + + private async adyenEncrypt( + clientKey: string, + pageOrigin: string, + ): Promise { + const relay = this.options.relay; + if (typeof relay.adyenEncrypt !== "function") { + return { outcome: "not_enabled" }; + } + const controller = new AbortController(); + const timer = setTimeout( + () => controller.abort(new RelayTimeoutError()), + this.attemptTimeoutMs, + ); + try { + return await failAfter( + relay.adyenEncrypt( + { + injectionRef: this.options.placeholder.injectionRef, + clientKey, + pageOrigin, + }, + { signal: controller.signal }, + ), + this.attemptTimeoutMs, + ); + } finally { + clearTimeout(timer); + } + } + + /** + * The key in the secured-field iframes under the paused request's page, + * else the one adyen-web config on that page names. Two different keys on + * one page give none: the card must not be encrypted to a guess. + */ + private async adyenClientKey(sessionId: string): Promise { + const page = topPageSession(this.sessions, sessionId); + const keys = new Set(); + for (const session of this.sessions.values()) { + const key = adyenClientKeyFromFrameUrl(session.url); + if (!key) continue; + if (page && topPageSession(this.sessions, session.sessionId) !== page) { + continue; + } + keys.add(key); + } + if (keys.size > 1) return undefined; + if (keys.size === 1) return [...keys][0]; + const evaluated = await this.connection + .send( + "Runtime.evaluate", + { expression: ADYEN_DOM_CLIENT_KEY_EXPRESSION, returnByValue: true }, + page ?? sessionId, + ) + .catch(() => null); + const key = evaluatedString(evaluated); + return isAdyenClientKey(key) ? key : undefined; + } + private async awaitRelay( request: PausedRequest, headers: Record, @@ -840,14 +1072,14 @@ class PaymentInterceptor { const urlHeld = textHoldsPlaceholderNumber(request.url, this.number); if (urlHeld && this.closed) return { kind: "held", body: "" }; if (postDataPlan(request) === "empty") { - return urlHeld ? { kind: "held", body: "" } : { kind: "miss" }; + return urlHeld ? { kind: "held", body: "" } : { kind: "miss", body: "" }; } const body = await readBody(this.connection, sessionId, request); if (body === undefined) return { kind: "unreadable" }; if (urlHeld || textHoldsPlaceholderNumber(body, this.number)) { return { kind: "held", body }; } - return { kind: "miss" }; + return { kind: "miss", body }; } private decisionForOutcome( @@ -884,6 +1116,17 @@ class PaymentInterceptor { await this.settle(entry, "continue"); return; } + if (decision.action === "reencrypted") { + const continued = await this.settle(entry, { + continueWith: decision.body, + }); + this.emit( + continued + ? { type: "reencrypted", url } + : { type: "failed", url, reason: "adyen_encrypt" }, + ); + return; + } if (decision.action === "fail") { await this.settle(entry, "fail"); this.emit({ type: "failed", url, reason: decision.reason }); @@ -911,18 +1154,27 @@ class PaymentInterceptor { action: SettleAction, ): Promise { if (entry.phase.status !== "open") return false; - if (action === "continue") { + if ( + action === "continue" || + (typeof action === "object" && "continueWith" in action) + ) { + let continued = true; const done = continueRequest( this.connection, entry.sessionId, entry.requestId, - ).finally(() => { - entry.phase = { status: "done" }; - this.inflight.delete(entry.key); - }); + action === "continue" ? undefined : action.continueWith, + ) + .then((ok) => { + continued = ok; + }) + .finally(() => { + entry.phase = { status: "done" }; + this.inflight.delete(entry.key); + }); entry.phase = { status: "continuing", done }; await done; - return true; + return continued; } entry.phase = { status: "done" }; try { @@ -989,6 +1241,7 @@ class PaymentInterceptor { this.closed = true; this.buffering = false; this.backlog = null; + this.preparedAdyen.clear(); for (const flight of this.relayFlights.values()) flight.controller.abort(); await this.drainInflight(); for (const sessionId of this.sessions.keys()) { @@ -1041,6 +1294,16 @@ class PaymentInterceptor { } } +/** + * How long fields fetched by `prepareAdyen` wait for the payment. Well inside + * the time Adyen accepts an encrypted field's `generationtime`. + */ +const PREPARED_ADYEN_TTL_MS = 10 * 60_000; + +function preparedKey(clientKey: string, pageOrigin: string): string { + return `${clientKey}\n${pageOrigin}`; +} + function inflightKey(sessionId: string, requestId: string): string { return `${sessionId}\n${requestId}`; } @@ -1515,15 +1778,28 @@ async function armFetch( session.fetchEnabled = true; } +/** False when the browser refused to continue and the request was failed instead. */ async function continueRequest( connection: CdpConnection, sessionId: string, requestId: string, -): Promise { + postData?: string, +): Promise { try { - await connection.send("Fetch.continueRequest", { requestId }, sessionId); + await connection.send( + "Fetch.continueRequest", + { + requestId, + ...(postData !== undefined + ? { postData: Buffer.from(postData, "utf8").toString("base64") } + : {}), + }, + sessionId, + ); + return true; } catch { await failRequest(connection, sessionId, requestId); + return false; } } diff --git a/packages/browser-pay/src/relay.test.ts b/packages/browser-pay/src/relay.test.ts index 4b3c336f0..b6684dbef 100644 --- a/packages/browser-pay/src/relay.test.ts +++ b/packages/browser-pay/src/relay.test.ts @@ -412,3 +412,132 @@ function stalledBody( }); return Promise.resolve(new Response(stream, { status: 200 })); } + +describe("httpPaymentRelay adyenEncrypt", () => { + const ENCRYPT = { + injectionRef: "inj_fixture_adyen", + clientKey: "test_FIXTUREKEY123", + pageOrigin: "https://shop.example", + }; + const BLOBS = { + encryptedCardNumber: "eyJ.real-number", + encryptedExpiryMonth: "eyJ.real-month", + encryptedExpiryYear: "eyJ.real-year", + encryptedSecurityCode: "eyJ.real-cvc", + }; + + it("POSTs the injection, client key and page origin to the encrypt path with the api key", async () => { + const seen: { + method?: string; + url?: string; + headers?: http.IncomingHttpHeaders; + body?: string; + } = {}; + const server = await listen((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk: Buffer) => chunks.push(chunk)); + req.on("end", () => { + seen.method = req.method; + seen.url = req.url; + seen.headers = req.headers; + seen.body = Buffer.concat(chunks).toString("utf8"); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ...BLOBS, extra: "ignored" })); + }); + }); + try { + const relay = httpPaymentRelay({ + baseUrl: origin(server), + apiKey: "test-key", + transactionId: "tx_adyen", + }); + await expect(relay.adyenEncrypt!(ENCRYPT)).resolves.toStrictEqual({ + outcome: "encrypted", + fields: BLOBS, + }); + expect(seen.method).toBe("POST"); + expect(seen.url).toBe("/v1/transactions/tx_adyen/payment/adyen/encrypt"); + expect(seen.headers?.["x-api-key"]).toBe("test-key"); + expect(seen.headers?.["content-type"]).toBe("application/json"); + expect(JSON.parse(seen.body ?? "")).toStrictEqual(ENCRYPT); + } finally { + server.close(); + } + }); + + it("throws without the response text on an error status or an unreadable body", async () => { + const replies: [number, string][] = [ + [403, '{"secret":"eyJ.leaked"}'], + [200, '{"encryptedCardNumber":"eyJ.leaked"}'], + [200, "eyJ.leaked not json"], + ]; + for (const [status, body] of replies) { + const server = await listen((_req, res) => { + res.writeHead(status, { "content-type": "application/json" }); + res.end(body); + }); + try { + const relay = httpPaymentRelay({ + baseUrl: origin(server), + apiKey: "test-key", + transactionId: "tx_adyen", + }); + const error = await relay.adyenEncrypt!(ENCRYPT).catch( + (caught: unknown) => caught as Error, + ); + expect(error).toBeInstanceOf(Error); + if (status !== 200) expect(error).toBeInstanceOf(RelayHttpError); + expect( + JSON.stringify(error, Object.getOwnPropertyNames(error)), + ).not.toContain("leaked"); + } finally { + server.close(); + } + } + }); + + it("reads the backend's typed not-enabled answer as off, on an error status or a 200", async () => { + const replies: [number, string][] = [ + [403, '{"code":"adyen_encryption_not_enabled","message":"off"}'], + [503, '{"code":"adyen_encryption_not_enabled"}'], + [200, '{"reason":"adyen_encryption_not_enabled"}'], + ]; + for (const [status, body] of replies) { + const server = await listen((_req, res) => { + res.writeHead(status, { "content-type": "application/json" }); + res.end(body); + }); + try { + const relay = httpPaymentRelay({ + baseUrl: origin(server), + apiKey: "test-key", + transactionId: "tx_adyen", + }); + await expect(relay.adyenEncrypt!(ENCRYPT)).resolves.toStrictEqual({ + outcome: "not_enabled", + }); + } finally { + server.close(); + } + } + }); + + it("does not read another error code as not enabled", async () => { + const server = await listen((_req, res) => { + res.writeHead(403, { "content-type": "application/json" }); + res.end('{"code":"merchant_mismatch"}'); + }); + try { + const relay = httpPaymentRelay({ + baseUrl: origin(server), + apiKey: "test-key", + transactionId: "tx_adyen", + }); + await expect(relay.adyenEncrypt!(ENCRYPT)).rejects.toBeInstanceOf( + RelayHttpError, + ); + } finally { + server.close(); + } + }); +}); diff --git a/packages/browser-pay/src/relay.ts b/packages/browser-pay/src/relay.ts index 9105393bf..21ddd6ce1 100644 --- a/packages/browser-pay/src/relay.ts +++ b/packages/browser-pay/src/relay.ts @@ -6,7 +6,11 @@ import { } from "@sapiom/analytics-core/credential"; import { + isAdyenNotEnabled, + parseAdyenEncryptResponse, parseRelayResponse, + type AdyenEncryptRequest, + type AdyenEncryptResult, type RelayRequest, type RelayResponse, } from "./contract.js"; @@ -20,6 +24,16 @@ export interface PaymentRelay { request: RelayRequest, options?: RelayCallOptions, ): Promise; + /** + * Encrypts the authorized card to the Adyen public key behind `clientKey`, + * inside the card vault. Needed only for Adyen secured-fields checkouts. + * `not_enabled` is the backend saying the feature is off; a relay without + * this method is treated the same way (`adyen_not_enabled`). + */ + adyenEncrypt?( + request: AdyenEncryptRequest, + options?: RelayCallOptions, + ): Promise; } export interface HttpRelayOptions { @@ -136,45 +150,65 @@ async function discardBody(response: Response): Promise { await response.body?.cancel().catch(() => undefined); } +type HttpConfig = ReturnType; + +/** + * POSTs JSON under the transaction's payment path and returns the 2xx body + * text. With `readErrorBody`, a non-2xx, non-redirect body is returned too. + */ +async function postPayment( + config: HttpConfig, + path: string, + payload: unknown, + signal: AbortSignal | undefined, + readErrorBody = false, +): Promise<{ status: number; text: string }> { + const url = `${config.baseUrl}/v1/transactions/${encodeURIComponent(config.transactionId)}/payment/${path}`; + let response: Response; + try { + response = await credentialFetch( + config.fetchImpl, + url, + { + method: "POST", + redirect: "manual", + headers: { + accept: "application/json", + "content-type": "application/json", + }, + body: JSON.stringify(payload), + signal, + }, + { header: "x-api-key", value: config.apiKey }, + config.policy, + ); + } catch (error) { + throw transportError(error, signal); + } + const redirect = response.status >= 300 && response.status < 400; + const ok = response.status >= 200 && response.status < 300; + if (redirect || (!ok && !readErrorBody)) { + await discardBody(response); + if (redirect) throw new Error("Payment relay refused a redirect"); + throw new RelayHttpError(response.status); + } + try { + return { status: response.status, text: await response.text() }; + } catch (error) { + throw transportError(error, signal); + } +} + export function httpPaymentRelay(options: HttpRelayOptions): PaymentRelay { const config = requireHttpOptions(options); return { async relay(request, call) { - const url = `${config.baseUrl}/v1/transactions/${encodeURIComponent(config.transactionId)}/payment/relay`; - let response: Response; - try { - response = await credentialFetch( - config.fetchImpl, - url, - { - method: "POST", - redirect: "manual", - headers: { - accept: "application/json", - "content-type": "application/json", - }, - body: JSON.stringify(request), - signal: call?.signal, - }, - { header: "x-api-key", value: config.apiKey }, - config.policy, - ); - } catch (error) { - throw transportError(error, call?.signal); - } - if (response.status < 200 || response.status >= 300) { - await discardBody(response); - if (response.status >= 300 && response.status < 400) { - throw new Error("Payment relay refused a redirect"); - } - throw new RelayHttpError(response.status); - } - let text: string; - try { - text = await response.text(); - } catch (error) { - throw transportError(error, call?.signal); - } + const { status, text } = await postPayment( + config, + "relay", + request, + call?.signal, + ); let parsed: unknown; try { parsed = JSON.parse(text); @@ -188,7 +222,32 @@ export function httpPaymentRelay(options: HttpRelayOptions): PaymentRelay { // The thrown error must not include the response text. } } - throw new Error(`Payment relay failed (HTTP ${response.status})`); + throw new Error(`Payment relay failed (HTTP ${status})`); + }, + async adyenEncrypt(request, call) { + const { status, text } = await postPayment( + config, + "adyen/encrypt", + { + injectionRef: request.injectionRef, + clientKey: request.clientKey, + pageOrigin: request.pageOrigin, + }, + call?.signal, + true, + ); + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + // The thrown error must not include the response text. + } + if (status < 200 || status >= 300) { + // An error body is read only for the typed "not enabled" answer. + if (isAdyenNotEnabled(parsed)) return { outcome: "not_enabled" }; + throw new RelayHttpError(status); + } + return parseAdyenEncryptResponse(parsed); }, }; } diff --git a/packages/browser-pay/test/cdp-stub.ts b/packages/browser-pay/test/cdp-stub.ts new file mode 100644 index 000000000..c9bd20d7e --- /dev/null +++ b/packages/browser-pay/test/cdp-stub.ts @@ -0,0 +1,142 @@ +import crypto from "node:crypto"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import type { Duplex } from "node:stream"; + +export interface CdpCommand { + method: string; + params: Record; + sessionId?: string; +} + +/** Returns the `result` for a command, or `undefined` for `{}`. */ +export type CdpReply = (command: CdpCommand) => unknown; + +export interface CdpStub { + url: string; + commands: CdpCommand[]; + emit(event: Record): void; + close(): Promise; +} + +function serverFrame(text: string): Buffer { + const payload = Buffer.from(text); + if (payload.length < 126) { + return Buffer.concat([Buffer.from([0x81, payload.length]), payload]); + } + if (payload.length < 65_536) { + const header = Buffer.alloc(4); + header[0] = 0x81; + header[1] = 126; + header.writeUInt16BE(payload.length, 2); + return Buffer.concat([header, payload]); + } + const header = Buffer.alloc(10); + header[0] = 0x81; + header[1] = 127; + header.writeBigUInt64BE(BigInt(payload.length), 2); + return Buffer.concat([header, payload]); +} + +/** A minimal CDP WebSocket server: records every command and answers with `reply`. */ +export async function startCdpStub( + reply: CdpReply = () => undefined, +): Promise { + const commands: CdpCommand[] = []; + let socket: Duplex | undefined; + let pending = Buffer.alloc(0); + + const onMessage = (text: string) => { + const message = JSON.parse(text) as { + id?: number; + method?: string; + params?: Record; + sessionId?: string; + }; + if (!message.id || !message.method) return; + const command: CdpCommand = { + method: message.method, + params: message.params ?? {}, + ...(message.sessionId ? { sessionId: message.sessionId } : {}), + }; + commands.push(command); + const result = reply(command) ?? {}; + socket?.write(serverFrame(JSON.stringify({ id: message.id, result }))); + }; + + const parse = () => { + for (;;) { + if (pending.length < 2) return; + let length = pending[1] & 0x7f; + let offset = 2; + if (length === 126) { + if (pending.length < 4) return; + length = pending.readUInt16BE(2); + offset = 4; + } else if (length === 127) { + if (pending.length < 10) return; + length = Number(pending.readBigUInt64BE(2)); + offset = 10; + } + const masked = (pending[1] & 0x80) !== 0; + const maskAt = offset; + if (masked) offset += 4; + if (pending.length < offset + length) return; + const opcode = pending[0] & 0x0f; + const payload = Buffer.from(pending.subarray(offset, offset + length)); + if (masked) { + for (let index = 0; index < payload.length; index++) { + payload[index] ^= pending[maskAt + (index % 4)]; + } + } + pending = pending.subarray(offset + length); + if (opcode === 0x1) onMessage(payload.toString("utf8")); + } + }; + + const server = http.createServer(); + server.on("upgrade", (request, upgraded, head) => { + const key = String(request.headers["sec-websocket-key"] ?? ""); + const accept = crypto + .createHash("sha1") + .update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`) + .digest("base64"); + upgraded.write( + `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`, + ); + socket = upgraded; + if (head?.length) pending = Buffer.concat([pending, head]); + upgraded.on("data", (chunk: Buffer) => { + pending = Buffer.concat([pending, chunk]); + parse(); + }); + upgraded.on("error", () => {}); + }); + await new Promise((resolve) => { + server.listen(0, "127.0.0.1", () => resolve()); + }); + const address = server.address() as AddressInfo; + return { + url: `ws://127.0.0.1:${address.port}`, + commands, + emit(event) { + socket?.write(serverFrame(JSON.stringify(event))); + }, + close() { + socket?.destroy(); + return new Promise((resolve) => server.close(() => resolve())); + }, + }; +} + +export async function waitFor( + predicate: () => boolean, + label: string, +): Promise { + const deadline = Date.now() + 3_000; + while (!predicate()) { + if (Date.now() > deadline) + throw new Error(`timed out waiting for ${label}`); + await new Promise((resolve) => setTimeout(resolve, 10)); + } +} From 4f5cbfdb189fea4da08bce8a99a301ca90e73b61 Mon Sep 17 00:00:00 2001 From: Ewan Date: Tue, 17 Nov 2026 04:30:22 +0100 Subject: [PATCH 2/6] fix(browser-pay): read Adyen not-enabled in any case, type a per-brand Adyen stand-in (SAP-5180) - isAdyenNotEnabled compares case-insensitively: the backend sends 409 {"code":"ADYEN_ENCRYPTION_NOT_ENABLED"}, which surfaced as adyen_encrypt. Contract test feeds that body verbatim through httpPaymentRelay -> attachInterceptor -> fillCard. - fillCard types Adyen's plain consumer test card for the card's brand (visa 4111.., mastercard 5555 4444.., amex 3700..) into secured fields instead of the placeholder number, whose random BIN can name a variant Adyen refuses for the real card (109 Invalid variant). Missing or other brand: blocked adyen_card_brand, backend not asked. - prepareAdyen: a later answer drops earlier prepared fields, an older call finishing last cannot restore them, and after detach it reports adyen_not_enabled. Co-Authored-By: Claude Opus 5.5 --- .changeset/browser-pay-adyen-reencrypt.md | 2 +- packages/browser-pay/README.md | 8 +- packages/browser-pay/src/contract.ts | 13 ++- .../browser-pay/src/fill-card.adyen.test.ts | 106 +++++++++++++++++- packages/browser-pay/src/fill-card.ts | 60 +++++++--- .../browser-pay/src/interceptor.adyen.test.ts | 69 ++++++++++++ packages/browser-pay/src/interceptor.ts | 18 ++- .../adyen-encrypt-not-enabled.409.json | 1 + 8 files changed, 246 insertions(+), 31 deletions(-) create mode 100644 packages/browser-pay/test/fixtures/adyen-encrypt-not-enabled.409.json diff --git a/.changeset/browser-pay-adyen-reencrypt.md b/.changeset/browser-pay-adyen-reencrypt.md index a4efac6b4..a50342608 100644 --- a/.changeset/browser-pay-adyen-reencrypt.md +++ b/.changeset/browser-pay-adyen-reencrypt.md @@ -2,4 +2,4 @@ "@sapiom/browser-pay": minor --- -Pay Adyen secured-fields checkouts by re-encrypting the card in the card vault (SAP-5180). The interceptor holds an outgoing Adyen payment (`paymentMethod.encryptedCardNumber`, on the merchant's `/payments` call or Adyen's `/sessions/{id}/payments`), asks `POST /v1/transactions/{id}/payment/adyen/encrypt` for the card's own encrypted fields, swaps the four `encrypted*` fields and sends the request on. It runs only when the backend answers with fields: its `adyen_encryption_not_enabled` answer, a relay without `adyenEncrypt`, or `disableAdyenEncryption: true` fail the payment closed (`adyen_not_enabled`). `fillCard(page, card, { adyen: handle })` asks first and types nothing on Adyen secured fields unless the payment will be re-encrypted (`blocked`). +Pay Adyen secured-fields checkouts by re-encrypting the card in the card vault (SAP-5180). The interceptor holds an outgoing Adyen payment (`paymentMethod.encryptedCardNumber`, on the merchant's `/payments` call or Adyen's `/sessions/{id}/payments`), asks `POST /v1/transactions/{id}/payment/adyen/encrypt` for the card's own encrypted fields, swaps the four `encrypted*` fields and sends the request on. It runs only when the backend answers with fields: its `adyen_encryption_not_enabled` answer, a relay without `adyenEncrypt`, or `disableAdyenEncryption: true` fail the payment closed (`adyen_not_enabled`). `fillCard(page, card, { adyen: handle })` asks first and types nothing on Adyen secured fields unless the payment will be re-encrypted (`blocked`). There it types Adyen's plain test card for the card's `brand` (`visa`, `mastercard`, `american-express`) instead of the placeholder number, so Adyen's variant check fits the real card; another or no brand is `blocked: "adyen_card_brand"`. The backend's not-enabled code is read in any case. diff --git a/packages/browser-pay/README.md b/packages/browser-pay/README.md index 6663de243..8cb7ffa77 100644 --- a/packages/browser-pay/README.md +++ b/packages/browser-pay/README.md @@ -51,13 +51,15 @@ It throws a `TypeError`, whose message carries no card values, before touching a ## Adyen secured fields -Adyen secured fields encrypt the typed card inside Adyen's iframes, so the placeholder never shows in the payment request. When the backend has Adyen encryption switched on, the interceptor holds any request whose JSON body has a string `paymentMethod.encryptedCardNumber` (the merchant's own `/payments` call, or Adyen's `/sessions/{id}/payments`), asks `POST /v1/transactions/{transactionId}/payment/adyen/encrypt` with `x-api-key` and `{ "injectionRef", "clientKey", "pageOrigin" }` for the authorized card's own `encryptedCardNumber`, `encryptedExpiryMonth`, `encryptedExpiryYear` and `encryptedSecurityCode`, replaces those four fields and sends the request on. Every other key is kept. The event is `reencrypted`. +Adyen secured fields encrypt the typed card inside Adyen's iframes, so what was typed never shows in the payment request. A body whose `paymentMethod` is nested deeper than the top level is not recognised and goes on unchanged, with the typed card's ciphertext, so the payment is declined. When the backend has Adyen encryption switched on, the interceptor holds any request whose JSON body has a string `paymentMethod.encryptedCardNumber` (the merchant's own `/payments` call, or Adyen's `/sessions/{id}/payments`), asks `POST /v1/transactions/{transactionId}/payment/adyen/encrypt` with `x-api-key` and `{ "injectionRef", "clientKey", "pageOrigin" }` for the authorized card's own `encryptedCardNumber`, `encryptedExpiryMonth`, `encryptedExpiryYear` and `encryptedSecurityCode`, replaces those four fields and sends the request on. Every other key is kept. The event is `reencrypted`. The client key comes from the secured-field iframe URL (`…/securedfields/{clientKey}/{version}/securedFields.html`), else from the page (`#clientKey`, `data-client-key`, or a `clientKey: "test_…"` literal in an inline script). Two different keys on one page give none. -It is off unless the backend says otherwise. A payment fails closed, and the placeholder's ciphertext is never sent, with `adyen_not_enabled` when the backend answers `adyen_encryption_not_enabled` (as `code` or `reason`), when the relay has no `adyenEncrypt`, or when `AttachOptions.disableAdyenEncryption` is `true`; with `adyen_client_key` when no single key is found; and with `adyen_encrypt` when the call fails or outlasts `attemptTimeoutMs`. No option turns it on past the backend. +It is off unless the backend says otherwise. A payment fails closed, and the placeholder's ciphertext is never sent, with `adyen_not_enabled` when the backend answers `adyen_encryption_not_enabled` (as `code` or `reason`, in any case; the backend sends `ADYEN_ENCRYPTION_NOT_ENABLED`), when the relay has no `adyenEncrypt`, or when `AttachOptions.disableAdyenEncryption` is `true`; with `adyen_client_key` when no single key is found; and with `adyen_encrypt` when the call fails or outlasts `attemptTimeoutMs`. No option turns it on past the backend. -Pass the interceptor handle to `fillCard` so it asks before typing: `fillCard(page, card, { adyen: handle })`. On a page with Adyen secured-field iframes it types nothing, and returns `ok: false` with `blocked` (`adyen_not_enabled`, `adyen_client_key`, or `adyen_encrypt`), unless the backend returned fields; those fields are then used once for the payment, within 10 minutes. Without `adyen` it never types into Adyen secured fields. The placeholder typed into the iframes must be the authorized card's brand, since Adyen reads the brand from what was typed. +Pass the interceptor handle to `fillCard` so it asks before typing: `fillCard(page, card, { adyen: handle })`. On a page with Adyen secured-field iframes it types nothing, and returns `ok: false` with `blocked` (`adyen_not_enabled`, `adyen_client_key`, `adyen_encrypt`, or `adyen_card_brand`), unless the backend returned fields; those fields are then used once for the payment, within 10 minutes, unless a later `prepareAdyen` answer replaces them. Without `adyen` it never types into Adyen secured fields. + +On Adyen secured fields `fillCard` types a stand-in number instead of the placeholder number: Adyen's published plain consumer test card for the card's `brand` (`visa`, `mastercard` or `american-express`, as the placeholder names it). Adyen sends the brand and variant it reads from the typed BIN with the payment and refuses one whose variant does not fit the real card (`109 Invalid variant`), so a random BIN of the right brand is not enough. Pass `brand` in `card`; without it, or for another brand, it types nothing and returns `blocked: "adyen_card_brand"`. ## Relay contract diff --git a/packages/browser-pay/src/contract.ts b/packages/browser-pay/src/contract.ts index 42ae57510..a28a372b7 100644 --- a/packages/browser-pay/src/contract.ts +++ b/packages/browser-pay/src/contract.ts @@ -133,7 +133,8 @@ export interface AdyenEncryptRequest { /** * The backend's typed answer when Adyen card encryption is switched off for - * this deployment. It arrives as `code` (an error body) or `reason`. + * this deployment. It arrives as `code` (an error body) or `reason`, in any + * case: the backend sends `ADYEN_ENCRYPTION_NOT_ENABLED`. */ export const ADYEN_ENCRYPTION_NOT_ENABLED = "adyen_encryption_not_enabled"; @@ -144,8 +145,14 @@ export type AdyenEncryptResult = export function isAdyenNotEnabled(value: unknown): boolean { return ( isRecord(value) && - (value.code === ADYEN_ENCRYPTION_NOT_ENABLED || - value.reason === ADYEN_ENCRYPTION_NOT_ENABLED) + (isNotEnabledCode(value.code) || isNotEnabledCode(value.reason)) + ); +} + +function isNotEnabledCode(value: unknown): boolean { + return ( + typeof value === "string" && + value.toLowerCase() === ADYEN_ENCRYPTION_NOT_ENABLED ); } diff --git a/packages/browser-pay/src/fill-card.adyen.test.ts b/packages/browser-pay/src/fill-card.adyen.test.ts index 576ea9e78..1443927e5 100644 --- a/packages/browser-pay/src/fill-card.adyen.test.ts +++ b/packages/browser-pay/src/fill-card.adyen.test.ts @@ -1,3 +1,7 @@ +import { readFileSync } from "node:fs"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import { join } from "node:path"; import { ADYEN_DOM_CLIENT_KEY_EXPRESSION } from "./detect"; import { fillCard, @@ -6,13 +10,20 @@ import { type LocatorLike, type PageLike, } from "./fill-card"; -import type { AdyenGate, AdyenReadiness } from "./interceptor"; +import { + attachInterceptor, + type AdyenGate, + type AdyenReadiness, +} from "./interceptor"; +import { httpPaymentRelay } from "./relay"; +import { startCdpStub } from "../test/cdp-stub"; const CARD: CardToFill = { - number: "4000000000000002", + number: "4778901234561927", expMonth: 3, expYear: 2029, cvc: "321", + brand: "visa", }; const PAGE = "https://shop.example/checkout"; @@ -44,6 +55,8 @@ interface FakePage { page: PageLike; /** Every click, fill or keystroke sequence sent to any field. */ touched: string[]; + /** The last value typed or filled into each field, by hint. */ + typed: Record; } function fakePage( @@ -51,6 +64,7 @@ function fakePage( domKey: string | null = null, ): FakePage { const touched: string[] = []; + const typed: Record = {}; const built: FrameLike[] = []; const main: FrameLike = makeFrame(PAGE, undefined); built.push(main); @@ -66,10 +80,12 @@ function fakePage( fill: async (text) => { if (text) touched.push(`fill ${hint}`); value = text; + typed[hint ?? ""] = text; }, pressSequentially: async (text) => { touched.push(`type ${hint}`); value = text; + typed[hint ?? ""] = text; }, press: async () => {}, inputValue: async () => value, @@ -105,6 +121,7 @@ function fakePage( return { page: { frames: () => built, waitForTimeout: async () => {} }, touched, + typed, }; } @@ -171,6 +188,42 @@ describe("fillCard on Adyen secured fields", () => { expect(touched).toStrictEqual([]); }); + it.each([ + ["visa", "4111111111111111"], + ["mastercard", "5555444433331111"], + ["american-express", "370000000000002"], + ])( + "types Adyen's plain %s test card, not the placeholder number", + async (brand, standIn) => { + const { page, typed } = fakePage(ADYEN_FIELDS(KEY)); + const result = await fillCard( + page, + { ...CARD, brand }, + { timeoutMs: 50, keyDelayMs: 0, adyen: gate({ enabled: true }) }, + ); + expect(result.ok).toBe(true); + expect(typed.encryptedcardnumber).toBe(standIn); + }, + ); + + it("types nothing, without asking the backend, when the card's brand has no stand-in", async () => { + for (const brand of [undefined, "discover", "unknown", "toString"]) { + const { page, touched } = fakePage(ADYEN_FIELDS(KEY)); + const adyen = gate({ enabled: true }); + const result = await fillCard( + page, + { ...CARD, brand }, + { timeoutMs: 50, adyen }, + ); + expect(result).toStrictEqual({ + ...NOT_TYPED, + blocked: "adyen_card_brand", + }); + expect(adyen.calls).toHaveLength(0); + expect(touched).toStrictEqual([]); + } + }); + it("types the stand-in when the backend will re-encrypt the card", async () => { const { page, touched } = fakePage(ADYEN_FIELDS(KEY)); const adyen = gate({ enabled: true }); @@ -244,3 +297,52 @@ describe("fillCard on Adyen secured fields", () => { expect(adyen.calls).toHaveLength(0); }); }); + +describe("fillCard against the backend's not-enabled answer, through the real relay", () => { + /** The backend's body, verbatim: `adyen-encrypt.controller.ts` upper-cases the code. */ + const BACKEND_BODY = readFileSync( + join(__dirname, "../test/fixtures/adyen-encrypt-not-enabled.409.json"), + "utf8", + ); + + it.each([ + ["the backend's 409 body", 409, BACKEND_BODY], + ["a lowercase code", 409, '{"code":"adyen_encryption_not_enabled"}'], + ])( + "blocks with adyen_not_enabled and types nothing on %s", + async (_name, status, body) => { + const server = http.createServer((_req, res) => { + res.writeHead(status, { "content-type": "application/json" }); + res.end(body); + }); + await new Promise((resolve) => + server.listen(0, "127.0.0.1", resolve), + ); + const stub = await startCdpStub(); + const handle = await attachInterceptor(stub.url, { + relay: httpPaymentRelay({ + baseUrl: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, + apiKey: "test-key", + transactionId: "tx_adyen", + }), + placeholder: { number: CARD.number, injectionRef: "inj_adyen" }, + }); + try { + const { page, touched } = fakePage(ADYEN_FIELDS(KEY)); + const result = await fillCard(page, CARD, { + timeoutMs: 50, + adyen: handle, + }); + expect(result).toStrictEqual({ + ...NOT_TYPED, + blocked: "adyen_not_enabled", + }); + expect(touched).toStrictEqual([]); + } finally { + await handle.detach(); + await stub.close(); + server.close(); + } + }, + ); +}); diff --git a/packages/browser-pay/src/fill-card.ts b/packages/browser-pay/src/fill-card.ts index 445a2d604..2b7af0819 100644 --- a/packages/browser-pay/src/fill-card.ts +++ b/packages/browser-pay/src/fill-card.ts @@ -28,8 +28,28 @@ export interface CardToFill { cvc: string; /** Typed only when the form has a cardholder-name field. */ name?: string; + /** + * The card's brand as the placeholder names it (`visa`, `mastercard`, `american-express`). + * Needed only on Adyen secured fields, where it picks the stand-in number typed. + */ + brand?: string; } +/** + * What `fillCard` types into Adyen secured fields instead of the placeholder number: one of + * Adyen's published test cards per brand, on a plain consumer BIN. Adyen secured fields send the + * brand and variant they read from the typed BIN with the payment, and Adyen refuses a payment + * whose variant does not fit the re-encrypted real card ("109 Invalid variant"); a random BIN of + * the right brand can name a variant the real card is not. The typed number never reaches Adyen: + * its ciphertext is replaced, or the payment fails closed. + * Source: https://docs.adyen.com/development-resources/test-cards-and-credentials/test-card-numbers/ + */ +const ADYEN_STAND_IN_NUMBERS: ReadonlyMap = new Map([ + ["visa", "4111111111111111"], + ["mastercard", "5555444433331111"], + ["american-express", "370000000000002"], +]); + /** A card form field `fillCard` recognises. */ export type CardField = | "number" @@ -64,7 +84,8 @@ export interface FillCardResult { /** * Set when nothing was typed because the form is Adyen secured fields and paying it is not * possible: `adyen_not_enabled` (switched off, or no `adyen` gate given), `adyen_client_key` - * (the page's client key could not be read), `adyen_encrypt` (the backend failed). + * (the page's client key could not be read), `adyen_encrypt` (the backend failed), + * `adyen_card_brand` (the card's `brand` is missing or has no Adyen stand-in). */ blocked?: FillCardBlock; } @@ -72,7 +93,8 @@ export interface FillCardResult { /** Why `fillCard` typed nothing. */ export type FillCardBlock = | Extract["reason"] - | "adyen_client_key"; + | "adyen_client_key" + | "adyen_card_brand"; export interface FillCardOptions { /** Delay between keystrokes, in milliseconds. Defaults to 25. */ @@ -783,8 +805,8 @@ export async function fillCard( ranked = await rank(page, await scan(page, extra, untrusted)); } - const blocked = await adyenBlock(page, options.adyen); - if (blocked) { + const typing = await adyenTyping(page, options.adyen, card); + if ("blocked" in typing) { return { ok: false, filled: [], @@ -792,14 +814,14 @@ export async function fillCard( unconfirmed: [], origins: {}, untrusted: [...untrusted], - blocked, + blocked: typing.blocked, }; } const split = ranked.has("expMonth") && ranked.has("expYear"); const mm = two(card.expMonth); const plan: Array<[CardField, (m: Match) => Promise]> = [ - ["number", (m) => typeFirst(m, [card.number], true, false, delay)], + ["number", (m) => typeFirst(m, [typing.number], true, false, delay)], ...(split ? ([ [ @@ -892,20 +914,24 @@ export async function fillCard( } /** - * For a page with Adyen secured-field iframes: why typing must not start, or `undefined` when the - * gate says the payment will be re-encrypted. Pages without them are never blocked here. - * The client key comes from the iframe URLs; a page config is read only when they carry none. + * The number to type, or why typing must not start. A page with Adyen secured-field iframes gets + * the card brand's stand-in, once the gate says the payment will be re-encrypted; any other page + * gets the card's own number. The client key comes from the iframe URLs; a page config is read + * only when they carry none. */ -async function adyenBlock( +async function adyenTyping( page: PageLike, gate: AdyenGate | undefined, -): Promise { + card: CardToFill, +): Promise<{ number: string } | { blocked: FillCardBlock }> { const frames = page.frames(); const adyenFrames = frames.filter((f) => isAdyenSecuredFieldsFrameUrl(f.url()), ); - if (adyenFrames.length === 0) return undefined; - if (!gate) return "adyen_not_enabled"; + if (adyenFrames.length === 0) return { number: card.number }; + if (!gate) return { blocked: "adyen_not_enabled" }; + const standIn = ADYEN_STAND_IN_NUMBERS.get(card.brand ?? ""); + if (!standIn) return { blocked: "adyen_card_brand" }; const keys = new Set(); for (const frame of adyenFrames) { const key = adyenClientKeyFromFrameUrl(frame.url()); @@ -920,11 +946,13 @@ async function adyenBlock( if (isAdyenClientKey(fromDom)) clientKey = fromDom; } // Two different keys on one page: never encrypt the card to a guess. - if (!clientKey) return "adyen_client_key"; + if (!clientKey) return { blocked: "adyen_client_key" }; const pageOrigin = originOf(frames[0]?.url() ?? ""); - if (!/^https?:\/\//.test(pageOrigin)) return "adyen_client_key"; + if (!/^https?:\/\//.test(pageOrigin)) return { blocked: "adyen_client_key" }; const readiness = await gate .prepareAdyen({ clientKey, pageOrigin }) .catch((): AdyenReadiness => ({ enabled: false, reason: "adyen_encrypt" })); - return readiness.enabled ? undefined : readiness.reason; + return readiness.enabled + ? { number: standIn } + : { blocked: readiness.reason }; } diff --git a/packages/browser-pay/src/interceptor.adyen.test.ts b/packages/browser-pay/src/interceptor.adyen.test.ts index ef8156013..de29e8e5c 100644 --- a/packages/browser-pay/src/interceptor.adyen.test.ts +++ b/packages/browser-pay/src/interceptor.adyen.test.ts @@ -584,6 +584,75 @@ describe("Adyen encryption gate", () => { assertNothingSecret(harness); }); + it("a later not-enabled answer drops fields an earlier prepareAdyen fetched", async () => { + const answers = [ENCRYPTED, NOT_ENABLED, NOT_ENABLED]; + harness = await arm({ + frames: [{ sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }], + encrypt: async () => answers.shift()!, + }); + const input = { clientKey: CLIENT_KEY, pageOrigin: PAGE_ORIGIN }; + await expect(harness.prepare(input)).resolves.toStrictEqual({ + enabled: true, + }); + await expect(harness.prepare(input)).resolves.toStrictEqual({ + enabled: false, + reason: "adyen_not_enabled", + }); + pause(harness.stub, "req-denied", ADVANCED); + await expectClosed("req-denied", "adyen_not_enabled"); + expect(harness.encryptCalls).toHaveLength(3); + }); + + it("an older prepareAdyen finishing last does not restore fields a newer one cleared", async () => { + let releaseFirst: (result: AdyenEncryptResult) => void = () => {}; + const answers: Array> = [ + new Promise((resolve) => (releaseFirst = resolve)), + Promise.resolve(NOT_ENABLED), + Promise.resolve(NOT_ENABLED), + ]; + harness = await arm({ + frames: [{ sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }], + encrypt: () => answers.shift()!, + }); + const input = { clientKey: CLIENT_KEY, pageOrigin: PAGE_ORIGIN }; + const older = harness.prepare(input); + await expect(harness.prepare(input)).resolves.toMatchObject({ + enabled: false, + }); + releaseFirst(ENCRYPTED); + await older; + pause(harness.stub, "req-race", ADVANCED); + await expectClosed("req-race", "adyen_not_enabled"); + expect(harness.encryptCalls).toHaveLength(3); + }); + + it("prepareAdyen after detach says not enabled without asking the backend", async () => { + harness = await arm({}); + await harness.detach(); + await expect( + harness.prepare({ clientKey: CLIENT_KEY, pageOrigin: PAGE_ORIGIN }), + ).resolves.toStrictEqual({ enabled: false, reason: "adyen_not_enabled" }); + expect(harness.encryptCalls).toHaveLength(0); + }); + + it("prepareAdyen says not enabled when detach lands while the backend answers", async () => { + let release: (result: AdyenEncryptResult) => void = () => {}; + harness = await arm({ + encrypt: () => new Promise((resolve) => (release = resolve)), + }); + const pending = harness.prepare({ + clientKey: CLIENT_KEY, + pageOrigin: PAGE_ORIGIN, + }); + await waitFor(() => harness!.encryptCalls.length === 1, "encrypt call"); + await harness.detach(); + release(ENCRYPTED); + await expect(pending).resolves.toStrictEqual({ + enabled: false, + reason: "adyen_not_enabled", + }); + }); + it("prepareAdyen reports a backend failure without throwing or logging values", async () => { harness = await arm({ encrypt: async () => { diff --git a/packages/browser-pay/src/interceptor.ts b/packages/browser-pay/src/interceptor.ts index 83e0058bb..bf033937e 100644 --- a/packages/browser-pay/src/interceptor.ts +++ b/packages/browser-pay/src/interceptor.ts @@ -396,6 +396,8 @@ class PaymentInterceptor { string, { fields: AdyenEncryptedFields; at: number } >(); + /** Counts `prepareAdyen` calls, so only the latest one's answer is kept. */ + private adyenPrepareCalls = 0; private readonly timeoutMs: number; private readonly attemptTimeoutMs: number; private readonly logger: PayLogger; @@ -848,7 +850,11 @@ class PaymentInterceptor { clientKey: string; pageOrigin: string; }): Promise { - if (!this.adyenAllowed()) { + // Any new answer replaces fields an earlier call prepared, so a later "off" is never bypassed. + const key = preparedKey(input.clientKey, input.pageOrigin); + this.preparedAdyen.delete(key); + const call = ++this.adyenPrepareCalls; + if (this.closed || !this.adyenAllowed()) { return { enabled: false, reason: "adyen_not_enabled" }; } if (!isAdyenClientKey(input.clientKey)) { @@ -861,13 +867,13 @@ class PaymentInterceptor { this.logAdyenFailure(error); return { enabled: false, reason: "adyen_encrypt" }; } - if (result.outcome === "not_enabled") { + if (this.closed || result.outcome === "not_enabled") { return { enabled: false, reason: "adyen_not_enabled" }; } - this.preparedAdyen.set(preparedKey(input.clientKey, input.pageOrigin), { - fields: result.fields, - at: Date.now(), - }); + // A slower, older call must not restore fields a newer call cleared. + if (call === this.adyenPrepareCalls) { + this.preparedAdyen.set(key, { fields: result.fields, at: Date.now() }); + } return { enabled: true }; } diff --git a/packages/browser-pay/test/fixtures/adyen-encrypt-not-enabled.409.json b/packages/browser-pay/test/fixtures/adyen-encrypt-not-enabled.409.json new file mode 100644 index 000000000..de7a5895a --- /dev/null +++ b/packages/browser-pay/test/fixtures/adyen-encrypt-not-enabled.409.json @@ -0,0 +1 @@ +{"code":"ADYEN_ENCRYPTION_NOT_ENABLED"} From cfdd6e0af5f45645793c2ed42e65b9e1dbb0bff9 Mon Sep 17 00:00:00 2001 From: Ewan Date: Tue, 17 Nov 2026 04:46:04 +0100 Subject: [PATCH 3/6] test(browser-pay): give the Adyen interceptor integration test the 60s budget its siblings have (SAP-5180) CI test (22.x) on 4f5cbfdb hit Jest's 5s default on this Chromium test. Like the other tests in the suite, it now closes the shop's keep-alive sockets before close(). Co-Authored-By: Claude Opus 5.5 --- packages/browser-pay/src/interceptor.integration.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/browser-pay/src/interceptor.integration.test.ts b/packages/browser-pay/src/interceptor.integration.test.ts index 01f8bdec0..174c30279 100644 --- a/packages/browser-pay/src/interceptor.integration.test.ts +++ b/packages/browser-pay/src/interceptor.integration.test.ts @@ -837,9 +837,10 @@ if (!chromeBin) { } finally { await page?.close().catch(() => {}); await handle.detach(); + shop.server.closeAllConnections(); await new Promise((resolve) => shop.server.close(resolve)); } - }); + }, 60_000); it("refuses a real Playwright browser and page, which have no wsEndpoint()", async () => { const { chromium } = await import("playwright"); From b00597412fb56cb180d9c6fc823e1bbd496341da Mon Sep 17 00:00:00 2001 From: Ewan Date: Tue, 17 Nov 2026 04:46:46 +0100 Subject: [PATCH 4/6] fix(browser-pay): read the page's Adyen client key only when every DOM source names the same one (SAP-5180) The DOM fallback returned the first key it found, so a stale #clientKey or script literal could pick the key while a different one was also on the page. It now collects keys from every secured-field iframe src, #clientKey, data-client-key and each inline clientKey literal, and returns one only when they agree. An undecodable iframe key is skipped instead of failing the whole read. Keys may contain lower-case letters, as Adyen documents. Co-Authored-By: Claude Opus 5.5 --- packages/browser-pay/src/detect.test.ts | 7 +++- packages/browser-pay/src/detect.ts | 39 +++++++++-------- .../src/fill-card.integration.test.ts | 42 +++++++++++++++++++ 3 files changed, 69 insertions(+), 19 deletions(-) diff --git a/packages/browser-pay/src/detect.test.ts b/packages/browser-pay/src/detect.test.ts index fe721969e..53527faec 100644 --- a/packages/browser-pay/src/detect.test.ts +++ b/packages/browser-pay/src/detect.test.ts @@ -57,6 +57,11 @@ describe("adyenClientKeyFromFrameUrl", () => { "https://checkoutshopper-live-us.adyen.com/checkoutshopper/securedfields/live_Q1W2E3/5.0.0/securedFields.html", ), ).toBe("live_Q1W2E3"); + expect( + adyenClientKeyFromFrameUrl( + "https://checkoutshopper-test.adyen.com/checkoutshopper/securedfields/test_870be2854add4f56b86778353010f36c/6.4.1/securedFields.html", + ), + ).toBe("test_870be2854add4f56b86778353010f36c"); }); it("ignores other hosts, plain http, other paths and malformed keys", () => { @@ -65,7 +70,7 @@ describe("adyenClientKeyFromFrameUrl", () => { "https://evil-adyen.com/checkoutshopper/securedfields/test_ABC/6.4.1/securedFields.html", "http://checkoutshopper-test.adyen.com/checkoutshopper/securedfields/test_ABC/6.4.1/securedFields.html", "https://checkoutshopper-test.adyen.com/checkoutshopper/v1/clientKeys/test_ABC", - "https://checkoutshopper-test.adyen.com/checkoutshopper/securedfields/test_abc/6.4.1/securedFields.html", + "https://checkoutshopper-test.adyen.com/checkoutshopper/securedfields/test_ab-c/6.4.1/securedFields.html", "https://checkoutshopper-test.adyen.com/checkoutshopper/securedfields/pub.v2.ABC/6.4.1/securedFields.html", "not a url", "", diff --git a/packages/browser-pay/src/detect.ts b/packages/browser-pay/src/detect.ts index 2d35a02f6..2eef6b588 100644 --- a/packages/browser-pay/src/detect.ts +++ b/packages/browser-pay/src/detect.ts @@ -116,11 +116,11 @@ export function redactHeld(value: string, number: string): string { return maskHeldSpans(value, digits); } -const ADYEN_CLIENT_KEY = /^(test|live)_[A-Z0-9]+$/; +const ADYEN_CLIENT_KEY = /^(test|live)_[A-Za-z0-9]+$/; const ADYEN_SECURED_FIELDS_PATH = /\/securedfields\/([^/]+)\/[^/]+\/securedFields\.html$/; -/** An Adyen client key: `test_` or `live_` and upper-case letters and digits. */ +/** An Adyen client key: `test_` or `live_` and letters and digits. */ export function isAdyenClientKey(value: unknown): value is string { return typeof value === "string" && ADYEN_CLIENT_KEY.test(value); } @@ -169,34 +169,37 @@ function safeDecode(value: string): string | undefined { /** * Evaluated in the checkout page when no secured-field iframe was seen as a - * target: the key in a secured-field iframe `src` in the DOM, then adyen-web - * config the page renders (`#clientKey`, `data-client-key`, or a - * `clientKey: "test_…"` literal in an inline script). Returns a string or - * `null`; the caller validates it. + * target: the keys in secured-field iframe `src`s in the DOM and in the + * adyen-web config the page renders (`#clientKey`, `data-client-key`, or + * `clientKey: "test_…"` literals in inline scripts). Returns the key when + * they all name one, else `null`; the caller validates it. */ export const ADYEN_DOM_CLIENT_KEY_EXPRESSION = `(() => { const shape = ${ADYEN_CLIENT_KEY.toString()}; - const ok = (value) => { + const keys = new Set(); + const add = (value) => { const text = typeof value === "string" ? value.trim() : ""; - return shape.test(text) ? text : null; + if (shape.test(text)) keys.add(text); }; for (const frame of document.querySelectorAll("iframe[src*='securedfields']")) { - const match = ${ADYEN_SECURED_FIELDS_PATH.toString()}.exec(new URL(frame.src, location.href).pathname); - const key = match && ok(decodeURIComponent(match[1])); - if (key) return key; + try { + const match = ${ADYEN_SECURED_FIELDS_PATH.toString()}.exec(new URL(frame.src, location.href).pathname); + if (match) add(decodeURIComponent(match[1])); + } catch { + // An unparseable src or key names nothing; the other sources still can. + } } const element = document.getElementById("clientKey"); - const fromElement = element && ok(element.value || element.textContent); - if (fromElement) return fromElement; + if (element) add(element.value || element.textContent); for (const node of document.querySelectorAll("[data-client-key],[data-clientkey]")) { - const key = ok(node.getAttribute("data-client-key") || node.getAttribute("data-clientkey")); - if (key) return key; + add(node.getAttribute("data-client-key") || node.getAttribute("data-clientkey")); } for (const script of document.querySelectorAll("script:not([src])")) { - const match = /clientKey["']?\\s*[:=]\\s*["']((?:test|live)_[A-Z0-9]+)["']/.exec(script.textContent || ""); - if (match) return match[1]; + for (const match of (script.textContent || "").matchAll(/clientKey["']?\\s*[:=]\\s*["']((?:test|live)_[A-Za-z0-9]+)["']/g)) { + add(match[1]); + } } - return null; + return keys.size === 1 ? [...keys][0] : null; })()`; /** diff --git a/packages/browser-pay/src/fill-card.integration.test.ts b/packages/browser-pay/src/fill-card.integration.test.ts index 286d7d3a4..370c6667d 100644 --- a/packages/browser-pay/src/fill-card.integration.test.ts +++ b/packages/browser-pay/src/fill-card.integration.test.ts @@ -2,6 +2,7 @@ import http from "node:http"; import { existsSync } from "node:fs"; import type { AddressInfo } from "node:net"; import type { Browser, Page } from "playwright"; +import { ADYEN_DOM_CLIENT_KEY_EXPRESSION } from "./detect"; import { fillCard, type CardToFill, type PageLike } from "./fill-card"; const CARD: CardToFill = { @@ -876,5 +877,46 @@ function serve( expect(JSON.stringify(result)).not.toContain(CARD.number); await page.close(); }); + + it.each([ + [ + "one key named by every source", + `
test_ONEKEY1
+`, + "test_ONEKEY1", + ], + [ + "a lower-case key", + `
test_870be2854add4f56b86778353010f36c
`, + "test_870be2854add4f56b86778353010f36c", + ], + [ + "an undecodable iframe key before a readable config", + ` +
test_ONEKEY1
`, + "test_ONEKEY1", + ], + [ + "#clientKey and a different data-client-key", + `
test_OLD123
`, + null, + ], + [ + "two different keys in one inline script", + ``, + null, + ], + ])( + "reads the page's Adyen client key: %s", + async (_name, body, expected) => { + const page = await browser.newPage(); + await page.route("https://*.adyen.com/**", (route) => route.abort()); + await page.setContent(`Checkout${body}`); + expect(await page.evaluate(ADYEN_DOM_CLIENT_KEY_EXPRESSION)).toBe( + expected, + ); + await page.close(); + }, + ); }, ); From e2ca340e60fbf22ee17bda71c56e572584607ea9 Mon Sep 17 00:00:00 2001 From: Ewan Date: Tue, 17 Nov 2026 04:47:07 +0100 Subject: [PATCH 5/6] fix(browser-pay): type the Adyen stand-in only into a number field Adyen's frames host (SAP-5180) A page with idle Adyen secured-field iframes and a visible native or other provider's card form got the brand's test card in that form, which the interceptor does not replace. The stand-in now goes only into number fields inside an Adyen secured-field frame; any other number field gets the card's own number. Co-Authored-By: Claude Opus 5.5 --- .../browser-pay/src/fill-card.adyen.test.ts | 16 ++++++++++++++++ packages/browser-pay/src/fill-card.ts | 18 ++++++++++++++---- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/packages/browser-pay/src/fill-card.adyen.test.ts b/packages/browser-pay/src/fill-card.adyen.test.ts index 1443927e5..412e86fed 100644 --- a/packages/browser-pay/src/fill-card.adyen.test.ts +++ b/packages/browser-pay/src/fill-card.adyen.test.ts @@ -280,6 +280,22 @@ describe("fillCard on Adyen secured fields", () => { expect(touched).toStrictEqual([]); }); + it("types the card's own number into a number field outside Adyen's frames", async () => { + const { page, typed } = fakePage([ + { url: securedField(KEY, "encryptedCardNumber") }, + { url: "https://js.stripe.com/v3/elements", hint: "cardnumber" }, + { url: "https://js.stripe.com/v3/exp", hint: "exp-date" }, + { url: "https://js.stripe.com/v3/cvc", hint: "cvc" }, + ]); + const result = await fillCard(page, CARD, { + timeoutMs: 50, + keyDelayMs: 0, + adyen: gate({ enabled: true }), + }); + expect(result.ok).toBe(true); + expect(typed.cardnumber).toBe(CARD.number); + }); + it("never asks the gate on a page without Adyen secured fields", async () => { const { page } = fakePage([ { url: "https://js.stripe.com/v3/elements", hint: "cardnumber" }, diff --git a/packages/browser-pay/src/fill-card.ts b/packages/browser-pay/src/fill-card.ts index 2b7af0819..757511a03 100644 --- a/packages/browser-pay/src/fill-card.ts +++ b/packages/browser-pay/src/fill-card.ts @@ -821,7 +821,17 @@ export async function fillCard( const split = ranked.has("expMonth") && ranked.has("expYear"); const mm = two(card.expMonth); const plan: Array<[CardField, (m: Match) => Promise]> = [ - ["number", (m) => typeFirst(m, [typing.number], true, false, delay)], + [ + "number", + (m) => + typeFirst( + m, + [isAdyenSecuredFieldsFrameUrl(m.url) ? typing.number : card.number], + true, + false, + delay, + ), + ], ...(split ? ([ [ @@ -914,9 +924,9 @@ export async function fillCard( } /** - * The number to type, or why typing must not start. A page with Adyen secured-field iframes gets - * the card brand's stand-in, once the gate says the payment will be re-encrypted; any other page - * gets the card's own number. The client key comes from the iframe URLs; a page config is read + * The number to type into Adyen secured fields, or why typing must not start. A page with Adyen + * secured-field iframes gets the card brand's stand-in for them, once the gate says the payment + * will be re-encrypted; a number field outside them, and any other page, gets the card's own number. The client key comes from the iframe URLs; a page config is read * only when they carry none. */ async function adyenTyping( From 4a01e17ceec5510ad1972f1ec04679d8ef717047 Mon Sep 17 00:00:00 2001 From: Ewan Date: Tue, 17 Nov 2026 04:52:48 +0100 Subject: [PATCH 6/6] fix(browser-pay): let an Adyen not-enabled answer void every prepared and in-flight success (SAP-5180) A not-enabled answer from the backend now clears prepared fields for every client key and page origin, and bumps a denial count. A prepareAdyen whose success lands after any denial answers not enabled and stores nothing, so fillCard types nothing on a superseded prepare. Regressions: cross-key denial drops cached fields; superseded prepare answers disabled; fillCard racing a newer denial types nothing. Co-Authored-By: Claude Opus 5.5 (SAP-5180) --- .../browser-pay/src/fill-card.adyen.test.ts | 55 +++++++++++++++++++ .../browser-pay/src/interceptor.adyen.test.ts | 45 +++++++++++++++ packages/browser-pay/src/interceptor.ts | 17 +++++- 3 files changed, 116 insertions(+), 1 deletion(-) diff --git a/packages/browser-pay/src/fill-card.adyen.test.ts b/packages/browser-pay/src/fill-card.adyen.test.ts index 412e86fed..e69c1b443 100644 --- a/packages/browser-pay/src/fill-card.adyen.test.ts +++ b/packages/browser-pay/src/fill-card.adyen.test.ts @@ -15,6 +15,7 @@ import { type AdyenGate, type AdyenReadiness, } from "./interceptor"; +import type { AdyenEncryptResult } from "./contract"; import { httpPaymentRelay } from "./relay"; import { startCdpStub } from "../test/cdp-stub"; @@ -314,6 +315,60 @@ describe("fillCard on Adyen secured fields", () => { }); }); +describe("fillCard racing a newer not-enabled answer, through the real interceptor", () => { + it("types nothing when its own prepare succeeds after a newer one was denied", async () => { + let releaseFirst: (result: AdyenEncryptResult) => void = () => {}; + const answers: Array> = [ + new Promise((resolve) => (releaseFirst = resolve)), + Promise.resolve({ outcome: "not_enabled" }), + ]; + let encryptCalls = 0; + const stub = await startCdpStub(); + const handle = await attachInterceptor(stub.url, { + relay: { + relay: async () => ({ outcome: "unknown" }), + adyenEncrypt: () => { + encryptCalls += 1; + return answers.shift()!; + }, + }, + placeholder: { number: CARD.number, injectionRef: "inj_adyen" }, + }); + try { + const { page, touched } = fakePage(ADYEN_FIELDS(KEY)); + const filling = fillCard(page, CARD, { + timeoutMs: 50, + keyDelayMs: 0, + adyen: handle, + }); + while (encryptCalls === 0) await new Promise((r) => setTimeout(r, 1)); + await expect( + handle.prepareAdyen({ + clientKey: KEY, + pageOrigin: "https://shop.example", + }), + ).resolves.toStrictEqual({ enabled: false, reason: "adyen_not_enabled" }); + releaseFirst({ + outcome: "encrypted", + fields: { + encryptedCardNumber: "eyJ.N", + encryptedExpiryMonth: "eyJ.M", + encryptedExpiryYear: "eyJ.Y", + encryptedSecurityCode: "eyJ.C", + }, + }); + await expect(filling).resolves.toStrictEqual({ + ...NOT_TYPED, + blocked: "adyen_not_enabled", + }); + expect(touched).toStrictEqual([]); + } finally { + await handle.detach(); + await stub.close(); + } + }); +}); + describe("fillCard against the backend's not-enabled answer, through the real relay", () => { /** The backend's body, verbatim: `adyen-encrypt.controller.ts` upper-cases the code. */ const BACKEND_BODY = readFileSync( diff --git a/packages/browser-pay/src/interceptor.adyen.test.ts b/packages/browser-pay/src/interceptor.adyen.test.ts index de29e8e5c..9f699f150 100644 --- a/packages/browser-pay/src/interceptor.adyen.test.ts +++ b/packages/browser-pay/src/interceptor.adyen.test.ts @@ -626,6 +626,51 @@ describe("Adyen encryption gate", () => { expect(harness.encryptCalls).toHaveLength(3); }); + it("a not-enabled answer for one key drops fields prepared for every other key", async () => { + const answers = [ENCRYPTED, NOT_ENABLED, ENCRYPTED]; + harness = await arm({ + frames: [{ sessionId: "frame-number", url: frameUrl(CLIENT_KEY) }], + encrypt: async () => answers.shift()!, + }); + await expect( + harness.prepare({ clientKey: CLIENT_KEY, pageOrigin: PAGE_ORIGIN }), + ).resolves.toStrictEqual({ enabled: true }); + await expect( + harness.prepare({ + clientKey: CLIENT_KEY, + pageOrigin: "https://other-shop.example", + }), + ).resolves.toStrictEqual({ enabled: false, reason: "adyen_not_enabled" }); + pause(harness.stub, "req-cross", ADVANCED); + await settle(harness.stub, "req-cross"); + // The payment asked the backend again instead of spending the cached fields. + expect(harness.encryptCalls).toHaveLength(3); + }); + + it("an older prepareAdyen succeeding after a newer denial answers not enabled", async () => { + let releaseFirst: (result: AdyenEncryptResult) => void = () => {}; + const answers: Array> = [ + new Promise((resolve) => (releaseFirst = resolve)), + Promise.resolve(NOT_ENABLED), + ]; + harness = await arm({ encrypt: () => answers.shift()! }); + const older = harness.prepare({ + clientKey: CLIENT_KEY, + pageOrigin: PAGE_ORIGIN, + }); + await expect( + harness.prepare({ + clientKey: CLIENT_KEY, + pageOrigin: "https://other-shop.example", + }), + ).resolves.toStrictEqual({ enabled: false, reason: "adyen_not_enabled" }); + releaseFirst(ENCRYPTED); + await expect(older).resolves.toStrictEqual({ + enabled: false, + reason: "adyen_not_enabled", + }); + }); + it("prepareAdyen after detach says not enabled without asking the backend", async () => { harness = await arm({}); await harness.detach(); diff --git a/packages/browser-pay/src/interceptor.ts b/packages/browser-pay/src/interceptor.ts index bf033937e..a10911d1d 100644 --- a/packages/browser-pay/src/interceptor.ts +++ b/packages/browser-pay/src/interceptor.ts @@ -398,6 +398,8 @@ class PaymentInterceptor { >(); /** Counts `prepareAdyen` calls, so only the latest one's answer is kept. */ private adyenPrepareCalls = 0; + /** Counts not-enabled answers, so a success begun before one is never used. */ + private adyenDenials = 0; private readonly timeoutMs: number; private readonly attemptTimeoutMs: number; private readonly logger: PayLogger; @@ -830,6 +832,7 @@ class PaymentInterceptor { } if (this.closed) return { action: "fail", reason: "detached" }; if (result.outcome === "not_enabled") { + this.denyAdyen(); return { action: "fail", reason: "adyen_not_enabled" }; } return { @@ -854,6 +857,7 @@ class PaymentInterceptor { const key = preparedKey(input.clientKey, input.pageOrigin); this.preparedAdyen.delete(key); const call = ++this.adyenPrepareCalls; + const denials = this.adyenDenials; if (this.closed || !this.adyenAllowed()) { return { enabled: false, reason: "adyen_not_enabled" }; } @@ -867,7 +871,12 @@ class PaymentInterceptor { this.logAdyenFailure(error); return { enabled: false, reason: "adyen_encrypt" }; } - if (this.closed || result.outcome === "not_enabled") { + if (result.outcome === "not_enabled") { + this.denyAdyen(); + return { enabled: false, reason: "adyen_not_enabled" }; + } + // A success that lands after any not-enabled answer is stale: the backend has since said off. + if (this.closed || denials !== this.adyenDenials) { return { enabled: false, reason: "adyen_not_enabled" }; } // A slower, older call must not restore fields a newer call cleared. @@ -877,6 +886,12 @@ class PaymentInterceptor { return { enabled: true }; } + /** The backend's "off" covers every key and origin, so no prepared fields survive it. */ + private denyAdyen(): void { + this.adyenDenials += 1; + this.preparedAdyen.clear(); + } + /** Prepared fields are used once, and only while fresh. */ private takePreparedAdyen( clientKey: string,