@visa/cli 4.1.0-rc.8 → 4.1.0-rc.80

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 (70) hide show
  1. package/README.md +178 -231
  2. package/dist/checkout-engine/adapters/generic.d.ts +23 -0
  3. package/dist/checkout-engine/adapters/generic.js +216 -0
  4. package/dist/checkout-engine/adapters/index.d.ts +8 -0
  5. package/dist/checkout-engine/adapters/index.js +21 -0
  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/adapters/stripe-like.d.ts +10 -0
  9. package/dist/checkout-engine/adapters/stripe-like.js +21 -0
  10. package/dist/checkout-engine/amount.d.ts +15 -0
  11. package/dist/checkout-engine/amount.js +72 -0
  12. package/dist/checkout-engine/browser-launch.d.ts +46 -0
  13. package/dist/checkout-engine/browser-launch.js +81 -0
  14. package/dist/checkout-engine/ceremony.d.ts +64 -0
  15. package/dist/checkout-engine/ceremony.js +261 -0
  16. package/dist/checkout-engine/cli-engine.d.ts +214 -0
  17. package/dist/checkout-engine/cli-engine.js +701 -0
  18. package/dist/checkout-engine/detect.d.ts +61 -0
  19. package/dist/checkout-engine/detect.js +398 -0
  20. package/dist/checkout-engine/evidence.d.ts +25 -0
  21. package/dist/checkout-engine/evidence.js +104 -0
  22. package/dist/checkout-engine/executor.d.ts +176 -0
  23. package/dist/checkout-engine/executor.js +1322 -0
  24. package/dist/checkout-engine/hosted-approval.d.ts +142 -0
  25. package/dist/checkout-engine/hosted-approval.js +339 -0
  26. package/dist/checkout-engine/index.d.ts +6 -0
  27. package/dist/checkout-engine/index.js +8 -0
  28. package/dist/checkout-engine/inline-target.d.ts +13 -0
  29. package/dist/checkout-engine/inline-target.js +37 -0
  30. package/dist/checkout-engine/instrument.d.ts +61 -0
  31. package/dist/checkout-engine/instrument.js +87 -0
  32. package/dist/checkout-engine/live-fill-approval.d.ts +43 -0
  33. package/dist/checkout-engine/live-fill-approval.js +90 -0
  34. package/dist/checkout-engine/mandate/card-mandate.d.ts +121 -0
  35. package/dist/checkout-engine/mandate/card-mandate.js +227 -0
  36. package/dist/checkout-engine/mandate/mandate-ledger.d.ts +142 -0
  37. package/dist/checkout-engine/mandate/mandate-ledger.js +338 -0
  38. package/dist/checkout-engine/mandate.d.ts +25 -0
  39. package/dist/checkout-engine/mandate.js +100 -0
  40. package/dist/checkout-engine/outcome.d.ts +30 -0
  41. package/dist/checkout-engine/outcome.js +225 -0
  42. package/dist/checkout-engine/owner-only-file.d.ts +19 -0
  43. package/dist/checkout-engine/owner-only-file.js +41 -0
  44. package/dist/checkout-engine/package.json +3 -0
  45. package/dist/checkout-engine/receipt.d.ts +81 -0
  46. package/dist/checkout-engine/receipt.js +109 -0
  47. package/dist/checkout-engine/repo-env.d.ts +11 -0
  48. package/dist/checkout-engine/repo-env.js +23 -0
  49. package/dist/checkout-engine/trace-handles.d.ts +8 -0
  50. package/dist/checkout-engine/trace-handles.js +12 -0
  51. package/dist/checkout-engine/types.d.ts +44 -0
  52. package/dist/checkout-engine/types.js +2 -0
  53. package/dist/checkout-engine/vgs-gateway/fetch-credential.d.mts +74 -0
  54. package/dist/checkout-engine/vgs-gateway/fetch-credential.mjs +248 -0
  55. package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +82 -0
  56. package/dist/checkout-engine/vgs-gateway/server-mint-client.js +180 -0
  57. package/dist/checkout-engine/vgs-live-instrument.d.ts +170 -0
  58. package/dist/checkout-engine/vgs-live-instrument.js +293 -0
  59. package/dist/checkout-engine/vic-confirmation.d.ts +34 -0
  60. package/dist/checkout-engine/vic-confirmation.js +39 -0
  61. package/dist/cli.js +442 -433
  62. package/dist/mcp-server/index.js +360 -170
  63. package/dist/skills/pair-visa-agent/RUNTIMES.md +92 -0
  64. package/dist/skills/pair-visa-agent/SKILL.md +447 -0
  65. package/dist/skills/pair-visa-agent/scripts/setup.mjs +48 -0
  66. package/install.ps1 +3 -41
  67. package/install.sh +3 -35
  68. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  69. package/package.json +16 -12
  70. package/server.json +3 -3
