@visa/cli 4.1.0-rc.25 → 4.1.0-rc.26

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 (40) hide show
  1. package/README.md +132 -242
  2. package/dist/checkout-engine/cli-engine.d.ts +142 -0
  3. package/dist/checkout-engine/cli-engine.js +377 -35
  4. package/dist/checkout-engine/detect.d.ts +1 -1
  5. package/dist/checkout-engine/detect.js +20 -0
  6. package/dist/checkout-engine/evidence.d.ts +3 -0
  7. package/dist/checkout-engine/evidence.js +51 -6
  8. package/dist/checkout-engine/executor.d.ts +3 -1
  9. package/dist/checkout-engine/executor.js +75 -2
  10. package/dist/checkout-engine/hosted-approval.d.ts +64 -7
  11. package/dist/checkout-engine/hosted-approval.js +194 -54
  12. package/dist/checkout-engine/index.d.ts +4 -1
  13. package/dist/checkout-engine/index.js +3 -0
  14. package/dist/checkout-engine/instrument.d.ts +1 -0
  15. package/dist/checkout-engine/instrument.js +4 -0
  16. package/dist/checkout-engine/live-fill-approval.d.ts +0 -9
  17. package/dist/checkout-engine/live-fill-approval.js +0 -17
  18. package/dist/checkout-engine/mandate/card-mandate.d.ts +117 -0
  19. package/dist/checkout-engine/mandate/card-mandate.js +221 -0
  20. package/dist/checkout-engine/mandate/mandate-ledger.d.ts +135 -0
  21. package/dist/checkout-engine/mandate/mandate-ledger.js +318 -0
  22. package/dist/checkout-engine/outcome.d.ts +2 -2
  23. package/dist/checkout-engine/outcome.js +36 -1
  24. package/dist/checkout-engine/owner-only-file.d.ts +9 -0
  25. package/dist/checkout-engine/owner-only-file.js +20 -1
  26. package/dist/checkout-engine/run-live-fill.js +151 -101
  27. package/dist/checkout-engine/types.d.ts +13 -0
  28. package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +34 -1
  29. package/dist/checkout-engine/vgs-gateway/server-mint-client.js +35 -7
  30. package/dist/checkout-engine/vgs-live-instrument.d.ts +27 -0
  31. package/dist/checkout-engine/vgs-live-instrument.js +37 -0
  32. package/dist/cli.js +268 -385
  33. package/dist/mcp-server/index.js +251 -161
  34. package/dist/skills/pair-visa-agent/RUNTIMES.md +1 -1
  35. package/dist/skills/pair-visa-agent/SKILL.md +89 -47
  36. package/install.ps1 +3 -41
  37. package/install.sh +3 -35
  38. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  39. package/package.json +5 -4
  40. package/server.json +3 -3
