@visa/cli 4.1.0-rc.124 → 4.1.0-rc.125

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visa/cli",
3
- "version": "4.1.0-rc.124",
3
+ "version": "4.1.0-rc.125",
4
4
  "description": "Visa CLI runtime for stable agent identity and separately authorized payment capabilities",
5
5
  "bin": {
6
6
  "visa-cli": "./bin/visa-cli.js",
package/server.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-10-17/server.schema.json",
3
3
  "name": "io.github.visa-crypto-labs/visa-cli",
4
- "version": "4.1.0-rc.124",
4
+ "version": "4.1.0-rc.125",
5
5
  "title": "Visa CLI",
6
6
  "description": "Pair a human-approved agent identity, configure payment capabilities separately, and discover and pay x402 services from your AI coding assistant.",
7
7
  "websiteUrl": "https://github.com/Visa-Crypto-Labs/Visa-mono/tree/main/packages/cli#readme",
@@ -9,7 +9,7 @@
9
9
  {
10
10
  "registryType": "npm",
11
11
  "identifier": "@visa/cli",
12
- "version": "4.1.0-rc.124",
12
+ "version": "4.1.0-rc.125",
13
13
  "transport": {
14
14
  "type": "stdio"
15
15
  },
@@ -1,13 +0,0 @@
1
- import type { VgsCheckoutTarget } from './vgs-live-instrument.js';
2
- /**
3
- * Build a checkout target from inline CLI flags (`--merchant-url` +
4
- * `--amount`, with optional `--merchant-name` / `--country` / `--currency`)
5
- * so any merchant can be paid without authoring a checkout JSON file first.
6
- *
7
- * Returns null when neither driving flag is present (file mode). Shape-only:
8
- * the returned target flows through run-live-fill's existing validation block
9
- * (positive-decimal amount, ISO codes, HTTPS), which stays the single source
10
- * of truth — nothing is double-validated here except the URL parse, which
11
- * must happen early because the merchant-name default derives from it.
12
- */
13
- export declare function inlineTargetFromFlags(input: Map<string, string>): VgsCheckoutTarget | null;
@@ -1,37 +0,0 @@
1
- /**
2
- * Build a checkout target from inline CLI flags (`--merchant-url` +
3
- * `--amount`, with optional `--merchant-name` / `--country` / `--currency`)
4
- * so any merchant can be paid without authoring a checkout JSON file first.
5
- *
6
- * Returns null when neither driving flag is present (file mode). Shape-only:
7
- * the returned target flows through run-live-fill's existing validation block
8
- * (positive-decimal amount, ISO codes, HTTPS), which stays the single source
9
- * of truth — nothing is double-validated here except the URL parse, which
10
- * must happen early because the merchant-name default derives from it.
11
- */
12
- export function inlineTargetFromFlags(input) {
13
- const merchantUrl = input.get('--merchant-url');
14
- const amount = input.get('--amount');
15
- if (merchantUrl === undefined && amount === undefined)
16
- return null;
17
- if (!merchantUrl || !amount) {
18
- throw new Error('inline checkout needs both --merchant-url and --amount');
19
- }
20
- let host;
21
- try {
22
- host = new URL(merchantUrl).hostname;
23
- }
24
- catch {
25
- throw new Error('--merchant-url must be a valid URL');
26
- }
27
- if (!host) {
28
- throw new Error('--merchant-url must have a hostname');
29
- }
30
- return {
31
- merchantName: input.get('--merchant-name') ?? host,
32
- merchantUrl,
33
- merchantCountryCode: input.get('--country') ?? 'US',
34
- transactionAmount: amount,
35
- transactionCurrencyCode: input.get('--currency') ?? 'USD',
36
- };
37
- }
@@ -1,11 +0,0 @@
1
- /**
2
- * Load the monorepo root `.env` as DEFAULTS for the runner, so stable
3
- * per-machine config (VGS credentials, CHECKOUT_APPROVAL_BASE_URL,
4
- * CHECKOUT_AGENT_MODE) is set once instead of
5
- * retyped on every invocation. `process.loadEnvFile` never overrides
6
- * variables already present in the environment (verified: shell always wins),
7
- * so an explicit `FOO=x pnpm pay …` still beats the file. A missing file is
8
- * fine — the runner then relies on the ambient environment exactly as before.
9
- */
10
- export declare function defaultRepoEnvPath(): string;
11
- export declare function loadRepoEnvDefaults(path?: string, log?: (line: string) => void): boolean;
@@ -1,23 +0,0 @@
1
- import { fileURLToPath } from 'node:url';
2
- /**
3
- * Load the monorepo root `.env` as DEFAULTS for the runner, so stable
4
- * per-machine config (VGS credentials, CHECKOUT_APPROVAL_BASE_URL,
5
- * CHECKOUT_AGENT_MODE) is set once instead of
6
- * retyped on every invocation. `process.loadEnvFile` never overrides
7
- * variables already present in the environment (verified: shell always wins),
8
- * so an explicit `FOO=x pnpm pay …` still beats the file. A missing file is
9
- * fine — the runner then relies on the ambient environment exactly as before.
10
- */
11
- export function defaultRepoEnvPath() {
12
- return fileURLToPath(new URL('../../../.env', import.meta.url));
13
- }
14
- export function loadRepoEnvDefaults(path = defaultRepoEnvPath(), log = (line) => process.stdout.write(`${line}\n`)) {
15
- try {
16
- process.loadEnvFile(path);
17
- }
18
- catch {
19
- return false;
20
- }
21
- log(`loaded env defaults from ${path} (already-set variables win)`);
22
- return true;
23
- }
@@ -1,74 +0,0 @@
1
- export type VgsTransaction = {
2
- merchantName: string
3
- merchantUrl: string
4
- merchantCountryCode: string
5
- transactionAmount: string
6
- transactionCurrencyCode: string
7
- }
8
-
9
- export function createIntent(
10
- input: {
11
- tokenId: string
12
- assuranceData: unknown
13
- transaction: VgsTransaction
14
- },
15
- env?: Record<string, string | undefined>
16
- ): Promise<{
17
- intentId: string
18
- /**
19
- * Creation-time status attribute (null when VGS omits it). HTTP 201 alone
20
- * does not mean the intent is authorized — surface this when a later
21
- * cryptogram fails (#5709).
22
- */
23
- status: string | null
24
- }>
25
-
26
- export function fetchCryptogram(
27
- input: {
28
- tokenId: string
29
- intentId: string
30
- transaction: VgsTransaction
31
- },
32
- env?: Record<string, string | undefined>
33
- ): Promise<{
34
- networkToken: string
35
- expMonth: number
36
- expYear: number
37
- cryptogramType: string
38
- cryptogramValue: string
39
- cryptogramExpiresAt?: string
40
- }>
41
-
42
- export function getCredential(
43
- input: {
44
- tokenId: string
45
- assuranceData: unknown
46
- transaction: VgsTransaction
47
- },
48
- env?: Record<string, string | undefined>
49
- ): Promise<{
50
- networkToken: string
51
- expMonth: number
52
- expYear: number
53
- cryptogramType: string
54
- cryptogramValue: string
55
- cryptogramExpiresAt?: string
56
- }>
57
-
58
- export function postConfirmation(input: {
59
- tokenId: string
60
- intentId: string
61
- transactionStatus: 'APPROVED' | 'DECLINED' | 'PENDING' | 'ERROR' | 'CANCELLED'
62
- transactionType:
63
- | 'PURCHASE'
64
- | 'AUTHORIZATION'
65
- | 'CAPTURE'
66
- | 'REFUND'
67
- | 'REVERSAL'
68
- | 'VERIFICATION'
69
- | 'CHARGEBACK'
70
- | 'FRAUD'
71
- /** ISO 8601; converted to the guide's quoted epoch-seconds on the wire. */
72
- transactionTimestamp: string
73
- transaction: Pick<VgsTransaction, 'transactionAmount' | 'transactionCurrencyCode'>
74
- }, env?: Record<string, string | undefined>): Promise<{ ok: true }>
@@ -1,248 +0,0 @@
1
- // ⚠️ RETIRED CLIENT-SECRET PATH — used ONLY by the local `pnpm fill:live` spike
2
- // (run-live-fill.ts) and the older pay.ts dev entrypoints, NOT by the shipped
3
- // pay_merchant CLI. The productionized CLI (cli-engine.ts) mints SERVER-SIDE via
4
- // a scoped mint token (vgs-gateway/server-mint-client.ts) and never holds
5
- // VGS_USERNAME/VGS_PASSWORD. This module (and its spike callers) are slated for
6
- // deletion in the Phase-1 follow-up; do NOT add new callers. The
7
- // no-client-vgs-secret gate keeps the shipped path clear of everything below.
8
- //
9
- // Real credential fetch — NO mocks. Calls the live VGS agentic gateway to mint a
10
- // fresh, intent-scoped payment credential (DPAN + expiry + the 3-digit DAVV) and
11
- // returns it in memory. Same VGS agentic wire calls as enrollment; this just
12
- // returns the FULL values (for the form-filler) instead of masking.
13
- //
14
- // Nothing here persists or logs the credential — it is returned to the caller
15
- // (fillCheckout), and must never be written to disk or passed through an
16
- // LLM/agent context.
17
- //
18
- // Requires env: VGS_USERNAME, VGS_PASSWORD (the VGS service-account client id/secret),
19
- // and either VGS_ENVIRONMENT=live (+ optional VGS_GATEWAY_URL) or sandbox.
20
-
21
- const TOKEN_URL = 'https://auth.verygoodsecurity.com/auth/realms/vgs/protocol/openid-connect/token'
22
-
23
- function gatewayBase(env = process.env) {
24
- if (env.VGS_GATEWAY_URL) return env.VGS_GATEWAY_URL.replace(/\/$/, '')
25
- return env.VGS_ENVIRONMENT === 'live'
26
- ? 'https://gw-01-live.vgsapi.com'
27
- : 'https://gw-01-sandbox.vgsapi.com'
28
- }
29
-
30
- async function mintOauthToken(env = process.env) {
31
- const clientId = env.VGS_USERNAME
32
- const clientSecret = env.VGS_PASSWORD
33
- if (!clientId || !clientSecret) {
34
- throw new Error('Set VGS_USERNAME and VGS_PASSWORD (the VGS service-account client id/secret).')
35
- }
36
- const body = new URLSearchParams({
37
- client_id: clientId,
38
- client_secret: clientSecret,
39
- grant_type: 'client_credentials',
40
- })
41
- const r = await fetch(TOKEN_URL, {
42
- method: 'POST',
43
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
44
- body,
45
- })
46
- if (!r.ok) throw new Error(`VGS token grant failed (${r.status}).`)
47
- return (await r.json()).access_token
48
- }
49
-
50
- async function postJsonApi(url, type, attributes, env = process.env) {
51
- const token = await mintOauthToken(env)
52
- const r = await fetch(url, {
53
- method: 'POST',
54
- headers: {
55
- Authorization: `Bearer ${token}`,
56
- 'Content-Type': 'application/vnd.api+json',
57
- },
58
- body: JSON.stringify({ data: { ...(type ? { type } : {}), attributes } }),
59
- })
60
- const text = await r.text()
61
- let doc = {}
62
- try {
63
- doc = JSON.parse(text)
64
- } catch {
65
- /* non-json error body */
66
- }
67
- // Support trace handles VGS asked for on the #5713 decline thread: trace_id
68
- // keys the request on VGS's side, network_correlation_id on the Visa network
69
- // side. Routing metadata only — never credential material — and logged even
70
- // on error responses so any run stays traceable after the fact.
71
- const obs = doc?.meta?.observability
72
- if (obs && typeof obs === 'object') {
73
- console.info(
74
- JSON.stringify({
75
- op: 'vgs_observability',
76
- type,
77
- status: r.status,
78
- trace_id: obs.trace_id,
79
- vault_id: obs.vault_id,
80
- network_correlation_id: obs.network_correlation_id,
81
- })
82
- )
83
- }
84
- if (!r.ok) {
85
- // Never echo the full body (can carry ids); surface status + a short detail.
86
- const detail = doc?.errors?.[0]?.detail || doc?.errors?.[0]?.title || ''
87
- throw new Error(`VGS ${type} POST failed (${r.status})${detail ? `: ${detail}` : ''}.`)
88
- }
89
- return doc
90
- }
91
-
92
- const txnData = (t) => [
93
- {
94
- merchant_name: t.merchantName,
95
- merchant_url: t.merchantUrl,
96
- merchant_country_code: t.merchantCountryCode,
97
- transaction_amount: {
98
- transaction_amount: t.transactionAmount,
99
- transaction_currency_code: t.transactionCurrencyCode,
100
- },
101
- },
102
- ]
103
-
104
- /**
105
- * Create a fresh intent scoped to `transaction`, bound to the passkey assurance.
106
- * Needs `assuranceData` from a device-binding passkey ceremony run for THIS
107
- * purchase (merchant + amount + currency aligned) — replaying enrollment-time
108
- * assurance mints an intent that 201s but whose cryptogram never completes
109
- * (#5709, confirmed live 2026-07-17).
110
- * @returns {Promise<{intentId: string, status: string | null}>} the fresh
111
- * intent id plus the creation-time status attribute (null when VGS omits it) —
112
- * callers surface the status when a later cryptogram fails, since HTTP 201
113
- * alone does not mean the intent is authorized.
114
- */
115
- export async function createIntent({ tokenId, assuranceData, transaction }, env = process.env) {
116
- const effectiveUntil = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString()
117
- const cap = Math.max(Math.ceil(Number(transaction.transactionAmount) || 0) + 10, 25)
118
- const doc = await postJsonApi(
119
- `${gatewayBase(env)}/agentic-tokens/${encodeURIComponent(tokenId)}/intents`,
120
- 'intents',
121
- {
122
- consumer_prompt: `Buy an item from ${transaction.merchantName} for ${transaction.transactionCurrencyCode} ${transaction.transactionAmount}`,
123
- assurance_data: assuranceData,
124
- mandates: [
125
- {
126
- description: `Purchase at ${transaction.merchantName}`,
127
- decline_threshold: { amount: cap, currency_code: transaction.transactionCurrencyCode },
128
- effective_until: effectiveUntil,
129
- merchant_category: 'Retail',
130
- merchant_category_code: '5999',
131
- preferred_merchant_name: transaction.merchantName,
132
- quantity: 1,
133
- },
134
- ],
135
- },
136
- env
137
- )
138
- const intentId = doc.data?.id
139
- if (!intentId) throw new Error('createIntent: response missing data.id')
140
- const status = doc.data?.attributes?.status
141
- return { intentId, status: typeof status === 'string' && status ? status : null }
142
- }
143
-
144
- /**
145
- * Mint the FULL payment credential for an existing intent. Real VGS call — the
146
- * DAVV is single-use and expires in hours, so call this immediately before fill.
147
- * @returns {Promise<{networkToken,expMonth,expYear,cryptogramType,cryptogramValue}>}
148
- */
149
- export async function fetchCryptogram({ tokenId, intentId, transaction }, env = process.env) {
150
- // Intent approval can be asynchronous on live: creation returns PENDING and
151
- // the first cryptogram answer can be PENDING too (observed 2026-07-17,
152
- // donate.stripe.com run). Poll briefly on PENDING only — every other
153
- // non-COMPLETED status still fails fast on the first answer. Both knobs are
154
- // env-tunable (and injectable for tests, which must not sleep wall-clock).
155
- const PENDING_ATTEMPTS = Math.max(1, Number(env.VGS_CRYPTOGRAM_PENDING_ATTEMPTS) || 4)
156
- const PENDING_WAIT_MS = Number.isFinite(Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS))
157
- ? Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS)
158
- : 5000
159
- let a = {}
160
- for (let attempt = 1; ; attempt++) {
161
- const doc = await postJsonApi(
162
- `${gatewayBase(env)}/agentic-tokens/${encodeURIComponent(tokenId)}/intents/${encodeURIComponent(intentId)}/cryptograms`,
163
- 'cryptograms',
164
- { transaction_data: txnData(transaction) },
165
- env
166
- )
167
- a = doc.data?.attributes ?? {}
168
- const s = typeof a.status === 'string' ? a.status.toUpperCase() : ''
169
- if (s !== 'PENDING' || attempt >= PENDING_ATTEMPTS) break
170
- console.info(
171
- JSON.stringify({ op: 'cryptogram_pending_retry', attempt, waitMs: PENDING_WAIT_MS })
172
- )
173
- await new Promise((resolve) => setTimeout(resolve, PENDING_WAIT_MS))
174
- }
175
- // A network_token can come back while the cryptogram is still pending/failed —
176
- // mirror lib/server/vgs.ts and reject anything not COMPLETED, so we never key a
177
- // not-yet-valid credential (which would decline and read as a fill bug).
178
- const status = a.status
179
- if (typeof status === 'string' && status && status.toUpperCase() !== 'COMPLETED') {
180
- throw new Error(`cryptogram not completed (status ${status})`)
181
- }
182
- const networkToken = a.network_token
183
- const value = a.cryptogram?.value
184
- if (typeof networkToken !== 'string' || !networkToken) {
185
- throw new Error('cryptogram response missing network_token')
186
- }
187
- if (typeof value !== 'string' || !value) {
188
- throw new Error('cryptogram response missing cryptogram value')
189
- }
190
- return {
191
- networkToken,
192
- expMonth: typeof a.exp_month === 'number' ? a.exp_month : Number(a.exp_month) || 0,
193
- expYear: typeof a.exp_year === 'number' ? a.exp_year : Number(a.exp_year) || 0,
194
- cryptogramType: a.cryptogram?.type ?? '',
195
- cryptogramValue: value,
196
- cryptogramExpiresAt:
197
- typeof a.cryptogram?.expires_at === 'string' ? a.cryptogram.expires_at : undefined,
198
- }
199
- }
200
-
201
- /**
202
- * Full path: create the intent (needs fresh passkey assurance) then mint the
203
- * credential. Use fetchCryptogram directly if you already have an intentId.
204
- */
205
- export async function getCredential({ tokenId, assuranceData, transaction }, env = process.env) {
206
- const { intentId, status } = await createIntent({ tokenId, assuranceData, transaction }, env)
207
- try {
208
- return await fetchCryptogram({ tokenId, intentId, transaction }, env)
209
- } catch (err) {
210
- // HTTP 201 on intent creation does not mean the intent was authorized —
211
- // surface its creation-time status so a not-completed cryptogram is
212
- // diagnosable (#5709) instead of an opaque failure.
213
- throw new Error(`${err.message} (intent status at creation: ${status ?? 'unknown'})`)
214
- }
215
- }
216
-
217
- /**
218
- * Report the observed merchant outcome back to VIC for a consumed intent.
219
- * Mirrors lib/server/vgs.ts postConfirmation exactly: same endpoint, same
220
- * JSON:API envelope, and the guide's quoted Unix-epoch-seconds timestamp
221
- * (callers pass ISO 8601; converted here).
222
- */
223
- export async function postConfirmation(
224
- { tokenId, intentId, transactionStatus, transactionType, transactionTimestamp, transaction },
225
- env = process.env
226
- ) {
227
- await postJsonApi(
228
- `${gatewayBase(env)}/agentic-tokens/${encodeURIComponent(tokenId)}/intents/${encodeURIComponent(intentId)}/confirmations`,
229
- 'confirmations',
230
- {
231
- confirmation_data: [
232
- {
233
- payment_confirmation_data: {
234
- transaction_status: transactionStatus,
235
- transaction_type: transactionType,
236
- transaction_timestamp: String(Math.floor(Date.parse(transactionTimestamp) / 1000)),
237
- transaction_amount: {
238
- transaction_amount: transaction.transactionAmount,
239
- transaction_currency_code: transaction.transactionCurrencyCode,
240
- },
241
- },
242
- },
243
- ],
244
- },
245
- env
246
- )
247
- return { ok: true }
248
- }