@visa/cli 4.1.0-rc.165 → 4.1.0-rc.167

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.
@@ -10,9 +10,32 @@ export { minorFromDecimal, pageCurrency } from './amount.js';
10
10
  export type CheckoutMode = 'dry-run' | 'submit';
11
11
  export type CheckoutOutcome = 'reviewed-dry-run'
12
12
  /** Historical receipt value from the credential-disclosing dry-run. */
13
- | 'filled-dry-run' | 'partial-fill' | 'adapter-required' | 'confirmed' | 'declined' | 'action-required' | 'cancelled' | 'blocked-by-mandate' | 'failed';
13
+ | 'filled-dry-run' | 'partial-fill' | 'adapter-required' | 'confirmed' | 'declined' | 'action-required' | 'cancelled' | 'blocked-by-mandate'
14
+ /**
15
+ * KNOWN-NOT-CHARGED. Every `failed` path ends before the pay control was
16
+ * clicked (or before a credential existed at all), so a caller may retry it
17
+ * without risking a second charge.
18
+ */
19
+ | 'failed'
20
+ /**
21
+ * SUBMITTED, OUTCOME UNKNOWN — the pay control WAS clicked and neither a
22
+ * confirmation nor a decline was observed before the deadline. The charge may
23
+ * have captured. NEVER retry this automatically.
24
+ *
25
+ * This case used to be reported as `failed`, and the difference is not
26
+ * academic: on 2026-08-17 a whop.com checkout returned `failed` here, the
27
+ * caller read that as "nothing happened" and re-ran the purchase, and the
28
+ * second run drew a second $5 against the owner's mandate. `outcome.ts`
29
+ * already treats an unrecognized post-submit page as the SAFE direction
30
+ * ('unknown' → operator verification); collapsing it into `failed` at the
31
+ * boundary is what threw that safety away. The distinction has to survive all
32
+ * the way to the value consumers branch on.
33
+ */
34
+ | 'unverified';
14
35
  /** Stable machine-readable cause for an expected terminal checkout result. */
15
- export type CheckoutFailureCode = 'card-number-field-unavailable' | 'human-action-required' | 'mandate-blocked';
36
+ export type CheckoutFailureCode = 'card-number-field-unavailable' | 'human-action-required' | 'mandate-blocked'
37
+ /** A detected, visible field we held a value for refused every fill attempt. */
38
+ | 'required-field-unfillable';
16
39
  export type CredentialLifecycle = 'not-requested' | 'minted-not-exposed' | 'partially-exposed' | 'fully-filled';
17
40
  export type CredentialTiming = {
18
41
  approvedAt?: string;
@@ -1116,9 +1116,30 @@ export async function submitApprovedCheckout(reviewId, opts, store = defaultPrep
1116
1116
  ? []
1117
1117
  : ['expiry']),
1118
1118
  ];
1119
+ // Roles the adapter TRIED to fill and never landed, across every reveal
1120
+ // attempt. A job only exists when the field was detected, was visible, and
1121
+ // we held a value for it (see `add()` in adapters/generic.ts) — so a failure
1122
+ // here is never "the page didn't ask for it". It means the page asked, we
1123
+ // answered, and the element refused.
1124
+ //
1125
+ // Roles that failed on an early attempt and succeeded after a reveal are
1126
+ // excluded: `successfulRoles` spans all four attempts, same as above.
1127
+ const failedFillRoles = [
1128
+ ...new Set(evidence
1129
+ .getSteps()
1130
+ .filter((step) => step.type === 'field-fill' && step.data.ok === false)
1131
+ .map((step) => String(step.data.role))),
1132
+ ]
1133
+ .filter((role) => !successfulRoles.has(role))
1134
+ .sort();
1119
1135
  evidence.step('fill-complete', {
1120
- ok: missingCredentialRoles.length === 0,
1136
+ // "Ready to submit", not "the card fields landed". Before 2026-08-17 this
1137
+ // read only the credential roles, so a whop.com run whose city/state/
1138
+ // postalCode all timed out recorded `ok: true` and clicked Get access on
1139
+ // a form it knew was incomplete.
1140
+ ok: missingCredentialRoles.length === 0 && failedFillRoles.length === 0,
1121
1141
  missingCredentialRoles,
1142
+ failedFillRoles,
1122
1143
  });
