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

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 (58) hide show
  1. package/dist/checkout-engine/adapters/generic.d.ts +19 -0
  2. package/dist/checkout-engine/adapters/generic.js +201 -0
  3. package/dist/checkout-engine/adapters/index.d.ts +7 -0
  4. package/dist/checkout-engine/adapters/index.js +17 -0
  5. package/dist/checkout-engine/adapters/stripe-like.d.ts +10 -0
  6. package/dist/checkout-engine/adapters/stripe-like.js +21 -0
  7. package/dist/checkout-engine/browser-launch.d.ts +46 -0
  8. package/dist/checkout-engine/browser-launch.js +81 -0
  9. package/dist/checkout-engine/ceremony.d.ts +64 -0
  10. package/dist/checkout-engine/ceremony.js +261 -0
  11. package/dist/checkout-engine/cli-engine.d.ts +60 -0
  12. package/dist/checkout-engine/cli-engine.js +225 -0
  13. package/dist/checkout-engine/detect.d.ts +61 -0
  14. package/dist/checkout-engine/detect.js +372 -0
  15. package/dist/checkout-engine/evidence.d.ts +22 -0
  16. package/dist/checkout-engine/evidence.js +59 -0
  17. package/dist/checkout-engine/executor.d.ts +147 -0
  18. package/dist/checkout-engine/executor.js +1187 -0
  19. package/dist/checkout-engine/hosted-approval.d.ts +69 -0
  20. package/dist/checkout-engine/hosted-approval.js +159 -0
  21. package/dist/checkout-engine/index.d.ts +3 -0
  22. package/dist/checkout-engine/index.js +5 -0
  23. package/dist/checkout-engine/inline-target.d.ts +13 -0
  24. package/dist/checkout-engine/inline-target.js +37 -0
  25. package/dist/checkout-engine/instrument.d.ts +54 -0
  26. package/dist/checkout-engine/instrument.js +83 -0
  27. package/dist/checkout-engine/live-fill-approval.d.ts +52 -0
  28. package/dist/checkout-engine/live-fill-approval.js +107 -0
  29. package/dist/checkout-engine/mandate.d.ts +25 -0
  30. package/dist/checkout-engine/mandate.js +100 -0
  31. package/dist/checkout-engine/outcome.d.ts +30 -0
  32. package/dist/checkout-engine/outcome.js +190 -0
  33. package/dist/checkout-engine/owner-only-file.d.ts +10 -0
  34. package/dist/checkout-engine/owner-only-file.js +22 -0
  35. package/dist/checkout-engine/package.json +3 -0
  36. package/dist/checkout-engine/pay-args.d.ts +14 -0
  37. package/dist/checkout-engine/pay-args.js +44 -0
  38. package/dist/checkout-engine/pay.d.ts +1 -0
  39. package/dist/checkout-engine/pay.js +13 -0
  40. package/dist/checkout-engine/receipt.d.ts +81 -0
  41. package/dist/checkout-engine/receipt.js +109 -0
  42. package/dist/checkout-engine/repo-env.d.ts +11 -0
  43. package/dist/checkout-engine/repo-env.js +23 -0
  44. package/dist/checkout-engine/run-live-fill.d.ts +1 -0
  45. package/dist/checkout-engine/run-live-fill.js +443 -0
  46. package/dist/checkout-engine/types.d.ts +26 -0
  47. package/dist/checkout-engine/types.js +2 -0
  48. package/dist/checkout-engine/vgs-gateway/fetch-credential.d.mts +74 -0
  49. package/dist/checkout-engine/vgs-gateway/fetch-credential.mjs +240 -0
  50. package/dist/checkout-engine/vgs-live-instrument.d.ts +141 -0
  51. package/dist/checkout-engine/vgs-live-instrument.js +252 -0
  52. package/dist/checkout-engine/vic-confirmation.d.ts +34 -0
  53. package/dist/checkout-engine/vic-confirmation.js +39 -0
  54. package/dist/cli.js +219 -219
  55. package/dist/mcp-server/index.js +103 -103
  56. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  57. package/package.json +4 -3
  58. package/server.json +2 -2
