@visa/cli 4.1.0-rc.25 → 4.1.0-rc.251
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.
- package/README.md +273 -227
- package/dist/checkout-engine/adapters/generic.d.ts +69 -0
- package/dist/checkout-engine/adapters/generic.js +383 -58
- package/dist/checkout-engine/adapters/index.d.ts +4 -1
- package/dist/checkout-engine/adapters/index.js +10 -3
- package/dist/checkout-engine/adapters/shopify.d.ts +80 -0
- package/dist/checkout-engine/adapters/shopify.js +688 -0
- package/dist/checkout-engine/amount.d.ts +15 -0
- package/dist/checkout-engine/amount.js +72 -0
- package/dist/checkout-engine/browser-launch.d.ts +9 -4
- package/dist/checkout-engine/browser-launch.js +19 -4
- package/dist/checkout-engine/browserbase-browser.d.ts +24 -0
- package/dist/checkout-engine/browserbase-browser.js +186 -0
- package/dist/checkout-engine/cli-engine.d.ts +297 -4
- package/dist/checkout-engine/cli-engine.js +942 -48
- package/dist/checkout-engine/confirmed-merchants.d.ts +31 -0
- package/dist/checkout-engine/confirmed-merchants.js +165 -0
- package/dist/checkout-engine/detect.d.ts +1 -1
- package/dist/checkout-engine/detect.js +26 -0
- package/dist/checkout-engine/evidence.d.ts +4 -1
- package/dist/checkout-engine/evidence.js +51 -6
- package/dist/checkout-engine/executor.d.ts +64 -4
- package/dist/checkout-engine/executor.js +625 -146
- package/dist/checkout-engine/hosted-approval.d.ts +124 -7
- package/dist/checkout-engine/hosted-approval.js +384 -54
- package/dist/checkout-engine/index.d.ts +9 -2
- package/dist/checkout-engine/index.js +8 -1
- package/dist/checkout-engine/instrument.d.ts +7 -0
- package/dist/checkout-engine/instrument.js +4 -0
- package/dist/checkout-engine/known-merchants.d.ts +10 -0
- package/dist/checkout-engine/known-merchants.js +38 -0
- package/dist/checkout-engine/live-fill-approval.d.ts +5 -20
- package/dist/checkout-engine/live-fill-approval.js +20 -51
- package/dist/checkout-engine/mandate/card-mandate.d.ts +121 -0
- package/dist/checkout-engine/mandate/card-mandate.js +226 -0
- package/dist/checkout-engine/mandate/mandate-ledger.d.ts +174 -0
- package/dist/checkout-engine/mandate/mandate-ledger.js +410 -0
- package/dist/checkout-engine/outcome.d.ts +2 -2
- package/dist/checkout-engine/outcome.js +36 -1
- package/dist/checkout-engine/owner-only-file.d.ts +9 -0
- package/dist/checkout-engine/owner-only-file.js +20 -1
- package/dist/checkout-engine/receipt-dir.d.ts +6 -0
- package/dist/checkout-engine/receipt-dir.js +8 -0
- package/dist/checkout-engine/receipt.d.ts +56 -2
- package/dist/checkout-engine/receipt.js +55 -16
- package/dist/checkout-engine/shopify-primary-domain.d.ts +25 -0
- package/dist/checkout-engine/shopify-primary-domain.js +96 -0
- package/dist/checkout-engine/trace-handles.d.ts +8 -0
- package/dist/checkout-engine/trace-handles.js +12 -0
- package/dist/checkout-engine/types.d.ts +28 -2
- package/dist/checkout-engine/unresolved-charges.d.ts +34 -0
- package/dist/checkout-engine/unresolved-charges.js +134 -0
- package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +53 -1
- package/dist/checkout-engine/vgs-gateway/server-mint-client.js +78 -10
- package/dist/checkout-engine/vgs-live-instrument.d.ts +38 -35
- package/dist/checkout-engine/vgs-live-instrument.js +51 -74
- package/dist/checkout-engine/vic-confirmation.d.ts +18 -0
- package/dist/checkout-engine/vic-confirmation.js +9 -3
- package/dist/checkout-engine/web-bot-auth.d.ts +98 -0
- package/dist/checkout-engine/web-bot-auth.js +218 -0
- package/dist/cli.js +905 -505
- package/dist/mcp-apps/ucp-checkout.html +280 -0
- package/dist/mcp-server/index.js +744 -175
- package/dist/merchant-ucp-mcp/index.js +6 -0
- package/dist/skills/pair-visa-agent/RUNTIMES.md +122 -79
- package/dist/skills/pair-visa-agent/SKILL.md +436 -279
- package/dist/skills/pair-visa-agent/scripts/__tests__/setup.test.mjs +407 -0
- package/dist/skills/pair-visa-agent/scripts/setup.mjs +310 -30
- package/dist/skills/visa-shopify-checkout/SKILL.md +122 -0
- package/dist/skills/visa-shopify-checkout/references/evidence-and-states.md +37 -0
- package/dist/skills/visa-ucp-shopping/SKILL.md +86 -0
- package/dist/subway-direct.mjs +1 -0
- package/install.ps1 +9 -46
- package/install.sh +5 -37
- package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
- package/package.json +32 -28
- package/server.json +4 -4
- package/dist/checkout-engine/inline-target.d.ts +0 -13
- package/dist/checkout-engine/inline-target.js +0 -37
- package/dist/checkout-engine/pay-args.d.ts +0 -14
- package/dist/checkout-engine/pay-args.js +0 -44
- package/dist/checkout-engine/pay.d.ts +0 -1
- package/dist/checkout-engine/pay.js +0 -13
- package/dist/checkout-engine/repo-env.d.ts +0 -11
- package/dist/checkout-engine/repo-env.js +0 -23
- package/dist/checkout-engine/run-live-fill.d.ts +0 -1
- package/dist/checkout-engine/run-live-fill.js +0 -443
- package/dist/checkout-engine/vgs-gateway/fetch-credential.d.mts +0 -74
- package/dist/checkout-engine/vgs-gateway/fetch-credential.mjs +0 -248
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
// Owner-only persisted ledger for card mandates (budgets). One passkey approval
|
|
2
|
+
// creates one VGS intent with a CEILING decline threshold; this ledger tracks
|
|
3
|
+
// the cumulative budget the agent may draw against that intent without a fresh
|
|
4
|
+
// tap. It deliberately MIRRORS csmoove530's standing-mandate ledger (#5600 /
|
|
5
|
+
// #5724) so the two reconcile later rather than competing:
|
|
6
|
+
//
|
|
7
|
+
// - owner-only (chmod 600) JSON artifact under ~/.visa-mcp/, atomic write;
|
|
8
|
+
// - integer minor-unit accounting only — no floating-point money;
|
|
9
|
+
// - atomic reserve -> commit | release around every draw, so approved plus
|
|
10
|
+
// in-flight spend can never exceed the authenticated ceiling.
|
|
11
|
+
//
|
|
12
|
+
// VGS's decline_threshold is a per-transaction NETWORK control; this ledger is
|
|
13
|
+
// the SEPARATE cumulative budget control. The file holds identifiers and
|
|
14
|
+
// accounting state only — never a bootstrap mint token, PAN, DPAN, CVC, or
|
|
15
|
+
// cryptogram values. Cross-process concurrency is NOT solved by a file
|
|
16
|
+
// (same caveat csmoove notes); the in-process mutex below serializes draws
|
|
17
|
+
// within one CLI process, which is the live-spike target.
|
|
18
|
+
//
|
|
19
|
+
// SELF-HEALING: a reservation is persisted the instant it is taken and is only
|
|
20
|
+
// removed by commit() or release(). A crash BETWEEN reserve and commit/release
|
|
21
|
+
// would otherwise strand the reservation forever, permanently shrinking
|
|
22
|
+
// `remaining`. The headroom-deciding paths (reserve() and findCovering()) run a
|
|
23
|
+
// stale-reservation sweep on load: any reservation older than
|
|
24
|
+
// STALE_RESERVATION_MS (a draw cannot legitimately stay in-flight that long) is
|
|
25
|
+
// dropped, returning its headroom, so a stranded reservation can never block a
|
|
26
|
+
// legitimate draw. reserve()'s save() persists the prune; findCovering() heals
|
|
27
|
+
// its in-memory view. The sweep uses the caller's clock (michaelyang1 L1).
|
|
28
|
+
import { randomBytes } from 'node:crypto';
|
|
29
|
+
import { homedir } from 'node:os';
|
|
30
|
+
import { join } from 'node:path';
|
|
31
|
+
import { readOwnerOnlyJson, writeOwnerOnlyJson } from '../owner-only-file.js';
|
|
32
|
+
export const CARD_MANDATE_LEDGER_VERSION = 1;
|
|
33
|
+
// A ledger with a long draw history is larger than a single credential; cap
|
|
34
|
+
// generously but still bounded (owner-only-file's default 16 KB is too small).
|
|
35
|
+
const LEDGER_MAX_BYTES = 512 * 1024;
|
|
36
|
+
// A tap-free draw's reserve -> commit/release cycle completes in one network
|
|
37
|
+
// round-trip; a reservation older than this window can only be the debris of a
|
|
38
|
+
// crash between reserve and commit/release, so load() sweeps it (L1 self-heal).
|
|
39
|
+
// Must match the server-authoritative TTL (CARD_MANDATE_RESERVATION_TTL_SECONDS
|
|
40
|
+
// in apps/auth/src/server.ts, default 15 min) to avoid a window where the local
|
|
41
|
+
// ledger over-reports available headroom.
|
|
42
|
+
const STALE_RESERVATION_MS = 15 * 60 * 1000;
|
|
43
|
+
// Mandates expired longer ago than this are pruned on the next create(). Generous
|
|
44
|
+
// (a week) so a recently-expired mandate is still visible in `mandate list`, but
|
|
45
|
+
// bounded so a long-lived heavy user cannot grow the owner-only ledger file into
|
|
46
|
+
// its size cap — which would otherwise brick EVERY ledger op (create/reserve/
|
|
47
|
+
// findCovering/commit/release all load the file first).
|
|
48
|
+
const EXPIRED_PRUNE_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
49
|
+
function reservedTotal(record) {
|
|
50
|
+
return record.reservations.reduce((sum, r) => sum + r.amountMinor, 0);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Drop reservations older than STALE_RESERVATION_MS across every mandate — the
|
|
54
|
+
* debris of a crash between reserve and commit/release. Mutates in place and
|
|
55
|
+
* returns true if anything was swept (so the caller can decide to persist).
|
|
56
|
+
* A reservation with an unparseable `reservedAt` is treated as stale.
|
|
57
|
+
*/
|
|
58
|
+
function sweepStaleReservations(file, nowMs) {
|
|
59
|
+
let swept = false;
|
|
60
|
+
for (const m of file.mandates) {
|
|
61
|
+
const kept = m.reservations.filter((r) => {
|
|
62
|
+
const reservedMs = Date.parse(r.reservedAt);
|
|
63
|
+
const stale = !Number.isFinite(reservedMs) || nowMs - reservedMs > STALE_RESERVATION_MS;
|
|
64
|
+
if (stale)
|
|
65
|
+
swept = true;
|
|
66
|
+
return !stale;
|
|
67
|
+
});
|
|
68
|
+
if (kept.length !== m.reservations.length)
|
|
69
|
+
m.reservations = kept;
|
|
70
|
+
}
|
|
71
|
+
return swept;
|
|
72
|
+
}
|
|
73
|
+
/** Available headroom = ceiling - committed - reserved. Integer minor units. */
|
|
74
|
+
export function remainingMinor(record) {
|
|
75
|
+
return record.ceilingMinor - record.spentMinor - reservedTotal(record);
|
|
76
|
+
}
|
|
77
|
+
function isExpired(record, now) {
|
|
78
|
+
const end = Date.parse(record.expiresAt);
|
|
79
|
+
return !Number.isFinite(end) || end <= now.getTime();
|
|
80
|
+
}
|
|
81
|
+
function committedDrawCount(record) {
|
|
82
|
+
return record.draws.filter((draw) => draw.status === 'committed').length;
|
|
83
|
+
}
|
|
84
|
+
function hasDrawCountHeadroom(record) {
|
|
85
|
+
return (record.maxDraws === undefined ||
|
|
86
|
+
committedDrawCount(record) + record.reservations.length < record.maxDraws);
|
|
87
|
+
}
|
|
88
|
+
function assertPositiveInteger(value, label) {
|
|
89
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
90
|
+
throw new Error(`${label} must be a positive integer (minor units)`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The persisted card-mandate ledger. All mutating operations are serialized on
|
|
95
|
+
* an in-process promise chain so two concurrent draws cannot both observe the
|
|
96
|
+
* same remaining balance (the read-modify-write is atomic within the process).
|
|
97
|
+
*/
|
|
98
|
+
export class MandateLedger {
|
|
99
|
+
path;
|
|
100
|
+
chain = Promise.resolve();
|
|
101
|
+
constructor(path = defaultLedgerPath()) {
|
|
102
|
+
this.path = path;
|
|
103
|
+
}
|
|
104
|
+
/** Serialize a read-modify-write so concurrent draws can't race the file. */
|
|
105
|
+
run(fn) {
|
|
106
|
+
const next = this.chain.then(fn, fn);
|
|
107
|
+
// Keep the chain alive even if this op rejects; swallow only the chain copy.
|
|
108
|
+
this.chain = next.then(() => undefined, () => undefined);
|
|
109
|
+
return next;
|
|
110
|
+
}
|
|
111
|
+
// `nowMs` is the caller's clock for the stale-reservation sweep. The sweep
|
|
112
|
+
// deliberately runs only on the headroom-DECIDING loads — reserve() and
|
|
113
|
+
// findCovering() — which are the paths that must not be blocked by
|
|
114
|
+
// crash-stranded reservation debris. commit(), release(), and markUnhonored()
|
|
115
|
+
// pass NO clock on purpose: sweeping while finalizing a reservation could drop
|
|
116
|
+
// the very reservation being committed/released. Pure snapshot reads (get) and
|
|
117
|
+
// create() are likewise clock-independent.
|
|
118
|
+
async load(nowMs) {
|
|
119
|
+
try {
|
|
120
|
+
const doc = await readOwnerOnlyJson(this.path, 'card mandate ledger', LEDGER_MAX_BYTES);
|
|
121
|
+
if (!doc || !Array.isArray(doc.mandates)) {
|
|
122
|
+
return { version: CARD_MANDATE_LEDGER_VERSION, mandates: [] };
|
|
123
|
+
}
|
|
124
|
+
// One-time migration for pre-hardening ledgers. The budget mint is a
|
|
125
|
+
// bootstrap bearer used only during create/register and must not survive
|
|
126
|
+
// process exit. Scrub it eagerly on read, not merely on the next mutation.
|
|
127
|
+
let scrubbedBootstrapToken = false;
|
|
128
|
+
for (const mandate of doc.mandates) {
|
|
129
|
+
if (Object.prototype.hasOwnProperty.call(mandate, 'mintToken')) {
|
|
130
|
+
delete mandate.mintToken;
|
|
131
|
+
scrubbedBootstrapToken = true;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (scrubbedBootstrapToken)
|
|
135
|
+
await writeOwnerOnlyJson(this.path, doc);
|
|
136
|
+
// Self-heal: prune reservations stranded by a crash before commit/release
|
|
137
|
+
// so `remaining` reflects reality. In-memory here; a mutating caller then
|
|
138
|
+
// persists the pruned state via save().
|
|
139
|
+
if (nowMs !== undefined)
|
|
140
|
+
sweepStaleReservations(doc, nowMs);
|
|
141
|
+
return doc;
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
// A missing ledger is the normal first-run state.
|
|
145
|
+
if (err.code === 'ENOENT') {
|
|
146
|
+
return { version: CARD_MANDATE_LEDGER_VERSION, mandates: [] };
|
|
147
|
+
}
|
|
148
|
+
throw err;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
async save(file) {
|
|
152
|
+
await writeOwnerOnlyJson(this.path, file);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Append a freshly-created mandate record. `now` drives the expired-mandate
|
|
156
|
+
* prune below; it defaults to the wall clock but is injectable so callers (and
|
|
157
|
+
* tests) can pin it — every other mutating method takes the same clock, and a
|
|
158
|
+
* real `new Date()` here would otherwise make the prune non-deterministic
|
|
159
|
+
* against fixtures dated relative to a fixed reference time.
|
|
160
|
+
*/
|
|
161
|
+
create(record, now = new Date()) {
|
|
162
|
+
return this.run(async () => {
|
|
163
|
+
const file = await this.load();
|
|
164
|
+
if (file.mandates.some((m) => m.mandateId === record.mandateId)) {
|
|
165
|
+
throw new Error(`mandate ${record.mandateId} already exists in the ledger`);
|
|
166
|
+
}
|
|
167
|
+
// Bound ledger growth: drop mandates expired beyond the grace window. They
|
|
168
|
+
// are already invisible to `mandate list` and unselectable by findCovering,
|
|
169
|
+
// so nothing references them. A mandate with an unparseable expiry is kept
|
|
170
|
+
// (fail-safe — never prune what we cannot date).
|
|
171
|
+
const pruneBefore = now.getTime() - EXPIRED_PRUNE_GRACE_MS;
|
|
172
|
+
file.mandates = file.mandates.filter((m) => {
|
|
173
|
+
const exp = Date.parse(m.expiresAt);
|
|
174
|
+
return !Number.isFinite(exp) || exp >= pruneBefore;
|
|
175
|
+
});
|
|
176
|
+
// Even an older caller that still supplies the deprecated field cannot
|
|
177
|
+
// persist the bootstrap bearer.
|
|
178
|
+
const { mintToken: _discardedBootstrapToken, ...safeRecord } = record;
|
|
179
|
+
file.mandates.push(safeRecord);
|
|
180
|
+
await this.save(file);
|
|
181
|
+
return safeRecord;
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
/** Read a single mandate (no lock — a snapshot copy). */
|
|
185
|
+
async get(mandateId) {
|
|
186
|
+
const file = await this.load();
|
|
187
|
+
return file.mandates.find((m) => m.mandateId === mandateId) ?? null;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* First ACTIVE mandate (not expired) whose merchant + currency match and whose
|
|
191
|
+
* remaining headroom covers amountMinor. Used by pay_merchant to decide the
|
|
192
|
+
* tap-free draw path vs the no-covering-mandate refusal (#7348).
|
|
193
|
+
*/
|
|
194
|
+
async findCovering(query) {
|
|
195
|
+
const now = query.now ?? new Date();
|
|
196
|
+
const file = await this.load(now.getTime());
|
|
197
|
+
// Multiple mandates can now cover one merchant: a merchant-scoped mandate for
|
|
198
|
+
// this host AND any crossMerchant (budget) mandate both qualify (#6003). A
|
|
199
|
+
// mandate the network refused is skipped via `!m.unhonoredAt` so it can never
|
|
200
|
+
// be re-selected. A register-failed mandate is skipped the same way
|
|
201
|
+
// (`!m.registerFailedAt`): it has no server row, so a delegated draw would 404
|
|
202
|
+
// `no_mandate` — better to surface the no-covering refusal (#7348).
|
|
203
|
+
// Selection order among covering candidates:
|
|
204
|
+
// 1. Prefer a merchant-SCOPED mandate over a crossMerchant budget one —
|
|
205
|
+
// spend the dedicated grant for this merchant first and keep the broader
|
|
206
|
+
// broader retail budget for merchants that have no scoped mandate. Draining
|
|
207
|
+
// the budget for a purchase a scoped mandate already covers both wastes
|
|
208
|
+
// the general headroom and can later force a fresh tap at another merchant.
|
|
209
|
+
// 2. Then the MOST headroom, then the latest expiry — never let a near-empty
|
|
210
|
+
// or near-expiry mandate get selected over a fuller, longer-lived sibling
|
|
211
|
+
// and then fail a draw the sibling would have covered.
|
|
212
|
+
const candidates = file.mandates.filter((m) =>
|
|
213
|
+
// A crossMerchant retail budget is locally cross-host; a merchant-scoped
|
|
214
|
+
// one only matches its own host. Network Retail/5999 eligibility is
|
|
215
|
+
// enforced downstream and is not inferred from a website hostname.
|
|
216
|
+
(m.crossMerchant || m.merchantHost === query.merchantHost) &&
|
|
217
|
+
m.agentJkt === query.agentJkt &&
|
|
218
|
+
m.currencyCode.toUpperCase() === query.currencyCode.toUpperCase() &&
|
|
219
|
+
!m.unhonoredAt &&
|
|
220
|
+
!m.registerFailedAt &&
|
|
221
|
+
!m.serverRevokedAt &&
|
|
222
|
+
!isExpired(m, now) &&
|
|
223
|
+
hasDrawCountHeadroom(m) &&
|
|
224
|
+
remainingMinor(m) >= query.amountMinor);
|
|
225
|
+
candidates.sort((a, b) =>
|
|
226
|
+
// A scoped mandate (crossMerchant falsy → 0) sorts before a budget one (1).
|
|
227
|
+
(a.crossMerchant ? 1 : 0) - (b.crossMerchant ? 1 : 0) ||
|
|
228
|
+
remainingMinor(b) - remainingMinor(a) ||
|
|
229
|
+
Date.parse(b.expiresAt) - Date.parse(a.expiresAt));
|
|
230
|
+
return candidates[0] ?? null;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Mark a mandate as unhonored — the network declined a ceiling-scoped draw
|
|
234
|
+
* against it, so it must never be selected again. Atomic, owner-only write on
|
|
235
|
+
* the same serialized chain as every other mutation. Idempotent: a second
|
|
236
|
+
* call keeps the first timestamp. Throws only if the mandate is unknown.
|
|
237
|
+
*/
|
|
238
|
+
markUnhonored(mandateId, now = new Date()) {
|
|
239
|
+
return this.run(async () => {
|
|
240
|
+
const file = await this.load();
|
|
241
|
+
const record = file.mandates.find((m) => m.mandateId === mandateId);
|
|
242
|
+
if (!record)
|
|
243
|
+
throw new Error(`no such mandate ${mandateId}`);
|
|
244
|
+
if (!record.unhonoredAt) {
|
|
245
|
+
record.unhonoredAt = now.toISOString();
|
|
246
|
+
await this.save(file);
|
|
247
|
+
}
|
|
248
|
+
return record;
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Mark a mandate as register-failed — the delegated-draw register handshake
|
|
253
|
+
* did not create the server row at mandate-start, so it must never be selected
|
|
254
|
+
* for a (delegated) draw. Atomic, owner-only write on the same serialized chain
|
|
255
|
+
* as every other mutation. Idempotent: a second call keeps the first timestamp.
|
|
256
|
+
* Throws only if the mandate is unknown.
|
|
257
|
+
*/
|
|
258
|
+
markRegisterFailed(mandateId, now = new Date()) {
|
|
259
|
+
return this.run(async () => {
|
|
260
|
+
const file = await this.load();
|
|
261
|
+
const record = file.mandates.find((m) => m.mandateId === mandateId);
|
|
262
|
+
if (!record)
|
|
263
|
+
throw new Error(`no such mandate ${mandateId}`);
|
|
264
|
+
if (!record.registerFailedAt) {
|
|
265
|
+
record.registerFailedAt = now.toISOString();
|
|
266
|
+
await this.save(file);
|
|
267
|
+
}
|
|
268
|
+
return record;
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Retire a locally cached mandate after the authenticated account API proves
|
|
273
|
+
* it was revoked. This is idempotent and monotonic: an owner revocation can
|
|
274
|
+
* never be undone by a later stale/local read.
|
|
275
|
+
*/
|
|
276
|
+
markServerRevoked(mandateId, revokedAt) {
|
|
277
|
+
return this.run(async () => {
|
|
278
|
+
const parsed = new Date(revokedAt);
|
|
279
|
+
if (Number.isNaN(parsed.getTime()))
|
|
280
|
+
throw new Error('server revocation timestamp is invalid');
|
|
281
|
+
const file = await this.load();
|
|
282
|
+
const record = file.mandates.find((m) => m.mandateId === mandateId);
|
|
283
|
+
if (!record)
|
|
284
|
+
throw new Error(`no such mandate ${mandateId}`);
|
|
285
|
+
if (!record.serverRevokedAt) {
|
|
286
|
+
record.serverRevokedAt = parsed.toISOString();
|
|
287
|
+
await this.save(file);
|
|
288
|
+
}
|
|
289
|
+
return record;
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* ONE SPENDING LIMIT: adopt the ceiling the SERVER actually approved.
|
|
294
|
+
*
|
|
295
|
+
* The requested ceiling is only a request. At register, auth clamps it to the
|
|
296
|
+
* owner's live card-grant cap (`min(requested, grant daily limit)`) and writes
|
|
297
|
+
* that. The local record used to keep the requested figure, so a runtime whose
|
|
298
|
+
* request exceeded the grant reported — and selected against — a budget the
|
|
299
|
+
* owner never approved. The draw still failed closed at auth's verdict, so it
|
|
300
|
+
* was never over-spend; it was the runtime lying about its own headroom and
|
|
301
|
+
* then hitting a decline it could not explain.
|
|
302
|
+
*
|
|
303
|
+
* LOWERS ONLY. A value at or above the current ceiling is ignored, not
|
|
304
|
+
* written: the server clamps downward, so a higher number means an unexpected
|
|
305
|
+
* response, and honouring it would let a client-observed value hand a runtime
|
|
306
|
+
* headroom no human approved. Cap authority stays server-side either way —
|
|
307
|
+
* this only stops the local copy from overstating it.
|
|
308
|
+
*
|
|
309
|
+
* Atomic and idempotent on the same serialized chain as every other mutation.
|
|
310
|
+
* Throws only if the mandate is unknown.
|
|
311
|
+
*/
|
|
312
|
+
applyApprovedCeiling(mandateId, approvedCeilingMinor) {
|
|
313
|
+
return this.run(async () => {
|
|
314
|
+
assertPositiveInteger(approvedCeilingMinor, 'approved mandate ceiling');
|
|
315
|
+
const file = await this.load();
|
|
316
|
+
const record = file.mandates.find((m) => m.mandateId === mandateId);
|
|
317
|
+
if (!record)
|
|
318
|
+
throw new Error(`no such mandate ${mandateId}`);
|
|
319
|
+
if (approvedCeilingMinor >= record.ceilingMinor)
|
|
320
|
+
return record;
|
|
321
|
+
record.ceilingMinor = approvedCeilingMinor;
|
|
322
|
+
await this.save(file);
|
|
323
|
+
return record;
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Atomically reserve headroom for a draw. Fail-closed: refuses when the
|
|
328
|
+
* mandate is unknown, expired, or the amount exceeds remaining headroom. The
|
|
329
|
+
* reservation counts against availability immediately, closing the window in
|
|
330
|
+
* which two concurrent draws both see the same remaining balance.
|
|
331
|
+
*/
|
|
332
|
+
reserve(mandateId, amountMinor, now = new Date()) {
|
|
333
|
+
return this.run(async () => {
|
|
334
|
+
assertPositiveInteger(amountMinor, 'draw amount');
|
|
335
|
+
// Sweep with the draw's clock so a crash-stranded reservation cannot block
|
|
336
|
+
// a legitimate draw; the save() below persists the pruned state.
|
|
337
|
+
const file = await this.load(now.getTime());
|
|
338
|
+
const record = file.mandates.find((m) => m.mandateId === mandateId);
|
|
339
|
+
if (!record)
|
|
340
|
+
throw new Error(`no such mandate ${mandateId}`);
|
|
341
|
+
if (isExpired(record, now)) {
|
|
342
|
+
throw new Error(`mandate ${mandateId} expired at ${record.expiresAt}`);
|
|
343
|
+
}
|
|
344
|
+
if (amountMinor > remainingMinor(record)) {
|
|
345
|
+
throw new Error(`draw ${amountMinor} exceeds remaining budget ${remainingMinor(record)} (minor units)`);
|
|
346
|
+
}
|
|
347
|
+
if (!hasDrawCountHeadroom(record)) {
|
|
348
|
+
throw new Error(`mandate ${mandateId} reached its approved purchase-count limit`);
|
|
349
|
+
}
|
|
350
|
+
const reservationId = `rsv_${randomBytes(9).toString('base64url')}`;
|
|
351
|
+
record.reservations.push({ reservationId, amountMinor, reservedAt: now.toISOString() });
|
|
352
|
+
await this.save(file);
|
|
353
|
+
return reservationId;
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
/** Commit a reservation to permanent spend and record the payable draw. */
|
|
357
|
+
commit(mandateId, reservationId, meta, now = new Date()) {
|
|
358
|
+
return this.run(async () => {
|
|
359
|
+
const file = await this.load();
|
|
360
|
+
const record = file.mandates.find((m) => m.mandateId === mandateId);
|
|
361
|
+
if (!record)
|
|
362
|
+
throw new Error(`no such mandate ${mandateId}`);
|
|
363
|
+
const idx = record.reservations.findIndex((r) => r.reservationId === reservationId);
|
|
364
|
+
if (idx === -1) {
|
|
365
|
+
throw new Error(`reservation ${reservationId} is not open (already committed or released)`);
|
|
366
|
+
}
|
|
367
|
+
const [reservation] = record.reservations.splice(idx, 1);
|
|
368
|
+
record.spentMinor += reservation.amountMinor;
|
|
369
|
+
record.draws.push({
|
|
370
|
+
drawId: `drw_${randomBytes(9).toString('base64url')}`,
|
|
371
|
+
reservationId,
|
|
372
|
+
amountMinor: reservation.amountMinor,
|
|
373
|
+
intentId: meta.intentId,
|
|
374
|
+
status: 'committed',
|
|
375
|
+
at: now.toISOString(),
|
|
376
|
+
});
|
|
377
|
+
await this.save(file);
|
|
378
|
+
return record;
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
/** Release a reservation back to availability (draw failed / not payable). */
|
|
382
|
+
release(mandateId, reservationId, now = new Date()) {
|
|
383
|
+
return this.run(async () => {
|
|
384
|
+
const file = await this.load();
|
|
385
|
+
const record = file.mandates.find((m) => m.mandateId === mandateId);
|
|
386
|
+
if (!record)
|
|
387
|
+
throw new Error(`no such mandate ${mandateId}`);
|
|
388
|
+
const idx = record.reservations.findIndex((r) => r.reservationId === reservationId);
|
|
389
|
+
if (idx === -1) {
|
|
390
|
+
// Idempotent by refusal: a committed/released reservation cannot be
|
|
391
|
+
// released again, but a redundant release must not corrupt state.
|
|
392
|
+
return record;
|
|
393
|
+
}
|
|
394
|
+
const [reservation] = record.reservations.splice(idx, 1);
|
|
395
|
+
record.draws.push({
|
|
396
|
+
drawId: `drw_${randomBytes(9).toString('base64url')}`,
|
|
397
|
+
reservationId,
|
|
398
|
+
amountMinor: reservation.amountMinor,
|
|
399
|
+
intentId: record.mandateId,
|
|
400
|
+
status: 'released',
|
|
401
|
+
at: now.toISOString(),
|
|
402
|
+
});
|
|
403
|
+
await this.save(file);
|
|
404
|
+
return record;
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
export function defaultLedgerPath() {
|
|
409
|
+
return (process.env.VISA_CARD_MANDATE_LEDGER_FILE ?? join(homedir(), '.visa-mcp', 'card-mandates.json'));
|
|
410
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Page } from 'playwright-core';
|
|
2
|
-
export type OutcomeStatus = 'confirmed' | 'declined' | 'action-required' | 'processing' | 'unknown';
|
|
2
|
+
export type OutcomeStatus = 'confirmed' | 'declined' | 'action-required' | 'verification-required' | 'processing' | 'unknown';
|
|
3
3
|
export type OutcomeClassification = {
|
|
4
4
|
status: OutcomeStatus;
|
|
5
5
|
/** The named pattern that decided the status, e.g. "body:card-declined". */
|
|
@@ -8,7 +8,7 @@ export type OutcomeClassification = {
|
|
|
8
8
|
/** Pure classification of one page state (case-insensitive on all inputs). */
|
|
9
9
|
export declare function classifyOutcomePage(url: string, bodyText: string, frameUrls?: readonly string[]): OutcomeClassification;
|
|
10
10
|
export type ObservedOutcome = {
|
|
11
|
-
status: 'confirmed' | 'declined' | 'action-required' | 'unknown';
|
|
11
|
+
status: 'confirmed' | 'declined' | 'action-required' | 'verification-required' | 'unknown';
|
|
12
12
|
signal: string | null;
|
|
13
13
|
/** Last non-final classification when the deadline expired ('processing' | 'unknown'). */
|
|
14
14
|
lastSeen: OutcomeStatus;
|
|
@@ -65,11 +65,34 @@ const ACTION_REQUIRED_URL = [
|
|
|
65
65
|
// credential) but its copy also says "Enter the code sent to …", which would
|
|
66
66
|
// otherwise match body:code-sent and misreport it as 3DS. Its own copy is
|
|
67
67
|
// distinctive: "to use your saved information" / "Logging in as <email>".
|
|
68
|
-
|
|
68
|
+
// The Stripe Link login modal. Checked BEFORE every other body pattern
|
|
69
|
+
// (including the email-OTP split below): completing it pays with an old saved
|
|
70
|
+
// card, not the minted credential, so it must stay action-required (human) and
|
|
71
|
+
// must never be mistaken for an agent-resolvable email code. See #5879.
|
|
72
|
+
const LINK_WALLET_BODY = [
|
|
69
73
|
{
|
|
70
74
|
name: 'body:link-wallet',
|
|
71
75
|
re: /use your saved information|logging in as .{1,60}?\. your device will be remembered/,
|
|
72
76
|
},
|
|
77
|
+
];
|
|
78
|
+
// Agent-RESOLVABLE email OTP: a code the MERCHANT emailed to the agent's own
|
|
79
|
+
// inbox, which wallet_mail_await_otp can retrieve. Kept deliberately narrow —
|
|
80
|
+
// it requires an EMAIL indicator (email / inbox / @) so an SMS "code sent to
|
|
81
|
+
// your phone" or an issuer 3DS challenge (both un-retrievable by the agent)
|
|
82
|
+
// stay action-required and fall to a human. This is the ONLY status the OTP
|
|
83
|
+
// subroutine will try to auto-complete.
|
|
84
|
+
const VERIFICATION_REQUIRED_BODY = [
|
|
85
|
+
// "a code was sent / e-mailed to your email / inbox" (code-first order).
|
|
86
|
+
{
|
|
87
|
+
name: 'body:email-code-sent',
|
|
88
|
+
re: /(?:code|passcode).{0,40}(?:sent|e-?mailed).{0,40}(?:e-?mail|inbox|@)/,
|
|
89
|
+
},
|
|
90
|
+
// "we e-mailed you a … code" (email-verb-first order).
|
|
91
|
+
{ name: 'body:email-code-sent', re: /e-?mailed\b.{0,40}(?:code|passcode)/ },
|
|
92
|
+
// "check your email / inbox for a … code".
|
|
93
|
+
{ name: 'body:check-email-code', re: /check your (?:e-?mail|inbox).{0,40}(?:code|verif)/ },
|
|
94
|
+
];
|
|
95
|
+
const ACTION_REQUIRED_BODY = [
|
|
73
96
|
{ name: 'body:3d-secure', re: /3-?d secure/ },
|
|
74
97
|
{ name: 'body:verify-identity', re: /verify your identity/ },
|
|
75
98
|
{ name: 'body:one-time-code', re: /enter (?:the )?(?:one[- ]?time|verification|security) code/ },
|
|
@@ -122,6 +145,15 @@ export function classifyOutcomePage(url, bodyText, frameUrls = []) {
|
|
|
122
145
|
if (frame)
|
|
123
146
|
return { status: 'action-required', signal: frame };
|
|
124
147
|
}
|
|
148
|
+
// Stripe Link modal first — it must never fall through to the email-OTP split.
|
|
149
|
+
const linkWallet = match(LINK_WALLET_BODY, b);
|
|
150
|
+
if (linkWallet)
|
|
151
|
+
return { status: 'action-required', signal: linkWallet };
|
|
152
|
+
// Agent-resolvable email OTP: its own verdict, so the executor can retrieve
|
|
153
|
+
// the code rather than stopping for a human.
|
|
154
|
+
const emailVerify = match(VERIFICATION_REQUIRED_BODY, b);
|
|
155
|
+
if (emailVerify)
|
|
156
|
+
return { status: 'verification-required', signal: emailVerify };
|
|
125
157
|
const challengeUrl = match(ACTION_REQUIRED_URL, u);
|
|
126
158
|
if (challengeUrl)
|
|
127
159
|
return { status: 'action-required', signal: challengeUrl };
|
|
@@ -167,6 +199,9 @@ export async function observeOutcome(page, opts = {}) {
|
|
|
167
199
|
// continues until the post-challenge confirmed/declined signal appears.
|
|
168
200
|
if (seen.status === 'confirmed' ||
|
|
169
201
|
seen.status === 'declined' ||
|
|
202
|
+
// Email OTP won't self-resolve either — return it so the executor's
|
|
203
|
+
// single-use OTP subroutine can retrieve the code (or a human is asked).
|
|
204
|
+
seen.status === 'verification-required' ||
|
|
170
205
|
(seen.status === 'action-required' && !opts.holdThroughChallenge)) {
|
|
171
206
|
return {
|
|
172
207
|
status: seen.status,
|
|
@@ -8,3 +8,12 @@
|
|
|
8
8
|
export declare function assertOwnerOnlyFile(path: string, label: string, maxBytes?: number): Promise<void>;
|
|
9
9
|
/** The same guard, then parse — contents are read only after the guard passes. */
|
|
10
10
|
export declare function readOwnerOnlyJson<T>(path: string, label: string, maxBytes?: number): Promise<T>;
|
|
11
|
+
/**
|
|
12
|
+
* Atomically write an owner-only (chmod 600) JSON artifact: serialize to a
|
|
13
|
+
* sibling temp file created 0600, then rename over the target so a reader never
|
|
14
|
+
* observes a half-written ledger (and a crash mid-write leaves the prior file
|
|
15
|
+
* intact). The parent directory is created if absent (matching ~/.visa-mcp).
|
|
16
|
+
* Used by the card-mandate ledger — the same owner-only posture as
|
|
17
|
+
* agent-credential.json / contact.json.
|
|
18
|
+
*/
|
|
19
|
+
export declare function writeOwnerOnlyJson(path: string, value: unknown): Promise<void>;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { chmod, lstat, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
2
4
|
/**
|
|
3
5
|
* lstat-only guard for operator-supplied secret-bearing files: must be a
|
|
4
6
|
* regular file (never a symlink), owner-only (chmod 600), and size-bounded.
|
|
@@ -20,3 +22,20 @@ export async function readOwnerOnlyJson(path, label, maxBytes = 16 * 1024) {
|
|
|
20
22
|
await assertOwnerOnlyFile(path, label, maxBytes);
|
|
21
23
|
return JSON.parse(await readFile(path, 'utf8'));
|
|
22
24
|
}
|
|
25
|
+
/**
|
|
26
|
+
* Atomically write an owner-only (chmod 600) JSON artifact: serialize to a
|
|
27
|
+
* sibling temp file created 0600, then rename over the target so a reader never
|
|
28
|
+
* observes a half-written ledger (and a crash mid-write leaves the prior file
|
|
29
|
+
* intact). The parent directory is created if absent (matching ~/.visa-mcp).
|
|
30
|
+
* Used by the card-mandate ledger — the same owner-only posture as
|
|
31
|
+
* agent-credential.json / contact.json.
|
|
32
|
+
*/
|
|
33
|
+
export async function writeOwnerOnlyJson(path, value) {
|
|
34
|
+
await mkdir(dirname(path), { recursive: true });
|
|
35
|
+
const tmp = `${path}.tmp-${randomBytes(6).toString('hex')}`;
|
|
36
|
+
await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
37
|
+
// writeFile's mode only applies on create; chmod defensively in case the temp
|
|
38
|
+
// name somehow pre-existed with looser bits.
|
|
39
|
+
await chmod(tmp, 0o600);
|
|
40
|
+
await rename(tmp, path);
|
|
41
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
/**
|
|
4
|
+
* Where this device's checkout receipts live. Owned by its own module so the
|
|
5
|
+
* writer (cli-engine.ts) and the reader (confirmed-merchants.ts) can never
|
|
6
|
+
* drift onto two paths.
|
|
7
|
+
*/
|
|
8
|
+
export const RECEIPT_DIR = join(homedir(), '.visa-mcp', 'checkout-receipts');
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { EvidenceStep } from './evidence.js';
|
|
2
2
|
import type { CheckoutMode, CheckoutOutcome, CheckoutResult, CredentialLifecycle, CredentialTiming } from './executor.js';
|
|
3
3
|
import type { VicConfirmationReport } from './vic-confirmation.js';
|
|
4
|
-
|
|
4
|
+
/** Published v1 artifact shape. Retained so patch releases remain readable/typable. */
|
|
5
|
+
export type CheckoutReceiptV1 = {
|
|
5
6
|
schema: 'checkout-agent-receipt/v1';
|
|
6
7
|
recordedAt: string;
|
|
7
8
|
mode: CheckoutMode;
|
|
@@ -32,6 +33,55 @@ export type CheckoutReceipt = {
|
|
|
32
33
|
snapshotSummary: string | null;
|
|
33
34
|
};
|
|
34
35
|
};
|
|
36
|
+
export type CheckoutReceiptV2 = {
|
|
37
|
+
schema: 'checkout-agent-receipt/v2';
|
|
38
|
+
recordedAt: string;
|
|
39
|
+
/** Correlates terminal pre-review observations that have no reviewId yet. */
|
|
40
|
+
observationId?: string;
|
|
41
|
+
/** Explicitly distinguishes pre-submit review observations from payment attempts. */
|
|
42
|
+
phase?: 'review';
|
|
43
|
+
merchant: {
|
|
44
|
+
name: string;
|
|
45
|
+
host: string;
|
|
46
|
+
checkoutUrl: string | null;
|
|
47
|
+
};
|
|
48
|
+
transaction: {
|
|
49
|
+
amount: string;
|
|
50
|
+
amountMinor: number;
|
|
51
|
+
currency: string;
|
|
52
|
+
};
|
|
53
|
+
outcome: CheckoutOutcome;
|
|
54
|
+
agent: {
|
|
55
|
+
name: string;
|
|
56
|
+
} | null;
|
|
57
|
+
rail: {
|
|
58
|
+
type: 'card';
|
|
59
|
+
cardLast4: string | null;
|
|
60
|
+
};
|
|
61
|
+
network: {
|
|
62
|
+
confirmation: 'APPROVED' | 'DECLINED' | null;
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* Capability evidence for unsuccessful checkout surfaces. Optional so
|
|
66
|
+
* previously published v2 receipt producers remain source-compatible.
|
|
67
|
+
*/
|
|
68
|
+
capability?: {
|
|
69
|
+
failureCode: string | null;
|
|
70
|
+
detectedRoles: string[];
|
|
71
|
+
requiresAdapter: string[];
|
|
72
|
+
};
|
|
73
|
+
/** Local reviewed-attempt identifier. Keeps filenames stable across schema versions. */
|
|
74
|
+
receiptId: string | null;
|
|
75
|
+
/** Merchant confirmation reference only; never substituted with an internal review id. */
|
|
76
|
+
reference: string | null;
|
|
77
|
+
recovery: {
|
|
78
|
+
required: boolean;
|
|
79
|
+
retrySafe: boolean;
|
|
80
|
+
action: string;
|
|
81
|
+
actions: string[];
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
export type CheckoutReceipt = CheckoutReceiptV1 | CheckoutReceiptV2;
|
|
35
85
|
export type ReceiptWriteReport = {
|
|
36
86
|
written: true;
|
|
37
87
|
path: string;
|
|
@@ -43,9 +93,11 @@ export type ReceiptWriteReport = {
|
|
|
43
93
|
export declare function buildReceipt(input: {
|
|
44
94
|
mode: CheckoutMode;
|
|
45
95
|
reviewId: string | null;
|
|
96
|
+
observationId?: string;
|
|
46
97
|
merchant: {
|
|
47
98
|
name: string;
|
|
48
99
|
host: string;
|
|
100
|
+
url?: string;
|
|
49
101
|
};
|
|
50
102
|
transaction: {
|
|
51
103
|
amount: string;
|
|
@@ -54,9 +106,11 @@ export declare function buildReceipt(input: {
|
|
|
54
106
|
};
|
|
55
107
|
result: CheckoutResult;
|
|
56
108
|
vicConfirmation: VicConfirmationReport | null;
|
|
109
|
+
agentName?: string;
|
|
110
|
+
cardLast4?: string;
|
|
57
111
|
/** Injectable for tests; defaults to now. */
|
|
58
112
|
recordedAt?: Date;
|
|
59
|
-
}):
|
|
113
|
+
}): CheckoutReceiptV2;
|
|
60
114
|
/**
|
|
61
115
|
* Defense-in-depth scrub before anything touches disk: any standalone
|
|
62
116
|
* 12–19-digit run that passes Luhn is replaced — contiguous OR separated by
|