@@ -0,0 +1,318 @@
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 plus the scoped mint token (owner-only) — never PAN, DPAN,
15
+ // CVC, or 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
+ const STALE_RESERVATION_MS = 5 * 60 * 1000;
40
+ // Mandates expired longer ago than this are pruned on the next create(). Generous
41
+ // (a week) so a recently-expired mandate is still visible in `mandate list`, but
42
+ // bounded so a long-lived heavy user cannot grow the owner-only ledger file into
43
+ // its size cap — which would otherwise brick EVERY ledger op (create/reserve/
44
+ // findCovering/commit/release all load the file first).
45
+ const EXPIRED_PRUNE_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
46
+ function reservedTotal(record) {
47
+ return record.reservations.reduce((sum, r) => sum + r.amountMinor, 0);
48
+ }
49
+ /**
50
+ * Drop reservations older than STALE_RESERVATION_MS across every mandate — the
51
+ * debris of a crash between reserve and commit/release. Mutates in place and
52
+ * returns true if anything was swept (so the caller can decide to persist).
53
+ * A reservation with an unparseable `reservedAt` is treated as stale.
54
+ */
55
+ function sweepStaleReservations(file, nowMs) {
56
+ let swept = false;
57
+ for (const m of file.mandates) {
58
+ const kept = m.reservations.filter((r) => {
59
+ const reservedMs = Date.parse(r.reservedAt);
60
+ const stale = !Number.isFinite(reservedMs) || nowMs - reservedMs > STALE_RESERVATION_MS;
61
+ if (stale)
62
+ swept = true;
63
+ return !stale;
64
+ });
65
+ if (kept.length !== m.reservations.length)
66
+ m.reservations = kept;
67
+ }
68
+ return swept;
69
+ }
70
+ /** Available headroom = ceiling - committed - reserved. Integer minor units. */
71
+ export function remainingMinor(record) {
72
+ return record.ceilingMinor - record.spentMinor - reservedTotal(record);
73
+ }
74
+ function isExpired(record, now) {
75
+ const end = Date.parse(record.expiresAt);
76
+ return !Number.isFinite(end) || end <= now.getTime();
77
+ }
78
+ function assertPositiveInteger(value, label) {
79
+ if (!Number.isSafeInteger(value) || value <= 0) {
80
+ throw new Error(`${label} must be a positive integer (minor units)`);
81
+ }
82
+ }
83
+ /**
84
+ * The persisted card-mandate ledger. All mutating operations are serialized on
85
+ * an in-process promise chain so two concurrent draws cannot both observe the
86
+ * same remaining balance (the read-modify-write is atomic within the process).
87
+ */
88
+ export class MandateLedger {
89
+ path;
90
+ chain = Promise.resolve();
91
+ constructor(path = defaultLedgerPath()) {
92
+ this.path = path;
93
+ }
94
+ /** Serialize a read-modify-write so concurrent draws can't race the file. */
95
+ run(fn) {
96
+ const next = this.chain.then(fn, fn);
97
+ // Keep the chain alive even if this op rejects; swallow only the chain copy.
98
+ this.chain = next.then(() => undefined, () => undefined);
99
+ return next;
100
+ }
101
+ // `nowMs` is the caller's clock for the stale-reservation sweep. The sweep
102
+ // deliberately runs only on the headroom-DECIDING loads — reserve() and
103
+ // findCovering() — which are the paths that must not be blocked by
104
+ // crash-stranded reservation debris. commit(), release(), and markUnhonored()
105
+ // pass NO clock on purpose: sweeping while finalizing a reservation could drop
106
+ // the very reservation being committed/released. Pure snapshot reads (get) and
107
+ // create() are likewise clock-independent.
108
+ async load(nowMs) {
109
+ try {
110
+ const doc = await readOwnerOnlyJson(this.path, 'card mandate ledger', LEDGER_MAX_BYTES);
111
+ if (!doc || !Array.isArray(doc.mandates)) {
112
+ return { version: CARD_MANDATE_LEDGER_VERSION, mandates: [] };
113
+ }
114
+ // Self-heal: prune reservations stranded by a crash before commit/release
115
+ // so `remaining` reflects reality. In-memory here; a mutating caller then
116
+ // persists the pruned state via save().
117
+ if (nowMs !== undefined)
118
+ sweepStaleReservations(doc, nowMs);
119
+ return doc;
120
+ }
121
+ catch (err) {
122
+ // A missing ledger is the normal first-run state.
123
+ if (err.code === 'ENOENT') {
124
+ return { version: CARD_MANDATE_LEDGER_VERSION, mandates: [] };
125
+ }
126
+ throw err;
127
+ }
128
+ }
129
+ async save(file) {
130
+ await writeOwnerOnlyJson(this.path, file);
131
+ }
132
+ /** Append a freshly-created mandate record. */
133
+ create(record) {
134
+ return this.run(async () => {
135
+ const file = await this.load();
136
+ if (file.mandates.some((m) => m.mandateId === record.mandateId)) {
137
+ throw new Error(`mandate ${record.mandateId} already exists in the ledger`);
138
+ }
139
+ // Bound ledger growth: drop mandates expired beyond the grace window. They
140
+ // are already invisible to `mandate list` and unselectable by findCovering,
141
+ // so nothing references them. A mandate with an unparseable expiry is kept
142
+ // (fail-safe — never prune what we cannot date).
143
+ const pruneBefore = new Date().getTime() - EXPIRED_PRUNE_GRACE_MS;
144
+ file.mandates = file.mandates.filter((m) => {
145
+ const exp = Date.parse(m.expiresAt);
146
+ return !Number.isFinite(exp) || exp >= pruneBefore;
147
+ });
148
+ file.mandates.push(record);
149
+ await this.save(file);
150
+ return record;
151
+ });
152
+ }
153
+ /** Read a single mandate (no lock — a snapshot copy). */
154
+ async get(mandateId) {
155
+ const file = await this.load();
156
+ return file.mandates.find((m) => m.mandateId === mandateId) ?? null;
157
+ }
158
+ /**
159
+ * First ACTIVE mandate (not expired) whose merchant + currency match and whose
160
+ * remaining headroom covers amountMinor. Used by pay_merchant to decide the
161
+ * tap-free draw path vs a fresh per-purchase tap.
162
+ */
163
+ async findCovering(query) {
164
+ const now = query.now ?? new Date();
165
+ const file = await this.load(now.getTime());
166
+ // Multiple mandates can now cover one merchant: a merchant-scoped mandate for
167
+ // this host AND any crossMerchant (budget) mandate both qualify (#6003). A
168
+ // mandate the network refused is skipped via `!m.unhonoredAt` so it can never
169
+ // be re-selected. A register-failed mandate is skipped the same way
170
+ // (`!m.registerFailedAt`): it has no server row, so a delegated draw would 404
171
+ // `no_mandate` — better to fall through to a fresh per-purchase tap.
172
+ // Selection order among covering candidates:
173
+ // 1. Prefer a merchant-SCOPED mandate over a crossMerchant budget one —
174
+ // spend the dedicated grant for this merchant first and keep the broader
175
+ // any-merchant budget for merchants that have no scoped mandate. Draining
176
+ // the budget for a purchase a scoped mandate already covers both wastes
177
+ // the general headroom and can later force a fresh tap at another merchant.
178
+ // 2. Then the MOST headroom, then the latest expiry — never let a near-empty
179
+ // or near-expiry mandate get selected over a fuller, longer-lived sibling
180
+ // and then fail a draw the sibling would have covered.
181
+ const candidates = file.mandates.filter((m) =>
182
+ // A crossMerchant (budget) mandate covers ANY merchant; a merchant-scoped
183
+ // one only its own host. A budget mandate the owner approved for "any
184
+ // merchant" is deliberately not host-restricted.
185
+ (m.crossMerchant || m.merchantHost === query.merchantHost) &&
186
+ m.currencyCode.toUpperCase() === query.currencyCode.toUpperCase() &&
187
+ !m.unhonoredAt &&
188
+ !m.registerFailedAt &&
189
+ !isExpired(m, now) &&
190
+ remainingMinor(m) >= query.amountMinor);
191
+ candidates.sort((a, b) =>
192
+ // A scoped mandate (crossMerchant falsy → 0) sorts before a budget one (1).
193
+ (a.crossMerchant ? 1 : 0) - (b.crossMerchant ? 1 : 0) ||
194
+ remainingMinor(b) - remainingMinor(a) ||
195
+ Date.parse(b.expiresAt) - Date.parse(a.expiresAt));
196
+ return candidates[0] ?? null;
197
+ }
198
+ /**
199
+ * Mark a mandate as unhonored — the network declined a ceiling-scoped draw
200
+ * against it, so it must never be selected again. Atomic, owner-only write on
201
+ * the same serialized chain as every other mutation. Idempotent: a second
202
+ * call keeps the first timestamp. Throws only if the mandate is unknown.
203
+ */
204
+ markUnhonored(mandateId, now = new Date()) {
205
+ return this.run(async () => {
206
+ const file = await this.load();
207
+ const record = file.mandates.find((m) => m.mandateId === mandateId);
208
+ if (!record)
209
+ throw new Error(`no such mandate ${mandateId}`);
210
+ if (!record.unhonoredAt) {
211
+ record.unhonoredAt = now.toISOString();
212
+ await this.save(file);
213
+ }
214
+ return record;
215
+ });
216
+ }
217
+ /**
218
+ * Mark a mandate as register-failed — the delegated-draw register handshake
219
+ * did not create the server row at mandate-start, so it must never be selected
220
+ * for a (delegated) draw. Atomic, owner-only write on the same serialized chain
221
+ * as every other mutation. Idempotent: a second call keeps the first timestamp.
222
+ * Throws only if the mandate is unknown.
223
+ */
224
+ markRegisterFailed(mandateId, now = new Date()) {
225
+ return this.run(async () => {
226
+ const file = await this.load();
227
+ const record = file.mandates.find((m) => m.mandateId === mandateId);
228
+ if (!record)
229
+ throw new Error(`no such mandate ${mandateId}`);
230
+ if (!record.registerFailedAt) {
231
+ record.registerFailedAt = now.toISOString();
232
+ await this.save(file);
233
+ }
234
+ return record;
235
+ });
236
+ }
237
+ /**
238
+ * Atomically reserve headroom for a draw. Fail-closed: refuses when the
239
+ * mandate is unknown, expired, or the amount exceeds remaining headroom. The
240
+ * reservation counts against availability immediately, closing the window in
241
+ * which two concurrent draws both see the same remaining balance.
242
+ */
243
+ reserve(mandateId, amountMinor, now = new Date()) {
244
+ return this.run(async () => {
245
+ assertPositiveInteger(amountMinor, 'draw amount');
246
+ // Sweep with the draw's clock so a crash-stranded reservation cannot block
247
+ // a legitimate draw; the save() below persists the pruned state.
248
+ const file = await this.load(now.getTime());
249
+ const record = file.mandates.find((m) => m.mandateId === mandateId);
250
+ if (!record)
251
+ throw new Error(`no such mandate ${mandateId}`);
252
+ if (isExpired(record, now)) {
253
+ throw new Error(`mandate ${mandateId} expired at ${record.expiresAt}`);
254
+ }
255
+ if (amountMinor > remainingMinor(record)) {
256
+ throw new Error(`draw ${amountMinor} exceeds remaining budget ${remainingMinor(record)} (minor units)`);
257
+ }
258
+ const reservationId = `rsv_${randomBytes(9).toString('base64url')}`;
259
+ record.reservations.push({ reservationId, amountMinor, reservedAt: now.toISOString() });
260
+ await this.save(file);
261
+ return reservationId;
262
+ });
263
+ }
264
+ /** Commit a reservation to permanent spend and record the payable draw. */
265
+ commit(mandateId, reservationId, meta, now = new Date()) {
266
+ return this.run(async () => {
267
+ const file = await this.load();
268
+ const record = file.mandates.find((m) => m.mandateId === mandateId);
269
+ if (!record)
270
+ throw new Error(`no such mandate ${mandateId}`);
271
+ const idx = record.reservations.findIndex((r) => r.reservationId === reservationId);
272
+ if (idx === -1) {
273
+ throw new Error(`reservation ${reservationId} is not open (already committed or released)`);
274
+ }
275
+ const [reservation] = record.reservations.splice(idx, 1);
276
+ record.spentMinor += reservation.amountMinor;
277
+ record.draws.push({
278
+ drawId: `drw_${randomBytes(9).toString('base64url')}`,
279
+ reservationId,
280
+ amountMinor: reservation.amountMinor,
281
+ intentId: meta.intentId,
282
+ status: 'committed',
283
+ at: now.toISOString(),
284
+ });
285
+ await this.save(file);
286
+ return record;
287
+ });
288
+ }
289
+ /** Release a reservation back to availability (draw failed / not payable). */
290
+ release(mandateId, reservationId, now = new Date()) {
291
+ return this.run(async () => {
292
+ const file = await this.load();
293
+ const record = file.mandates.find((m) => m.mandateId === mandateId);
294
+ if (!record)
295
+ throw new Error(`no such mandate ${mandateId}`);
296
+ const idx = record.reservations.findIndex((r) => r.reservationId === reservationId);
297
+ if (idx === -1) {
298
+ // Idempotent by refusal: a committed/released reservation cannot be
299
+ // released again, but a redundant release must not corrupt state.
300
+ return record;
301
+ }
302
+ const [reservation] = record.reservations.splice(idx, 1);
303
+ record.draws.push({
304
+ drawId: `drw_${randomBytes(9).toString('base64url')}`,
305
+ reservationId,
306
+ amountMinor: reservation.amountMinor,
307
+ intentId: record.mandateId,
308
+ status: 'released',
309
+ at: now.toISOString(),
310
+ });
311
+ await this.save(file);
312
+ return record;
313
+ });
314
+ }
315
+ }
316
+ export function defaultLedgerPath() {
317
+ return (process.env.VISA_CARD_MANDATE_LEDGER_FILE ?? join(homedir(), '.visa-mcp', 'card-mandates.json'));
318
+ }
@@ -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
- const ACTION_REQUIRED_BODY = [
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 { lstat, readFile } from 'node:fs/promises';
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
+ }