@visa/cli 4.1.0-rc.9 → 4.1.0-rc.91
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 +178 -231
- 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 +227 -0
- package/dist/checkout-engine/cli-engine.js +779 -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 +187 -0
- package/dist/checkout-engine/hosted-approval.js +478 -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 +338 -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 +179 -0
- package/dist/checkout-engine/vgs-live-instrument.js +296 -0
- package/dist/checkout-engine/vic-confirmation.d.ts +34 -0
- package/dist/checkout-engine/vic-confirmation.js +39 -0
- package/dist/cli.js +448 -433
- package/dist/mcp-server/index.js +366 -170
- package/dist/skills/pair-visa-agent/RUNTIMES.md +92 -0
- package/dist/skills/pair-visa-agent/SKILL.md +468 -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 +16 -12
- package/server.json +3 -3
|
@@ -0,0 +1,248 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { VgsCheckoutTarget, VgsPaymentCredential } from '../vgs-live-instrument.js';
|
|
2
|
+
export type ServerMintDeps = {
|
|
3
|
+
/** Injectable for tests — defaults to global fetch. */
|
|
4
|
+
fetchImpl?: typeof fetch;
|
|
5
|
+
/** Injectable for tests — never wall-clock-sleep in a unit test. */
|
|
6
|
+
sleep?: (ms: number) => Promise<void>;
|
|
7
|
+
env?: NodeJS.ProcessEnv;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* The merchant ORIGIN (scheme + host) — not the full checkout URL. A merchant's
|
|
11
|
+
* identity is its origin; a real checkout URL can carry hundreds of chars of
|
|
12
|
+
* campaign/tracking query params. Confirmed live: an oversized `merchantUrl`
|
|
13
|
+
* (a ~280-char Wikimedia donation URL) makes the cryptogram mint fail downstream
|
|
14
|
+
* with a vague `502 "card network could not complete"`, while the same merchant
|
|
15
|
+
* with a trimmed URL mints fine. Sending the origin is both correct (that IS the
|
|
16
|
+
* merchant) and safely bounded. Falls back to the raw value if it does not parse
|
|
17
|
+
* — the mint must never throw here.
|
|
18
|
+
*/
|
|
19
|
+
export declare function merchantOrigin(url: string): string;
|
|
20
|
+
/**
|
|
21
|
+
* Optional mandate override for serverCreateIntent. Absent → the historical
|
|
22
|
+
* 1:1 fresh-tap shape is preserved byte-for-byte (cap = ceil(amount)+10 min 25,
|
|
23
|
+
* quantity 1, 30-day window). Present → the card-mandate (budget) layer sets a
|
|
24
|
+
* CEILING decline threshold and a multi-draw quantity so one passkey approves a
|
|
25
|
+
* spend ceiling and later draws pull cryptograms under it without a fresh tap.
|
|
26
|
+
* Whether the network honors a ceiling-scoped assurance across multiple
|
|
27
|
+
* sub-amount draws is UNPROVEN — see packages/checkout-engine/src/mandate/.
|
|
28
|
+
*/
|
|
29
|
+
export type ServerIntentMandateOverride = {
|
|
30
|
+
/** Wire decline-threshold amount (major-unit decimal string), e.g. "500.00". */
|
|
31
|
+
declineThresholdAmount?: string;
|
|
32
|
+
/** Number of draws the intent may fulfil (VGS mandate `quantity`). */
|
|
33
|
+
quantity?: number;
|
|
34
|
+
/** ISO 8601 mandate validity end. */
|
|
35
|
+
effectiveUntil?: string;
|
|
36
|
+
/** Human-readable consumer prompt describing the ceiling grant. */
|
|
37
|
+
consumerPrompt?: string;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Create a fresh intent via POST {base}/api/vgs/intent. The server holds the VGS
|
|
41
|
+
* credential and calls the gateway; we send the same mandate shape the local
|
|
42
|
+
* path built (cap = ceil(amount)+10, min 25; merchant category Retail/5999) —
|
|
43
|
+
* unless `input.mandate` overrides the threshold/quantity/window for the
|
|
44
|
+
* card-mandate (budget) layer.
|
|
45
|
+
*/
|
|
46
|
+
export declare function serverCreateIntent(base: string, mintToken: string, input: {
|
|
47
|
+
tokenId: string;
|
|
48
|
+
assuranceData: unknown;
|
|
49
|
+
transaction: VgsCheckoutTarget;
|
|
50
|
+
mandate?: ServerIntentMandateOverride;
|
|
51
|
+
}, deps?: ServerMintDeps): Promise<{
|
|
52
|
+
intentId: string;
|
|
53
|
+
status: string | null;
|
|
54
|
+
}>;
|
|
55
|
+
/**
|
|
56
|
+
* Mint the FULL payment credential via POST {base}/api/vgs/payment-cryptogram.
|
|
57
|
+
* The server's route does a SINGLE gateway call and 502s on a not-COMPLETED
|
|
58
|
+
* (e.g. PENDING) cryptogram, but live intent approval is asynchronous and the
|
|
59
|
+
* first cryptogram answer can be PENDING (#5709). So we retry the route on any
|
|
60
|
+
* non-2xx up to PENDING_ATTEMPTS, matching fetch-credential.mjs's cadence
|
|
61
|
+
* exactly — a genuinely hard failure just surfaces after the same bounded wait.
|
|
62
|
+
* Re-POSTing for the same intentId is idempotent (mirrors the old client loop).
|
|
63
|
+
*/
|
|
64
|
+
export declare function serverFetchCryptogram(base: string, mintToken: string, input: {
|
|
65
|
+
tokenId: string;
|
|
66
|
+
intentId: string;
|
|
67
|
+
transaction: VgsCheckoutTarget;
|
|
68
|
+
}, deps?: ServerMintDeps): Promise<VgsPaymentCredential>;
|
|
69
|
+
/** Report the observed merchant outcome via POST {base}/api/vgs/confirmation. */
|
|
70
|
+
export declare function serverPostConfirmation(base: string, mintToken: string, input: {
|
|
71
|
+
tokenId: string;
|
|
72
|
+
intentId: string;
|
|
73
|
+
transactionStatus: string;
|
|
74
|
+
transactionType: string;
|
|
75
|
+
transactionTimestamp: string;
|
|
76
|
+
transaction: {
|
|
77
|
+
transactionAmount: string;
|
|
78
|
+
transactionCurrencyCode: string;
|
|
79
|
+
};
|
|
80
|
+
}, deps?: ServerMintDeps): Promise<{
|
|
81
|
+
ok: true;
|
|
82
|
+
}>;
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// Server-side mint client (Phase 1) — the checkout runner mints the payment
|
|
2
|
+
// credential by calling the verify-web deployment's gateway routes with a
|
|
3
|
+
// short-lived, purpose-scoped MINT TOKEN, instead of holding the shared VGS
|
|
4
|
+
// service-account secret (the gateway client id/secret) on the machine.
|
|
5
|
+
//
|
|
6
|
+
// The mint token is issued at approval time (agent-approval/complete, which is
|
|
7
|
+
// session + internal-tester + token-ownership gated) and released to this
|
|
8
|
+
// runner by the claim leg. It is bound to the exact approved purchase, so these
|
|
9
|
+
// calls can only mint the credential the human approved.
|
|
10
|
+
//
|
|
11
|
+
// Request derivation here mirrors ../fetch-credential.mjs EXACTLY (mandate cap,
|
|
12
|
+
// consumer prompt, PENDING retry cadence) — the only change is the transport:
|
|
13
|
+
// verify-web routes + Bearer mint token, never the VGS gateway + VGS secret.
|
|
14
|
+
import { traceHandleFields } from '../trace-handles.js';
|
|
15
|
+
const defaultSleep = (ms) => new Promise((r) => {
|
|
16
|
+
const t = setTimeout(r, ms);
|
|
17
|
+
t.unref?.();
|
|
18
|
+
});
|
|
19
|
+
function stripTrailingSlashes(value) {
|
|
20
|
+
let out = value;
|
|
21
|
+
while (out.endsWith('/'))
|
|
22
|
+
out = out.slice(0, -1);
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The merchant ORIGIN (scheme + host) — not the full checkout URL. A merchant's
|
|
27
|
+
* identity is its origin; a real checkout URL can carry hundreds of chars of
|
|
28
|
+
* campaign/tracking query params. Confirmed live: an oversized `merchantUrl`
|
|
29
|
+
* (a ~280-char Wikimedia donation URL) makes the cryptogram mint fail downstream
|
|
30
|
+
* with a vague `502 "card network could not complete"`, while the same merchant
|
|
31
|
+
* with a trimmed URL mints fine. Sending the origin is both correct (that IS the
|
|
32
|
+
* merchant) and safely bounded. Falls back to the raw value if it does not parse
|
|
33
|
+
* — the mint must never throw here.
|
|
34
|
+
*/
|
|
35
|
+
export function merchantOrigin(url) {
|
|
36
|
+
try {
|
|
37
|
+
return new URL(url).origin;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return url;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Read a stable, non-secret error message from a route's JSON body. */
|
|
44
|
+
async function routeError(res) {
|
|
45
|
+
const doc = (await res.json().catch(() => null));
|
|
46
|
+
return doc?.error || doc?.error_code || `HTTP ${res.status}`;
|
|
47
|
+
}
|
|
48
|
+
function bearer(mintToken) {
|
|
49
|
+
return { 'content-type': 'application/json', authorization: `Bearer ${mintToken}` };
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Create a fresh intent via POST {base}/api/vgs/intent. The server holds the VGS
|
|
53
|
+
* credential and calls the gateway; we send the same mandate shape the local
|
|
54
|
+
* path built (cap = ceil(amount)+10, min 25; merchant category Retail/5999) —
|
|
55
|
+
* unless `input.mandate` overrides the threshold/quantity/window for the
|
|
56
|
+
* card-mandate (budget) layer.
|
|
57
|
+
*/
|
|
58
|
+
export async function serverCreateIntent(base, mintToken, input, deps = {}) {
|
|
59
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
60
|
+
const { tokenId, assuranceData, transaction: t } = input;
|
|
61
|
+
const override = input.mandate ?? {};
|
|
62
|
+
const defaultCap = Math.max(Math.ceil(Number(t.transactionAmount) || 0) + 10, 25);
|
|
63
|
+
const declineThresholdAmount = override.declineThresholdAmount ?? String(defaultCap);
|
|
64
|
+
const quantity = override.quantity ?? 1;
|
|
65
|
+
const effectiveUntil = override.effectiveUntil ?? new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString();
|
|
66
|
+
const consumerPrompt = override.consumerPrompt ??
|
|
67
|
+
`Buy an item from ${t.merchantName} for ${t.transactionCurrencyCode.toUpperCase()} ${t.transactionAmount}`;
|
|
68
|
+
const res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/intent`, {
|
|
69
|
+
method: 'POST',
|
|
70
|
+
headers: bearer(mintToken),
|
|
71
|
+
body: JSON.stringify({
|
|
72
|
+
tokenId,
|
|
73
|
+
consumerPrompt,
|
|
74
|
+
assuranceData,
|
|
75
|
+
mandates: [
|
|
76
|
+
{
|
|
77
|
+
description: `Purchase at ${t.merchantName}`,
|
|
78
|
+
declineThresholdAmount,
|
|
79
|
+
declineThresholdCurrencyCode: t.transactionCurrencyCode.toUpperCase(),
|
|
80
|
+
effectiveUntil,
|
|
81
|
+
merchantCategory: 'Retail',
|
|
82
|
+
merchantCategoryCode: '5999',
|
|
83
|
+
preferredMerchantName: t.merchantName,
|
|
84
|
+
quantity,
|
|
85
|
+
},
|
|
86
|
+
],
|
|
87
|
+
}),
|
|
88
|
+
});
|
|
89
|
+
if (!res.ok)
|
|
90
|
+
throw new Error(`server intent failed (${res.status}): ${await routeError(res)}`);
|
|
91
|
+
const doc = (await res.json().catch(() => null));
|
|
92
|
+
if (!doc?.intentId)
|
|
93
|
+
throw new Error('server intent response missing intentId');
|
|
94
|
+
return { intentId: doc.intentId, status: typeof doc.status === 'string' ? doc.status : null };
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Mint the FULL payment credential via POST {base}/api/vgs/payment-cryptogram.
|
|
98
|
+
* The server's route does a SINGLE gateway call and 502s on a not-COMPLETED
|
|
99
|
+
* (e.g. PENDING) cryptogram, but live intent approval is asynchronous and the
|
|
100
|
+
* first cryptogram answer can be PENDING (#5709). So we retry the route on any
|
|
101
|
+
* non-2xx up to PENDING_ATTEMPTS, matching fetch-credential.mjs's cadence
|
|
102
|
+
* exactly — a genuinely hard failure just surfaces after the same bounded wait.
|
|
103
|
+
* Re-POSTing for the same intentId is idempotent (mirrors the old client loop).
|
|
104
|
+
*/
|
|
105
|
+
export async function serverFetchCryptogram(base, mintToken, input, deps = {}) {
|
|
106
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
107
|
+
const sleep = deps.sleep ?? defaultSleep;
|
|
108
|
+
const env = deps.env ?? process.env;
|
|
109
|
+
const attempts = Math.max(1, Number(env.VGS_CRYPTOGRAM_PENDING_ATTEMPTS) || 4);
|
|
110
|
+
const waitMs = Number.isFinite(Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS))
|
|
111
|
+
? Number(env.VGS_CRYPTOGRAM_PENDING_WAIT_MS)
|
|
112
|
+
: 5000;
|
|
113
|
+
const { tokenId, intentId, transaction: t } = input;
|
|
114
|
+
const body = JSON.stringify({
|
|
115
|
+
tokenId,
|
|
116
|
+
intentId,
|
|
117
|
+
transaction: {
|
|
118
|
+
merchantName: t.merchantName,
|
|
119
|
+
// Send the merchant ORIGIN, not the full (possibly huge) checkout URL — an
|
|
120
|
+
// oversized merchantUrl makes the downstream cryptogram mint 502 (proven live).
|
|
121
|
+
merchantUrl: merchantOrigin(t.merchantUrl),
|
|
122
|
+
merchantCountryCode: t.merchantCountryCode,
|
|
123
|
+
transactionAmount: t.transactionAmount,
|
|
124
|
+
transactionCurrencyCode: t.transactionCurrencyCode.toUpperCase(),
|
|
125
|
+
},
|
|
126
|
+
});
|
|
127
|
+
let lastError = 'unknown';
|
|
128
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
129
|
+
const res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/payment-cryptogram`, {
|
|
130
|
+
method: 'POST',
|
|
131
|
+
headers: bearer(mintToken),
|
|
132
|
+
body,
|
|
133
|
+
});
|
|
134
|
+
if (res.ok) {
|
|
135
|
+
const c = (await res.json().catch(() => null));
|
|
136
|
+
if (!c || typeof c.networkToken !== 'string' || typeof c.cryptogramValue !== 'string') {
|
|
137
|
+
throw new Error('server cryptogram response missing credential fields');
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
networkToken: c.networkToken,
|
|
141
|
+
expMonth: Number(c.expMonth) || 0,
|
|
142
|
+
expYear: Number(c.expYear) || 0,
|
|
143
|
+
cryptogramType: c.cryptogramType ?? '',
|
|
144
|
+
cryptogramValue: c.cryptogramValue,
|
|
145
|
+
...(typeof c.cryptogramExpiresAt === 'string'
|
|
146
|
+
? { cryptogramExpiresAt: c.cryptogramExpiresAt }
|
|
147
|
+
: {}),
|
|
148
|
+
...traceHandleFields(c),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
// A 4xx (bad request / binding refusal / auth) is terminal — never retry it.
|
|
152
|
+
if (res.status >= 400 && res.status < 500) {
|
|
153
|
+
throw new Error(`server cryptogram refused (${res.status}): ${await routeError(res)}`);
|
|
154
|
+
}
|
|
155
|
+
lastError = `${res.status}: ${await routeError(res)}`;
|
|
156
|
+
if (attempt < attempts)
|
|
157
|
+
await sleep(waitMs);
|
|
158
|
+
}
|
|
159
|
+
throw new Error(`server cryptogram not completed after ${attempts} attempts (last: ${lastError})`);
|
|
160
|
+
}
|
|
161
|
+
/** Report the observed merchant outcome via POST {base}/api/vgs/confirmation. */
|
|
162
|
+
export async function serverPostConfirmation(base, mintToken, input, deps = {}) {
|
|
163
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
164
|
+
const res = await fetchImpl(`${stripTrailingSlashes(base)}/api/vgs/confirmation`, {
|
|
165
|
+
method: 'POST',
|
|
166
|
+
headers: bearer(mintToken),
|
|
167
|
+
body: JSON.stringify({
|
|
168
|
+
tokenId: input.tokenId,
|
|
169
|
+
intentId: input.intentId,
|
|
170
|
+
transactionStatus: input.transactionStatus,
|
|
171
|
+
transactionType: input.transactionType,
|
|
172
|
+
transactionTimestamp: input.transactionTimestamp,
|
|
173
|
+
transactionAmount: input.transaction.transactionAmount,
|
|
174
|
+
transactionCurrencyCode: input.transaction.transactionCurrencyCode.toUpperCase(),
|
|
175
|
+
}),
|
|
176
|
+
});
|
|
177
|
+
if (!res.ok)
|
|
178
|
+
throw new Error(`server confirmation failed (${res.status}): ${await routeError(res)}`);
|
|
179
|
+
return { ok: true };
|
|
180
|
+
}
|