@visa/cli 4.1.0-rc.24 → 4.1.0-rc.240

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.
Files changed (86) hide show
  1. package/README.md +262 -227
  2. package/dist/checkout-engine/adapters/generic.d.ts +69 -0
  3. package/dist/checkout-engine/adapters/generic.js +383 -58
  4. package/dist/checkout-engine/adapters/index.d.ts +4 -1
  5. package/dist/checkout-engine/adapters/index.js +10 -3
  6. package/dist/checkout-engine/adapters/shopify.d.ts +80 -0
  7. package/dist/checkout-engine/adapters/shopify.js +688 -0
  8. package/dist/checkout-engine/amount.d.ts +15 -0
  9. package/dist/checkout-engine/amount.js +72 -0
  10. package/dist/checkout-engine/browser-launch.d.ts +9 -4
  11. package/dist/checkout-engine/browser-launch.js +19 -4
  12. package/dist/checkout-engine/browserbase-browser.d.ts +24 -0
  13. package/dist/checkout-engine/browserbase-browser.js +186 -0
  14. package/dist/checkout-engine/cli-engine.d.ts +297 -4
  15. package/dist/checkout-engine/cli-engine.js +942 -48
  16. package/dist/checkout-engine/confirmed-merchants.d.ts +31 -0
  17. package/dist/checkout-engine/confirmed-merchants.js +165 -0
  18. package/dist/checkout-engine/detect.d.ts +1 -1
  19. package/dist/checkout-engine/detect.js +26 -0
  20. package/dist/checkout-engine/evidence.d.ts +4 -1
  21. package/dist/checkout-engine/evidence.js +51 -6
  22. package/dist/checkout-engine/executor.d.ts +64 -4
  23. package/dist/checkout-engine/executor.js +604 -145
  24. package/dist/checkout-engine/hosted-approval.d.ts +124 -7
  25. package/dist/checkout-engine/hosted-approval.js +384 -54
  26. package/dist/checkout-engine/index.d.ts +9 -2
  27. package/dist/checkout-engine/index.js +8 -1
  28. package/dist/checkout-engine/instrument.d.ts +7 -0
  29. package/dist/checkout-engine/instrument.js +4 -0
  30. package/dist/checkout-engine/known-merchants.d.ts +10 -0
  31. package/dist/checkout-engine/known-merchants.js +38 -0
  32. package/dist/checkout-engine/live-fill-approval.d.ts +5 -20
  33. package/dist/checkout-engine/live-fill-approval.js +20 -51
  34. package/dist/checkout-engine/mandate/card-mandate.d.ts +121 -0
  35. package/dist/checkout-engine/mandate/card-mandate.js +226 -0
  36. package/dist/checkout-engine/mandate/mandate-ledger.d.ts +174 -0
  37. package/dist/checkout-engine/mandate/mandate-ledger.js +410 -0
  38. package/dist/checkout-engine/outcome.d.ts +2 -2
  39. package/dist/checkout-engine/outcome.js +36 -1
  40. package/dist/checkout-engine/owner-only-file.d.ts +9 -0
  41. package/dist/checkout-engine/owner-only-file.js +20 -1
  42. package/dist/checkout-engine/receipt-dir.d.ts +6 -0
  43. package/dist/checkout-engine/receipt-dir.js +8 -0
  44. package/dist/checkout-engine/receipt.d.ts +56 -2
  45. package/dist/checkout-engine/receipt.js +55 -16
  46. package/dist/checkout-engine/trace-handles.d.ts +8 -0
  47. package/dist/checkout-engine/trace-handles.js +12 -0
  48. package/dist/checkout-engine/types.d.ts +28 -2
  49. package/dist/checkout-engine/unresolved-charges.d.ts +34 -0
  50. package/dist/checkout-engine/unresolved-charges.js +134 -0
  51. package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +53 -1
  52. package/dist/checkout-engine/vgs-gateway/server-mint-client.js +78 -10
  53. package/dist/checkout-engine/vgs-live-instrument.d.ts +38 -35
  54. package/dist/checkout-engine/vgs-live-instrument.js +51 -74
  55. package/dist/checkout-engine/vic-confirmation.d.ts +18 -0
  56. package/dist/checkout-engine/vic-confirmation.js +9 -3
  57. package/dist/checkout-engine/web-bot-auth.d.ts +98 -0
  58. package/dist/checkout-engine/web-bot-auth.js +218 -0
  59. package/dist/cli.js +968 -505
  60. package/dist/mcp-apps/ucp-checkout.html +280 -0
  61. package/dist/mcp-server/index.js +807 -175
  62. package/dist/skills/pair-visa-agent/RUNTIMES.md +122 -79
  63. package/dist/skills/pair-visa-agent/SKILL.md +436 -248
  64. package/dist/skills/pair-visa-agent/scripts/__tests__/setup.test.mjs +407 -0
  65. package/dist/skills/pair-visa-agent/scripts/setup.mjs +310 -30
  66. package/dist/skills/visa-shopify-checkout/SKILL.md +122 -0
  67. package/dist/skills/visa-shopify-checkout/references/evidence-and-states.md +37 -0
  68. package/dist/skills/visa-ucp-shopping/SKILL.md +84 -0
  69. package/dist/subway-direct.mjs +1 -0
  70. package/install.ps1 +9 -46
  71. package/install.sh +5 -37
  72. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  73. package/package.json +32 -28
  74. package/server.json +4 -4
  75. package/dist/checkout-engine/inline-target.d.ts +0 -13
  76. package/dist/checkout-engine/inline-target.js +0 -37
  77. package/dist/checkout-engine/pay-args.d.ts +0 -14
  78. package/dist/checkout-engine/pay-args.js +0 -44
  79. package/dist/checkout-engine/pay.d.ts +0 -1
  80. package/dist/checkout-engine/pay.js +0 -13
  81. package/dist/checkout-engine/repo-env.d.ts +0 -11
  82. package/dist/checkout-engine/repo-env.js +0 -23
  83. package/dist/checkout-engine/run-live-fill.d.ts +0 -1
  84. package/dist/checkout-engine/run-live-fill.js +0 -443
  85. package/dist/checkout-engine/vgs-gateway/fetch-credential.d.mts +0 -74
  86. package/dist/checkout-engine/vgs-gateway/fetch-credential.mjs +0 -248
