Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/browser-pay-adyen-reencrypt.md
Original file line number Diff line number Diff line change
@@ -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`). 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.
16 changes: 14 additions & 2 deletions packages/browser-pay/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ 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 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`, 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`, `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

`POST /v1/transactions/{transactionId}/payment/relay` with `x-api-key`. `transactionId` is only in the path. The JSON body is:
Expand Down Expand Up @@ -168,7 +180,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.

Expand All @@ -186,6 +198,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.
60 changes: 60 additions & 0 deletions packages/browser-pay/src/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,63 @@ 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<AdyenEncryptedField, string>;

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`, in any
* case: the backend sends `ADYEN_ENCRYPTION_NOT_ENABLED`.
*/
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) &&
(isNotEnabledCode(value.code) || isNotEnabledCode(value.reason))
);
}

function isNotEnabledCode(value: unknown): boolean {
return (
typeof value === "string" &&
value.toLowerCase() === 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 };
}
115 changes: 114 additions & 1 deletion packages/browser-pay/src/detect.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { redactHeld, textHoldsPlaceholderNumber } from "./detect";
import {
adyenClientKeyFromFrameUrl,
isAdyenSecuredFieldsFrameUrl,
isAdyenSecuredFieldsPayment,
redactHeld,
textHoldsPlaceholderNumber,
withAdyenEncryptedFields,
} from "./detect";

const NUMBER = "4242424242424242";

Expand Down Expand Up @@ -37,3 +44,109 @@ 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");
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", () => {
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_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",
"",
]) {
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));
});
});
136 changes: 136 additions & 0 deletions packages/browser-pay/src/detect.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import type { AdyenEncryptedFields } from "./contract.js";
import { isRecord } from "./guards.js";

export interface HeldPlaceholder {
number: string;
injectionRef: string;
Expand Down Expand Up @@ -112,3 +115,136 @@ 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-Za-z0-9]+$/;
const ADYEN_SECURED_FIELDS_PATH =
/\/securedfields\/([^/]+)\/[^/]+\/securedFields\.html$/;

/** 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);
}

/**
* 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 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 keys = new Set();
const add = (value) => {
const text = typeof value === "string" ? value.trim() : "";
if (shape.test(text)) keys.add(text);
};
for (const frame of document.querySelectorAll("iframe[src*='securedfields']")) {
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");
if (element) add(element.value || element.textContent);
for (const node of document.querySelectorAll("[data-client-key],[data-clientkey]")) {
add(node.getAttribute("data-client-key") || node.getAttribute("data-clientkey"));
}
for (const script of document.querySelectorAll("script:not([src])")) {
for (const match of (script.textContent || "").matchAll(/clientKey["']?\\s*[:=]\\s*["']((?:test|live)_[A-Za-z0-9]+)["']/g)) {
add(match[1]);
}
}
return keys.size === 1 ? [...keys][0] : null;
})()`;
Comment thread
ratataque marked this conversation as resolved.
Resolved

/**
* 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<string, unknown> | undefined {
if (!isRecord(value) || !isRecord(value.paymentMethod)) return undefined;
const method = value.paymentMethod;
return typeof method.encryptedCardNumber === "string" &&
method.encryptedCardNumber.length > 0
? method
: undefined;
}
Loading
Loading