@visa/cli 4.1.0-rc.13 → 4.1.0-rc.130

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 (63) hide show
  1. package/README.md +188 -232
  2. package/dist/checkout-engine/adapters/generic.d.ts +4 -0
  3. package/dist/checkout-engine/adapters/generic.js +28 -13
  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 +31 -0
  7. package/dist/checkout-engine/adapters/shopify.js +423 -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/cli-engine.d.ts +207 -2
  11. package/dist/checkout-engine/cli-engine.js +677 -27
  12. package/dist/checkout-engine/detect.d.ts +1 -1
  13. package/dist/checkout-engine/detect.js +26 -0
  14. package/dist/checkout-engine/evidence.d.ts +4 -1
  15. package/dist/checkout-engine/evidence.js +51 -6
  16. package/dist/checkout-engine/executor.d.ts +34 -4
  17. package/dist/checkout-engine/executor.js +266 -115
  18. package/dist/checkout-engine/hosted-approval.d.ts +133 -8
  19. package/dist/checkout-engine/hosted-approval.js +400 -49
  20. package/dist/checkout-engine/index.d.ts +4 -1
  21. package/dist/checkout-engine/index.js +3 -0
  22. package/dist/checkout-engine/instrument.d.ts +7 -0
  23. package/dist/checkout-engine/instrument.js +4 -0
  24. package/dist/checkout-engine/live-fill-approval.d.ts +0 -20
  25. package/dist/checkout-engine/live-fill-approval.js +15 -51
  26. package/dist/checkout-engine/mandate/card-mandate.d.ts +121 -0
  27. package/dist/checkout-engine/mandate/card-mandate.js +227 -0
  28. package/dist/checkout-engine/mandate/mandate-ledger.d.ts +165 -0
  29. package/dist/checkout-engine/mandate/mandate-ledger.js +373 -0
  30. package/dist/checkout-engine/outcome.d.ts +2 -2
  31. package/dist/checkout-engine/outcome.js +36 -1
  32. package/dist/checkout-engine/owner-only-file.d.ts +9 -0
  33. package/dist/checkout-engine/owner-only-file.js +20 -1
  34. package/dist/checkout-engine/trace-handles.d.ts +8 -0
  35. package/dist/checkout-engine/trace-handles.js +12 -0
  36. package/dist/checkout-engine/types.d.ts +20 -2
  37. package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +82 -0
  38. package/dist/checkout-engine/vgs-gateway/server-mint-client.js +180 -0
  39. package/dist/checkout-engine/vgs-live-instrument.d.ts +38 -0
  40. package/dist/checkout-engine/vgs-live-instrument.js +52 -8
  41. package/dist/checkout-engine/vic-confirmation.js +2 -2
  42. package/dist/cli.js +579 -494
  43. package/dist/mcp-server/index.js +441 -176
  44. package/dist/skills/pair-visa-agent/RUNTIMES.md +92 -0
  45. package/dist/skills/pair-visa-agent/SKILL.md +467 -0
  46. package/dist/skills/pair-visa-agent/scripts/setup.mjs +48 -0
  47. package/install.ps1 +3 -41
  48. package/install.sh +4 -36
  49. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  50. package/package.json +16 -12
  51. package/server.json +3 -3
  52. package/dist/checkout-engine/inline-target.d.ts +0 -13
  53. package/dist/checkout-engine/inline-target.js +0 -37
  54. package/dist/checkout-engine/pay-args.d.ts +0 -14
  55. package/dist/checkout-engine/pay-args.js +0 -44
  56. package/dist/checkout-engine/pay.d.ts +0 -1
  57. package/dist/checkout-engine/pay.js +0 -13
  58. package/dist/checkout-engine/repo-env.d.ts +0 -11
  59. package/dist/checkout-engine/repo-env.js +0 -23
  60. package/dist/checkout-engine/run-live-fill.d.ts +0 -1
  61. package/dist/checkout-engine/run-live-fill.js +0 -443
  62. package/dist/checkout-engine/vgs-gateway/fetch-credential.d.mts +0 -74
  63. package/dist/checkout-engine/vgs-gateway/fetch-credential.mjs +0 -240