@@ -1,3 +1,4 @@
1
+ import { traceHandleFields } from './trace-handles.js';
1
2
  /**
2
3
  * Our fail-closed freshness bound, matching the runner's 15-minute checkout
3
4
  * review window — NOT a claim about VGS's actual assurance TTL (unpublished).
@@ -19,6 +20,43 @@ export function decimalToMinor(value) {
19
20
  const minor = Number(whole) * 100 + Number(fraction.padEnd(2, '0'));
20
21
  return Number.isSafeInteger(minor) ? minor : null;
21
22
  }
23
+ /**
24
+ * Currencies whose minor unit is 1/100 of the major unit (2 decimal places).
25
+ * minorToDecimal's /100 + pad-to-2 rendering is ONLY correct for these. The
26
+ * card mandate path accepts any 3-letter ISO code, so a 0- or 3-decimal
27
+ * currency (JPY, BHD, …) would otherwise be emitted with a wrong wire amount.
28
+ * We only support USD/USDC today; extend deliberately (and fix the exponent)
29
+ * before adding any non-2-decimal currency.
30
+ *
31
+ * NOTE (scanner FP pre-empt): this is a CLIENT-SIDE currency-exponent lookup for
32
+ * rendering a wire amount in @visa/checkout-engine — it is NOT the cross-store
33
+ * `PAYMENT_CURRENCIES` enum governed by apps/auth/src/shared-validators.ts, and
34
+ * this package cannot import from apps/auth (no dependency edge). It intentionally
35
+ * does not mirror that enum's membership; do not "reconcile" the two.
36
+ */
37
+ export const TWO_DECIMAL_CURRENCIES = new Set(['USD', 'USDC']);
38
+ /**
39
+ * Inverse of decimalToMinor: render integer minor units as a major-unit decimal
40
+ * string ("D.DD") for the VGS wire (e.g. a ceiling of 50000 minor → "500.00").
41
+ * Integer-only; never floating-point money. Throws on a non-integer/negative so
42
+ * a bad accounting value cannot silently reach the network.
43
+ *
44
+ * The /100 + pad-to-2 rendering assumes a 2-decimal (exponent-2) currency. Pass
45
+ * `currencyCode` on any path that accepts arbitrary currencies (the mandate
46
+ * path) and it REFUSES a non-2-decimal currency rather than emit a wrong wire
47
+ * amount. Omit it only where the currency is already known to be USD/USDC.
48
+ */
49
+ export function minorToDecimal(minor, currencyCode) {
50
+ if (!Number.isSafeInteger(minor) || minor < 0) {
51
+ throw new Error('minor units must be a non-negative safe integer');
52
+ }
53
+ if (currencyCode !== undefined && !TWO_DECIMAL_CURRENCIES.has(currencyCode.toUpperCase())) {
54
+ throw new Error(`minorToDecimal only supports 2-decimal currencies (${[...TWO_DECIMAL_CURRENCIES].join('/')}); refusing to emit a wire amount for ${currencyCode}`);
55
+ }
56
+ const whole = Math.floor(minor / 100);
57
+ const fraction = minor % 100;
58
+ return `${whole}.${String(fraction).padStart(2, '0')}`;
59
+ }
22
60
  function validateTarget(reference, ctx) {
23
61
  if (typeof reference.merchantName !== 'string' ||
24
62
  typeof reference.merchantCountryCode !== 'string' ||
@@ -49,13 +87,6 @@ function validateTarget(reference, ctx) {
49
87
  throw new Error(`VGS credential currency mismatch: ${currency} vs ${ctx.currency}`);
50
88
  }
51
89
  }
52
- function validateCliCredential(value) {
53
- if (typeof value.tokenId !== 'string' || !value.tokenId.trim()) {
54
- throw new Error('CLI agent credential requires tokenId');
55
- }
56
- // Deliberately no assuranceData requirement: the artifact's enrollment-time
57
- // assurance is identity/enrollment material and is never read here (#5709).
58
- }
59
90
  /**
60
91
  * Refuse to mint an intent unless the assurance is fresh and its declared
61
92
  * scope matches the checkout target exactly. `now` is injectable so the
@@ -68,7 +99,10 @@ export function validatePurchaseAssurance(value, target, now = new Date()) {
68
99
  if (value == null || typeof value !== 'object') {
69
100
  throw new Error(`purchase assurance is missing — ${remedy}`);
70
101
  }
71
- if (value.assuranceData == null) {
102
+ // A passkey-exempt approval (marked by the approval SERVER, never assumed
103
+ // locally) carries no assurance by design — every scope/freshness check
104
+ // below still applies to it unchanged.
105
+ if (value.assuranceData == null && value.assuranceExempt !== true) {
72
106
  throw new Error(`purchase assurance requires assuranceData — ${remedy}`);
73
107
  }
74
108
  const mintedAtMs = typeof value.mintedAt === 'string' ? Date.parse(value.mintedAt) : NaN;
@@ -125,13 +159,14 @@ export function validateCredential(value, now = new Date()) {
125
159
  (value.expYear === now.getFullYear() && value.expMonth < now.getMonth() + 1)) {
126
160
  throw new Error('VGS credential is expired');
127
161
  }
128
- if (value.cryptogramExpiresAt !== undefined) {
129
- const expiresAtMs = Date.parse(value.cryptogramExpiresAt);
130
- if (!Number.isFinite(expiresAtMs))
131
- throw new Error('VGS credential expiry is invalid');
132
- if (expiresAtMs - now.getTime() < 60_000) {
133
- throw new Error('VGS credential has less than 60 seconds of validity remaining');
134
- }
162
+ if (value.cryptogramExpiresAt === undefined) {
163
+ throw new Error('VGS credential expiry is missing');
164
+ }
165
+ const expiresAtMs = Date.parse(value.cryptogramExpiresAt);
166
+ if (!Number.isFinite(expiresAtMs))
167
+ throw new Error('VGS credential expiry is invalid');
168
+ if (expiresAtMs - now.getTime() < 60_000) {
169
+ throw new Error('VGS credential has less than 60 seconds of validity remaining');
135
170
  }
136
171
  }
137
172
  /**
@@ -188,65 +223,7 @@ export class VgsLiveInstrument {
188
223
  cvc: value.cryptogramValue,
189
224
  cardholderName: this.cardholderName.trim(),
190
225
  ...(value.cryptogramExpiresAt ? { credentialExpiresAt: value.cryptogramExpiresAt } : {}),
191
- };
192
- }
193
- }
194
- /**
195
- * Consumes #5614's claimed CLI enrollment artifact (for the tokenId) plus a
196
- * FRESH purchase-scoped assurance, and creates a fresh, transaction-scoped VIC
197
- * intent + credential after checkout approval. This is the production-shaped
198
- * bridge; unlike VgsLiveInstrument it never needs a pre-created intent ID.
199
- *
200
- * The enrollment artifact's stored assuranceData is deliberately never sent:
201
- * replaying it makes intent creation succeed (HTTP 201) while the cryptogram
202
- * deterministically never completes — the #5709 dead end. Purchase
203
- * authorization is the fresh, merchant+amount+currency-scoped assurance,
204
- * validated against the checkout target BEFORE any intent is minted so a
205
- * doomed intent is never created.
206
- */
207
- export class VgsAssuranceInstrument {
208
- enrollment;
209
- purchase;
210
- target;
211
- cardholderName;
212
- mintCredential;
213
- kind = 'agentic-token';
214
- used = false;
215
- minted = null;
216
- constructor(enrollment, purchase, target, cardholderName, mintCredential) {
217
- this.enrollment = enrollment;
218
- this.purchase = purchase;
219
- this.target = target;
220
- this.cardholderName = cardholderName;
221
- this.mintCredential = mintCredential;
222
- }
223
- /** See VgsLiveInstrument.confirmationTarget — same contract. */
224
- confirmationTarget() {
225
- return this.minted;
226
- }
227
- async getCredential(ctx) {
228
- if (this.used)
229
- throw new Error('VGS assurance instrument is single-use');
230
- this.used = true;
231
- validateCliCredential(this.enrollment);
232
- validateTarget(this.target, ctx);
233
- validatePurchaseAssurance(this.purchase, this.target);
234
- if (!this.cardholderName.trim())
235
- throw new Error('cardholder name is required');
236
- const { payment: value, intentId } = await this.mintCredential({
237
- tokenId: this.enrollment.tokenId,
238
- assuranceData: this.purchase.assuranceData,
239
- transaction: this.target,
240
- });
241
- this.minted = { tokenId: this.enrollment.tokenId, intentId };
242
- validateCredential(value);
243
- return {
244
- pan: value.networkToken,
245
- expMonth: value.expMonth,
246
- expYear: value.expYear,
247
- cvc: value.cryptogramValue,
248
- cardholderName: this.cardholderName.trim(),
249
- ...(value.cryptogramExpiresAt ? { credentialExpiresAt: value.cryptogramExpiresAt } : {}),
226
+ ...traceHandleFields(value),
250
227
  };
251
228
  }
252
229
  }
@@ -12,11 +12,29 @@ export type PostVicConfirmation = (input: {
12
12
  transactionCurrencyCode: string;
13
13
  };
14
14
  }) => Promise<unknown>;
