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

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 +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.d.ts +18 -0
  50. package/dist/checkout-engine/vic-confirmation.js +9 -3
  51. package/dist/checkout-engine/web-bot-auth.d.ts +92 -0
  52. package/dist/checkout-engine/web-bot-auth.js +159 -0
  53. package/dist/cli.js +663 -492
  54. package/dist/mcp-apps/ucp-checkout.html +280 -0
  55. package/dist/mcp-server/index.js +514 -174
  56. package/dist/skills/pair-visa-agent/RUNTIMES.md +92 -0
  57. package/dist/skills/pair-visa-agent/SKILL.md +526 -0
  58. package/dist/skills/pair-visa-agent/scripts/setup.mjs +48 -0
  59. package/dist/subway-direct.mjs +1 -0
  60. package/install.ps1 +3 -41
  61. package/install.sh +4 -36
  62. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  63. package/package.json +18 -14
  64. package/server.json +3 -3
  65. package/dist/checkout-engine/inline-target.d.ts +0 -13
  66. package/dist/checkout-engine/inline-target.js +0 -37
  67. package/dist/checkout-engine/pay-args.d.ts +0 -14
  68. package/dist/checkout-engine/pay-args.js +0 -44
  69. package/dist/checkout-engine/pay.d.ts +0 -1
  70. package/dist/checkout-engine/pay.js +0 -13
  71. package/dist/checkout-engine/repo-env.d.ts +0 -11
  72. package/dist/checkout-engine/repo-env.js +0 -23
  73. package/dist/checkout-engine/run-live-fill.d.ts +0 -1
  74. package/dist/checkout-engine/run-live-fill.js +0 -443
  75. package/dist/checkout-engine/vgs-gateway/fetch-credential.d.mts +0 -74
  76. 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,89 @@
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` disables it (headless/agent hosts where
62
+ // launching a browser on the WRONG machine is pointless or noisy).
63
+ if (process.env.CHECKOUT_SKIP_BROWSER_OPEN === '1')
64
+ return;
65
+ // Platform-appropriate opener; unknown platforms just skip (the URL is logged).
66
+ const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start ""' : 'xdg-open';
67
+ if (process.platform !== 'darwin' && process.platform !== 'win32' && process.platform !== 'linux')
68
+ return;
69
+ const quoted = `'${url.replaceAll("'", "'\\''")}'`;
70
+ try {
71
+ // exec is async and fire-and-forget; swallow the callback error so a missing
72
+ // opener binary (common on headless Linux) can never surface as a failure.
73
+ exec(`${opener} ${quoted}`, () => { });
74
+ }
75
+ catch {
76
+ // Spawn failure (no shell, sandboxed) — ignore; the printed URL is the path.
77
+ }
15
78
  }
16
79
  /**
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.
80
+ * The staging apps/web deploy (which now hosts the /agent/enroll/approve page
81
+ * after the v4-verify-web GA graduation) hosted approval is the NORMAL path
82
+ * (no local certs, no vendored SDK, no localhost anywhere), so its origin is a
83
+ * built-in default rather than per-machine config. Not a secret: it's the
84
+ * public page the operator's browser opens anyway.
21
85
  */
22
- export const DEFAULT_APPROVAL_BASE_URL = 'https://v4-verify-web-visa-code-preview.up.railway.app';
86
+ export const DEFAULT_APPROVAL_BASE_URL = 'https://web-visa-code-preview.up.railway.app';
23
87
  /**
24
88
  * Flag > environment > built-in default. An explicitly EMPTY value
25
89
  * (CHECKOUT_APPROVAL_BASE_URL='') opts out of hosted approval entirely —
@@ -64,16 +128,36 @@ function stripTrailingSlashes(value) {
64
128
  * rather than falling back to a client-held secret.
65
129
  */
66
130
  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;
131
+ const { baseUrl, tokenId, target, consumerEmail, agentJkt, maxDraws, perTransaction, intent,
132
+ // Default to stderr, NOT a no-op: the approval URL is the one thing a remote /
133
+ // SSH / headless-terminal human needs to proceed, and swallowing it (the old
134
+ // `() => {}` default) left it emitted nowhere readable. Tests inject their own.
135
+ log = (line) => void process.stderr.write(`${line}\n`), onApprovalUrl, openUrl = defaultOpenUrl, fetchImpl = fetch, sleep = defaultSleep, now = Date.now, pollIntervalMs = HOSTED_APPROVAL_POLL_MS,
136
+ // A human approving on a SEPARATE device (open the link, sign in, tap the
137
+ // passkey) needs more than the interactive 4-minute window; allow an env
138
+ // override without threading a flag through every caller.
139
+ timeoutMs = resolveApprovalTimeoutMs(), } = opts;
140
+ const canonicalJkt = typeof agentJkt === 'string' && /^[A-Za-z0-9_-]{43}$/.test(agentJkt);
141
+ if (!canonicalJkt) {
142
+ throw new Error('a budget approval requires the exact current agent request-key JKT');
143
+ }
68
144
  const base = stripTrailingSlashes(assertApprovalBaseUrl(baseUrl));
69
145
  // The server's currency map is uppercase ISO 4217; the loader normalizes the
70
146
  // target once, but normalize here too so a direct caller with a lowercase
71
147
  // code registers (and verifies) the same value the relay stores.
72
148
  const currency = target.transactionCurrencyCode.toUpperCase();
149
+ // Sanitize once, register + verify the SAME value: the relay stores the
150
+ // sanitized form, so equality below must compare against it, not the raw input.
151
+ const intentSanitized = sanitizeApprovalIntent(intent);
73
152
  const verifier = randomBytes(32).toString('base64url');
74
153
  const challenge = createHash('sha256').update(verifier, 'utf8').digest('base64url');
75
154
  const deadline = now() + timeoutMs;
76
- const timeoutError = () => new Error(`no passkey approval within ${Math.round(timeoutMs / 1000)}s — ` +
155
+ // Verification-neutral: what the page asks the human for is a per-card
156
+ // property (passkey ceremony, issuer one-time code, or nothing beyond the
157
+ // signed-in approval) that this runner never learns. Naming a passkey here
158
+ // told operators on code-verified cards to wait for a device prompt that was
159
+ // never coming, and then blamed the timeout on the step they never saw.
160
+ const timeoutError = () => new Error(`no approval within ${Math.round(timeoutMs / 1000)}s — ` +
77
161
  'the checkout was cancelled; run again to retry');
78
162
  // Bound EVERY request by the remaining deadline: race the fetch against the
79
163
  // (injectable) sleep and abort the request when the deadline wins, so a
@@ -107,6 +191,11 @@ export async function runHostedApproval(opts) {
107
191
  amount: target.transactionAmount,
108
192
  currency,
109
193
  ...(consumerEmail ? { consumerEmail } : {}),
194
+ budget: true,
195
+ agentJkt,
196
+ maxDraws,
197
+ ...(perTransaction !== undefined ? { perTransaction } : {}),
198
+ ...(intentSanitized !== undefined ? { intent: intentSanitized } : {}),
110
199
  },
111
200
  }),
112
201
  });
@@ -115,57 +204,293 @@ export async function runHostedApproval(opts) {
115
204
  throw new Error(`could not register the hosted approval (${registerRes.status})` +
116
205
  (body.error ? `: ${body.error}` : ''));
117
206
  }
118
- const approveUrl = `${base}/approve?req=${challenge}`;
207
+ // GA graduation: the approval page moved into apps/web under /agent/enroll
208
+ // (the /api/vgs/** routes above kept their paths verbatim).
209
+ const approveUrl = `${base}/agent/enroll/approve?req=${challenge}`;
210
+ // Surface the URL as DATA first (headless relay), then as a log line + best-
211
+ // effort browser open for the interactive case.
212
+ onApprovalUrl?.(approveUrl);
119
213
  log(`approve the purchase in your browser: ${approveUrl}`);
214
+ log(`budget recipient request key: ${agentJkt.slice(0, 8)}…${agentJkt.slice(-6)}`);
120
215
  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 ` +