1123
1144
  if (options.debugShotsDir) {
1124
1145
  await captureDebugShot(page, options.debugShotsDir, checkout.review.id, '2-filled', evidence, state.fields);
@@ -1177,6 +1198,20 @@ export async function submitApprovedCheckout(reviewId, opts, store = defaultPrep
1177
1198
  evidence.setSnapshotSummary(await snapshotSummary(page));
1178
1199
  return makeResult('failed', state.fields, evidence, requiresAdapter, `credential fill incomplete: missing ${missingCredentialRoles.join(', ')}`);
1179
1200
  }
1201
+ // STOP BEFORE THE CLICK when any field we tried to fill refused. Submitting
1202
+ // a form we know is incomplete is how a PSP ends up holding a charge we
1203
+ // cannot then confirm or account for: the 2026-08-17 whop.com run filled the
1204
+ // card into Basis Theory iframes, watched city/state/postalCode time out at
1205
+ // 5s each, clicked Get access anyway, and could never observe an outcome.
1206
+ //
1207
+ // This refusal happens BEFORE the submit click, so nothing can be charged by
1208
+ // it — the safe direction, and the reason it is allowed to be strict. A
1209
+ // merchant whose address widget we cannot drive now fails cleanly and
1210
+ // retryably instead of dangerously.
1211
+ if (failedFillRoles.length > 0) {
1212
+ evidence.setSnapshotSummary(await snapshotSummary(page));
1213
+ return makeResult('partial-fill', state.fields, evidence, requiresAdapter, `required field fill failed: ${failedFillRoles.join(', ')} — not submitting an incomplete form. Nothing was charged.`, undefined, 'required-field-unfillable');
1214
+ }
1180
1215
  if (!submit) {
1181
1216
  evidence.setSnapshotSummary(await snapshotSummary(page));
1182
1217
  return makeResult('failed', state.fields, evidence, requiresAdapter, 'no submit control detected');
@@ -1216,6 +1251,12 @@ export async function submitApprovedCheckout(reviewId, opts, store = defaultPrep
1216
1251
  credentialExpiresAt,
1217
1252
  });
1218
1253
  }
1254
+ // ORDER IS LOAD-BEARING: record the click BEFORE performing it. The catch
1255
+ // block classifies a throw by whether this step exists — recorded means
1256
+ // "we may have charged" (`unverified`), absent means "retry is safe"
1257
+ // (`failed`). Recording after `submit.click()` would let a throw raised by
1258
+ // the click itself look retry-safe, which is the double-charge direction.
1259
+ // Pinned by "a throw AFTER the pay control was clicked reports unverified".
1219
1260
  evidence.step('submit', { clicked: true, target: submit.desc });
1220
1261
  await submit.click();
1221
1262
  await settle(page);
@@ -1337,19 +1378,35 @@ export async function submitApprovedCheckout(reviewId, opts, store = defaultPrep
1337
1378
  });
1338
1379
  return makeResult('confirmed', state.fields, evidence, requiresAdapter, undefined, confirmationRef);
1339
1380
  }
1381
+ // The pay control was clicked and the observer reached its deadline with no
1382
+ // definitive answer. This is NOT a failure — it is the absence of an answer,
1383
+ // and the charge may well have captured. Reporting it as `failed` is what
1384
+ // let a caller re-run the 2026-08-17 whop.com purchase and draw a second $5.
1340
1385
  evidence.step('outcome', {
1341
- outcome: 'failed',
1386
+ outcome: 'unverified',
1342
1387
  reason: 'no confirmation or decline signal',
1343
1388
  lastSeen: observed.lastSeen,
1344
1389
  attempts: observed.attempts,
1345
1390
  elapsedMs: observed.elapsedMs,
1346
1391
  });
1347
- return makeResult('failed', state.fields, evidence, requiresAdapter, observed.lastSeen === 'processing'
1348
- ? 'submitted but outcome unknown (page still processing at deadline)'
1349
- : 'submitted but outcome unknown');
1392
+ return makeResult('unverified', state.fields, evidence, requiresAdapter, observed.lastSeen === 'processing'
1393
+ ? 'submitted but outcome unknown (page still processing at deadline) — the charge may have gone through; verify with the merchant before any retry'
1394
+ : 'submitted but outcome unknown — the charge may have gone through; verify with the merchant before any retry');
1350
1395
  }
1351
1396
  catch (err) {
1352
1397
  const detail = err.message;
1398
+ // A throw AFTER the pay control was clicked (browser teardown, navigation
1399
+ // race, evidence I/O) leaves the same open question as the deadline path: we
1400
+ // clicked, and we do not know what happened. It must not report `failed`
1401
+ // either. A throw before the click never disclosed a payable form, so it
1402
+ // stays a clean, retry-safe failure.
1403
+ const submitted = evidence
1404
+ .getSteps()
1405
+ .some((step) => step.type === 'submit' && step.data.clicked === true);
1406
+ if (submitted) {
1407
+ evidence.step('outcome', { outcome: 'unverified', error: detail });
1408
+ return makeResult('unverified', state.fields, evidence, requiresAdapter, `${detail} — the pay control was already clicked; the charge may have gone through, so verify with the merchant before any retry`);
1409
+ }
1353
1410
  evidence.step('outcome', { outcome: 'failed', error: detail });
1354
1411
  return makeResult('failed', state.fields, evidence, requiresAdapter, detail);
1355
1412
  }
