@visa/cli 4.1.0-rc.16 → 4.1.0-rc.160

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 (75) hide show
  1. package/README.md +189 -232
  2. package/dist/checkout-engine/adapters/generic.d.ts +46 -0
  3. package/dist/checkout-engine/adapters/generic.js +188 -14
  4. package/dist/checkout-engine/adapters/index.d.ts +4 -1
  5. package/dist/checkout-engine/adapters/index.js +10 -3
  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/amount.d.ts +15 -0
  9. package/dist/checkout-engine/amount.js +72 -0
  10. package/dist/checkout-engine/cli-engine.d.ts +259 -4
  11. package/dist/checkout-engine/cli-engine.js +797 -43
  12. package/dist/checkout-engine/confirmed-merchants.d.ts +31 -0
  13. package/dist/checkout-engine/confirmed-merchants.js +165 -0
  14. package/dist/checkout-engine/detect.d.ts +1 -1
  15. package/dist/checkout-engine/detect.js +26 -0
  16. package/dist/checkout-engine/evidence.d.ts +4 -1
  17. package/dist/checkout-engine/evidence.js +51 -6
  18. package/dist/checkout-engine/executor.d.ts +39 -4
  19. package/dist/checkout-engine/executor.js +323 -117
  20. package/dist/checkout-engine/hosted-approval.d.ts +124 -7
  21. package/dist/checkout-engine/hosted-approval.js +379 -54
  22. package/dist/checkout-engine/index.d.ts +8 -2
  23. package/dist/checkout-engine/index.js +7 -1
  24. package/dist/checkout-engine/instrument.d.ts +7 -0
  25. package/dist/checkout-engine/instrument.js +4 -0
  26. package/dist/checkout-engine/known-merchants.d.ts +10 -0
  27. package/dist/checkout-engine/known-merchants.js +38 -0
  28. package/dist/checkout-engine/live-fill-approval.d.ts +0 -20
  29. package/dist/checkout-engine/live-fill-approval.js +15 -51
  30. package/dist/checkout-engine/mandate/card-mandate.d.ts +121 -0
  31. package/dist/checkout-engine/mandate/card-mandate.js +227 -0
  32. package/dist/checkout-engine/mandate/mandate-ledger.d.ts +178 -0
  33. package/dist/checkout-engine/mandate/mandate-ledger.js +395 -0
  34. package/dist/checkout-engine/outcome.d.ts +2 -2
  35. package/dist/checkout-engine/outcome.js +36 -1
  36. package/dist/checkout-engine/owner-only-file.d.ts +9 -0
  37. package/dist/checkout-engine/owner-only-file.js +20 -1
  38. package/dist/checkout-engine/receipt-dir.d.ts +6 -0
  39. package/dist/checkout-engine/receipt-dir.js +8 -0
  40. package/dist/checkout-engine/receipt.d.ts +42 -2
  41. package/dist/checkout-engine/receipt.js +30 -14
  42. package/dist/checkout-engine/trace-handles.d.ts +8 -0
  43. package/dist/checkout-engine/trace-handles.js +12 -0
  44. package/dist/checkout-engine/types.d.ts +20 -2
  45. package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +53 -1
  46. package/dist/checkout-engine/vgs-gateway/server-mint-client.js +78 -10
  47. package/dist/checkout-engine/vgs-live-instrument.d.ts +38 -35
  48. package/dist/checkout-engine/vgs-live-instrument.js +51 -74
  49. package/dist/checkout-engine/vic-confirmation.js +2 -2
  50. package/dist/checkout-engine/web-bot-auth.d.ts +92 -0
  51. package/dist/checkout-engine/web-bot-auth.js +159 -0
  52. package/dist/cli.js +663 -492
  53. package/dist/mcp-apps/ucp-checkout.html +280 -0
  54. package/dist/mcp-server/index.js +514 -174
  55. package/dist/skills/pair-visa-agent/RUNTIMES.md +92 -0
  56. package/dist/skills/pair-visa-agent/SKILL.md +526 -0
  57. package/dist/skills/pair-visa-agent/scripts/setup.mjs +48 -0
  58. package/dist/subway-direct.mjs +1 -0
  59. package/install.ps1 +3 -41
  60. package/install.sh +4 -36
  61. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  62. package/package.json +18 -14
  63. package/server.json +3 -3
  64. package/dist/checkout-engine/inline-target.d.ts +0 -13
  65. package/dist/checkout-engine/inline-target.js +0 -37
  66. package/dist/checkout-engine/pay-args.d.ts +0 -14
  67. package/dist/checkout-engine/pay-args.js +0 -44
  68. package/dist/checkout-engine/pay.d.ts +0 -1
  69. package/dist/checkout-engine/pay.js +0 -13
  70. package/dist/checkout-engine/repo-env.d.ts +0 -11
  71. package/dist/checkout-engine/repo-env.js +0 -23
  72. package/dist/checkout-engine/run-live-fill.d.ts +0 -1
  73. package/dist/checkout-engine/run-live-fill.js +0 -443
  74. package/dist/checkout-engine/vgs-gateway/fetch-credential.d.mts +0 -74
  75. package/dist/checkout-engine/vgs-gateway/fetch-credential.mjs +0 -248
