@visa/cli 4.1.0-rc.2 → 4.1.0-rc.200

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 (76) hide show
  1. package/README.md +200 -226
  2. package/dist/checkout-engine/adapters/generic.d.ts +88 -0
  3. package/dist/checkout-engine/adapters/generic.js +526 -0
  4. package/dist/checkout-engine/adapters/index.d.ts +10 -0
  5. package/dist/checkout-engine/adapters/index.js +24 -0
  6. package/dist/checkout-engine/adapters/shopify.d.ts +55 -0
  7. package/dist/checkout-engine/adapters/shopify.js +514 -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 +315 -0
  17. package/dist/checkout-engine/cli-engine.js +996 -0
  18. package/dist/checkout-engine/confirmed-merchants.d.ts +31 -0
  19. package/dist/checkout-engine/confirmed-merchants.js +165 -0
  20. package/dist/checkout-engine/detect.d.ts +61 -0
  21. package/dist/checkout-engine/detect.js +398 -0
  22. package/dist/checkout-engine/evidence.d.ts +25 -0
  23. package/dist/checkout-engine/evidence.js +104 -0
  24. package/dist/checkout-engine/executor.d.ts +215 -0
  25. package/dist/checkout-engine/executor.js +1520 -0
  26. package/dist/checkout-engine/hosted-approval.d.ts +195 -0
  27. package/dist/checkout-engine/hosted-approval.js +498 -0
  28. package/dist/checkout-engine/index.d.ts +9 -0
  29. package/dist/checkout-engine/index.js +11 -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/known-merchants.d.ts +10 -0
  33. package/dist/checkout-engine/known-merchants.js +38 -0
  34. package/dist/checkout-engine/live-fill-approval.d.ts +37 -0
  35. package/dist/checkout-engine/live-fill-approval.js +76 -0
  36. package/dist/checkout-engine/mandate/card-mandate.d.ts +121 -0
  37. package/dist/checkout-engine/mandate/card-mandate.js +227 -0
  38. package/dist/checkout-engine/mandate/mandate-ledger.d.ts +178 -0
  39. package/dist/checkout-engine/mandate/mandate-ledger.js +395 -0
  40. package/dist/checkout-engine/mandate.d.ts +25 -0
  41. package/dist/checkout-engine/mandate.js +100 -0
  42. package/dist/checkout-engine/outcome.d.ts +30 -0
  43. package/dist/checkout-engine/outcome.js +225 -0
  44. package/dist/checkout-engine/owner-only-file.d.ts +19 -0
  45. package/dist/checkout-engine/owner-only-file.js +41 -0
  46. package/dist/checkout-engine/package.json +3 -0
  47. package/dist/checkout-engine/receipt-dir.d.ts +6 -0
  48. package/dist/checkout-engine/receipt-dir.js +8 -0
  49. package/dist/checkout-engine/receipt.d.ts +121 -0
  50. package/dist/checkout-engine/receipt.js +138 -0
  51. package/dist/checkout-engine/trace-handles.d.ts +8 -0
  52. package/dist/checkout-engine/trace-handles.js +12 -0
  53. package/dist/checkout-engine/types.d.ts +52 -0
  54. package/dist/checkout-engine/types.js +2 -0
  55. package/dist/checkout-engine/unresolved-charges.d.ts +34 -0
  56. package/dist/checkout-engine/unresolved-charges.js +125 -0
  57. package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +101 -0
  58. package/dist/checkout-engine/vgs-gateway/server-mint-client.js +218 -0
  59. package/dist/checkout-engine/vgs-live-instrument.d.ts +144 -0
  60. package/dist/checkout-engine/vgs-live-instrument.js +229 -0
  61. package/dist/checkout-engine/vic-confirmation.d.ts +52 -0
  62. package/dist/checkout-engine/vic-confirmation.js +45 -0
  63. package/dist/checkout-engine/web-bot-auth.d.ts +92 -0
  64. package/dist/checkout-engine/web-bot-auth.js +159 -0
  65. package/dist/cli.js +721 -445
  66. package/dist/mcp-apps/ucp-checkout.html +280 -0
  67. package/dist/mcp-server/index.js +573 -175
  68. package/dist/skills/pair-visa-agent/RUNTIMES.md +93 -0
  69. package/dist/skills/pair-visa-agent/SKILL.md +557 -0
  70. package/dist/skills/pair-visa-agent/scripts/setup.mjs +48 -0
  71. package/dist/subway-direct.mjs +1 -0
  72. package/install.ps1 +5 -43
  73. package/install.sh +5 -37
  74. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  75. package/package.json +33 -25
  76. package/server.json +4 -4
