@visa/cli 4.1.0-rc.297 → 4.1.0-rc.299

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 (77) hide show
  1. package/README.md +29 -45
  2. package/dist/cli.js +556 -786
  3. package/dist/mcp-server/index.js +408 -622
  4. package/dist/merchant-ucp-mcp/index.js +6 -6
  5. package/dist/skills/pair-visa-agent/SKILL.md +175 -240
  6. package/native/bin/win32-arm64/visa-runtime-signer.exe +0 -0
  7. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  8. package/native/bin/win32-x64/visa-runtime-signer.exe +0 -0
  9. package/package.json +2 -4
  10. package/server.json +2 -2
  11. package/dist/checkout-engine/adapters/generic.d.ts +0 -88
  12. package/dist/checkout-engine/adapters/generic.js +0 -526
  13. package/dist/checkout-engine/adapters/index.d.ts +0 -10
  14. package/dist/checkout-engine/adapters/index.js +0 -24
  15. package/dist/checkout-engine/adapters/shopify.d.ts +0 -98
  16. package/dist/checkout-engine/adapters/shopify.js +0 -744
  17. package/dist/checkout-engine/adapters/stripe-like.d.ts +0 -10
  18. package/dist/checkout-engine/adapters/stripe-like.js +0 -21
  19. package/dist/checkout-engine/amount.d.ts +0 -17
  20. package/dist/checkout-engine/amount.js +0 -72
  21. package/dist/checkout-engine/browser-launch.d.ts +0 -51
  22. package/dist/checkout-engine/browser-launch.js +0 -96
  23. package/dist/checkout-engine/browserbase-browser.d.ts +0 -24
  24. package/dist/checkout-engine/browserbase-browser.js +0 -186
  25. package/dist/checkout-engine/ceremony.d.ts +0 -64
  26. package/dist/checkout-engine/ceremony.js +0 -261
  27. package/dist/checkout-engine/cli-engine.d.ts +0 -417
  28. package/dist/checkout-engine/cli-engine.js +0 -1331
  29. package/dist/checkout-engine/confirmed-merchants.d.ts +0 -31
  30. package/dist/checkout-engine/confirmed-merchants.js +0 -165
  31. package/dist/checkout-engine/detect.d.ts +0 -61
  32. package/dist/checkout-engine/detect.js +0 -398
  33. package/dist/checkout-engine/evidence.d.ts +0 -25
  34. package/dist/checkout-engine/evidence.js +0 -104
  35. package/dist/checkout-engine/executor.d.ts +0 -262
  36. package/dist/checkout-engine/executor.js +0 -1837
  37. package/dist/checkout-engine/hosted-approval.d.ts +0 -195
  38. package/dist/checkout-engine/hosted-approval.js +0 -501
  39. package/dist/checkout-engine/index.d.ts +0 -12
  40. package/dist/checkout-engine/index.js +0 -13
  41. package/dist/checkout-engine/instrument.d.ts +0 -61
  42. package/dist/checkout-engine/instrument.js +0 -87
  43. package/dist/checkout-engine/known-merchants.d.ts +0 -10
  44. package/dist/checkout-engine/known-merchants.js +0 -38
  45. package/dist/checkout-engine/live-fill-approval.d.ts +0 -37
  46. package/dist/checkout-engine/live-fill-approval.js +0 -76
  47. package/dist/checkout-engine/mandate/card-mandate.d.ts +0 -121
  48. package/dist/checkout-engine/mandate/card-mandate.js +0 -226
  49. package/dist/checkout-engine/mandate/mandate-ledger.d.ts +0 -175
  50. package/dist/checkout-engine/mandate/mandate-ledger.js +0 -425
  51. package/dist/checkout-engine/mandate.d.ts +0 -33
  52. package/dist/checkout-engine/mandate.js +0 -135
  53. package/dist/checkout-engine/outcome.d.ts +0 -30
  54. package/dist/checkout-engine/outcome.js +0 -225
  55. package/dist/checkout-engine/owner-only-file.d.ts +0 -19
  56. package/dist/checkout-engine/owner-only-file.js +0 -41
  57. package/dist/checkout-engine/package.json +0 -3
  58. package/dist/checkout-engine/receipt-dir.d.ts +0 -6
  59. package/dist/checkout-engine/receipt-dir.js +0 -8
  60. package/dist/checkout-engine/receipt.d.ts +0 -135
  61. package/dist/checkout-engine/receipt.js +0 -148
  62. package/dist/checkout-engine/shopify-primary-domain.d.ts +0 -25
  63. package/dist/checkout-engine/shopify-primary-domain.js +0 -96
  64. package/dist/checkout-engine/trace-handles.d.ts +0 -8
  65. package/dist/checkout-engine/trace-handles.js +0 -12
  66. package/dist/checkout-engine/types.d.ts +0 -52
  67. package/dist/checkout-engine/types.js +0 -2
  68. package/dist/checkout-engine/unresolved-charges.d.ts +0 -34
  69. package/dist/checkout-engine/unresolved-charges.js +0 -134
  70. package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +0 -155
  71. package/dist/checkout-engine/vgs-gateway/server-mint-client.js +0 -493
  72. package/dist/checkout-engine/vgs-live-instrument.d.ts +0 -144
  73. package/dist/checkout-engine/vgs-live-instrument.js +0 -229
  74. package/dist/checkout-engine/vic-confirmation.d.ts +0 -52
  75. package/dist/checkout-engine/vic-confirmation.js +0 -45
  76. package/dist/checkout-engine/web-bot-auth.d.ts +0 -98
  77. package/dist/checkout-engine/web-bot-auth.js +0 -218
