@visa/cli 4.1.0-rc.25 → 4.1.0-rc.251

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 (89) hide show
  1. package/README.md +273 -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 +625 -146
  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/shopify-primary-domain.d.ts +25 -0
  47. package/dist/checkout-engine/shopify-primary-domain.js +96 -0
  48. package/dist/checkout-engine/trace-handles.d.ts +8 -0
  49. package/dist/checkout-engine/trace-handles.js +12 -0
  50. package/dist/checkout-engine/types.d.ts +28 -2
  51. package/dist/checkout-engine/unresolved-charges.d.ts +34 -0
  52. package/dist/checkout-engine/unresolved-charges.js +134 -0
  53. package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +53 -1
  54. package/dist/checkout-engine/vgs-gateway/server-mint-client.js +78 -10
  55. package/dist/checkout-engine/vgs-live-instrument.d.ts +38 -35
  56. package/dist/checkout-engine/vgs-live-instrument.js +51 -74
  57. package/dist/checkout-engine/vic-confirmation.d.ts +18 -0
  58. package/dist/checkout-engine/vic-confirmation.js +9 -3
  59. package/dist/checkout-engine/web-bot-auth.d.ts +98 -0
  60. package/dist/checkout-engine/web-bot-auth.js +218 -0
  61. package/dist/cli.js +905 -505
  62. package/dist/mcp-apps/ucp-checkout.html +280 -0
  63. package/dist/mcp-server/index.js +744 -175
  64. package/dist/merchant-ucp-mcp/index.js +6 -0
  65. package/dist/skills/pair-visa-agent/RUNTIMES.md +122 -79
  66. package/dist/skills/pair-visa-agent/SKILL.md +436 -279
  67. package/dist/skills/pair-visa-agent/scripts/__tests__/setup.test.mjs +407 -0
  68. package/dist/skills/pair-visa-agent/scripts/setup.mjs +310 -30
  69. package/dist/skills/visa-shopify-checkout/SKILL.md +122 -0
  70. package/dist/skills/visa-shopify-checkout/references/evidence-and-states.md +37 -0
  71. package/dist/skills/visa-ucp-shopping/SKILL.md +86 -0
  72. package/dist/subway-direct.mjs +1 -0
  73. package/install.ps1 +9 -46
  74. package/install.sh +5 -37
  75. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  76. package/package.json +32 -28
  77. package/server.json +4 -4
  78. package/dist/checkout-engine/inline-target.d.ts +0 -13
  79. package/dist/checkout-engine/inline-target.js +0 -37
  80. package/dist/checkout-engine/pay-args.d.ts +0 -14
  81. package/dist/checkout-engine/pay-args.js +0 -44
  82. package/dist/checkout-engine/pay.d.ts +0 -1
  83. package/dist/checkout-engine/pay.js +0 -13
  84. package/dist/checkout-engine/repo-env.d.ts +0 -11
  85. package/dist/checkout-engine/repo-env.js +0 -23
  86. package/dist/checkout-engine/run-live-fill.d.ts +0 -1
  87. package/dist/checkout-engine/run-live-fill.js +0 -443
  88. package/dist/checkout-engine/vgs-gateway/fetch-credential.d.mts +0 -74
  89. package/dist/checkout-engine/vgs-gateway/fetch-credential.mjs +0 -248
@@ -11,6 +11,7 @@
11
11
  // Request derivation here mirrors ../fetch-credential.mjs EXACTLY (mandate cap,
12
12
  // consumer prompt, PENDING retry cadence) — the only change is the transport:
13
13
  // verify-web routes + Bearer mint token, never the VGS gateway + VGS secret.
