@visa/cli 4.1.0-rc.9 → 4.1.0-rc.91

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 +227 -0
  17. package/dist/checkout-engine/cli-engine.js +779 -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 +187 -0
  25. package/dist/checkout-engine/hosted-approval.js +478 -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 +179 -0
  58. package/dist/checkout-engine/vgs-live-instrument.js +296 -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 +448 -433
  62. package/dist/mcp-server/index.js +366 -170
  63. package/dist/skills/pair-visa-agent/RUNTIMES.md +92 -0
  64. package/dist/skills/pair-visa-agent/SKILL.md +468 -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,779 @@
1
+ // createCliCheckoutEngine — the review()/pay() adapter consumed by @visa/cli's
2
+ // pay_merchant tool. It COMPOSES prepareCheckout, runHostedApproval, the
3
+ // server-side mint (serverCreateIntent/serverFetchCryptogram — the credential is
4
+ // minted by the verify-web deployment, not this machine), submitApprovedCheckout,
5
+ // reportVicOutcome, and receipts into a two-call API.
6
+ //
7
+ // A live browser + prepared-checkout session is held in-process between review
8
+ // and pay, keyed by reviewId, so the submitted checkout is the exact one the
9
+ // human approved. Passkey approval uses the hosted /approve page only.
10
+ //
11
+ // Every browser/network primitive is injectable (CliEngineDeps) so the session/
12
+ // timer/store lifecycle is unit-testable without launching Chromium.
13
+ import { homedir } from 'node:os';
14
+ import { join } from 'node:path';
15
+ import { readFile } from 'node:fs/promises';
16
+ import { launchCheckoutBrowser } from './browser-launch.js';
17
+ import { prepareCheckout as realPrepareCheckout, submitApprovedCheckout as realSubmitApprovedCheckout, InMemoryPreparedCheckoutStore, } from './executor.js';
18
+ import { claimMandatePickup as realClaimMandatePickup, runHostedApproval as realRunHostedApproval, } from './hosted-approval.js';
19
+ import { VgsAssuranceInstrument, VgsLiveInstrument, decimalToMinor, } from './vgs-live-instrument.js';
20
+ import { serverCreateIntent, serverFetchCryptogram, serverPostConfirmation, } from './vgs-gateway/server-mint-client.js';
21
+ import { createCardMandate, DEFAULT_MANDATE_MAX_DRAWS, drawFromMandate, MandateDrawDeclinedError, } from './mandate/card-mandate.js';
22
+ import { MandateLedger } from './mandate/mandate-ledger.js';
23
+ import { buildReceipt, writeReceipt as realWriteReceipt } from './receipt.js';
24
+ import { reportVicOutcome as realReportVicOutcome, } from './vic-confirmation.js';
25
+ /**
26
+ * A card-mandate draw failed transiently (retryable) rather than definitively.
27
+ * Gateway 5xx, "server cryptogram not completed / try again", and network
28
+ * reset/timeout errors are transient: the mandate stays healthy and must NOT be
29
+ * disabled. Walks the error's cause chain so a wrapped MandateDrawDeclinedError
30
+ * is classified by its underlying gateway error. Exported for tests.
31
+ */
32
+ export function isTransientDrawFailure(err) {
33
+ const msgs = [];
34
+ let e = err;
35
+ for (let i = 0; i < 5 && e; i++) {
36
+ if (e instanceof Error && typeof e.message === 'string')
37
+ msgs.push(e.message);
38
+ e = e.cause;
39
+ }
40
+ // Transient = a gateway 5xx / 429 in the mint client's "(last: <status>: …)"
41
+ // framing, or an unambiguous network reset/timeout error name. The status is
42
+ // ANCHORED to `(last:` so a bare 3-digit token elsewhere (an amount, a ref id,
43
+ // an attempt count) can never be mistaken for a status code, and so the
44
+ // advisory DRAW_REMEDY wrapper text ("gateway 5xx / try again") cannot
45
+ // self-classify a hard decline as transient. A hard decline (4xx / a
46
+ // card-decline reason) matches nothing here → the mandate is correctly disabled.
47
+ return /\(last:\s*(?:5\d\d|429)\b|\bETIMEDOUT\b|\bECONNRESET\b|\bECONNREFUSED\b|\bEAI_AGAIN\b|socket hang up|tim(?:e|ed)[ -]?out/i.test(msgs.join(' '));
48
+ }
49
+ /**
50
+ * A verdict refusal may be wrapped by drawFromMandate after its local
51
+ * reservation is released. Walk the cause chain so the original auth status +
52
+ * reasons still decide whether the mandate is permanently disabled.
53
+ */
54
+ function classifyCardDrawVerdictFailure(err) {
55
+ const transientReasons = new Set(['challenge_failed', 'challenge_malformed', 'verdict_refused']);
56
+ let current = err;
57
+ for (let i = 0; i < 5 && current; i++) {
58
+ const candidate = current;
59
+ const status = typeof candidate.status === 'number' ? candidate.status : 0;
60
+ const reasons = Array.isArray(candidate.reasons)
61
+ ? candidate.reasons.filter((reason) => typeof reason === 'string')
62
+ : [];
63
+ if (status !== 0 || reasons.length > 0) {
64
+ return {
65
+ transient: status === 503 ||
66
+ reasons.length === 0 ||
67
+ reasons.every((reason) => transientReasons.has(reason)),
68
+ reasons,
69
+ };
70
+ }
71
+ current = candidate.cause;
72
+ }
73
+ return null;
74
+ }
75
+ /**
76
+ * Resolve the card instrument for one flow. Fail-closed: an unusable legacy file
77
+ * with no grant token rethrows (never silently proceeds), and the ONLY thing the
78
+ * fallback contributes is a token id — a non-secret handle the server
79
+ * re-authorizes against the owner (`requireTokenOwnership`) and against the live
80
+ * grant on every draw. Nothing here authorizes anything.
81
+ */
82
+ async function resolveCardInstrument(input) {
83
+ let credential = null;
84
+ let readError = null;
85
+ try {
86
+ credential = JSON.parse(await readFile(input.credentialPath, 'utf8'));
87
+ }
88
+ catch (err) {
89
+ readError = err;
90
+ }
91
+ if (credential && typeof credential.tokenId === 'string' && credential.tokenId.trim()) {
92
+ return credential;
93
+ }
94
+ if (typeof input.cardTokenId === 'string' && input.cardTokenId.trim()) {
95
+ return { tokenId: input.cardTokenId, source: 'card-grant' };
96
+ }
97
+ throw new Error('no card instrument is available to this runtime: there is no usable credential at ' +
98
+ `${input.credentialPath} and no activated card:vic grant token was supplied. Run ` +
99
+ '`visa agent grant-card <agent-id> --ceiling <usd> --per-transaction <usd> --wait` to ' +
100
+ 'attach one, or use a pre-provisioned VIC runtime.', readError instanceof Error ? { cause: readError } : undefined);
101
+ }
102
+ const RECEIPT_DIR = join(homedir(), '.visa-mcp', 'checkout-receipts');
103
+ // Must match the prepared-checkout store TTL so a session and its store entry
104
+ // expire together — an abandoned review can't leak the browser + state.
105
+ const PREPARED_TTL_MS = 5 * 60 * 1000;
106
+ const defaultStore = new InMemoryPreparedCheckoutStore({ ttlMs: PREPARED_TTL_MS });
107
+ const defaultSessions = new Map();
108
+ const defaultLedger = new MandateLedger();
109
+ export function createCliCheckoutEngine(deps = {}) {
110
+ const store = deps.store ?? defaultStore;
111
+ const sessions = deps.sessions ?? defaultSessions;
112
+ const ttlMs = deps.ttlMs ?? PREPARED_TTL_MS;
113
+ const launchBrowser = deps.launchBrowser ?? (() => launchCheckoutBrowser());
114
+ const prepareCheckout = deps.prepareCheckout ?? realPrepareCheckout;
115
+ const submitApprovedCheckout = deps.submitApprovedCheckout ?? realSubmitApprovedCheckout;
116
+ const runHostedApproval = deps.runHostedApproval ?? realRunHostedApproval;
117
+ const claimMandatePickup = deps.claimMandatePickup ?? realClaimMandatePickup;
118
+ const reportVicOutcome = deps.reportVicOutcome ?? realReportVicOutcome;
119
+ const writeReceipt = deps.writeReceipt ?? realWriteReceipt;
120
+ const ledger = deps.ledger ?? defaultLedger;
121
+ const now = deps.now ?? (() => new Date());
122
+ const fetchMandateCryptogram = deps.serverFetchCryptogram ?? serverFetchCryptogram;
123
+ const postServerConfirmation = deps.serverPostConfirmation ?? serverPostConfirmation;
124
+ const cardDrawVerdict = deps.cardDrawVerdict ?? null;
125
+ const cardMandateRegister = deps.cardMandateRegister ?? null;
126
+ async function closeSession(reviewId) {
127
+ const session = sessions.get(reviewId);
128
+ if (!session)
129
+ return;
130
+ clearTimeout(session.cleanupTimer);
131
+ sessions.delete(reviewId);
132
+ await session.browser.close().catch(() => { });
133
+ }
134
+ function buildTarget(input) {
135
+ return {
136
+ merchantName: input.merchantName ?? new URL(input.url).hostname,
137
+ merchantUrl: input.url,
138
+ merchantCountryCode: input.merchantCountryCode ?? 'US',
139
+ transactionAmount: input.amount,
140
+ transactionCurrencyCode: input.currency,
141
+ };
142
+ }
143
+ // Seed the one server-authoritative cumulative store keyed by the VGS intent
144
+ // ID (#5942). On failure the local record is marked register-failed so
145
+ // findCovering() SKIPS it — the mandate exists but is never drawn tap-free —
146
+ // and the caller reports the failure honestly. Shared by mandate-start and
147
+ // pickup-claim; both refuse before their ceremony/claim when no capability
148
+ // can register, so registerCap is always present here.
149
+ async function registerMandateOrDisable(args) {
150
+ if (!cardMandateRegister)
151
+ return { registerFailed: true, registerFailureReason: 'no_seam' };
152
+ const reg = await cardMandateRegister
153
+ .register({
154
+ authBaseUrl: args.registerCap.authBaseUrl,
155
+ agentKey: args.registerCap.agentKey,
156
+ mandateId: args.mandateId,
157
+ mintToken: args.mintToken,
158
+ ceiling: args.ceiling,
159
+ currency: args.currency,
160
+ })
161
+ .catch((err) => ({
162
+ ok: false,
163
+ reason: err instanceof Error ? err.message : String(err),
164
+ }));
165
+ if (reg.ok)
166
+ return { registerFailed: false };
167
+ // Register failed: the server `card_mandate_spend` row was never created, so
168
+ // a delegated draw against this mandate would 404 `no_mandate`. Mark it
169
+ // register-failed so findCovering() SKIPS it and the owner's next checkout
170
+ // falls through to a fresh per-purchase tap, rather than silently selecting
171
+ // a mandate that can't be drawn. Marking is best-effort too — a failure here
172
+ // must not abort the flow.
173
+ const marked = await ledger
174
+ .markRegisterFailed(args.mandateId, now())
175
+ .then(() => true)
176
+ .catch(() => false);
177
+ process.stderr.write(marked
178
+ ? `warning: card-mandate register failed (${reg.reason ?? 'unknown'}) — this mandate ` +
179
+ `will NOT be used for tap-free draws; your next checkout will use a fresh ` +
180
+ `per-purchase passkey tap. Re-run 'mandate start' to try again.\n`
181
+ : // Escalate: the mark write ALSO failed, so the mandate is persisted but
182
+ // NOT disabled — findCovering could still select an undrawable mandate.
183
+ // Tell the owner loudly not to rely on it and how to recover.
184
+ `warning: card-mandate register failed (${reg.reason ?? 'unknown'}) AND the mandate ` +
185
+ `could NOT be disabled locally — do not rely on it. Run 'mandate list' and re-run ` +
186
+ `'mandate start'. mandateId=${args.mandateId}\n`);
187
+ return {
188
+ registerFailed: true,
189
+ ...(reg.reason !== undefined ? { registerFailureReason: reg.reason } : {}),
190
+ };
191
+ }
192
+ return {
193
+ // BUDGET step: one passkey approves a CEILING; a VGS intent is minted with
194
+ // that ceiling as its decline threshold and the owner-only ledger records
195
+ // the cumulative budget. No browser checkout is prepared — this is purely
196
+ // the passkey ceremony + intent, so later pay() draws need no fresh tap.
197
+ async startCardMandate(input) {
198
+ const ceilingMinor = decimalToMinor(input.ceiling);
199
+ if (ceilingMinor === null || ceilingMinor <= 0) {
200
+ throw new Error(`invalid mandate ceiling ${JSON.stringify(input.ceiling)}`);
201
+ }
202
+ if (input.currency.toUpperCase() !== 'USD') {
203
+ throw new Error('card spend budgets currently support USD only');
204
+ }
205
+ if (input.perTransaction !== undefined) {
206
+ const perTxMinor = decimalToMinor(input.perTransaction);
207
+ if (perTxMinor === null || perTxMinor <= 0 || perTxMinor > ceilingMinor) {
208
+ throw new Error(`invalid mandate perTransaction ${JSON.stringify(input.perTransaction)} — ` +
209
+ 'must be a positive amount at or under the ceiling');
210
+ }
211
+ }
212
+ // A budget token can bootstrap one VGS intent and its register handshake,
213
+ // but it is never payable draw authority. Refuse before the passkey
214
+ // ceremony unless this runtime can both prove the separately provisioned
215
+ // card capability and register the resulting intent server-side.
216
+ const registerCap = cardMandateRegister?.loadCapability(input.agentRef) ?? null;
217
+ if (!cardMandateRegister || !registerCap) {
218
+ throw new Error('startCardMandate requires separately provisioned card authority in this runtime; ' +
219
+ 'identity pairing alone does not grant a card mandate');
220
+ }
221
+ // There is one budget product: eligible retail merchants under the
222
+ // provider's required Retail/5999 network category, with total,
223
+ // per-purchase, count, and time bounds stated on the approval page. The
224
+ // sentinel is provider metadata, never a user-entered merchant route.
225
+ const merchant = {
226
+ name: 'retail spend budget',
227
+ url: 'https://retail-budget.visa/budget',
228
+ countryCode: 'US',
229
+ };
230
+ // Legacy credential file OR the activated card:vic grant's token — see
231
+ // resolveCardInstrument. A v2-paired runtime only ever has the latter.
232
+ const credential = await resolveCardInstrument(input);
233
+ // The passkey ceremony is scoped to the CEILING + merchant (not one
234
+ // charge) — that scope is the unproven part of the spike.
235
+ const ceilingTarget = {
236
+ merchantName: merchant.name,
237
+ merchantUrl: merchant.url,
238
+ merchantCountryCode: merchant.countryCode,
239
+ transactionAmount: input.ceiling,
240
+ transactionCurrencyCode: input.currency,
241
+ };
242
+ // BUDGET mode: the ceiling target's amount IS the approved ceiling, so the
243
+ // server mints a budget mint token bound to that ceiling — later draws pull
244
+ // sub-ceiling amounts against it tap-free (the single-purchase fresh-tap
245
+ // path below stays non-budget).
246
+ const assurance = await runHostedApproval({
247
+ baseUrl: input.approvalBaseUrl,
248
+ tokenId: credential.tokenId,
249
+ target: ceilingTarget,
250
+ consumerEmail: input.contact.email,
251
+ budget: true,
252
+ agentJkt: registerCap.agentJkt,
253
+ onApprovalUrl: deps.onApprovalUrl,
254
+ maxDraws: DEFAULT_MANDATE_MAX_DRAWS,
255
+ ...(input.perTransaction !== undefined ? { perTransaction: input.perTransaction } : {}),
256
+ ...(input.intent !== undefined ? { intent: input.intent } : {}),
257
+ });
258
+ const mintToken = assurance.mintToken;
259
+ if (!mintToken) {
260
+ throw new Error('the approval server issued no mint token — server-side minting requires the ' +
261
+ 'verify-web deployment to run real/turnkey auth (not the dev stub). Retry once it does.');
262
+ }
263
+ if (!Number.isSafeInteger(assurance.validUntil) ||
264
+ assurance.validUntil <= Math.floor(now().getTime() / 1000)) {
265
+ throw new Error('the approval server issued no valid budget expiry');
266
+ }
267
+ const expiresAt = new Date(assurance.validUntil * 1000).toISOString();
268
+ const facts = await createCardMandate({
269
+ agentJkt: registerCap.agentJkt,
270
+ tokenId: credential.tokenId,
271
+ assuranceData: assurance.assuranceData,
272
+ ceilingMinor,
273
+ merchant,
274
+ currencyCode: input.currency,
275
+ expiresAt,
276
+ maxDraws: DEFAULT_MANDATE_MAX_DRAWS,
277
+ crossMerchant: true,
278
+ }, {
279
+ createIntent: (i) => serverCreateIntent(input.approvalBaseUrl, mintToken, i),
280
+ ledger,
281
+ approvalBaseUrl: input.approvalBaseUrl,
282
+ now,
283
+ });
284
+ // Seed the one server-authoritative cumulative store keyed by the VGS
285
+ // intent ID. A later draw requires its PoP verdict; the budget token never
286
+ // falls back as payable authority.
287
+ const registered = await registerMandateOrDisable({
288
+ registerCap,
289
+ mandateId: facts.mandateId,
290
+ mintToken,
291
+ ceiling: input.ceiling,
292
+ currency: input.currency,
293
+ });
294
+ return {
295
+ ...facts,
296
+ merchantHost: new URL(merchant.url).hostname,
297
+ registerFailed: registered.registerFailed,
298
+ ...(registered.registerFailureReason !== undefined
299
+ ? { registerFailureReason: registered.registerFailureReason }
300
+ : {}),
301
+ };
302
+ },
303
+ // PICKUP leg: the owner already approved the ceiling in the account panel
304
+ // and handed this runtime a single-use pickup code. Claim it, verify it was
305
+ // minted for exactly this runtime's request key + card token, then run the
306
+ // same intent → register → ledger sequence as startCardMandate. No approval
307
+ // page, no passkey, no contact profile — the human side already happened.
308
+ async claimCardMandate(input) {
309
+ const registerCap = cardMandateRegister?.loadCapability(input.agentRef) ?? null;
310
+ if (!cardMandateRegister || !registerCap) {
311
+ throw new Error('claimCardMandate requires separately provisioned card authority in this runtime; ' +
312
+ 'identity pairing alone does not grant a card mandate');
313
+ }
314
+ const credential = await resolveCardInstrument(input);
315
+ const claim = await claimMandatePickup({
316
+ baseUrl: input.approvalBaseUrl,
317
+ pickupCode: input.pickupCode,
318
+ agentJkt: registerCap.agentJkt,
319
+ tokenId: credential.tokenId,
320
+ });
321
+ const ceilingMinor = decimalToMinor(claim.ceiling);
322
+ if (ceilingMinor === null || ceilingMinor <= 0) {
323
+ throw new Error(`the handoff carried an invalid ceiling ${JSON.stringify(claim.ceiling)}`);
324
+ }
325
+ // Same single-product bound as mandate-start (the panel initiate route
326
+ // enforces it too; a divergent store entry must not widen it here).
327
+ if (claim.currency.toUpperCase() !== 'USD') {
328
+ throw new Error('card spend budgets currently support USD only');
329
+ }
330
+ const expiresAt = new Date(claim.validUntil * 1000).toISOString();
331
+ const facts = await createCardMandate({
332
+ agentJkt: registerCap.agentJkt,
333
+ tokenId: credential.tokenId,
334
+ assuranceData: claim.assuranceData,
335
+ ceilingMinor,
336
+ merchant: claim.merchant,
337
+ currencyCode: claim.currency,
338
+ expiresAt,
339
+ maxDraws: claim.maxDraws,
340
+ crossMerchant: true,
341
+ }, {
342
+ createIntent: (i) => serverCreateIntent(input.approvalBaseUrl, claim.mintToken, i),
343
+ ledger,
344
+ approvalBaseUrl: input.approvalBaseUrl,
345
+ now,
346
+ });
347
+ const registered = await registerMandateOrDisable({
348
+ registerCap,
349
+ mandateId: facts.mandateId,
350
+ mintToken: claim.mintToken,
351
+ ceiling: claim.ceiling,
352
+ currency: claim.currency,
353
+ });
354
+ return {
355
+ ...facts,
356
+ merchantHost: new URL(claim.merchant.url).hostname,
357
+ registerFailed: registered.registerFailed,
358
+ ...(registered.registerFailureReason !== undefined
359
+ ? { registerFailureReason: registered.registerFailureReason }
360
+ : {}),
361
+ };
362
+ },
363
+ async review(input) {
364
+ const amountMinor = decimalToMinor(input.amount);
365
+ if (amountMinor === null)
366
+ throw new Error(`invalid amount ${JSON.stringify(input.amount)}`);
367
+ const host = new URL(input.url).hostname;
368
+ const browser = await launchBrowser();
369
+ try {
370
+ const prep = await prepareCheckout({
371
+ url: input.url,
372
+ mandate: {
373
+ maxAmountMinor: amountMinor,
374
+ currency: input.currency,
375
+ merchantHost: host,
376
+ expiresAt: new Date(Date.now() + 15 * 60 * 1000).toISOString(),
377
+ },
378
+ amountMinor,
379
+ currency: input.currency,
380
+ browser,
381
+ contact: input.contact,
382
+ }, store);
383
+ if (prep.status !== 'ready') {
384
+ await browser.close();
385
+ throw new Error(`review refused: ${prep.result.outcome} — ${prep.result.detail ?? ''}`);
386
+ }
387
+ const r = prep.checkout.review;
388
+ // Expire the companion session on the SAME schedule as the store entry
389
+ // (unref'd so a pending timer never keeps the process alive).
390
+ const cleanupTimer = setTimeout(() => void closeSession(r.id), ttlMs);
391
+ cleanupTimer.unref?.();
392
+ sessions.set(r.id, {
393
+ browser,
394
+ target: buildTarget(input),
395
+ amountMinor,
396
+ currency: input.currency,
397
+ contact: input.contact,
398
+ cleanupTimer,
399
+ });
400
+ return {
401
+ reviewId: r.id,
402
+ merchantHost: r.merchantHost,
403
+ amountMinor: r.amountMinor,
404
+ currency: r.currency,
405
+ submitTargetFingerprint: JSON.stringify(r.submitTargetFingerprint ?? null),
406
+ detectedRoles: [...r.detectedRoles],
407
+ };
408
+ }
409
+ catch (err) {
410
+ await browser.close().catch(() => { });
411
+ throw err;
412
+ }
413
+ },
414
+ async pay(input) {
415
+ const session = sessions.get(input.reviewId);
416
+ if (!session) {
417
+ return {
418
+ outcome: 'failed',
419
+ confirmationRef: null,
420
+ receiptPath: null,
421
+ detail: `no prepared review ${input.reviewId} — call review first (a review does not survive a restart)`,
422
+ vicConfirmation: null,
423
+ source: null,
424
+ remainingMinor: null,
425
+ };
426
+ }
427
+ // The reviewId selects the prepared browser session, but the pay call also
428
+ // repeats the target facts. Refuse if any repeated fact disagrees so the
429
+ // caller cannot submit one reviewed checkout while labeling the result or
430
+ // telemetry as another. Never echo the full URLs: payment links can carry
431
+ // claimable secrets in their path/query.
432
+ let payUrl;
433
+ let reviewedUrl;
434
+ try {
435
+ payUrl = new URL(input.url).toString();
436
+ reviewedUrl = new URL(session.target.merchantUrl).toString();
437
+ }
438
+ catch {
439
+ await closeSession(input.reviewId);
440
+ return {
441
+ outcome: 'failed',
442
+ confirmationRef: null,
443
+ receiptPath: null,
444
+ detail: 'pay merchant URL is invalid or does not match the reviewed checkout — start a fresh review',
445
+ vicConfirmation: null,
446
+ source: null,
447
+ remainingMinor: null,
448
+ };
449
+ }
450
+ if (payUrl !== reviewedUrl) {
451
+ await closeSession(input.reviewId);
452
+ return {
453
+ outcome: 'failed',
454
+ confirmationRef: null,
455
+ receiptPath: null,
456
+ detail: 'pay merchant URL does not match the reviewed checkout — start a fresh review',
457
+ vicConfirmation: null,
458
+ source: null,
459
+ remainingMinor: null,
460
+ };
461
+ }
462
+ if (input.currency.toUpperCase() !== session.currency.toUpperCase()) {
463
+ await closeSession(input.reviewId);
464
+ return {
465
+ outcome: 'failed',
466
+ confirmationRef: null,
467
+ receiptPath: null,
468
+ detail: `pay currency ${JSON.stringify(input.currency)} does not match the reviewed currency (${session.currency}) — start a fresh review`,
469
+ vicConfirmation: null,
470
+ source: null,
471
+ remainingMinor: null,
472
+ };
473
+ }
474
+ // Amount-bind the confirmation: the pay-call amount must match the
475
+ // reviewed amount. The reviewId already locks the immutable mandate, but
476
+ // re-checking here makes the confirmation explicitly amount-bound so a
477
+ // caller cannot pay a different figure than the human reviewed.
478
+ const payAmountMinor = decimalToMinor(input.amount);
479
+ if (payAmountMinor !== session.amountMinor) {
480
+ await closeSession(input.reviewId);
481
+ return {
482
+ outcome: 'failed',
483
+ confirmationRef: null,
484
+ receiptPath: null,
485
+ detail: `pay amount ${JSON.stringify(input.amount)} does not match the reviewed amount (${session.amountMinor} minor units) — start a fresh review`,
486
+ vicConfirmation: null,
487
+ source: null,
488
+ remainingMinor: null,
489
+ };
490
+ }
491
+ // Reject an expired prepared checkout BEFORE running the hosted passkey
492
+ // approval — the store may have expired/closed the entry while the review
493
+ // waited. Peeking here avoids minting a credential we can't submit.
494
+ if (!store.peek(input.reviewId)) {
495
+ await closeSession(input.reviewId);
496
+ return {
497
+ outcome: 'failed',
498
+ confirmationRef: null,
499
+ receiptPath: null,
500
+ detail: `prepared review ${input.reviewId} expired — start a fresh review`,
501
+ vicConfirmation: null,
502
+ source: null,
503
+ remainingMinor: null,
504
+ };
505
+ }
506
+ clearTimeout(session.cleanupTimer);
507
+ try {
508
+ // NO instrument read here. A tap-free mandate draw spends `covering
509
+ // .tokenId` (frozen into the mandate at start) and needs neither the
510
+ // legacy credential file nor a grant token; only the fresh-tap branch
511
+ // below needs one, and it resolves lazily so a grant-only device with an
512
+ // as-yet-unrefreshed token can still draw on a mandate it already holds.
513
+ const host = new URL(session.target.merchantUrl).hostname;
514
+ // Does an ACTIVE card mandate already cover this exact purchase? If so,
515
+ // draw against it TAP-FREE (no hosted passkey). Else fall back to today's
516
+ // 1:1 fresh-tap flow. Mandates no longer persist the bootstrap token:
517
+ // it is consumed by intent creation + register and has no draw power.
518
+ const covering = await ledger.findCovering({
519
+ merchantHost: host,
520
+ currencyCode: session.currency,
521
+ amountMinor: session.amountMinor,
522
+ now: now(),
523
+ });
524
+ let source;
525
+ let confirmBase;
526
+ // Fresh purchases confirm with their one-purchase mint token. Mandate
527
+ // draws set this only after the local reserve succeeds and auth returns
528
+ // the exact per-draw verdict used to mint the credential.
529
+ let confirmationAuthority = null;
530
+ let drawnRemaining = null;
531
+ let instrument;
532
+ if (covering) {
533
+ // --- Tap-free mandate draw ------------------------------------------
534
+ source = 'mandate';
535
+ confirmBase = covering.approvalBaseUrl;
536
+ const mandateId = covering.mandateId;
537
+ // A mandate cryptogram is authorized only by a PoP-signed verdict.
538
+ // The budget mint token is bootstrap-only and cannot bypass the
539
+ // server reserve/commit ledger when local draw authority is absent.
540
+ //
541
+ // #5928 CRITICAL-2: the CLI does NOT settle the reservation. verify-web
542
+ // (which knows whether the cryptogram was payable) commits it on a
543
+ // payable mint and releases it on a decline, server-authoritatively, so
544
+ // the drawer can never release after a payable mint to dodge the ceiling.
545
+ const verdictSeam = cardDrawVerdict;
546
+ const capability = verdictSeam?.loadCapability(covering.agentJkt) ?? null;
547
+ if (!capability || !verdictSeam) {
548
+ return {
549
+ outcome: 'failed',
550
+ confirmationRef: null,
551
+ receiptPath: null,
552
+ detail: 'this mandate cannot draw because its delegated card authority is unavailable; ' +
553
+ 'restore the runtime binding or use a fresh per-purchase passkey approval',
554
+ vicConfirmation: null,
555
+ source,
556
+ remainingMinor: null,
557
+ };
558
+ }
559
+ if (covering.agentJkt && capability.agentJkt !== covering.agentJkt) {
560
+ return {
561
+ outcome: 'failed',
562
+ confirmationRef: null,
563
+ receiptPath: null,
564
+ detail: 'this budget belongs to a different request key than the selected card capability; ' +
565
+ 'restore that exact runtime key or use a fresh per-purchase approval',
566
+ vicConfirmation: null,
567
+ source,
568
+ remainingMinor: null,
569
+ };
570
+ }
571
+ // VgsLiveInstrument mints against an EXISTING intent (the mandate) with
572
+ // no fresh assurance — exactly the draw semantics. The fetchCredential
573
+ // seam routes through drawFromMandate so the ledger accounting (reserve
574
+ // -> commit on payable, release on reject) wraps the cryptogram pull.
575
+ const reference = {
576
+ tokenId: covering.tokenId,
577
+ intentId: mandateId,
578
+ merchantName: session.target.merchantName,
579
+ merchantUrl: session.target.merchantUrl,
580
+ merchantCountryCode: session.target.merchantCountryCode,
581
+ transactionAmount: session.target.transactionAmount,
582
+ transactionCurrencyCode: session.currency,
583
+ };
584
+ const fetchCredential = async ({ transaction }) => {
585
+ let draw;
586
+ try {
587
+ draw = await drawFromMandate({
588
+ mandateId,
589
+ amountMinor: session.amountMinor,
590
+ transaction: { ...transaction, transactionCurrencyCode: session.currency },
591
+ }, {
592
+ // Ordering matters: reserve the local ledger FIRST, then ask
593
+ // auth to reserve the server-authoritative budget immediately
594
+ // before the payable mint. A local reserve race/expiry/file
595
+ // failure therefore makes zero auth/verdict calls and cannot
596
+ // strand a server reservation until its sweep.
597
+ fetchCryptogram: async (i) => {
598
+ const { verdict } = await verdictSeam.fetchVerdict({
599
+ authBaseUrl: capability.authBaseUrl,
600
+ agentKey: capability.agentKey,
601
+ mandateId,
602
+ // One draw per review; the reviewId is auth's idempotency key.
603
+ drawId: input.reviewId,
604
+ draw: {
605
+ tokenId: covering.tokenId,
606
+ amount: session.target.transactionAmount,
607
+ currency: session.currency,
608
+ merchantName: session.target.merchantName,
609
+ merchantUrl: session.target.merchantUrl,
610
+ merchantCountryCode: session.target.merchantCountryCode,
611
+ },
612
+ });
613
+ confirmationAuthority = verdict;
614
+ return fetchMandateCryptogram(confirmBase, verdict, i);
615
+ },
616
+ ledger,
617
+ now,
618
+ });
619
+ }
620
+ catch (err) {
621
+ // Disable the mandate ONLY for a post-reservation NETWORK decline
622
+ // (MandateDrawDeclinedError). That case leaves the mandate
623
+ // active+covering, so a naive retry would re-select it and fail
624
+ // identically — trapping the caller; marking it unhonored makes the
625
+ // next pay_merchant skip it and take a fresh per-purchase tap. We do
626
+ // NOT attempt an unsafe same-call browser fallback mid-submit.
627
+ //
628
+ // A PRE-network failure — reserve() failing closed on a concurrent
629
+ // over-budget race or expiry, or commit() throwing on file I/O —
630
+ // is NOT a network decline: the mandate is HEALTHY, so we must
631
+ // rethrow WITHOUT disabling it (michaelyang1 M1). drawFromMandate
632
+ // has already released any reservation, so the budget is intact.
633
+ // Only a DEFINITIVE (hard) decline disables the mandate. A TRANSIENT
634
+ // failure — a gateway 5xx / "not completed, try again" / network
635
+ // reset/timeout — must NOT permanently kill the budget: the mandate
636
+ // may be perfectly healthy (it can have committed a draw seconds
637
+ // earlier) and the rails may recover on retry. Over-disabling on a
638
+ // transient 502 threw away good budgets and forced a fresh passkey
639
+ // every time.
640
+ // Classify on the underlying gateway CAUSE, not the MandateDrawDeclinedError
641
+ // wrapper — the wrapper's own advisory text mentions "try again"/"network",
642
+ // which would otherwise self-classify every decline as transient.
643
+ if (err instanceof MandateDrawDeclinedError) {
644
+ const verdictFailure = classifyCardDrawVerdictFailure(err);
645
+ if (verdictFailure) {
646
+ if (!verdictFailure.transient) {
647
+ await ledger.markUnhonored(mandateId, now()).catch(() => { });
648
+ }
649
+ throw new Error(verdictFailure.transient
650
+ ? `the card-mandate draw could not be authorized right now (${verdictFailure.reasons.join(', ') || 'temporary error'}) — retry shortly`
651
+ : `this card mandate can no longer be drawn (${verdictFailure.reasons.join(', ') || 'refused'}); it has been disabled — retry the checkout to use a fresh per-purchase passkey tap`, { cause: err });
652
+ }
653
+ if (!isTransientDrawFailure(err.cause ?? err)) {
654
+ await ledger.markUnhonored(mandateId, now());
655
+ }
656
+ }
657
+ // #5928 CRITICAL-2: the server-side reservation is released by
658
+ // verify-web (it saw the mint fail), not here — the CLI never settles.
659
+ throw err;
660
+ }
661
+ drawnRemaining = draw.remainingMinor;
662
+ // #5928 CRITICAL-2: the reservation is committed by verify-web on the
663
+ // payable mint (server-authoritative); the CLI does not settle.
664
+ return draw.payment;
665
+ };
666
+ instrument = new VgsLiveInstrument(reference, session.contact.fullName ?? '', fetchCredential);
667
+ }
668
+ else {
669
+ // --- 1:1 fresh-tap flow (unchanged) ---------------------------------
670
+ source = 'fresh-tap';
671
+ // Legacy credential file OR the activated card:vic grant's token.
672
+ const credential = await resolveCardInstrument(input);
673
+ const assurance = await runHostedApproval({
674
+ baseUrl: input.approvalBaseUrl,
675
+ tokenId: credential.tokenId,
676
+ target: session.target,
677
+ consumerEmail: session.contact.email,
678
+ onApprovalUrl: input.onApprovalUrl ?? deps.onApprovalUrl,
679
+ });
680
+ // Server-side mint (Phase 1): the approval claim releases a scoped mint
681
+ // token; the credential is minted by the verify-web deployment (which
682
+ // holds the VGS secret), never on this machine. No token means the
683
+ // deployment ran the dev-auth stub — refuse loudly rather than reach for
684
+ // a client-held secret (there is none anymore).
685
+ const mintToken = assurance.mintToken;
686
+ if (!mintToken) {
687
+ return {
688
+ outcome: 'failed',
689
+ confirmationRef: null,
690
+ receiptPath: null,
691
+ detail: 'the approval server issued no mint token — server-side minting requires the ' +
692
+ 'verify-web deployment to run real/turnkey auth (not the dev stub). Retry once it does.',
693
+ vicConfirmation: null,
694
+ source: 'fresh-tap',
695
+ remainingMinor: null,
696
+ };
697
+ }
698
+ confirmBase = input.approvalBaseUrl;
699
+ confirmationAuthority = mintToken;
700
+ instrument = new VgsAssuranceInstrument(credential, assurance, session.target, session.contact.fullName ?? '', async (mintInput) => {
701
+ const { intentId, status } = await serverCreateIntent(confirmBase, mintToken, mintInput);
702
+ try {
703
+ const payment = await serverFetchCryptogram(confirmBase, mintToken, {
704
+ tokenId: mintInput.tokenId,
705
+ intentId,
706
+ transaction: mintInput.transaction,
707
+ });
708
+ return { payment, intentId };
709
+ }
710
+ catch (err) {
711
+ throw new Error(`${err.message} (intent status at creation: ${status ?? 'unknown'})`);
712
+ }
713
+ });
714
+ }
715
+ const mode = input.submit ? 'submit' : 'dry-run';
716
+ const result = await submitApprovedCheckout(input.reviewId, {
717
+ approval: { approved: true, reviewId: input.reviewId },
718
+ instrument,
719
+ contact: session.contact,
720
+ mode,
721
+ ...(deps.resolveEmailOtp ? { resolveEmailOtp: deps.resolveEmailOtp } : {}),
722
+ }, store);
723
+ // Report the observed submit outcome to VIC for the consumed intent
724
+ // (APPROVED/DECLINED). Only definitive submit answers post. Mirrors
725
+ // run-live-fill.ts.
726
+ let vicConfirmation = null;
727
+ if (mode === 'submit') {
728
+ vicConfirmation = await reportVicOutcome({
729
+ target: instrument.confirmationTarget(),
730
+ outcome: result.outcome,
731
+ transaction: {
732
+ transactionAmount: session.target.transactionAmount,
733
+ transactionCurrencyCode: session.currency,
734
+ },
735
+ post: (confInput) => {
736
+ if (!confirmationAuthority) {
737
+ throw new Error('confirmation authority missing for the consumed VIC intent');
738
+ }
739
+ return postServerConfirmation(confirmBase, confirmationAuthority, confInput);
740
+ },
741
+ });
742
+ }
743
+ let receiptPath = null;
744
+ const report = await writeReceipt(RECEIPT_DIR, buildReceipt({
745
+ mode,
746
+ reviewId: input.reviewId,
747
+ // Derive BOTH name and host from the reviewed session target (not
748
+ // pay()'s input.url), so the receipt always reflects the checkout
749
+ // the human actually reviewed + that reviewId bound for submit.
750
+ merchant: {
751
+ name: session.target.merchantName,
752
+ host: new URL(session.target.merchantUrl).hostname,
753
+ },
754
+ transaction: {
755
+ amount: session.target.transactionAmount,
756
+ amountMinor: session.amountMinor,
757
+ currency: session.currency,
758
+ },
759
+ result,
760
+ vicConfirmation,
761
+ }));
762
+ if (report.written)
763
+ receiptPath = report.path;
764
+ return {
765
+ outcome: result.outcome,
766
+ confirmationRef: result.confirmationRef ?? null,
767
+ receiptPath,
768
+ detail: result.detail ?? null,
769
+ vicConfirmation,
770
+ source,
771
+ remainingMinor: drawnRemaining,
772
+ };
773
+ }
774
+ finally {
775
+ await closeSession(input.reviewId);
776
+ }
777
+ },
778
+ };
779
+ }