@@ -0,0 +1,248 @@
1
+ // ⚠️ RETIRED CLIENT-SECRET PATH — used ONLY by the local `pnpm fill:live` spike
2
+ // (run-live-fill.ts) and the older pay.ts dev entrypoints, NOT by the shipped
3
+ // pay_merchant CLI. The productionized CLI (cli-engine.ts) mints SERVER-SIDE via
4
+ // a scoped mint token (vgs-gateway/server-mint-client.ts) and never holds
5
+ // VGS_USERNAME/VGS_PASSWORD. This module (and its spike callers) are slated for
6
+ // deletion in the Phase-1 follow-up; do NOT add new callers. The
7
+ // no-client-vgs-secret gate keeps the shipped path clear of everything below.
8
+ //
9
+ // Real credential fetch — NO mocks. Calls the live VGS agentic gateway to mint a
10
+ // fresh, intent-scoped payment credential (DPAN + expiry + the 3-digit DAVV) and
11
+ // returns it in memory. Same VGS agentic wire calls as enrollment; this just
12
+ // returns the FULL values (for the form-filler) instead of masking.
13
+ //
14
+ // Nothing here persists or logs the credential — it is returned to the caller
15
+ // (fillCheckout), and must never be written to disk or passed through an
16
+ // LLM/agent context.
17
+ //
18
+ // Requires env: VGS_USERNAME, VGS_PASSWORD (the VGS service-account client id/secret),
19
+ // and either VGS_ENVIRONMENT=live (+ optional VGS_GATEWAY_URL) or sandbox.
20
+
21
+ const TOKEN_URL = 'https://auth.verygoodsecurity.com/auth/realms/vgs/protocol/openid-connect/token'
22
+
23
+ function gatewayBase(env = process.env) {
24
+ if (env.VGS_GATEWAY_URL) return env.VGS_GATEWAY_URL.replace(/\/$/, '')
25
+ return env.VGS_ENVIRONMENT === 'live'
26
+ ? 'https://gw-01-live.vgsapi.com'
27
+ : 'https://gw-01-sandbox.vgsapi.com'
28
+ }
29
+
30
+ async function mintOauthToken(env = process.env) {
31
+ const clientId = env.VGS_USERNAME
32
+ const clientSecret = env.VGS_PASSWORD
33
+ if (!clientId || !clientSecret) {
34
+ throw new Error('Set VGS_USERNAME and VGS_PASSWORD (the VGS service-account client id/secret).')
35
+ }
36
+ const body = new URLSearchParams({
37
+ client_id: clientId,
38
+ client_secret: clientSecret,
39
+ grant_type: 'client_credentials',
40
+ })
41
+ const r = await fetch(TOKEN_URL, {
42
+ method: 'POST',
43
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
44
+ body,
45
+ })
46
+ if (!r.ok) throw new Error(`VGS token grant failed (${r.status}).`)
47
+ return (await r.json()).access_token
48
+ }
49
+
50
+ async function postJsonApi(url, type, attributes, env = process.env) {
51
+ const token = await mintOauthToken(env)
52
+ const r = await fetch(url, {
53
+ method: 'POST',
54
+ headers: {
55
+ Authorization: `Bearer ${token}`,
56
+ 'Content-Type': 'application/vnd.api+json',
57
+ },
58
+ body: JSON.stringify({ data: { ...(type ? { type } : {}), attributes } }),
59
+ })
60
+ const text = await r.text()
61
+ let doc = {}
62
+ try {
63
+ doc = JSON.parse(text)
64
+ } catch {
65
+ /* non-json error body */
66
+ }
67
+ // Support trace handles VGS asked for on the #5713 decline thread: trace_id
68
+ // keys the request on VGS's side, network_correlation_id on the Visa network
69
+ // side. Routing metadata only — never credential material — and logged even
70
+ // on error responses so any run stays traceable after the fact.
71
+ const obs = doc?.meta?.observability
72
+ if (obs && typeof obs === 'object') {
73
+ console.info(
74
+ JSON.stringify({
75
+ op: 'vgs_observability',
76
+ type,
77
+ status: r.status,
78
+ trace_id: obs.trace_id,
79
+ vault_id: obs.vault_id,
80
+ network_correlation_id: obs.network_correlation_id,
81
+ })
82
+ )
83
+ }
84
+ if (!r.ok) {
85
+ // Never echo the full body (can carry ids); surface status + a short detail.
86
+ const detail = doc?.errors?.[0]?.detail || doc?.errors?.[0]?.title || ''
87
+ throw new Error(`VGS ${type} POST failed (${r.status})${detail ? `: ${detail}` : ''}.`)
88
+ }
89
+ return doc
90
+ }
91
+
92
+ const txnData = (t) => [
93
+ {
94
+ merchant_name: t.merchantName,
95
+ merchant_url: t.merchantUrl,
96
+ merchant_country_code: t.merchantCountryCode,
97
+ transaction_amount: {
98
+ transaction_amount: t.transactionAmount,
99
+ transaction_currency_code: t.transactionCurrencyCode,
100
+ },
101
+ },
102
+ ]
103
+
104
+ /**
105
+ * Create a fresh intent scoped to `transaction`, bound to the passkey assurance.
106
+ * Needs `assuranceData` from a device-binding passkey ceremony run for THIS
107
+ * purchase (merchant + amount + currency aligned) — replaying enrollment-time
108
+ * assurance mints an intent that 201s but whose cryptogram never completes
109
+ * (#5709, confirmed live 2026-07-17).
110
+ * @returns {Promise<{intentId: string, status: string | null}>} the fresh
111
+ * intent id plus the creation-time status attribute (null when VGS omits it) —
112
+ * callers surface the status when a later cryptogram fails, since HTTP 201
113
+ * alone does not mean the intent is authorized.
114
+ */
115
+ export async function createIntent({ tokenId, assuranceData, transaction }, env = process.env) {
116
+ const effectiveUntil = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString()
117
+ const cap = Math.max(Math.ceil(Number(transaction.transactionAmount) || 0) + 10, 25)
118
+ const doc = await postJsonApi(
119
+ `${gatewayBase(env)}/agentic-tokens/${encodeURIComponent(tokenId)}/intents`,
120
+ 'intents',
121
+ {
122
+ consumer_prompt: `Buy an item from ${transaction.merchantName} for ${transaction.transactionCurrencyCode} ${transaction.transactionAmount}`,
123
+ assurance_data: assuranceData,
124
+ mandates: [
125
+ {
126
+ description: `Purchase at ${transaction.merchantName}`,
127
+ decline_threshold: { amount: cap, currency_code: transaction.transactionCurrencyCode },
128
+ effective_until: effectiveUntil,
129
+ merchant_category: 'Retail',
130
+ merchant_category_code: '5999',
131
+ preferred_merchant_name: transaction.merchantName,
132
+ quantity: 1,
133
+ },
134
+ ],
135
+ },
136
+ env
137
+ )
138
+ const intentId = doc.data?.id
139
+ if (!intentId) throw new Error('createIntent: response missing data.id')
140
+ const status = doc.data?.attributes?.status
141
+ return { intentId, status: typeof status === 'string' && status ? status : null }
142
+ }
143
+
144
+ /**
145
+ * Mint the FULL payment credential for an existing intent. Real VGS call — the
146
+ * DAVV is single-use and expires in hours, so call this immediately before fill.
147
+ * @returns {Promise<{networkToken,expMonth,expYear,cryptogramType,cryptogramValue}>}
148
+ */
149
+ export async function fetchCryptogram({ tokenId, intentId, transaction }, env = process.env) {
150
+ // Intent approval can be asynchronous on live: creation returns PENDING and
151
+ // the first cryptogram answer can be PENDING too (observed 2026-07-17,
152
+ // donate.stripe.com run). Poll briefly on PENDING only — every other
153
+ // non-COMPLETED status still fails fast on the first answer. Both knobs are
154
+ // env-tunable (and injectable for tests, which must not sleep wall-clock).
155
+ const PENDING_ATTEMPTS = Math.max(1, Number(env.VGS_CRYPTOGRAM_PENDING_ATTEMPTS) || 4)
156
+ const PENDING_WAIT_MS = Number.isFinite(Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS))
157
+ ? Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS)
158
+ : 5000
159
+ let a = {}
160
+ for (let attempt = 1; ; attempt++) {
161
+ const doc = await postJsonApi(
162
+ `${gatewayBase(env)}/agentic-tokens/${encodeURIComponent(tokenId)}/intents/${encodeURIComponent(intentId)}/cryptograms`,
163
+ 'cryptograms',
164
+ { transaction_data: txnData(transaction) },
165
+ env
166
+ )
167
+ a = doc.data?.attributes ?? {}
168
+ const s = typeof a.status === 'string' ? a.status.toUpperCase() : ''
169
+ if (s !== 'PENDING' || attempt >= PENDING_ATTEMPTS) break
170
+ console.info(
171
+ JSON.stringify({ op: 'cryptogram_pending_retry', attempt, waitMs: PENDING_WAIT_MS })
172
+ )
173
+ await new Promise((resolve) => setTimeout(resolve, PENDING_WAIT_MS))
174
+ }
175
+ // A network_token can come back while the cryptogram is still pending/failed —
176
+ // mirror lib/server/vgs.ts and reject anything not COMPLETED, so we never key a
177
+ // not-yet-valid credential (which would decline and read as a fill bug).
178
+ const status = a.status
179
+ if (typeof status === 'string' && status && status.toUpperCase() !== 'COMPLETED') {
180
+ throw new Error(`cryptogram not completed (status ${status})`)
181
+ }
182
+ const networkToken = a.network_token
183
+ const value = a.cryptogram?.value
184
+ if (typeof networkToken !== 'string' || !networkToken) {
185
+ throw new Error('cryptogram response missing network_token')
186
+ }
187
+ if (typeof value !== 'string' || !value) {
188
+ throw new Error('cryptogram response missing cryptogram value')
189
+ }
190
+ return {
191
+ networkToken,
192
+ expMonth: typeof a.exp_month === 'number' ? a.exp_month : Number(a.exp_month) || 0,
193
+ expYear: typeof a.exp_year === 'number' ? a.exp_year : Number(a.exp_year) || 0,
194
+ cryptogramType: a.cryptogram?.type ?? '',
195
+ cryptogramValue: value,
196
+ cryptogramExpiresAt:
197
+ typeof a.cryptogram?.expires_at === 'string' ? a.cryptogram.expires_at : undefined,
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Full path: create the intent (needs fresh passkey assurance) then mint the
203
+ * credential. Use fetchCryptogram directly if you already have an intentId.
204
+ */
205
+ export async function getCredential({ tokenId, assuranceData, transaction }, env = process.env) {
206
+ const { intentId, status } = await createIntent({ tokenId, assuranceData, transaction }, env)
207
+ try {
208
+ return await fetchCryptogram({ tokenId, intentId, transaction }, env)
209
+ } catch (err) {
210
+ // HTTP 201 on intent creation does not mean the intent was authorized —
211
+ // surface its creation-time status so a not-completed cryptogram is
212
+ // diagnosable (#5709) instead of an opaque failure.
213
+ throw new Error(`${err.message} (intent status at creation: ${status ?? 'unknown'})`)
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Report the observed merchant outcome back to VIC for a consumed intent.
219
+ * Mirrors lib/server/vgs.ts postConfirmation exactly: same endpoint, same
220
+ * JSON:API envelope, and the guide's quoted Unix-epoch-seconds timestamp
221
+ * (callers pass ISO 8601; converted here).
222
+ */
223
+ export async function postConfirmation(
224
+ { tokenId, intentId, transactionStatus, transactionType, transactionTimestamp, transaction },
225
+ env = process.env
226
+ ) {
227
+ await postJsonApi(
228
+ `${gatewayBase(env)}/agentic-tokens/${encodeURIComponent(tokenId)}/intents/${encodeURIComponent(intentId)}/confirmations`,
229
+ 'confirmations',
230
+ {
231
+ confirmation_data: [
232
+ {
233
+ payment_confirmation_data: {
234
+ transaction_status: transactionStatus,
235
+ transaction_type: transactionType,
236
+ transaction_timestamp: String(Math.floor(Date.parse(transactionTimestamp) / 1000)),
237
+ transaction_amount: {
238
+ transaction_amount: transaction.transactionAmount,
239
+ transaction_currency_code: transaction.transactionCurrencyCode,
240
+ },
241
+ },
242
+ },
243
+ ],
244
+ },
245
+ env
246
+ )
247
+ return { ok: true }
248
+ }
@@ -0,0 +1,82 @@
1
+ import type { VgsCheckoutTarget, VgsPaymentCredential } from '../vgs-live-instrument.js';
2
+ export type ServerMintDeps = {
3
+ /** Injectable for tests — defaults to global fetch. */
4
+ fetchImpl?: typeof fetch;
5
+ /** Injectable for tests — never wall-clock-sleep in a unit test. */
6
+ sleep?: (ms: number) => Promise<void>;
7
+ env?: NodeJS.ProcessEnv;
8
+ };
9
+ /**
10
+ * The merchant ORIGIN (scheme + host) — not the full checkout URL. A merchant's
11
+ * identity is its origin; a real checkout URL can carry hundreds of chars of
12
+ * campaign/tracking query params. Confirmed live: an oversized `merchantUrl`
13
+ * (a ~280-char Wikimedia donation URL) makes the cryptogram mint fail downstream
14
+ * with a vague `502 "card network could not complete"`, while the same merchant
15
+ * with a trimmed URL mints fine. Sending the origin is both correct (that IS the
16
+ * merchant) and safely bounded. Falls back to the raw value if it does not parse
17
+ * — the mint must never throw here.
18
+ */
19
+ export declare function merchantOrigin(url: string): string;
20
+ /**
21
+ * Optional mandate override for serverCreateIntent. Absent → the historical
22
+ * 1:1 fresh-tap shape is preserved byte-for-byte (cap = ceil(amount)+10 min 25,
23
+ * quantity 1, 30-day window). Present → the card-mandate (budget) layer sets a
24
+ * CEILING decline threshold and a multi-draw quantity so one passkey approves a
25
+ * spend ceiling and later draws pull cryptograms under it without a fresh tap.
26
+ * Whether the network honors a ceiling-scoped assurance across multiple
27
+ * sub-amount draws is UNPROVEN — see packages/checkout-engine/src/mandate/.
28
+ */
29
+ export type ServerIntentMandateOverride = {
30
+ /** Wire decline-threshold amount (major-unit decimal string), e.g. "500.00". */
31
+ declineThresholdAmount?: string;
32
+ /** Number of draws the intent may fulfil (VGS mandate `quantity`). */
33
+ quantity?: number;
34
+ /** ISO 8601 mandate validity end. */
35
+ effectiveUntil?: string;
36
+ /** Human-readable consumer prompt describing the ceiling grant. */
37
+ consumerPrompt?: string;
38
+ };
39
+ /**
40
+ * Create a fresh intent via POST {base}/api/vgs/intent. The server holds the VGS
41
+ * credential and calls the gateway; we send the same mandate shape the local
42
+ * path built (cap = ceil(amount)+10, min 25; merchant category Retail/5999) —
43
+ * unless `input.mandate` overrides the threshold/quantity/window for the
44
+ * card-mandate (budget) layer.
45
+ */
46
+ export declare function serverCreateIntent(base: string, mintToken: string, input: {
47
+ tokenId: string;
48
+ assuranceData: unknown;
49
+ transaction: VgsCheckoutTarget;
50
+ mandate?: ServerIntentMandateOverride;
51
+ }, deps?: ServerMintDeps): Promise<{
52
+ intentId: string;
53
+ status: string | null;
54
+ }>;
55
+ /**
56
+ * Mint the FULL payment credential via POST {base}/api/vgs/payment-cryptogram.
57
+ * The server's route does a SINGLE gateway call and 502s on a not-COMPLETED
58
+ * (e.g. PENDING) cryptogram, but live intent approval is asynchronous and the
59
+ * first cryptogram answer can be PENDING (#5709). So we retry the route on any
60
+ * non-2xx up to PENDING_ATTEMPTS, matching fetch-credential.mjs's cadence
61
+ * exactly — a genuinely hard failure just surfaces after the same bounded wait.
62
+ * Re-POSTing for the same intentId is idempotent (mirrors the old client loop).
63
+ */
64
+ export declare function serverFetchCryptogram(base: string, mintToken: string, input: {
65
+ tokenId: string;
66
+ intentId: string;
67
+ transaction: VgsCheckoutTarget;
68
+ }, deps?: ServerMintDeps): Promise<VgsPaymentCredential>;
69
+ /** Report the observed merchant outcome via POST {base}/api/vgs/confirmation. */
70
+ export declare function serverPostConfirmation(base: string, mintToken: string, input: {
71
+ tokenId: string;
72
+ intentId: string;
73
+ transactionStatus: string;
74
+ transactionType: string;
75
+ transactionTimestamp: string;
76
+ transaction: {
77
+ transactionAmount: string;
78
+ transactionCurrencyCode: string;
79
+ };
80
+ }, deps?: ServerMintDeps): Promise<{
81
+ ok: true;
82
+ }>;
@@ -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
+ }
@@ -0,0 +1,170 @@
1
+ import type { CardCredential, Instrument, InstrumentContext } from './instrument.js';
2
+ export type VgsCheckoutReference = {
3
+ tokenId: string;
4
+ intentId: string;
5
+ merchantName: string;
6
+ merchantUrl: string;
7
+ merchantCountryCode: string;
8
+ transactionAmount: string;
9
+ transactionCurrencyCode: string;
10
+ };
11
+ export type VgsCheckoutTarget = Omit<VgsCheckoutReference, 'tokenId' | 'intentId'>;
12
+ export type CliAgentCredential = {
13
+ tokenId: string;
14
+ /** Present only in artifacts claimed by older CLI versions — never read
15
+ * here: enrollment-time assurance is not purchase authorization (#5709),
16
+ * and current CLIs no longer persist it at all. */
17
+ assuranceData?: unknown;
18
+ name?: string;
19
+ agentJkt?: string;
20
+ claimedAt?: string;
21
+ source?: string;
22
+ };
23
+ /**
24
+ * Fresh, purchase-scoped assurance from a device-binding passkey ceremony run
25
+ * for THIS purchase. Issue #5709 (confirmed live 2026-07-17): VGS accepts an
26
+ * intent minted from the enrollment-time assurance — and even from a fresh
27
+ * assurance scoped to a DIFFERENT merchant — but the cryptogram then
28
+ * deterministically never completes. Only a ceremony scoped to the actual
29
+ * merchant + amount + currency yields a payable credential, so the declared
30
+ * scope here is validated against the checkout target before any intent is
31
+ * minted, and the enrollment artifact's stored assurance is never used as
32
+ * purchase authorization.
33
+ */
34
+ export type PurchaseAssurance = {
35
+ /** Opaque VgsAgenticAuth output — never inspected, only forwarded. */
36
+ assuranceData: unknown;
37
+ /** ISO 8601 completion time of the ceremony this assurance came from. */
38
+ mintedAt: string;
39
+ /** Host of the merchant checkout URL the ceremony was scoped to. */
40
+ merchantHost: string;
41
+ /** Decimal major-unit amount the ceremony was scoped to. */
42
+ transactionAmount: string;
43
+ /** ISO 4217 currency the ceremony was scoped to. */
44
+ transactionCurrencyCode: string;
45
+ };
46
+ /**
47
+ * Our fail-closed freshness bound, matching the runner's 15-minute checkout
48
+ * review window — NOT a claim about VGS's actual assurance TTL (unpublished).
49
+ * The only proven-working configuration mints the intent right after the
50
+ * ceremony; anything older is refused before an intent is created.
51
+ */
52
+ export declare const PURCHASE_ASSURANCE_MAX_AGE_MS: number;
53
+ export type VgsPaymentCredential = {
54
+ networkToken: string;
55
+ expMonth: number;
56
+ expYear: number;
57
+ cryptogramType: string;
58
+ cryptogramValue: string;
59
+ cryptogramExpiresAt?: string;
60
+ vgsTraceId?: string;
61
+ networkCorrelationId?: string;
62
+ };
63
+ export type FetchVgsPaymentCredential = (input: {
64
+ tokenId: string;
65
+ intentId: string;
66
+ transaction: {
67
+ merchantName: string;
68
+ merchantUrl: string;
69
+ merchantCountryCode: string;
70
+ transactionAmount: string;
71
+ transactionCurrencyCode: string;
72
+ };
73
+ }) => Promise<VgsPaymentCredential>;
74
+ export type MintFreshVgsPaymentCredential = (input: {
75
+ tokenId: string;
76
+ assuranceData: unknown;
77
+ transaction: VgsCheckoutTarget;
78
+ }) => Promise<{
79
+ payment: VgsPaymentCredential;
80
+ intentId: string;
81
+ }>;
82
+ /** The (token, intent) pair a VIC confirmation is posted against. */
83
+ export type VicConfirmationTarget = {
84
+ tokenId: string;
85
+ intentId: string;
86
+ };
87
+ export declare function decimalToMinor(value: unknown): number | null;
88
+ /**
89
+ * Currencies whose minor unit is 1/100 of the major unit (2 decimal places).
90
+ * minorToDecimal's /100 + pad-to-2 rendering is ONLY correct for these. The
91
+ * card mandate path accepts any 3-letter ISO code, so a 0- or 3-decimal
92
+ * currency (JPY, BHD, …) would otherwise be emitted with a wrong wire amount.
93
+ * We only support USD/USDC today; extend deliberately (and fix the exponent)
94
+ * before adding any non-2-decimal currency.
95
+ *
96
+ * NOTE (scanner FP pre-empt): this is a CLIENT-SIDE currency-exponent lookup for
97
+ * rendering a wire amount in @visa/checkout-engine — it is NOT the cross-store
98
+ * `PAYMENT_CURRENCIES` enum governed by apps/auth/src/shared-validators.ts, and
99
+ * this package cannot import from apps/auth (no dependency edge). It intentionally
100
+ * does not mirror that enum's membership; do not "reconcile" the two.
101
+ */
102
+ export declare const TWO_DECIMAL_CURRENCIES: Set<string>;
103
+ /**
104
+ * Inverse of decimalToMinor: render integer minor units as a major-unit decimal
105
+ * string ("D.DD") for the VGS wire (e.g. a ceiling of 50000 minor → "500.00").
106
+ * Integer-only; never floating-point money. Throws on a non-integer/negative so
107
+ * a bad accounting value cannot silently reach the network.
108
+ *
109
+ * The /100 + pad-to-2 rendering assumes a 2-decimal (exponent-2) currency. Pass
110
+ * `currencyCode` on any path that accepts arbitrary currencies (the mandate
111
+ * path) and it REFUSES a non-2-decimal currency rather than emit a wrong wire
112
+ * amount. Omit it only where the currency is already known to be USD/USDC.
113
+ */
114
+ export declare function minorToDecimal(minor: number, currencyCode?: string): string;
115
+ /**
116
+ * Refuse to mint an intent unless the assurance is fresh and its declared
117
+ * scope matches the checkout target exactly. `now` is injectable so the
118
+ * freshness rules are testable with a pinned clock (same pattern as
119
+ * validateCredential).
120
+ */
121
+ export declare function validatePurchaseAssurance(value: PurchaseAssurance, target: VgsCheckoutTarget, now?: Date): void;
122
+ export declare function validateCredential(value: VgsPaymentCredential, now?: Date): void;
123
+ /**
124
+ * Mints the full DPAN + short DAVV only after the executor revalidates the
125
+ * reviewed merchant, amount, and currency. The payment credential remains in
126
+ * memory, is never returned to the caller, and can be requested only once.
127
+ */
128
+ export declare class VgsLiveInstrument implements Instrument {
129
+ private readonly reference;
130
+ private readonly cardholderName;
131
+ private readonly fetchCredential;
132
+ readonly kind: "agentic-token";
133
+ private used;
134
+ private minted;
135
+ constructor(reference: VgsCheckoutReference, cardholderName: string, fetchCredential: FetchVgsPaymentCredential);
136
+ /**
137
+ * Non-null once VGS has actually issued a credential (the intent is consumed
138
+ * from that moment, even if local validation later rejects the credential) —
139
+ * exactly the population a VIC confirmation can be owed for.
140
+ */
141
+ confirmationTarget(): VicConfirmationTarget | null;
142
+ getCredential(ctx: InstrumentContext): Promise<CardCredential>;
143
+ }
144
+ /**
145
+ * Consumes #5614's claimed CLI enrollment artifact (for the tokenId) plus a
146
+ * FRESH purchase-scoped assurance, and creates a fresh, transaction-scoped VIC
147
+ * intent + credential after checkout approval. This is the production-shaped
148
+ * bridge; unlike VgsLiveInstrument it never needs a pre-created intent ID.
149
+ *
150
+ * The enrollment artifact's stored assuranceData is deliberately never sent:
151
+ * replaying it makes intent creation succeed (HTTP 201) while the cryptogram
152
+ * deterministically never completes — the #5709 dead end. Purchase
153
+ * authorization is the fresh, merchant+amount+currency-scoped assurance,
154
+ * validated against the checkout target BEFORE any intent is minted so a
155
+ * doomed intent is never created.
156
+ */
157
+ export declare class VgsAssuranceInstrument implements Instrument {
158
+ private readonly enrollment;
159
+ private readonly purchase;
160
+ private readonly target;
161
+ private readonly cardholderName;
162
+ private readonly mintCredential;
163
+ readonly kind: "agentic-token";
164
+ private used;
165
+ private minted;
166
+ constructor(enrollment: CliAgentCredential, purchase: PurchaseAssurance, target: VgsCheckoutTarget, cardholderName: string, mintCredential: MintFreshVgsPaymentCredential);
167
+ /** See VgsLiveInstrument.confirmationTarget — same contract. */
168
+ confirmationTarget(): VicConfirmationTarget | null;
169
+ getCredential(ctx: InstrumentContext): Promise<CardCredential>;
170
+ }