@visa/cli 4.1.0-rc.2 → 4.1.0-rc.200
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 +200 -226
- package/dist/checkout-engine/adapters/generic.d.ts +88 -0
- package/dist/checkout-engine/adapters/generic.js +526 -0
- package/dist/checkout-engine/adapters/index.d.ts +10 -0
- package/dist/checkout-engine/adapters/index.js +24 -0
- package/dist/checkout-engine/adapters/shopify.d.ts +55 -0
- package/dist/checkout-engine/adapters/shopify.js +514 -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 +315 -0
- package/dist/checkout-engine/cli-engine.js +996 -0
- 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 +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 +215 -0
- package/dist/checkout-engine/executor.js +1520 -0
- package/dist/checkout-engine/hosted-approval.d.ts +195 -0
- package/dist/checkout-engine/hosted-approval.js +498 -0
- package/dist/checkout-engine/index.d.ts +9 -0
- package/dist/checkout-engine/index.js +11 -0
- package/dist/checkout-engine/instrument.d.ts +61 -0
- package/dist/checkout-engine/instrument.js +87 -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 +37 -0
- package/dist/checkout-engine/live-fill-approval.js +76 -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 +178 -0
- package/dist/checkout-engine/mandate/mandate-ledger.js +395 -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-dir.d.ts +6 -0
- package/dist/checkout-engine/receipt-dir.js +8 -0
- package/dist/checkout-engine/receipt.d.ts +121 -0
- package/dist/checkout-engine/receipt.js +138 -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 +52 -0
- package/dist/checkout-engine/types.js +2 -0
- package/dist/checkout-engine/unresolved-charges.d.ts +34 -0
- package/dist/checkout-engine/unresolved-charges.js +125 -0
- package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +101 -0
- package/dist/checkout-engine/vgs-gateway/server-mint-client.js +218 -0
- package/dist/checkout-engine/vgs-live-instrument.d.ts +144 -0
- package/dist/checkout-engine/vgs-live-instrument.js +229 -0
- package/dist/checkout-engine/vic-confirmation.d.ts +52 -0
- package/dist/checkout-engine/vic-confirmation.js +45 -0
- package/dist/checkout-engine/web-bot-auth.d.ts +92 -0
- package/dist/checkout-engine/web-bot-auth.js +159 -0
- package/dist/cli.js +721 -445
- package/dist/mcp-apps/ucp-checkout.html +280 -0
- package/dist/mcp-server/index.js +573 -175
- package/dist/skills/pair-visa-agent/RUNTIMES.md +93 -0
- package/dist/skills/pair-visa-agent/SKILL.md +557 -0
- package/dist/skills/pair-visa-agent/scripts/setup.mjs +48 -0
- package/dist/subway-direct.mjs +1 -0
- package/install.ps1 +5 -43
- package/install.sh +5 -37
- package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
- package/package.json +33 -25
- package/server.json +4 -4
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Instrument abstraction: the checkout engine is deliberately blind to WHERE
|
|
2
|
+
// card credentials come from. Official test PANs, callback-backed agentic
|
|
3
|
+
// credentials, and owner-only VIC harness files are enabled; VGS aliases stay
|
|
4
|
+
// stubbed until a reveal seam exists. The executor remains unchanged across
|
|
5
|
+
// every instrument.
|
|
6
|
+
// Official public test PANs only. These are the sanctioned Visa/network test
|
|
7
|
+
// numbers used against local fixtures; they carry no funds and pass Luhn.
|
|
8
|
+
export const OFFICIAL_TEST_PANS = {
|
|
9
|
+
visa: '4242424242424242',
|
|
10
|
+
visaAlt: '4111111111111111',
|
|
11
|
+
// PAN whose last four are 0002 is treated as a forced decline by the
|
|
12
|
+
// fixture acquirer, for exercising the declined outcome path.
|
|
13
|
+
visaDecline: '4000000000000002',
|
|
14
|
+
// Ending 0069: the fixture acquirer shows a processing interstitial, then
|
|
15
|
+
// JS-redirects to a Shopify-style thank-you URL with no confirmation text —
|
|
16
|
+
// exercises the outcome observer's late, URL-signal confirmation path.
|
|
17
|
+
visaSlowConfirm: '4000000000000069',
|
|
18
|
+
// Ending 0044: the fixture acquirer returns a neutral page with neither a
|
|
19
|
+
// confirmation nor a decline signal — exercises the unknown-outcome deadline.
|
|
20
|
+
visaUnknownOutcome: '4000000000000044',
|
|
21
|
+
// Ending 0010: the fixture acquirer answers with a 3DS-style verification
|
|
22
|
+
// page embedding an ACS challenge iframe that never completes — exercises
|
|
23
|
+
// the observer's action-required (issuer challenge) path.
|
|
24
|
+
visaChallenge: '4000000000000010',
|
|
25
|
+
// Ending 0077: the fixture acquirer emails a one-time code to the agent
|
|
26
|
+
// inbox and shows a 'check your email for a code' page with a one-time-code
|
|
27
|
+
// field — exercises the executor's agent-resolvable email-OTP subroutine.
|
|
28
|
+
visaEmailOtp: '4000000000000077',
|
|
29
|
+
};
|
|
30
|
+
function futureExpiry() {
|
|
31
|
+
const now = new Date();
|
|
32
|
+
return { expMonth: 12, expYear: now.getFullYear() + 3 };
|
|
33
|
+
}
|
|
34
|
+
export class TestCardInstrument {
|
|
35
|
+
kind = 'test-card';
|
|
36
|
+
credential;
|
|
37
|
+
constructor(opts = {}) {
|
|
38
|
+
const exp = futureExpiry();
|
|
39
|
+
this.credential = {
|
|
40
|
+
pan: opts.pan ?? OFFICIAL_TEST_PANS.visa,
|
|
41
|
+
expMonth: opts.expMonth ?? exp.expMonth,
|
|
42
|
+
expYear: opts.expYear ?? exp.expYear,
|
|
43
|
+
cvc: opts.cvc ?? '123',
|
|
44
|
+
cardholderName: opts.cardholderName ?? 'Test Agent',
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
async getCredential(_ctx) {
|
|
48
|
+
return this.credential;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const NOT_ENABLED = 'not enabled: pending VGS alias reveal support';
|
|
52
|
+
// Stub. Once VGS enablement lands, this resolves a network token / alias into a
|
|
53
|
+
// fillable credential (a virtual PAN plus its verification value).
|
|
54
|
+
export class VgsAliasInstrument {
|
|
55
|
+
_alias;
|
|
56
|
+
kind = 'vgs-alias';
|
|
57
|
+
constructor(_alias) {
|
|
58
|
+
this._alias = _alias;
|
|
59
|
+
}
|
|
60
|
+
async getCredential(_ctx) {
|
|
61
|
+
throw new Error(`${NOT_ENABLED}. VgsAliasInstrument cannot resolve alias "${this._alias}" ` +
|
|
62
|
+
'to a fillable PAN until VGS exposes the reveal seam for this spike.');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
// A server-side provider mints the transaction-bound credential whose pan
|
|
66
|
+
// carries the DPAN and whose cvc carries the short DAVV. Omitting the provider
|
|
67
|
+
// preserves a clear fail-closed result for callers that have only a token ref.
|
|
68
|
+
export class AgenticTokenInstrument {
|
|
69
|
+
tokenRef;
|
|
70
|
+
mintCredential;
|
|
71
|
+
kind = 'agentic-token';
|
|
72
|
+
used = false;
|
|
73
|
+
constructor(tokenRef, mintCredential) {
|
|
74
|
+
this.tokenRef = tokenRef;
|
|
75
|
+
this.mintCredential = mintCredential;
|
|
76
|
+
}
|
|
77
|
+
async getCredential(ctx) {
|
|
78
|
+
if (!this.mintCredential) {
|
|
79
|
+
throw new Error('not enabled: no agentic credential provider configured. ' +
|
|
80
|
+
`Token ${this.tokenRef} needs a server-side VGS credential provider.`);
|
|
81
|
+
}
|
|
82
|
+
if (this.used)
|
|
83
|
+
throw new Error('agentic credential instrument is single-use');
|
|
84
|
+
this.used = true;
|
|
85
|
+
return this.mintCredential(ctx);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export type MerchantIdentity = {
|
|
2
|
+
/** Human-recognizable merchant name. */
|
|
3
|
+
name: string;
|
|
4
|
+
/** What the merchant is, e.g. "charity (animal rescue)". */
|
|
5
|
+
category: string;
|
|
6
|
+
/** The merchant's own site, when known — not the checkout URL. */
|
|
7
|
+
website?: string;
|
|
8
|
+
};
|
|
9
|
+
/** Checkout URL → who is actually behind it. Confirmed live 2026-07/2026-08. */
|
|
10
|
+
export declare const KNOWN_MERCHANT_IDENTITIES: Readonly<Record<string, MerchantIdentity>>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Curated identities for checkout URLs the registry cannot name on its own.
|
|
2
|
+
//
|
|
3
|
+
// Hosted payment links are anonymous by construction: the page host is the
|
|
4
|
+
// PSP's (donate.stripe.com, buy.stripe.com), the path is an opaque token, and
|
|
5
|
+
// the receipt records nothing else. So a registry row for a completed payment
|
|
6
|
+
// link answers "where can I use my card?" with a string no human recognizes.
|
|
7
|
+
// This map carries the once-per-link human identification, keyed by the exact
|
|
8
|
+
// checkout URL the receipts group on.
|
|
9
|
+
//
|
|
10
|
+
// Curation rule: an entry is added only after a checkout at that URL completed
|
|
11
|
+
// for real (engine outcome 'confirmed' + VIC APPROVED — the same admission rule
|
|
12
|
+
// confirmed-merchants.ts enforces) and the merchant behind the link was
|
|
13
|
+
// identified by a person. The map never creates registry rows; it only names
|
|
14
|
+
// rows the device's own receipts already earned. A URL missing here still
|
|
15
|
+
// lists — it just shows as its host.
|
|
16
|
+
/** Checkout URL → who is actually behind it. Confirmed live 2026-07/2026-08. */
|
|
17
|
+
export const KNOWN_MERCHANT_IDENTITIES = {
|
|
18
|
+
'https://donate.stripe.com/3cscPcaqY20H8ta4gh': {
|
|
19
|
+
name: 'NC Seaside Animal Rescue',
|
|
20
|
+
category: 'charity (animal rescue, NC nonprofit)',
|
|
21
|
+
website: 'https://www.ncseasideanimalrescue.org/make-a-donation',
|
|
22
|
+
},
|
|
23
|
+
'https://donate.stripe.com/14k3ei9TYgwFclq145': {
|
|
24
|
+
name: 'FreeCAD',
|
|
25
|
+
category: 'open-source project donation (CAD software)',
|
|
26
|
+
website: 'https://www.freecad.org',
|
|
27
|
+
},
|
|
28
|
+
'https://buy.stripe.com/dR6eWGaK41MX2YgaEF': {
|
|
29
|
+
name: 'scribepod',
|
|
30
|
+
category: 'indie creator tip jar (AI podcast project)',
|
|
31
|
+
website: 'https://github.com/yacineMTB/scribepod',
|
|
32
|
+
},
|
|
33
|
+
'https://donate.stripe.com/7sIcNj9Gs4WO6d29AA': {
|
|
34
|
+
name: 'n0bleKing GRAFFITI',
|
|
35
|
+
category: 'indie creator tip jar (pixel art and fonts)',
|
|
36
|
+
website: 'https://nobleking-graffiti.itch.io',
|
|
37
|
+
},
|
|
38
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { CheckoutMode, CheckoutOutcome, CheckoutResult } from './executor.js';
|
|
2
|
+
export declare const MODE_ENV_FLAG = "CHECKOUT_AGENT_MODE";
|
|
3
|
+
/**
|
|
4
|
+
* `--mode` values map 1:1 onto CheckoutMode; an absent flag falls back to the
|
|
5
|
+
* CHECKOUT_AGENT_MODE environment default, then to the safe dry-run default.
|
|
6
|
+
*/
|
|
7
|
+
export declare function parseCheckoutMode(value: string | undefined, env?: Record<string, string | undefined>): CheckoutMode;
|
|
8
|
+
/** Distinct phrases per mode so dry-run muscle memory can never authorize a payment. */
|
|
9
|
+
export declare function approvalPhrase(mode: CheckoutMode, reviewId: string): string;
|
|
10
|
+
/** Integer-only minor→display formatting (two-decimal currencies, the same assumption as decimalToMinor). */
|
|
11
|
+
export declare function formatAmountMinor(amountMinor: number, currency: string): string;
|
|
12
|
+
/** The operator question. In submit mode it names the exact charge — amount and merchant. */
|
|
13
|
+
export declare function approvalQuestion(mode: CheckoutMode, review: {
|
|
14
|
+
merchantHost: string;
|
|
15
|
+
amountMinor: number;
|
|
16
|
+
currency: string;
|
|
17
|
+
}, phrase: string): string;
|
|
18
|
+
/** The one outcome each mode may exit 0 with. */
|
|
19
|
+
export declare function isRunSuccess(mode: CheckoutMode, outcome: CheckoutOutcome): boolean;
|
|
20
|
+
/**
|
|
21
|
+
* True when the pay control was actually clicked but the run ended with an
|
|
22
|
+
* UNKNOWN outcome — neither 'confirmed' nor 'declined' (e.g. a slow redirect
|
|
23
|
+
* or confirmation copy the heuristics don't recognize). The charge may still
|
|
24
|
+
* have gone through; the operator must verify with the merchant before any
|
|
25
|
+
* retry, because a blind rerun risks a double charge. A 'declined' outcome is
|
|
26
|
+
* a definitive negative from the merchant, so it does not warn. Neither does
|
|
27
|
+
* 'action-required': a 3-D Secure challenge intercepts BEFORE authorization,
|
|
28
|
+
* so no charge can exist until it is completed — the double-charge warning
|
|
29
|
+
* would misdirect the operator, and the runner prints the challenge-specific
|
|
30
|
+
* notice instead.
|
|
31
|
+
*
|
|
32
|
+
* The executor now NAMES this state in the outcome itself ('unverified'), so
|
|
33
|
+
* the two agree by construction. This predicate stays the broader guard: it
|
|
34
|
+
* also catches a post-click throw or any future outcome that leaves the same
|
|
35
|
+
* question open, and it is what the receipt's reconciliation list reads.
|
|
36
|
+
*/
|
|
37
|
+
export declare function submitClickedWithoutConfirmation(result: CheckoutResult): boolean;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Deliberate-enablement seam for run-live-fill's submit mode. A real submit
|
|
2
|
+
// moves real money, so it requires:
|
|
3
|
+
// 1. the invocation opts in (--mode submit, or the CHECKOUT_AGENT_MODE
|
|
4
|
+
// environment default for operators who always run one mode),
|
|
5
|
+
// 2. the operator types the PAY phrase against the exact review id (and a
|
|
6
|
+
// hosted run additionally requires the passkey tap on the verify site).
|
|
7
|
+
// The PAY phrase differs from dry-run's FILL phrase and names the exact review
|
|
8
|
+
// id, so a muscle-memory rerun of the dry-run procedure cannot drift into
|
|
9
|
+
// charging a card. Fresh checkouts need ZERO persisted config.
|
|
10
|
+
//
|
|
11
|
+
// There was a third requirement — a CHECKOUT_AGENT_ALLOW_SUBMIT=1 environment
|
|
12
|
+
// arm, exempted for interactive TTYs — meant to stop AUTOMATION reaching a live
|
|
13
|
+
// charge. It never ran: nothing in the product ever called `assertSubmitAllowed`.
|
|
14
|
+
// The same flag DID gate `pay_merchant`, where being default-off with no
|
|
15
|
+
// in-product way to set it meant a real install could not complete a purchase at
|
|
16
|
+
// all. Both are gone; the phrase and the mandate caps are the gates.
|
|
17
|
+
export const MODE_ENV_FLAG = 'CHECKOUT_AGENT_MODE';
|
|
18
|
+
/**
|
|
19
|
+
* `--mode` values map 1:1 onto CheckoutMode; an absent flag falls back to the
|
|
20
|
+
* CHECKOUT_AGENT_MODE environment default, then to the safe dry-run default.
|
|
21
|
+
*/
|
|
22
|
+
export function parseCheckoutMode(value, env = process.env) {
|
|
23
|
+
const effective = value ?? env[MODE_ENV_FLAG];
|
|
24
|
+
if (effective === undefined || effective === 'dry-run')
|
|
25
|
+
return 'dry-run';
|
|
26
|
+
if (effective === 'submit')
|
|
27
|
+
return 'submit';
|
|
28
|
+
throw new Error(`--mode (or ${MODE_ENV_FLAG}) must be dry-run or submit (got ${JSON.stringify(effective)})`);
|
|
29
|
+
}
|
|
30
|
+
/** Distinct phrases per mode so dry-run muscle memory can never authorize a payment. */
|
|
31
|
+
export function approvalPhrase(mode, reviewId) {
|
|
32
|
+
return `${mode === 'submit' ? 'PAY' : 'CHECK'} ${reviewId}`;
|
|
33
|
+
}
|
|
34
|
+
/** Integer-only minor→display formatting (two-decimal currencies, the same assumption as decimalToMinor). */
|
|
35
|
+
export function formatAmountMinor(amountMinor, currency) {
|
|
36
|
+
return `${Math.floor(amountMinor / 100)}.${String(amountMinor % 100).padStart(2, '0')} ${currency}`;
|
|
37
|
+
}
|
|
38
|
+
/** The operator question. In submit mode it names the exact charge — amount and merchant. */
|
|
39
|
+
export function approvalQuestion(mode, review, phrase) {
|
|
40
|
+
if (mode === 'submit') {
|
|
41
|
+
return (`Inspect the visible checkout. This WILL charge ` +
|
|
42
|
+
`${formatAmountMinor(review.amountMinor, review.currency)} at ${review.merchantHost}. ` +
|
|
43
|
+
`Type ${JSON.stringify(phrase)} to disclose the credential AND submit the order: `);
|
|
44
|
+
}
|
|
45
|
+
return (`Inspect the visible checkout. Type ${JSON.stringify(phrase)} ` +
|
|
46
|
+
`to validate the reviewed page without minting, filling, or submitting a credential: `);
|
|
47
|
+
}
|
|
48
|
+
/** The one outcome each mode may exit 0 with. */
|
|
49
|
+
export function isRunSuccess(mode, outcome) {
|
|
50
|
+
return outcome === (mode === 'submit' ? 'confirmed' : 'reviewed-dry-run');
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* True when the pay control was actually clicked but the run ended with an
|
|
54
|
+
* UNKNOWN outcome — neither 'confirmed' nor 'declined' (e.g. a slow redirect
|
|
55
|
+
* or confirmation copy the heuristics don't recognize). The charge may still
|
|
56
|
+
* have gone through; the operator must verify with the merchant before any
|
|
57
|
+
* retry, because a blind rerun risks a double charge. A 'declined' outcome is
|
|
58
|
+
* a definitive negative from the merchant, so it does not warn. Neither does
|
|
59
|
+
* 'action-required': a 3-D Secure challenge intercepts BEFORE authorization,
|
|
60
|
+
* so no charge can exist until it is completed — the double-charge warning
|
|
61
|
+
* would misdirect the operator, and the runner prints the challenge-specific
|
|
62
|
+
* notice instead.
|
|
63
|
+
*
|
|
64
|
+
* The executor now NAMES this state in the outcome itself ('unverified'), so
|
|
65
|
+
* the two agree by construction. This predicate stays the broader guard: it
|
|
66
|
+
* also catches a post-click throw or any future outcome that leaves the same
|
|
67
|
+
* question open, and it is what the receipt's reconciliation list reads.
|
|
68
|
+
*/
|
|
69
|
+
export function submitClickedWithoutConfirmation(result) {
|
|
70
|
+
if (result.outcome === 'confirmed' ||
|
|
71
|
+
result.outcome === 'declined' ||
|
|
72
|
+
result.outcome === 'action-required') {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
return result.evidence.getSteps().some((s) => s.type === 'submit' && s.data.clicked === true);
|
|
76
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { type VgsCheckoutTarget, type VgsPaymentCredential } from '../vgs-live-instrument.js';
|
|
2
|
+
import { MandateLedger } from './mandate-ledger.js';
|
|
3
|
+
/**
|
|
4
|
+
* Default number of draws a ceiling intent may fulfil (VGS mandate quantity).
|
|
5
|
+
* This is a purchase-COUNT cap, NOT the exposure bound: VGS enforces the
|
|
6
|
+
* declineThreshold as a CUMULATIVE cap across draws (live-verified 2026-07-23),
|
|
7
|
+
* so the total the network will authorize is the ceiling REGARDLESS of how many
|
|
8
|
+
* draws it is spread across — maxDraws only limits the number of separate
|
|
9
|
+
* purchases, it does not multiply the exposure. Kept SMALL as a sensible default
|
|
10
|
+
* purchase count (the owner-side client ledger also caps cumulative spend at ONE
|
|
11
|
+
* ceiling). This is the single default; callers that don't set maxDraws inherit
|
|
12
|
+
* it (do not re-duplicate it upstream).
|
|
13
|
+
*/
|
|
14
|
+
export declare const DEFAULT_MANDATE_MAX_DRAWS = 3;
|
|
15
|
+
export type CardMandateMerchant = {
|
|
16
|
+
name: string;
|
|
17
|
+
url: string;
|
|
18
|
+
countryCode: string;
|
|
19
|
+
};
|
|
20
|
+
export type CreateCardMandateInput = {
|
|
21
|
+
/** Exact current runtime request key selected before human approval. */
|
|
22
|
+
agentJkt: string;
|
|
23
|
+
tokenId: string;
|
|
24
|
+
assuranceData: unknown;
|
|
25
|
+
ceilingMinor: number;
|
|
26
|
+
merchant: CardMandateMerchant;
|
|
27
|
+
currencyCode: string;
|
|
28
|
+
expiresAt: string;
|
|
29
|
+
/** Max draws the ceiling intent may fulfil; defaults to DEFAULT_MANDATE_MAX_DRAWS. */
|
|
30
|
+
maxDraws?: number;
|
|
31
|
+
/** Cross-host retail budget; network category eligibility still applies. */
|
|
32
|
+
crossMerchant?: boolean;
|
|
33
|
+
};
|
|
34
|
+
export type CreateIntentFn = (input: {
|
|
35
|
+
tokenId: string;
|
|
36
|
+
assuranceData: unknown;
|
|
37
|
+
transaction: VgsCheckoutTarget;
|
|
38
|
+
mandate: {
|
|
39
|
+
declineThresholdAmount: string;
|
|
40
|
+
quantity: number;
|
|
41
|
+
effectiveUntil: string;
|
|
42
|
+
consumerPrompt: string;
|
|
43
|
+
};
|
|
44
|
+
}) => Promise<{
|
|
45
|
+
intentId: string;
|
|
46
|
+
status: string | null;
|
|
47
|
+
}>;
|
|
48
|
+
export type CreateCardMandateDeps = {
|
|
49
|
+
/** Mint the ceiling intent — wire serverCreateIntent(base, mintToken, …). */
|
|
50
|
+
createIntent: CreateIntentFn;
|
|
51
|
+
ledger: MandateLedger;
|
|
52
|
+
/** verify-web origin the intent is minted against (persisted for later draws). */
|
|
53
|
+
approvalBaseUrl: string;
|
|
54
|
+
/** Scoped mint token to persist for tap-free draws. */
|
|
55
|
+
mintToken?: string;
|
|
56
|
+
now?: () => Date;
|
|
57
|
+
};
|
|
58
|
+
export type CardMandateFacts = {
|
|
59
|
+
mandateId: string;
|
|
60
|
+
ceilingMinor: number;
|
|
61
|
+
remainingMinor: number;
|
|
62
|
+
currencyCode: string;
|
|
63
|
+
merchant: CardMandateMerchant;
|
|
64
|
+
expiresAt: string;
|
|
65
|
+
/** Network-enforced maximum purchase count disclosed at approval. */
|
|
66
|
+
maxDraws: number;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Create a card mandate: approve a spend CEILING once (the passkey assurance
|
|
70
|
+
* passed here was scoped to the ceiling + merchant), mint one VGS intent with
|
|
71
|
+
* that ceiling as its decline threshold, and record the cumulative-budget
|
|
72
|
+
* ledger entry. Integer minor units only.
|
|
73
|
+
*/
|
|
74
|
+
export declare function createCardMandate(input: CreateCardMandateInput, deps: CreateCardMandateDeps): Promise<CardMandateFacts>;
|
|
75
|
+
export type FetchCryptogramFn = (input: {
|
|
76
|
+
tokenId: string;
|
|
77
|
+
intentId: string;
|
|
78
|
+
transaction: VgsCheckoutTarget;
|
|
79
|
+
}) => Promise<VgsPaymentCredential>;
|
|
80
|
+
export type DrawFromMandateInput = {
|
|
81
|
+
mandateId: string;
|
|
82
|
+
amountMinor: number;
|
|
83
|
+
/** The exact per-draw checkout target (merchant + amount + currency). */
|
|
84
|
+
transaction: VgsCheckoutTarget;
|
|
85
|
+
};
|
|
86
|
+
export type DrawFromMandateDeps = {
|
|
87
|
+
/** Draw a cryptogram against the mandate intent — wire serverFetchCryptogram. */
|
|
88
|
+
fetchCryptogram: FetchCryptogramFn;
|
|
89
|
+
ledger: MandateLedger;
|
|
90
|
+
/** Override the payable-credential gate (default validateCredential). */
|
|
91
|
+
validate?: (credential: VgsPaymentCredential) => void;
|
|
92
|
+
now?: () => Date;
|
|
93
|
+
};
|
|
94
|
+
export type DrawResult = {
|
|
95
|
+
payment: VgsPaymentCredential;
|
|
96
|
+
intentId: string;
|
|
97
|
+
remainingMinor: number;
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Thrown ONLY for the post-reservation network/validation rejection class — the
|
|
101
|
+
* cryptogram fetch failed or returned a non-payable credential (the DRAW_REMEDY
|
|
102
|
+
* path). This is the sole draw failure that should DISABLE the mandate: it means
|
|
103
|
+
* the acquirer would not honor a ceiling-scoped assurance for a sub-amount draw.
|
|
104
|
+
*
|
|
105
|
+
* Pre-network failures — a fail-closed `reserve()` (concurrent over-budget race
|
|
106
|
+
* or expiry) or a `commit()` file-I/O error — throw a plain Error instead, so
|
|
107
|
+
* the caller (cli-engine) can rethrow them WITHOUT marking a HEALTHY mandate
|
|
108
|
+
* unhonored. Discriminating on this type is what keeps a transient race from
|
|
109
|
+
* permanently disabling a good mandate (michaelyang1 M1).
|
|
110
|
+
*/
|
|
111
|
+
export declare class MandateDrawDeclinedError extends Error {
|
|
112
|
+
readonly cause?: unknown;
|
|
113
|
+
constructor(message: string, cause?: unknown);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Draw a cryptogram against an existing card mandate with NO fresh tap. The
|
|
117
|
+
* reservation is atomic and the budget is decremented ONLY after a payable
|
|
118
|
+
* cryptogram returns; any rejection releases the reservation so remaining is
|
|
119
|
+
* unchanged. Validates merchant + currency + amount against the mandate first.
|
|
120
|
+
*/
|
|
121
|
+
export declare function drawFromMandate(input: DrawFromMandateInput, deps: DrawFromMandateDeps): Promise<DrawResult>;
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// Card mandate (budget) layer — the split the north-star card flow needs:
|
|
2
|
+
//
|
|
3
|
+
// BUDGET = start_card_mandate: approve a CEILING once with the passkey. This
|
|
4
|
+
// mints ONE VGS intent whose decline threshold is the ceiling (not
|
|
5
|
+
// amount+10) and whose quantity permits many draws. The passkey
|
|
6
|
+
// assurance is scoped to the ceiling + merchant, not one charge.
|
|
7
|
+
// DRAW = pay_merchant (tap-free): pull a cryptogram against that intent for
|
|
8
|
+
// an in-budget purchase, WITHOUT a fresh tap, and decrement the
|
|
9
|
+
// cumulative budget in the owner-only ledger.
|
|
10
|
+
//
|
|
11
|
+
// This mirrors x402's start_session -> wallet_pay shape on the card rail.
|
|
12
|
+
//
|
|
13
|
+
// PROVEN (live probe 2026-07-23): VGS honors a ceiling-scoped assurance across
|
|
14
|
+
// multiple sub-amount cryptogram draws against one intent, AND enforces the
|
|
15
|
+
// decline threshold as a CUMULATIVE cap — draws summing to the ceiling are
|
|
16
|
+
// payable, the next draw over the cumulative ceiling is declined. So the total
|
|
17
|
+
// the network authorizes is the ceiling, not maxDraws × ceiling. drawFromMandate
|
|
18
|
+
// stays FAIL-CLEAN as defense-in-depth: the budget is decremented only after a
|
|
19
|
+
// payable cryptogram returns; a network rejection leaves the budget untouched.
|
|
20
|
+
// The caller (cli-engine) then marks the mandate unhonored so the NEXT
|
|
21
|
+
// pay_merchant skips it and surfaces the no-covering refusal (#7348) — the same call is
|
|
22
|
+
// not retried in-flight. Never fail-open.
|
|
23
|
+
import { decimalToMinor, minorToDecimal, validateCredential, } from '../vgs-live-instrument.js';
|
|
24
|
+
import { CARD_MANDATE_LEDGER_VERSION, remainingMinor, } from './mandate-ledger.js';
|
|
25
|
+
/**
|
|
26
|
+
* Default number of draws a ceiling intent may fulfil (VGS mandate quantity).
|
|
27
|
+
* This is a purchase-COUNT cap, NOT the exposure bound: VGS enforces the
|
|
28
|
+
* declineThreshold as a CUMULATIVE cap across draws (live-verified 2026-07-23),
|
|
29
|
+
* so the total the network will authorize is the ceiling REGARDLESS of how many
|
|
30
|
+
* draws it is spread across — maxDraws only limits the number of separate
|
|
31
|
+
* purchases, it does not multiply the exposure. Kept SMALL as a sensible default
|
|
32
|
+
* purchase count (the owner-side client ledger also caps cumulative spend at ONE
|
|
33
|
+
* ceiling). This is the single default; callers that don't set maxDraws inherit
|
|
34
|
+
* it (do not re-duplicate it upstream).
|
|
35
|
+
*/
|
|
36
|
+
export const DEFAULT_MANDATE_MAX_DRAWS = 3;
|
|
37
|
+
function assertPositiveInteger(value, label) {
|
|
38
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
39
|
+
throw new Error(`${label} must be a positive integer (minor units)`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function merchantHost(url) {
|
|
43
|
+
try {
|
|
44
|
+
return new URL(url).hostname;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
throw new Error(`mandate merchant URL is invalid: ${url}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Create a card mandate: approve a spend CEILING once (the passkey assurance
|
|
52
|
+
* passed here was scoped to the ceiling + merchant), mint one VGS intent with
|
|
53
|
+
* that ceiling as its decline threshold, and record the cumulative-budget
|
|
54
|
+
* ledger entry. Integer minor units only.
|
|
55
|
+
*/
|
|
56
|
+
export async function createCardMandate(input, deps) {
|
|
57
|
+
assertPositiveInteger(input.ceilingMinor, 'mandate ceiling');
|
|
58
|
+
const currencyCode = String(input.currencyCode).toUpperCase();
|
|
59
|
+
if (!/^[A-Z]{3}$/.test(currencyCode)) {
|
|
60
|
+
throw new Error('mandate currency must be a 3-letter ISO 4217 code');
|
|
61
|
+
}
|
|
62
|
+
if (!input.tokenId?.trim())
|
|
63
|
+
throw new Error('mandate requires a tokenId');
|
|
64
|
+
if (!/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(input.agentJkt)) {
|
|
65
|
+
throw new Error('mandate requires a canonical agent request-key JKT');
|
|
66
|
+
}
|
|
67
|
+
const now = (deps.now ?? (() => new Date()))();
|
|
68
|
+
const expiryMs = Date.parse(input.expiresAt);
|
|
69
|
+
if (!Number.isFinite(expiryMs))
|
|
70
|
+
throw new Error('mandate expiresAt must be ISO 8601');
|
|
71
|
+
if (expiryMs <= now.getTime())
|
|
72
|
+
throw new Error('mandate expiresAt is already in the past');
|
|
73
|
+
const host = merchantHost(input.merchant.url);
|
|
74
|
+
const maxDraws = input.maxDraws ?? DEFAULT_MANDATE_MAX_DRAWS;
|
|
75
|
+
if (!Number.isSafeInteger(maxDraws) || maxDraws < 1) {
|
|
76
|
+
throw new Error('mandate maxDraws must be a positive integer');
|
|
77
|
+
}
|
|
78
|
+
// Pass the currency so a non-2-decimal currency is REFUSED here rather than
|
|
79
|
+
// silently rendered with a wrong wire amount (minorToDecimal assumes /100).
|
|
80
|
+
const ceilingDecimal = minorToDecimal(input.ceilingMinor, currencyCode);
|
|
81
|
+
// The passkey prompt must state the REAL grant. VGS enforces the
|
|
82
|
+
// declineThreshold as a CUMULATIVE cap across draws (live-verified 2026-07-23),
|
|
83
|
+
// so the total this single approval can authorize is the CEILING — not
|
|
84
|
+
// maxDraws × ceiling. maxDraws only caps how many separate purchases the intent
|
|
85
|
+
// may fulfil. The prompt therefore names the ceiling as the total and maxDraws
|
|
86
|
+
// as the purchase-count limit (H1: consent must match the true grant).
|
|
87
|
+
// The intent transaction is scoped to the CEILING itself: the decline
|
|
88
|
+
// threshold IS the ceiling (not the historical ceil(amount)+10), and quantity
|
|
89
|
+
// permits multiple draws.
|
|
90
|
+
const ceilingTarget = {
|
|
91
|
+
merchantName: input.merchant.name,
|
|
92
|
+
merchantUrl: input.merchant.url,
|
|
93
|
+
merchantCountryCode: input.merchant.countryCode.toUpperCase(),
|
|
94
|
+
transactionAmount: ceilingDecimal,
|
|
95
|
+
transactionCurrencyCode: currencyCode,
|
|
96
|
+
};
|
|
97
|
+
const { intentId } = await deps.createIntent({
|
|
98
|
+
tokenId: input.tokenId,
|
|
99
|
+
assuranceData: input.assuranceData,
|
|
100
|
+
transaction: ceilingTarget,
|
|
101
|
+
mandate: {
|
|
102
|
+
declineThresholdAmount: ceilingDecimal,
|
|
103
|
+
quantity: maxDraws,
|
|
104
|
+
effectiveUntil: new Date(expiryMs).toISOString(),
|
|
105
|
+
consumerPrompt: `Approve up to ${ceilingDecimal} ${currencyCode} total (across up to ` +
|
|
106
|
+
`${maxDraws} purchase${maxDraws === 1 ? '' : 's'}) at ${input.merchant.name} ` +
|
|
107
|
+
`for my Visa agent`,
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
if (!intentId?.trim())
|
|
111
|
+
throw new Error('mandate intent creation returned no intentId');
|
|
112
|
+
const record = {
|
|
113
|
+
version: CARD_MANDATE_LEDGER_VERSION,
|
|
114
|
+
mandateId: intentId,
|
|
115
|
+
agentJkt: input.agentJkt,
|
|
116
|
+
tokenId: input.tokenId,
|
|
117
|
+
ceilingMinor: input.ceilingMinor,
|
|
118
|
+
spentMinor: 0,
|
|
119
|
+
reservations: [],
|
|
120
|
+
currencyCode,
|
|
121
|
+
merchantName: input.merchant.name,
|
|
122
|
+
merchantUrl: input.merchant.url,
|
|
123
|
+
merchantHost: host,
|
|
124
|
+
merchantCountryCode: input.merchant.countryCode.toUpperCase(),
|
|
125
|
+
approvalBaseUrl: deps.approvalBaseUrl,
|
|
126
|
+
...(deps.mintToken ? { mintToken: deps.mintToken } : {}),
|
|
127
|
+
expiresAt: new Date(expiryMs).toISOString(),
|
|
128
|
+
maxDraws,
|
|
129
|
+
createdAt: now.toISOString(),
|
|
130
|
+
draws: [],
|
|
131
|
+
...(input.crossMerchant ? { crossMerchant: true } : {}),
|
|
132
|
+
};
|
|
133
|
+
await deps.ledger.create(record, now);
|
|
134
|
+
return {
|
|
135
|
+
mandateId: record.mandateId,
|
|
136
|
+
ceilingMinor: record.ceilingMinor,
|
|
137
|
+
remainingMinor: remainingMinor(record),
|
|
138
|
+
currencyCode,
|
|
139
|
+
merchant: input.merchant,
|
|
140
|
+
expiresAt: record.expiresAt,
|
|
141
|
+
maxDraws,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
const DRAW_REMEDY = 'the card-mandate draw did not complete — a ceiling-scoped assurance may not be honored ' +
|
|
145
|
+
'for this sub-amount draw. The budget is untouched. If this was a transient network error ' +
|
|
146
|
+
'(gateway 5xx / try again), retry — the mandate stays active; a persistent decline disables ' +
|
|
147
|
+
'the mandate; a v4 card grant then requires a new mandate before another checkout';
|
|
148
|
+
/**
|
|
149
|
+
* Thrown ONLY for the post-reservation network/validation rejection class — the
|
|
150
|
+
* cryptogram fetch failed or returned a non-payable credential (the DRAW_REMEDY
|
|
151
|
+
* path). This is the sole draw failure that should DISABLE the mandate: it means
|
|
152
|
+
* the acquirer would not honor a ceiling-scoped assurance for a sub-amount draw.
|
|
153
|
+
*
|
|
154
|
+
* Pre-network failures — a fail-closed `reserve()` (concurrent over-budget race
|
|
155
|
+
* or expiry) or a `commit()` file-I/O error — throw a plain Error instead, so
|
|
156
|
+
* the caller (cli-engine) can rethrow them WITHOUT marking a HEALTHY mandate
|
|
157
|
+
* unhonored. Discriminating on this type is what keeps a transient race from
|
|
158
|
+
* permanently disabling a good mandate (michaelyang1 M1).
|
|
159
|
+
*/
|
|
160
|
+
export class MandateDrawDeclinedError extends Error {
|
|
161
|
+
cause;
|
|
162
|
+
constructor(message, cause) {
|
|
163
|
+
super(message);
|
|
164
|
+
this.name = 'MandateDrawDeclinedError';
|
|
165
|
+
this.cause = cause;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Draw a cryptogram against an existing card mandate with NO fresh tap. The
|
|
170
|
+
* reservation is atomic and the budget is decremented ONLY after a payable
|
|
171
|
+
* cryptogram returns; any rejection releases the reservation so remaining is
|
|
172
|
+
* unchanged. Validates merchant + currency + amount against the mandate first.
|
|
173
|
+
*/
|
|
174
|
+
export async function drawFromMandate(input, deps) {
|
|
175
|
+
assertPositiveInteger(input.amountMinor, 'draw amount');
|
|
176
|
+
const validate = deps.validate ?? validateCredential;
|
|
177
|
+
const now = (deps.now ?? (() => new Date()))();
|
|
178
|
+
const record = await deps.ledger.get(input.mandateId);
|
|
179
|
+
if (!record)
|
|
180
|
+
throw new Error(`no such mandate ${input.mandateId}`);
|
|
181
|
+
// The wire amount and the accounting amount MUST agree — a mismatch would
|
|
182
|
+
// draw one figure while reserving another. Fail before any reservation.
|
|
183
|
+
const wireMinor = decimalToMinor(input.transaction.transactionAmount);
|
|
184
|
+
if (wireMinor === null || wireMinor !== input.amountMinor) {
|
|
185
|
+
throw new Error(`draw amount ${input.amountMinor} disagrees with transaction amount ` +
|
|
186
|
+
`${JSON.stringify(input.transaction.transactionAmount)} (minor units)`);
|
|
187
|
+
}
|
|
188
|
+
// Currency must always match; merchant must match UNLESS this is a budget
|
|
189
|
+
// (crossMerchant) mandate the owner approved for eligible retail merchants. The network
|
|
190
|
+
// honors a ceiling-scoped cryptogram cross-merchant, so a budget mandate is
|
|
191
|
+
// deliberately not host-restricted — the ceiling + per-transaction limit still
|
|
192
|
+
// bound it.
|
|
193
|
+
const targetHost = merchantHost(input.transaction.merchantUrl);
|
|
194
|
+
if (!record.crossMerchant && targetHost !== record.merchantHost) {
|
|
195
|
+
throw new Error(`draw merchant ${targetHost} does not match mandate merchant ${record.merchantHost}`);
|
|
196
|
+
}
|
|
197
|
+
if (String(input.transaction.transactionCurrencyCode).toUpperCase() !==
|
|
198
|
+
record.currencyCode.toUpperCase()) {
|
|
199
|
+
throw new Error(`draw currency ${input.transaction.transactionCurrencyCode} does not match mandate ` +
|
|
200
|
+
`currency ${record.currencyCode}`);
|
|
201
|
+
}
|
|
202
|
+
// Atomic reserve — throws (fail-closed) if expired or over remaining budget.
|
|
203
|
+
const reservationId = await deps.ledger.reserve(input.mandateId, input.amountMinor, now);
|
|
204
|
+
let payment;
|
|
205
|
+
try {
|
|
206
|
+
payment = await deps.fetchCryptogram({
|
|
207
|
+
tokenId: record.tokenId,
|
|
208
|
+
intentId: record.mandateId,
|
|
209
|
+
transaction: input.transaction,
|
|
210
|
+
});
|
|
211
|
+
// A 2xx that is not actually a payable DAVV must NOT decrement the budget.
|
|
212
|
+
validate(payment);
|
|
213
|
+
}
|
|
214
|
+
catch (err) {
|
|
215
|
+
await deps.ledger.release(input.mandateId, reservationId, now);
|
|
216
|
+
// Typed so the caller disables the mandate ONLY for this post-reservation
|
|
217
|
+
// network/validation decline — never for a pre-network reserve()/commit()
|
|
218
|
+
// failure, which throws a plain Error above/below this try.
|
|
219
|
+
throw new MandateDrawDeclinedError(`${DRAW_REMEDY}: ${err.message}`, err);
|
|
220
|
+
}
|
|
221
|
+
const committed = await deps.ledger.commit(input.mandateId, reservationId, { intentId: record.mandateId }, now);
|
|
222
|
+
return {
|
|
223
|
+
payment,
|
|
224
|
+
intentId: record.mandateId,
|
|
225
|
+
remainingMinor: remainingMinor(committed),
|
|
226
|
+
};
|
|
227
|
+
}
|