15
+ /**
16
+ * Why a confirmation was not posted, as a BOUNDED value rather than prose.
17
+ *
18
+ * `reason` below is a human sentence built for the local receipt; it embeds
19
+ * upstream error text and is useless as an aggregate. These three codes are the
20
+ * whole space, and they mean very different things:
21
+ *
22
+ * - `outcome_not_definitive` — the merchant never gave a definitive answer, so
23
+ * there is nothing truthful to report. Expected, not a fault.
24
+ * - `no_credential_minted` — no VIC credential existed for this run, so there
25
+ * is no intent to confirm against. Expected, not a fault.
26
+ * - `post_failed` — we HAD a definitive outcome and an intent to report it
27
+ * against, and the POST did not land. This one is a fault: the processor
28
+ * lifecycle row is never written, so the purchase can never rank above the
29
+ * platform's own record no matter how well it actually went.
30
+ */
31
+ export type VicConfirmationSkipCode = 'outcome_not_definitive' | 'no_credential_minted' | 'post_failed';
15
32
  export type VicConfirmationReport = {
16
33
  posted: true;
17
34
  transactionStatus: VicTransactionStatus;
18
35
  } | {
19
36
  posted: false;
37
+ code: VicConfirmationSkipCode;
20
38
  reason: string;
21
39
  };