@@ -1,4 +1,6 @@
1
- import { lstat, readFile } from 'node:fs/promises';
1
+ import { randomBytes } from 'node:crypto';
2
+ import { chmod, lstat, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
2
4
  /**
3
5
  * lstat-only guard for operator-supplied secret-bearing files: must be a
4
6
  * regular file (never a symlink), owner-only (chmod 600), and size-bounded.
@@ -20,3 +22,20 @@ export async function readOwnerOnlyJson(path, label, maxBytes = 16 * 1024) {
20
22
  await assertOwnerOnlyFile(path, label, maxBytes);
21
23
  return JSON.parse(await readFile(path, 'utf8'));
22
24
  }
25
+ /**
26
+ * Atomically write an owner-only (chmod 600) JSON artifact: serialize to a
27
+ * sibling temp file created 0600, then rename over the target so a reader never
28
+ * observes a half-written ledger (and a crash mid-write leaves the prior file
29
+ * intact). The parent directory is created if absent (matching ~/.visa-mcp).
30
+ * Used by the card-mandate ledger — the same owner-only posture as
31
+ * agent-credential.json / contact.json.
32
+ */
33
+ export async function writeOwnerOnlyJson(path, value) {
34
+ await mkdir(dirname(path), { recursive: true });
35
+ const tmp = `${path}.tmp-${randomBytes(6).toString('hex')}`;
36
+ await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
37
+ // writeFile's mode only applies on create; chmod defensively in case the temp
38
+ // name somehow pre-existed with looser bits.
39
+ await chmod(tmp, 0o600);
40
+ await rename(tmp, path);
41
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Where this device's checkout receipts live. Owned by its own module so the
3
+ * writer (cli-engine.ts) and the reader (confirmed-merchants.ts) can never
4
+ * drift onto two paths.
5
+ */
6
+ export declare const RECEIPT_DIR: string;
@@ -0,0 +1,8 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ /**
4
+ * Where this device's checkout receipts live. Owned by its own module so the
5
+ * writer (cli-engine.ts) and the reader (confirmed-merchants.ts) can never
6
+ * drift onto two paths.
7
+ */
8
+ export const RECEIPT_DIR = join(homedir(), '.visa-mcp', 'checkout-receipts');
@@ -1,7 +1,8 @@
1
1
  import type { EvidenceStep } from './evidence.js';
2
2
  import type { CheckoutMode, CheckoutOutcome, CheckoutResult, CredentialLifecycle, CredentialTiming } from './executor.js';
3
3
  import type { VicConfirmationReport } from './vic-confirmation.js';
4
- export type CheckoutReceipt = {
4
+ /** Published v1 artifact shape. Retained so patch releases remain readable/typable. */
5
+ export type CheckoutReceiptV1 = {
5
6
  schema: 'checkout-agent-receipt/v1';
6
7
  recordedAt: string;
7
8
  mode: CheckoutMode;
@@ -32,6 +33,42 @@ export type CheckoutReceipt = {
32
33
  snapshotSummary: string | null;
33
34
  };
34
35
  };
36
+ export type CheckoutReceiptV2 = {
37
+ schema: 'checkout-agent-receipt/v2';
38
+ recordedAt: string;
39
+ merchant: {
40
+ name: string;
41
+ host: string;
42
+ checkoutUrl: string | null;
43
+ };
44
+ transaction: {
45
+ amount: string;
46
+ amountMinor: number;
47
+ currency: string;
48
+ };
49
+ outcome: CheckoutOutcome;
50
+ agent: {
51
+ name: string;
52
+ } | null;
53
+ rail: {
54
+ type: 'card';
55
+ cardLast4: string | null;
56
+ };
57
+ network: {
58
+ confirmation: 'APPROVED' | 'DECLINED' | null;
59
+ };
60
+ /** Local reviewed-attempt identifier. Keeps filenames stable across schema versions. */
61
+ receiptId: string | null;
62
+ /** Merchant confirmation reference only; never substituted with an internal review id. */
63
+ reference: string | null;
64
+ recovery: {
65
+ required: boolean;
66
+ retrySafe: boolean;
67
+ action: string;
68
+ actions: string[];
69
+ };
70
+ };
71
+ export type CheckoutReceipt = CheckoutReceiptV1 | CheckoutReceiptV2;
35
72
  export type ReceiptWriteReport = {
36
73
  written: true;
37
74
  path: string;
@@ -46,6 +83,7 @@ export declare function buildReceipt(input: {
46
83
  merchant: {
47
84
  name: string;
48
85
  host: string;
86
+ url?: string;
49
87
  };
50
88
  transaction: {
51
89
  amount: string;
@@ -54,9 +92,11 @@ export declare function buildReceipt(input: {
54
92
  };
55
93
  result: CheckoutResult;
56
94
  vicConfirmation: VicConfirmationReport | null;
95
+ agentName?: string;
96
+ cardLast4?: string;
57
97
  /** Injectable for tests; defaults to now. */
58
98
  recordedAt?: Date;
59
- }): CheckoutReceipt;
99
+ }): CheckoutReceiptV2;
60
100
  /**
61
101
  * Defense-in-depth scrub before anything touches disk: any standalone
62
102
  * 12–19-digit run that passes Luhn is replaced — contiguous OR separated by
@@ -1,5 +1,6 @@
1
1
  import { mkdir, writeFile } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
+ import { KNOWN_MERCHANT_IDENTITIES } from './known-merchants.js';
3
4
  import { submitClickedWithoutConfirmation } from './live-fill-approval.js';
4
5
  /**
5
6
  * What the operator still owes after this run. Empty for a clean dry-run fill
@@ -29,23 +30,37 @@ function reconciliationFor(result, vicConfirmation) {
29
30
  }
30
31
  export function buildReceipt(input) {
31
32
  const { result } = input;
33
+ const reconciliation = reconciliationFor(result, input.vicConfirmation);
34
+ const fallbackAction = input.mode === 'dry-run'
35
+ ? 'Dry run only — nothing was submitted; safe to run again.'
36
+ : result.outcome === 'confirmed'
37
+ ? 'No action needed.'
38
+ : result.outcome === 'declined'
39
+ ? 'Review the decline before trying again.'
40
+ : 'Review this outcome before retrying.';
41
+ const recoveryActions = reconciliation.reasons.length > 0 ? reconciliation.reasons : [fallbackAction];
42
+ const cardLast4 = input.cardLast4 && /^\d{4}$/.test(input.cardLast4) ? input.cardLast4 : null;
43
+ const checkoutUrl = input.merchant.url && KNOWN_MERCHANT_IDENTITIES[input.merchant.url] ? input.merchant.url : null;
44
+ const networkConfirmation = input.vicConfirmation?.posted === true ? input.vicConfirmation.transactionStatus : null;
32
45
  return {
33
- schema: 'checkout-agent-receipt/v1',
46
+ schema: 'checkout-agent-receipt/v2',
34
47
  recordedAt: (input.recordedAt ?? new Date()).toISOString(),
35
- mode: input.mode,
36
- reviewId: input.reviewId,
37
- merchant: { name: input.merchant.name, host: input.merchant.host },
48
+ merchant: { name: input.merchant.name, host: input.merchant.host, checkoutUrl },
38
49
  transaction: input.transaction,
39
50
  outcome: result.outcome,
40
- detail: result.detail ?? null,
41
- confirmationRef: result.confirmationRef ?? null,
42
- vicConfirmation: input.vicConfirmation,
43
- credentialLifecycle: result.credentialLifecycle,
44
- credentialTiming: result.credentialTiming,
45
- detectedRoles: Object.keys(result.fields),
46
- requiresAdapter: [...result.requiresAdapter],
47
- reconciliation: reconciliationFor(result, input.vicConfirmation),
48
- evidence: result.evidence.toObject(),
51
+ agent: input.agentName ? { name: input.agentName } : null,
52
+ rail: { type: 'card', cardLast4 },
53
+ network: { confirmation: networkConfirmation },
54
+ receiptId: input.reviewId,
55
+ reference: result.confirmationRef ?? null,
56
+ recovery: {
57
+ required: reconciliation.required,
58
+ // A clean dry-run did not submit anything, so repeating inspection is
59
+ // safe. Every submit outcome requires either no retry or owner review.
60
+ retrySafe: input.mode === 'dry-run' && !reconciliation.required,
61
+ action: recoveryActions[0],
62
+ actions: recoveryActions,
63
+ },
49
64
  };
50
65
  }
51
66
  function luhnValid(digits) {
@@ -88,7 +103,8 @@ export function serializeReceipt(receipt) {
88
103
  }
89
104
  export function receiptFileName(receipt) {
90
105
  const ts = receipt.recordedAt.replace(/[:.]/g, '-');
91
- const review = (receipt.reviewId ?? 'no-review').replace(/[^A-Za-z0-9-]/g, '');
106
+ const receiptId = receipt.schema === 'checkout-agent-receipt/v1' ? receipt.reviewId : receipt.receiptId;
107
+ const review = (receiptId ?? 'no-review').replace(/[^A-Za-z0-9-]/g, '');
92
108
  return `receipt-${ts}-${review || 'no-review'}.json`;
93
109
  }
94
110
  /**
@@ -0,0 +1,8 @@
1
+ export declare function safeTraceHandle(value: unknown): string | undefined;
2
+ export declare function traceHandleFields(value: {
3
+ vgsTraceId?: unknown;
4
+ networkCorrelationId?: unknown;
5
+ }): {
6
+ vgsTraceId?: string;
7
+ networkCorrelationId?: string;
8
+ };
@@ -0,0 +1,12 @@
1
+ const SAFE_TRACE_HANDLE_RE = /^[A-Za-z0-9._:-]{1,128}$/;
2
+ export function safeTraceHandle(value) {
3
+ return typeof value === 'string' && SAFE_TRACE_HANDLE_RE.test(value) ? value : undefined;
4
+ }
5
+ export function traceHandleFields(value) {
6
+ const vgsTraceId = safeTraceHandle(value.vgsTraceId);
7
+ const networkCorrelationId = safeTraceHandle(value.networkCorrelationId);
8
+ return {
9
+ ...(vgsTraceId ? { vgsTraceId } : {}),
10
+ ...(networkCorrelationId ? { networkCorrelationId } : {}),
11
+ };
12
+ }
@@ -1,5 +1,4 @@
1
- export type Contact = {
2
- email?: string;
1
+ export type PostalAddress = {
3
2
  firstName?: string;
4
3
  lastName?: string;
5
4
  fullName?: string;
@@ -10,6 +9,11 @@ export type Contact = {
10
9
  postalCode?: string;
11
10
  country?: string;
12
11
  };
12
+ export type Contact = PostalAddress & {
13
+ email?: string;
14
+ phone?: string;
15
+ billingAddress?: PostalAddress;
16
+ };
13
17
  export type FilledField = {
14
18
  role: string;
15
19
  locator: string;
@@ -23,4 +27,18 @@ export type FilledField = {
23
27
  export type FillResult = {
24
28
  ok: boolean;
25
29
  filled: FilledField[];
30
+ detail?: string;
31
+ };
32
+ export type OtpRequest = {
33
+ /** ISO watermark captured BEFORE the click that triggers the OTP email. */
34
+ after: string;
35
+ /** The merchant hostname; the sender's registrable domain must match it. */
36
+ merchantHost: string;
37
+ };
38
+ export type OtpResolution = {
39
+ /** The single-use code. The executor fills it exactly once; never retried. */
40
+ code: string;
41
+ /** The sender's registrable domain — a trust signal, safe to log (no PII). */
42
+ fromDomain: string;
26
43
  };
44
+ export type OtpResolver = (req: OtpRequest) => Promise<OtpResolution | null>;
@@ -6,15 +6,67 @@ export type ServerMintDeps = {
6
6
  sleep?: (ms: number) => Promise<void>;
7
7
  env?: NodeJS.ProcessEnv;
8
8
  };
9
+ /**
10
+ * The merchant ORIGIN (scheme + host) — not the full checkout URL. A merchant's
11
+ * identity is its origin; a real checkout URL can carry hundreds of chars of
12
+ * campaign/tracking query params. Confirmed live: an oversized `merchantUrl`
13
+ * (a ~280-char Wikimedia donation URL) makes the cryptogram mint fail downstream
14
+ * with a vague `502 "card network could not complete"`, while the same merchant
15
+ * with a trimmed URL mints fine. Sending the origin is both correct (that IS the
16
+ * merchant) and safely bounded. Falls back to the raw value if it does not parse
17
+ * — the mint must never throw here.
18
+ */
19
+ export declare function merchantOrigin(url: string): string;
20
+ /**
21
+ * A definitive refusal from the cryptogram mint route — the request will not
22
+ * succeed if retried unchanged.
23
+ *
24
+ * `terminal` is the load-bearing field. Draw terminality used to be decided by
25
+ * regex over the error MESSAGE, which made it hostage to text nobody controls:
26
+ * this client now interpolates the provider's own `upstream_codes` into the
27
+ * message for diagnosability, and a provider identifier such as
28
+ * `request_timeout` would match the transient matcher's unanchored
29
+ * `tim(e|ed)-out` alternative — flipping a permanent 422 back to "transient",
30
+ * skipping markUnhonored, and stranding the mandate in the exact retry-forever
31
+ * loop this whole change exists to kill. Terminality is therefore carried
32
+ * structurally, and consumers must consult it BEFORE any message matching.
33
+ */
34
+ export declare class ServerCryptogramRefusedError extends Error {
35
+ readonly status: number;
36
+ readonly terminal: true;
37
+ constructor(status: number, detail: string);
38
+ }
39
+ /**
40
+ * Optional mandate override for serverCreateIntent. Absent → the default
41
+ * intent shape (cap = ceil(amount)+10 min 25, quantity 1, 30-day window).
42
+ * Present → the card-mandate (budget) layer sets a CEILING decline threshold
43
+ * and a multi-draw quantity so one passkey approves a spend ceiling and later
44
+ * draws pull cryptograms under it without a fresh tap. Whether the network
45
+ * honors a ceiling-scoped assurance across multiple sub-amount draws is
46
+ * UNPROVEN — see packages/checkout-engine/src/mandate/.
47
+ */
48
+ export type ServerIntentMandateOverride = {
49
+ /** Wire decline-threshold amount (major-unit decimal string), e.g. "500.00". */
50
+ declineThresholdAmount?: string;
51
+ /** Number of draws the intent may fulfil (VGS mandate `quantity`). */
52
+ quantity?: number;
53
+ /** ISO 8601 mandate validity end. */
54
+ effectiveUntil?: string;
55
+ /** Human-readable consumer prompt describing the ceiling grant. */
56
+ consumerPrompt?: string;
57
+ };
9
58
  /**
10
59
  * Create a fresh intent via POST {base}/api/vgs/intent. The server holds the VGS
11
60
  * credential and calls the gateway; we send the same mandate shape the local
12
- * path built (cap = ceil(amount)+10, min 25; merchant category Retail/5999).
61
+ * path built (cap = ceil(amount)+10, min 25; merchant category Retail/5999)
62
+ * unless `input.mandate` overrides the threshold/quantity/window for the
63
+ * card-mandate (budget) layer.
13
64
  */
14
65
  export declare function serverCreateIntent(base: string, mintToken: string, input: {
15
66
  tokenId: string;
16
67
  assuranceData: unknown;
17
68
  transaction: VgsCheckoutTarget;
69
+ mandate?: ServerIntentMandateOverride;
18
70
  }, deps?: ServerMintDeps): Promise<{
19
71
  intentId: string;
20
72
  status: string | null;
@@ -11,6 +11,7 @@
11
11
  // Request derivation here mirrors ../fetch-credential.mjs EXACTLY (mandate cap,
12
12
  // consumer prompt, PENDING retry cadence) — the only change is the transport:
13
13
  // verify-web routes + Bearer mint token, never the VGS gateway + VGS secret.
14
+ import { traceHandleFields } from '../trace-handles.js';
14
15
  const defaultSleep = (ms) => new Promise((r) => {
15
16
  const t = setTimeout(r, ms);
16
17
  t.unref?.();
@@ -21,10 +22,62 @@ function stripTrailingSlashes(value) {
21
22
  out = out.slice(0, -1);
22
23
  return out;
23
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
+ }
24
66
  /** Read a stable, non-secret error message from a route's JSON body. */
25
67
  async function routeError(res) {
26
68
  const doc = (await res.json().catch(() => null));
27
- return doc?.error || doc?.error_code || `HTTP ${res.status}`;
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;
28
81
  }
29
82
  function bearer(mintToken) {
30
83
  return { 'content-type': 'application/json', authorization: `Bearer ${mintToken}` };
@@ -32,29 +85,37 @@ function bearer(mintToken) {
32
85
  /**
33
86
  * Create a fresh intent via POST {base}/api/vgs/intent. The server holds the VGS
34
87
  * credential and calls the gateway; we send the same mandate shape the local
35
- * path built (cap = ceil(amount)+10, min 25; merchant category Retail/5999).
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.
36
91
  */
37
92
  export async function serverCreateIntent(base, mintToken, input, deps = {}) {
38
93
  const fetchImpl = deps.fetchImpl ?? fetch;
39
94
  const { tokenId, assuranceData, transaction: t } = input;
40
- const cap = Math.max(Math.ceil(Number(t.transactionAmount) || 0) + 10, 25);
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}`;
41
102
  const res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/intent`, {
42
103
  method: 'POST',
43
104
  headers: bearer(mintToken),
44
105
  body: JSON.stringify({
45
106
  tokenId,
46
- consumerPrompt: `Buy an item from ${t.merchantName} for ${t.transactionCurrencyCode.toUpperCase()} ${t.transactionAmount}`,
107
+ consumerPrompt,
47
108
  assuranceData,
48
109
  mandates: [
49
110
  {
50
111
  description: `Purchase at ${t.merchantName}`,
51
- declineThresholdAmount: String(cap),
112
+ declineThresholdAmount,
52
113
  declineThresholdCurrencyCode: t.transactionCurrencyCode.toUpperCase(),
53
- effectiveUntil: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
114
+ effectiveUntil,
54
115
  merchantCategory: 'Retail',
55
116
  merchantCategoryCode: '5999',
56
117
  preferredMerchantName: t.merchantName,
57
- quantity: 1,
118
+ quantity,
58
119
  },
59
120
  ],
60
121
  }),
@@ -89,7 +150,9 @@ export async function serverFetchCryptogram(base, mintToken, input, deps = {}) {
89
150
  intentId,
90
151
  transaction: {
91
152
  merchantName: t.merchantName,
92
- merchantUrl: t.merchantUrl,
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),
93
156
  merchantCountryCode: t.merchantCountryCode,
94
157
  transactionAmount: t.transactionAmount,
95
158
  transactionCurrencyCode: t.transactionCurrencyCode.toUpperCase(),
@@ -116,11 +179,16 @@ export async function serverFetchCryptogram(base, mintToken, input, deps = {}) {
116
179
  ...(typeof c.cryptogramExpiresAt === 'string'
117
180
  ? { cryptogramExpiresAt: c.cryptogramExpiresAt }
118
181
  : {}),
182
+ ...traceHandleFields(c),
119
183
  };
120
184
  }
121
185
  // A 4xx (bad request / binding refusal / auth) is terminal — never retry it.
122
- if (res.status >= 400 && res.status < 500) {
123
- throw new Error(`server cryptogram refused (${res.status}): ${await routeError(res)}`);
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));
124
192
  }
125
193
  lastError = `${res.status}: ${await routeError(res)}`;
126
194
  if (attempt < attempts)
@@ -42,6 +42,15 @@ export type PurchaseAssurance = {
42
42
  transactionAmount: string;
43
43
  /** ISO 4217 currency the ceremony was scoped to. */
44
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;
45
54
  };
46
55
  /**
47
56
  * Our fail-closed freshness bound, matching the runner's 15-minute checkout
@@ -57,6 +66,8 @@ export type VgsPaymentCredential = {
57
66
  cryptogramType: string;
58
67
  cryptogramValue: string;
59
68
  cryptogramExpiresAt?: string;
69
+ vgsTraceId?: string;
70
+ networkCorrelationId?: string;
60
71
  };
61
72
  export type FetchVgsPaymentCredential = (input: {
62
73
  tokenId: string;
@@ -69,20 +80,39 @@ export type FetchVgsPaymentCredential = (input: {
69
80
  transactionCurrencyCode: string;
70
81
  };
71
82
  }) => 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
83
  /** The (token, intent) pair a VIC confirmation is posted against. */
81
84
  export type VicConfirmationTarget = {
82
85
  tokenId: string;
83
86
  intentId: string;
84
87
  };
85
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;
86
116
  /**
87
117
  * Refuse to mint an intent unless the assurance is fresh and its declared
88
118
  * scope matches the checkout target exactly. `now` is injectable so the
@@ -112,30 +142,3 @@ export declare class VgsLiveInstrument implements Instrument {
112
142
  confirmationTarget(): VicConfirmationTarget | null;
113
143
  getCredential(ctx: InstrumentContext): Promise<CardCredential>;
114
144
  }
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
- }