@visa/cli 4.1.0-rc.21 → 4.1.0-rc.211

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +200 -226
  2. package/dist/checkout-engine/adapters/generic.d.ts +69 -0
  3. package/dist/checkout-engine/adapters/generic.js +383 -58
  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 +264 -4
  11. package/dist/checkout-engine/cli-engine.js +803 -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 +47 -4
  19. package/dist/checkout-engine/executor.js +418 -131
  20. package/dist/checkout-engine/hosted-approval.d.ts +124 -7
  21. package/dist/checkout-engine/hosted-approval.js +381 -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 +5 -20
  29. package/dist/checkout-engine/live-fill-approval.js +20 -51
  30. package/dist/checkout-engine/mandate/card-mandate.d.ts +121 -0
  31. package/dist/checkout-engine/mandate/card-mandate.js +226 -0
  32. package/dist/checkout-engine/mandate/mandate-ledger.d.ts +174 -0
  33. package/dist/checkout-engine/mandate/mandate-ledger.js +410 -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 +43 -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 +28 -2
  45. package/dist/checkout-engine/unresolved-charges.d.ts +34 -0
  46. package/dist/checkout-engine/unresolved-charges.js +125 -0
  47. package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +53 -1
  48. package/dist/checkout-engine/vgs-gateway/server-mint-client.js +78 -10
  49. package/dist/checkout-engine/vgs-live-instrument.d.ts +38 -35
  50. package/dist/checkout-engine/vgs-live-instrument.js +51 -74
  51. package/dist/checkout-engine/vic-confirmation.d.ts +18 -0
  52. package/dist/checkout-engine/vic-confirmation.js +9 -3
  53. package/dist/checkout-engine/web-bot-auth.d.ts +92 -0
  54. package/dist/checkout-engine/web-bot-auth.js +159 -0
  55. package/dist/cli.js +772 -496
  56. package/dist/mcp-apps/ucp-checkout.html +280 -0
  57. package/dist/mcp-server/index.js +637 -175
  58. package/dist/skills/pair-visa-agent/RUNTIMES.md +93 -0
  59. package/dist/skills/pair-visa-agent/SKILL.md +479 -221
  60. package/dist/subway-direct.mjs +1 -0
  61. package/install.ps1 +5 -43
  62. package/install.sh +5 -37
  63. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  64. package/package.json +33 -27
  65. package/server.json +4 -4
  66. package/dist/checkout-engine/inline-target.d.ts +0 -13
  67. package/dist/checkout-engine/inline-target.js +0 -37
  68. package/dist/checkout-engine/pay-args.d.ts +0 -14
  69. package/dist/checkout-engine/pay-args.js +0 -44
  70. package/dist/checkout-engine/pay.d.ts +0 -1
  71. package/dist/checkout-engine/pay.js +0 -13
  72. package/dist/checkout-engine/repo-env.d.ts +0 -11
  73. package/dist/checkout-engine/repo-env.js +0 -23
  74. package/dist/checkout-engine/run-live-fill.d.ts +0 -1
  75. package/dist/checkout-engine/run-live-fill.js +0 -443
  76. package/dist/checkout-engine/vgs-gateway/fetch-credential.d.mts +0 -74
  77. package/dist/checkout-engine/vgs-gateway/fetch-credential.mjs +0 -248
@@ -26,15 +26,51 @@ import type { PurchaseAssurance, VgsCheckoutTarget } from './vgs-live-instrument
26
26
  * hang the runner past the advertised timeout.
27
27
  */
