@visa/cli 4.1.0-rc.298 → 4.1.0-rc.299

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 +29 -45
  2. package/dist/cli.js +556 -786
  3. package/dist/mcp-server/index.js +408 -622
  4. package/dist/merchant-ucp-mcp/index.js +6 -6
  5. package/dist/skills/pair-visa-agent/SKILL.md +175 -240
  6. package/native/bin/win32-arm64/visa-runtime-signer.exe +0 -0
  7. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  8. package/native/bin/win32-x64/visa-runtime-signer.exe +0 -0
  9. package/package.json +2 -4
  10. package/server.json +2 -2
  11. package/dist/checkout-engine/adapters/generic.d.ts +0 -88
  12. package/dist/checkout-engine/adapters/generic.js +0 -526
  13. package/dist/checkout-engine/adapters/index.d.ts +0 -10
  14. package/dist/checkout-engine/adapters/index.js +0 -24
  15. package/dist/checkout-engine/adapters/shopify.d.ts +0 -98
  16. package/dist/checkout-engine/adapters/shopify.js +0 -744
  17. package/dist/checkout-engine/adapters/stripe-like.d.ts +0 -10
  18. package/dist/checkout-engine/adapters/stripe-like.js +0 -21
  19. package/dist/checkout-engine/amount.d.ts +0 -17
  20. package/dist/checkout-engine/amount.js +0 -72
  21. package/dist/checkout-engine/browser-launch.d.ts +0 -51
  22. package/dist/checkout-engine/browser-launch.js +0 -96
  23. package/dist/checkout-engine/browserbase-browser.d.ts +0 -24
  24. package/dist/checkout-engine/browserbase-browser.js +0 -186
  25. package/dist/checkout-engine/ceremony.d.ts +0 -64
  26. package/dist/checkout-engine/ceremony.js +0 -261
  27. package/dist/checkout-engine/cli-engine.d.ts +0 -417
  28. package/dist/checkout-engine/cli-engine.js +0 -1331
  29. package/dist/checkout-engine/confirmed-merchants.d.ts +0 -31
  30. package/dist/checkout-engine/confirmed-merchants.js +0 -165
  31. package/dist/checkout-engine/detect.d.ts +0 -61
  32. package/dist/checkout-engine/detect.js +0 -398
  33. package/dist/checkout-engine/evidence.d.ts +0 -25
  34. package/dist/checkout-engine/evidence.js +0 -104
  35. package/dist/checkout-engine/executor.d.ts +0 -262
  36. package/dist/checkout-engine/executor.js +0 -1837
  37. package/dist/checkout-engine/hosted-approval.d.ts +0 -195
  38. package/dist/checkout-engine/hosted-approval.js +0 -501
  39. package/dist/checkout-engine/index.d.ts +0 -12
  40. package/dist/checkout-engine/index.js +0 -13
  41. package/dist/checkout-engine/instrument.d.ts +0 -61
  42. package/dist/checkout-engine/instrument.js +0 -87
  43. package/dist/checkout-engine/known-merchants.d.ts +0 -10
  44. package/dist/checkout-engine/known-merchants.js +0 -38
  45. package/dist/checkout-engine/live-fill-approval.d.ts +0 -37
  46. package/dist/checkout-engine/live-fill-approval.js +0 -76
  47. package/dist/checkout-engine/mandate/card-mandate.d.ts +0 -121
  48. package/dist/checkout-engine/mandate/card-mandate.js +0 -226
  49. package/dist/checkout-engine/mandate/mandate-ledger.d.ts +0 -175
  50. package/dist/checkout-engine/mandate/mandate-ledger.js +0 -425
  51. package/dist/checkout-engine/mandate.d.ts +0 -33
  52. package/dist/checkout-engine/mandate.js +0 -135
  53. package/dist/checkout-engine/outcome.d.ts +0 -30
  54. package/dist/checkout-engine/outcome.js +0 -225
  55. package/dist/checkout-engine/owner-only-file.d.ts +0 -19
  56. package/dist/checkout-engine/owner-only-file.js +0 -41
  57. package/dist/checkout-engine/package.json +0 -3
  58. package/dist/checkout-engine/receipt-dir.d.ts +0 -6
  59. package/dist/checkout-engine/receipt-dir.js +0 -8
  60. package/dist/checkout-engine/receipt.d.ts +0 -135
  61. package/dist/checkout-engine/receipt.js +0 -148
  62. package/dist/checkout-engine/shopify-primary-domain.d.ts +0 -25
  63. package/dist/checkout-engine/shopify-primary-domain.js +0 -96
  64. package/dist/checkout-engine/trace-handles.d.ts +0 -8
  65. package/dist/checkout-engine/trace-handles.js +0 -12
  66. package/dist/checkout-engine/types.d.ts +0 -52
  67. package/dist/checkout-engine/types.js +0 -2
  68. package/dist/checkout-engine/unresolved-charges.d.ts +0 -34
  69. package/dist/checkout-engine/unresolved-charges.js +0 -134
  70. package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +0 -155
  71. package/dist/checkout-engine/vgs-gateway/server-mint-client.js +0 -493
  72. package/dist/checkout-engine/vgs-live-instrument.d.ts +0 -144
  73. package/dist/checkout-engine/vgs-live-instrument.js +0 -229
  74. package/dist/checkout-engine/vic-confirmation.d.ts +0 -52
  75. package/dist/checkout-engine/vic-confirmation.js +0 -45
  76. package/dist/checkout-engine/web-bot-auth.d.ts +0 -98
  77. package/dist/checkout-engine/web-bot-auth.js +0 -218
