@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,179 @@
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
+ export type MintFreshVgsPaymentCredential = (input: {
84
+ tokenId: string;
85
+ assuranceData: unknown;
86
+ transaction: VgsCheckoutTarget;
87
+ }) => Promise<{
88
+ payment: VgsPaymentCredential;
89
+ intentId: string;
90
+ }>;
91
+ /** The (token, intent) pair a VIC confirmation is posted against. */
92
+ export type VicConfirmationTarget = {
93
+ tokenId: string;
94
+ intentId: string;
95
+ };
96
+ export declare function decimalToMinor(value: unknown): number | null;
97
+ /**
98
+ * Currencies whose minor unit is 1/100 of the major unit (2 decimal places).
99
+ * minorToDecimal's /100 + pad-to-2 rendering is ONLY correct for these. The
100
+ * card mandate path accepts any 3-letter ISO code, so a 0- or 3-decimal
101
+ * currency (JPY, BHD, …) would otherwise be emitted with a wrong wire amount.
102
+ * We only support USD/USDC today; extend deliberately (and fix the exponent)
103
+ * before adding any non-2-decimal currency.
104
+ *
105
+ * NOTE (scanner FP pre-empt): this is a CLIENT-SIDE currency-exponent lookup for
106
+ * rendering a wire amount in @visa/checkout-engine — it is NOT the cross-store
107
+ * `PAYMENT_CURRENCIES` enum governed by apps/auth/src/shared-validators.ts, and
108
+ * this package cannot import from apps/auth (no dependency edge). It intentionally
109
+ * does not mirror that enum's membership; do not "reconcile" the two.
110
+ */
111
+ export declare const TWO_DECIMAL_CURRENCIES: Set<string>;
112
+ /**
113
+ * Inverse of decimalToMinor: render integer minor units as a major-unit decimal
114
+ * string ("D.DD") for the VGS wire (e.g. a ceiling of 50000 minor → "500.00").
115
+ * Integer-only; never floating-point money. Throws on a non-integer/negative so
116
+ * a bad accounting value cannot silently reach the network.
117
+ *
118
+ * The /100 + pad-to-2 rendering assumes a 2-decimal (exponent-2) currency. Pass
119
+ * `currencyCode` on any path that accepts arbitrary currencies (the mandate
120
+ * path) and it REFUSES a non-2-decimal currency rather than emit a wrong wire
121
+ * amount. Omit it only where the currency is already known to be USD/USDC.
122
+ */
123
+ export declare function minorToDecimal(minor: number, currencyCode?: string): string;
124
+ /**
125
+ * Refuse to mint an intent unless the assurance is fresh and its declared
126
+ * scope matches the checkout target exactly. `now` is injectable so the
127
+ * freshness rules are testable with a pinned clock (same pattern as
128
+ * validateCredential).
129
+ */
130
+ export declare function validatePurchaseAssurance(value: PurchaseAssurance, target: VgsCheckoutTarget, now?: Date): void;
131
+ export declare function validateCredential(value: VgsPaymentCredential, now?: Date): void;
132
+ /**
133
+ * Mints the full DPAN + short DAVV only after the executor revalidates the
134
+ * reviewed merchant, amount, and currency. The payment credential remains in
135
+ * memory, is never returned to the caller, and can be requested only once.
136
+ */
137
+ export declare class VgsLiveInstrument implements Instrument {
138
+ private readonly reference;
139
+ private readonly cardholderName;
140
+ private readonly fetchCredential;
141
+ readonly kind: "agentic-token";
142
+ private used;
143
+ private minted;
144
+ constructor(reference: VgsCheckoutReference, cardholderName: string, fetchCredential: FetchVgsPaymentCredential);
145
+ /**
146
+ * Non-null once VGS has actually issued a credential (the intent is consumed
147
+ * from that moment, even if local validation later rejects the credential) —
148
+ * exactly the population a VIC confirmation can be owed for.
149
+ */
150
+ confirmationTarget(): VicConfirmationTarget | null;
151
+ getCredential(ctx: InstrumentContext): Promise<CardCredential>;
152
+ }
153
+ /**
154
+ * Consumes #5614's claimed CLI enrollment artifact (for the tokenId) plus a
155
+ * FRESH purchase-scoped assurance, and creates a fresh, transaction-scoped VIC
156
+ * intent + credential after checkout approval. This is the production-shaped
157
+ * bridge; unlike VgsLiveInstrument it never needs a pre-created intent ID.
158
+ *
159
+ * The enrollment artifact's stored assuranceData is deliberately never sent:
160
+ * replaying it makes intent creation succeed (HTTP 201) while the cryptogram
161
+ * deterministically never completes — the #5709 dead end. Purchase
162
+ * authorization is the fresh, merchant+amount+currency-scoped assurance,
163
+ * validated against the checkout target BEFORE any intent is minted so a
164
+ * doomed intent is never created.
165
+ */
166
+ export declare class VgsAssuranceInstrument implements Instrument {
167
+ private readonly enrollment;
168
+ private readonly purchase;
169
+ private readonly target;
170
+ private readonly cardholderName;
171
+ private readonly mintCredential;
172
+ readonly kind: "agentic-token";
173
+ private used;
174
+ private minted;
175
+ constructor(enrollment: CliAgentCredential, purchase: PurchaseAssurance, target: VgsCheckoutTarget, cardholderName: string, mintCredential: MintFreshVgsPaymentCredential);
176
+ /** See VgsLiveInstrument.confirmationTarget — same contract. */
177
+ confirmationTarget(): VicConfirmationTarget | null;
178
+ getCredential(ctx: InstrumentContext): Promise<CardCredential>;
179
+ }
@@ -0,0 +1,296 @@
1
+ import { traceHandleFields } from './trace-handles.js';
2
+ /**
3
+ * Our fail-closed freshness bound, matching the runner's 15-minute checkout
4
+ * review window — NOT a claim about VGS's actual assurance TTL (unpublished).
5
+ * The only proven-working configuration mints the intent right after the
6
+ * ceremony; anything older is refused before an intent is created.
7
+ */
8
+ export const PURCHASE_ASSURANCE_MAX_AGE_MS = 15 * 60 * 1000;
9
+ /** Tolerated forward clock skew on `mintedAt` before it is treated as invalid. */
10
+ const PURCHASE_ASSURANCE_MAX_SKEW_MS = 2 * 60 * 1000;
11
+ export function decimalToMinor(value) {
12
+ // JSON files routinely carry a number where the contract says decimal string
13
+ // ("transactionAmount": 5): refuse non-strings HERE so every caller surfaces
14
+ // its scoped invalid/mismatch remedy instead of a raw TypeError crash.
15
+ if (typeof value !== 'string')
16
+ return null;
17
+ if (!/^\d+(\.\d{1,2})?$/.test(value))
18
+ return null;
19
+ const [whole, fraction = ''] = value.split('.');
20
+ const minor = Number(whole) * 100 + Number(fraction.padEnd(2, '0'));
21
+ return Number.isSafeInteger(minor) ? minor : null;
22
+ }
23
+ /**
24
+ * Currencies whose minor unit is 1/100 of the major unit (2 decimal places).
25
+ * minorToDecimal's /100 + pad-to-2 rendering is ONLY correct for these. The
26
+ * card mandate path accepts any 3-letter ISO code, so a 0- or 3-decimal
27
+ * currency (JPY, BHD, …) would otherwise be emitted with a wrong wire amount.
28
+ * We only support USD/USDC today; extend deliberately (and fix the exponent)
29
+ * before adding any non-2-decimal currency.
30
+ *
31
+ * NOTE (scanner FP pre-empt): this is a CLIENT-SIDE currency-exponent lookup for
32
+ * rendering a wire amount in @visa/checkout-engine — it is NOT the cross-store
33
+ * `PAYMENT_CURRENCIES` enum governed by apps/auth/src/shared-validators.ts, and
34
+ * this package cannot import from apps/auth (no dependency edge). It intentionally
35
+ * does not mirror that enum's membership; do not "reconcile" the two.
36
+ */
37
+ export const TWO_DECIMAL_CURRENCIES = new Set(['USD', 'USDC']);
38
+ /**
39
+ * Inverse of decimalToMinor: render integer minor units as a major-unit decimal
40
+ * string ("D.DD") for the VGS wire (e.g. a ceiling of 50000 minor → "500.00").
41
+ * Integer-only; never floating-point money. Throws on a non-integer/negative so
42
+ * a bad accounting value cannot silently reach the network.
43
+ *
44
+ * The /100 + pad-to-2 rendering assumes a 2-decimal (exponent-2) currency. Pass
45
+ * `currencyCode` on any path that accepts arbitrary currencies (the mandate
46
+ * path) and it REFUSES a non-2-decimal currency rather than emit a wrong wire
47
+ * amount. Omit it only where the currency is already known to be USD/USDC.
48
+ */
49
+ export function minorToDecimal(minor, currencyCode) {
50
+ if (!Number.isSafeInteger(minor) || minor < 0) {
51
+ throw new Error('minor units must be a non-negative safe integer');
52
+ }
53
+ if (currencyCode !== undefined && !TWO_DECIMAL_CURRENCIES.has(currencyCode.toUpperCase())) {
54
+ throw new Error(`minorToDecimal only supports 2-decimal currencies (${[...TWO_DECIMAL_CURRENCIES].join('/')}); refusing to emit a wire amount for ${currencyCode}`);
55
+ }
56
+ const whole = Math.floor(minor / 100);
57
+ const fraction = minor % 100;
58
+ return `${whole}.${String(fraction).padStart(2, '0')}`;
59
+ }
60
+ function validateTarget(reference, ctx) {
61
+ if (typeof reference.merchantName !== 'string' ||
62
+ typeof reference.merchantCountryCode !== 'string' ||
63
+ !reference.merchantName.trim() ||
64
+ !/^[A-Z]{2}$/.test(reference.merchantCountryCode)) {
65
+ throw new Error('VGS checkout reference merchant name/country is invalid');
66
+ }
67
+ let referenceHost;
68
+ try {
69
+ referenceHost = new URL(reference.merchantUrl).hostname;
70
+ }
71
+ catch {
72
+ throw new Error('VGS checkout reference merchant URL is invalid');
73
+ }
74
+ if (referenceHost !== ctx.merchantHost) {
75
+ throw new Error(`VGS credential merchant mismatch: ${referenceHost} vs ${ctx.merchantHost}`);
76
+ }
77
+ const amountMinor = decimalToMinor(reference.transactionAmount);
78
+ if (amountMinor === null)
79
+ throw new Error('VGS checkout reference amount is invalid');
80
+ if (amountMinor !== ctx.amountMinor) {
81
+ throw new Error(`VGS credential amount mismatch: ${amountMinor} vs ${ctx.amountMinor} minor units`);
82
+ }
83
+ // String() so a JSON-number currency (840) mismatches with a readable
84
+ // message instead of crashing on .toUpperCase().
85
+ const currency = String(reference.transactionCurrencyCode).toUpperCase();
86
+ if (currency !== ctx.currency) {
87
+ throw new Error(`VGS credential currency mismatch: ${currency} vs ${ctx.currency}`);
88
+ }
89
+ }
90
+ function validateCliCredential(value) {
91
+ if (typeof value.tokenId !== 'string' || !value.tokenId.trim()) {
92
+ throw new Error('CLI agent credential requires tokenId');
93
+ }
94
+ // Deliberately no assuranceData requirement: the artifact's enrollment-time
95
+ // assurance is identity/enrollment material and is never read here (#5709).
96
+ }
97
+ /**
98
+ * Refuse to mint an intent unless the assurance is fresh and its declared
99
+ * scope matches the checkout target exactly. `now` is injectable so the
100
+ * freshness rules are testable with a pinned clock (same pattern as
101
+ * validateCredential).
102
+ */
103
+ export function validatePurchaseAssurance(value, target, now = new Date()) {
104
+ const remedy = 'run a fresh device-binding ceremony scoped to this exact merchant, amount, and ' +
105
+ 'currency, and pass its output via --purchase-assurance-file (#5709)';
106
+ if (value == null || typeof value !== 'object') {
107
+ throw new Error(`purchase assurance is missing — ${remedy}`);
108
+ }
109
+ // A passkey-exempt approval (marked by the approval SERVER, never assumed
110
+ // locally) carries no assurance by design — every scope/freshness check
111
+ // below still applies to it unchanged.
112
+ if (value.assuranceData == null && value.assuranceExempt !== true) {
113
+ throw new Error(`purchase assurance requires assuranceData — ${remedy}`);
114
+ }
115
+ const mintedAtMs = typeof value.mintedAt === 'string' ? Date.parse(value.mintedAt) : NaN;
116
+ if (!Number.isFinite(mintedAtMs)) {
117
+ throw new Error(`purchase assurance requires an ISO 8601 mintedAt — ${remedy}`);
118
+ }
119
+ const age = now.getTime() - mintedAtMs;
120
+ if (age < -PURCHASE_ASSURANCE_MAX_SKEW_MS) {
121
+ throw new Error(`purchase assurance mintedAt is in the future — ${remedy}`);
122
+ }
123
+ if (age > PURCHASE_ASSURANCE_MAX_AGE_MS) {
124
+ throw new Error(`purchase assurance is stale (minted ${value.mintedAt}, limit ` +
125
+ `${PURCHASE_ASSURANCE_MAX_AGE_MS / 60000} minutes) — ${remedy}`);
126
+ }
127
+ let targetHost;
128
+ try {
129
+ targetHost = new URL(target.merchantUrl).hostname;
130
+ }
131
+ catch {
132
+ throw new Error('VGS checkout reference merchant URL is invalid');
133
+ }
134
+ if (value.merchantHost !== targetHost) {
135
+ throw new Error(`purchase assurance merchant mismatch: ${value.merchantHost} vs ${targetHost} — ${remedy}`);
136
+ }
137
+ const assuranceMinor = decimalToMinor(value.transactionAmount);
138
+ const targetMinor = decimalToMinor(target.transactionAmount);
139
+ if (assuranceMinor === null || assuranceMinor !== targetMinor) {
140
+ throw new Error(`purchase assurance amount mismatch: ${value.transactionAmount} vs ` +
141
+ `${target.transactionAmount} — ${remedy}`);
142
+ }
143
+ if (typeof value.transactionCurrencyCode !== 'string' ||
144
+ value.transactionCurrencyCode.toUpperCase() !==
145
+ String(target.transactionCurrencyCode).toUpperCase()) {
146
+ throw new Error(`purchase assurance currency mismatch: ${value.transactionCurrencyCode} vs ` +
147
+ `${target.transactionCurrencyCode} — ${remedy}`);
148
+ }
149
+ }
150
+ // `now` is injectable so expiry rules are testable with a pinned clock.
151
+ export function validateCredential(value, now = new Date()) {
152
+ if (!/^\d{12,19}$/.test(value.networkToken)) {
153
+ throw new Error('VGS credential network token must contain 12-19 digits');
154
+ }
155
+ if (!/^\d{3,4}$/.test(value.cryptogramValue)) {
156
+ throw new Error('VGS credential short DAVV must contain 3-4 digits');
157
+ }
158
+ if (typeof value.cryptogramType !== 'string' || value.cryptogramType.toUpperCase() !== 'DAVV') {
159
+ throw new Error(`VGS credential type ${value.cryptogramType || '<missing>'} is not DAVV`);
160
+ }
161
+ if (!Number.isInteger(value.expMonth) || value.expMonth < 1 || value.expMonth > 12) {
162
+ throw new Error('VGS credential expiration month is invalid');
163
+ }
164
+ if (!Number.isInteger(value.expYear) ||
165
+ value.expYear < now.getFullYear() ||
166
+ (value.expYear === now.getFullYear() && value.expMonth < now.getMonth() + 1)) {
167
+ throw new Error('VGS credential is expired');
168
+ }
169
+ if (value.cryptogramExpiresAt === undefined) {
170
+ throw new Error('VGS credential expiry is missing');
171
+ }
172
+ const expiresAtMs = Date.parse(value.cryptogramExpiresAt);
173
+ if (!Number.isFinite(expiresAtMs))
174
+ throw new Error('VGS credential expiry is invalid');
175
+ if (expiresAtMs - now.getTime() < 60_000) {
176
+ throw new Error('VGS credential has less than 60 seconds of validity remaining');
177
+ }
178
+ }
179
+ /**
180
+ * Mints the full DPAN + short DAVV only after the executor revalidates the
181
+ * reviewed merchant, amount, and currency. The payment credential remains in
182
+ * memory, is never returned to the caller, and can be requested only once.
183
+ */
184
+ export class VgsLiveInstrument {
185
+ reference;
186
+ cardholderName;
187
+ fetchCredential;
188
+ kind = 'agentic-token';
189
+ used = false;
190
+ minted = null;
191
+ constructor(reference, cardholderName, fetchCredential) {
192
+ this.reference = reference;
193
+ this.cardholderName = cardholderName;
194
+ this.fetchCredential = fetchCredential;
195
+ }
196
+ /**
197
+ * Non-null once VGS has actually issued a credential (the intent is consumed
198
+ * from that moment, even if local validation later rejects the credential) —
199
+ * exactly the population a VIC confirmation can be owed for.
200
+ */
201
+ confirmationTarget() {
202
+ return this.minted;
203
+ }
204
+ async getCredential(ctx) {
205
+ if (this.used)
206
+ throw new Error('VGS live credential instrument is single-use');
207
+ this.used = true;
208
+ validateTarget(this.reference, ctx);
209
+ if (!this.reference.tokenId || !this.reference.intentId) {
210
+ throw new Error('VGS checkout reference requires tokenId and intentId');
211
+ }
212
+ if (!this.cardholderName.trim())
213
+ throw new Error('cardholder name is required');
214
+ const { tokenId, intentId, ...transaction } = this.reference;
215
+ const value = await this.fetchCredential({ tokenId, intentId, transaction });
216
+ this.minted = { tokenId, intentId };
217
+ try {
218
+ validateCredential(value);
219
+ }
220
+ catch (err) {
221
+ // VGS already issued a cryptogram for this intent even though we refuse
222
+ // to fill it; "correct inputs and retry" would silently reuse a consumed
223
+ // intent, so steer the operator to a fresh one.
224
+ throw new Error(`${err.message} — a credential was issued by VGS but rejected locally; obtain a fresh intent before retrying`);
225
+ }
226
+ return {
227
+ pan: value.networkToken,
228
+ expMonth: value.expMonth,
229
+ expYear: value.expYear,
230
+ cvc: value.cryptogramValue,
231
+ cardholderName: this.cardholderName.trim(),
232
+ ...(value.cryptogramExpiresAt ? { credentialExpiresAt: value.cryptogramExpiresAt } : {}),
233
+ ...traceHandleFields(value),
234
+ };
235
+ }
236
+ }
237
+ /**
238
+ * Consumes #5614's claimed CLI enrollment artifact (for the tokenId) plus a
239
+ * FRESH purchase-scoped assurance, and creates a fresh, transaction-scoped VIC
240
+ * intent + credential after checkout approval. This is the production-shaped
241
+ * bridge; unlike VgsLiveInstrument it never needs a pre-created intent ID.
242
+ *
243
+ * The enrollment artifact's stored assuranceData is deliberately never sent:
244
+ * replaying it makes intent creation succeed (HTTP 201) while the cryptogram
245
+ * deterministically never completes — the #5709 dead end. Purchase
246
+ * authorization is the fresh, merchant+amount+currency-scoped assurance,
247
+ * validated against the checkout target BEFORE any intent is minted so a
248
+ * doomed intent is never created.
249
+ */
250
+ export class VgsAssuranceInstrument {
251
+ enrollment;
252
+ purchase;
253
+ target;
254
+ cardholderName;
255
+ mintCredential;
256
+ kind = 'agentic-token';
257
+ used = false;
258
+ minted = null;
259
+ constructor(enrollment, purchase, target, cardholderName, mintCredential) {
260
+ this.enrollment = enrollment;
261
+ this.purchase = purchase;
262
+ this.target = target;
263
+ this.cardholderName = cardholderName;
264
+ this.mintCredential = mintCredential;
265
+ }
266
+ /** See VgsLiveInstrument.confirmationTarget — same contract. */
267
+ confirmationTarget() {
268
+ return this.minted;
269
+ }
270
+ async getCredential(ctx) {
271
+ if (this.used)
272
+ throw new Error('VGS assurance instrument is single-use');
273
+ this.used = true;
274
+ validateCliCredential(this.enrollment);
275
+ validateTarget(this.target, ctx);
276
+ validatePurchaseAssurance(this.purchase, this.target);
277
+ if (!this.cardholderName.trim())
278
+ throw new Error('cardholder name is required');
279
+ const { payment: value, intentId } = await this.mintCredential({
280
+ tokenId: this.enrollment.tokenId,
281
+ assuranceData: this.purchase.assuranceData,
282
+ transaction: this.target,
283
+ });
284
+ this.minted = { tokenId: this.enrollment.tokenId, intentId };
285
+ validateCredential(value);
286
+ return {
287
+ pan: value.networkToken,
288
+ expMonth: value.expMonth,
289
+ expYear: value.expYear,
290
+ cvc: value.cryptogramValue,
291
+ cardholderName: this.cardholderName.trim(),
292
+ ...(value.cryptogramExpiresAt ? { credentialExpiresAt: value.cryptogramExpiresAt } : {}),
293
+ ...traceHandleFields(value),
294
+ };
295
+ }
296
+ }
@@ -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>;
@@ -0,0 +1,39 @@
1
+ /** Definitive merchant answers map to a status; everything else maps to none. */
2
+ export function outcomeToTransactionStatus(outcome) {
3
+ if (outcome === 'confirmed')
4
+ return 'APPROVED';
5
+ if (outcome === 'declined')
6
+ return 'DECLINED';
7
+ return null;
8
+ }
9
+ export async function reportVicOutcome(input) {
10
+ const transactionStatus = outcomeToTransactionStatus(input.outcome);
11
+ if (!transactionStatus) {
12
+ return {
13
+ posted: false,
14
+ reason: `outcome '${input.outcome}' is not a definitive merchant answer — ` +
15
+ 'resolve it with the merchant, then post the confirmation manually',
16
+ };
17
+ }
18
+ if (!input.target) {
19
+ return { posted: false, reason: 'no VIC credential was minted in this run' };
20
+ }
21
+ try {
22
+ await input.post({
23
+ tokenId: input.target.tokenId,
24
+ intentId: input.target.intentId,
25
+ transactionStatus,
26
+ transactionType: 'PURCHASE',
27
+ transactionTimestamp: (input.timestamp ?? new Date()).toISOString(),
28
+ transaction: input.transaction,
29
+ });
30
+ return { posted: true, transactionStatus };
31
+ }
32
+ catch (err) {
33
+ return {
34
+ posted: false,
35
+ reason: `confirmation POST failed: ${err.message} — the merchant-reported outcome ` +
36
+ 'remains unverified; retry the confirmation for this intent out-of-band',
37
+ };
38
+ }
39
+ }