@@ -0,0 +1,218 @@
1
+ // Server-side mint client (Phase 1) — the checkout runner mints the payment
2
+ // credential by calling the verify-web deployment's gateway routes with a
3
+ // short-lived, purpose-scoped MINT TOKEN, instead of holding the shared VGS
4
+ // service-account secret (the gateway client id/secret) on the machine.
5
+ //
6
+ // The mint token is issued at approval time (agent-approval/complete, which is
7
+ // session + internal-tester + token-ownership gated) and released to this
8
+ // runner by the claim leg. It is bound to the exact approved purchase, so these
9
+ // calls can only mint the credential the human approved.
10
+ //
11
+ // Request derivation here mirrors ../fetch-credential.mjs EXACTLY (mandate cap,
12
+ // consumer prompt, PENDING retry cadence) — the only change is the transport:
13
+ // verify-web routes + Bearer mint token, never the VGS gateway + VGS secret.
14
+ import { traceHandleFields } from '../trace-handles.js';
15
+ const defaultSleep = (ms) => new Promise((r) => {
16
+ const t = setTimeout(r, ms);
17
+ t.unref?.();
18
+ });
19
+ function stripTrailingSlashes(value) {
20
+ let out = value;
21
+ while (out.endsWith('/'))
22
+ out = out.slice(0, -1);
23
+ return out;
24
+ }
25
+ /**
26
+ * The merchant ORIGIN (scheme + host) — not the full checkout URL. A merchant's
27
+ * identity is its origin; a real checkout URL can carry hundreds of chars of
28
+ * campaign/tracking query params. Confirmed live: an oversized `merchantUrl`
29
+ * (a ~280-char Wikimedia donation URL) makes the cryptogram mint fail downstream
30
+ * with a vague `502 "card network could not complete"`, while the same merchant
31
+ * with a trimmed URL mints fine. Sending the origin is both correct (that IS the
32
+ * merchant) and safely bounded. Falls back to the raw value if it does not parse
33
+ * — the mint must never throw here.
34
+ */
35
+ export function merchantOrigin(url) {
36
+ try {
37
+ return new URL(url).origin;
38
+ }
39
+ catch {
40
+ return url;
41
+ }
42
+ }
43
+ /**
44
+ * A definitive refusal from the cryptogram mint route — the request will not
45
+ * succeed if retried unchanged.
46
+ *
47
+ * `terminal` is the load-bearing field. Draw terminality used to be decided by
48
+ * regex over the error MESSAGE, which made it hostage to text nobody controls:
49
+ * this client now interpolates the provider's own `upstream_codes` into the
50
+ * message for diagnosability, and a provider identifier such as
51
+ * `request_timeout` would match the transient matcher's unanchored
52
+ * `tim(e|ed)-out` alternative — flipping a permanent 422 back to "transient",
53
+ * skipping markUnhonored, and stranding the mandate in the exact retry-forever
54
+ * loop this whole change exists to kill. Terminality is therefore carried
55
+ * structurally, and consumers must consult it BEFORE any message matching.
56
+ */
57
+ export class ServerCryptogramRefusedError extends Error {
58
+ status;
59
+ terminal = true;
60
+ constructor(status, detail) {
61
+ super(`server cryptogram refused (${status}): ${detail}`);
62
+ this.name = 'ServerCryptogramRefusedError';
63
+ this.status = status;
64
+ }
65
+ }
66
+ /** Read a stable, non-secret error message from a route's JSON body. */
67
+ async function routeError(res) {
68
+ const doc = (await res.json().catch(() => null));
69
+ const base = doc?.error || doc?.error_code || `HTTP ${res.status}`;
70
+ // Carry the provider's own status and rejected-attribute identifiers into the
71
+ // message when the route reflected them. Without this the operator sees only
72
+ // our status and has to go log-diving to learn WHICH field the gateway
73
+ // objected to — the gap that left a live create_intent 422 undiagnosable.
74
+ const parts = [];
75
+ if (typeof doc?.upstream_status === 'number')
76
+ parts.push(`upstream_status=${doc.upstream_status}`);
77
+ if (Array.isArray(doc?.upstream_codes) && doc.upstream_codes.length > 0) {
78
+ parts.push(`upstream_codes=${doc.upstream_codes.join(',')}`);
79
+ }
80
+ return parts.length > 0 ? `${base} [${parts.join(' ')}]` : base;
81
+ }
82
+ function bearer(mintToken) {
83
+ return { 'content-type': 'application/json', authorization: `Bearer ${mintToken}` };
84
+ }
85
+ /**
86
+ * Create a fresh intent via POST {base}/api/vgs/intent. The server holds the VGS
87
+ * credential and calls the gateway; we send the same mandate shape the local
88
+ * path built (cap = ceil(amount)+10, min 25; merchant category Retail/5999) —
89
+ * unless `input.mandate` overrides the threshold/quantity/window for the
90
+ * card-mandate (budget) layer.
91
+ */
92
+ export async function serverCreateIntent(base, mintToken, input, deps = {}) {
93
+ const fetchImpl = deps.fetchImpl ?? fetch;
94
+ const { tokenId, assuranceData, transaction: t } = input;
95
+ const override = input.mandate ?? {};
96
+ const defaultCap = Math.max(Math.ceil(Number(t.transactionAmount) || 0) + 10, 25);
97
+ const declineThresholdAmount = override.declineThresholdAmount ?? String(defaultCap);
98
+ const quantity = override.quantity ?? 1;
99
+ const effectiveUntil = override.effectiveUntil ?? new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString();
100
+ const consumerPrompt = override.consumerPrompt ??
101
+ `Buy an item from ${t.merchantName} for ${t.transactionCurrencyCode.toUpperCase()} ${t.transactionAmount}`;
102
+ const res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/intent`, {
103
+ method: 'POST',
104
+ headers: bearer(mintToken),
105
+ body: JSON.stringify({
106
+ tokenId,
107
+ consumerPrompt,
108
+ assuranceData,
109
+ mandates: [
110
+ {
111
+ description: `Purchase at ${t.merchantName}`,
112
+ declineThresholdAmount,
113
+ declineThresholdCurrencyCode: t.transactionCurrencyCode.toUpperCase(),
114
+ effectiveUntil,
115
+ merchantCategory: 'Retail',
116
+ merchantCategoryCode: '5999',
117
+ preferredMerchantName: t.merchantName,
118
+ quantity,
119
+ },
120
+ ],
121
+ }),
122
+ });
123
+ if (!res.ok)
124
+ throw new Error(`server intent failed (${res.status}): ${await routeError(res)}`);
125
+ const doc = (await res.json().catch(() => null));
126
+ if (!doc?.intentId)
127
+ throw new Error('server intent response missing intentId');
128
+ return { intentId: doc.intentId, status: typeof doc.status === 'string' ? doc.status : null };
129
+ }
130
+ /**
131
+ * Mint the FULL payment credential via POST {base}/api/vgs/payment-cryptogram.
132
+ * The server's route does a SINGLE gateway call and 502s on a not-COMPLETED
133
+ * (e.g. PENDING) cryptogram, but live intent approval is asynchronous and the
134
+ * first cryptogram answer can be PENDING (#5709). So we retry the route on any
135
+ * non-2xx up to PENDING_ATTEMPTS, matching fetch-credential.mjs's cadence
136
+ * exactly — a genuinely hard failure just surfaces after the same bounded wait.
137
+ * Re-POSTing for the same intentId is idempotent (mirrors the old client loop).
138
+ */
139
+ export async function serverFetchCryptogram(base, mintToken, input, deps = {}) {
140
+ const fetchImpl = deps.fetchImpl ?? fetch;
141
+ const sleep = deps.sleep ?? defaultSleep;
142
+ const env = deps.env ?? process.env;
143
+ const attempts = Math.max(1, Number(env.VGS_CRYPTOGRAM_PENDING_ATTEMPTS) || 4);
144
+ const waitMs = Number.isFinite(Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS))
145
+ ? Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS)
146
+ : 5000;
147
+ const { tokenId, intentId, transaction: t } = input;
148
+ const body = JSON.stringify({
149
+ tokenId,
150
+ intentId,
151
+ transaction: {
152
+ merchantName: t.merchantName,
153
+ // Send the merchant ORIGIN, not the full (possibly huge) checkout URL — an
154
+ // oversized merchantUrl makes the downstream cryptogram mint 502 (proven live).
155
+ merchantUrl: merchantOrigin(t.merchantUrl),
156
+ merchantCountryCode: t.merchantCountryCode,
157
+ transactionAmount: t.transactionAmount,
158
+ transactionCurrencyCode: t.transactionCurrencyCode.toUpperCase(),
159
+ },
160
+ });
161
+ let lastError = 'unknown';
162
+ for (let attempt = 1; attempt <= attempts; attempt++) {
163
+ const res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/payment-cryptogram`, {
164
+ method: 'POST',
165
+ headers: bearer(mintToken),
166
+ body,
167
+ });
168
+ if (res.ok) {
169
+ const c = (await res.json().catch(() => null));
170
+ if (!c || typeof c.networkToken !== 'string' || typeof c.cryptogramValue !== 'string') {
171
+ throw new Error('server cryptogram response missing credential fields');
172
+ }
173
+ return {
174
+ networkToken: c.networkToken,
175
+ expMonth: Number(c.expMonth) || 0,
176
+ expYear: Number(c.expYear) || 0,
177
+ cryptogramType: c.cryptogramType ?? '',
178
+ cryptogramValue: c.cryptogramValue,
179
+ ...(typeof c.cryptogramExpiresAt === 'string'
180
+ ? { cryptogramExpiresAt: c.cryptogramExpiresAt }
181
+ : {}),
182
+ ...traceHandleFields(c),
183
+ };
184
+ }
185
+ // A 4xx (bad request / binding refusal / auth) is terminal — never retry it.
186
+ // 429 is the sole exception: it is an explicitly retryable 4xx, and treating
187
+ // it as terminal would let a transient rate limit permanently disable a
188
+ // healthy mandate. The route maps upstream rate limits to 503 today, so this
189
+ // is a guard against a future emitter, not a live path.
190
+ if (res.status >= 400 && res.status < 500 && res.status !== 429) {
191
+ throw new ServerCryptogramRefusedError(res.status, await routeError(res));
192
+ }
193
+ lastError = `${res.status}: ${await routeError(res)}`;
194
+ if (attempt < attempts)
195
+ await sleep(waitMs);
196
+ }
197
+ throw new Error(`server cryptogram not completed after ${attempts} attempts (last: ${lastError})`);
198
+ }
199
+ /** Report the observed merchant outcome via POST {base}/api/vgs/confirmation. */
200
+ export async function serverPostConfirmation(base, mintToken, input, deps = {}) {
201
+ const fetchImpl = deps.fetchImpl ?? fetch;
202
+ const res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/confirmation`, {
203
+ method: 'POST',
204
+ headers: bearer(mintToken),
205
+ body: JSON.stringify({
206
+ tokenId: input.tokenId,
207
+ intentId: input.intentId,
208
+ transactionStatus: input.transactionStatus,
209
+ transactionType: input.transactionType,
210
+ transactionTimestamp: input.transactionTimestamp,
211
+ transactionAmount: input.transaction.transactionAmount,
212
+ transactionCurrencyCode: input.transaction.transactionCurrencyCode.toUpperCase(),
213
+ }),
214
+ });
215
+ if (!res.ok)
216
+ throw new Error(`server confirmation failed (${res.status}): ${await routeError(res)}`);
217
+ return { ok: true };
218
+ }
@@ -0,0 +1,144 @@
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
+ }
@@ -0,0 +1,229 @@
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
+ /**
91
+ * Refuse to mint an intent unless the assurance is fresh and its declared
92
+ * scope matches the checkout target exactly. `now` is injectable so the
93
+ * freshness rules are testable with a pinned clock (same pattern as
94
+ * validateCredential).
95
+ */
96
+ export function validatePurchaseAssurance(value, target, now = new Date()) {
97
+ const remedy = 'run a fresh device-binding ceremony scoped to this exact merchant, amount, and ' +
98
+ 'currency, and pass its output via --purchase-assurance-file (#5709)';
99
+ if (value == null || typeof value !== 'object') {
100
+ throw new Error(`purchase assurance is missing — ${remedy}`);
101
+ }
102
+ // A passkey-exempt approval (marked by the approval SERVER, never assumed
103
+ // locally) carries no assurance by design — every scope/freshness check
104
+ // below still applies to it unchanged.
105
+ if (value.assuranceData == null && value.assuranceExempt !== true) {
106
+ throw new Error(`purchase assurance requires assuranceData — ${remedy}`);
107
+ }
108
+ const mintedAtMs = typeof value.mintedAt === 'string' ? Date.parse(value.mintedAt) : NaN;
109
+ if (!Number.isFinite(mintedAtMs)) {
110
+ throw new Error(`purchase assurance requires an ISO 8601 mintedAt — ${remedy}`);
111
+ }
112
+ const age = now.getTime() - mintedAtMs;
113
+ if (age < -PURCHASE_ASSURANCE_MAX_SKEW_MS) {
114
+ throw new Error(`purchase assurance mintedAt is in the future — ${remedy}`);
115
+ }
116
+ if (age > PURCHASE_ASSURANCE_MAX_AGE_MS) {
117
+ throw new Error(`purchase assurance is stale (minted ${value.mintedAt}, limit ` +
118
+ `${PURCHASE_ASSURANCE_MAX_AGE_MS / 60000} minutes) — ${remedy}`);
119
+ }
120
+ let targetHost;
121
+ try {
122
+ targetHost = new URL(target.merchantUrl).hostname;
123
+ }
124
+ catch {
125
+ throw new Error('VGS checkout reference merchant URL is invalid');
126
+ }
127
+ if (value.merchantHost !== targetHost) {
128
+ throw new Error(`purchase assurance merchant mismatch: ${value.merchantHost} vs ${targetHost} — ${remedy}`);
129
+ }
130
+ const assuranceMinor = decimalToMinor(value.transactionAmount);
131
+ const targetMinor = decimalToMinor(target.transactionAmount);
132
+ if (assuranceMinor === null || assuranceMinor !== targetMinor) {
133
+ throw new Error(`purchase assurance amount mismatch: ${value.transactionAmount} vs ` +
134
+ `${target.transactionAmount} — ${remedy}`);
135
+ }
136
+ if (typeof value.transactionCurrencyCode !== 'string' ||
137
+ value.transactionCurrencyCode.toUpperCase() !==
138
+ String(target.transactionCurrencyCode).toUpperCase()) {
139
+ throw new Error(`purchase assurance currency mismatch: ${value.transactionCurrencyCode} vs ` +
140
+ `${target.transactionCurrencyCode} — ${remedy}`);
141
+ }
142
+ }
143
+ // `now` is injectable so expiry rules are testable with a pinned clock.
144
+ export function validateCredential(value, now = new Date()) {
145
+ if (!/^\d{12,19}$/.test(value.networkToken)) {
146
+ throw new Error('VGS credential network token must contain 12-19 digits');
147
+ }
148
+ if (!/^\d{3,4}$/.test(value.cryptogramValue)) {
149
+ throw new Error('VGS credential short DAVV must contain 3-4 digits');
150
+ }
151
+ if (typeof value.cryptogramType !== 'string' || value.cryptogramType.toUpperCase() !== 'DAVV') {
152
+ throw new Error(`VGS credential type ${value.cryptogramType || '<missing>'} is not DAVV`);
153
+ }
154
+ if (!Number.isInteger(value.expMonth) || value.expMonth < 1 || value.expMonth > 12) {
155
+ throw new Error('VGS credential expiration month is invalid');
156
+ }
157
+ if (!Number.isInteger(value.expYear) ||
158
+ value.expYear < now.getFullYear() ||
159
+ (value.expYear === now.getFullYear() && value.expMonth < now.getMonth() + 1)) {
160
+ throw new Error('VGS credential is expired');
161
+ }
162
+ if (value.cryptogramExpiresAt === undefined) {
163
+ throw new Error('VGS credential expiry is missing');
164
+ }
165
+ const expiresAtMs = Date.parse(value.cryptogramExpiresAt);
166
+ if (!Number.isFinite(expiresAtMs))
167
+ throw new Error('VGS credential expiry is invalid');
168
+ if (expiresAtMs - now.getTime() < 60_000) {
169
+ throw new Error('VGS credential has less than 60 seconds of validity remaining');
170
+ }
171
+ }
172
+ /**
173
+ * Mints the full DPAN + short DAVV only after the executor revalidates the
174
+ * reviewed merchant, amount, and currency. The payment credential remains in
175
+ * memory, is never returned to the caller, and can be requested only once.
176
+ */
177
+ export class VgsLiveInstrument {
178
+ reference;
179
+ cardholderName;
180
+ fetchCredential;
181
+ kind = 'agentic-token';
182
+ used = false;
183
+ minted = null;
184
+ constructor(reference, cardholderName, fetchCredential) {
185
+ this.reference = reference;
186
+ this.cardholderName = cardholderName;
187
+ this.fetchCredential = fetchCredential;
188
+ }
189
+ /**
190
+ * Non-null once VGS has actually issued a credential (the intent is consumed
191
+ * from that moment, even if local validation later rejects the credential) —
192
+ * exactly the population a VIC confirmation can be owed for.
193
+ */
194
+ confirmationTarget() {
195
+ return this.minted;
196
+ }
197
+ async getCredential(ctx) {
198
+ if (this.used)
199
+ throw new Error('VGS live credential instrument is single-use');
200
+ this.used = true;
201
+ validateTarget(this.reference, ctx);
202
+ if (!this.reference.tokenId || !this.reference.intentId) {
203
+ throw new Error('VGS checkout reference requires tokenId and intentId');
204
+ }
205
+ if (!this.cardholderName.trim())
206
+ throw new Error('cardholder name is required');
207
+ const { tokenId, intentId, ...transaction } = this.reference;
208
+ const value = await this.fetchCredential({ tokenId, intentId, transaction });
209
+ this.minted = { tokenId, intentId };
210
+ try {
211
+ validateCredential(value);
212
+ }
213
+ catch (err) {
214
+ // VGS already issued a cryptogram for this intent even though we refuse
215
+ // to fill it; "correct inputs and retry" would silently reuse a consumed
216
+ // intent, so steer the operator to a fresh one.
217
+ throw new Error(`${err.message} — a credential was issued by VGS but rejected locally; obtain a fresh intent before retrying`);
218
+ }
219
+ return {
220
+ pan: value.networkToken,
221
+ expMonth: value.expMonth,
222
+ expYear: value.expYear,
223
+ cvc: value.cryptogramValue,
224
+ cardholderName: this.cardholderName.trim(),
225
+ ...(value.cryptogramExpiresAt ? { credentialExpiresAt: value.cryptogramExpiresAt } : {}),
226
+ ...traceHandleFields(value),
227
+ };
228
+ }
229
+ }
@@ -0,0 +1,52 @@
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
+ /**
16
+ * Why a confirmation was not posted, as a BOUNDED value rather than prose.
17
+ *
18
+ * `reason` below is a human sentence built for the local receipt; it embeds
19
+ * upstream error text and is useless as an aggregate. These three codes are the
20
+ * whole space, and they mean very different things:
21
+ *
22
+ * - `outcome_not_definitive` — the merchant never gave a definitive answer, so
23
+ * there is nothing truthful to report. Expected, not a fault.
24
+ * - `no_credential_minted` — no VIC credential existed for this run, so there
25
+ * is no intent to confirm against. Expected, not a fault.
26
+ * - `post_failed` — we HAD a definitive outcome and an intent to report it
27
+ * against, and the POST did not land. This one is a fault: the processor
28
+ * lifecycle row is never written, so the purchase can never rank above the
29
+ * platform's own record no matter how well it actually went.
30
+ */
31
+ export type VicConfirmationSkipCode = 'outcome_not_definitive' | 'no_credential_minted' | 'post_failed';
32
+ export type VicConfirmationReport = {
33
+ posted: true;
34
+ transactionStatus: VicTransactionStatus;
35
+ } | {
36
+ posted: false;
37
+ code: VicConfirmationSkipCode;
38
+ reason: string;
39
+ };
40
+ /** Definitive merchant answers map to a status; everything else maps to none. */
41
+ export declare function outcomeToTransactionStatus(outcome: CheckoutOutcome): VicTransactionStatus | null;
42
+ export declare function reportVicOutcome(input: {
43
+ target: VicConfirmationTarget | null;
44
+ outcome: CheckoutOutcome;
45
+ transaction: {
46
+ transactionAmount: string;
47
+ transactionCurrencyCode: string;
48
+ };
49
+ post: PostVicConfirmation;
50
+ /** Injectable for tests; defaults to now. */
51
+ timestamp?: Date;
52
+ }): Promise<VicConfirmationReport>;