14
+ import { traceHandleFields } from '../trace-handles.js';
14
15
  const defaultSleep = (ms) => new Promise((r) => {
15
16
  const t = setTimeout(r, ms);
16
17
  t.unref?.();
@@ -21,10 +22,62 @@ function stripTrailingSlashes(value) {
21
22
  out = out.slice(0, -1);
22
23
  return out;
23
24
  }
25
+ /**
26
+ * The merchant ORIGIN (scheme + host) — not the full checkout URL. A merchant's
27
+ * identity is its origin; a real checkout URL can carry hundreds of chars of
28
+ * campaign/tracking query params. Confirmed live: an oversized `merchantUrl`
29
+ * (a ~280-char Wikimedia donation URL) makes the cryptogram mint fail downstream
30
+ * with a vague `502 "card network could not complete"`, while the same merchant
31
+ * with a trimmed URL mints fine. Sending the origin is both correct (that IS the
32
+ * merchant) and safely bounded. Falls back to the raw value if it does not parse
33
+ * — the mint must never throw here.
34
+ */
35
+ export function merchantOrigin(url) {
36
+ try {
37
+ return new URL(url).origin;
38
+ }
39
+ catch {
40
+ return url;
41
+ }
42
+ }
43
+ /**
44
+ * A definitive refusal from the cryptogram mint route — the request will not
45
+ * succeed if retried unchanged.
46
+ *
47
+ * `terminal` is the load-bearing field. Draw terminality used to be decided by
48
+ * regex over the error MESSAGE, which made it hostage to text nobody controls:
49
+ * this client now interpolates the provider's own `upstream_codes` into the
50
+ * message for diagnosability, and a provider identifier such as
51
+ * `request_timeout` would match the transient matcher's unanchored
52
+ * `tim(e|ed)-out` alternative — flipping a permanent 422 back to "transient",
53
+ * skipping markUnhonored, and stranding the mandate in the exact retry-forever
54
+ * loop this whole change exists to kill. Terminality is therefore carried
55
+ * structurally, and consumers must consult it BEFORE any message matching.
56
+ */
57
+ export class ServerCryptogramRefusedError extends Error {
58
+ status;
59
+ terminal = true;
60
+ constructor(status, detail) {
61
+ super(`server cryptogram refused (${status}): ${detail}`);
62
+ this.name = 'ServerCryptogramRefusedError';
63
+ this.status = status;
64
+ }
65
+ }
24
66
  /** Read a stable, non-secret error message from a route's JSON body. */
25
67
  async function routeError(res) {
26
68
  const doc = (await res.json().catch(() => null));
27
- return doc?.error || doc?.error_code || `HTTP ${res.status}`;
69
+ const base = doc?.error || doc?.error_code || `HTTP ${res.status}`;
70
+ // Carry the provider's own status and rejected-attribute identifiers into the
71
+ // message when the route reflected them. Without this the operator sees only
72
+ // our status and has to go log-diving to learn WHICH field the gateway
73
+ // objected to — the gap that left a live create_intent 422 undiagnosable.
74
+ const parts = [];
75
+ if (typeof doc?.upstream_status === 'number')
76
+ parts.push(`upstream_status=${doc.upstream_status}`);
77
+ if (Array.isArray(doc?.upstream_codes) && doc.upstream_codes.length > 0) {
78
+ parts.push(`upstream_codes=${doc.upstream_codes.join(',')}`);
79
+ }
80
+ return parts.length > 0 ? `${base} [${parts.join(' ')}]` : base;
28
81
  }
29
82
  function bearer(mintToken) {
30
83
  return { 'content-type': 'application/json', authorization: `Bearer ${mintToken}` };
@@ -32,29 +85,37 @@ function bearer(mintToken) {
32
85
  /**
33
86
  * Create a fresh intent via POST {base}/api/vgs/intent. The server holds the VGS
34
87
  * credential and calls the gateway; we send the same mandate shape the local
35
- * path built (cap = ceil(amount)+10, min 25; merchant category Retail/5999).
88
+ * path built (cap = ceil(amount)+10, min 25; merchant category Retail/5999)
89
+ * unless `input.mandate` overrides the threshold/quantity/window for the
90
+ * card-mandate (budget) layer.
36
91
  */
37
92
  export async function serverCreateIntent(base, mintToken, input, deps = {}) {
38
93
  const fetchImpl = deps.fetchImpl ?? fetch;
39
94
  const { tokenId, assuranceData, transaction: t } = input;
40
- const cap = Math.max(Math.ceil(Number(t.transactionAmount) || 0) + 10, 25);
95
+ const override = input.mandate ?? {};
96
+ const defaultCap = Math.max(Math.ceil(Number(t.transactionAmount) || 0) + 10, 25);
97
+ const declineThresholdAmount = override.declineThresholdAmount ?? String(defaultCap);
98
+ const quantity = override.quantity ?? 1;
99
+ const effectiveUntil = override.effectiveUntil ?? new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString();
100
+ const consumerPrompt = override.consumerPrompt ??
101
+ `Buy an item from ${t.merchantName} for ${t.transactionCurrencyCode.toUpperCase()} ${t.transactionAmount}`;
41
102
  const res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/intent`, {
42
103
  method: 'POST',
43
104
  headers: bearer(mintToken),
44
105
  body: JSON.stringify({
45
106
  tokenId,
46
- consumerPrompt: `Buy an item from ${t.merchantName} for ${t.transactionCurrencyCode.toUpperCase()} ${t.transactionAmount}`,
107
+ consumerPrompt,
47
108
  assuranceData,
48
109
  mandates: [
49
110
  {
50
111
  description: `Purchase at ${t.merchantName}`,
51
- declineThresholdAmount: String(cap),
112
+ declineThresholdAmount,
52
113
  declineThresholdCurrencyCode: t.transactionCurrencyCode.toUpperCase(),
53
- effectiveUntil: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
114
+ effectiveUntil,
54
115
  merchantCategory: 'Retail',
55
116
  merchantCategoryCode: '5999',
56
117
  preferredMerchantName: t.merchantName,
57
- quantity: 1,
118
+ quantity,
58
119
  },
59
120
  ],
60
121
  }),
@@ -89,7 +150,9 @@ export async function serverFetchCryptogram(base, mintToken, input, deps = {}) {
89
150
  intentId,
90
151
  transaction: {
91
152
  merchantName: t.merchantName,
92
- merchantUrl: t.merchantUrl,
153
+ // Send the merchant ORIGIN, not the full (possibly huge) checkout URL — an
154
+ // oversized merchantUrl makes the downstream cryptogram mint 502 (proven live).
155
+ merchantUrl: merchantOrigin(t.merchantUrl),
93
156
  merchantCountryCode: t.merchantCountryCode,
94
157
  transactionAmount: t.transactionAmount,
95
158
  transactionCurrencyCode: t.transactionCurrencyCode.toUpperCase(),
@@ -116,11 +179,16 @@ export async function serverFetchCryptogram(base, mintToken, input, deps = {}) {
116
179
  ...(typeof c.cryptogramExpiresAt === 'string'
117
180
  ? { cryptogramExpiresAt: c.cryptogramExpiresAt }
118
181
  : {}),
182
+ ...traceHandleFields(c),
119
183
  };
120
184
  }
121
185
  // A 4xx (bad request / binding refusal / auth) is terminal — never retry it.
122
- if (res.status >= 400 && res.status < 500) {
123
- throw new Error(`server cryptogram refused (${res.status}): ${await routeError(res)}`);
186
+ // 429 is the sole exception: it is an explicitly retryable 4xx, and treating
187
+ // it as terminal would let a transient rate limit permanently disable a
188
+ // healthy mandate. The route maps upstream rate limits to 503 today, so this
189
+ // is a guard against a future emitter, not a live path.
190
+ if (res.status >= 400 && res.status < 500 && res.status !== 429) {
191
+ throw new ServerCryptogramRefusedError(res.status, await routeError(res));
124
192
  }
125
193
  lastError = `${res.status}: ${await routeError(res)}`;
126
194
  if (attempt < attempts)
@@ -42,6 +42,15 @@ export type PurchaseAssurance = {
42
42
  transactionAmount: string;
43
43
  /** ISO 4217 currency the ceremony was scoped to. */
44
44
  transactionCurrencyCode: string;
45
+ /**
46
+ * True iff the approval server marked this token passkey-exempt ('otp'
47
+ * cardholder ID&V / 'none' — verified against the owner's account card
48
+ * record at complete-time): no ceremony ran, `assuranceData` is null by
49
+ * design, and the intent is minted without it (the signed mint token
50
+ * carries the same exemption for the server's own check). Absent/false →
51
+ * assuranceData is REQUIRED, exactly the historical contract.
52
+ */
53
+ assuranceExempt?: boolean;
45
54
  };
46
55
  /**
47
56
  * Our fail-closed freshness bound, matching the runner's 15-minute checkout
@@ -57,6 +66,8 @@ export type VgsPaymentCredential = {
57
66
  cryptogramType: string;
58
67
  cryptogramValue: string;
59
68
  cryptogramExpiresAt?: string;
69
+ vgsTraceId?: string;
70
+ networkCorrelationId?: string;
60
71
  };
61
72
  export type FetchVgsPaymentCredential = (input: {
62
73
  tokenId: string;
@@ -69,20 +80,39 @@ export type FetchVgsPaymentCredential = (input: {
69
80
  transactionCurrencyCode: string;
70
81
  };
71
82
  }) => Promise<VgsPaymentCredential>;
72
- export type MintFreshVgsPaymentCredential = (input: {
73
- tokenId: string;
74
- assuranceData: unknown;
75
- transaction: VgsCheckoutTarget;
76
- }) => Promise<{
77
- payment: VgsPaymentCredential;
78
- intentId: string;
79
- }>;
80
83
  /** The (token, intent) pair a VIC confirmation is posted against. */
81
84
  export type VicConfirmationTarget = {
82
85
  tokenId: string;
83
86
  intentId: string;
84
87
  };
85
88
  export declare function decimalToMinor(value: unknown): number | null;
89
+ /**
90
+ * Currencies whose minor unit is 1/100 of the major unit (2 decimal places).
91
+ * minorToDecimal's /100 + pad-to-2 rendering is ONLY correct for these. The
92
+ * card mandate path accepts any 3-letter ISO code, so a 0- or 3-decimal
93
+ * currency (JPY, BHD, …) would otherwise be emitted with a wrong wire amount.
94
+ * We only support USD/USDC today; extend deliberately (and fix the exponent)
95
+ * before adding any non-2-decimal currency.
96
+ *
97
+ * NOTE (scanner FP pre-empt): this is a CLIENT-SIDE currency-exponent lookup for
98
+ * rendering a wire amount in @visa/checkout-engine — it is NOT the cross-store
99
+ * `PAYMENT_CURRENCIES` enum governed by apps/auth/src/shared-validators.ts, and
100
+ * this package cannot import from apps/auth (no dependency edge). It intentionally
101
+ * does not mirror that enum's membership; do not "reconcile" the two.
102
+ */
103
+ export declare const TWO_DECIMAL_CURRENCIES: Set<string>;
104
+ /**
105
+ * Inverse of decimalToMinor: render integer minor units as a major-unit decimal
106
+ * string ("D.DD") for the VGS wire (e.g. a ceiling of 50000 minor → "500.00").
107
+ * Integer-only; never floating-point money. Throws on a non-integer/negative so
108
+ * a bad accounting value cannot silently reach the network.
109
+ *
110
+ * The /100 + pad-to-2 rendering assumes a 2-decimal (exponent-2) currency. Pass
111
+ * `currencyCode` on any path that accepts arbitrary currencies (the mandate
112
+ * path) and it REFUSES a non-2-decimal currency rather than emit a wrong wire
113
+ * amount. Omit it only where the currency is already known to be USD/USDC.
114
+ */
115
+ export declare function minorToDecimal(minor: number, currencyCode?: string): string;
86
116
  /**
87
117
  * Refuse to mint an intent unless the assurance is fresh and its declared
88
118
  * scope matches the checkout target exactly. `now` is injectable so the
@@ -112,30 +142,3 @@ export declare class VgsLiveInstrument implements Instrument {
112
142
  confirmationTarget(): VicConfirmationTarget | null;
113
143
  getCredential(ctx: InstrumentContext): Promise<CardCredential>;
114
144
  }
115
- /**
116
- * Consumes #5614's claimed CLI enrollment artifact (for the tokenId) plus a
117
- * FRESH purchase-scoped assurance, and creates a fresh, transaction-scoped VIC
118
- * intent + credential after checkout approval. This is the production-shaped
119
- * bridge; unlike VgsLiveInstrument it never needs a pre-created intent ID.
120
- *
121
- * The enrollment artifact's stored assuranceData is deliberately never sent:
122
- * replaying it makes intent creation succeed (HTTP 201) while the cryptogram
123
- * deterministically never completes — the #5709 dead end. Purchase
124
- * authorization is the fresh, merchant+amount+currency-scoped assurance,
125
- * validated against the checkout target BEFORE any intent is minted so a
126
- * doomed intent is never created.
127
- */
128
- export declare class VgsAssuranceInstrument implements Instrument {
129
- private readonly enrollment;
130
- private readonly purchase;
131
- private readonly target;
132
- private readonly cardholderName;
133
- private readonly mintCredential;
134
- readonly kind: "agentic-token";
135
- private used;
136
- private minted;
137
- constructor(enrollment: CliAgentCredential, purchase: PurchaseAssurance, target: VgsCheckoutTarget, cardholderName: string, mintCredential: MintFreshVgsPaymentCredential);
138
- /** See VgsLiveInstrument.confirmationTarget — same contract. */
139
- confirmationTarget(): VicConfirmationTarget | null;
140
- getCredential(ctx: InstrumentContext): Promise<CardCredential>;
141
- }
@@ -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;