@visa/cli 4.1.0-rc.6 → 4.1.0-rc.61
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 +168 -235
- package/dist/checkout-engine/adapters/generic.d.ts +23 -0
- package/dist/checkout-engine/adapters/generic.js +216 -0
- package/dist/checkout-engine/adapters/index.d.ts +8 -0
- package/dist/checkout-engine/adapters/index.js +21 -0
- package/dist/checkout-engine/adapters/shopify.d.ts +31 -0
- package/dist/checkout-engine/adapters/shopify.js +423 -0
- package/dist/checkout-engine/adapters/stripe-like.d.ts +10 -0
- package/dist/checkout-engine/adapters/stripe-like.js +21 -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 +46 -0
- package/dist/checkout-engine/browser-launch.js +81 -0
- package/dist/checkout-engine/ceremony.d.ts +64 -0
- package/dist/checkout-engine/ceremony.js +261 -0
- package/dist/checkout-engine/cli-engine.d.ts +200 -0
- package/dist/checkout-engine/cli-engine.js +659 -0
- package/dist/checkout-engine/detect.d.ts +61 -0
- package/dist/checkout-engine/detect.js +398 -0
- package/dist/checkout-engine/evidence.d.ts +25 -0
- package/dist/checkout-engine/evidence.js +104 -0
- package/dist/checkout-engine/executor.d.ts +176 -0
- package/dist/checkout-engine/executor.js +1322 -0
- package/dist/checkout-engine/hosted-approval.d.ts +142 -0
- package/dist/checkout-engine/hosted-approval.js +339 -0
- package/dist/checkout-engine/index.d.ts +6 -0
- package/dist/checkout-engine/index.js +8 -0
- package/dist/checkout-engine/inline-target.d.ts +13 -0
- package/dist/checkout-engine/inline-target.js +37 -0
- package/dist/checkout-engine/instrument.d.ts +61 -0
- package/dist/checkout-engine/instrument.js +87 -0
- package/dist/checkout-engine/live-fill-approval.d.ts +43 -0
- package/dist/checkout-engine/live-fill-approval.js +90 -0
- package/dist/checkout-engine/mandate/card-mandate.d.ts +121 -0
- package/dist/checkout-engine/mandate/card-mandate.js +227 -0
- package/dist/checkout-engine/mandate/mandate-ledger.d.ts +142 -0
- package/dist/checkout-engine/mandate/mandate-ledger.js +335 -0
- package/dist/checkout-engine/mandate.d.ts +25 -0
- package/dist/checkout-engine/mandate.js +100 -0
- package/dist/checkout-engine/outcome.d.ts +30 -0
- package/dist/checkout-engine/outcome.js +225 -0
- package/dist/checkout-engine/owner-only-file.d.ts +19 -0
- package/dist/checkout-engine/owner-only-file.js +41 -0
- package/dist/checkout-engine/package.json +3 -0
- package/dist/checkout-engine/receipt.d.ts +81 -0
- package/dist/checkout-engine/receipt.js +109 -0
- package/dist/checkout-engine/repo-env.d.ts +11 -0
- package/dist/checkout-engine/repo-env.js +23 -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 +44 -0
- package/dist/checkout-engine/types.js +2 -0
- package/dist/checkout-engine/vgs-gateway/fetch-credential.d.mts +74 -0
- package/dist/checkout-engine/vgs-gateway/fetch-credential.mjs +248 -0
- package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +82 -0
- package/dist/checkout-engine/vgs-gateway/server-mint-client.js +180 -0
- package/dist/checkout-engine/vgs-live-instrument.d.ts +170 -0
- package/dist/checkout-engine/vgs-live-instrument.js +293 -0
- package/dist/checkout-engine/vic-confirmation.d.ts +34 -0
- package/dist/checkout-engine/vic-confirmation.js +39 -0
- package/dist/cli.js +391 -427
- package/dist/mcp-server/index.js +312 -163
- package/dist/skills/pair-visa-agent/RUNTIMES.md +92 -0
- package/dist/skills/pair-visa-agent/SKILL.md +315 -0
- package/dist/skills/pair-visa-agent/scripts/setup.mjs +48 -0
- package/install.ps1 +3 -41
- package/install.sh +3 -35
- package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
- package/package.json +11 -7
- package/server.json +3 -3
|
@@ -0,0 +1,659 @@
|
|
|
1
|
+
// createCliCheckoutEngine — the review()/pay() adapter consumed by @visa/cli's
|
|
2
|
+
// pay_merchant tool. It COMPOSES prepareCheckout, runHostedApproval, the
|
|
3
|
+
// server-side mint (serverCreateIntent/serverFetchCryptogram — the credential is
|
|
4
|
+
// minted by the verify-web deployment, not this machine), submitApprovedCheckout,
|
|
5
|
+
// reportVicOutcome, and receipts into a two-call API.
|
|
6
|
+
//
|
|
7
|
+
// A live browser + prepared-checkout session is held in-process between review
|
|
8
|
+
// and pay, keyed by reviewId, so the submitted checkout is the exact one the
|
|
9
|
+
// human approved. Passkey approval uses the hosted /approve page only.
|
|
10
|
+
//
|
|
11
|
+
// Every browser/network primitive is injectable (CliEngineDeps) so the session/
|
|
12
|
+
// timer/store lifecycle is unit-testable without launching Chromium.
|
|
13
|
+
import { homedir } from 'node:os';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
import { readFile } from 'node:fs/promises';
|
|
16
|
+
import { launchCheckoutBrowser } from './browser-launch.js';
|
|
17
|
+
import { prepareCheckout as realPrepareCheckout, submitApprovedCheckout as realSubmitApprovedCheckout, InMemoryPreparedCheckoutStore, } from './executor.js';
|
|
18
|
+
import { runHostedApproval as realRunHostedApproval } from './hosted-approval.js';
|
|
19
|
+
import { VgsAssuranceInstrument, VgsLiveInstrument, decimalToMinor, } from './vgs-live-instrument.js';
|
|
20
|
+
import { serverCreateIntent, serverFetchCryptogram, serverPostConfirmation, } from './vgs-gateway/server-mint-client.js';
|
|
21
|
+
import { createCardMandate, DEFAULT_MANDATE_MAX_DRAWS, drawFromMandate, MandateDrawDeclinedError, } from './mandate/card-mandate.js';
|
|
22
|
+
import { MandateLedger } from './mandate/mandate-ledger.js';
|
|
23
|
+
import { buildReceipt, writeReceipt as realWriteReceipt } from './receipt.js';
|
|
24
|
+
import { reportVicOutcome as realReportVicOutcome, } from './vic-confirmation.js';
|
|
25
|
+
/**
|
|
26
|
+
* A card-mandate draw failed transiently (retryable) rather than definitively.
|
|
27
|
+
* Gateway 5xx, "server cryptogram not completed / try again", and network
|
|
28
|
+
* reset/timeout errors are transient: the mandate stays healthy and must NOT be
|
|
29
|
+
* disabled. Walks the error's cause chain so a wrapped MandateDrawDeclinedError
|
|
30
|
+
* is classified by its underlying gateway error. Exported for tests.
|
|
31
|
+
*/
|
|
32
|
+
export function isTransientDrawFailure(err) {
|
|
33
|
+
const msgs = [];
|
|
34
|
+
let e = err;
|
|
35
|
+
for (let i = 0; i < 5 && e; i++) {
|
|
36
|
+
if (e instanceof Error && typeof e.message === 'string')
|
|
37
|
+
msgs.push(e.message);
|
|
38
|
+
e = e.cause;
|
|
39
|
+
}
|
|
40
|
+
// Transient = a gateway 5xx / 429 in the mint client's "(last: <status>: …)"
|
|
41
|
+
// framing, or an unambiguous network reset/timeout error name. The status is
|
|
42
|
+
// ANCHORED to `(last:` so a bare 3-digit token elsewhere (an amount, a ref id,
|
|
43
|
+
// an attempt count) can never be mistaken for a status code, and so the
|
|
44
|
+
// advisory DRAW_REMEDY wrapper text ("gateway 5xx / try again") cannot
|
|
45
|
+
// self-classify a hard decline as transient. A hard decline (4xx / a
|
|
46
|
+
// card-decline reason) matches nothing here → the mandate is correctly disabled.
|
|
47
|
+
return /\(last:\s*(?:5\d\d|429)\b|\bETIMEDOUT\b|\bECONNRESET\b|\bECONNREFUSED\b|\bEAI_AGAIN\b|socket hang up|tim(?:e|ed)[ -]?out/i.test(msgs.join(' '));
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* A verdict refusal may be wrapped by drawFromMandate after its local
|
|
51
|
+
* reservation is released. Walk the cause chain so the original auth status +
|
|
52
|
+
* reasons still decide whether the mandate is permanently disabled.
|
|
53
|
+
*/
|
|
54
|
+
function classifyCardDrawVerdictFailure(err) {
|
|
55
|
+
const transientReasons = new Set(['challenge_failed', 'challenge_malformed', 'verdict_refused']);
|
|
56
|
+
let current = err;
|
|
57
|
+
for (let i = 0; i < 5 && current; i++) {
|
|
58
|
+
const candidate = current;
|
|
59
|
+
const status = typeof candidate.status === 'number' ? candidate.status : 0;
|
|
60
|
+
const reasons = Array.isArray(candidate.reasons)
|
|
61
|
+
? candidate.reasons.filter((reason) => typeof reason === 'string')
|
|
62
|
+
: [];
|
|
63
|
+
if (status !== 0 || reasons.length > 0) {
|
|
64
|
+
return {
|
|
65
|
+
transient: status === 503 ||
|
|
66
|
+
reasons.length === 0 ||
|
|
67
|
+
reasons.every((reason) => transientReasons.has(reason)),
|
|
68
|
+
reasons,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
current = candidate.cause;
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
const RECEIPT_DIR = join(homedir(), '.visa-mcp', 'checkout-receipts');
|
|
76
|
+
// Must match the prepared-checkout store TTL so a session and its store entry
|
|
77
|
+
// expire together — an abandoned review can't leak the browser + state.
|
|
78
|
+
const PREPARED_TTL_MS = 5 * 60 * 1000;
|
|
79
|
+
const defaultStore = new InMemoryPreparedCheckoutStore({ ttlMs: PREPARED_TTL_MS });
|
|
80
|
+
const defaultSessions = new Map();
|
|
81
|
+
const defaultLedger = new MandateLedger();
|
|
82
|
+
export function createCliCheckoutEngine(deps = {}) {
|
|
83
|
+
const store = deps.store ?? defaultStore;
|
|
84
|
+
const sessions = deps.sessions ?? defaultSessions;
|
|
85
|
+
const ttlMs = deps.ttlMs ?? PREPARED_TTL_MS;
|
|
86
|
+
const launchBrowser = deps.launchBrowser ?? (() => launchCheckoutBrowser());
|
|
87
|
+
const prepareCheckout = deps.prepareCheckout ?? realPrepareCheckout;
|
|
88
|
+
const submitApprovedCheckout = deps.submitApprovedCheckout ?? realSubmitApprovedCheckout;
|
|
89
|
+
const runHostedApproval = deps.runHostedApproval ?? realRunHostedApproval;
|
|
90
|
+
const reportVicOutcome = deps.reportVicOutcome ?? realReportVicOutcome;
|
|
91
|
+
const writeReceipt = deps.writeReceipt ?? realWriteReceipt;
|
|
92
|
+
const ledger = deps.ledger ?? defaultLedger;
|
|
93
|
+
const now = deps.now ?? (() => new Date());
|
|
94
|
+
const fetchMandateCryptogram = deps.serverFetchCryptogram ?? serverFetchCryptogram;
|
|
95
|
+
const postServerConfirmation = deps.serverPostConfirmation ?? serverPostConfirmation;
|
|
96
|
+
const cardDrawVerdict = deps.cardDrawVerdict ?? null;
|
|
97
|
+
const cardMandateRegister = deps.cardMandateRegister ?? null;
|
|
98
|
+
async function closeSession(reviewId) {
|
|
99
|
+
const session = sessions.get(reviewId);
|
|
100
|
+
if (!session)
|
|
101
|
+
return;
|
|
102
|
+
clearTimeout(session.cleanupTimer);
|
|
103
|
+
sessions.delete(reviewId);
|
|
104
|
+
await session.browser.close().catch(() => { });
|
|
105
|
+
}
|
|
106
|
+
function buildTarget(input) {
|
|
107
|
+
return {
|
|
108
|
+
merchantName: input.merchantName ?? new URL(input.url).hostname,
|
|
109
|
+
merchantUrl: input.url,
|
|
110
|
+
merchantCountryCode: input.merchantCountryCode ?? 'US',
|
|
111
|
+
transactionAmount: input.amount,
|
|
112
|
+
transactionCurrencyCode: input.currency,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
// BUDGET step: one passkey approves a CEILING; a VGS intent is minted with
|
|
117
|
+
// that ceiling as its decline threshold and the owner-only ledger records
|
|
118
|
+
// the cumulative budget. No browser checkout is prepared — this is purely
|
|
119
|
+
// the passkey ceremony + intent, so later pay() draws need no fresh tap.
|
|
120
|
+
async startCardMandate(input) {
|
|
121
|
+
const ceilingMinor = decimalToMinor(input.ceiling);
|
|
122
|
+
if (ceilingMinor === null || ceilingMinor <= 0) {
|
|
123
|
+
throw new Error(`invalid mandate ceiling ${JSON.stringify(input.ceiling)}`);
|
|
124
|
+
}
|
|
125
|
+
if (input.currency.toUpperCase() !== 'USD') {
|
|
126
|
+
throw new Error('card spend budgets currently support USD only');
|
|
127
|
+
}
|
|
128
|
+
if (input.perTransaction !== undefined) {
|
|
129
|
+
const perTxMinor = decimalToMinor(input.perTransaction);
|
|
130
|
+
if (perTxMinor === null || perTxMinor <= 0 || perTxMinor > ceilingMinor) {
|
|
131
|
+
throw new Error(`invalid mandate perTransaction ${JSON.stringify(input.perTransaction)} — ` +
|
|
132
|
+
'must be a positive amount at or under the ceiling');
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
// A budget token can bootstrap one VGS intent and its register handshake,
|
|
136
|
+
// but it is never payable draw authority. Refuse before the passkey
|
|
137
|
+
// ceremony unless this runtime can both prove the separately provisioned
|
|
138
|
+
// card capability and register the resulting intent server-side.
|
|
139
|
+
const registerCap = cardMandateRegister?.loadCapability(input.agentRef) ?? null;
|
|
140
|
+
if (!cardMandateRegister || !registerCap) {
|
|
141
|
+
throw new Error('startCardMandate requires separately provisioned card authority in this runtime; ' +
|
|
142
|
+
'identity pairing alone does not grant a card mandate');
|
|
143
|
+
}
|
|
144
|
+
// There is one budget product: eligible retail merchants under the
|
|
145
|
+
// provider's required Retail/5999 network category, with total,
|
|
146
|
+
// per-purchase, count, and time bounds stated on the approval page. The
|
|
147
|
+
// sentinel is provider metadata, never a user-entered merchant route.
|
|
148
|
+
const merchant = {
|
|
149
|
+
name: 'retail spend budget',
|
|
150
|
+
url: 'https://retail-budget.visa/budget',
|
|
151
|
+
countryCode: 'US',
|
|
152
|
+
};
|
|
153
|
+
const credential = JSON.parse(await readFile(input.credentialPath, 'utf8'));
|
|
154
|
+
// The passkey ceremony is scoped to the CEILING + merchant (not one
|
|
155
|
+
// charge) — that scope is the unproven part of the spike.
|
|
156
|
+
const ceilingTarget = {
|
|
157
|
+
merchantName: merchant.name,
|
|
158
|
+
merchantUrl: merchant.url,
|
|
159
|
+
merchantCountryCode: merchant.countryCode,
|
|
160
|
+
transactionAmount: input.ceiling,
|
|
161
|
+
transactionCurrencyCode: input.currency,
|
|
162
|
+
};
|
|
163
|
+
// BUDGET mode: the ceiling target's amount IS the approved ceiling, so the
|
|
164
|
+
// server mints a budget mint token bound to that ceiling — later draws pull
|
|
165
|
+
// sub-ceiling amounts against it tap-free (the single-purchase fresh-tap
|
|
166
|
+
// path below stays non-budget).
|
|
167
|
+
const assurance = await runHostedApproval({
|
|
168
|
+
baseUrl: input.approvalBaseUrl,
|
|
169
|
+
tokenId: credential.tokenId,
|
|
170
|
+
target: ceilingTarget,
|
|
171
|
+
consumerEmail: input.contact.email,
|
|
172
|
+
budget: true,
|
|
173
|
+
agentJkt: registerCap.agentJkt,
|
|
174
|
+
onApprovalUrl: deps.onApprovalUrl,
|
|
175
|
+
maxDraws: DEFAULT_MANDATE_MAX_DRAWS,
|
|
176
|
+
...(input.perTransaction !== undefined ? { perTransaction: input.perTransaction } : {}),
|
|
177
|
+
...(input.intent !== undefined ? { intent: input.intent } : {}),
|
|
178
|
+
});
|
|
179
|
+
const mintToken = assurance.mintToken;
|
|
180
|
+
if (!mintToken) {
|
|
181
|
+
throw new Error('the approval server issued no mint token — server-side minting requires the ' +
|
|
182
|
+
'verify-web deployment to run real/turnkey auth (not the dev stub). Retry once it does.');
|
|
183
|
+
}
|
|
184
|
+
if (!Number.isSafeInteger(assurance.validUntil) ||
|
|
185
|
+
assurance.validUntil <= Math.floor(now().getTime() / 1000)) {
|
|
186
|
+
throw new Error('the approval server issued no valid budget expiry');
|
|
187
|
+
}
|
|
188
|
+
const expiresAt = new Date(assurance.validUntil * 1000).toISOString();
|
|
189
|
+
const facts = await createCardMandate({
|
|
190
|
+
agentJkt: registerCap.agentJkt,
|
|
191
|
+
tokenId: credential.tokenId,
|
|
192
|
+
assuranceData: assurance.assuranceData,
|
|
193
|
+
ceilingMinor,
|
|
194
|
+
merchant,
|
|
195
|
+
currencyCode: input.currency,
|
|
196
|
+
expiresAt,
|
|
197
|
+
maxDraws: DEFAULT_MANDATE_MAX_DRAWS,
|
|
198
|
+
crossMerchant: true,
|
|
199
|
+
}, {
|
|
200
|
+
createIntent: (i) => serverCreateIntent(input.approvalBaseUrl, mintToken, i),
|
|
201
|
+
ledger,
|
|
202
|
+
approvalBaseUrl: input.approvalBaseUrl,
|
|
203
|
+
now,
|
|
204
|
+
});
|
|
205
|
+
// Seed the one server-authoritative cumulative store keyed by the VGS
|
|
206
|
+
// intent ID. A later draw requires its PoP verdict; the budget token never
|
|
207
|
+
// falls back as payable authority.
|
|
208
|
+
let registerFailed = false;
|
|
209
|
+
if (registerCap && cardMandateRegister) {
|
|
210
|
+
const reg = await cardMandateRegister
|
|
211
|
+
.register({
|
|
212
|
+
authBaseUrl: registerCap.authBaseUrl,
|
|
213
|
+
agentKey: registerCap.agentKey,
|
|
214
|
+
mandateId: facts.mandateId,
|
|
215
|
+
mintToken,
|
|
216
|
+
ceiling: input.ceiling,
|
|
217
|
+
currency: input.currency,
|
|
218
|
+
})
|
|
219
|
+
.catch((err) => ({
|
|
220
|
+
ok: false,
|
|
221
|
+
reason: err instanceof Error ? err.message : String(err),
|
|
222
|
+
}));
|
|
223
|
+
if (!reg.ok) {
|
|
224
|
+
registerFailed = true;
|
|
225
|
+
// Register failed: the server `card_mandate_spend` row was never
|
|
226
|
+
// created, so a delegated draw against this mandate would 404
|
|
227
|
+
// `no_mandate`. Mark it register-failed so findCovering() SKIPS it and
|
|
228
|
+
// the owner's next checkout falls through to a fresh per-purchase tap,
|
|
229
|
+
// rather than silently selecting a mandate that can't be drawn. Marking
|
|
230
|
+
// is best-effort too — a failure here must not abort mandate-start.
|
|
231
|
+
const marked = await ledger
|
|
232
|
+
.markRegisterFailed(facts.mandateId, now())
|
|
233
|
+
.then(() => true)
|
|
234
|
+
.catch(() => false);
|
|
235
|
+
process.stderr.write(marked
|
|
236
|
+
? `warning: card-mandate register failed (${reg.reason ?? 'unknown'}) — this mandate ` +
|
|
237
|
+
`will NOT be used for tap-free draws; your next checkout will use a fresh ` +
|
|
238
|
+
`per-purchase passkey tap. Re-run 'mandate start' to try again.\n`
|
|
239
|
+
: // Escalate: the mark write ALSO failed, so the mandate is persisted but
|
|
240
|
+
// NOT disabled — findCovering could still select an undrawable mandate.
|
|
241
|
+
// Tell the owner loudly not to rely on it and how to recover.
|
|
242
|
+
`warning: card-mandate register failed (${reg.reason ?? 'unknown'}) AND the mandate ` +
|
|
243
|
+
`could NOT be disabled locally — do not rely on it. Run 'mandate list' and re-run ` +
|
|
244
|
+
`'mandate start'. mandateId=${facts.mandateId}\n`);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return { ...facts, merchantHost: new URL(merchant.url).hostname, registerFailed };
|
|
248
|
+
},
|
|
249
|
+
async review(input) {
|
|
250
|
+
const amountMinor = decimalToMinor(input.amount);
|
|
251
|
+
if (amountMinor === null)
|
|
252
|
+
throw new Error(`invalid amount ${JSON.stringify(input.amount)}`);
|
|
253
|
+
const host = new URL(input.url).hostname;
|
|
254
|
+
const browser = await launchBrowser();
|
|
255
|
+
try {
|
|
256
|
+
const prep = await prepareCheckout({
|
|
257
|
+
url: input.url,
|
|
258
|
+
mandate: {
|
|
259
|
+
maxAmountMinor: amountMinor,
|
|
260
|
+
currency: input.currency,
|
|
261
|
+
merchantHost: host,
|
|
262
|
+
expiresAt: new Date(Date.now() + 15 * 60 * 1000).toISOString(),
|
|
263
|
+
},
|
|
264
|
+
amountMinor,
|
|
265
|
+
currency: input.currency,
|
|
266
|
+
browser,
|
|
267
|
+
contact: input.contact,
|
|
268
|
+
}, store);
|
|
269
|
+
if (prep.status !== 'ready') {
|
|
270
|
+
await browser.close();
|
|
271
|
+
throw new Error(`review refused: ${prep.result.outcome} — ${prep.result.detail ?? ''}`);
|
|
272
|
+
}
|
|
273
|
+
const r = prep.checkout.review;
|
|
274
|
+
// Expire the companion session on the SAME schedule as the store entry
|
|
275
|
+
// (unref'd so a pending timer never keeps the process alive).
|
|
276
|
+
const cleanupTimer = setTimeout(() => void closeSession(r.id), ttlMs);
|
|
277
|
+
cleanupTimer.unref?.();
|
|
278
|
+
sessions.set(r.id, {
|
|
279
|
+
browser,
|
|
280
|
+
target: buildTarget(input),
|
|
281
|
+
amountMinor,
|
|
282
|
+
currency: input.currency,
|
|
283
|
+
contact: input.contact,
|
|
284
|
+
cleanupTimer,
|
|
285
|
+
});
|
|
286
|
+
return {
|
|
287
|
+
reviewId: r.id,
|
|
288
|
+
merchantHost: r.merchantHost,
|
|
289
|
+
amountMinor: r.amountMinor,
|
|
290
|
+
currency: r.currency,
|
|
291
|
+
submitTargetFingerprint: JSON.stringify(r.submitTargetFingerprint ?? null),
|
|
292
|
+
detectedRoles: [...r.detectedRoles],
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
catch (err) {
|
|
296
|
+
await browser.close().catch(() => { });
|
|
297
|
+
throw err;
|
|
298
|
+
}
|
|
299
|
+
},
|
|
300
|
+
async pay(input) {
|
|
301
|
+
const session = sessions.get(input.reviewId);
|
|
302
|
+
if (!session) {
|
|
303
|
+
return {
|
|
304
|
+
outcome: 'failed',
|
|
305
|
+
confirmationRef: null,
|
|
306
|
+
receiptPath: null,
|
|
307
|
+
detail: `no prepared review ${input.reviewId} — call review first (a review does not survive a restart)`,
|
|
308
|
+
vicConfirmation: null,
|
|
309
|
+
source: null,
|
|
310
|
+
remainingMinor: null,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
// The reviewId selects the prepared browser session, but the pay call also
|
|
314
|
+
// repeats the target facts. Refuse if any repeated fact disagrees so the
|
|
315
|
+
// caller cannot submit one reviewed checkout while labeling the result or
|
|
316
|
+
// telemetry as another. Never echo the full URLs: payment links can carry
|
|
317
|
+
// claimable secrets in their path/query.
|
|
318
|
+
let payUrl;
|
|
319
|
+
let reviewedUrl;
|
|
320
|
+
try {
|
|
321
|
+
payUrl = new URL(input.url).toString();
|
|
322
|
+
reviewedUrl = new URL(session.target.merchantUrl).toString();
|
|
323
|
+
}
|
|
324
|
+
catch {
|
|
325
|
+
await closeSession(input.reviewId);
|
|
326
|
+
return {
|
|
327
|
+
outcome: 'failed',
|
|
328
|
+
confirmationRef: null,
|
|
329
|
+
receiptPath: null,
|
|
330
|
+
detail: 'pay merchant URL is invalid or does not match the reviewed checkout — start a fresh review',
|
|
331
|
+
vicConfirmation: null,
|
|
332
|
+
source: null,
|
|
333
|
+
remainingMinor: null,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
if (payUrl !== reviewedUrl) {
|
|
337
|
+
await closeSession(input.reviewId);
|
|
338
|
+
return {
|
|
339
|
+
outcome: 'failed',
|
|
340
|
+
confirmationRef: null,
|
|
341
|
+
receiptPath: null,
|
|
342
|
+
detail: 'pay merchant URL does not match the reviewed checkout — start a fresh review',
|
|
343
|
+
vicConfirmation: null,
|
|
344
|
+
source: null,
|
|
345
|
+
remainingMinor: null,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
if (input.currency.toUpperCase() !== session.currency.toUpperCase()) {
|
|
349
|
+
await closeSession(input.reviewId);
|
|
350
|
+
return {
|
|
351
|
+
outcome: 'failed',
|
|
352
|
+
confirmationRef: null,
|
|
353
|
+
receiptPath: null,
|
|
354
|
+
detail: `pay currency ${JSON.stringify(input.currency)} does not match the reviewed currency (${session.currency}) — start a fresh review`,
|
|
355
|
+
vicConfirmation: null,
|
|
356
|
+
source: null,
|
|
357
|
+
remainingMinor: null,
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
// Amount-bind the confirmation: the pay-call amount must match the
|
|
361
|
+
// reviewed amount. The reviewId already locks the immutable mandate, but
|
|
362
|
+
// re-checking here makes the confirmation explicitly amount-bound so a
|
|
363
|
+
// caller cannot pay a different figure than the human reviewed.
|
|
364
|
+
const payAmountMinor = decimalToMinor(input.amount);
|
|
365
|
+
if (payAmountMinor !== session.amountMinor) {
|
|
366
|
+
await closeSession(input.reviewId);
|
|
367
|
+
return {
|
|
368
|
+
outcome: 'failed',
|
|
369
|
+
confirmationRef: null,
|
|
370
|
+
receiptPath: null,
|
|
371
|
+
detail: `pay amount ${JSON.stringify(input.amount)} does not match the reviewed amount (${session.amountMinor} minor units) — start a fresh review`,
|
|
372
|
+
vicConfirmation: null,
|
|
373
|
+
source: null,
|
|
374
|
+
remainingMinor: null,
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
// Reject an expired prepared checkout BEFORE running the hosted passkey
|
|
378
|
+
// approval — the store may have expired/closed the entry while the review
|
|
379
|
+
// waited. Peeking here avoids minting a credential we can't submit.
|
|
380
|
+
if (!store.peek(input.reviewId)) {
|
|
381
|
+
await closeSession(input.reviewId);
|
|
382
|
+
return {
|
|
383
|
+
outcome: 'failed',
|
|
384
|
+
confirmationRef: null,
|
|
385
|
+
receiptPath: null,
|
|
386
|
+
detail: `prepared review ${input.reviewId} expired — start a fresh review`,
|
|
387
|
+
vicConfirmation: null,
|
|
388
|
+
source: null,
|
|
389
|
+
remainingMinor: null,
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
clearTimeout(session.cleanupTimer);
|
|
393
|
+
try {
|
|
394
|
+
const credential = JSON.parse(await readFile(input.credentialPath, 'utf8'));
|
|
395
|
+
const host = new URL(session.target.merchantUrl).hostname;
|
|
396
|
+
// Does an ACTIVE card mandate already cover this exact purchase? If so,
|
|
397
|
+
// draw against it TAP-FREE (no hosted passkey). Else fall back to today's
|
|
398
|
+
// 1:1 fresh-tap flow. Mandates no longer persist the bootstrap token:
|
|
399
|
+
// it is consumed by intent creation + register and has no draw power.
|
|
400
|
+
const covering = await ledger.findCovering({
|
|
401
|
+
merchantHost: host,
|
|
402
|
+
currencyCode: session.currency,
|
|
403
|
+
amountMinor: session.amountMinor,
|
|
404
|
+
now: now(),
|
|
405
|
+
});
|
|
406
|
+
let source;
|
|
407
|
+
let confirmBase;
|
|
408
|
+
// Fresh purchases confirm with their one-purchase mint token. Mandate
|
|
409
|
+
// draws set this only after the local reserve succeeds and auth returns
|
|
410
|
+
// the exact per-draw verdict used to mint the credential.
|
|
411
|
+
let confirmationAuthority = null;
|
|
412
|
+
let drawnRemaining = null;
|
|
413
|
+
let instrument;
|
|
414
|
+
if (covering) {
|
|
415
|
+
// --- Tap-free mandate draw ------------------------------------------
|
|
416
|
+
source = 'mandate';
|
|
417
|
+
confirmBase = covering.approvalBaseUrl;
|
|
418
|
+
const mandateId = covering.mandateId;
|
|
419
|
+
// A mandate cryptogram is authorized only by a PoP-signed verdict.
|
|
420
|
+
// The budget mint token is bootstrap-only and cannot bypass the
|
|
421
|
+
// server reserve/commit ledger when local draw authority is absent.
|
|
422
|
+
//
|
|
423
|
+
// #5928 CRITICAL-2: the CLI does NOT settle the reservation. verify-web
|
|
424
|
+
// (which knows whether the cryptogram was payable) commits it on a
|
|
425
|
+
// payable mint and releases it on a decline, server-authoritatively, so
|
|
426
|
+
// the drawer can never release after a payable mint to dodge the ceiling.
|
|
427
|
+
const verdictSeam = cardDrawVerdict;
|
|
428
|
+
const capability = verdictSeam?.loadCapability(covering.agentJkt) ?? null;
|
|
429
|
+
if (!capability || !verdictSeam) {
|
|
430
|
+
return {
|
|
431
|
+
outcome: 'failed',
|
|
432
|
+
confirmationRef: null,
|
|
433
|
+
receiptPath: null,
|
|
434
|
+
detail: 'this mandate cannot draw because its delegated card authority is unavailable; ' +
|
|
435
|
+
'restore the runtime binding or use a fresh per-purchase passkey approval',
|
|
436
|
+
vicConfirmation: null,
|
|
437
|
+
source,
|
|
438
|
+
remainingMinor: null,
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
if (covering.agentJkt && capability.agentJkt !== covering.agentJkt) {
|
|
442
|
+
return {
|
|
443
|
+
outcome: 'failed',
|
|
444
|
+
confirmationRef: null,
|
|
445
|
+
receiptPath: null,
|
|
446
|
+
detail: 'this budget belongs to a different request key than the selected card capability; ' +
|
|
447
|
+
'restore that exact runtime key or use a fresh per-purchase approval',
|
|
448
|
+
vicConfirmation: null,
|
|
449
|
+
source,
|
|
450
|
+
remainingMinor: null,
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
// VgsLiveInstrument mints against an EXISTING intent (the mandate) with
|
|
454
|
+
// no fresh assurance — exactly the draw semantics. The fetchCredential
|
|
455
|
+
// seam routes through drawFromMandate so the ledger accounting (reserve
|
|
456
|
+
// -> commit on payable, release on reject) wraps the cryptogram pull.
|
|
457
|
+
const reference = {
|
|
458
|
+
tokenId: covering.tokenId,
|
|
459
|
+
intentId: mandateId,
|
|
460
|
+
merchantName: session.target.merchantName,
|
|
461
|
+
merchantUrl: session.target.merchantUrl,
|
|
462
|
+
merchantCountryCode: session.target.merchantCountryCode,
|
|
463
|
+
transactionAmount: session.target.transactionAmount,
|
|
464
|
+
transactionCurrencyCode: session.currency,
|
|
465
|
+
};
|
|
466
|
+
const fetchCredential = async ({ transaction }) => {
|
|
467
|
+
let draw;
|
|
468
|
+
try {
|
|
469
|
+
draw = await drawFromMandate({
|
|
470
|
+
mandateId,
|
|
471
|
+
amountMinor: session.amountMinor,
|
|
472
|
+
transaction: { ...transaction, transactionCurrencyCode: session.currency },
|
|
473
|
+
}, {
|
|
474
|
+
// Ordering matters: reserve the local ledger FIRST, then ask
|
|
475
|
+
// auth to reserve the server-authoritative budget immediately
|
|
476
|
+
// before the payable mint. A local reserve race/expiry/file
|
|
477
|
+
// failure therefore makes zero auth/verdict calls and cannot
|
|
478
|
+
// strand a server reservation until its sweep.
|
|
479
|
+
fetchCryptogram: async (i) => {
|
|
480
|
+
const { verdict } = await verdictSeam.fetchVerdict({
|
|
481
|
+
authBaseUrl: capability.authBaseUrl,
|
|
482
|
+
agentKey: capability.agentKey,
|
|
483
|
+
mandateId,
|
|
484
|
+
// One draw per review; the reviewId is auth's idempotency key.
|
|
485
|
+
drawId: input.reviewId,
|
|
486
|
+
draw: {
|
|
487
|
+
tokenId: covering.tokenId,
|
|
488
|
+
amount: session.target.transactionAmount,
|
|
489
|
+
currency: session.currency,
|
|
490
|
+
merchantName: session.target.merchantName,
|
|
491
|
+
merchantUrl: session.target.merchantUrl,
|
|
492
|
+
merchantCountryCode: session.target.merchantCountryCode,
|
|
493
|
+
},
|
|
494
|
+
});
|
|
495
|
+
confirmationAuthority = verdict;
|
|
496
|
+
return fetchMandateCryptogram(confirmBase, verdict, i);
|
|
497
|
+
},
|
|
498
|
+
ledger,
|
|
499
|
+
now,
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
catch (err) {
|
|
503
|
+
// Disable the mandate ONLY for a post-reservation NETWORK decline
|
|
504
|
+
// (MandateDrawDeclinedError). That case leaves the mandate
|
|
505
|
+
// active+covering, so a naive retry would re-select it and fail
|
|
506
|
+
// identically — trapping the caller; marking it unhonored makes the
|
|
507
|
+
// next pay_merchant skip it and take a fresh per-purchase tap. We do
|
|
508
|
+
// NOT attempt an unsafe same-call browser fallback mid-submit.
|
|
509
|
+
//
|
|
510
|
+
// A PRE-network failure — reserve() failing closed on a concurrent
|
|
511
|
+
// over-budget race or expiry, or commit() throwing on file I/O —
|
|
512
|
+
// is NOT a network decline: the mandate is HEALTHY, so we must
|
|
513
|
+
// rethrow WITHOUT disabling it (michaelyang1 M1). drawFromMandate
|
|
514
|
+
// has already released any reservation, so the budget is intact.
|
|
515
|
+
// Only a DEFINITIVE (hard) decline disables the mandate. A TRANSIENT
|
|
516
|
+
// failure — a gateway 5xx / "not completed, try again" / network
|
|
517
|
+
// reset/timeout — must NOT permanently kill the budget: the mandate
|
|
518
|
+
// may be perfectly healthy (it can have committed a draw seconds
|
|
519
|
+
// earlier) and the rails may recover on retry. Over-disabling on a
|
|
520
|
+
// transient 502 threw away good budgets and forced a fresh passkey
|
|
521
|
+
// every time.
|
|
522
|
+
// Classify on the underlying gateway CAUSE, not the MandateDrawDeclinedError
|
|
523
|
+
// wrapper — the wrapper's own advisory text mentions "try again"/"network",
|
|
524
|
+
// which would otherwise self-classify every decline as transient.
|
|
525
|
+
if (err instanceof MandateDrawDeclinedError) {
|
|
526
|
+
const verdictFailure = classifyCardDrawVerdictFailure(err);
|
|
527
|
+
if (verdictFailure) {
|
|
528
|
+
if (!verdictFailure.transient) {
|
|
529
|
+
await ledger.markUnhonored(mandateId, now()).catch(() => { });
|
|
530
|
+
}
|
|
531
|
+
throw new Error(verdictFailure.transient
|
|
532
|
+
? `the card-mandate draw could not be authorized right now (${verdictFailure.reasons.join(', ') || 'temporary error'}) — retry shortly`
|
|
533
|
+
: `this card mandate can no longer be drawn (${verdictFailure.reasons.join(', ') || 'refused'}); it has been disabled — retry the checkout to use a fresh per-purchase passkey tap`, { cause: err });
|
|
534
|
+
}
|
|
535
|
+
if (!isTransientDrawFailure(err.cause ?? err)) {
|
|
536
|
+
await ledger.markUnhonored(mandateId, now());
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
// #5928 CRITICAL-2: the server-side reservation is released by
|
|
540
|
+
// verify-web (it saw the mint fail), not here — the CLI never settles.
|
|
541
|
+
throw err;
|
|
542
|
+
}
|
|
543
|
+
drawnRemaining = draw.remainingMinor;
|
|
544
|
+
// #5928 CRITICAL-2: the reservation is committed by verify-web on the
|
|
545
|
+
// payable mint (server-authoritative); the CLI does not settle.
|
|
546
|
+
return draw.payment;
|
|
547
|
+
};
|
|
548
|
+
instrument = new VgsLiveInstrument(reference, session.contact.fullName ?? '', fetchCredential);
|
|
549
|
+
}
|
|
550
|
+
else {
|
|
551
|
+
// --- 1:1 fresh-tap flow (unchanged) ---------------------------------
|
|
552
|
+
source = 'fresh-tap';
|
|
553
|
+
const assurance = await runHostedApproval({
|
|
554
|
+
baseUrl: input.approvalBaseUrl,
|
|
555
|
+
tokenId: credential.tokenId,
|
|
556
|
+
target: session.target,
|
|
557
|
+
consumerEmail: session.contact.email,
|
|
558
|
+
onApprovalUrl: input.onApprovalUrl ?? deps.onApprovalUrl,
|
|
559
|
+
});
|
|
560
|
+
// Server-side mint (Phase 1): the approval claim releases a scoped mint
|
|
561
|
+
// token; the credential is minted by the verify-web deployment (which
|
|
562
|
+
// holds the VGS secret), never on this machine. No token means the
|
|
563
|
+
// deployment ran the dev-auth stub — refuse loudly rather than reach for
|
|
564
|
+
// a client-held secret (there is none anymore).
|
|
565
|
+
const mintToken = assurance.mintToken;
|
|
566
|
+
if (!mintToken) {
|
|
567
|
+
return {
|
|
568
|
+
outcome: 'failed',
|
|
569
|
+
confirmationRef: null,
|
|
570
|
+
receiptPath: null,
|
|
571
|
+
detail: 'the approval server issued no mint token — server-side minting requires the ' +
|
|
572
|
+
'verify-web deployment to run real/turnkey auth (not the dev stub). Retry once it does.',
|
|
573
|
+
vicConfirmation: null,
|
|
574
|
+
source: 'fresh-tap',
|
|
575
|
+
remainingMinor: null,
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
confirmBase = input.approvalBaseUrl;
|
|
579
|
+
confirmationAuthority = mintToken;
|
|
580
|
+
instrument = new VgsAssuranceInstrument(credential, assurance, session.target, session.contact.fullName ?? '', async (mintInput) => {
|
|
581
|
+
const { intentId, status } = await serverCreateIntent(confirmBase, mintToken, mintInput);
|
|
582
|
+
try {
|
|
583
|
+
const payment = await serverFetchCryptogram(confirmBase, mintToken, {
|
|
584
|
+
tokenId: mintInput.tokenId,
|
|
585
|
+
intentId,
|
|
586
|
+
transaction: mintInput.transaction,
|
|
587
|
+
});
|
|
588
|
+
return { payment, intentId };
|
|
589
|
+
}
|
|
590
|
+
catch (err) {
|
|
591
|
+
throw new Error(`${err.message} (intent status at creation: ${status ?? 'unknown'})`);
|
|
592
|
+
}
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
const mode = input.submit ? 'submit' : 'dry-run';
|
|
596
|
+
const result = await submitApprovedCheckout(input.reviewId, {
|
|
597
|
+
approval: { approved: true, reviewId: input.reviewId },
|
|
598
|
+
instrument,
|
|
599
|
+
contact: session.contact,
|
|
600
|
+
mode,
|
|
601
|
+
...(deps.resolveEmailOtp ? { resolveEmailOtp: deps.resolveEmailOtp } : {}),
|
|
602
|
+
}, store);
|
|
603
|
+
// Report the observed submit outcome to VIC for the consumed intent
|
|
604
|
+
// (APPROVED/DECLINED). Only definitive submit answers post. Mirrors
|
|
605
|
+
// run-live-fill.ts.
|
|
606
|
+
let vicConfirmation = null;
|
|
607
|
+
if (mode === 'submit') {
|
|
608
|
+
vicConfirmation = await reportVicOutcome({
|
|
609
|
+
target: instrument.confirmationTarget(),
|
|
610
|
+
outcome: result.outcome,
|
|
611
|
+
transaction: {
|
|
612
|
+
transactionAmount: session.target.transactionAmount,
|
|
613
|
+
transactionCurrencyCode: session.currency,
|
|
614
|
+
},
|
|
615
|
+
post: (confInput) => {
|
|
616
|
+
if (!confirmationAuthority) {
|
|
617
|
+
throw new Error('confirmation authority missing for the consumed VIC intent');
|
|
618
|
+
}
|
|
619
|
+
return postServerConfirmation(confirmBase, confirmationAuthority, confInput);
|
|
620
|
+
},
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
let receiptPath = null;
|
|
624
|
+
const report = await writeReceipt(RECEIPT_DIR, buildReceipt({
|
|
625
|
+
mode,
|
|
626
|
+
reviewId: input.reviewId,
|
|
627
|
+
// Derive BOTH name and host from the reviewed session target (not
|
|
628
|
+
// pay()'s input.url), so the receipt always reflects the checkout
|
|
629
|
+
// the human actually reviewed + that reviewId bound for submit.
|
|
630
|
+
merchant: {
|
|
631
|
+
name: session.target.merchantName,
|
|
632
|
+
host: new URL(session.target.merchantUrl).hostname,
|
|
633
|
+
},
|
|
634
|
+
transaction: {
|
|
635
|
+
amount: session.target.transactionAmount,
|
|
636
|
+
amountMinor: session.amountMinor,
|
|
637
|
+
currency: session.currency,
|
|
638
|
+
},
|
|
639
|
+
result,
|
|
640
|
+
vicConfirmation,
|
|
641
|
+
}));
|
|
642
|
+
if (report.written)
|
|
643
|
+
receiptPath = report.path;
|
|
644
|
+
return {
|
|
645
|
+
outcome: result.outcome,
|
|
646
|
+
confirmationRef: result.confirmationRef ?? null,
|
|
647
|
+
receiptPath,
|
|
648
|
+
detail: result.detail ?? null,
|
|
649
|
+
vicConfirmation,
|
|
650
|
+
source,
|
|
651
|
+
remainingMinor: drawnRemaining,
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
finally {
|
|
655
|
+
await closeSession(input.reviewId);
|
|
656
|
+
}
|
|
657
|
+
},
|
|
658
|
+
};
|
|
659
|
+
}
|