@@ -0,0 +1,180 @@
1
+ // Server-side mint client (Phase 1) — the checkout runner mints the payment
2
+ // credential by calling the verify-web deployment's gateway routes with a
3
+ // short-lived, purpose-scoped MINT TOKEN, instead of holding the shared VGS
4
+ // service-account secret (the gateway client id/secret) on the machine.
5
+ //
6
+ // The mint token is issued at approval time (agent-approval/complete, which is
7
+ // session + internal-tester + token-ownership gated) and released to this
8
+ // runner by the claim leg. It is bound to the exact approved purchase, so these
9
+ // calls can only mint the credential the human approved.
10
+ //
11
+ // Request derivation here mirrors ../fetch-credential.mjs EXACTLY (mandate cap,
12
+ // consumer prompt, PENDING retry cadence) — the only change is the transport:
13
+ // verify-web routes + Bearer mint token, never the VGS gateway + VGS secret.
14
+ import { traceHandleFields } from '../trace-handles.js';
15
+ const defaultSleep = (ms) => new Promise((r) => {
16
+ const t = setTimeout(r, ms);
17
+ t.unref?.();
18
+ });
19
+ function stripTrailingSlashes(value) {
20
+ let out = value;
21
+ while (out.endsWith('/'))
22
+ out = out.slice(0, -1);
23
+ return out;
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
+ /** Read a stable, non-secret error message from a route's JSON body. */
44
+ async function routeError(res) {
45
+ const doc = (await res.json().catch(() => null));
46
+ return doc?.error || doc?.error_code || `HTTP ${res.status}`;
47
+ }
48
+ function bearer(mintToken) {
49
+ return { 'content-type': 'application/json', authorization: `Bearer ${mintToken}` };
50
+ }
51
+ /**
52
+ * Create a fresh intent via POST {base}/api/vgs/intent. The server holds the VGS
53
+ * credential and calls the gateway; we send the same mandate shape the local
54
+ * path built (cap = ceil(amount)+10, min 25; merchant category Retail/5999) —
55
+ * unless `input.mandate` overrides the threshold/quantity/window for the
56
+ * card-mandate (budget) layer.
57
+ */
58
+ export async function serverCreateIntent(base, mintToken, input, deps = {}) {
59
+ const fetchImpl = deps.fetchImpl ?? fetch;
60
+ const { tokenId, assuranceData, transaction: t } = input;
61
+ const override = input.mandate ?? {};
62
+ const defaultCap = Math.max(Math.ceil(Number(t.transactionAmount) || 0) + 10, 25);
63
+ const declineThresholdAmount = override.declineThresholdAmount ?? String(defaultCap);
64
+ const quantity = override.quantity ?? 1;
65
+ const effectiveUntil = override.effectiveUntil ?? new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString();
66
+ const consumerPrompt = override.consumerPrompt ??
67
+ `Buy an item from ${t.merchantName} for ${t.transactionCurrencyCode.toUpperCase()} ${t.transactionAmount}`;
68
+ const res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/intent`, {
69
+ method: 'POST',
70
+ headers: bearer(mintToken),
71
+ body: JSON.stringify({
72
+ tokenId,
73
+ consumerPrompt,
74
+ assuranceData,
75
+ mandates: [
76
+ {
77
+ description: `Purchase at ${t.merchantName}`,
78
+ declineThresholdAmount,
79
+ declineThresholdCurrencyCode: t.transactionCurrencyCode.toUpperCase(),
80
+ effectiveUntil,
81
+ merchantCategory: 'Retail',
82
+ merchantCategoryCode: '5999',
83
+ preferredMerchantName: t.merchantName,
84
+ quantity,
85
+ },
86
+ ],
87
+ }),
88
+ });
89
+ if (!res.ok)
90
+ throw new Error(`server intent failed (${res.status}): ${await routeError(res)}`);
91
+ const doc = (await res.json().catch(() => null));
92
+ if (!doc?.intentId)
93
+ throw new Error('server intent response missing intentId');
94
+ return { intentId: doc.intentId, status: typeof doc.status === 'string' ? doc.status : null };
95
+ }
96
+ /**
97
+ * Mint the FULL payment credential via POST {base}/api/vgs/payment-cryptogram.
98
+ * The server's route does a SINGLE gateway call and 502s on a not-COMPLETED
99
+ * (e.g. PENDING) cryptogram, but live intent approval is asynchronous and the
100
+ * first cryptogram answer can be PENDING (#5709). So we retry the route on any
101
+ * non-2xx up to PENDING_ATTEMPTS, matching fetch-credential.mjs's cadence
102
+ * exactly — a genuinely hard failure just surfaces after the same bounded wait.
103
+ * Re-POSTing for the same intentId is idempotent (mirrors the old client loop).
104
+ */
105
+ export async function serverFetchCryptogram(base, mintToken, input, deps = {}) {
106
+ const fetchImpl = deps.fetchImpl ?? fetch;
107
+ const sleep = deps.sleep ?? defaultSleep;
108
+ const env = deps.env ?? process.env;
109
+ const attempts = Math.max(1, Number(env.VGS_CRYPTOGRAM_PENDING_ATTEMPTS) || 4);
110
+ const waitMs = Number.isFinite(Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS))
111
+ ? Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS)
112
+ : 5000;
113
+ const { tokenId, intentId, transaction: t } = input;
114
+ const body = JSON.stringify({
115
+ tokenId,
116
+ intentId,
117
+ transaction: {
118
+ merchantName: t.merchantName,
119
+ // Send the merchant ORIGIN, not the full (possibly huge) checkout URL — an
120
+ // oversized merchantUrl makes the downstream cryptogram mint 502 (proven live).
121
+ merchantUrl: merchantOrigin(t.merchantUrl),
122
+ merchantCountryCode: t.merchantCountryCode,
123
+ transactionAmount: t.transactionAmount,
124
+ transactionCurrencyCode: t.transactionCurrencyCode.toUpperCase(),
125
+ },
126
+ });
127
+ let lastError = 'unknown';
128
+ for (let attempt = 1; attempt <= attempts; attempt++) {
129
+ const res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/payment-cryptogram`, {
130
+ method: 'POST',
131
+ headers: bearer(mintToken),
132
+ body,
133
+ });
134
+ if (res.ok) {
135
+ const c = (await res.json().catch(() => null));
136
+ if (!c || typeof c.networkToken !== 'string' || typeof c.cryptogramValue !== 'string') {
137
+ throw new Error('server cryptogram response missing credential fields');
138
+ }
139
+ return {
140
+ networkToken: c.networkToken,
141
+ expMonth: Number(c.expMonth) || 0,
142
+ expYear: Number(c.expYear) || 0,
143
+ cryptogramType: c.cryptogramType ?? '',
144
+ cryptogramValue: c.cryptogramValue,
145
+ ...(typeof c.cryptogramExpiresAt === 'string'
146
+ ? { cryptogramExpiresAt: c.cryptogramExpiresAt }
147
+ : {}),
148
+ ...traceHandleFields(c),
149
+ };
150
+ }
151
+ // A 4xx (bad request / binding refusal / auth) is terminal — never retry it.
152
+ if (res.status >= 400 && res.status < 500) {
153
+ throw new Error(`server cryptogram refused (${res.status}): ${await routeError(res)}`);
154
+ }
155
+ lastError = `${res.status}: ${await routeError(res)}`;
156
+ if (attempt < attempts)
157
+ await sleep(waitMs);
158
+ }
159
+ throw new Error(`server cryptogram not completed after ${attempts} attempts (last: ${lastError})`);
160
+ }
161
+ /** Report the observed merchant outcome via POST {base}/api/vgs/confirmation. */
162
+ export async function serverPostConfirmation(base, mintToken, input, deps = {}) {
163
+ const fetchImpl = deps.fetchImpl ?? fetch;
164
+ const res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/confirmation`, {
165
+ method: 'POST',
166
+ headers: bearer(mintToken),
167
+ body: JSON.stringify({
168
+ tokenId: input.tokenId,
169
+ intentId: input.intentId,
170
+ transactionStatus: input.transactionStatus,
171
+ transactionType: input.transactionType,
172
+ transactionTimestamp: input.transactionTimestamp,
173
+ transactionAmount: input.transaction.transactionAmount,
174
+ transactionCurrencyCode: input.transaction.transactionCurrencyCode.toUpperCase(),
175
+ }),
176
+ });
177
+ if (!res.ok)
178
+ throw new Error(`server confirmation failed (${res.status}): ${await routeError(res)}`);
179
+ return { ok: true };
180
+ }
@@ -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;
@@ -83,6 +94,33 @@ export type VicConfirmationTarget = {
83
94
  intentId: string;
84
95
  };
85
96
  export declare function decimalToMinor(value: unknown): number | null;
97
+ /**
98
+ * Currencies whose minor unit is 1/100 of the major unit (2 decimal places).
99
+ * minorToDecimal's /100 + pad-to-2 rendering is ONLY correct for these. The
100
+ * card mandate path accepts any 3-letter ISO code, so a 0- or 3-decimal
101
+ * currency (JPY, BHD, …) would otherwise be emitted with a wrong wire amount.
102
+ * We only support USD/USDC today; extend deliberately (and fix the exponent)
103
+ * before adding any non-2-decimal currency.
104
+ *
105
+ * NOTE (scanner FP pre-empt): this is a CLIENT-SIDE currency-exponent lookup for
106
+ * rendering a wire amount in @visa/checkout-engine — it is NOT the cross-store
107
+ * `PAYMENT_CURRENCIES` enum governed by apps/auth/src/shared-validators.ts, and
108
+ * this package cannot import from apps/auth (no dependency edge). It intentionally
109
+ * does not mirror that enum's membership; do not "reconcile" the two.
110
+ */
111
+ export declare const TWO_DECIMAL_CURRENCIES: Set<string>;
112
+ /**
113
+ * Inverse of decimalToMinor: render integer minor units as a major-unit decimal
114
+ * string ("D.DD") for the VGS wire (e.g. a ceiling of 50000 minor → "500.00").
115
+ * Integer-only; never floating-point money. Throws on a non-integer/negative so
116
+ * a bad accounting value cannot silently reach the network.
117
+ *
118
+ * The /100 + pad-to-2 rendering assumes a 2-decimal (exponent-2) currency. Pass
119
+ * `currencyCode` on any path that accepts arbitrary currencies (the mandate
120
+ * path) and it REFUSES a non-2-decimal currency rather than emit a wrong wire
121
+ * amount. Omit it only where the currency is already known to be USD/USDC.
122
+ */
123
+ export declare function minorToDecimal(minor: number, currencyCode?: string): string;
86
124
  /**
87
125
  * Refuse to mint an intent unless the assurance is fresh and its declared
88
126
  * scope matches the checkout target exactly. `now` is injectable so the
@@ -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' ||
@@ -68,7 +106,10 @@ export function validatePurchaseAssurance(value, target, now = new Date()) {
68
106
  if (value == null || typeof value !== 'object') {
69
107
  throw new Error(`purchase assurance is missing — ${remedy}`);
70
108
  }
71
- if (value.assuranceData == null) {
109
+ // A passkey-exempt approval (marked by the approval SERVER, never assumed
110
+ // locally) carries no assurance by design — every scope/freshness check
111
+ // below still applies to it unchanged.
112
+ if (value.assuranceData == null && value.assuranceExempt !== true) {
72
113
  throw new Error(`purchase assurance requires assuranceData — ${remedy}`);
73
114
  }
74
115
  const mintedAtMs = typeof value.mintedAt === 'string' ? Date.parse(value.mintedAt) : NaN;
@@ -125,13 +166,14 @@ export function validateCredential(value, now = new Date()) {
125
166
  (value.expYear === now.getFullYear() && value.expMonth < now.getMonth() + 1)) {
126
167
  throw new Error('VGS credential is expired');
127
168
  }
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
- }
169
+ if (value.cryptogramExpiresAt === undefined) {
170
+ throw new Error('VGS credential expiry is missing');
171
+ }
172
+ const expiresAtMs = Date.parse(value.cryptogramExpiresAt);
173
+ if (!Number.isFinite(expiresAtMs))
174
+ throw new Error('VGS credential expiry is invalid');
175
+ if (expiresAtMs - now.getTime() < 60_000) {
176
+ throw new Error('VGS credential has less than 60 seconds of validity remaining');
135
177
  }
136
178
  }
137
179
  /**
@@ -188,6 +230,7 @@ export class VgsLiveInstrument {
188
230
  cvc: value.cryptogramValue,
189
231
  cardholderName: this.cardholderName.trim(),
190
232
  ...(value.cryptogramExpiresAt ? { credentialExpiresAt: value.cryptogramExpiresAt } : {}),
233
+ ...traceHandleFields(value),
191
234
  };
192
235
  }
193
236
  }
@@ -247,6 +290,7 @@ export class VgsAssuranceInstrument {
247
290
  cvc: value.cryptogramValue,
248
291
  cardholderName: this.cardholderName.trim(),
249
292
  ...(value.cryptogramExpiresAt ? { credentialExpiresAt: value.cryptogramExpiresAt } : {}),
293
+ ...traceHandleFields(value),
250
294
  };
251
295
  }
252
296
  }
@@ -32,8 +32,8 @@ export async function reportVicOutcome(input) {
32
32
  catch (err) {
33
33
  return {
34
34
  posted: false,
35
- reason: `confirmation POST failed: ${err.message} — the merchant outcome stands; ` +
36
- 'retry the confirmation for this intent out-of-band',
35
+ reason: `confirmation POST failed: ${err.message} — the merchant-reported outcome ` +
36
+ 'remains unverified; retry the confirmation for this intent out-of-band',
37
37
  };
38
38
  }
39
39
  }