216
+ let lastHeartbeat = now();
217
+ // Keep the event loop alive for the whole poll wait. `defaultSleep` unref()'s
218
+ // its timer (so the deadline race can't hang the process past the timeout), but
219
+ // that means the ONLY pending work between polls is an unref'd timer — in a bare
220
+ // CLI invocation (no stdin/other handles) node would exit 0 mid-poll, after the
221
+ // first `pending` claim and before the operator finishes the passkey, so the
222
+ // minted token is parked but never claimed. A ref'd keepalive, cleared on every
223
+ // exit, holds the process open until the poll loop returns/throws.
224
+ const keepAlive = setInterval(() => { }, 60_000);
225
+ try {
226
+ for (;;) {
227
+ const res = await fetchWithDeadline(`${base}/api/vgs/agent-approval/claim`, {
228
+ method: 'POST',
229
+ headers: { 'content-type': 'application/json' },
230
+ body: JSON.stringify({ verifier }),
231
+ });
232
+ if (res.ok) {
233
+ const doc = (await res.json().catch(() => null));
234
+ // The operator refused — terminal and immediate. Exit the wait now
235
+ // rather than polling out the timeout; retrying cannot help.
236
+ if (doc?.status === 'declined')
237
+ throw new HostedApprovalDeclinedError();
238
+ if (doc?.status === 'completed') {
239
+ // A passkey-exempt token ('otp' cardholder ID&V / 'none') runs no
240
+ // ceremony and produces no assurance — the approval server marks the
241
+ // claim explicitly (derived from the owner's verified card record at
242
+ // complete-time). Only that marker excuses a null assuranceData; a
243
+ // silently dropped payload still fails exactly as before.
244
+ const assuranceExempt = doc.cardholderVerification === 'otp' || doc.cardholderVerification === 'none';
245
+ if ((doc.assuranceData === undefined || doc.assuranceData === null) && !assuranceExempt) {
246
+ throw new Error('hosted approval completed but carried no assuranceData');
247
+ }
248
+ // The context the approval was COMPLETED against must be exactly this
249
+ // run's checkout target — a divergent field means the relay entry was
250
+ // not ours (corruption, or a mutated registration) and the assurance
251
+ // is scoped to something else. Fail naming the field; no secrets here
252
+ // (merchant facts only).
253
+ const expected = {
254
+ tokenId,
255
+ merchantName: target.merchantName,
256
+ merchantUrl: target.merchantUrl,
257
+ merchantCountryCode: target.merchantCountryCode,
258
+ amount: target.transactionAmount,
259
+ currency,
260
+ };
261
+ for (const [field, want] of Object.entries(expected)) {
262
+ if (doc.context?.[field] !== want) {
263
+ throw new Error(`hosted approval context mismatch on ${field} — the approval was not for this ` +
264
+ 'exact purchase; run the checkout again for a fresh link');
265
+ }
266
+ }
267
+ // A budget approval must complete AS a budget approval — a relay that
268
+ // dropped the flag did not complete OUR registration. Compare the
269
+ // boolean explicitly (it is not a string, so it lives outside the
270
+ // string-map loop above).
271
+ if (doc.context?.budget !== true) {
272
+ throw new Error('hosted approval context mismatch on budget — the approval was not for this ' +
149
273
  'exact purchase; run the checkout again for a fresh link');
150
274
  }
275
+ if (doc.context?.agentJkt !== agentJkt) {
276
+ throw new Error('hosted approval context mismatch on agentJkt — the approval was not for this ' +
277
+ 'exact request key; run the checkout again for a fresh link');
278
+ }
279
+ // The draw ceiling must survive the relay intact too — a relay that
280
+ // dropped or altered maxDraws would mint a budget token whose draw
281
+ // count no longer matches what the operator approved. Compare exactly,
282
+ // the omitted/undefined case included, so a silently dropped value is
283
+ // caught the same as a mutated one.
284
+ if (doc.context?.maxDraws !== maxDraws) {
285
+ throw new Error('hosted approval context mismatch on maxDraws — the approval was not for this ' +
286
+ 'exact purchase; run the checkout again for a fresh link');
287
+ }
288
+ // Same drop-or-mutate rule for the per-purchase cap: the term the
289
+ // operator read must be the term the token enforces.
290
+ if (doc.context?.perTransaction !== perTransaction) {
291
+ throw new Error('hosted approval context mismatch on perTransaction — the approval was not for ' +
292
+ 'this exact purchase; run the checkout again for a fresh link');
293
+ }
294
+ // The intent is display-only, but a relay that altered it showed the
295
+ // operator different words than the agent sent — refuse, either way.
296
+ if (doc.context?.intent !== intentSanitized) {
297
+ throw new Error('hosted approval context mismatch on intent — the approval was not for this ' +
298
+ 'exact purchase; run the checkout again for a fresh link');
299
+ }
300
+ if (!Number.isSafeInteger(doc.validUntil) ||
301
+ doc.validUntil <= Math.floor(now() / 1000)) {
302
+ throw new Error('hosted budget approval completed without a valid future expiry');
303
+ }
304
+ log(assuranceExempt
305
+ ? 'approval received from the hosted page (code-verified card, no passkey).'
306
+ : 'approval received from the hosted page (passkey-verified card).');
307
+ return {
308
+ ...assuranceFromCeremony(target, doc.assuranceData ?? null),
309
+ ...(assuranceExempt ? { assuranceExempt: true } : {}),
310
+ ...(typeof doc.mintToken === 'string' && doc.mintToken
311
+ ? { mintToken: doc.mintToken }
312
+ : {}),
313
+ validUntil: doc.validUntil,
314
+ };
151
315
  }
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
- };
316
+ // status 'pending' the operator is still signing in / tapping.
317
+ }
318
+ else if (res.status === 404) {
319
+ // Registered moments ago, so absent now means expired or already claimed.
320
+ throw new Error('the hosted approval expired or was already used — run the checkout again for a fresh link');
159
321
  }
160
- // status 'pending' the operator is still signing in / tapping.
322
+ // Any other status (429 rate bucket, transient 5xx) polls through.
323
+ if (now() >= deadline)
324
+ throw timeoutError();
325
+ // Heartbeat so a human staring at a terminal (or an agent tailing logs)
326
+ // knows the wait is live and where to approve — the loop is otherwise silent
327
+ // for up to the full timeout between the open and the completed claim.
328
+ if (now() - lastHeartbeat >= HOSTED_APPROVAL_HEARTBEAT_MS) {
329
+ lastHeartbeat = now();
330
+ const leftS = Math.max(0, Math.round((deadline - now()) / 1000));
331
+ log(`still waiting for approval (~${leftS}s left) — approve at ${approveUrl}`);
332
+ }
333
+ await sleep(pollIntervalMs);
334
+ }
335
+ }
336
+ finally {
337
+ clearInterval(keepAlive);
338
+ }
339
+ }
340
+ const PICKUP_CODE_SHAPE = /^[A-Za-z0-9_-]{43}$/;
341
+ const DECIMAL_AMOUNT_SHAPE = /^[0-9]+(\.[0-9]{1,2})?$/;
342
+ function pickupMismatch(field, detail) {
343
+ return new Error(`mandate pickup code mismatch on ${field} — ${detail}. Ask the owner to start a fresh ` +
344
+ 'mandate in the panel for this agent');
345
+ }
346
+ export async function claimMandatePickup(opts) {
347
+ const { baseUrl, pickupCode, agentJkt, expectedHandoffId, tokenId, fetchImpl = fetch, sleep = defaultSleep, now = Date.now, attempts = 3, retryDelayMs = 1_000, } = opts;
348
+ // Both producers (runHostedApproval and the panel initiate route) mint the
349
+ // verifier as randomBytes(32).base64url = 43 chars; refuse anything else
350
+ // before it travels.
351
+ if (!PICKUP_CODE_SHAPE.test(pickupCode)) {
352
+ throw new Error('that does not look like a mandate pickup code (43 URL-safe characters) — ' +
353
+ 'paste the code exactly as the panel displayed it');
354
+ }
355
+ if (!/^[A-Za-z0-9_-]{43}$/.test(agentJkt)) {
356
+ throw new Error('claiming a mandate pickup requires the exact current agent request-key JKT');
357
+ }
358
+ if (!tokenId.trim()) {
359
+ throw new Error('claiming a mandate pickup requires the provisioned card token id');
360
+ }
361
+ const base = stripTrailingSlashes(assertApprovalBaseUrl(baseUrl));
362
+ let res = null;
363
+ for (let attempt = 1;; attempt++) {
364
+ res = await fetchImpl(`${base}/api/vgs/agent-approval/claim`, {
365
+ method: 'POST',
366
+ headers: { 'content-type': 'application/json' },
367
+ body: JSON.stringify({ verifier: pickupCode }),
368
+ });
369
+ // 4xx other than 404/429 is a terminal shape/validation answer; 404 is the
370
+ // single-use/TTL answer. Only rate-limit and 5xx are worth a bounded retry —
371
+ // the entry is durable until claimed or expired.
372
+ if (res.ok || res.status === 404 || (res.status < 500 && res.status !== 429))
373
+ break;
374
+ if (attempt >= attempts)
375
+ break;
376
+ await sleep(retryDelayMs);
377
+ }
378
+ if (res.status === 404) {
379
+ throw new Error('this pickup code has expired or was already used — codes are single-use and live ' +
380
+ 'about 10 minutes. Ask the owner to start a fresh mandate in the panel');
381
+ }
382
+ if (!res.ok) {
383
+ const body = (await res.json().catch(() => ({})));
384
+ throw new Error(`could not redeem the pickup code (${res.status})` + (body.error ? `: ${body.error}` : ''));
385
+ }
386
+ const doc = (await res.json().catch(() => null));
387
+ if (doc?.status === 'declined')
388
+ throw new HostedApprovalDeclinedError();
389
+ if (doc?.status !== 'completed') {
390
+ // A panel-issued pickup code is parked already-completed (the owner approved
391
+ // in the panel before the code existed). `pending` means this verifier came
392
+ // from an in-flight runner ceremony, not a mandate handoff — redeeming it
393
+ // here would race the runner that owns it.
394
+ throw new Error('this code is not a completed mandate handoff — it looks like an in-progress approval. ' +
395
+ 'Use the pickup code the panel displayed after the owner approved the mandate');
396
+ }
397
+ const ctx = doc.context ?? {};
398
+ if (ctx.budget !== true) {
399
+ throw pickupMismatch('budget', 'the approval is a one-purchase approval, not a spend budget');
400
+ }
401
+ // A budget names exactly ONE agent, by one of two pins.
402
+ //
403
+ // - `agentJkt` — the panel flow: the owner picked an agent that already
404
+ // existed, so the approval names its key and this runtime compares keys.
405
+ // - `handoffId` — the Add-agent dialog: the budget was minted before any
406
+ // agent existed, so it names the handoff the agent would go on to redeem.
407
+ // This runtime redeemed one moments ago and knows which, so the comparison
408
+ // is just as concrete — it is simply a different identifier.
409
+ //
410
+ // EXACTLY one, enforced before either is compared. Neither pin is an unbound
411
+ // budget, and "no pin" must never be the quiet way past a binding check.
412
+ // BOTH pins is worse: it names two agents, and checking whichever one happens
413
+ // to match would let the weaker claim decide. The signer refuses to mint such
414
+ // a context and the approval store refuses to hold one, so this is the third
415
+ // and last place to say it — the one that runs on material already in hand.
416
+ const hasHandoffPin = typeof ctx.handoffId === 'string';
417
+ const hasAgentPin = typeof ctx.agentJkt === 'string';
418
+ if (hasHandoffPin === hasAgentPin) {
419
+ throw pickupMismatch('agentJkt', hasHandoffPin
420
+ ? 'this budget names two different agents at once — it binds to a handoff or to a key, never both'
421
+ : 'this budget names no agent at all, so nothing can prove it belongs to this runtime');
422
+ }
423
+ if (hasHandoffPin) {
424
+ if (!expectedHandoffId || ctx.handoffId !== expectedHandoffId) {
425
+ throw pickupMismatch('handoffId', 'this budget belongs to a different agent handoff than the one this runtime just claimed');
161
426
  }
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');
427
+ }
428
+ else if (ctx.agentJkt !== agentJkt) {
429
+ throw pickupMismatch('agentJkt', 'the owner approved this mandate for a different agent key than this runtime holds');
430
+ }
431
+ if (ctx.tokenId !== tokenId) {
432
+ throw pickupMismatch('tokenId', "the mandate was approved against a different enrolled card than this runtime's card " +
433
+ 'authority points at (the owner may have re-enrolled a card — re-run grant-card first)');
434
+ }
435
+ const ceiling = ctx.amount;
436
+ if (typeof ceiling !== 'string' || !DECIMAL_AMOUNT_SHAPE.test(ceiling) || Number(ceiling) <= 0) {
437
+ throw pickupMismatch('amount', 'the approved ceiling is missing or malformed');
438
+ }
439
+ const currency = ctx.currency;
440
+ if (typeof currency !== 'string' || !/^[A-Z]{3}$/.test(currency)) {
441
+ throw pickupMismatch('currency', 'the approved currency is missing or malformed');
442
+ }
443
+ const maxDraws = ctx.maxDraws;
444
+ if (!Number.isSafeInteger(maxDraws) || maxDraws < 1) {
445
+ throw pickupMismatch('maxDraws', 'the approved purchase count is missing or malformed');
446
+ }
447
+ const perTransaction = ctx.perTransaction;
448
+ if (perTransaction !== undefined) {
449
+ if (typeof perTransaction !== 'string' ||
450
+ !DECIMAL_AMOUNT_SHAPE.test(perTransaction) ||
451
+ Number(perTransaction) <= 0 ||
452
+ Number(perTransaction) > Number(ceiling)) {
453
+ throw pickupMismatch('perTransaction', 'the approved per-purchase cap is malformed');
165
454
  }
166
- // Any other status (429 rate bucket, transient 5xx) polls through.
167
- if (now() >= deadline)
168
- throw timeoutError();
169
- await sleep(pollIntervalMs);
170
455
  }
456
+ const merchantName = ctx.merchantName;
457
+ const merchantUrl = ctx.merchantUrl;
458
+ const merchantCountryCode = ctx.merchantCountryCode;
459
+ if (typeof merchantName !== 'string' ||
460
+ !merchantName.trim() ||
461
+ typeof merchantUrl !== 'string' ||
462
+ !merchantUrl.trim() ||
463
+ typeof merchantCountryCode !== 'string' ||
464
+ !merchantCountryCode.trim()) {
465
+ throw pickupMismatch('merchant', 'the approved budget target is missing or malformed');
466
+ }
467
+ if (typeof doc.mintToken !== 'string' || !doc.mintToken) {
468
+ throw new Error('the mandate handoff carried no mint token — the deployment that parked it ran the ' +
469
+ 'dev-auth stub, which cannot mint draw authority. Re-initiate against a real deployment');
470
+ }
471
+ if (!Number.isSafeInteger(doc.validUntil) ||
472
+ doc.validUntil <= Math.floor(now() / 1000)) {
473
+ throw new Error('the mandate handoff carried no valid future expiry — ask the owner to re-initiate');
474
+ }
475
+ // Same exemption contract as runHostedApproval: only the server's explicit
476
+ // code-verified-card marker excuses a missing assurance payload.
477
+ const assuranceExempt = doc.cardholderVerification === 'otp' || doc.cardholderVerification === 'none';
478
+ if ((doc.assuranceData === undefined || doc.assuranceData === null) && !assuranceExempt) {
479
+ throw new Error('the mandate handoff completed but carried no assuranceData');
480
+ }
481
+ return {
482
+ assuranceData: doc.assuranceData ?? null,
483
+ assuranceExempt,
484
+ mintToken: doc.mintToken,
485
+ validUntil: doc.validUntil,
486
+ ceiling,
487
+ currency,
488
+ maxDraws: maxDraws,
489
+ ...(perTransaction !== undefined ? { perTransaction: perTransaction } : {}),
490
+ merchant: {
491
+ name: merchantName,
492
+ url: merchantUrl,
493
+ countryCode: merchantCountryCode,
494
+ },
495
+ };
171
496
  }