22
40
  /** Definitive merchant answers map to a status; everything else maps to none. */
@@ -11,12 +11,17 @@ export async function reportVicOutcome(input) {
11
11
  if (!transactionStatus) {
12
12
  return {
13
13
  posted: false,
14
+ code: 'outcome_not_definitive',
14
15
  reason: `outcome '${input.outcome}' is not a definitive merchant answer — ` +
15
16
  'resolve it with the merchant, then post the confirmation manually',
16
17
  };
17
18
  }
18
19
  if (!input.target) {
19
- return { posted: false, reason: 'no VIC credential was minted in this run' };
20
+ return {
21
+ posted: false,
22
+ code: 'no_credential_minted',
23
+ reason: 'no VIC credential was minted in this run',
24
+ };
20
25
  }
21
26
  try {
22
27
  await input.post({
@@ -32,8 +37,9 @@ export async function reportVicOutcome(input) {
32
37
  catch (err) {
33
38
  return {
34
39
  posted: false,
35
- reason: `confirmation POST failed: ${err.message} — the merchant outcome stands; ` +
36
- 'retry the confirmation for this intent out-of-band',
40
+ code: 'post_failed',
41
+ reason: `confirmation POST failed: ${err.message} — the merchant-reported outcome ` +
42
+ 'remains unverified; retry the confirmation for this intent out-of-band',
37
43
  };
38
44
  }
39
45
  }
@@ -0,0 +1,98 @@
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
+ signFn?: (signingInput: Uint8Array) => Promise<Uint8Array>;
25
+ }
26
+ export interface WebBotAuthConfig {
27
+ /** Absolute https URL of the operator-hosted signature directory. */
28
+ directoryUrl: string;
29
+ key: WebBotAuthSigningKey;
30
+ ttlSeconds?: number;
31
+ }
32
+ export interface WebBotAuthHeaders {
33
+ 'Signature-Input': string;
34
+ Signature: string;
35
+ 'Signature-Agent': string;
36
+ [header: string]: string;
37
+ }
38
+ export interface SignatureBaseParams {
39
+ authority: string;
40
+ directoryUrl: string;
41
+ keyId: string;
42
+ created: number;
43
+ expires: number;
44
+ }
45
+ /**
46
+ * Build the RFC 9421 signature base.
47
+ *
48
+ * The base is what actually gets signed, so its exact bytes are the contract
49
+ * with every verifier — one wrong space or a reordered parameter and the
50
+ * signature fails against a correct key. It is exported and pinned by a
51
+ * deterministic test vector for that reason.
52
+ */
53
+ export declare function buildSignatureBase(params: SignatureBaseParams): string;
54
+ /**
55
+ * The `@signature-params` value, which appears twice: as the final line of the
56
+ * signature base, and verbatim as the `Signature-Input` header value. Building
57
+ * it once is what keeps those two identical — a verifier rederives the base
58
+ * from the header it received, so any divergence fails every signature.
59
+ */
60
+ export declare function buildSignatureParams(params: SignatureBaseParams): string;
61
+ export interface BuildHeadersParams {
62
+ /** Host (and port, if non-default) of the request being signed. */
63
+ authority: string;
64
+ config: WebBotAuthConfig;
65
+ /** Unix seconds. Injected so tests are deterministic and never wall-clock. */
66
+ nowSeconds: number;
67
+ }
68
+ /**
69
+ * Produce the three Web Bot Auth headers for one request authority.
70
+ *
71
+ * Throws on unusable key material rather than emitting an unverifiable
72
+ * signature. Callers on the checkout path must treat a throw as "proceed
73
+ * unsigned" — see `webBotAuthHeadersOrNone`.
74
+ */
75
+ export declare function buildWebBotAuthHeaders(params: BuildHeadersParams): WebBotAuthHeaders;
76
+ /**
77
+ * Header-or-nothing wrapper for the checkout path.
78
+ *
79
+ * Signing is an optional trust upgrade, never a precondition for buying
80
+ * something. Unusable key material, a malformed URL, or any crypto failure
81
+ * degrades to an unsigned request — which is exactly what we sent before this
82
+ * module existed — rather than throwing into a live checkout.
83
+ */
84
+ export declare function webBotAuthHeadersOrNone(config: WebBotAuthConfig | null, targetUrl: string, nowSeconds: number): WebBotAuthHeaders | null;
85
+ /**
86
+ * Async version of buildWebBotAuthHeaders, supporting Turnkey or vault signFn signers.
87
+ */
88
+ export declare function buildWebBotAuthHeadersAsync(params: BuildHeadersParams): Promise<WebBotAuthHeaders>;
89
+ export declare function webBotAuthHeadersOrNoneAsync(config: WebBotAuthConfig | null, targetUrl: string, nowSeconds: number): Promise<WebBotAuthHeaders | null>;
90
+ /**
91
+ * Resolve signing config from the environment. Returns `null` — meaning "send
92
+ * unsigned" — unless a directory URL and a usable key are BOTH present.
93
+ *
94
+ * Default-off is deliberate. Until the operator directory is live and serving
95
+ * this key, a signature resolves to nothing and fails verification, which is
96
+ * worse than the honest unsigned request we sent before.
97
+ */
98
+ export declare function resolveWebBotAuthConfig(env: NodeJS.ProcessEnv, loadKey: () => WebBotAuthSigningKey | null): WebBotAuthConfig | null;
@@ -0,0 +1,218 @@
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
+ // privateJwk is optional on the key so a vault-held signer can supply signFn
92
+ // instead. Only the async builder can await such a signer, so refuse here with
93
+ // the same explicit message rather than handing undefined to createPrivateKey
94
+ // and surfacing an opaque node:crypto error.
95
+ if (!config.key.privateJwk) {
96
+ throw new Error(config.key.signFn
97
+ ? 'WebBotAuthSigningKey with signFn requires buildWebBotAuthHeadersAsync'
98
+ : 'WebBotAuthSigningKey requires either privateJwk or signFn');
99
+ }
100
+ const privateKey = createPrivateKey({
101
+ key: config.key.privateJwk,
102
+ format: 'jwk',
103
+ });
104
+ // Ed25519 takes no separate digest algorithm; null is the required argument.
105
+ const signature = cryptoSign(null, Buffer.from(base, 'utf8'), privateKey);
106
+ return {
107
+ 'Signature-Input': `${WEB_BOT_AUTH_SIGNATURE_LABEL}=${signatureParams}`,
108
+ Signature: `${WEB_BOT_AUTH_SIGNATURE_LABEL}=:${signature.toString('base64')}:`,
109
+ 'Signature-Agent': sfString(config.directoryUrl),
110
+ };
111
+ }
112
+ /**
113
+ * Header-or-nothing wrapper for the checkout path.
114
+ *
115
+ * Signing is an optional trust upgrade, never a precondition for buying
116
+ * something. Unusable key material, a malformed URL, or any crypto failure
117
+ * degrades to an unsigned request — which is exactly what we sent before this
118
+ * module existed — rather than throwing into a live checkout.
119
+ */
120
+ export function webBotAuthHeadersOrNone(config, targetUrl, nowSeconds) {
121
+ if (!config)
122
+ return null;
123
+ try {
124
+ const authority = new URL(targetUrl).host;
125
+ if (!authority)
126
+ return null;
127
+ return buildWebBotAuthHeaders({ authority, config, nowSeconds });
128
+ }
129
+ catch {
130
+ return null;
131
+ }
132
+ }
133
+ /**
134
+ * Async version of buildWebBotAuthHeaders, supporting Turnkey or vault signFn signers.
135
+ */
136
+ export async function buildWebBotAuthHeadersAsync(params) {
137
+ const { authority, config, nowSeconds } = params;
138
+ const ttl = Math.min(Math.max(1, Math.floor(config.ttlSeconds ?? WEB_BOT_AUTH_DEFAULT_TTL_SECONDS)), WEB_BOT_AUTH_MAX_TTL_SECONDS);
139
+ const created = Math.floor(nowSeconds);
140
+ const expires = created + ttl;
141
+ const baseParams = {
142
+ authority,
143
+ directoryUrl: config.directoryUrl,
144
+ keyId: config.key.keyId,
145
+ created,
146
+ expires,
147
+ };
148
+ const base = buildSignatureBase(baseParams);
149
+ const signatureParams = buildSignatureParams(baseParams);
150
+ let signature;
151
+ if (config.key.signFn) {
152
+ signature = await config.key.signFn(Buffer.from(base, 'utf8'));
153
+ }
154
+ else if (config.key.privateJwk) {
155
+ const privateKey = createPrivateKey({
156
+ key: config.key.privateJwk,
157
+ format: 'jwk',
158
+ });
159
+ signature = cryptoSign(null, Buffer.from(base, 'utf8'), privateKey);
160
+ }
161
+ else {
162
+ throw new Error('WebBotAuthSigningKey requires either privateJwk or signFn');
163
+ }
164
+ return {
165
+ 'Signature-Input': `${WEB_BOT_AUTH_SIGNATURE_LABEL}=${signatureParams}`,
166
+ Signature: `${WEB_BOT_AUTH_SIGNATURE_LABEL}=:${Buffer.from(signature).toString('base64')}:`,
167
+ 'Signature-Agent': sfString(config.directoryUrl),
168
+ };
169
+ }
170
+ export async function webBotAuthHeadersOrNoneAsync(config, targetUrl, nowSeconds) {
171
+ if (!config)
172
+ return null;
173
+ try {
174
+ const authority = new URL(targetUrl).host;
175
+ if (!authority)
176
+ return null;
177
+ return await buildWebBotAuthHeadersAsync({ authority, config, nowSeconds });
178
+ }
179
+ catch {
180
+ return null;
181
+ }
182
+ }
183
+ /**
184
+ * Resolve signing config from the environment. Returns `null` — meaning "send
185
+ * unsigned" — unless a directory URL and a usable key are BOTH present.
186
+ *
187
+ * Default-off is deliberate. Until the operator directory is live and serving
188
+ * this key, a signature resolves to nothing and fails verification, which is
189
+ * worse than the honest unsigned request we sent before.
190
+ */
191
+ export function resolveWebBotAuthConfig(env, loadKey) {
192
+ const directoryUrl = env.VISA_WEB_BOT_AUTH_DIRECTORY_URL?.trim();
193
+ if (!directoryUrl)
194
+ return null;
195
+ let parsed;
196
+ try {
197
+ parsed = new URL(directoryUrl);
198
+ }
199
+ catch {
200
+ return null;
201
+ }
202
+ // A directory fetched over plain http could be swapped in flight, which would
203
+ // let an observer substitute the key set our identity is judged against.
204
+ if (parsed.protocol !== 'https:')
205
+ return null;
206
+ let key = null;
207
+ try {
208
+ key = loadKey();
209
+ }
210
+ catch {
211
+ return null;
212
+ }
213
+ if (!key?.keyId || (!key.signFn && (key.privateJwk?.crv !== 'Ed25519' || !key.privateJwk.d)))
214
+ return null;
215
+ const rawTtl = Number(env.VISA_WEB_BOT_AUTH_TTL_SECONDS);
216
+ const ttlSeconds = Number.isFinite(rawTtl) && rawTtl > 0 ? rawTtl : undefined;
217
+ return { directoryUrl: parsed.toString(), key, ttlSeconds };
218
+ }