@visa/cli 4.1.0-rc.13 → 4.1.0-rc.130

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 (63) hide show
  1. package/README.md +188 -232
  2. package/dist/checkout-engine/adapters/generic.d.ts +4 -0
  3. package/dist/checkout-engine/adapters/generic.js +28 -13
  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 +31 -0
  7. package/dist/checkout-engine/adapters/shopify.js +423 -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 +207 -2
  11. package/dist/checkout-engine/cli-engine.js +677 -27
  12. package/dist/checkout-engine/detect.d.ts +1 -1
  13. package/dist/checkout-engine/detect.js +26 -0
  14. package/dist/checkout-engine/evidence.d.ts +4 -1
  15. package/dist/checkout-engine/evidence.js +51 -6
  16. package/dist/checkout-engine/executor.d.ts +34 -4
  17. package/dist/checkout-engine/executor.js +266 -115
  18. package/dist/checkout-engine/hosted-approval.d.ts +133 -8
  19. package/dist/checkout-engine/hosted-approval.js +400 -49
  20. package/dist/checkout-engine/index.d.ts +4 -1
  21. package/dist/checkout-engine/index.js +3 -0
  22. package/dist/checkout-engine/instrument.d.ts +7 -0
  23. package/dist/checkout-engine/instrument.js +4 -0
  24. package/dist/checkout-engine/live-fill-approval.d.ts +0 -20
  25. package/dist/checkout-engine/live-fill-approval.js +15 -51
  26. package/dist/checkout-engine/mandate/card-mandate.d.ts +121 -0
  27. package/dist/checkout-engine/mandate/card-mandate.js +227 -0
  28. package/dist/checkout-engine/mandate/mandate-ledger.d.ts +165 -0
  29. package/dist/checkout-engine/mandate/mandate-ledger.js +373 -0
  30. package/dist/checkout-engine/outcome.d.ts +2 -2
  31. package/dist/checkout-engine/outcome.js +36 -1
  32. package/dist/checkout-engine/owner-only-file.d.ts +9 -0
  33. package/dist/checkout-engine/owner-only-file.js +20 -1
  34. package/dist/checkout-engine/trace-handles.d.ts +8 -0
  35. package/dist/checkout-engine/trace-handles.js +12 -0
  36. package/dist/checkout-engine/types.d.ts +20 -2
  37. package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +82 -0
  38. package/dist/checkout-engine/vgs-gateway/server-mint-client.js +180 -0
  39. package/dist/checkout-engine/vgs-live-instrument.d.ts +38 -0
  40. package/dist/checkout-engine/vgs-live-instrument.js +52 -8
  41. package/dist/checkout-engine/vic-confirmation.js +2 -2
  42. package/dist/cli.js +579 -494
  43. package/dist/mcp-server/index.js +441 -176
  44. package/dist/skills/pair-visa-agent/RUNTIMES.md +92 -0
  45. package/dist/skills/pair-visa-agent/SKILL.md +467 -0
  46. package/dist/skills/pair-visa-agent/scripts/setup.mjs +48 -0
  47. package/install.ps1 +3 -41
  48. package/install.sh +4 -36
  49. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  50. package/package.json +16 -12
  51. package/server.json +3 -3
  52. package/dist/checkout-engine/inline-target.d.ts +0 -13
  53. package/dist/checkout-engine/inline-target.js +0 -37
  54. package/dist/checkout-engine/pay-args.d.ts +0 -14
  55. package/dist/checkout-engine/pay-args.js +0 -44
  56. package/dist/checkout-engine/pay.d.ts +0 -1
  57. package/dist/checkout-engine/pay.js +0 -13
  58. package/dist/checkout-engine/repo-env.d.ts +0 -11
  59. package/dist/checkout-engine/repo-env.js +0 -23
  60. package/dist/checkout-engine/run-live-fill.d.ts +0 -1
  61. package/dist/checkout-engine/run-live-fill.js +0 -443
  62. package/dist/checkout-engine/vgs-gateway/fetch-credential.d.mts +0 -74
  63. package/dist/checkout-engine/vgs-gateway/fetch-credential.mjs +0 -240