28
28
  export type HostedApprovalOptions = {
29
- /** The verify-web deployment origin, e.g. https://v4-verify-web-….up.railway.app */
29
+ /** The enrollment web deployment origin (apps/web), e.g. https://web-….up.railway.app */
30
30
  baseUrl: string;
31
31
  /** Durable agentic token id from the CLI agent credential. */
32
32
  tokenId: string;
33
33
  target: VgsCheckoutTarget;
34
34
  /** Prefills the approval page's enrollment-email field (optional). */
35
35
  consumerEmail?: string;
36
+ /**
37
+ * BUDGET/mandate approval — the only kind since #7348 retired the
38
+ * single-purchase plane: `target.transactionAmount` is the approved spend
39
+ * CEILING (not one charge), so the server mints a BUDGET mint token that
40
+ * later accepts many sub-ceiling draws tap-free.
41
+ */
42
+ budget: true;
43
+ /**
44
+ * Exact current request-key thumbprint receiving the budget; the
45
+ * authenticated page resolves it to the owner's stable agent before
46
+ * displaying or signing.
47
+ */
48
+ agentJkt: string;
49
+ /** Max draws the ceiling intent may fulfil — carried onto the token. */
50
+ maxDraws: number;
51
+ /**
52
+ * Per-purchase cap (decimal string, <= the ceiling) — shown on the approval
53
+ * page as a worst-case term and carried onto the mint token so the displayed
54
+ * cap is the enforced cap.
55
+ */
56
+ perTransaction?: string;
57
+ /**
58
+ * Agent-supplied one-liner describing what this approval is for. Sanitized
59
+ * here (control chars stripped, trimmed, capped) and rendered by the approval
60
+ * page in a clearly-labeled "written by the agent" block — provenance for the
61
+ * human to cross-check, never a trusted field.
62
+ */
63
+ intent?: string;
36
64
  log?: (line: string) => void;
37
- /** Injectable for tests; default opens the operator's default browser (macOS). */
65
+ /**
66
+ * Called once with the approval URL as DATA (not a log line) the instant it is
67
+ * known — before any polling. A headless agent (OpenClaw/Hermes) has no browser
68
+ * and no passkey; its whole job is to relay this URL to its human operator, so
69
+ * the URL must be capturable as a value, not just printed. The interactive CLI
70
+ * leaves this unset and relies on `log` + `openUrl`.
71
+ */
72
+ onApprovalUrl?: (url: string) => void;
73
+ /** Injectable for tests; default opens the operator's default browser, best-effort. */
38
74
  openUrl?: (url: string) => void;
39
75
  fetchImpl?: typeof fetch;
40
76
  /** Injectable for tests — never wall-clock-sleep in a unit test. */
@@ -43,15 +79,43 @@ export type HostedApprovalOptions = {
43
79
  pollIntervalMs?: number;
44
80
  timeoutMs?: number;
45
81
  };
82
+ /** One short sentence — must match the relay's cap (agent-approval.ts). */
83
+ export declare const APPROVAL_INTENT_MAX_CHARS = 200;
84
+ /**
85
+ * Sanitize an agent-supplied intent to what the relay will accept and the page
86
+ * will display: control chars (and JS line separators) stripped, trimmed,
87
+ * TRUNCATED to the cap (the runner is the agent's own side, so truncating here
88
+ * beats a failed registration; the server still rejects an over-cap value).
89
+ * Returns undefined when nothing displayable remains.
90
+ */
91
+ export declare function sanitizeApprovalIntent(value: string | undefined): string | undefined;
92
+ /**
93
+ * The operator saw the request and said NO. Terminal and non-retryable: the
94
+ * relay entry is consumed, re-running would only re-ask a human who already
95
+ * refused. Callers must not classify this as transient.
96
+ */
97
+ export declare class HostedApprovalDeclinedError extends Error {
98
+ constructor();
99
+ }
46
100
  export declare const HOSTED_APPROVAL_TIMEOUT_MS: number;
47
101
  export declare const HOSTED_APPROVAL_POLL_MS = 3000;
102
+ /** Emit a "still waiting" heartbeat roughly every this-many ms during the poll. */
103
+ export declare const HOSTED_APPROVAL_HEARTBEAT_MS = 30000;
48
104
  /**
49
- * The one deployed verify site — hosted approval is the NORMAL path (no local
50
- * certs, no vendored SDK, no localhost anywhere), so its origin is a built-in
51
- * default rather than per-machine config. Not a secret: it's the public page
52
- * the operator's browser opens anyway.
105
+ * Resolve the approval timeout: `CHECKOUT_APPROVAL_TIMEOUT_MS` (seconds*1000, an
106
+ * integer ms) overrides the default when it parses to a positive integer.
107
+ * Lets an operator widen the window for separate-device / headless approval
108
+ * without threading a flag through every caller. Invalid values fall back.
53
109
  */
54
- export declare const DEFAULT_APPROVAL_BASE_URL = "https://v4-verify-web-visa-code-preview.up.railway.app";
110
+ export declare function resolveApprovalTimeoutMs(): number;
111
+ /**
112
+ * The staging apps/web deploy (which now hosts the /agent/enroll/approve page
113
+ * after the v4-verify-web GA graduation) — hosted approval is the NORMAL path
114
+ * (no local certs, no vendored SDK, no localhost anywhere), so its origin is a
115
+ * built-in default rather than per-machine config. Not a secret: it's the
116
+ * public page the operator's browser opens anyway.
117
+ */
118
+ export declare const DEFAULT_APPROVAL_BASE_URL = "https://web-visa-code-preview.up.railway.app";
55
119
  /**
56
120
  * Flag > environment > built-in default. An explicitly EMPTY value
57
121
  * (CHECKOUT_APPROVAL_BASE_URL='') opts out of hosted approval entirely —
@@ -75,4 +139,57 @@ export declare function assertApprovalBaseUrl(value: string): string;
75
139
  */
76
140
  export declare function runHostedApproval(opts: HostedApprovalOptions): Promise<PurchaseAssurance & {
77
141
  mintToken?: string;
142
+ validUntil?: number;
78
143
  }>;
144
+ /**
145
+ * A panel-initiated mandate handoff, released by its single-use pickup code.
146
+ * The context here is SERVER truth (an owner-authenticated panel session parked
147
+ * it, and the code is the credential that releases it) — the runner had no part
148
+ * in registering it, so unlike {@link runHostedApproval} the fields are
149
+ * returned for the caller to act on rather than compared against a local run.
150
+ * What IS verified here is the binding: the entry must be a budget approval
151
+ * minted for exactly THIS runtime's request key and THIS device's card token.
152
+ */
153
+ export type MandatePickupClaim = {
154
+ /** Null only when {@link assuranceExempt} — a code-verified card runs no ceremony. */
155
+ assuranceData: unknown;
156
+ assuranceExempt: boolean;
157
+ mintToken: string;
158
+ /** Unix seconds — the mandate lapse the owner approved in the panel. */
159
+ validUntil: number;
160
+ /** Decimal ceiling string exactly as approved (the context's `amount`). */
161
+ ceiling: string;
162
+ currency: string;
163
+ maxDraws: number;
164
+ perTransaction?: string;
165
+ merchant: {
166
+ name: string;
167
+ url: string;
168
+ countryCode: string;
169
+ };
170
+ };
171
+ export type ClaimMandatePickupOptions = {
172
+ /** The enrollment web deployment origin (apps/web). */
173
+ baseUrl: string;
174
+ /** Single-use pickup code (the approval verifier) the owner handed over. */
175
+ pickupCode: string;
176
+ /** This runtime's exact current request-key JKT — the only key the code may fund. */
177
+ agentJkt: string;
178
+ /**
179
+ * The agent handoff this runtime just redeemed, when the code came from one.
180
+ * A budget minted in the Add-agent dialog exists before the agent does, so it
181
+ * pins the handoff rather than a key; this is the value that pin is compared
182
+ * against. Absent for the panel flow, whose budgets pin a key instead.
183
+ */
184
+ expectedHandoffId?: string;
185
+ /** The card token id this runtime's card authority points at. */
186
+ tokenId: string;
187
+ fetchImpl?: typeof fetch;
188
+ /** Injectable for tests — never wall-clock-sleep in a unit test. */
189
+ sleep?: (ms: number) => Promise<void>;
190
+ now?: () => number;
191
+ /** Bounded retries for transient 429/5xx; the claim itself is single-use. */
192
+ attempts?: number;
193
+ retryDelayMs?: number;
194
+ };
195
+ export declare function claimMandatePickup(opts: ClaimMandatePickupOptions): Promise<MandatePickupClaim>;
@@ -1,25 +1,91 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
2
  import { exec } from 'node:child_process';
3
3
  import { assuranceFromCeremony } from './ceremony.js';
4
+ /** One short sentence — must match the relay's cap (agent-approval.ts). */
5
+ export const APPROVAL_INTENT_MAX_CHARS = 200;
6
+ /**
7
+ * Sanitize an agent-supplied intent to what the relay will accept and the page
8
+ * will display: control chars (and JS line separators) stripped, trimmed,
9
+ * TRUNCATED to the cap (the runner is the agent's own side, so truncating here
10
+ * beats a failed registration; the server still rejects an over-cap value).
11
+ * Returns undefined when nothing displayable remains.
12
+ */
13
+ export function sanitizeApprovalIntent(value) {
14
+ if (value === undefined)
15
+ return undefined;
16
+ const cleaned = value
17
+ .replace(/[\p{Cc}\u2028\u2029]/gu, '')
18
+ .trim()
19
+ .slice(0, APPROVAL_INTENT_MAX_CHARS)
20
+ .trim();
21
+ return cleaned.length > 0 ? cleaned : undefined;
22
+ }
23
+ /**
24
+ * The operator saw the request and said NO. Terminal and non-retryable: the
25
+ * relay entry is consumed, re-running would only re-ask a human who already
26
+ * refused. Callers must not classify this as transient.
27
+ */
28
+ export class HostedApprovalDeclinedError extends Error {
29
+ constructor() {
30
+ super('The approver declined this request — the checkout was cancelled and nothing was charged');
31
+ this.name = 'HostedApprovalDeclinedError';
32
+ }
33
+ }
4
34
  export const HOSTED_APPROVAL_TIMEOUT_MS = 4 * 60 * 1000;
5
35
  export const HOSTED_APPROVAL_POLL_MS = 3_000;
36
+ /** Emit a "still waiting" heartbeat roughly every this-many ms during the poll. */
37
+ export const HOSTED_APPROVAL_HEARTBEAT_MS = 30_000;
38
+ /**
39
+ * Resolve the approval timeout: `CHECKOUT_APPROVAL_TIMEOUT_MS` (seconds*1000, an
40
+ * integer ms) overrides the default when it parses to a positive integer.
41
+ * Lets an operator widen the window for separate-device / headless approval
42
+ * without threading a flag through every caller. Invalid values fall back.
43
+ */
44
+ export function resolveApprovalTimeoutMs() {
45
+ const raw = process.env.CHECKOUT_APPROVAL_TIMEOUT_MS;
46
+ if (raw !== undefined) {
47
+ const n = Number(raw);
48
+ if (Number.isSafeInteger(n) && n > 0)
49
+ return n;
50
+ }
51
+ return HOSTED_APPROVAL_TIMEOUT_MS;
52
+ }
6
53
  /** Unref'd so a raced-and-abandoned deadline timer can never hold the process open. */
7
54
  const defaultSleep = (ms) => new Promise((r) => {
8
55
  const t = setTimeout(r, ms);
9
56
  t.unref?.();
10
57
  });
11
58
  function defaultOpenUrl(url) {
12
- // Quoting: the URL is server-origin + our own base64url challenge — no
13
- // shell-hostile characters but single-quote anyway.
14
- exec(`open '${url.replaceAll("'", "'\\''")}'`);
59
+ // Best-effort convenience only — the URL is always surfaced via `log`/
60
+ // `onApprovalUrl`, so this must never throw or hang if there is no browser.
61
+ // `CHECKOUT_SKIP_BROWSER_OPEN=1` or `VISA_SUPPRESS_BROWSER=true|1` disables it
62
+ // (headless/agent hosts where launching a browser on the WRONG machine is pointless or noisy).
63
+ if (process.env.CHECKOUT_SKIP_BROWSER_OPEN === '1' ||
64
+ process.env.VISA_SUPPRESS_BROWSER === '1' ||
65
+ process.env.VISA_SUPPRESS_BROWSER === 'true')
66
+ return;
67
+ // Platform-appropriate opener; unknown platforms just skip (the URL is logged).
68
+ const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start ""' : 'xdg-open';
69
+ if (process.platform !== 'darwin' && process.platform !== 'win32' && process.platform !== 'linux')
70
+ return;
71
+ const quoted = `'${url.replaceAll("'", "'\\''")}'`;
72
+ try {
73
+ // exec is async and fire-and-forget; swallow the callback error so a missing
74
+ // opener binary (common on headless Linux) can never surface as a failure.
75
+ exec(`${opener} ${quoted}`, () => { });
76
+ }
77
+ catch {
78
+ // Spawn failure (no shell, sandboxed) — ignore; the printed URL is the path.
79
+ }
15
80
  }
16
81
  /**
17
- * The one deployed verify site hosted approval is the NORMAL path (no local
18
- * certs, no vendored SDK, no localhost anywhere), so its origin is a built-in
19
- * default rather than per-machine config. Not a secret: it's the public page
20
- * the operator's browser opens anyway.
82
+ * The staging apps/web deploy (which now hosts the /agent/enroll/approve page
83
+ * after the v4-verify-web GA graduation) hosted approval is the NORMAL path
84
+ * (no local certs, no vendored SDK, no localhost anywhere), so its origin is a
85
+ * built-in default rather than per-machine config. Not a secret: it's the
86
+ * public page the operator's browser opens anyway.
21
87
  */
22
- export const DEFAULT_APPROVAL_BASE_URL = 'https://v4-verify-web-visa-code-preview.up.railway.app';
88
+ export const DEFAULT_APPROVAL_BASE_URL = 'https://web-visa-code-preview.up.railway.app';
23
89
  /**
24
90
  * Flag > environment > built-in default. An explicitly EMPTY value
25
91
  * (CHECKOUT_APPROVAL_BASE_URL='') opts out of hosted approval entirely —
@@ -64,16 +130,36 @@ function stripTrailingSlashes(value) {
64
130
  * rather than falling back to a client-held secret.
65
131
  */
66
132
  export async function runHostedApproval(opts) {
67
- const { baseUrl, tokenId, target, consumerEmail, log = () => { }, openUrl = defaultOpenUrl, fetchImpl = fetch, sleep = defaultSleep, now = Date.now, pollIntervalMs = HOSTED_APPROVAL_POLL_MS, timeoutMs = HOSTED_APPROVAL_TIMEOUT_MS, } = opts;
133
+ const { baseUrl, tokenId, target, consumerEmail, agentJkt, maxDraws, perTransaction, intent,
134
+ // Default to stderr, NOT a no-op: the approval URL is the one thing a remote /
135
+ // SSH / headless-terminal human needs to proceed, and swallowing it (the old
136
+ // `() => {}` default) left it emitted nowhere readable. Tests inject their own.
137
+ log = (line) => void process.stderr.write(`${line}\n`), onApprovalUrl, openUrl = defaultOpenUrl, fetchImpl = fetch, sleep = defaultSleep, now = Date.now, pollIntervalMs = HOSTED_APPROVAL_POLL_MS,
138
+ // A human approving on a SEPARATE device (open the link, sign in, tap the
139
+ // passkey) needs more than the interactive 4-minute window; allow an env
140
+ // override without threading a flag through every caller.
141
+ timeoutMs = resolveApprovalTimeoutMs(), } = opts;
142
+ const canonicalJkt = typeof agentJkt === 'string' && /^[A-Za-z0-9_-]{43}$/.test(agentJkt);
143
+ if (!canonicalJkt) {
144
+ throw new Error('a budget approval requires the exact current agent request-key JKT');
145
+ }
68
146
  const base = stripTrailingSlashes(assertApprovalBaseUrl(baseUrl));
69
147
  // The server's currency map is uppercase ISO 4217; the loader normalizes the
70
148
  // target once, but normalize here too so a direct caller with a lowercase
71
149
  // code registers (and verifies) the same value the relay stores.
72
150
  const currency = target.transactionCurrencyCode.toUpperCase();
151
+ // Sanitize once, register + verify the SAME value: the relay stores the
152
+ // sanitized form, so equality below must compare against it, not the raw input.
153
+ const intentSanitized = sanitizeApprovalIntent(intent);
73
154
  const verifier = randomBytes(32).toString('base64url');
74
155
  const challenge = createHash('sha256').update(verifier, 'utf8').digest('base64url');
75
156
  const deadline = now() + timeoutMs;
76
- const timeoutError = () => new Error(`no passkey approval within ${Math.round(timeoutMs / 1000)}s — ` +
157
+ // Verification-neutral: what the page asks the human for is a per-card
158
+ // property (passkey ceremony, issuer one-time code, or nothing beyond the
159
+ // signed-in approval) that this runner never learns. Naming a passkey here
160
+ // told operators on code-verified cards to wait for a device prompt that was
161
+ // never coming, and then blamed the timeout on the step they never saw.
162
+ const timeoutError = () => new Error(`no approval within ${Math.round(timeoutMs / 1000)}s — ` +
77
163
  'the checkout was cancelled; run again to retry');
78
164
  // Bound EVERY request by the remaining deadline: race the fetch against the
79
165
  // (injectable) sleep and abort the request when the deadline wins, so a
@@ -107,6 +193,11 @@ export async function runHostedApproval(opts) {
107
193
  amount: target.transactionAmount,
108
194
  currency,
109
195
  ...(consumerEmail ? { consumerEmail } : {}),
196
+ budget: true,
197
+ agentJkt,
198
+ maxDraws,
199
+ ...(perTransaction !== undefined ? { perTransaction } : {}),
200
+ ...(intentSanitized !== undefined ? { intent: intentSanitized } : {}),
110
201
  },
111
202
  }),
112
203
  });