@@ -0,0 +1,240 @@
1
+ // Real credential fetch — NO mocks. Calls the live VGS agentic gateway to mint a
2
+ // fresh, intent-scoped payment credential (DPAN + expiry + the 3-digit DAVV) and
3
+ // returns it in memory. Same wire calls the enrollment harness (../server-e2e.mjs)
4
+ // uses; this just returns the FULL values (for the form-filler) instead of masking.
5
+ //
6
+ // Nothing here persists or logs the credential — it is returned to the caller
7
+ // (fillCheckout), and must never be written to disk or passed through an
8
+ // LLM/agent context.
9
+ //
10
+ // Requires env: VGS_USERNAME, VGS_PASSWORD (the VGS service-account client id/secret),
11
+ // and either VGS_ENVIRONMENT=live (+ optional VGS_GATEWAY_URL) or sandbox.
12
+
13
+ const TOKEN_URL = 'https://auth.verygoodsecurity.com/auth/realms/vgs/protocol/openid-connect/token'
14
+
15
+ function gatewayBase(env = process.env) {
16
+ if (env.VGS_GATEWAY_URL) return env.VGS_GATEWAY_URL.replace(/\/$/, '')
17
+ return env.VGS_ENVIRONMENT === 'live'
18
+ ? 'https://gw-01-live.vgsapi.com'
19
+ : 'https://gw-01-sandbox.vgsapi.com'
20
+ }
21
+
22
+ async function mintOauthToken(env = process.env) {
23
+ const clientId = env.VGS_USERNAME
24
+ const clientSecret = env.VGS_PASSWORD
25
+ if (!clientId || !clientSecret) {
26
+ throw new Error('Set VGS_USERNAME and VGS_PASSWORD (the VGS service-account client id/secret).')
27
+ }
28
+ const body = new URLSearchParams({
29
+ client_id: clientId,
30
+ client_secret: clientSecret,
31
+ grant_type: 'client_credentials',
32
+ })
33
+ const r = await fetch(TOKEN_URL, {
34
+ method: 'POST',
35
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
36
+ body,
37
+ })
38
+ if (!r.ok) throw new Error(`VGS token grant failed (${r.status}).`)
39
+ return (await r.json()).access_token
40
+ }
41
+
42
+ async function postJsonApi(url, type, attributes, env = process.env) {
43
+ const token = await mintOauthToken(env)
44
+ const r = await fetch(url, {
45
+ method: 'POST',
46
+ headers: {
47
+ Authorization: `Bearer ${token}`,
48
+ 'Content-Type': 'application/vnd.api+json',
49
+ },
50
+ body: JSON.stringify({ data: { ...(type ? { type } : {}), attributes } }),
51
+ })
52
+ const text = await r.text()
53
+ let doc = {}
54
+ try {
55
+ doc = JSON.parse(text)
56
+ } catch {
57
+ /* non-json error body */
58
+ }
59
+ // Support trace handles VGS asked for on the #5713 decline thread: trace_id
60
+ // keys the request on VGS's side, network_correlation_id on the Visa network
61
+ // side. Routing metadata only — never credential material — and logged even
62
+ // on error responses so any run stays traceable after the fact.
63
+ const obs = doc?.meta?.observability
64
+ if (obs && typeof obs === 'object') {
65
+ console.info(
66
+ JSON.stringify({
67
+ op: 'vgs_observability',
68
+ type,
69
+ status: r.status,
70
+ trace_id: obs.trace_id,
71
+ vault_id: obs.vault_id,
72
+ network_correlation_id: obs.network_correlation_id,
73
+ })
74
+ )
75
+ }
76
+ if (!r.ok) {
77
+ // Never echo the full body (can carry ids); surface status + a short detail.
78
+ const detail = doc?.errors?.[0]?.detail || doc?.errors?.[0]?.title || ''
79
+ throw new Error(`VGS ${type} POST failed (${r.status})${detail ? `: ${detail}` : ''}.`)
80
+ }
81
+ return doc
82
+ }
83
+
84
+ const txnData = (t) => [
85
+ {
86
+ merchant_name: t.merchantName,
87
+ merchant_url: t.merchantUrl,
88
+ merchant_country_code: t.merchantCountryCode,
89
+ transaction_amount: {
90
+ transaction_amount: t.transactionAmount,
91
+ transaction_currency_code: t.transactionCurrencyCode,
92
+ },
93
+ },
94
+ ]
95
+
96
+ /**
97
+ * Create a fresh intent scoped to `transaction`, bound to the passkey assurance.
98
+ * Needs `assuranceData` from a device-binding passkey ceremony run for THIS
99
+ * purchase (merchant + amount + currency aligned) — replaying enrollment-time
100
+ * assurance mints an intent that 201s but whose cryptogram never completes
101
+ * (#5709, confirmed live 2026-07-17).
102
+ * @returns {Promise<{intentId: string, status: string | null}>} the fresh
103
+ * intent id plus the creation-time status attribute (null when VGS omits it) —
104
+ * callers surface the status when a later cryptogram fails, since HTTP 201
105
+ * alone does not mean the intent is authorized.
106
+ */
107
+ export async function createIntent({ tokenId, assuranceData, transaction }, env = process.env) {
108
+ const effectiveUntil = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString()
109
+ const cap = Math.max(Math.ceil(Number(transaction.transactionAmount) || 0) + 10, 25)
110
+ const doc = await postJsonApi(
111
+ `${gatewayBase(env)}/agentic-tokens/${encodeURIComponent(tokenId)}/intents`,
112
+ 'intents',
113
+ {
114
+ consumer_prompt: `Buy an item from ${transaction.merchantName} for ${transaction.transactionCurrencyCode} ${transaction.transactionAmount}`,
115
+ assurance_data: assuranceData,
116
+ mandates: [
117
+ {
118
+ description: `Purchase at ${transaction.merchantName}`,
119
+ decline_threshold: { amount: cap, currency_code: transaction.transactionCurrencyCode },
120
+ effective_until: effectiveUntil,
121
+ merchant_category: 'Retail',
122
+ merchant_category_code: '5999',
123
+ preferred_merchant_name: transaction.merchantName,
124
+ quantity: 1,
125
+ },
126
+ ],
127
+ },
128
+ env
129
+ )
130
+ const intentId = doc.data?.id
131
+ if (!intentId) throw new Error('createIntent: response missing data.id')
132
+ const status = doc.data?.attributes?.status
133
+ return { intentId, status: typeof status === 'string' && status ? status : null }
134
+ }
135
+
136
+ /**
137
+ * Mint the FULL payment credential for an existing intent. Real VGS call — the
138
+ * DAVV is single-use and expires in hours, so call this immediately before fill.
139
+ * @returns {Promise<{networkToken,expMonth,expYear,cryptogramType,cryptogramValue}>}
140
+ */
141
+ export async function fetchCryptogram({ tokenId, intentId, transaction }, env = process.env) {
142
+ // Intent approval can be asynchronous on live: creation returns PENDING and
143
+ // the first cryptogram answer can be PENDING too (observed 2026-07-17,
144
+ // donate.stripe.com run). Poll briefly on PENDING only — every other
145
+ // non-COMPLETED status still fails fast on the first answer. Both knobs are
146
+ // env-tunable (and injectable for tests, which must not sleep wall-clock).
147
+ const PENDING_ATTEMPTS = Math.max(1, Number(env.VGS_CRYPTOGRAM_PENDING_ATTEMPTS) || 4)
148
+ const PENDING_WAIT_MS = Number.isFinite(Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS))
149
+ ? Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS)
150
+ : 5000
151
+ let a = {}
152
+ for (let attempt = 1; ; attempt++) {
153
+ const doc = await postJsonApi(
154
+ `${gatewayBase(env)}/agentic-tokens/${encodeURIComponent(tokenId)}/intents/${encodeURIComponent(intentId)}/cryptograms`,
155
+ 'cryptograms',
156
+ { transaction_data: txnData(transaction) },
157
+ env
158
+ )
159
+ a = doc.data?.attributes ?? {}
160
+ const s = typeof a.status === 'string' ? a.status.toUpperCase() : ''
161
+ if (s !== 'PENDING' || attempt >= PENDING_ATTEMPTS) break
162
+ console.info(
163
+ JSON.stringify({ op: 'cryptogram_pending_retry', attempt, waitMs: PENDING_WAIT_MS })
164
+ )
165
+ await new Promise((resolve) => setTimeout(resolve, PENDING_WAIT_MS))
166
+ }
167
+ // A network_token can come back while the cryptogram is still pending/failed —
168
+ // mirror lib/server/vgs.ts and reject anything not COMPLETED, so we never key a
169
+ // not-yet-valid credential (which would decline and read as a fill bug).
170
+ const status = a.status
171
+ if (typeof status === 'string' && status && status.toUpperCase() !== 'COMPLETED') {
172
+ throw new Error(`cryptogram not completed (status ${status})`)
173
+ }
174
+ const networkToken = a.network_token
175
+ const value = a.cryptogram?.value
176
+ if (typeof networkToken !== 'string' || !networkToken) {
177
+ throw new Error('cryptogram response missing network_token')
178
+ }
179
+ if (typeof value !== 'string' || !value) {
180
+ throw new Error('cryptogram response missing cryptogram value')
181
+ }
182
+ return {
183
+ networkToken,
184
+ expMonth: typeof a.exp_month === 'number' ? a.exp_month : Number(a.exp_month) || 0,
185
+ expYear: typeof a.exp_year === 'number' ? a.exp_year : Number(a.exp_year) || 0,
186
+ cryptogramType: a.cryptogram?.type ?? '',
187
+ cryptogramValue: value,
188
+ cryptogramExpiresAt:
189
+ typeof a.cryptogram?.expires_at === 'string' ? a.cryptogram.expires_at : undefined,
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Full path: create the intent (needs fresh passkey assurance) then mint the
195
+ * credential. Use fetchCryptogram directly if you already have an intentId.
196
+ */
197
+ export async function getCredential({ tokenId, assuranceData, transaction }, env = process.env) {
198
+ const { intentId, status } = await createIntent({ tokenId, assuranceData, transaction }, env)
199
+ try {
200
+ return await fetchCryptogram({ tokenId, intentId, transaction }, env)
201
+ } catch (err) {
202
+ // HTTP 201 on intent creation does not mean the intent was authorized —
203
+ // surface its creation-time status so a not-completed cryptogram is
204
+ // diagnosable (#5709) instead of an opaque failure.
205
+ throw new Error(`${err.message} (intent status at creation: ${status ?? 'unknown'})`)
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Report the observed merchant outcome back to VIC for a consumed intent.
211
+ * Mirrors lib/server/vgs.ts postConfirmation exactly: same endpoint, same
212
+ * JSON:API envelope, and the guide's quoted Unix-epoch-seconds timestamp
213
+ * (callers pass ISO 8601; converted here).
214
+ */
215
+ export async function postConfirmation(
216
+ { tokenId, intentId, transactionStatus, transactionType, transactionTimestamp, transaction },
217
+ env = process.env
218
+ ) {
219
+ await postJsonApi(
220
+ `${gatewayBase(env)}/agentic-tokens/${encodeURIComponent(tokenId)}/intents/${encodeURIComponent(intentId)}/confirmations`,
221
+ 'confirmations',
222
+ {
223
+ confirmation_data: [
224
+ {
225
+ payment_confirmation_data: {
226
+ transaction_status: transactionStatus,
227
+ transaction_type: transactionType,
228
+ transaction_timestamp: String(Math.floor(Date.parse(transactionTimestamp) / 1000)),
229
+ transaction_amount: {
230
+ transaction_amount: transaction.transactionAmount,
231
+ transaction_currency_code: transaction.transactionCurrencyCode,
232
+ },
233
+ },
234
+ },
235
+ ],
236
+ },
237
+ env
238
+ )
239
+ return { ok: true }
240
+ }
@@ -0,0 +1,141 @@
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
+ };
61
+ export type FetchVgsPaymentCredential = (input: {
62
+ tokenId: string;
63
+ intentId: string;
64
+ transaction: {
65
+ merchantName: string;
66
+ merchantUrl: string;
67
+ merchantCountryCode: string;
68
+ transactionAmount: string;
69
+ transactionCurrencyCode: string;
70
+ };
71
+ }) => Promise<VgsPaymentCredential>;
72
+ export type MintFreshVgsPaymentCredential = (input: {
73
+ tokenId: string;
74
+ assuranceData: unknown;
75
+ transaction: VgsCheckoutTarget;
76
+ }) => Promise<{
77
+ payment: VgsPaymentCredential;
78
+ intentId: string;
79
+ }>;
80
+ /** The (token, intent) pair a VIC confirmation is posted against. */
81
+ export type VicConfirmationTarget = {
82
+ tokenId: string;
83
+ intentId: string;
84
+ };
85
+ export declare function decimalToMinor(value: unknown): number | null;
86
+ /**
87
+ * Refuse to mint an intent unless the assurance is fresh and its declared
88
+ * scope matches the checkout target exactly. `now` is injectable so the
89
+ * freshness rules are testable with a pinned clock (same pattern as
90
+ * validateCredential).
91
+ */
92
+ export declare function validatePurchaseAssurance(value: PurchaseAssurance, target: VgsCheckoutTarget, now?: Date): void;
93
+ export declare function validateCredential(value: VgsPaymentCredential, now?: Date): void;
94
+ /**
95
+ * Mints the full DPAN + short DAVV only after the executor revalidates the
96
+ * reviewed merchant, amount, and currency. The payment credential remains in
97
+ * memory, is never returned to the caller, and can be requested only once.
98
+ */
99
+ export declare class VgsLiveInstrument implements Instrument {
100
+ private readonly reference;
101
+ private readonly cardholderName;
102
+ private readonly fetchCredential;
103
+ readonly kind: "agentic-token";
104
+ private used;
105
+ private minted;
106
+ constructor(reference: VgsCheckoutReference, cardholderName: string, fetchCredential: FetchVgsPaymentCredential);
107
+ /**
108
+ * Non-null once VGS has actually issued a credential (the intent is consumed
109
+ * from that moment, even if local validation later rejects the credential) —
110
+ * exactly the population a VIC confirmation can be owed for.
111
+ */
112
+ confirmationTarget(): VicConfirmationTarget | null;
113
+ getCredential(ctx: InstrumentContext): Promise<CardCredential>;
114
+ }
115
+ /**
116
+ * Consumes #5614's claimed CLI enrollment artifact (for the tokenId) plus a
117
+ * FRESH purchase-scoped assurance, and creates a fresh, transaction-scoped VIC
118
+ * intent + credential after checkout approval. This is the production-shaped
119
+ * bridge; unlike VgsLiveInstrument it never needs a pre-created intent ID.
120
+ *
121
+ * The enrollment artifact's stored assuranceData is deliberately never sent:
122
+ * replaying it makes intent creation succeed (HTTP 201) while the cryptogram
123
+ * deterministically never completes — the #5709 dead end. Purchase
124
+ * authorization is the fresh, merchant+amount+currency-scoped assurance,
125
+ * validated against the checkout target BEFORE any intent is minted so a
126
+ * doomed intent is never created.
127
+ */
128
+ export declare class VgsAssuranceInstrument implements Instrument {
129
+ private readonly enrollment;
130
+ private readonly purchase;
131
+ private readonly target;
132
+ private readonly cardholderName;
133
+ private readonly mintCredential;
134
+ readonly kind: "agentic-token";
135
+ private used;
136
+ private minted;
137
+ constructor(enrollment: CliAgentCredential, purchase: PurchaseAssurance, target: VgsCheckoutTarget, cardholderName: string, mintCredential: MintFreshVgsPaymentCredential);
138
+ /** See VgsLiveInstrument.confirmationTarget — same contract. */
139
+ confirmationTarget(): VicConfirmationTarget | null;
140
+ getCredential(ctx: InstrumentContext): Promise<CardCredential>;
141
+ }
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Our fail-closed freshness bound, matching the runner's 15-minute checkout
3
+ * review window — NOT a claim about VGS's actual assurance TTL (unpublished).
4
+ * The only proven-working configuration mints the intent right after the
5
+ * ceremony; anything older is refused before an intent is created.
6
+ */
7
+ export const PURCHASE_ASSURANCE_MAX_AGE_MS = 15 * 60 * 1000;
8
+ /** Tolerated forward clock skew on `mintedAt` before it is treated as invalid. */
9
+ const PURCHASE_ASSURANCE_MAX_SKEW_MS = 2 * 60 * 1000;
10
+ export function decimalToMinor(value) {
11
+ // JSON files routinely carry a number where the contract says decimal string
12
+ // ("transactionAmount": 5): refuse non-strings HERE so every caller surfaces
13
+ // its scoped invalid/mismatch remedy instead of a raw TypeError crash.
14
+ if (typeof value !== 'string')
15
+ return null;
16
+ if (!/^\d+(\.\d{1,2})?$/.test(value))
17
+ return null;
18
+ const [whole, fraction = ''] = value.split('.');
19
+ const minor = Number(whole) * 100 + Number(fraction.padEnd(2, '0'));
20
+ return Number.isSafeInteger(minor) ? minor : null;
21
+ }
22
+ function validateTarget(reference, ctx) {
23
+ if (typeof reference.merchantName !== 'string' ||
24
+ typeof reference.merchantCountryCode !== 'string' ||
25
+ !reference.merchantName.trim() ||
26
+ !/^[A-Z]{2}$/.test(reference.merchantCountryCode)) {
27
+ throw new Error('VGS checkout reference merchant name/country is invalid');
28
+ }
29
+ let referenceHost;
30
+ try {
31
+ referenceHost = new URL(reference.merchantUrl).hostname;
32
+ }
33
+ catch {
34
+ throw new Error('VGS checkout reference merchant URL is invalid');
35
+ }
36
+ if (referenceHost !== ctx.merchantHost) {
37
+ throw new Error(`VGS credential merchant mismatch: ${referenceHost} vs ${ctx.merchantHost}`);
38
+ }
39
+ const amountMinor = decimalToMinor(reference.transactionAmount);
40
+ if (amountMinor === null)
41
+ throw new Error('VGS checkout reference amount is invalid');
42
+ if (amountMinor !== ctx.amountMinor) {
43
+ throw new Error(`VGS credential amount mismatch: ${amountMinor} vs ${ctx.amountMinor} minor units`);
44
+ }
45
+ // String() so a JSON-number currency (840) mismatches with a readable
46
+ // message instead of crashing on .toUpperCase().
47
+ const currency = String(reference.transactionCurrencyCode).toUpperCase();
48
+ if (currency !== ctx.currency) {
49
+ throw new Error(`VGS credential currency mismatch: ${currency} vs ${ctx.currency}`);
50
+ }
51
+ }
52
+ function validateCliCredential(value) {
53
+ if (typeof value.tokenId !== 'string' || !value.tokenId.trim()) {
54
+ throw new Error('CLI agent credential requires tokenId');
55
+ }
56
+ // Deliberately no assuranceData requirement: the artifact's enrollment-time
57
+ // assurance is identity/enrollment material and is never read here (#5709).
58
+ }
59
+ /**
60
+ * Refuse to mint an intent unless the assurance is fresh and its declared
61
+ * scope matches the checkout target exactly. `now` is injectable so the
62
+ * freshness rules are testable with a pinned clock (same pattern as
63
+ * validateCredential).
64
+ */
65
+ export function validatePurchaseAssurance(value, target, now = new Date()) {
66
+ const remedy = 'run a fresh device-binding ceremony scoped to this exact merchant, amount, and ' +
67
+ 'currency, and pass its output via --purchase-assurance-file (#5709)';
68
+ if (value == null || typeof value !== 'object') {
69
+ throw new Error(`purchase assurance is missing — ${remedy}`);
70
+ }
71
+ if (value.assuranceData == null) {
72
+ throw new Error(`purchase assurance requires assuranceData — ${remedy}`);
73
+ }
74
+ const mintedAtMs = typeof value.mintedAt === 'string' ? Date.parse(value.mintedAt) : NaN;
75
+ if (!Number.isFinite(mintedAtMs)) {
76
+ throw new Error(`purchase assurance requires an ISO 8601 mintedAt — ${remedy}`);
77
+ }
78
+ const age = now.getTime() - mintedAtMs;
79
+ if (age < -PURCHASE_ASSURANCE_MAX_SKEW_MS) {
80
+ throw new Error(`purchase assurance mintedAt is in the future — ${remedy}`);
81
+ }
82
+ if (age > PURCHASE_ASSURANCE_MAX_AGE_MS) {
83
+ throw new Error(`purchase assurance is stale (minted ${value.mintedAt}, limit ` +
84
+ `${PURCHASE_ASSURANCE_MAX_AGE_MS / 60000} minutes) — ${remedy}`);
85
+ }
86
+ let targetHost;
87
+ try {
88
+ targetHost = new URL(target.merchantUrl).hostname;
89
+ }
90
+ catch {
91
+ throw new Error('VGS checkout reference merchant URL is invalid');
92
+ }
93
+ if (value.merchantHost !== targetHost) {
94
+ throw new Error(`purchase assurance merchant mismatch: ${value.merchantHost} vs ${targetHost} — ${remedy}`);
95
+ }
96
+ const assuranceMinor = decimalToMinor(value.transactionAmount);
97
+ const targetMinor = decimalToMinor(target.transactionAmount);
98
+ if (assuranceMinor === null || assuranceMinor !== targetMinor) {
99
+ throw new Error(`purchase assurance amount mismatch: ${value.transactionAmount} vs ` +
100
+ `${target.transactionAmount} — ${remedy}`);
101
+ }
102
+ if (typeof value.transactionCurrencyCode !== 'string' ||
103
+ value.transactionCurrencyCode.toUpperCase() !==
104
+ String(target.transactionCurrencyCode).toUpperCase()) {
105
+ throw new Error(`purchase assurance currency mismatch: ${value.transactionCurrencyCode} vs ` +
106
+ `${target.transactionCurrencyCode} — ${remedy}`);
107
+ }
108
+ }
109
+ // `now` is injectable so expiry rules are testable with a pinned clock.
110
+ export function validateCredential(value, now = new Date()) {
111
+ if (!/^\d{12,19}$/.test(value.networkToken)) {
112
+ throw new Error('VGS credential network token must contain 12-19 digits');
113
+ }
114
+ if (!/^\d{3,4}$/.test(value.cryptogramValue)) {
115
+ throw new Error('VGS credential short DAVV must contain 3-4 digits');
116
+ }
117
+ if (typeof value.cryptogramType !== 'string' || value.cryptogramType.toUpperCase() !== 'DAVV') {
118
+ throw new Error(`VGS credential type ${value.cryptogramType || '<missing>'} is not DAVV`);
119
+ }
120
+ if (!Number.isInteger(value.expMonth) || value.expMonth < 1 || value.expMonth > 12) {
121
+ throw new Error('VGS credential expiration month is invalid');
122
+ }
123
+ if (!Number.isInteger(value.expYear) ||
124
+ value.expYear < now.getFullYear() ||
125
+ (value.expYear === now.getFullYear() && value.expMonth < now.getMonth() + 1)) {
126
+ throw new Error('VGS credential is expired');
127
+ }
128
+ if (value.cryptogramExpiresAt !== undefined) {
129
+ const expiresAtMs = Date.parse(value.cryptogramExpiresAt);
130
+ if (!Number.isFinite(expiresAtMs))
131
+ throw new Error('VGS credential expiry is invalid');
132
+ if (expiresAtMs - now.getTime() < 60_000) {
133
+ throw new Error('VGS credential has less than 60 seconds of validity remaining');
134
+ }
135
+ }
136
+ }
137
+ /**
138
+ * Mints the full DPAN + short DAVV only after the executor revalidates the
139
+ * reviewed merchant, amount, and currency. The payment credential remains in
140
+ * memory, is never returned to the caller, and can be requested only once.
141
+ */
142
+ export class VgsLiveInstrument {
143
+ reference;
144
+ cardholderName;
145
+ fetchCredential;
146
+ kind = 'agentic-token';
147
+ used = false;
148
+ minted = null;
149
+ constructor(reference, cardholderName, fetchCredential) {
150
+ this.reference = reference;
151
+ this.cardholderName = cardholderName;
152
+ this.fetchCredential = fetchCredential;
153
+ }
154
+ /**
155
+ * Non-null once VGS has actually issued a credential (the intent is consumed
156
+ * from that moment, even if local validation later rejects the credential) —
157
+ * exactly the population a VIC confirmation can be owed for.
158
+ */
159
+ confirmationTarget() {
160
+ return this.minted;
161
+ }
162
+ async getCredential(ctx) {
163
+ if (this.used)
164
+ throw new Error('VGS live credential instrument is single-use');
165
+ this.used = true;
166
+ validateTarget(this.reference, ctx);
167
+ if (!this.reference.tokenId || !this.reference.intentId) {
168
+ throw new Error('VGS checkout reference requires tokenId and intentId');
169
+ }
170
+ if (!this.cardholderName.trim())
171
+ throw new Error('cardholder name is required');
172
+ const { tokenId, intentId, ...transaction } = this.reference;
173
+ const value = await this.fetchCredential({ tokenId, intentId, transaction });
174
+ this.minted = { tokenId, intentId };
175
+ try {
176
+ validateCredential(value);
177
+ }
178
+ catch (err) {
179
+ // VGS already issued a cryptogram for this intent even though we refuse
180
+ // to fill it; "correct inputs and retry" would silently reuse a consumed
181
+ // intent, so steer the operator to a fresh one.
182
+ throw new Error(`${err.message} — a credential was issued by VGS but rejected locally; obtain a fresh intent before retrying`);
183
+ }
184
+ return {
185
+ pan: value.networkToken,
186
+ expMonth: value.expMonth,
187
+ expYear: value.expYear,
188
+ cvc: value.cryptogramValue,
189
+ cardholderName: this.cardholderName.trim(),
190
+ ...(value.cryptogramExpiresAt ? { credentialExpiresAt: value.cryptogramExpiresAt } : {}),
191
+ };
192
+ }
193
+ }
194
+ /**
195
+ * Consumes #5614's claimed CLI enrollment artifact (for the tokenId) plus a
196
+ * FRESH purchase-scoped assurance, and creates a fresh, transaction-scoped VIC
197
+ * intent + credential after checkout approval. This is the production-shaped
198
+ * bridge; unlike VgsLiveInstrument it never needs a pre-created intent ID.
199
+ *
200
+ * The enrollment artifact's stored assuranceData is deliberately never sent:
201
+ * replaying it makes intent creation succeed (HTTP 201) while the cryptogram
202
+ * deterministically never completes — the #5709 dead end. Purchase
203
+ * authorization is the fresh, merchant+amount+currency-scoped assurance,
204
+ * validated against the checkout target BEFORE any intent is minted so a
205
+ * doomed intent is never created.
206
+ */
207
+ export class VgsAssuranceInstrument {
208
+ enrollment;
209
+ purchase;
210
+ target;
211
+ cardholderName;
212
+ mintCredential;
213
+ kind = 'agentic-token';
214
+ used = false;
215
+ minted = null;
216
+ constructor(enrollment, purchase, target, cardholderName, mintCredential) {
217
+ this.enrollment = enrollment;
218
+ this.purchase = purchase;
219
+ this.target = target;
220
+ this.cardholderName = cardholderName;
221
+ this.mintCredential = mintCredential;
222
+ }
223
+ /** See VgsLiveInstrument.confirmationTarget — same contract. */
224
+ confirmationTarget() {
225
+ return this.minted;
226
+ }
227
+ async getCredential(ctx) {
228
+ if (this.used)
229
+ throw new Error('VGS assurance instrument is single-use');
230
+ this.used = true;
231
+ validateCliCredential(this.enrollment);
232
+ validateTarget(this.target, ctx);
233
+ validatePurchaseAssurance(this.purchase, this.target);
234
+ if (!this.cardholderName.trim())
235
+ throw new Error('cardholder name is required');
236
+ const { payment: value, intentId } = await this.mintCredential({
237
+ tokenId: this.enrollment.tokenId,
238
+ assuranceData: this.purchase.assuranceData,
239
+ transaction: this.target,
240
+ });
241
+ this.minted = { tokenId: this.enrollment.tokenId, intentId };
242
+ validateCredential(value);
243
+ return {
244
+ pan: value.networkToken,
245
+ expMonth: value.expMonth,
246
+ expYear: value.expYear,
247
+ cvc: value.cryptogramValue,
248
+ cardholderName: this.cardholderName.trim(),
249
+ ...(value.cryptogramExpiresAt ? { credentialExpiresAt: value.cryptogramExpiresAt } : {}),
250
+ };
251
+ }
252
+ }
@@ -0,0 +1,34 @@
1
+ import type { CheckoutOutcome } from './executor.js';
2
+ import type { VicConfirmationTarget } from './vgs-live-instrument.js';
3
+ export type VicTransactionStatus = 'APPROVED' | 'DECLINED';
4
+ export type PostVicConfirmation = (input: {
5
+ tokenId: string;
6
+ intentId: string;
7
+ transactionStatus: VicTransactionStatus;
8
+ transactionType: 'PURCHASE';
9
+ transactionTimestamp: string;
10
+ transaction: {
11
+ transactionAmount: string;
12
+ transactionCurrencyCode: string;
13
+ };
14
+ }) => Promise<unknown>;
15
+ export type VicConfirmationReport = {
16
+ posted: true;
17
+ transactionStatus: VicTransactionStatus;
18
+ } | {
19
+ posted: false;
20
+ reason: string;
21
+ };
22
+ /** Definitive merchant answers map to a status; everything else maps to none. */
23
+ export declare function outcomeToTransactionStatus(outcome: CheckoutOutcome): VicTransactionStatus | null;
24
+ export declare function reportVicOutcome(input: {
25
+ target: VicConfirmationTarget | null;
26
+ outcome: CheckoutOutcome;
27
+ transaction: {
28
+ transactionAmount: string;
29
+ transactionCurrencyCode: string;
30
+ };
31
+ post: PostVicConfirmation;
32
+ /** Injectable for tests; defaults to now. */
33
+ timestamp?: Date;
34
+ }): Promise<VicConfirmationReport>;