@@ -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 —
@@ -56,17 +120,47 @@ function stripTrailingSlashes(value) {
56
120
  out = out.slice(0, -1);
57
121
  return out;
58
122
  }
123
+ /**
124
+ * The claim also releases the scoped MINT TOKEN (server-side mint, Phase 1) —
125
+ * bound to this exact approved purchase — so the runner can call the gateway
126
+ * mint routes without the VGS secret. Absent when the deployment ran the
127
+ * dev-auth stub (it mints no token); the caller then surfaces a clear error
128
+ * rather than falling back to a client-held secret.
129
+ */
59
130
  export async function runHostedApproval(opts) {
60
- 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, budget, 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 (budget && !canonicalJkt) {
142
+ throw new Error('a budget approval requires the exact current agent request-key JKT');
143
+ }
144
+ if (!budget && agentJkt !== undefined) {
145
+ throw new Error('agentJkt is accepted only for a budget approval');
146
+ }
61
147
  const base = stripTrailingSlashes(assertApprovalBaseUrl(baseUrl));
62
148
  // The server's currency map is uppercase ISO 4217; the loader normalizes the
63
149
  // target once, but normalize here too so a direct caller with a lowercase
64
150
  // code registers (and verifies) the same value the relay stores.
65
151
  const currency = target.transactionCurrencyCode.toUpperCase();
152
+ // Sanitize once, register + verify the SAME value: the relay stores the
153
+ // sanitized form, so equality below must compare against it, not the raw input.
154
+ const intentSanitized = sanitizeApprovalIntent(intent);
66
155
  const verifier = randomBytes(32).toString('base64url');
67
156
  const challenge = createHash('sha256').update(verifier, 'utf8').digest('base64url');
68
157
  const deadline = now() + timeoutMs;
69
- const timeoutError = () => new Error(`no passkey approval within ${Math.round(timeoutMs / 1000)}s — ` +
158
+ // Verification-neutral: what the page asks the human for is a per-card
159
+ // property (passkey ceremony, issuer one-time code, or nothing beyond the
160
+ // signed-in approval) that this runner never learns. Naming a passkey here
161
+ // told operators on code-verified cards to wait for a device prompt that was
162
+ // never coming, and then blamed the timeout on the step they never saw.
163
+ const timeoutError = () => new Error(`no approval within ${Math.round(timeoutMs / 1000)}s — ` +
70
164
  'the checkout was cancelled; run again to retry');
71
165
  // Bound EVERY request by the remaining deadline: race the fetch against the
72
166
  // (injectable) sleep and abort the request when the deadline wins, so a
@@ -100,6 +194,11 @@ export async function runHostedApproval(opts) {
100
194
  amount: target.transactionAmount,
101
195
  currency,
102
196
  ...(consumerEmail ? { consumerEmail } : {}),
197
+ ...(budget ? { budget: true } : {}),
198
+ ...(budget ? { agentJkt } : {}),
199
+ ...(budget && maxDraws !== undefined ? { maxDraws } : {}),
200
+ ...(budget && perTransaction !== undefined ? { perTransaction } : {}),
201
+ ...(intentSanitized !== undefined ? { intent: intentSanitized } : {}),
103
202
  },
104
203
  }),
105
204
  });
@@ -108,52 +207,304 @@ export async function runHostedApproval(opts) {
108
207
  throw new Error(`could not register the hosted approval (${registerRes.status})` +
109
208
  (body.error ? `: ${body.error}` : ''));
110
209
  }
111
- const approveUrl = `${base}/approve?req=${challenge}`;
210
+ // GA graduation: the approval page moved into apps/web under /agent/enroll
211
+ // (the /api/vgs/** routes above kept their paths verbatim).
212
+ const approveUrl = `${base}/agent/enroll/approve?req=${challenge}`;
213
+ // Surface the URL as DATA first (headless relay), then as a log line + best-
214
+ // effort browser open for the interactive case.
215
+ onApprovalUrl?.(approveUrl);
112
216
  log(`approve the purchase in your browser: ${approveUrl}`);
217
+ if (budget && agentJkt) {
218
+ log(`budget recipient request key: ${agentJkt.slice(0, 8)}…${agentJkt.slice(-6)}`);
219
+ }
113
220
  openUrl(approveUrl);
