@visa/cli 4.1.0-rc.155 → 4.1.0-rc.157
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/checkout-engine/adapters/generic.d.ts +32 -0
- package/dist/checkout-engine/adapters/generic.js +148 -1
- package/dist/checkout-engine/executor.d.ts +2 -0
- package/dist/checkout-engine/executor.js +11 -1
- package/dist/checkout-engine/web-bot-auth.d.ts +92 -0
- package/dist/checkout-engine/web-bot-auth.js +159 -0
- package/dist/cli.js +355 -352
- package/dist/mcp-server/index.js +273 -271
- package/dist/skills/pair-visa-agent/SKILL.md +68 -9
- package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
- package/package.json +2 -3
- package/server.json +2 -2
|
@@ -26,6 +26,38 @@ export declare function fillContactFieldMap(page: Page, fields: FieldMap, contac
|
|
|
26
26
|
export declare function fillFieldMap(page: Page, fields: FieldMap, credential: CardCredential, contact: Contact, opts?: {
|
|
27
27
|
fillTimeoutMs?: number;
|
|
28
28
|
}): Promise<FilledField[]>;
|
|
29
|
+
/**
|
|
30
|
+
* Re-detect and adopt fresh entries for every card field after the panel is
|
|
31
|
+
* unfolded. Injected for tests; the executor's own detector is used in
|
|
32
|
+
* production.
|
|
33
|
+
*/
|
|
34
|
+
export declare function refreshCardGroupFromPage(page: Page, fields: FieldMap, detect?: (page: Page) => Promise<DetectResult>): Promise<string[]>;
|
|
35
|
+
/**
|
|
36
|
+
* Reveal card fields that a checkout keeps collapsed until a payment method is
|
|
37
|
+
* chosen.
|
|
38
|
+
*
|
|
39
|
+
* `fillFields` skips any entry with `visible === false`, so a card-number input
|
|
40
|
+
* sitting inside a folded panel is never even attempted — the generic adapter
|
|
41
|
+
* then reports `ok: false` ("fill incomplete") without having typed anything.
|
|
42
|
+
* That is the correct default: filling an invisible input is how a credential
|
|
43
|
+
* gets typed into the wrong place. But a payment-method `<select>` guarding the
|
|
44
|
+
* card panel is common enough to be worth handling, and the recovery is a
|
|
45
|
+
* single deterministic interaction rather than a guess.
|
|
46
|
+
*
|
|
47
|
+
* We only ever SELECT a card option — never a wallet, bank transfer, or
|
|
48
|
+
* anything else — and we only act when the card field is already detected but
|
|
49
|
+
* hidden. If nothing changes, the caller proceeds exactly as before and still
|
|
50
|
+
* fails closed.
|
|
51
|
+
*
|
|
52
|
+
* Mutates `fields.number.visible` on success so the subsequent fill attempts
|
|
53
|
+
* the field it just revealed.
|
|
54
|
+
*/
|
|
55
|
+
export declare function revealCollapsedCardSection(page: Page, fields: FieldMap, opts?: {
|
|
56
|
+
timeoutMs?: number;
|
|
57
|
+
}): Promise<{
|
|
58
|
+
revealed: boolean;
|
|
59
|
+
via: string | null;
|
|
60
|
+
}>;
|
|
29
61
|
export declare class GenericAdapter implements CheckoutAdapter {
|
|
30
62
|
name: string;
|
|
31
63
|
matches(_detected: DetectResult): boolean;
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// <select> dropdowns, handles split vs combined expiry, two- vs four-digit
|
|
3
3
|
// years, and split first/last name. It is the fallback that should beat any
|
|
4
4
|
// well-behaved guest checkout on its own.
|
|
5
|
+
import { detectFields } from '../detect.js';
|
|
5
6
|
import { maskCvc, maskExpiry, maskPan, redactContact } from '../evidence.js';
|
|
6
7
|
function pad2(n) {
|
|
7
8
|
return String(n).padStart(2, '0');
|
|
@@ -212,6 +213,145 @@ export async function fillContactFieldMap(page, fields, contact, opts = {}) {
|
|
|
212
213
|
export async function fillFieldMap(page, fields, credential, contact, opts = {}) {
|
|
213
214
|
return fillFields(page, fields, credential, contact, opts);
|
|
214
215
|
}
|
|
216
|
+
/** Option text that identifies a card-paying choice, most specific first. */
|
|
217
|
+
const CARD_OPTION_PATTERNS = [
|
|
218
|
+
/^\s*visa\s*$/i,
|
|
219
|
+
/credit\s*card|card\s*payment/i,
|
|
220
|
+
/^\s*(mastercard|master\s*card)\s*$/i,
|
|
221
|
+
/\bcard\b/i,
|
|
222
|
+
];
|
|
223
|
+
/**
|
|
224
|
+
* Attribute selectors for a card-number input that survive a panel re-render,
|
|
225
|
+
* tried in order. The originally detected locator is tried first so a page that
|
|
226
|
+
* does NOT re-render keeps its higher-confidence match.
|
|
227
|
+
*/
|
|
228
|
+
const CARD_NUMBER_FALLBACK_SELECTORS = [
|
|
229
|
+
'input[autocomplete="cc-number"]',
|
|
230
|
+
'input[name*="creditcardnumber" i]',
|
|
231
|
+
'input[name*="cardnumber" i]',
|
|
232
|
+
'input[id*="cardnumber" i]',
|
|
233
|
+
'input[name*="cc-number" i]',
|
|
234
|
+
];
|
|
235
|
+
/** First selector that resolves to a visible input, or null if none do. */
|
|
236
|
+
async function firstVisibleCardNumberLocator(page, detectedLocator, timeoutMs) {
|
|
237
|
+
for (const selector of [detectedLocator, ...CARD_NUMBER_FALLBACK_SELECTORS]) {
|
|
238
|
+
try {
|
|
239
|
+
await page
|
|
240
|
+
.locator(selector)
|
|
241
|
+
.first()
|
|
242
|
+
.waitFor({ state: 'visible', timeout: Math.max(500, Math.floor(timeoutMs / 3)) });
|
|
243
|
+
return selector;
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
/** Card-credential roles that share the panel a payment select unfolds. */
|
|
252
|
+
const CARD_GROUP_ROLES = ['number', 'cvc', 'expCombined', 'expMonth', 'expYear'];
|
|
253
|
+
/**
|
|
254
|
+
* Re-detect and adopt fresh entries for every card field after the panel is
|
|
255
|
+
* unfolded. Injected for tests; the executor's own detector is used in
|
|
256
|
+
* production.
|
|
257
|
+
*/
|
|
258
|
+
export async function refreshCardGroupFromPage(page, fields, detect = detectFields) {
|
|
259
|
+
let fresh;
|
|
260
|
+
try {
|
|
261
|
+
fresh = (await detect(page)).fields;
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
return [];
|
|
265
|
+
}
|
|
266
|
+
const adopted = [];
|
|
267
|
+
for (const role of CARD_GROUP_ROLES) {
|
|
268
|
+
const next = fresh[role];
|
|
269
|
+
if (!next || next.visible === false)
|
|
270
|
+
continue;
|
|
271
|
+
const current = fields[role];
|
|
272
|
+
// Only ever replace an entry we could not have filled anyway. A field that
|
|
273
|
+
// is already visible was detected against the live DOM and keeps its
|
|
274
|
+
// higher-confidence match.
|
|
275
|
+
if (current && current.visible !== false)
|
|
276
|
+
continue;
|
|
277
|
+
fields[role] = next;
|
|
278
|
+
adopted.push(role);
|
|
279
|
+
}
|
|
280
|
+
return adopted;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Reveal card fields that a checkout keeps collapsed until a payment method is
|
|
284
|
+
* chosen.
|
|
285
|
+
*
|
|
286
|
+
* `fillFields` skips any entry with `visible === false`, so a card-number input
|
|
287
|
+
* sitting inside a folded panel is never even attempted — the generic adapter
|
|
288
|
+
* then reports `ok: false` ("fill incomplete") without having typed anything.
|
|
289
|
+
* That is the correct default: filling an invisible input is how a credential
|
|
290
|
+
* gets typed into the wrong place. But a payment-method `<select>` guarding the
|
|
291
|
+
* card panel is common enough to be worth handling, and the recovery is a
|
|
292
|
+
* single deterministic interaction rather than a guess.
|
|
293
|
+
*
|
|
294
|
+
* We only ever SELECT a card option — never a wallet, bank transfer, or
|
|
295
|
+
* anything else — and we only act when the card field is already detected but
|
|
296
|
+
* hidden. If nothing changes, the caller proceeds exactly as before and still
|
|
297
|
+
* fails closed.
|
|
298
|
+
*
|
|
299
|
+
* Mutates `fields.number.visible` on success so the subsequent fill attempts
|
|
300
|
+
* the field it just revealed.
|
|
301
|
+
*/
|
|
302
|
+
export async function revealCollapsedCardSection(page, fields, opts = {}) {
|
|
303
|
+
const number = fields.number;
|
|
304
|
+
if (!number || number.visible !== false)
|
|
305
|
+
return { revealed: false, via: null };
|
|
306
|
+
const timeoutMs = opts.timeoutMs ?? 5_000;
|
|
307
|
+
const selects = page.locator('select');
|
|
308
|
+
const count = await selects.count().catch(() => 0);
|
|
309
|
+
for (let i = 0; i < Math.min(count, 12); i++) {
|
|
310
|
+
const select = selects.nth(i);
|
|
311
|
+
// Read option labels through the locator API rather than page.evaluate.
|
|
312
|
+
// A bundled build rewrites the function passed to evaluate() and the
|
|
313
|
+
// injected helper is not defined in page scope, so it throws at runtime —
|
|
314
|
+
// silently, once a catch treats it as "this select didn't match". Staying
|
|
315
|
+
// on the locator API keeps this working in source and bundled alike.
|
|
316
|
+
let labels;
|
|
317
|
+
try {
|
|
318
|
+
labels = await select.locator('option').allTextContents();
|
|
319
|
+
}
|
|
320
|
+
catch {
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
for (const pattern of CARD_OPTION_PATTERNS) {
|
|
324
|
+
const label = labels.map((l) => l.trim()).find((l) => l && pattern.test(l));
|
|
325
|
+
if (!label)
|
|
326
|
+
continue;
|
|
327
|
+
try {
|
|
328
|
+
await select.selectOption({ label }, { timeout: timeoutMs });
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
// Re-acquire the field instead of waiting on the detected locator.
|
|
334
|
+
// Unfolding the panel typically re-renders it, and the detector's
|
|
335
|
+
// synthetic `data-ca-id` attribute does not survive that — waiting on the
|
|
336
|
+
// old locator times out even though the field is now on screen and
|
|
337
|
+
// fillable. Stable attribute selectors survive the re-render.
|
|
338
|
+
const revealedLocator = await firstVisibleCardNumberLocator(page, number.locator, timeoutMs);
|
|
339
|
+
if (!revealedLocator)
|
|
340
|
+
continue;
|
|
341
|
+
number.locator = revealedLocator;
|
|
342
|
+
number.visible = true;
|
|
343
|
+
// The number is not alone in that panel: cvc and expiry were re-rendered
|
|
344
|
+
// with it and still carry stale, invisible entries. Filling only the
|
|
345
|
+
// number would trade "adapter fill incomplete" for "credential fill
|
|
346
|
+
// incomplete: missing cvc, expiry" — still a failed purchase, still after
|
|
347
|
+
// a credential was minted. Re-detect and adopt fresh entries for the
|
|
348
|
+
// whole card group.
|
|
349
|
+
await refreshCardGroupFromPage(page, fields);
|
|
350
|
+
return { revealed: true, via: label };
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
return { revealed: false, via: null };
|
|
354
|
+
}
|
|
215
355
|
export class GenericAdapter {
|
|
216
356
|
name = 'generic';
|
|
217
357
|
matches(_detected) {
|
|
@@ -219,10 +359,17 @@ export class GenericAdapter {
|
|
|
219
359
|
return true;
|
|
220
360
|
}
|
|
221
361
|
async fill(page, fields, credential, contact) {
|
|
362
|
+
const reveal = await revealCollapsedCardSection(page, fields);
|
|
222
363
|
const filled = await fillFieldMap(page, fields, credential, contact);
|
|
364
|
+
const ok = filled.some((f) => f.role === 'number' && f.ok);
|
|
223
365
|
return {
|
|
224
|
-
ok
|
|
366
|
+
ok,
|
|
225
367
|
filled,
|
|
368
|
+
...(ok || !reveal.revealed
|
|
369
|
+
? {}
|
|
370
|
+
: {
|
|
371
|
+
detail: `revealed the card section via "${reveal.via}" but the number field still did not fill`,
|
|
372
|
+
}),
|
|
226
373
|
};
|
|
227
374
|
}
|
|
228
375
|
}
|
|
@@ -5,6 +5,7 @@ import type { Instrument } from './instrument.js';
|
|
|
5
5
|
import type { Contact, OtpResolver } from './types.js';
|
|
6
6
|
import { EvidenceLog } from './evidence.js';
|
|
7
7
|
import { type ObservedOutcome } from './outcome.js';
|
|
8
|
+
import { type WebBotAuthConfig } from './web-bot-auth.js';
|
|
8
9
|
export { minorFromDecimal, pageCurrency } from './amount.js';
|
|
9
10
|
export type CheckoutMode = 'dry-run' | 'submit';
|
|
10
11
|
export type CheckoutOutcome = 'reviewed-dry-run'
|
|
@@ -35,6 +36,7 @@ export type PrepareCheckoutOptions = {
|
|
|
35
36
|
amountMinor?: number;
|
|
36
37
|
currency?: string;
|
|
37
38
|
debugShotsDir?: string;
|
|
39
|
+
webBotAuth?: WebBotAuthConfig | null;
|
|
38
40
|
};
|
|
39
41
|
export type RunCheckoutOptions = PrepareCheckoutOptions & {
|
|
40
42
|
instrument: Instrument;
|
|
@@ -24,6 +24,7 @@ import { observeOutcome } from './outcome.js';
|
|
|
24
24
|
import { selectAdapter } from './adapters/index.js';
|
|
25
25
|
import { traceHandleFields } from './trace-handles.js';
|
|
26
26
|
import { readGenericPageAmount } from './amount.js';
|
|
27
|
+
import { webBotAuthHeadersOrNone } from './web-bot-auth.js';
|
|
27
28
|
import { detectShopifyChallenge, isShopifyCheckoutPage, readShopifyAmount, readStableShopifyAmount, shopifyEnglishCheckoutUrl, } from './adapters/shopify.js';
|
|
28
29
|
export { minorFromDecimal, pageCurrency } from './amount.js';
|
|
29
30
|
const SUBMIT_TEXT = /pay|place order|complete|buy|submit|checkout/i;
|
|
@@ -679,7 +680,16 @@ export async function prepareCheckout(opts, store = defaultPreparedCheckoutStore
|
|
|
679
680
|
// Accept-Language (observed live 2026-08-16: a Shopify checkout redirected
|
|
680
681
|
// to /es-us and rendered "Impuestos estimados", so the total never parsed
|
|
681
682
|
// and the review refused fail-closed on a perfectly good checkout).
|
|
682
|
-
|
|
683
|
+
// Present Web Bot Auth (RFC 9421) credentials when, and only when, an
|
|
684
|
+
// operator directory is configured to resolve them. Off by default: an
|
|
685
|
+
// unresolvable signature fails verification and is worse than none. The
|
|
686
|
+
// signature covers @authority, so it is bound to the checkout host — a
|
|
687
|
+
// cross-origin redirect simply arrives unverified, never wrongly verified.
|
|
688
|
+
const webBotAuthHeaders = webBotAuthHeadersOrNone(options.webBotAuth ?? null, options.url, Date.now() / 1000);
|
|
689
|
+
const context = await options.browser.newContext({
|
|
690
|
+
locale: 'en-US',
|
|
691
|
+
...(webBotAuthHeaders ? { extraHTTPHeaders: webBotAuthHeaders } : {}),
|
|
692
|
+
});
|
|
683
693
|
// Bound every action so a mis-detected or hidden element fails fast instead
|
|
684
694
|
// of stalling on Playwright's long default timeout.
|
|
685
695
|
context.setDefaultTimeout(6000);
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/** Signature validity ceiling. A signature is a bearer-ish artifact for as long
|
|
2
|
+
* as it is valid, so the window stays short even if a caller asks for more. */
|
|
3
|
+
export declare const WEB_BOT_AUTH_MAX_TTL_SECONDS = 300;
|
|
4
|
+
/** Default validity. Long enough to survive a redirect chain and a slow TLS
|
|
5
|
+
* handshake, short enough that a captured signature is near-useless. */
|
|
6
|
+
export declare const WEB_BOT_AUTH_DEFAULT_TTL_SECONDS = 60;
|
|
7
|
+
/** Label for the single signature we emit. RFC 9421 allows several per request. */
|
|
8
|
+
export declare const WEB_BOT_AUTH_SIGNATURE_LABEL = "sig1";
|
|
9
|
+
/** Tag fixed by the Web Bot Auth draft; verifiers select on it. */
|
|
10
|
+
export declare const WEB_BOT_AUTH_TAG = "web-bot-auth";
|
|
11
|
+
/** Components covered by the signature, in the order they appear in the base. */
|
|
12
|
+
export declare const WEB_BOT_AUTH_COVERED_COMPONENTS: readonly ["@authority", "signature-agent"];
|
|
13
|
+
/** Ed25519 private key in JWK form, as stored in the agent's runtime key file. */
|
|
14
|
+
export interface WebBotAuthPrivateJwk {
|
|
15
|
+
kty: 'OKP';
|
|
16
|
+
crv: 'Ed25519';
|
|
17
|
+
x: string;
|
|
18
|
+
d: string;
|
|
19
|
+
}
|
|
20
|
+
export interface WebBotAuthSigningKey {
|
|
21
|
+
/** RFC 7638 thumbprint. Must match a `kid` published in the directory. */
|
|
22
|
+
keyId: string;
|
|
23
|
+
privateJwk: WebBotAuthPrivateJwk;
|
|
24
|
+
}
|
|
25
|
+
export interface WebBotAuthConfig {
|
|
26
|
+
/** Absolute https URL of the operator-hosted signature directory. */
|
|
27
|
+
directoryUrl: string;
|
|
28
|
+
key: WebBotAuthSigningKey;
|
|
29
|
+
ttlSeconds?: number;
|
|
30
|
+
}
|
|
31
|
+
export interface WebBotAuthHeaders {
|
|
32
|
+
'Signature-Input': string;
|
|
33
|
+
Signature: string;
|
|
34
|
+
'Signature-Agent': string;
|
|
35
|
+
[header: string]: string;
|
|
36
|
+
}
|
|
37
|
+
export interface SignatureBaseParams {
|
|
38
|
+
authority: string;
|
|
39
|
+
directoryUrl: string;
|
|
40
|
+
keyId: string;
|
|
41
|
+
created: number;
|
|
42
|
+
expires: number;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Build the RFC 9421 signature base.
|
|
46
|
+
*
|
|
47
|
+
* The base is what actually gets signed, so its exact bytes are the contract
|
|
48
|
+
* with every verifier — one wrong space or a reordered parameter and the
|
|
49
|
+
* signature fails against a correct key. It is exported and pinned by a
|
|
50
|
+
* deterministic test vector for that reason.
|
|
51
|
+
*/
|
|
52
|
+
export declare function buildSignatureBase(params: SignatureBaseParams): string;
|
|
53
|
+
/**
|
|
54
|
+
* The `@signature-params` value, which appears twice: as the final line of the
|
|
55
|
+
* signature base, and verbatim as the `Signature-Input` header value. Building
|
|
56
|
+
* it once is what keeps those two identical — a verifier rederives the base
|
|
57
|
+
* from the header it received, so any divergence fails every signature.
|
|
58
|
+
*/
|
|
59
|
+
export declare function buildSignatureParams(params: SignatureBaseParams): string;
|
|
60
|
+
export interface BuildHeadersParams {
|
|
61
|
+
/** Host (and port, if non-default) of the request being signed. */
|
|
62
|
+
authority: string;
|
|
63
|
+
config: WebBotAuthConfig;
|
|
64
|
+
/** Unix seconds. Injected so tests are deterministic and never wall-clock. */
|
|
65
|
+
nowSeconds: number;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Produce the three Web Bot Auth headers for one request authority.
|
|
69
|
+
*
|
|
70
|
+
* Throws on unusable key material rather than emitting an unverifiable
|
|
71
|
+
* signature. Callers on the checkout path must treat a throw as "proceed
|
|
72
|
+
* unsigned" — see `webBotAuthHeadersOrNone`.
|
|
73
|
+
*/
|
|
74
|
+
export declare function buildWebBotAuthHeaders(params: BuildHeadersParams): WebBotAuthHeaders;
|
|
75
|
+
/**
|
|
76
|
+
* Header-or-nothing wrapper for the checkout path.
|
|
77
|
+
*
|
|
78
|
+
* Signing is an optional trust upgrade, never a precondition for buying
|
|
79
|
+
* something. Unusable key material, a malformed URL, or any crypto failure
|
|
80
|
+
* degrades to an unsigned request — which is exactly what we sent before this
|
|
81
|
+
* module existed — rather than throwing into a live checkout.
|
|
82
|
+
*/
|
|
83
|
+
export declare function webBotAuthHeadersOrNone(config: WebBotAuthConfig | null, targetUrl: string, nowSeconds: number): WebBotAuthHeaders | null;
|
|
84
|
+
/**
|
|
85
|
+
* Resolve signing config from the environment. Returns `null` — meaning "send
|
|
86
|
+
* unsigned" — unless a directory URL and a usable key are BOTH present.
|
|
87
|
+
*
|
|
88
|
+
* Default-off is deliberate. Until the operator directory is live and serving
|
|
89
|
+
* this key, a signature resolves to nothing and fails verification, which is
|
|
90
|
+
* worse than the honest unsigned request we sent before.
|
|
91
|
+
*/
|
|
92
|
+
export declare function resolveWebBotAuthConfig(env: NodeJS.ProcessEnv, loadKey: () => WebBotAuthSigningKey | null): WebBotAuthConfig | null;
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @purpose Web Bot Auth (RFC 9421) request signing for checkout navigations —
|
|
3
|
+
* the client half of Trusted Agent Protocol verification.
|
|
4
|
+
*
|
|
5
|
+
* Cloudflare's TAP verifies an agent by checking an RFC 9421 HTTP message
|
|
6
|
+
* signature on the request. Three headers carry it: `Signature-Input` names the
|
|
7
|
+
* covered components and parameters, `Signature` carries the Ed25519 signature
|
|
8
|
+
* over the derived base, and `Signature-Agent` gives the URL of the directory
|
|
9
|
+
* that resolves `keyid` to a public key. The checkout browser previously sent
|
|
10
|
+
* none of them, so a TAP-aware edge had nothing to verify and fell through to
|
|
11
|
+
* ordinary bot management.
|
|
12
|
+
*
|
|
13
|
+
* TWO HALVES, BOTH REQUIRED. This module presents a `keyid`; the auth server
|
|
14
|
+
* must publish that key at the `Signature-Agent` URL for anything to resolve.
|
|
15
|
+
* Signing while the directory is absent is strictly worse than not signing,
|
|
16
|
+
* because it advertises intent and then fails verification — which is why
|
|
17
|
+
* signing stays OFF unless explicitly configured with a directory URL.
|
|
18
|
+
*
|
|
19
|
+
* KEY MATERIAL NEVER LEAVES THIS MODULE. The signing key is accepted as a
|
|
20
|
+
* value, used once per request, and never logged, serialized, returned, or
|
|
21
|
+
* attached to evidence. Callers get headers, never the key. This module takes
|
|
22
|
+
* no logger for exactly that reason.
|
|
23
|
+
*/
|
|
24
|
+
import { createPrivateKey, sign as cryptoSign } from 'node:crypto';
|
|
25
|
+
/** Signature validity ceiling. A signature is a bearer-ish artifact for as long
|
|
26
|
+
* as it is valid, so the window stays short even if a caller asks for more. */
|
|
27
|
+
export const WEB_BOT_AUTH_MAX_TTL_SECONDS = 300;
|
|
28
|
+
/** Default validity. Long enough to survive a redirect chain and a slow TLS
|
|
29
|
+
* handshake, short enough that a captured signature is near-useless. */
|
|
30
|
+
export const WEB_BOT_AUTH_DEFAULT_TTL_SECONDS = 60;
|
|
31
|
+
/** Label for the single signature we emit. RFC 9421 allows several per request. */
|
|
32
|
+
export const WEB_BOT_AUTH_SIGNATURE_LABEL = 'sig1';
|
|
33
|
+
/** Tag fixed by the Web Bot Auth draft; verifiers select on it. */
|
|
34
|
+
export const WEB_BOT_AUTH_TAG = 'web-bot-auth';
|
|
35
|
+
/** Components covered by the signature, in the order they appear in the base. */
|
|
36
|
+
export const WEB_BOT_AUTH_COVERED_COMPONENTS = ['@authority', 'signature-agent'];
|
|
37
|
+
/** Serialize an RFC 8941 structured-field string (always double-quoted). */
|
|
38
|
+
function sfString(value) {
|
|
39
|
+
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Build the RFC 9421 signature base.
|
|
43
|
+
*
|
|
44
|
+
* The base is what actually gets signed, so its exact bytes are the contract
|
|
45
|
+
* with every verifier — one wrong space or a reordered parameter and the
|
|
46
|
+
* signature fails against a correct key. It is exported and pinned by a
|
|
47
|
+
* deterministic test vector for that reason.
|
|
48
|
+
*/
|
|
49
|
+
export function buildSignatureBase(params) {
|
|
50
|
+
return [
|
|
51
|
+
`"@authority": ${params.authority}`,
|
|
52
|
+
`"signature-agent": ${sfString(params.directoryUrl)}`,
|
|
53
|
+
`"@signature-params": ${buildSignatureParams(params)}`,
|
|
54
|
+
].join('\n');
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The `@signature-params` value, which appears twice: as the final line of the
|
|
58
|
+
* signature base, and verbatim as the `Signature-Input` header value. Building
|
|
59
|
+
* it once is what keeps those two identical — a verifier rederives the base
|
|
60
|
+
* from the header it received, so any divergence fails every signature.
|
|
61
|
+
*/
|
|
62
|
+
export function buildSignatureParams(params) {
|
|
63
|
+
return (`(${WEB_BOT_AUTH_COVERED_COMPONENTS.map(sfString).join(' ')})` +
|
|
64
|
+
`;created=${params.created}` +
|
|
65
|
+
`;expires=${params.expires}` +
|
|
66
|
+
`;keyid=${sfString(params.keyId)}` +
|
|
67
|
+
`;alg="ed25519"` +
|
|
68
|
+
`;tag=${sfString(WEB_BOT_AUTH_TAG)}`);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Produce the three Web Bot Auth headers for one request authority.
|
|
72
|
+
*
|
|
73
|
+
* Throws on unusable key material rather than emitting an unverifiable
|
|
74
|
+
* signature. Callers on the checkout path must treat a throw as "proceed
|
|
75
|
+
* unsigned" — see `webBotAuthHeadersOrNone`.
|
|
76
|
+
*/
|
|
77
|
+
export function buildWebBotAuthHeaders(params) {
|
|
78
|
+
const { authority, config, nowSeconds } = params;
|
|
79
|
+
const ttl = Math.min(Math.max(1, Math.floor(config.ttlSeconds ?? WEB_BOT_AUTH_DEFAULT_TTL_SECONDS)), WEB_BOT_AUTH_MAX_TTL_SECONDS);
|
|
80
|
+
const created = Math.floor(nowSeconds);
|
|
81
|
+
const expires = created + ttl;
|
|
82
|
+
const baseParams = {
|
|
83
|
+
authority,
|
|
84
|
+
directoryUrl: config.directoryUrl,
|
|
85
|
+
keyId: config.key.keyId,
|
|
86
|
+
created,
|
|
87
|
+
expires,
|
|
88
|
+
};
|
|
89
|
+
const base = buildSignatureBase(baseParams);
|
|
90
|
+
const signatureParams = buildSignatureParams(baseParams);
|
|
91
|
+
const privateKey = createPrivateKey({
|
|
92
|
+
key: config.key.privateJwk,
|
|
93
|
+
format: 'jwk',
|
|
94
|
+
});
|
|
95
|
+
// Ed25519 takes no separate digest algorithm; null is the required argument.
|
|
96
|
+
const signature = cryptoSign(null, Buffer.from(base, 'utf8'), privateKey);
|
|
97
|
+
return {
|
|
98
|
+
'Signature-Input': `${WEB_BOT_AUTH_SIGNATURE_LABEL}=${signatureParams}`,
|
|
99
|
+
Signature: `${WEB_BOT_AUTH_SIGNATURE_LABEL}=:${signature.toString('base64')}:`,
|
|
100
|
+
'Signature-Agent': sfString(config.directoryUrl),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Header-or-nothing wrapper for the checkout path.
|
|
105
|
+
*
|
|
106
|
+
* Signing is an optional trust upgrade, never a precondition for buying
|
|
107
|
+
* something. Unusable key material, a malformed URL, or any crypto failure
|
|
108
|
+
* degrades to an unsigned request — which is exactly what we sent before this
|
|
109
|
+
* module existed — rather than throwing into a live checkout.
|
|
110
|
+
*/
|
|
111
|
+
export function webBotAuthHeadersOrNone(config, targetUrl, nowSeconds) {
|
|
112
|
+
if (!config)
|
|
113
|
+
return null;
|
|
114
|
+
try {
|
|
115
|
+
const authority = new URL(targetUrl).host;
|
|
116
|
+
if (!authority)
|
|
117
|
+
return null;
|
|
118
|
+
return buildWebBotAuthHeaders({ authority, config, nowSeconds });
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Resolve signing config from the environment. Returns `null` — meaning "send
|
|
126
|
+
* unsigned" — unless a directory URL and a usable key are BOTH present.
|
|
127
|
+
*
|
|
128
|
+
* Default-off is deliberate. Until the operator directory is live and serving
|
|
129
|
+
* this key, a signature resolves to nothing and fails verification, which is
|
|
130
|
+
* worse than the honest unsigned request we sent before.
|
|
131
|
+
*/
|
|
132
|
+
export function resolveWebBotAuthConfig(env, loadKey) {
|
|
133
|
+
const directoryUrl = env.VISA_WEB_BOT_AUTH_DIRECTORY_URL?.trim();
|
|
134
|
+
if (!directoryUrl)
|
|
135
|
+
return null;
|
|
136
|
+
let parsed;
|
|
137
|
+
try {
|
|
138
|
+
parsed = new URL(directoryUrl);
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
// A directory fetched over plain http could be swapped in flight, which would
|
|
144
|
+
// let an observer substitute the key set our identity is judged against.
|
|
145
|
+
if (parsed.protocol !== 'https:')
|
|
146
|
+
return null;
|
|
147
|
+
let key = null;
|
|
148
|
+
try {
|
|
149
|
+
key = loadKey();
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
if (!key?.keyId || key.privateJwk?.crv !== 'Ed25519' || !key.privateJwk.d)
|
|
155
|
+
return null;
|
|
156
|
+
const rawTtl = Number(env.VISA_WEB_BOT_AUTH_TTL_SECONDS);
|
|
157
|
+
const ttlSeconds = Number.isFinite(rawTtl) && rawTtl > 0 ? rawTtl : undefined;
|
|
158
|
+
return { directoryUrl: parsed.toString(), key, ttlSeconds };
|
|
159
|
+
}
|