@@ -28,5 +28,10 @@ export declare function isRunSuccess(mode: CheckoutMode, outcome: CheckoutOutcom
28
28
  * so no charge can exist until it is completed — the double-charge warning
29
29
  * would misdirect the operator, and the runner prints the challenge-specific
30
30
  * notice instead.
31
+ *
32
+ * The executor now NAMES this state in the outcome itself ('unverified'), so
33
+ * the two agree by construction. This predicate stays the broader guard: it
34
+ * also catches a post-click throw or any future outcome that leaves the same
35
+ * question open, and it is what the receipt's reconciliation list reads.
31
36
  */
32
37
  export declare function submitClickedWithoutConfirmation(result: CheckoutResult): boolean;
@@ -60,6 +60,11 @@ export function isRunSuccess(mode, outcome) {
60
60
  * so no charge can exist until it is completed — the double-charge warning
61
61
  * would misdirect the operator, and the runner prints the challenge-specific
62
62
  * notice instead.
63
+ *
64
+ * The executor now NAMES this state in the outcome itself ('unverified'), so
65
+ * the two agree by construction. This predicate stays the broader guard: it
66
+ * also catches a post-click throw or any future outcome that leaves the same
67
+ * question open, and it is what the receipt's reconciliation list reads.
63
68
  */
64
69
  export function submitClickedWithoutConfirmation(result) {
65
70
  if (result.outcome === 'confirmed' ||
@@ -37,7 +37,15 @@ export function buildReceipt(input) {
37
37
  ? 'No action needed.'
38
38
  : result.outcome === 'declined'
39
39
  ? 'Review the decline before trying again.'
40
- : 'Review this outcome before retrying.';
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
+ ? 'Nothing was submitted and nothing was charged. Safe to try again once the checkout can be filled.'
48
+ : 'Review this outcome before retrying.';
41
49
  const recoveryActions = reconciliation.reasons.length > 0 ? reconciliation.reasons : [fallbackAction];
42
50
  const cardLast4 = input.cardLast4 && /^\d{4}$/.test(input.cardLast4) ? input.cardLast4 : null;
43
51
  const checkoutUrl = input.merchant.url && KNOWN_MERCHANT_IDENTITIES[input.merchant.url] ? input.merchant.url : null;
@@ -0,0 +1,34 @@
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[]>;
@@ -0,0 +1,125 @@
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
+ if (typeof receipt.outcome !== 'string' || !MAY_HAVE_CHARGED_OUTCOMES.has(receipt.outcome)) {
65
+ return null;
66
+ }
67
+ if (typeof receipt.recordedAt !== 'string' || Number.isNaN(Date.parse(receipt.recordedAt))) {
68
+ return null;
69
+ }
70
+ const host = receipt.merchant?.host;
71
+ if (typeof host !== 'string' || host.length === 0)
72
+ return null;
73
+ const transaction = receipt.transaction;
74
+ if (typeof transaction?.amount !== 'string')
75
+ return null;
76
+ if (typeof transaction.currency !== 'string')
77
+ return null;
78
+ // A receipt whose amount cannot be compared cannot gate a retry on amount, and
79
+ // a guard that silently matched every amount would be worse than none.
80
+ if (typeof transaction.amountMinor !== 'number' || !Number.isFinite(transaction.amountMinor)) {
81
+ return null;
82
+ }
83
+ return {
84
+ recordedAt: receipt.recordedAt,
85
+ host,
86
+ amount: transaction.amount,
87
+ amountMinor: transaction.amountMinor,
88
+ currency: transaction.currency,
89
+ outcome: receipt.outcome,
90
+ receiptFile,
91
+ };
92
+ }
93
+ /**
94
+ * Local attempts that may have charged, newest first.
95
+ *
96
+ * Never throws: a missing directory (nothing has ever been checked out here)
97
+ * and an unreadable one both read as "no unresolved charges". The caller
98
+ * decides what an empty answer means — see the fail-open note at its call site.
99
+ */
100
+ export async function readUnresolvedCharges(receiptDir = RECEIPT_DIR) {
101
+ let names;
102
+ try {
103
+ names = await readdir(receiptDir);
104
+ }
105
+ catch {
106
+ return [];
107
+ }
108
+ const charges = [];
109
+ for (const name of names) {
110
+ if (!name.endsWith('.json'))
111
+ continue;
112
+ let raw;
113
+ try {
114
+ raw = await readFile(join(receiptDir, name), 'utf8');
115
+ }
116
+ catch {
117
+ continue;
118
+ }
119
+ const charge = parseUnresolved(raw, name);
120
+ if (charge)
121
+ charges.push(charge);
122
+ }
123
+ charges.sort((left, right) => (left.recordedAt < right.recordedAt ? 1 : -1));
124
+ return charges;
125
+ }