@@ -115,57 +206,293 @@ export async function runHostedApproval(opts) {
115
206
  throw new Error(`could not register the hosted approval (${registerRes.status})` +
116
207
  (body.error ? `: ${body.error}` : ''));
117
208
  }
118
- const approveUrl = `${base}/approve?req=${challenge}`;
209
+ // GA graduation: the approval page moved into apps/web under /agent/enroll
210
+ // (the /api/vgs/** routes above kept their paths verbatim).
211
+ const approveUrl = `${base}/agent/enroll/approve?req=${challenge}`;
212
+ // Surface the URL as DATA first (headless relay), then as a log line + best-
213
+ // effort browser open for the interactive case.
214
+ onApprovalUrl?.(approveUrl);
119
215
  log(`approve the purchase in your browser: ${approveUrl}`);
216
+ log(`budget recipient request key: ${agentJkt.slice(0, 8)}…${agentJkt.slice(-6)}`);
120
217
  openUrl(approveUrl);
121
- for (;;) {
122
- const res = await fetchWithDeadline(`${base}/api/vgs/agent-approval/claim`, {
123
- method: 'POST',
124
- headers: { 'content-type': 'application/json' },
125
- body: JSON.stringify({ verifier }),
126
- });
127
- if (res.ok) {
128
- const doc = (await res.json().catch(() => null));
129
- if (doc?.status === 'completed') {
130
- if (doc.assuranceData === undefined || doc.assuranceData === null) {
131
- throw new Error('hosted approval completed but carried no assuranceData');
132
- }
133
- // The context the approval was COMPLETED against must be exactly this
134
- // run's checkout target — a divergent field means the relay entry was
135
- // not ours (corruption, or a mutated registration) and the assurance
136
- // is scoped to something else. Fail naming the field; no secrets here
137
- // (merchant facts only).
138
- const expected = {
139
- tokenId,
140
- merchantName: target.merchantName,
141
- merchantUrl: target.merchantUrl,
142
- merchantCountryCode: target.merchantCountryCode,
143
- amount: target.transactionAmount,
144
- currency,
145
- };
146
- for (const [field, want] of Object.entries(expected)) {
147
- if (doc.context?.[field] !== want) {
148
- throw new Error(`hosted approval context mismatch on ${field} — the approval was not for this ` +
218
+ let lastHeartbeat = now();
219
+ // Keep the event loop alive for the whole poll wait. `defaultSleep` unref()'s
220
+ // its timer (so the deadline race can't hang the process past the timeout), but
221
+ // that means the ONLY pending work between polls is an unref'd timer — in a bare
222
+ // CLI invocation (no stdin/other handles) node would exit 0 mid-poll, after the
223
+ // first `pending` claim and before the operator finishes the passkey, so the
224
+ // minted token is parked but never claimed. A ref'd keepalive, cleared on every
225
+ // exit, holds the process open until the poll loop returns/throws.
226
+ const keepAlive = setInterval(() => { }, 60_000);
227
+ try {
228
+ for (;;) {
229
+ const res = await fetchWithDeadline(`${base}/api/vgs/agent-approval/claim`, {
230
+ method: 'POST',
231
+ headers: { 'content-type': 'application/json' },
232
+ body: JSON.stringify({ verifier }),
233
+ });
234
+ if (res.ok) {
235
+ const doc = (await res.json().catch(() => null));
236
+ // The operator refused — terminal and immediate. Exit the wait now
237
+ // rather than polling out the timeout; retrying cannot help.
238
+ if (doc?.status === 'declined')
239
+ throw new HostedApprovalDeclinedError();
240
+ if (doc?.status === 'completed') {
241
+ // A passkey-exempt token ('otp' cardholder ID&V / 'none') runs no
242
+ // ceremony and produces no assurance — the approval server marks the
243
+ // claim explicitly (derived from the owner's verified card record at
244
+ // complete-time). Only that marker excuses a null assuranceData; a
245
+ // silently dropped payload still fails exactly as before.
246
+ const assuranceExempt = doc.cardholderVerification === 'otp' || doc.cardholderVerification === 'none';
247
+ if ((doc.assuranceData === undefined || doc.assuranceData === null) && !assuranceExempt) {
248
+ throw new Error('hosted approval completed but carried no assuranceData');
249
+ }
250
+ // The context the approval was COMPLETED against must be exactly this
251
+ // run's checkout target — a divergent field means the relay entry was
252
+ // not ours (corruption, or a mutated registration) and the assurance
253
+ // is scoped to something else. Fail naming the field; no secrets here
254
+ // (merchant facts only).
255
+ const expected = {
256
+ tokenId,
257
+ merchantName: target.merchantName,
258
+ merchantUrl: target.merchantUrl,
259
+ merchantCountryCode: target.merchantCountryCode,
260
+ amount: target.transactionAmount,
261
+ currency,
262
+ };
263
+ for (const [field, want] of Object.entries(expected)) {
264
+ if (doc.context?.[field] !== want) {
265
+ throw new Error(`hosted approval context mismatch on ${field} — the approval was not for this ` +
266
+ 'exact purchase; run the checkout again for a fresh link');
267
+ }
268
+ }
269
+ // A budget approval must complete AS a budget approval — a relay that
270
+ // dropped the flag did not complete OUR registration. Compare the
271
+ // boolean explicitly (it is not a string, so it lives outside the
272
+ // string-map loop above).
273
+ if (doc.context?.budget !== true) {
274
+ throw new Error('hosted approval context mismatch on budget — the approval was not for this ' +
149
275
  'exact purchase; run the checkout again for a fresh link');
150
276
  }
277
+ if (doc.context?.agentJkt !== agentJkt) {
278
+ throw new Error('hosted approval context mismatch on agentJkt — the approval was not for this ' +
279
+ 'exact request key; run the checkout again for a fresh link');
280
+ }
281
+ // The draw ceiling must survive the relay intact too — a relay that
282
+ // dropped or altered maxDraws would mint a budget token whose draw
283
+ // count no longer matches what the operator approved. Compare exactly,
284
+ // the omitted/undefined case included, so a silently dropped value is
285
+ // caught the same as a mutated one.
286
+ if (doc.context?.maxDraws !== maxDraws) {
287
+ throw new Error('hosted approval context mismatch on maxDraws — the approval was not for this ' +
288
+ 'exact purchase; run the checkout again for a fresh link');
289
+ }
290
+ // Same drop-or-mutate rule for the per-purchase cap: the term the
291
+ // operator read must be the term the token enforces.
292
+ if (doc.context?.perTransaction !== perTransaction) {
293
+ throw new Error('hosted approval context mismatch on perTransaction — the approval was not for ' +
294
+ 'this exact purchase; run the checkout again for a fresh link');
295
+ }
296
+ // The intent is display-only, but a relay that altered it showed the
297
+ // operator different words than the agent sent — refuse, either way.
298
+ if (doc.context?.intent !== intentSanitized) {
299
+ throw new Error('hosted approval context mismatch on intent — the approval was not for this ' +
300
+ 'exact purchase; run the checkout again for a fresh link');
301
+ }
302
+ if (!Number.isSafeInteger(doc.validUntil) ||
303
+ doc.validUntil <= Math.floor(now() / 1000)) {
304
+ throw new Error('hosted budget approval completed without a valid future expiry');
305
+ }
306
+ log(assuranceExempt
307
+ ? 'approval received from the hosted page (code-verified card, no passkey).'
308
+ : 'approval received from the hosted page (passkey-verified card).');
309
+ return {
310
+ ...assuranceFromCeremony(target, doc.assuranceData ?? null),
311
+ ...(assuranceExempt ? { assuranceExempt: true } : {}),
312
+ ...(typeof doc.mintToken === 'string' && doc.mintToken
313
+ ? { mintToken: doc.mintToken }
314
+ : {}),
315
+ validUntil: doc.validUntil,
316
+ };
151
317
  }
152
- log('passkey approval received from the hosted page.');
153
- return {
154
- ...assuranceFromCeremony(target, doc.assuranceData),
155
- ...(typeof doc.mintToken === 'string' && doc.mintToken
156
- ? { mintToken: doc.mintToken }
157
- : {}),
158
- };
318
+ // status 'pending' the operator is still signing in / tapping.
319
+ }
320
+ else if (res.status === 404) {
321
+ // Registered moments ago, so absent now means expired or already claimed.
322
+ throw new Error('the hosted approval expired or was already used — run the checkout again for a fresh link');
159
323
  }
160
- // status 'pending' the operator is still signing in / tapping.
324
+ // Any other status (429 rate bucket, transient 5xx) polls through.
325
+ if (now() >= deadline)
326
+ throw timeoutError();
327
+ // Heartbeat so a human staring at a terminal (or an agent tailing logs)
328
+ // knows the wait is live and where to approve — the loop is otherwise silent
329
+ // for up to the full timeout between the open and the completed claim.
330
+ if (now() - lastHeartbeat >= HOSTED_APPROVAL_HEARTBEAT_MS) {
331
+ lastHeartbeat = now();
332
+ const leftS = Math.max(0, Math.round((deadline - now()) / 1000));
333
+ log(`still waiting for approval (~${leftS}s left) — approve at ${approveUrl}`);
334
+ }
335
+ await sleep(pollIntervalMs);
336
+ }
337
+ }
338
+ finally {
339
+ clearInterval(keepAlive);
340
+ }
341
+ }
342
+ const PICKUP_CODE_SHAPE = /^[A-Za-z0-9_-]{43}$/;
343
+ const DECIMAL_AMOUNT_SHAPE = /^[0-9]+(\.[0-9]{1,2})?$/;
344
+ function pickupMismatch(field, detail) {
345
+ return new Error(`mandate pickup code mismatch on ${field} — ${detail}. Ask the owner to start a fresh ` +
346
+ 'mandate in the panel for this agent');
347
+ }
348
+ export async function claimMandatePickup(opts) {
349
+ const { baseUrl, pickupCode, agentJkt, expectedHandoffId, tokenId, fetchImpl = fetch, sleep = defaultSleep, now = Date.now, attempts = 3, retryDelayMs = 1_000, } = opts;
350
+ // Both producers (runHostedApproval and the panel initiate route) mint the
351
+ // verifier as randomBytes(32).base64url = 43 chars; refuse anything else
352
+ // before it travels.
353
+ if (!PICKUP_CODE_SHAPE.test(pickupCode)) {
354
+ throw new Error('that does not look like a mandate pickup code (43 URL-safe characters) — ' +
355
+ 'paste the code exactly as the panel displayed it');
356
+ }
357
+ if (!/^[A-Za-z0-9_-]{43}$/.test(agentJkt)) {
358
+ throw new Error('claiming a mandate pickup requires the exact current agent request-key JKT');
359
+ }
360
+ if (!tokenId.trim()) {
361
+ throw new Error('claiming a mandate pickup requires the provisioned card token id');
362
+ }
363
+ const base = stripTrailingSlashes(assertApprovalBaseUrl(baseUrl));
364
+ let res = null;
365
+ for (let attempt = 1;; attempt++) {
366
+ res = await fetchImpl(`${base}/api/vgs/agent-approval/claim`, {
367
+ method: 'POST',
368
+ headers: { 'content-type': 'application/json' },
369
+ body: JSON.stringify({ verifier: pickupCode }),
370
+ });
371
+ // 4xx other than 404/429 is a terminal shape/validation answer; 404 is the
372
+ // single-use/TTL answer. Only rate-limit and 5xx are worth a bounded retry —
373
+ // the entry is durable until claimed or expired.
374
+ if (res.ok || res.status === 404 || (res.status < 500 && res.status !== 429))
375
+ break;
376
+ if (attempt >= attempts)
377
+ break;
378
+ await sleep(retryDelayMs);
379
+ }
380
+ if (res.status === 404) {
381
+ throw new Error('this pickup code has expired or was already used — codes are single-use and live ' +
382
+ 'about 10 minutes. Ask the owner to start a fresh mandate in the panel');
383
+ }
384
+ if (!res.ok) {
385
+ const body = (await res.json().catch(() => ({})));
386
+ throw new Error(`could not redeem the pickup code (${res.status})` + (body.error ? `: ${body.error}` : ''));
387
+ }
388
+ const doc = (await res.json().catch(() => null));
389
+ if (doc?.status === 'declined')
390
+ throw new HostedApprovalDeclinedError();
391
+ if (doc?.status !== 'completed') {
392
+ // A panel-issued pickup code is parked already-completed (the owner approved
393
+ // in the panel before the code existed). `pending` means this verifier came
394
+ // from an in-flight runner ceremony, not a mandate handoff — redeeming it
395
+ // here would race the runner that owns it.
396
+ throw new Error('this code is not a completed mandate handoff — it looks like an in-progress approval. ' +
397
+ 'Use the pickup code the panel displayed after the owner approved the mandate');
398
+ }
399
+ const ctx = doc.context ?? {};
400
+ if (ctx.budget !== true) {
401
+ throw pickupMismatch('budget', 'the approval is a one-purchase approval, not a spend budget');
402
+ }
403
+ // A budget names exactly ONE agent, by one of two pins.
404
+ //
405
+ // - `agentJkt` — the panel flow: the owner picked an agent that already
406
+ // existed, so the approval names its key and this runtime compares keys.
407
+ // - `handoffId` — the Add-agent dialog: the budget was minted before any
408
+ // agent existed, so it names the handoff the agent would go on to redeem.
409
+ // This runtime redeemed one moments ago and knows which, so the comparison
410
+ // is just as concrete — it is simply a different identifier.
411
+ //
412
+ // EXACTLY one, enforced before either is compared. Neither pin is an unbound
413
+ // budget, and "no pin" must never be the quiet way past a binding check.
414
+ // BOTH pins is worse: it names two agents, and checking whichever one happens
415
+ // to match would let the weaker claim decide. The signer refuses to mint such
416
+ // a context and the approval store refuses to hold one, so this is the third
417
+ // and last place to say it — the one that runs on material already in hand.
418
+ const hasHandoffPin = typeof ctx.handoffId === 'string';
419
+ const hasAgentPin = typeof ctx.agentJkt === 'string';
420
+ if (hasHandoffPin === hasAgentPin) {
421
+ throw pickupMismatch('agentJkt', hasHandoffPin
422
+ ? 'this budget names two different agents at once — it binds to a handoff or to a key, never both'
423
+ : 'this budget names no agent at all, so nothing can prove it belongs to this runtime');
424
+ }
425
+ if (hasHandoffPin) {
426
+ if (!expectedHandoffId || ctx.handoffId !== expectedHandoffId) {
427
+ throw pickupMismatch('handoffId', 'this budget belongs to a different agent handoff than the one this runtime just claimed');
161
428
  }
162
- else if (res.status === 404) {
163
- // Registered moments ago, so absent now means expired or already claimed.
164
- throw new Error('the hosted approval expired or was already used run the checkout again for a fresh link');
429
+ }
430
+ else if (ctx.agentJkt !== agentJkt) {
431
+ throw pickupMismatch('agentJkt', 'the owner approved this mandate for a different agent key than this runtime holds');
432
+ }
433
+ if (ctx.tokenId !== tokenId) {
434
+ throw pickupMismatch('tokenId', "the mandate was approved against a different enrolled card than this runtime's card " +
435
+ 'authority points at (the owner may have re-enrolled a card — re-run grant-card first)');
436
+ }
437
+ const ceiling = ctx.amount;
438
+ if (typeof ceiling !== 'string' || !DECIMAL_AMOUNT_SHAPE.test(ceiling) || Number(ceiling) <= 0) {
439
+ throw pickupMismatch('amount', 'the approved ceiling is missing or malformed');
440
+ }
441
+ const currency = ctx.currency;
442
+ if (typeof currency !== 'string' || !/^[A-Z]{3}$/.test(currency)) {
443
+ throw pickupMismatch('currency', 'the approved currency is missing or malformed');
444
+ }
445
+ const maxDraws = ctx.maxDraws;
446
+ if (!Number.isSafeInteger(maxDraws) || maxDraws < 1) {
447
+ throw pickupMismatch('maxDraws', 'the approved purchase count is missing or malformed');
448
+ }
449
+ const perTransaction = ctx.perTransaction;
450
+ if (perTransaction !== undefined) {
451
+ if (typeof perTransaction !== 'string' ||
452
+ !DECIMAL_AMOUNT_SHAPE.test(perTransaction) ||
453
+ Number(perTransaction) <= 0 ||
454
+ Number(perTransaction) > Number(ceiling)) {
455
+ throw pickupMismatch('perTransaction', 'the approved per-purchase cap is malformed');
165
456
  }
166
- // Any other status (429 rate bucket, transient 5xx) polls through.
167
- if (now() >= deadline)
168
- throw timeoutError();
169
- await sleep(pollIntervalMs);
170
457
  }
458
+ const merchantName = ctx.merchantName;
459
+ const merchantUrl = ctx.merchantUrl;
460
+ const merchantCountryCode = ctx.merchantCountryCode;
461
+ if (typeof merchantName !== 'string' ||
462
+ !merchantName.trim() ||
463
+ typeof merchantUrl !== 'string' ||
464
+ !merchantUrl.trim() ||
465
+ typeof merchantCountryCode !== 'string' ||
466
+ !merchantCountryCode.trim()) {
467
+ throw pickupMismatch('merchant', 'the approved budget target is missing or malformed');
468
+ }
469
+ if (typeof doc.mintToken !== 'string' || !doc.mintToken) {
470
+ throw new Error('the mandate handoff carried no mint token — the deployment that parked it ran the ' +
471
+ 'dev-auth stub, which cannot mint draw authority. Re-initiate against a real deployment');
472
+ }
473
+ if (!Number.isSafeInteger(doc.validUntil) ||
474
+ doc.validUntil <= Math.floor(now() / 1000)) {
475
+ throw new Error('the mandate handoff carried no valid future expiry — ask the owner to re-initiate');
476
+ }
477
+ // Same exemption contract as runHostedApproval: only the server's explicit
478
+ // code-verified-card marker excuses a missing assurance payload.
479
+ const assuranceExempt = doc.cardholderVerification === 'otp' || doc.cardholderVerification === 'none';
480
+ if ((doc.assuranceData === undefined || doc.assuranceData === null) && !assuranceExempt) {
481
+ throw new Error('the mandate handoff completed but carried no assuranceData');
482
+ }
483
+ return {
484
+ assuranceData: doc.assuranceData ?? null,
485
+ assuranceExempt,
486
+ mintToken: doc.mintToken,
487
+ validUntil: doc.validUntil,
488
+ ceiling,
489
+ currency,
490
+ maxDraws: maxDraws,
491
+ ...(perTransaction !== undefined ? { perTransaction: perTransaction } : {}),
492
+ merchant: {
493
+ name: merchantName,
494
+ url: merchantUrl,
495
+ countryCode: merchantCountryCode,
496
+ },
497
+ };
171
498
  }