@@ -1,148 +0,0 @@
1
- import { mkdir, writeFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
3
- import { KNOWN_MERCHANT_IDENTITIES } from './known-merchants.js';
4
- import { submitClickedWithoutConfirmation } from './live-fill-approval.js';
5
- /**
6
- * What the operator still owes after this run. Empty for a clean dry-run fill
7
- * and for a definitive submit outcome whose VIC confirmation posted.
8
- */
9
- function reconciliationFor(result, vicConfirmation, mode) {
10
- const reasons = [];
11
- if (submitClickedWithoutConfirmation(result)) {
12
- reasons.push('the pay control was clicked but no definitive outcome was observed — ' +
13
- 'verify the charge with the merchant dashboard before any retry');
14
- }
15
- if ((result.outcome === 'confirmed' || result.outcome === 'declined') &&
16
- vicConfirmation &&
17
- !vicConfirmation.posted) {
18
- reasons.push(`the VIC confirmation was not posted (${vicConfirmation.reason}) — ` +
19
- 'retry it for this intent out-of-band');
20
- }
21
- if (result.outcome === 'confirmed' && !result.confirmationRef) {
22
- reasons.push('confirmed without a merchant confirmation reference — ' +
23
- 'record the order number from the merchant dashboard');
24
- }
25
- if (mode === 'submit' && result.outcome === 'action-required') {
26
- reasons.push('an issuer verification challenge was shown and not completed — ' +
27
- 'finish the purchase manually if still wanted, or confirm with the merchant that no order exists');
28
- }
29
- return { required: reasons.length > 0, reasons };
30
- }
31
- export function buildReceipt(input) {
32
- const { result } = input;
33
- const reconciliation = reconciliationFor(result, input.vicConfirmation, input.mode);
34
- const fallbackAction = input.mode === 'dry-run'
35
- ? 'Dry run only — nothing was submitted; safe to run again.'
36
- : result.outcome === 'confirmed'
37
- ? 'No action needed.'
38
- : result.outcome === 'declined'
39
- ? 'Review the decline before trying again.'
40
- : result.outcome === 'unverified'
41
- ? // Defensive: reconciliationFor() already pushes the richer
42
- // submit-clicked reason for this outcome, so this line is only
43
- // reached if that ever stops firing. It must still not invite a
44
- // retry.
45
- 'The charge may have gone through. Confirm with the merchant before retrying.'
46
- : result.outcome === 'partial-fill'
47
- ? // A v2 receipt carries no evidence log, so this line is the only
48
- // place the CAUSE survives — which field refused and why. An
49
- // operator opening this a week later can act on it; "could not
50
- // be filled" alone means reproducing a live merchant to learn
51
- // anything.
52
- `${result.detail ?? 'Nothing was submitted and nothing was charged.'} Safe to try again once the checkout can be filled.`
53
- : 'Review this outcome before retrying.';
54
- const recoveryActions = reconciliation.reasons.length > 0 ? reconciliation.reasons : [fallbackAction];
55
- const cardLast4 = input.cardLast4 && /^\d{4}$/.test(input.cardLast4) ? input.cardLast4 : null;
56
- const checkoutUrl = input.merchant.url && KNOWN_MERCHANT_IDENTITIES[input.merchant.url] ? input.merchant.url : null;
57
- const networkConfirmation = input.vicConfirmation?.posted === true ? input.vicConfirmation.transactionStatus : null;
58
- const capability = result.failureCode || result.requiresAdapter.length > 0
59
- ? {
60
- failureCode: result.failureCode ?? null,
61
- detectedRoles: Object.keys(result.fields).sort(),
62
- requiresAdapter: [...result.requiresAdapter].sort(),
63
- }
64
- : null;
65
- return {
66
- schema: 'checkout-agent-receipt/v2',
67
- recordedAt: (input.recordedAt ?? new Date()).toISOString(),
68
- ...(input.observationId ? { observationId: input.observationId } : {}),
69
- ...(input.observationId && input.reviewId === null ? { phase: 'review' } : {}),
70
- merchant: { name: input.merchant.name, host: input.merchant.host, checkoutUrl },
71
- transaction: input.transaction,
72
- outcome: result.outcome,
73
- agent: input.agentName ? { name: input.agentName } : null,
74
- rail: { type: 'card', cardLast4 },
75
- network: { confirmation: networkConfirmation },
76
- ...(capability ? { capability } : {}),
77
- receiptId: input.reviewId,
78
- reference: result.confirmationRef ?? null,
79
- recovery: {
80
- required: reconciliation.required,
81
- // A clean dry-run did not submit anything, so repeating inspection is
82
- // safe. Every submit outcome requires either no retry or owner review.
83
- retrySafe: input.mode === 'dry-run' && !reconciliation.required,
84
- action: recoveryActions[0],
85
- actions: recoveryActions,
86
- },
87
- };
88
- }
89
- function luhnValid(digits) {
90
- let sum = 0;
91
- let double = false;
92
- for (let i = digits.length - 1; i >= 0; i--) {
93
- let d = digits.charCodeAt(i) - 48;
94
- if (double) {
95
- d *= 2;
96
- if (d > 9)
97
- d -= 9;
98
- }
99
- sum += d;
100
- double = !double;
101
- }
102
- return sum % 10 === 0;
103
- }
104
- /**
105
- * Defense-in-depth scrub before anything touches disk: any standalone
106
- * 12–19-digit run that passes Luhn is replaced — contiguous OR separated by
107
- * single spaces/hyphens between digit groups, the way merchant card-preview
108
- * widgets render a typed number ("4242 4242 4242 4242") into page text that
109
- * can reach the snapshot summary. Upstream masking means a hit should be
110
- * impossible; the count surfaces so the runner can flag a leak.
111
- */
112
- export function redactPanLikeDigits(text) {
113
- let redactions = 0;
114
- const scrubbed = text.replace(/(?<!\d)(?<!\d[\s-])\d(?:[\s-]?\d){11,18}(?![\s-]?\d)/g, (run) => {
115
- const digits = run.replace(/[\s-]/g, '');
116
- if (digits.length < 12 || digits.length > 19 || !luhnValid(digits))
117
- return run;
118
- redactions++;
119
- return '<redacted:pan-like>';
120
- });
121
- return { text: scrubbed, redactions };
122
- }
123
- export function serializeReceipt(receipt) {
124
- const { text, redactions } = redactPanLikeDigits(`${JSON.stringify(receipt, null, 2)}\n`);
125
- return { json: text, panRedactions: redactions };
126
- }
127
- export function receiptFileName(receipt) {
128
- const ts = receipt.recordedAt.replace(/[:.]/g, '-');
129
- const receiptId = receipt.schema === 'checkout-agent-receipt/v1' ? receipt.reviewId : receipt.receiptId;
130
- const review = (receiptId ?? 'no-review').replace(/[^A-Za-z0-9-]/g, '');
131
- return `receipt-${ts}-${review || 'no-review'}.json`;
132
- }
133
- /**
134
- * Persist one receipt as an owner-only file (0600) in an owner-only directory
135
- * (0700). Refuses to overwrite an existing file (`wx`). Never throws.
136
- */
137
- export async function writeReceipt(dir, receipt) {
138
- try {
139
- await mkdir(dir, { recursive: true, mode: 0o700 });
140
- const path = join(dir, receiptFileName(receipt));
141
- const { json, panRedactions } = serializeReceipt(receipt);
142
- await writeFile(path, json, { mode: 0o600, flag: 'wx' });
143
- return { written: true, path, panRedactions };
144
- }
145
- catch (err) {
146
- return { written: false, reason: err.message };
147
- }
148
- }
@@ -1,25 +0,0 @@
1
- import type { Response } from 'playwright-core';
2
- export type NavigationRedirectEvidence = {
3
- sourceUrl: string;
4
- status: number;
5
- location: string | null;
6
- redirectReason: string | null;
7
- poweredBy: string | null;
8
- };
9
- /**
10
- * Resolve Shopify's permanent `*.myshopify.com` identity to its configured
11
- * primary storefront host using evidence from the navigation redirect chain.
12
- *
13
- * This deliberately does not treat a generic redirect, matching HTML, DNS, or
14
- * a shared Shopify CDN as merchant ownership proof. The only accepted cross-host
15
- * hop must originate on the mandate-bound `myshopify.com` host over HTTPS and
16
- * carry Shopify's exact `primary_domain_redirection` response signal directly
17
- * to the final checkout host.
18
- */
19
- export declare function shopifyPrimaryDomainAlias(args: {
20
- mandateHost: string | undefined;
21
- initialUrl: string;
22
- finalUrl: string;
23
- redirects: readonly NavigationRedirectEvidence[];
24
- }): string | null;
25
- export declare function navigationRedirectEvidence(finalResponse: Response | null): Promise<NavigationRedirectEvidence[]>;
@@ -1,96 +0,0 @@
1
- const MYSHOPIFY_HOST = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.myshopify\.com$/;
2
- function hostname(value) {
3
- try {
4
- return new URL(value).hostname.toLowerCase();
5
- }
6
- catch {
7
- try {
8
- return new URL(`https://${value}`).hostname.toLowerCase();
9
- }
10
- catch {
11
- return null;
12
- }
13
- }
14
- }
15
- function redirectTargetHost(redirect) {
16
- if (!redirect.location)
17
- return null;
18
- try {
19
- return new URL(redirect.location, redirect.sourceUrl).hostname.toLowerCase();
20
- }
21
- catch {
22
- return null;
23
- }
24
- }
25
- /**
26
- * Resolve Shopify's permanent `*.myshopify.com` identity to its configured
27
- * primary storefront host using evidence from the navigation redirect chain.
28
- *
29
- * This deliberately does not treat a generic redirect, matching HTML, DNS, or
30
- * a shared Shopify CDN as merchant ownership proof. The only accepted cross-host
31
- * hop must originate on the mandate-bound `myshopify.com` host over HTTPS and
32
- * carry Shopify's exact `primary_domain_redirection` response signal directly
33
- * to the final checkout host.
34
- */
35
- export function shopifyPrimaryDomainAlias(args) {
36
- if (!args.mandateHost)
37
- return null;
38
- let initial;
39
- let final;
40
- try {
41
- initial = new URL(args.initialUrl);
42
- final = new URL(args.finalUrl);
43
- }
44
- catch {
45
- return null;
46
- }
47
- if (initial.protocol !== 'https:' || final.protocol !== 'https:')
48
- return null;
49
- const mandateHost = hostname(args.mandateHost);
50
- const initialHost = initial.hostname.toLowerCase();
51
- const finalHost = final.hostname.toLowerCase();
52
- if (!mandateHost || mandateHost !== initialHost || !MYSHOPIFY_HOST.test(initialHost))
53
- return null;
54
- if (initialHost === finalHost)
55
- return null;
56
- const crossHostRedirects = args.redirects.filter((redirect) => {
57
- const sourceHost = hostname(redirect.sourceUrl);
58
- const targetHost = redirectTargetHost(redirect);
59
- return sourceHost !== null && targetHost !== null && sourceHost !== targetHost;
60
- });
61
- if (crossHostRedirects.length !== 1)
62
- return null;
63
- const redirect = crossHostRedirects[0];
64
- const source = new URL(redirect.sourceUrl);
65
- const target = redirect.location ? new URL(redirect.location, source) : null;
66
- if (source.protocol !== 'https:' ||
67
- source.hostname.toLowerCase() !== initialHost ||
68
- !target ||
69
- target.protocol !== 'https:' ||
70
- target.hostname.toLowerCase() !== finalHost ||
71
- ![301, 302, 307, 308].includes(redirect.status) ||
72
- redirect.redirectReason?.toLowerCase() !== 'primary_domain_redirection' ||
73
- redirect.poweredBy?.toLowerCase() !== 'shopify') {
74
- return null;
75
- }
76
- return finalHost;
77
- }
78
- export async function navigationRedirectEvidence(finalResponse) {
79
- const redirects = [];
80
- let request = finalResponse?.request().redirectedFrom() ?? null;
81
- while (request) {
82
- const response = await request.response();
83
- if (response) {
84
- const headers = response.headers();
85
- redirects.push({
86
- sourceUrl: request.url(),
87
- status: response.status(),
88
- location: headers.location ?? null,
89
- redirectReason: headers['x-redirect-reason'] ?? null,
90
- poweredBy: headers['powered-by'] ?? null,
91
- });
92
- }
93
- request = request.redirectedFrom();
94
- }
95
- return redirects.reverse();
96
- }
@@ -1,8 +0,0 @@
1
- export declare function safeTraceHandle(value: unknown): string | undefined;
2
- export declare function traceHandleFields(value: {
3
- vgsTraceId?: unknown;
4
- networkCorrelationId?: unknown;
5
- }): {
6
- vgsTraceId?: string;
7
- networkCorrelationId?: string;
8
- };
@@ -1,12 +0,0 @@
1
- const SAFE_TRACE_HANDLE_RE = /^[A-Za-z0-9._:-]{1,128}$/;
2
- export function safeTraceHandle(value) {
3
- return typeof value === 'string' && SAFE_TRACE_HANDLE_RE.test(value) ? value : undefined;
4
- }
5
- export function traceHandleFields(value) {
6
- const vgsTraceId = safeTraceHandle(value.vgsTraceId);
7
- const networkCorrelationId = safeTraceHandle(value.networkCorrelationId);
8
- return {
9
- ...(vgsTraceId ? { vgsTraceId } : {}),
10
- ...(networkCorrelationId ? { networkCorrelationId } : {}),
11
- };
12
- }
@@ -1,52 +0,0 @@
1
- export type PostalAddress = {
2
- firstName?: string;
3
- lastName?: string;
4
- fullName?: string;
5
- addressLine1?: string;
6
- addressLine2?: string;
7
- city?: string;
8
- state?: string;
9
- postalCode?: string;
10
- country?: string;
11
- };
12
- export type Contact = PostalAddress & {
13
- email?: string;
14
- phone?: string;
15
- billingAddress?: PostalAddress;
16
- };
17
- export type FilledField = {
18
- role: string;
19
- locator: string;
20
- confidence: number;
21
- source: string;
22
- frame?: string;
23
- value: string;
24
- ok: boolean;
25
- error?: string;
26
- /**
27
- * The detected node was gone by the time this field's turn came (the merchant
28
- * re-mounted that part of the form mid-fill) and a fresh detection pass was
29
- * used to find it again. Worth surfacing: a merchant that re-mounts is a
30
- * merchant whose fills are order-sensitive, which is the first thing to know
31
- * when one of them later refuses.
32
- */
33
- relocated?: boolean;
34
- };
35
- export type FillResult = {
36
- ok: boolean;
37
- filled: FilledField[];
38
- detail?: string;
39
- };
40
- export type OtpRequest = {
41
- /** ISO watermark captured BEFORE the click that triggers the OTP email. */
42
- after: string;
43
- /** The merchant hostname; the sender's registrable domain must match it. */
44
- merchantHost: string;
45
- };
46
- export type OtpResolution = {
47
- /** The single-use code. The executor fills it exactly once; never retried. */
48
- code: string;
49
- /** The sender's registrable domain — a trust signal, safe to log (no PII). */
50
- fromDomain: string;
51
- };
52
- export type OtpResolver = (req: OtpRequest) => Promise<OtpResolution | null>;
@@ -1,2 +0,0 @@
1
- // Shared value types used across the engine.
2
- export {};
@@ -1,34 +0,0 @@
1
- /**
2
- * Outcomes whose receipt cannot rule out a charge.
3
- *
4
- * Both of these record a run where the pay control was clicked and no
5
- * definitive answer came back:
6
- * - `unverified` — no confirmation or decline observed before the deadline
7
- * - `action-required` — an issuer challenge appeared, which happens AFTER the
8
- * click, so the authorization may already exist
9
- *
10
- * Everything else is either definitive (`confirmed`, `declined`) or provably
11
- * pre-click (`reviewed-dry-run`, `partial-fill`, `failed`, ...). Widening this
12
- * set blocks legitimate retries; narrowing it lets a double charge through, so
13
- * an outcome earns a place here only by being genuinely post-click.
14
- */
15
- export declare const MAY_HAVE_CHARGED_OUTCOMES: ReadonlySet<string>;
16
- /** One local attempt that may have taken money and was never resolved. */
17
- export type UnresolvedCharge = {
18
- recordedAt: string;
19
- host: string;
20
- amount: string;
21
- amountMinor: number;
22
- currency: string;
23
- outcome: string;
24
- /** Receipt file basename, so a caller can name the evidence a human must check. */
25
- receiptFile: string;
26
- };
27
- /**
28
- * Local attempts that may have charged, newest first.
29
- *
30
- * Never throws: a missing directory (nothing has ever been checked out here)
31
- * and an unreadable one both read as "no unresolved charges". The caller
32
- * decides what an empty answer means — see the fail-open note at its call site.
33
- */
34
- export declare function readUnresolvedCharges(receiptDir?: string): Promise<UnresolvedCharge[]>;
@@ -1,134 +0,0 @@
1
- // "Did this device already submit this exact purchase?", read back from the
2
- // checkout receipts on disk.
3
- //
4
- // The engine now reports a submitted-but-unobserved checkout as `unverified`
5
- // instead of `failed`, and pay_merchant tells the caller not to retry it. This
6
- // module is the belt to that suspenders: even a caller that ignores the words
7
- // can be stopped, because the previous attempt left a receipt.
8
- //
9
- // It answers one question — which local receipts record an attempt that MAY
10
- // HAVE CHARGED and was never resolved — and deliberately answers nothing else.
11
- // The matching (same merchant, same amount, recent enough) lives in the caller,
12
- // which owns the policy; this side owns only the read.
13
- //
14
- // Sibling of confirmed-merchants.ts and loaded through the same seam: it
15
- // imports node built-ins and types only, so reading receipts never pulls
16
- // playwright into the CLI process.
17
- //
18
- // Reading is best-effort by construction. The receipts directory is an operator
19
- // artifact that anything on the box can touch, so an unreadable or malformed
20
- // file is skipped rather than failing the whole read.
21
- import { readdir, readFile } from 'node:fs/promises';
22
- import { join } from 'node:path';
23
- import { RECEIPT_DIR } from './receipt-dir.js';
24
- /**
25
- * Outcomes whose receipt cannot rule out a charge.
26
- *
27
- * Both of these record a run where the pay control was clicked and no
28
- * definitive answer came back:
29
- * - `unverified` — no confirmation or decline observed before the deadline
30
- * - `action-required` — an issuer challenge appeared, which happens AFTER the
31
- * click, so the authorization may already exist
32
- *
33
- * Everything else is either definitive (`confirmed`, `declined`) or provably
34
- * pre-click (`reviewed-dry-run`, `partial-fill`, `failed`, ...). Widening this
35
- * set blocks legitimate retries; narrowing it lets a double charge through, so
36
- * an outcome earns a place here only by being genuinely post-click.
37
- */
38
- export const MAY_HAVE_CHARGED_OUTCOMES = new Set([
39
- 'unverified',
40
- 'action-required',
41
- ]);
42
- /**
43
- * Every field this module reads, validated. Deliberately permissive about
44
- * everything else: older and newer engines only have to carry these.
45
- *
46
- * Both receipt schemas expose all of them at the same paths, so unlike
47
- * confirmed-merchants.ts there is nothing here that needs a per-schema branch.
48
- */
49
- function parseUnresolved(json, receiptFile) {
50
- let parsed;
51
- try {
52
- parsed = JSON.parse(json);
53
- }
54
- catch {
55
- return null;
56
- }
57
- if (typeof parsed !== 'object' || parsed === null)
58
- return null;
59
- const receipt = parsed;
60
- if (receipt.schema !== 'checkout-agent-receipt/v1' &&
61
- receipt.schema !== 'checkout-agent-receipt/v2') {
62
- return null;
63
- }
64
- // Terminal review observations are useful capability evidence, but no pay
65
- // control, credential, or submission exists yet. They must never poison the
66
- // double-charge ledger even when the observed page showed a Shop Pay or 3DS
67
- // action-required surface.
68
- if (receipt.schema === 'checkout-agent-receipt/v2' &&
69
- (receipt.phase === 'review' ||
70
- (typeof receipt.observationId === 'string' && receipt.receiptId === null))) {
71
- return null;
72
- }
73
- if (typeof receipt.outcome !== 'string' || !MAY_HAVE_CHARGED_OUTCOMES.has(receipt.outcome)) {
74
- return null;
75
- }
76
- if (typeof receipt.recordedAt !== 'string' || Number.isNaN(Date.parse(receipt.recordedAt))) {
77
- return null;
78
- }
79
- const host = receipt.merchant?.host;
80
- if (typeof host !== 'string' || host.length === 0)
81
- return null;
82
- const transaction = receipt.transaction;
83
- if (typeof transaction?.amount !== 'string')
84
- return null;
85
- if (typeof transaction.currency !== 'string')
86
- return null;
87
- // A receipt whose amount cannot be compared cannot gate a retry on amount, and
88
- // a guard that silently matched every amount would be worse than none.
89
- if (typeof transaction.amountMinor !== 'number' || !Number.isFinite(transaction.amountMinor)) {
90
- return null;
91
- }
92
- return {
93
- recordedAt: receipt.recordedAt,
94
- host,
95
- amount: transaction.amount,
96
- amountMinor: transaction.amountMinor,
97
- currency: transaction.currency,
98
- outcome: receipt.outcome,
99
- receiptFile,
100
- };
101
- }
102
- /**
103
- * Local attempts that may have charged, newest first.
104
- *
105
- * Never throws: a missing directory (nothing has ever been checked out here)
106
- * and an unreadable one both read as "no unresolved charges". The caller
107
- * decides what an empty answer means — see the fail-open note at its call site.
108
- */
109
- export async function readUnresolvedCharges(receiptDir = RECEIPT_DIR) {
110
- let names;
111
- try {
112
- names = await readdir(receiptDir);
113
- }
114
- catch {
115
- return [];
116
- }
117
- const charges = [];
118
- for (const name of names) {
119
- if (!name.endsWith('.json'))
120
- continue;
121
- let raw;
122
- try {
123
- raw = await readFile(join(receiptDir, name), 'utf8');
124
- }
125
- catch {
126
- continue;
127
- }
128
- const charge = parseUnresolved(raw, name);
129
- if (charge)
130
- charges.push(charge);
131
- }
132
- charges.sort((left, right) => (left.recordedAt < right.recordedAt ? 1 : -1));
133
- return charges;
134
- }
@@ -1,155 +0,0 @@
1
- import { type KeyObject } from 'node:crypto';
2
- import type { VgsCheckoutTarget, VgsPaymentCredential } from '../vgs-live-instrument.js';
3
- export type ServerMintDeps = {
4
- /** Injectable for tests — defaults to global fetch. */
5
- fetchImpl?: typeof fetch;
6
- /** Injectable for tests — never wall-clock-sleep in a unit test. */
7
- sleep?: (ms: number) => Promise<void>;
8
- env?: NodeJS.ProcessEnv;
9
- };
10
- /**
11
- * The merchant ORIGIN (scheme + host) — not the full checkout URL. A merchant's
12
- * identity is its origin; a real checkout URL can carry hundreds of chars of
13
- * campaign/tracking query params. Confirmed live: an oversized `merchantUrl`
14
- * (a ~280-char Wikimedia donation URL) makes the cryptogram mint fail downstream
15
- * with a vague `502 "card network could not complete"`, while the same merchant
16
- * with a trimmed URL mints fine. Sending the origin is both correct (that IS the
17
- * merchant) and safely bounded. Falls back to the raw value if it does not parse
18
- * — the mint must never throw here.
19
- */
20
- export declare function merchantOrigin(url: string): string;
21
- /**
22
- * A definitive refusal from the cryptogram mint route — the request will not
23
- * succeed if retried unchanged.
24
- *
25
- * `terminal` is the load-bearing field. Draw terminality used to be decided by
26
- * regex over the error MESSAGE, which made it hostage to text nobody controls:
27
- * this client now interpolates the provider's own `upstream_codes` into the
28
- * message for diagnosability, and a provider identifier such as
29
- * `request_timeout` would match the transient matcher's unanchored
30
- * `tim(e|ed)-out` alternative — flipping a permanent 422 back to "transient",
31
- * skipping markUnhonored, and stranding the mandate in the exact retry-forever
32
- * loop this whole change exists to kill. Terminality is therefore carried
33
- * structurally, and consumers must consult it BEFORE any message matching.
34
- */
35
- export declare class ServerCryptogramRefusedError extends Error {
36
- readonly status: number;
37
- readonly terminal: true;
38
- constructor(status: number, detail: string);
39
- }
40
- export type ServerIntentBootstrapState = 'none' | 'pending' | 'created' | 'ambiguous' | 'conflict' | 'unknown';
41
- /**
42
- * The budget-intent route's failure, kept structured (#8470). `status` 0 means
43
- * the request never produced an HTTP response (network failure or abort), which
44
- * is outcome-uncertain exactly like a 5xx: the server may have dispatched.
45
- */
46
- export declare class ServerIntentError extends Error {
47
- readonly facts: {
48
- status: number;
49
- errorCode: string | null;
50
- /** null: the route supplied no boolean retry advice. */
51
- retryable: boolean | null;
52
- requestId: string | null;
53
- bootstrapState: ServerIntentBootstrapState;
54
- outcome: 'uncertain' | 'not_created' | 'unknown';
55
- };
56
- readonly code = "SERVER_INTENT_FAILED";
57
- constructor(message: string, facts: {
58
- status: number;
59
- errorCode: string | null;
60
- /** null: the route supplied no boolean retry advice. */
61
- retryable: boolean | null;
62
- requestId: string | null;
63
- bootstrapState: ServerIntentBootstrapState;
64
- outcome: 'uncertain' | 'not_created' | 'unknown';
65
- });
66
- }
67
- /**
68
- * Optional mandate override for serverCreateIntent. Absent → the default
69
- * intent shape (cap = ceil(amount)+10 min 25, quantity 1, 30-day window).
70
- * Present → the card-mandate (budget) layer sets a CEILING decline threshold
71
- * and a multi-draw quantity so one passkey approves a spend ceiling and later
72
- * draws pull cryptograms under it without a fresh tap. Whether the network
73
- * honors a ceiling-scoped assurance across multiple sub-amount draws is
74
- * UNPROVEN — see packages/checkout-engine/src/mandate/.
75
- */
76
- export type ServerIntentMandateOverride = {
77
- /** Wire decline-threshold amount (major-unit decimal string), e.g. "500.00". */
78
- declineThresholdAmount?: string;
79
- /** Number of draws the intent may fulfil (VGS mandate `quantity`). */
80
- quantity?: number;
81
- /** ISO 8601 mandate validity end. */
82
- effectiveUntil?: string;
83
- /** Human-readable consumer prompt describing the ceiling grant. */
84
- consumerPrompt?: string;
85
- };
86
- /**
87
- * Create a fresh intent via POST {base}/api/vgs/intent. The server holds the VGS
88
- * credential and calls the gateway; we send the same mandate shape the local
89
- * path built (cap = ceil(amount)+10, min 25; merchant category Retail/5999) —
90
- * unless `input.mandate` overrides the threshold/quantity/window for the
91
- * card-mandate (budget) layer.
92
- */
93
- export declare function serverCreateIntent(base: string, mintToken: string, input: {
94
- tokenId: string;
95
- assuranceData: unknown;
96
- transaction: VgsCheckoutTarget;
97
- mandate?: ServerIntentMandateOverride;
98
- }, deps?: ServerMintDeps): Promise<{
99
- intentId: string;
100
- status: string | null;
101
- }>;
102
- /**
103
- * Read the durable budget-bootstrap state for a budget mint token via
104
- * GET {base}/api/vgs/intent (#8470). A `created` answer carries the intent the
105
- * server already minted under this token, so the runner registers it instead
106
- * of dispatching again; `pending` and `ambiguous` are never redispatched.
107
- */
108
- export declare function serverReadIntentBootstrap(base: string, mintToken: string, deps?: ServerMintDeps): Promise<{
109
- state: ServerIntentBootstrapState;
110
- intentId: string | null;
111
- intentStatus: string | null;
112
- requestId: string | null;
113
- }>;
114
- /**
115
- * Mint the FULL payment credential via POST {base}/api/vgs/payment-cryptogram.
116
- * The server's route does a SINGLE gateway call and 502s on a not-COMPLETED
117
- * (e.g. PENDING) cryptogram, but live intent approval is asynchronous and the
118
- * first cryptogram answer can be PENDING (#5709). So we retry the route on any
119
- * non-2xx up to PENDING_ATTEMPTS, matching fetch-credential.mjs's cadence
120
- * exactly — a genuinely hard failure just surfaces after the same bounded wait.
121
- * Re-POSTing for the same intentId is idempotent (mirrors the old client loop).
122
- */
123
- export declare function serverFetchCryptogram(base: string, mintToken: string, input: {
124
- tokenId: string;
125
- intentId: string;
126
- transaction: VgsCheckoutTarget;
127
- }, deps?: ServerMintDeps): Promise<VgsPaymentCredential>;
128
- /** Report the observed merchant outcome via POST {base}/api/vgs/confirmation. */
129
- export declare function serverPostConfirmation(base: string, mintToken: string, input: {
130
- tokenId: string;
131
- intentId: string;
132
- transactionStatus: string;
133
- transactionType: string;
134
- transactionTimestamp: string;
135
- transaction: {
136
- transactionAmount: string;
137
- transactionCurrencyCode: string;
138
- };
139
- }, deps?: ServerMintDeps): Promise<{
140
- ok: true;
141
- }>;
142
- /** One exact protected attempt. Caller retains its delivery KeyObject across
143
- * retries; it is never serialized into a request, receipt, log, or agent context. */
144
- /** Pins are installed with the checkout deployment, never supplied by Auth or the response. */
145
- export interface ProtectedCardPins {
146
- executor: KeyObject;
147
- issuer: KeyObject;
148
- }
149
- export declare function serverFetchProtectedCryptogram(base: string, input: {
150
- financialAdmission: string;
151
- request: unknown;
152
- requestHash: string;
153
- deliveryKey: KeyObject;
154
- pins: ProtectedCardPins;
155
- }, deps?: ServerMintDeps): Promise<VgsPaymentCredential>;