114
- for (;;) {
115
- const res = await fetchWithDeadline(`${base}/api/vgs/agent-approval/claim`, {
116
- method: 'POST',
117
- headers: { 'content-type': 'application/json' },
118
- body: JSON.stringify({ verifier }),
119
- });
120
- if (res.ok) {
121
- const doc = (await res.json().catch(() => null));
122
- if (doc?.status === 'completed') {
123
- if (doc.assuranceData === undefined || doc.assuranceData === null) {
124
- throw new Error('hosted approval completed but carried no assuranceData');
125
- }
126
- // The context the approval was COMPLETED against must be exactly this
127
- // run's checkout target — a divergent field means the relay entry was
128
- // not ours (corruption, or a mutated registration) and the assurance
129
- // is scoped to something else. Fail naming the field; no secrets here
130
- // (merchant facts only).
131
- const expected = {
132
- tokenId,
133
- merchantName: target.merchantName,
134
- merchantUrl: target.merchantUrl,
135
- merchantCountryCode: target.merchantCountryCode,
136
- amount: target.transactionAmount,
137
- currency,
138
- };
139
- for (const [field, want] of Object.entries(expected)) {
140
- if (doc.context?.[field] !== want) {
141
- throw new Error(`hosted approval context mismatch on ${field} — the approval was not for this ` +
221
+ let lastHeartbeat = now();
222
+ // Keep the event loop alive for the whole poll wait. `defaultSleep` unref()'s
223
+ // its timer (so the deadline race can't hang the process past the timeout), but
224
+ // that means the ONLY pending work between polls is an unref'd timer — in a bare
225
+ // CLI invocation (no stdin/other handles) node would exit 0 mid-poll, after the
226
+ // first `pending` claim and before the operator finishes the passkey, so the
227
+ // minted token is parked but never claimed. A ref'd keepalive, cleared on every
228
+ // exit, holds the process open until the poll loop returns/throws.
229
+ const keepAlive = setInterval(() => { }, 60_000);
230
+ try {
231
+ for (;;) {
232
+ const res = await fetchWithDeadline(`${base}/api/vgs/agent-approval/claim`, {
233
+ method: 'POST',
234
+ headers: { 'content-type': 'application/json' },
235
+ body: JSON.stringify({ verifier }),
236
+ });
237
+ if (res.ok) {
238
+ const doc = (await res.json().catch(() => null));
239
+ // The operator refused — terminal and immediate. Exit the wait now
240
+ // rather than polling out the timeout; retrying cannot help.
241
+ if (doc?.status === 'declined')
242
+ throw new HostedApprovalDeclinedError();
243
+ if (doc?.status === 'completed') {
244
+ // A passkey-exempt token ('otp' cardholder ID&V / 'none') runs no
245
+ // ceremony and produces no assurance — the approval server marks the
246
+ // claim explicitly (derived from the owner's verified card record at
247
+ // complete-time). Only that marker excuses a null assuranceData; a
248
+ // silently dropped payload still fails exactly as before.
249
+ const assuranceExempt = doc.cardholderVerification === 'otp' || doc.cardholderVerification === 'none';
250
+ if ((doc.assuranceData === undefined || doc.assuranceData === null) && !assuranceExempt) {
251
+ throw new Error('hosted approval completed but carried no assuranceData');
252
+ }
253
+ // The context the approval was COMPLETED against must be exactly this
254
+ // run's checkout target — a divergent field means the relay entry was
255
+ // not ours (corruption, or a mutated registration) and the assurance
256
+ // is scoped to something else. Fail naming the field; no secrets here
257
+ // (merchant facts only).
258
+ const expected = {
259
+ tokenId,
260
+ merchantName: target.merchantName,
261
+ merchantUrl: target.merchantUrl,
262
+ merchantCountryCode: target.merchantCountryCode,
263
+ amount: target.transactionAmount,
264
+ currency,
265
+ };
266
+ for (const [field, want] of Object.entries(expected)) {
267
+ if (doc.context?.[field] !== want) {
268
+ throw new Error(`hosted approval context mismatch on ${field} — the approval was not for this ` +
269
+ 'exact purchase; run the checkout again for a fresh link');
270
+ }
271
+ }
272
+ // A budget approval must complete AS a budget approval — a relay that
273
+ // dropped the flag would mint a single-purchase token that then rejects
274
+ // the first sub-ceiling draw. Compare the boolean explicitly (it is not a
275
+ // string, so it lives outside the string-map loop above).
276
+ if (Boolean(doc.context?.budget) !== Boolean(budget)) {
277
+ throw new Error('hosted approval context mismatch on budget — the approval was not for this ' +
278
+ 'exact purchase; run the checkout again for a fresh link');
279
+ }
280
+ if (budget && doc.context?.agentJkt !== agentJkt) {
281
+ throw new Error('hosted approval context mismatch on agentJkt — the approval was not for this ' +
282
+ 'exact request key; run the checkout again for a fresh link');
283
+ }
284
+ if (!budget && doc.context?.agentJkt !== undefined) {
285
+ throw new Error('hosted approval unexpectedly carried an agentJkt for a one-purchase request');
286
+ }
287
+ // The advisory draw ceiling must survive the relay intact too — a relay
288
+ // that dropped or altered maxDraws would mint a budget token whose draw
289
+ // count no longer matches what the operator approved. Only the budget
290
+ // path registers maxDraws, so only enforce it there; compare exactly,
291
+ // the omitted/undefined case included, so a silently dropped value is
292
+ // caught the same as a mutated one.
293
+ if (budget && doc.context?.maxDraws !== maxDraws) {
294
+ throw new Error('hosted approval context mismatch on maxDraws — the approval was not for this ' +
295
+ 'exact purchase; run the checkout again for a fresh link');
296
+ }
297
+ // Same drop-or-mutate rule for the per-purchase cap: the term the
298
+ // operator read must be the term the token enforces.
299
+ if (budget && doc.context?.perTransaction !== perTransaction) {
300
+ throw new Error('hosted approval context mismatch on perTransaction — the approval was not for ' +
301
+ 'this exact purchase; run the checkout again for a fresh link');
302
+ }
303
+ // The intent is display-only, but a relay that altered it showed the
304
+ // operator different words than the agent sent — refuse, either way.
305
+ if (doc.context?.intent !== intentSanitized) {
306
+ throw new Error('hosted approval context mismatch on intent — the approval was not for this ' +
142
307
  'exact purchase; run the checkout again for a fresh link');
143
308
  }
309
+ if (budget) {
310
+ if (!Number.isSafeInteger(doc.validUntil) ||
311
+ doc.validUntil <= Math.floor(now() / 1000)) {
312
+ throw new Error('hosted budget approval completed without a valid future expiry');
313
+ }
314
+ }
315
+ else if (doc.validUntil !== undefined) {
316
+ throw new Error('hosted one-purchase approval unexpectedly carried a budget expiry');
317
+ }
318
+ log(assuranceExempt
319
+ ? 'approval received from the hosted page (code-verified card, no passkey).'
320
+ : 'approval received from the hosted page (passkey-verified card).');
321
+ return {
322
+ ...assuranceFromCeremony(target, doc.assuranceData ?? null),
323
+ ...(assuranceExempt ? { assuranceExempt: true } : {}),
324
+ ...(typeof doc.mintToken === 'string' && doc.mintToken
325
+ ? { mintToken: doc.mintToken }
326
+ : {}),
327
+ ...(budget ? { validUntil: doc.validUntil } : {}),
328
+ };
144
329
  }
145
- log('passkey approval received from the hosted page.');
146
- return assuranceFromCeremony(target, doc.assuranceData);
330
+ // status 'pending' the operator is still signing in / tapping.
331
+ }
332
+ else if (res.status === 404) {
333
+ // Registered moments ago, so absent now means expired or already claimed.
334
+ throw new Error('the hosted approval expired or was already used — run the checkout again for a fresh link');
147
335
  }
148
- // status 'pending' the operator is still signing in / tapping.
336
+ // Any other status (429 rate bucket, transient 5xx) polls through.
337
+ if (now() >= deadline)
338
+ throw timeoutError();
339
+ // Heartbeat so a human staring at a terminal (or an agent tailing logs)
340
+ // knows the wait is live and where to approve — the loop is otherwise silent
341
+ // for up to the full timeout between the open and the completed claim.
342
+ if (now() - lastHeartbeat >= HOSTED_APPROVAL_HEARTBEAT_MS) {
343
+ lastHeartbeat = now();
344
+ const leftS = Math.max(0, Math.round((deadline - now()) / 1000));
345
+ log(`still waiting for approval (~${leftS}s left) — approve at ${approveUrl}`);
346
+ }
347
+ await sleep(pollIntervalMs);
149
348
  }
150
- else if (res.status === 404) {
151
- // Registered moments ago, so absent now means expired or already claimed.
152
- throw new Error('the hosted approval expired or was already used — run the checkout again for a fresh link');
349
+ }
350
+ finally {
351
+ clearInterval(keepAlive);
352
+ }
353
+ }
354
+ const PICKUP_CODE_SHAPE = /^[A-Za-z0-9_-]{43}$/;
355
+ const DECIMAL_AMOUNT_SHAPE = /^[0-9]+(\.[0-9]{1,2})?$/;
356
+ function pickupMismatch(field, detail) {
357
+ return new Error(`mandate pickup code mismatch on ${field} — ${detail}. Ask the owner to start a fresh ` +
358
+ 'mandate in the panel for this agent');
359
+ }
360
+ export async function claimMandatePickup(opts) {
361
+ const { baseUrl, pickupCode, agentJkt, expectedHandoffId, tokenId, fetchImpl = fetch, sleep = defaultSleep, now = Date.now, attempts = 3, retryDelayMs = 1_000, } = opts;
362
+ // Both producers (runHostedApproval and the panel initiate route) mint the
363
+ // verifier as randomBytes(32).base64url = 43 chars; refuse anything else
364
+ // before it travels.
365
+ if (!PICKUP_CODE_SHAPE.test(pickupCode)) {
366
+ throw new Error('that does not look like a mandate pickup code (43 URL-safe characters) — ' +
367
+ 'paste the code exactly as the panel displayed it');
368
+ }
369
+ if (!/^[A-Za-z0-9_-]{43}$/.test(agentJkt)) {
370
+ throw new Error('claiming a mandate pickup requires the exact current agent request-key JKT');
371
+ }
372
+ if (!tokenId.trim()) {
373
+ throw new Error('claiming a mandate pickup requires the provisioned card token id');
374
+ }
375
+ const base = stripTrailingSlashes(assertApprovalBaseUrl(baseUrl));
376
+ let res = null;
377
+ for (let attempt = 1;; attempt++) {
378
+ res = await fetchImpl(`${base}/api/vgs/agent-approval/claim`, {
379
+ method: 'POST',
380
+ headers: { 'content-type': 'application/json' },
381
+ body: JSON.stringify({ verifier: pickupCode }),
382
+ });
383
+ // 4xx other than 404/429 is a terminal shape/validation answer; 404 is the
384
+ // single-use/TTL answer. Only rate-limit and 5xx are worth a bounded retry —
385
+ // the entry is durable until claimed or expired.
386
+ if (res.ok || res.status === 404 || (res.status < 500 && res.status !== 429))
387
+ break;
388
+ if (attempt >= attempts)
389
+ break;
390
+ await sleep(retryDelayMs);
391
+ }
392
+ if (res.status === 404) {
393
+ throw new Error('this pickup code has expired or was already used — codes are single-use and live ' +
394
+ 'about 10 minutes. Ask the owner to start a fresh mandate in the panel');
395
+ }
396
+ if (!res.ok) {
397
+ const body = (await res.json().catch(() => ({})));
398
+ throw new Error(`could not redeem the pickup code (${res.status})` + (body.error ? `: ${body.error}` : ''));
399
+ }
400
+ const doc = (await res.json().catch(() => null));
401
+ if (doc?.status === 'declined')
402
+ throw new HostedApprovalDeclinedError();
403
+ if (doc?.status !== 'completed') {
404
+ // A panel-issued pickup code is parked already-completed (the owner approved
405
+ // in the panel before the code existed). `pending` means this verifier came
406
+ // from an in-flight runner ceremony, not a mandate handoff — redeeming it
407
+ // here would race the runner that owns it.
408
+ throw new Error('this code is not a completed mandate handoff — it looks like an in-progress approval. ' +
409
+ 'Use the pickup code the panel displayed after the owner approved the mandate');
410
+ }
411
+ const ctx = doc.context ?? {};
412
+ if (ctx.budget !== true) {
413
+ throw pickupMismatch('budget', 'the approval is a one-purchase approval, not a spend budget');
414
+ }
415
+ // A budget names exactly ONE agent, by one of two pins.
416
+ //
417
+ // - `agentJkt` — the panel flow: the owner picked an agent that already
418
+ // existed, so the approval names its key and this runtime compares keys.
419
+ // - `handoffId` — the Add-agent dialog: the budget was minted before any
420
+ // agent existed, so it names the handoff the agent would go on to redeem.
421
+ // This runtime redeemed one moments ago and knows which, so the comparison
422
+ // is just as concrete — it is simply a different identifier.
423
+ //
424
+ // EXACTLY one, enforced before either is compared. Neither pin is an unbound
425
+ // budget, and "no pin" must never be the quiet way past a binding check.
426
+ // BOTH pins is worse: it names two agents, and checking whichever one happens
427
+ // to match would let the weaker claim decide. The signer refuses to mint such
428
+ // a context and the approval store refuses to hold one, so this is the third
429
+ // and last place to say it — the one that runs on material already in hand.
430
+ const hasHandoffPin = typeof ctx.handoffId === 'string';
431
+ const hasAgentPin = typeof ctx.agentJkt === 'string';
432
+ if (hasHandoffPin === hasAgentPin) {
433
+ throw pickupMismatch('agentJkt', hasHandoffPin
434
+ ? 'this budget names two different agents at once — it binds to a handoff or to a key, never both'
435
+ : 'this budget names no agent at all, so nothing can prove it belongs to this runtime');
436
+ }
437
+ if (hasHandoffPin) {
438
+ if (!expectedHandoffId || ctx.handoffId !== expectedHandoffId) {
439
+ throw pickupMismatch('handoffId', 'this budget belongs to a different agent handoff than the one this runtime just claimed');
153
440
  }
154
- // Any other status (429 rate bucket, transient 5xx) polls through.
155
- if (now() >= deadline)
156
- throw timeoutError();
157
- await sleep(pollIntervalMs);
158
441
  }
442
+ else if (ctx.agentJkt !== agentJkt) {
443
+ throw pickupMismatch('agentJkt', 'the owner approved this mandate for a different agent key than this runtime holds');
444
+ }
445
+ if (ctx.tokenId !== tokenId) {
446
+ throw pickupMismatch('tokenId', "the mandate was approved against a different enrolled card than this runtime's card " +
447
+ 'authority points at (the owner may have re-enrolled a card — re-run grant-card first)');
448
+ }
449
+ const ceiling = ctx.amount;
450
+ if (typeof ceiling !== 'string' || !DECIMAL_AMOUNT_SHAPE.test(ceiling) || Number(ceiling) <= 0) {
451
+ throw pickupMismatch('amount', 'the approved ceiling is missing or malformed');
452
+ }
453
+ const currency = ctx.currency;
454
+ if (typeof currency !== 'string' || !/^[A-Z]{3}$/.test(currency)) {
455
+ throw pickupMismatch('currency', 'the approved currency is missing or malformed');
456
+ }
457
+ const maxDraws = ctx.maxDraws;
458
+ if (!Number.isSafeInteger(maxDraws) || maxDraws < 1) {
459
+ throw pickupMismatch('maxDraws', 'the approved purchase count is missing or malformed');
460
+ }
461
+ const perTransaction = ctx.perTransaction;
462
+ if (perTransaction !== undefined) {
463
+ if (typeof perTransaction !== 'string' ||
464
+ !DECIMAL_AMOUNT_SHAPE.test(perTransaction) ||
465
+ Number(perTransaction) <= 0 ||
466
+ Number(perTransaction) > Number(ceiling)) {
467
+ throw pickupMismatch('perTransaction', 'the approved per-purchase cap is malformed');
468
+ }
469
+ }
470
+ const merchantName = ctx.merchantName;
471
+ const merchantUrl = ctx.merchantUrl;
472
+ const merchantCountryCode = ctx.merchantCountryCode;
473
+ if (typeof merchantName !== 'string' ||
474
+ !merchantName.trim() ||
475
+ typeof merchantUrl !== 'string' ||
476
+ !merchantUrl.trim() ||
477
+ typeof merchantCountryCode !== 'string' ||
478
+ !merchantCountryCode.trim()) {
479
+ throw pickupMismatch('merchant', 'the approved budget target is missing or malformed');
480
+ }
481
+ if (typeof doc.mintToken !== 'string' || !doc.mintToken) {
482
+ throw new Error('the mandate handoff carried no mint token — the deployment that parked it ran the ' +
483
+ 'dev-auth stub, which cannot mint draw authority. Re-initiate against a real deployment');
484
+ }
485
+ if (!Number.isSafeInteger(doc.validUntil) ||
486
+ doc.validUntil <= Math.floor(now() / 1000)) {
487
+ throw new Error('the mandate handoff carried no valid future expiry — ask the owner to re-initiate');
488
+ }
489
+ // Same exemption contract as runHostedApproval: only the server's explicit
490
+ // code-verified-card marker excuses a missing assurance payload.
491
+ const assuranceExempt = doc.cardholderVerification === 'otp' || doc.cardholderVerification === 'none';
492
+ if ((doc.assuranceData === undefined || doc.assuranceData === null) && !assuranceExempt) {
493
+ throw new Error('the mandate handoff completed but carried no assuranceData');
494
+ }
495
+ return {
496
+ assuranceData: doc.assuranceData ?? null,
497
+ assuranceExempt,
498
+ mintToken: doc.mintToken,
499
+ validUntil: doc.validUntil,
500
+ ceiling,
501
+ currency,
502
+ maxDraws: maxDraws,
503
+ ...(perTransaction !== undefined ? { perTransaction: perTransaction } : {}),
504
+ merchant: {
505
+ name: merchantName,
506
+ url: merchantUrl,
507
+ countryCode: merchantCountryCode,
508
+ },
509
+ };
159
510
  }
@@ -1,3 +1,6 @@
1
- export { createCliCheckoutEngine, type CliReviewInput, type CliReviewFacts, type CliPayInput, type CliReceiptFacts, } from './cli-engine.js';
1
+ export { createCliCheckoutEngine, type CliReviewInput, type CliReviewFacts, type CliPayInput, type CliReceiptFacts, type CliStartMandateInput, type CliMandateFacts, type CliEngineDeps, } from './cli-engine.js';
2
2
  export { prepareCheckout, submitApprovedCheckout, runCheckout, InMemoryPreparedCheckoutStore, } from './executor.js';
3
3
  export type { CheckoutResult, CheckoutReview, CheckoutOutcome } from './executor.js';
4
+ export { HostedApprovalDeclinedError, sanitizeApprovalIntent, APPROVAL_INTENT_MAX_CHARS, } from './hosted-approval.js';
5
+ export { createCardMandate, drawFromMandate, MandateDrawDeclinedError, DEFAULT_MANDATE_MAX_DRAWS, type CreateCardMandateInput, type CreateCardMandateDeps, type CardMandateFacts, type DrawFromMandateInput, type DrawFromMandateDeps, type DrawResult, type CardMandateMerchant, } from './mandate/card-mandate.js';
6
+ export { MandateLedger, remainingMinor, defaultLedgerPath, CARD_MANDATE_LEDGER_VERSION, type CardMandateRecord, type CardMandateLedgerFile, type CardMandateDraw, type CardMandateReservation, } from './mandate/mandate-ledger.js';
@@ -3,3 +3,6 @@
3
3
  // primitives are re-exported for direct/embedded use.
4
4
  export { createCliCheckoutEngine, } from './cli-engine.js';
5
5
  export { prepareCheckout, submitApprovedCheckout, runCheckout, InMemoryPreparedCheckoutStore, } from './executor.js';
6
+ export { HostedApprovalDeclinedError, sanitizeApprovalIntent, APPROVAL_INTENT_MAX_CHARS, } from './hosted-approval.js';
7
+ export { createCardMandate, drawFromMandate, MandateDrawDeclinedError, DEFAULT_MANDATE_MAX_DRAWS, } from './mandate/card-mandate.js';
8
+ export { MandateLedger, remainingMinor, defaultLedgerPath, CARD_MANDATE_LEDGER_VERSION, } from './mandate/mandate-ledger.js';
@@ -6,6 +6,12 @@ export type CardCredential = {
6
6
  cardholderName: string;
7
7
  /** Dynamic payment credential expiry, distinct from the card expiration. */
8
8
  credentialExpiresAt?: string;
9
+ /**
10
+ * Non-sensitive, bounded request-correlation handles returned by the mint
11
+ * route. These are evidence pointers, not card credential material.
12
+ */
13
+ vgsTraceId?: string;
14
+ networkCorrelationId?: string;
9
15
  };
10
16
  export type InstrumentContext = {
11
17
  merchantHost: string;
@@ -24,6 +30,7 @@ export declare const OFFICIAL_TEST_PANS: {
24
30
  readonly visaSlowConfirm: "4000000000000069";
25
31
  readonly visaUnknownOutcome: "4000000000000044";
26
32
  readonly visaChallenge: "4000000000000010";
33
+ readonly visaEmailOtp: "4000000000000077";
27
34
  };
28
35
  export type TestCardOptions = {
29
36
  pan?: string;
@@ -22,6 +22,10 @@ export const OFFICIAL_TEST_PANS = {
22
22
  // page embedding an ACS challenge iframe that never completes — exercises
23
23
  // the observer's action-required (issuer challenge) path.
24
24
  visaChallenge: '4000000000000010',
25
+ // Ending 0077: the fixture acquirer emails a one-time code to the agent
26
+ // inbox and shows a 'check your email for a code' page with a one-time-code
27
+ // field — exercises the executor's agent-resolvable email-OTP subroutine.
28
+ visaEmailOtp: '4000000000000077',
25
29
  };
26
30
  function futureExpiry() {
27
31
  const now = new Date();
@@ -1,30 +1,10 @@
1
1
  import type { CheckoutMode, CheckoutOutcome, CheckoutResult } from './executor.js';
2
- export declare const SUBMIT_ENV_FLAG = "CHECKOUT_AGENT_ALLOW_SUBMIT";
3
2
  export declare const MODE_ENV_FLAG = "CHECKOUT_AGENT_MODE";
4
3
  /**
5
4
  * `--mode` values map 1:1 onto CheckoutMode; an absent flag falls back to the
6
5
  * CHECKOUT_AGENT_MODE environment default, then to the safe dry-run default.
7
6
  */
8
7
  export declare function parseCheckoutMode(value: string | undefined, env?: Record<string, string | undefined>): CheckoutMode;
9
- /**
10
- * Fail fast (before any file read or browser launch) when submit lacks an
11
- * enablement. The env arm exists to stop AUTOMATION from reaching a live
12
- * charge by accident — so it is required only when stdin is not a real TTY
13
- * (scripts, agents, pipes). An interactive human needs no standing config:
14
- * their per-run consent is the typed PAY phrase plus the passkey tap, both of
15
- * which a non-interactive caller cannot fake (the phrase names the exact
16
- * review id; the passkey is a FIDO ceremony on the verify site).
17
- */
18
- export declare function assertSubmitAllowed(mode: CheckoutMode, env?: Record<string, string | undefined>, isInteractive?: boolean): void;
19
- export declare const LEGACY_REFERENCE_ENV_FLAG = "CHECKOUT_AGENT_ALLOW_LEGACY_REFERENCE";
20
- /**
21
- * The legacy --reference-file path replays a PRE-CREATED intent, so the
22
- * purchase-assurance gate (#5709) cannot vet the ceremony that backed it —
23
- * scope/freshness problems surface only as the opaque cryptogram failure the
24
- * gate exists to prevent. Default-off escape hatch, same shape as the submit
25
- * gate: fail fast before any file is read.
26
- */
27
- export declare function assertLegacyReferenceAllowed(usingReferenceFile: boolean, env?: Record<string, string | undefined>): void;
28
8
  /** Distinct phrases per mode so dry-run muscle memory can never authorize a payment. */
29
9
  export declare function approvalPhrase(mode: CheckoutMode, reviewId: string): string;
30
10
  /** Integer-only minor→display formatting (two-decimal currencies, the same assumption as decimalToMinor). */