@@ -1,493 +0,0 @@
1
- import { createDecipheriv, createHash, verify, createPublicKey, diffieHellman, hkdfSync, } from 'node:crypto';
2
- // Server-side mint client (Phase 1) — the checkout runner mints the payment
3
- // credential by calling the verify-web deployment's gateway routes with a
4
- // short-lived, purpose-scoped MINT TOKEN, instead of holding the shared VGS
5
- // service-account secret (the gateway client id/secret) on the machine.
6
- //
7
- // The mint token is issued at approval time (agent-approval/complete, which is
8
- // session + internal-tester + token-ownership gated) and released to this
9
- // runner by the claim leg. It is bound to the exact approved purchase, so these
10
- // calls can only mint the credential the human approved.
11
- //
12
- // Request derivation here mirrors ../fetch-credential.mjs EXACTLY (mandate cap,
13
- // consumer prompt, PENDING retry cadence) — the only change is the transport:
14
- // verify-web routes + Bearer mint token, never the VGS gateway + VGS secret.
15
- import { traceHandleFields } from '../trace-handles.js';
16
- const defaultSleep = (ms) => new Promise((r) => {
17
- const t = setTimeout(r, ms);
18
- t.unref?.();
19
- });
20
- function stripTrailingSlashes(value) {
21
- let out = value;
22
- while (out.endsWith('/'))
23
- out = out.slice(0, -1);
24
- return out;
25
- }
26
- /**
27
- * The merchant ORIGIN (scheme + host) — not the full checkout URL. A merchant's
28
- * identity is its origin; a real checkout URL can carry hundreds of chars of
29
- * campaign/tracking query params. Confirmed live: an oversized `merchantUrl`
30
- * (a ~280-char Wikimedia donation URL) makes the cryptogram mint fail downstream
31
- * with a vague `502 "card network could not complete"`, while the same merchant
32
- * with a trimmed URL mints fine. Sending the origin is both correct (that IS the
33
- * merchant) and safely bounded. Falls back to the raw value if it does not parse
34
- * — the mint must never throw here.
35
- */
36
- export function merchantOrigin(url) {
37
- try {
38
- return new URL(url).origin;
39
- }
40
- catch {
41
- return url;
42
- }
43
- }
44
- /**
45
- * A definitive refusal from the cryptogram mint route — the request will not
46
- * succeed if retried unchanged.
47
- *
48
- * `terminal` is the load-bearing field. Draw terminality used to be decided by
49
- * regex over the error MESSAGE, which made it hostage to text nobody controls:
50
- * this client now interpolates the provider's own `upstream_codes` into the
51
- * message for diagnosability, and a provider identifier such as
52
- * `request_timeout` would match the transient matcher's unanchored
53
- * `tim(e|ed)-out` alternative — flipping a permanent 422 back to "transient",
54
- * skipping markUnhonored, and stranding the mandate in the exact retry-forever
55
- * loop this whole change exists to kill. Terminality is therefore carried
56
- * structurally, and consumers must consult it BEFORE any message matching.
57
- */
58
- export class ServerCryptogramRefusedError extends Error {
59
- status;
60
- terminal = true;
61
- constructor(status, detail) {
62
- super(`server cryptogram refused (${status}): ${detail}`);
63
- this.name = 'ServerCryptogramRefusedError';
64
- this.status = status;
65
- }
66
- }
67
- async function readRouteErrorDoc(res) {
68
- return (await res.json().catch(() => null));
69
- }
70
- function routeErrorMessage(res, doc) {
71
- const base = doc?.error || doc?.error_code || `HTTP ${res.status}`;
72
- // Carry the provider's own status and rejected-attribute identifiers into the
73
- // message when the route reflected them. Without this the operator sees only
74
- // our status and has to go log-diving to learn WHICH field the gateway
75
- // objected to — the gap that left a live create_intent 422 undiagnosable.
76
- const parts = [];
77
- if (typeof doc?.upstream_status === 'number')
78
- parts.push(`upstream_status=${doc.upstream_status}`);
79
- if (Array.isArray(doc?.upstream_codes) && doc.upstream_codes.length > 0) {
80
- parts.push(`upstream_codes=${doc.upstream_codes.join(',')}`);
81
- }
82
- return parts.length > 0 ? `${base} [${parts.join(' ')}]` : base;
83
- }
84
- async function routeError(res) {
85
- return routeErrorMessage(res, await readRouteErrorDoc(res));
86
- }
87
- const BOOTSTRAP_STATES = new Set([
88
- 'none',
89
- 'pending',
90
- 'created',
91
- 'ambiguous',
92
- 'conflict',
93
- 'unknown',
94
- ]);
95
- function bootstrapStateOf(value) {
96
- return typeof value === 'string' && BOOTSTRAP_STATES.has(value)
97
- ? value
98
- : 'unknown';
99
- }
100
- const SAFE_REQUEST_ID = /^[A-Za-z0-9._:-]{1,128}$/;
101
- function requestIdOf(res, doc) {
102
- const candidate = res?.headers.get('x-request-id') ?? doc?.request_id ?? null;
103
- return typeof candidate === 'string' && SAFE_REQUEST_ID.test(candidate) ? candidate : null;
104
- }
105
- /**
106
- * The budget-intent route's failure, kept structured (#8470). `status` 0 means
107
- * the request never produced an HTTP response (network failure or abort), which
108
- * is outcome-uncertain exactly like a 5xx: the server may have dispatched.
109
- */
110
- export class ServerIntentError extends Error {
111
- facts;
112
- code = 'SERVER_INTENT_FAILED';
113
- constructor(message, facts) {
114
- super(message);
115
- this.facts = facts;
116
- this.name = 'ServerIntentError';
117
- }
118
- }
119
- function serverIntentErrorFrom(res, doc) {
120
- const errorCode = typeof doc?.error_code === 'string'
121
- ? doc.error_code
122
- : typeof doc?.error === 'string' && /^[a-z0-9_]{1,64}$/.test(doc.error)
123
- ? doc.error
124
- : null;
125
- const outcome = doc?.outcome === 'uncertain' || doc?.outcome === 'not_created'
126
- ? doc.outcome
127
- : res.status >= 500 || res.status === 0
128
- ? 'uncertain'
129
- : 'not_created';
130
- return new ServerIntentError(`server intent failed (${res.status}): ${routeErrorMessage(res, doc)}`, {
131
- status: res.status,
132
- errorCode,
133
- retryable: typeof doc?.retryable === 'boolean' ? doc.retryable : null,
134
- requestId: requestIdOf(res, doc),
135
- bootstrapState: bootstrapStateOf(doc?.bootstrap_state),
136
- outcome,
137
- });
138
- }
139
- function bearer(mintToken) {
140
- return { 'content-type': 'application/json', authorization: `Bearer ${mintToken}` };
141
- }
142
- /**
143
- * Create a fresh intent via POST {base}/api/vgs/intent. The server holds the VGS
144
- * credential and calls the gateway; we send the same mandate shape the local
145
- * path built (cap = ceil(amount)+10, min 25; merchant category Retail/5999) —
146
- * unless `input.mandate` overrides the threshold/quantity/window for the
147
- * card-mandate (budget) layer.
148
- */
149
- export async function serverCreateIntent(base, mintToken, input, deps = {}) {
150
- const fetchImpl = deps.fetchImpl ?? fetch;
151
- const { tokenId, assuranceData, transaction: t } = input;
152
- const override = input.mandate ?? {};
153
- const defaultCap = Math.max(Math.ceil(Number(t.transactionAmount) || 0) + 10, 25);
154
- const declineThresholdAmount = override.declineThresholdAmount ?? String(defaultCap);
155
- const quantity = override.quantity ?? 1;
156
- const effectiveUntil = override.effectiveUntil ?? new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString();
157
- const consumerPrompt = override.consumerPrompt ??
158
- `Buy an item from ${t.merchantName} for ${t.transactionCurrencyCode.toUpperCase()} ${t.transactionAmount}`;
159
- let res;
160
- try {
161
- res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/intent`, {
162
- method: 'POST',
163
- headers: bearer(mintToken),
164
- body: JSON.stringify({
165
- tokenId,
166
- consumerPrompt,
167
- assuranceData,
168
- mandates: [
169
- {
170
- description: `Purchase at ${t.merchantName}`,
171
- declineThresholdAmount,
172
- declineThresholdCurrencyCode: t.transactionCurrencyCode.toUpperCase(),
173
- effectiveUntil,
174
- merchantCategory: 'Retail',
175
- merchantCategoryCode: '5999',
176
- preferredMerchantName: t.merchantName,
177
- quantity,
178
- },
179
- ],
180
- }),
181
- });
182
- }
183
- catch (err) {
184
- // No HTTP response at all: the request may or may not have reached the
185
- // server, so this is outcome-uncertain, never a proven non-creation.
186
- throw new ServerIntentError(`server intent failed (0): ${err instanceof Error ? err.message : String(err)}`, {
187
- status: 0,
188
- errorCode: null,
189
- retryable: false,
190
- requestId: null,
191
- bootstrapState: 'unknown',
192
- outcome: 'uncertain',
193
- });
194
- }
195
- if (!res.ok)
196
- throw serverIntentErrorFrom(res, await readRouteErrorDoc(res));
197
- const doc = (await res.json().catch(() => null));
198
- if (!doc?.intentId)
199
- throw new Error('server intent response missing intentId');
200
- return { intentId: doc.intentId, status: typeof doc.status === 'string' ? doc.status : null };
201
- }
202
- /**
203
- * Read the durable budget-bootstrap state for a budget mint token via
204
- * GET {base}/api/vgs/intent (#8470). A `created` answer carries the intent the
205
- * server already minted under this token, so the runner registers it instead
206
- * of dispatching again; `pending` and `ambiguous` are never redispatched.
207
- */
208
- export async function serverReadIntentBootstrap(base, mintToken, deps = {}) {
209
- const fetchImpl = deps.fetchImpl ?? fetch;
210
- let res;
211
- try {
212
- res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/intent`, {
213
- method: 'GET',
214
- headers: bearer(mintToken),
215
- });
216
- }
217
- catch (err) {
218
- throw new ServerIntentError(`server intent status failed (0): ${err instanceof Error ? err.message : String(err)}`, {
219
- status: 0,
220
- errorCode: null,
221
- retryable: true,
222
- requestId: null,
223
- bootstrapState: 'unknown',
224
- outcome: 'unknown',
225
- });
226
- }
227
- const doc = (await res.json().catch(() => null));
228
- if (!res.ok) {
229
- const error = serverIntentErrorFrom(res, doc);
230
- throw new ServerIntentError(error.message.replace('server intent failed', 'server intent status failed'), {
231
- ...error.facts,
232
- retryable: error.facts.retryable || res.status === 503,
233
- outcome: 'unknown',
234
- });
235
- }
236
- const state = bootstrapStateOf(doc?.bootstrap_state);
237
- const intentId = typeof doc?.intent?.intentId === 'string' && doc.intent.intentId ? doc.intent.intentId : null;
238
- return {
239
- state: state === 'created' && !intentId ? 'unknown' : state,
240
- intentId,
241
- intentStatus: typeof doc?.intent?.status === 'string' ? doc.intent.status : null,
242
- requestId: requestIdOf(res, doc),
243
- };
244
- }
245
- /**
246
- * Mint the FULL payment credential via POST {base}/api/vgs/payment-cryptogram.
247
- * The server's route does a SINGLE gateway call and 502s on a not-COMPLETED
248
- * (e.g. PENDING) cryptogram, but live intent approval is asynchronous and the
249
- * first cryptogram answer can be PENDING (#5709). So we retry the route on any
250
- * non-2xx up to PENDING_ATTEMPTS, matching fetch-credential.mjs's cadence
251
- * exactly — a genuinely hard failure just surfaces after the same bounded wait.
252
- * Re-POSTing for the same intentId is idempotent (mirrors the old client loop).
253
- */
254
- export async function serverFetchCryptogram(base, mintToken, input, deps = {}) {
255
- const fetchImpl = deps.fetchImpl ?? fetch;
256
- const sleep = deps.sleep ?? defaultSleep;
257
- const env = deps.env ?? process.env;
258
- const attempts = Math.max(1, Number(env.VGS_CRYPTOGRAM_PENDING_ATTEMPTS) || 4);
259
- const waitMs = Number.isFinite(Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS))
260
- ? Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS)
261
- : 5000;
262
- const { tokenId, intentId, transaction: t } = input;
263
- const body = JSON.stringify({
264
- tokenId,
265
- intentId,
266
- transaction: {
267
- merchantName: t.merchantName,
268
- // Send the merchant ORIGIN, not the full (possibly huge) checkout URL — an
269
- // oversized merchantUrl makes the downstream cryptogram mint 502 (proven live).
270
- merchantUrl: merchantOrigin(t.merchantUrl),
271
- merchantCountryCode: t.merchantCountryCode,
272
- transactionAmount: t.transactionAmount,
273
- transactionCurrencyCode: t.transactionCurrencyCode.toUpperCase(),
274
- },
275
- });
276
- let lastError = 'unknown';
277
- for (let attempt = 1; attempt <= attempts; attempt++) {
278
- const res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/payment-cryptogram`, {
279
- method: 'POST',
280
- headers: bearer(mintToken),
281
- body,
282
- });
283
- if (res.ok) {
284
- const c = (await res.json().catch(() => null));
285
- if (!c || typeof c.networkToken !== 'string' || typeof c.cryptogramValue !== 'string') {
286
- throw new Error('server cryptogram response missing credential fields');
287
- }
288
- return {
289
- networkToken: c.networkToken,
290
- expMonth: Number(c.expMonth) || 0,
291
- expYear: Number(c.expYear) || 0,
292
- cryptogramType: c.cryptogramType ?? '',
293
- cryptogramValue: c.cryptogramValue,
294
- ...(typeof c.cryptogramExpiresAt === 'string'
295
- ? { cryptogramExpiresAt: c.cryptogramExpiresAt }
296
- : {}),
297
- ...traceHandleFields(c),
298
- };
299
- }
300
- // A 4xx (bad request / binding refusal / auth) is terminal — never retry it.
301
- // 429 is the sole exception: it is an explicitly retryable 4xx, and treating
302
- // it as terminal would let a transient rate limit permanently disable a
303
- // healthy mandate. The route maps upstream rate limits to 503 today, so this
304
- // is a guard against a future emitter, not a live path.
305
- if (res.status >= 400 && res.status < 500 && res.status !== 429) {
306
- throw new ServerCryptogramRefusedError(res.status, await routeError(res));
307
- }
308
- lastError = `${res.status}: ${await routeError(res)}`;
309
- if (attempt < attempts)
310
- await sleep(waitMs);
311
- }
312
- throw new Error(`server cryptogram not completed after ${attempts} attempts (last: ${lastError})`);
313
- }
314
- /** Report the observed merchant outcome via POST {base}/api/vgs/confirmation. */
315
- export async function serverPostConfirmation(base, mintToken, input, deps = {}) {
316
- const fetchImpl = deps.fetchImpl ?? fetch;
317
- const res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/confirmation`, {
318
- method: 'POST',
319
- headers: bearer(mintToken),
320
- body: JSON.stringify({
321
- tokenId: input.tokenId,
322
- intentId: input.intentId,
323
- transactionStatus: input.transactionStatus,
324
- transactionType: input.transactionType,
325
- transactionTimestamp: input.transactionTimestamp,
326
- transactionAmount: input.transaction.transactionAmount,
327
- transactionCurrencyCode: input.transaction.transactionCurrencyCode.toUpperCase(),
328
- }),
329
- });
330
- if (!res.ok)
331
- throw new Error(`server confirmation failed (${res.status}): ${await routeError(res)}`);
332
- return { ok: true };
333
- }
334
- function cardEvidence(token, key, typ, fields) {
335
- const fail = () => {
336
- throw new Error('protected_card_evidence_invalid');
337
- };
338
- if (key.type !== 'public' ||
339
- key.asymmetricKeyType !== 'ed25519' ||
340
- typeof token !== 'string' ||
341
- token.length > 16384)
342
- return fail();
343
- const parts = token.split('.');
344
- if (parts.length !== 3)
345
- return fail();
346
- const jwk = key.export({ format: 'jwk' });
347
- const kid = createHash('sha256')
348
- .update(JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x }))
349
- .digest('base64url');
350
- const header = JSON.parse(Buffer.from(parts[0], 'base64url').toString());
351
- const claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString());
352
- if (!header ||
353
- Object.keys(header).sort().join(',') !== 'alg,kid,typ' ||
354
- header.alg !== 'EdDSA' ||
355
- header.typ !== typ ||
356
- header.kid !== kid ||
357
- !claims ||
358
- Object.keys(claims).sort().join(',') !== fields.sort().join(',') ||
359
- claims.v !== 1 ||
360
- typeof claims.jti !== 'string' ||
361
- !claims.jti ||
362
- !Number.isSafeInteger(claims.iat) ||
363
- !verify(null, Buffer.from(parts.slice(0, 2).join('.')), key, Buffer.from(parts[2], 'base64url')))
364
- return fail();
365
- return claims;
366
- }
367
- export async function serverFetchProtectedCryptogram(base, input, deps = {}) {
368
- const hash = Buffer.from(input.requestHash, 'base64url');
369
- if (hash.length !== 32 ||
370
- hash.toString('base64url') !== input.requestHash ||
371
- input.deliveryKey.type !== 'private' ||
372
- input.deliveryKey.asymmetricKeyType !== 'x25519')
373
- throw new Error('protected_card_delivery_key_invalid');
374
- const response = await (deps.fetchImpl ?? fetch)(`${stripTrailingSlashes(base)}/api/vgs/payment-cryptogram`, {
375
- method: 'POST',
376
- headers: { 'content-type': 'application/json', 'x-visa-card-protected': 'v1' },
377
- body: JSON.stringify({
378
- financialAdmission: input.financialAdmission,
379
- request: input.request,
380
- }),
381
- redirect: 'error',
382
- });
383
- if (response.status === 202)
384
- throw new Error('protected_card_recovery_pending');
385
- if (!response.ok)
386
- throw new Error(`protected_card_refused_${response.status}`);
387
- const reader = response.body?.getReader();
388
- if (!reader)
389
- throw new Error('protected_card_response_invalid');
390
- const chunks = [];
391
- let size = 0;
392
- try {
393
- for (;;) {
394
- const part = await reader.read();
395
- if (part.done)
396
- break;
397
- size += part.value.byteLength;
398
- if (size > 65536) {
399
- await reader.cancel();
400
- throw new Error('protected_card_response_invalid');
401
- }
402
- chunks.push(part.value);
403
- }
404
- }
405
- finally {
406
- reader.releaseLock();
407
- }
408
- const envelope = JSON.parse(Buffer.concat(chunks).toString());
409
- if (!envelope ||
410
- Object.keys(envelope).sort().join(',') !==
411
- 'acknowledgement,ciphertext,ephemeralPublicJwk,iv,outcome,tag,v' ||
412
- envelope.v !== 1)
413
- throw new Error('protected_card_response_invalid');
414
- const coordinates = [
415
- 'v',
416
- 'aud',
417
- 'jti',
418
- 'attemptId',
419
- 'requestHash',
420
- 'admissionId',
421
- 'issuanceGeneration',
422
- 'iat',
423
- ];
424
- const outcome = cardEvidence(envelope.outcome, input.pins.executor, 'visa-card-delivery-outcome+jwt', [...coordinates, 'outcome', 'providerRef', 'credentialSha256']);
425
- const ack = cardEvidence(envelope.acknowledgement, input.pins.issuer, 'visa-card-delivery-state+jwt', [...coordinates, 'action', 'outcomeHash', 'exp']);
426
- const permit = JSON.parse(Buffer.from(input.financialAdmission.split('.')[1], 'base64url').toString());
427
- const now = Math.floor(Date.now() / 1000);
428
- if (outcome.aud !== 'urn:visa:authority:card-outcome' ||
429
- outcome.outcome !== 'credential_observed' ||
430
- outcome.requestHash !== input.requestHash ||
431
- outcome.attemptId !== permit.attemptId ||
432
- outcome.admissionId !== permit.jti ||
433
- outcome.issuanceGeneration !== permit.issuanceGeneration ||
434
- ack.aud !== 'urn:visa:executor:card-vic' ||
435
- ack.action !== 'recover_only' ||
436
- ack.requestHash !== outcome.requestHash ||
437
- ack.attemptId !== outcome.attemptId ||
438
- ack.admissionId !== outcome.admissionId ||
439
- ack.issuanceGeneration !== outcome.issuanceGeneration ||
440
- !Number.isSafeInteger(ack.exp) ||
441
- ack.exp <= now ||
442
- ack.iat > now + 5 ||
443
- ack.exp <= ack.iat ||
444
- ack.exp - ack.iat > 60 ||
445
- ack.outcomeHash !== createHash('sha256').update(envelope.outcome).digest('base64url'))
446
- throw new Error('protected_card_evidence_invalid');
447
- const jwk = envelope.ephemeralPublicJwk;
448
- if (!jwk ||
449
- Object.keys(jwk).sort().join(',') !== 'crv,kty,x' ||
450
- jwk.kty !== 'OKP' ||
451
- jwk.crv !== 'X25519')
452
- throw new Error('protected_card_response_invalid');
453
- const decode = (value, size) => {
454
- if (typeof value !== 'string')
455
- throw new Error('protected_card_response_invalid');
456
- const decoded = Buffer.from(value, 'base64url');
457
- if (decoded.toString('base64url') !== value || (size !== undefined && decoded.length !== size))
458
- throw new Error('protected_card_response_invalid');
459
- return decoded;
460
- };
461
- decode(jwk.x, 32);
462
- const shared = diffieHellman({
463
- privateKey: input.deliveryKey,
464
- publicKey: createPublicKey({ key: jwk, format: 'jwk' }),
465
- });
466
- const key = Buffer.from(hkdfSync('sha256', shared, hash, 'visa-card-delivery-v1', 32));
467
- shared.fill(0);
468
- let clear;
469
- try {
470
- const decipher = createDecipheriv('aes-256-gcm', key, decode(envelope.iv, 12));
471
- decipher.setAAD(Buffer.from(input.requestHash));
472
- decipher.setAuthTag(decode(envelope.tag, 16));
473
- clear = Buffer.concat([decipher.update(decode(envelope.ciphertext)), decipher.final()]);
474
- if (createHash('sha256').update(clear).digest('base64url') !== outcome.credentialSha256)
475
- throw new Error('protected_card_credential_invalid');
476
- const credential = JSON.parse(clear.toString());
477
- if (!credential ||
478
- typeof credential.networkToken !== 'string' ||
479
- typeof credential.cryptogramValue !== 'string' ||
480
- !Number.isInteger(credential.expMonth) ||
481
- credential.expMonth < 1 ||
482
- credential.expMonth > 12 ||
483
- !Number.isInteger(credential.expYear) ||
484
- credential.expYear < 2000 ||
485
- typeof credential.cryptogramType !== 'string')
486
- throw new Error('protected_card_credential_invalid');
487
- return credential;
488
- }
489
- finally {
490
- key.fill(0);
491
- clear?.fill(0);
492
- }
493
- }
@@ -1,144 +0,0 @@
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
- * 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;
54
- };
55
- /**
56
- * Our fail-closed freshness bound, matching the runner's 15-minute checkout
57
- * review window — NOT a claim about VGS's actual assurance TTL (unpublished).
58
- * The only proven-working configuration mints the intent right after the
59
- * ceremony; anything older is refused before an intent is created.
60
- */
61
- export declare const PURCHASE_ASSURANCE_MAX_AGE_MS: number;
62
- export type VgsPaymentCredential = {
63
- networkToken: string;
64
- expMonth: number;
65
- expYear: number;
66
- cryptogramType: string;
67
- cryptogramValue: string;
68
- cryptogramExpiresAt?: string;
69
- vgsTraceId?: string;
70
- networkCorrelationId?: string;
71
- };
72
- export type FetchVgsPaymentCredential = (input: {
73
- tokenId: string;
74
- intentId: string;
75
- transaction: {
76
- merchantName: string;
77
- merchantUrl: string;
78
- merchantCountryCode: string;
79
- transactionAmount: string;
80
- transactionCurrencyCode: string;
81
- };
82
- }) => Promise<VgsPaymentCredential>;
83
- /** The (token, intent) pair a VIC confirmation is posted against. */
84
- export type VicConfirmationTarget = {
85
- tokenId: string;
86
- intentId: string;
87
- };
88
- export declare function decimalToMinor(value: unknown): number | null;
89
- /**
90
- * Currencies whose minor unit is 1/100 of the major unit (2 decimal places).
91
- * minorToDecimal's /100 + pad-to-2 rendering is ONLY correct for these. The
92
- * card mandate path accepts any 3-letter ISO code, so a 0- or 3-decimal
93
- * currency (JPY, BHD, …) would otherwise be emitted with a wrong wire amount.
94
- * We only support USD/USDC today; extend deliberately (and fix the exponent)
95
- * before adding any non-2-decimal currency.
96
- *
97
- * NOTE (scanner FP pre-empt): this is a CLIENT-SIDE currency-exponent lookup for
98
- * rendering a wire amount in @visa/checkout-engine — it is NOT the cross-store
99
- * `PAYMENT_CURRENCIES` enum governed by apps/auth/src/shared-validators.ts, and
100
- * this package cannot import from apps/auth (no dependency edge). It intentionally
101
- * does not mirror that enum's membership; do not "reconcile" the two.
102
- */
103
- export declare const TWO_DECIMAL_CURRENCIES: Set<string>;
104
- /**
105
- * Inverse of decimalToMinor: render integer minor units as a major-unit decimal
106
- * string ("D.DD") for the VGS wire (e.g. a ceiling of 50000 minor → "500.00").
107
- * Integer-only; never floating-point money. Throws on a non-integer/negative so
108
- * a bad accounting value cannot silently reach the network.
109
- *
110
- * The /100 + pad-to-2 rendering assumes a 2-decimal (exponent-2) currency. Pass
111
- * `currencyCode` on any path that accepts arbitrary currencies (the mandate
112
- * path) and it REFUSES a non-2-decimal currency rather than emit a wrong wire
113
- * amount. Omit it only where the currency is already known to be USD/USDC.
114
- */
115
- export declare function minorToDecimal(minor: number, currencyCode?: string): string;
116
- /**
117
- * Refuse to mint an intent unless the assurance is fresh and its declared
118
- * scope matches the checkout target exactly. `now` is injectable so the
119
- * freshness rules are testable with a pinned clock (same pattern as
120
- * validateCredential).
121
- */
122
- export declare function validatePurchaseAssurance(value: PurchaseAssurance, target: VgsCheckoutTarget, now?: Date): void;
123
- export declare function validateCredential(value: VgsPaymentCredential, now?: Date): void;
124
- /**
125
- * Mints the full DPAN + short DAVV only after the executor revalidates the
126
- * reviewed merchant, amount, and currency. The payment credential remains in
127
- * memory, is never returned to the caller, and can be requested only once.
128
- */
129
- export declare class VgsLiveInstrument implements Instrument {
130
- private readonly reference;
131
- private readonly cardholderName;
132
- private readonly fetchCredential;
133
- readonly kind: "agentic-token";
134
- private used;
135
- private minted;
136
- constructor(reference: VgsCheckoutReference, cardholderName: string, fetchCredential: FetchVgsPaymentCredential);
137
- /**
138
- * Non-null once VGS has actually issued a credential (the intent is consumed
139
- * from that moment, even if local validation later rejects the credential) —
140
- * exactly the population a VIC confirmation can be owed for.
141
- */
142
- confirmationTarget(): VicConfirmationTarget | null;
143
- getCredential(ctx: InstrumentContext): Promise<CardCredential>;
144
- }