@visa/cli 4.1.0-rc.297 → 4.1.0-rc.299

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +29 -45
  2. package/dist/cli.js +556 -786
  3. package/dist/mcp-server/index.js +408 -622
  4. package/dist/merchant-ucp-mcp/index.js +6 -6
  5. package/dist/skills/pair-visa-agent/SKILL.md +175 -240
  6. package/native/bin/win32-arm64/visa-runtime-signer.exe +0 -0
  7. package/native/bin/win32-x64/visa-keychain-win.exe +0 -0
  8. package/native/bin/win32-x64/visa-runtime-signer.exe +0 -0
  9. package/package.json +2 -4
  10. package/server.json +2 -2
  11. package/dist/checkout-engine/adapters/generic.d.ts +0 -88
  12. package/dist/checkout-engine/adapters/generic.js +0 -526
  13. package/dist/checkout-engine/adapters/index.d.ts +0 -10
  14. package/dist/checkout-engine/adapters/index.js +0 -24
  15. package/dist/checkout-engine/adapters/shopify.d.ts +0 -98
  16. package/dist/checkout-engine/adapters/shopify.js +0 -744
  17. package/dist/checkout-engine/adapters/stripe-like.d.ts +0 -10
  18. package/dist/checkout-engine/adapters/stripe-like.js +0 -21
  19. package/dist/checkout-engine/amount.d.ts +0 -17
  20. package/dist/checkout-engine/amount.js +0 -72
  21. package/dist/checkout-engine/browser-launch.d.ts +0 -51
  22. package/dist/checkout-engine/browser-launch.js +0 -96
  23. package/dist/checkout-engine/browserbase-browser.d.ts +0 -24
  24. package/dist/checkout-engine/browserbase-browser.js +0 -186
  25. package/dist/checkout-engine/ceremony.d.ts +0 -64
  26. package/dist/checkout-engine/ceremony.js +0 -261
  27. package/dist/checkout-engine/cli-engine.d.ts +0 -417
  28. package/dist/checkout-engine/cli-engine.js +0 -1331
  29. package/dist/checkout-engine/confirmed-merchants.d.ts +0 -31
  30. package/dist/checkout-engine/confirmed-merchants.js +0 -165
  31. package/dist/checkout-engine/detect.d.ts +0 -61
  32. package/dist/checkout-engine/detect.js +0 -398
  33. package/dist/checkout-engine/evidence.d.ts +0 -25
  34. package/dist/checkout-engine/evidence.js +0 -104
  35. package/dist/checkout-engine/executor.d.ts +0 -262
  36. package/dist/checkout-engine/executor.js +0 -1837
  37. package/dist/checkout-engine/hosted-approval.d.ts +0 -195
  38. package/dist/checkout-engine/hosted-approval.js +0 -501
  39. package/dist/checkout-engine/index.d.ts +0 -12
  40. package/dist/checkout-engine/index.js +0 -13
  41. package/dist/checkout-engine/instrument.d.ts +0 -61
  42. package/dist/checkout-engine/instrument.js +0 -87
  43. package/dist/checkout-engine/known-merchants.d.ts +0 -10
  44. package/dist/checkout-engine/known-merchants.js +0 -38
  45. package/dist/checkout-engine/live-fill-approval.d.ts +0 -37
  46. package/dist/checkout-engine/live-fill-approval.js +0 -76
  47. package/dist/checkout-engine/mandate/card-mandate.d.ts +0 -121
  48. package/dist/checkout-engine/mandate/card-mandate.js +0 -226
  49. package/dist/checkout-engine/mandate/mandate-ledger.d.ts +0 -175
  50. package/dist/checkout-engine/mandate/mandate-ledger.js +0 -425
  51. package/dist/checkout-engine/mandate.d.ts +0 -33
  52. package/dist/checkout-engine/mandate.js +0 -135
  53. package/dist/checkout-engine/outcome.d.ts +0 -30
  54. package/dist/checkout-engine/outcome.js +0 -225
  55. package/dist/checkout-engine/owner-only-file.d.ts +0 -19
  56. package/dist/checkout-engine/owner-only-file.js +0 -41
  57. package/dist/checkout-engine/package.json +0 -3
  58. package/dist/checkout-engine/receipt-dir.d.ts +0 -6
  59. package/dist/checkout-engine/receipt-dir.js +0 -8
  60. package/dist/checkout-engine/receipt.d.ts +0 -135
  61. package/dist/checkout-engine/receipt.js +0 -148
  62. package/dist/checkout-engine/shopify-primary-domain.d.ts +0 -25
  63. package/dist/checkout-engine/shopify-primary-domain.js +0 -96
  64. package/dist/checkout-engine/trace-handles.d.ts +0 -8
  65. package/dist/checkout-engine/trace-handles.js +0 -12
  66. package/dist/checkout-engine/types.d.ts +0 -52
  67. package/dist/checkout-engine/types.js +0 -2
  68. package/dist/checkout-engine/unresolved-charges.d.ts +0 -34
  69. package/dist/checkout-engine/unresolved-charges.js +0 -134
  70. package/dist/checkout-engine/vgs-gateway/server-mint-client.d.ts +0 -155
  71. package/dist/checkout-engine/vgs-gateway/server-mint-client.js +0 -493
  72. package/dist/checkout-engine/vgs-live-instrument.d.ts +0 -144
  73. package/dist/checkout-engine/vgs-live-instrument.js +0 -229
  74. package/dist/checkout-engine/vic-confirmation.d.ts +0 -52
  75. package/dist/checkout-engine/vic-confirmation.js +0 -45
  76. package/dist/checkout-engine/web-bot-auth.d.ts +0 -98
  77. package/dist/checkout-engine/web-bot-auth.js +0 -218
@@ -1,229 +0,0 @@
1
- import { traceHandleFields } from './trace-handles.js';
2
- /**
3
- * Our fail-closed freshness bound, matching the runner's 15-minute checkout
4
- * review window — NOT a claim about VGS's actual assurance TTL (unpublished).
5
- * The only proven-working configuration mints the intent right after the
6
- * ceremony; anything older is refused before an intent is created.
7
- */
8
- export const PURCHASE_ASSURANCE_MAX_AGE_MS = 15 * 60 * 1000;
9
- /** Tolerated forward clock skew on `mintedAt` before it is treated as invalid. */
10
- const PURCHASE_ASSURANCE_MAX_SKEW_MS = 2 * 60 * 1000;
11
- export function decimalToMinor(value) {
12
- // JSON files routinely carry a number where the contract says decimal string
13
- // ("transactionAmount": 5): refuse non-strings HERE so every caller surfaces
14
- // its scoped invalid/mismatch remedy instead of a raw TypeError crash.
15
- if (typeof value !== 'string')
16
- return null;
17
- if (!/^\d+(\.\d{1,2})?$/.test(value))
18
- return null;
19
- const [whole, fraction = ''] = value.split('.');
20
- const minor = Number(whole) * 100 + Number(fraction.padEnd(2, '0'));
21
- return Number.isSafeInteger(minor) ? minor : null;
22
- }
23
- /**
24
- * Currencies whose minor unit is 1/100 of the major unit (2 decimal places).
25
- * minorToDecimal's /100 + pad-to-2 rendering is ONLY correct for these. The
26
- * card mandate path accepts any 3-letter ISO code, so a 0- or 3-decimal
27
- * currency (JPY, BHD, …) would otherwise be emitted with a wrong wire amount.
28
- * We only support USD/USDC today; extend deliberately (and fix the exponent)
29
- * before adding any non-2-decimal currency.
30
- *
31
- * NOTE (scanner FP pre-empt): this is a CLIENT-SIDE currency-exponent lookup for
32
- * rendering a wire amount in @visa/checkout-engine — it is NOT the cross-store
33
- * `PAYMENT_CURRENCIES` enum governed by apps/auth/src/shared-validators.ts, and
34
- * this package cannot import from apps/auth (no dependency edge). It intentionally
35
- * does not mirror that enum's membership; do not "reconcile" the two.
36
- */
37
- export const TWO_DECIMAL_CURRENCIES = new Set(['USD', 'USDC']);
38
- /**
39
- * Inverse of decimalToMinor: render integer minor units as a major-unit decimal
40
- * string ("D.DD") for the VGS wire (e.g. a ceiling of 50000 minor → "500.00").
41
- * Integer-only; never floating-point money. Throws on a non-integer/negative so
42
- * a bad accounting value cannot silently reach the network.
43
- *
44
- * The /100 + pad-to-2 rendering assumes a 2-decimal (exponent-2) currency. Pass
45
- * `currencyCode` on any path that accepts arbitrary currencies (the mandate
46
- * path) and it REFUSES a non-2-decimal currency rather than emit a wrong wire
47
- * amount. Omit it only where the currency is already known to be USD/USDC.
48
- */
49
- export function minorToDecimal(minor, currencyCode) {
50
- if (!Number.isSafeInteger(minor) || minor < 0) {
51
- throw new Error('minor units must be a non-negative safe integer');
52
- }
53
- if (currencyCode !== undefined && !TWO_DECIMAL_CURRENCIES.has(currencyCode.toUpperCase())) {
54
- throw new Error(`minorToDecimal only supports 2-decimal currencies (${[...TWO_DECIMAL_CURRENCIES].join('/')}); refusing to emit a wire amount for ${currencyCode}`);
55
- }
56
- const whole = Math.floor(minor / 100);
57
- const fraction = minor % 100;
58
- return `${whole}.${String(fraction).padStart(2, '0')}`;
59
- }
60
- function validateTarget(reference, ctx) {
61
- if (typeof reference.merchantName !== 'string' ||
62
- typeof reference.merchantCountryCode !== 'string' ||
63
- !reference.merchantName.trim() ||
64
- !/^[A-Z]{2}$/.test(reference.merchantCountryCode)) {
65
- throw new Error('VGS checkout reference merchant name/country is invalid');
66
- }
67
- let referenceHost;
68
- try {
69
- referenceHost = new URL(reference.merchantUrl).hostname;
70
- }
71
- catch {
72
- throw new Error('VGS checkout reference merchant URL is invalid');
73
- }
74
- if (referenceHost !== ctx.merchantHost) {
75
- throw new Error(`VGS credential merchant mismatch: ${referenceHost} vs ${ctx.merchantHost}`);
76
- }
77
- const amountMinor = decimalToMinor(reference.transactionAmount);
78
- if (amountMinor === null)
79
- throw new Error('VGS checkout reference amount is invalid');
80
- if (amountMinor !== ctx.amountMinor) {
81
- throw new Error(`VGS credential amount mismatch: ${amountMinor} vs ${ctx.amountMinor} minor units`);
82
- }
83
- // String() so a JSON-number currency (840) mismatches with a readable
84
- // message instead of crashing on .toUpperCase().
85
- const currency = String(reference.transactionCurrencyCode).toUpperCase();
86
- if (currency !== ctx.currency) {
87
- throw new Error(`VGS credential currency mismatch: ${currency} vs ${ctx.currency}`);
88
- }
89
- }
90
- /**
91
- * Refuse to mint an intent unless the assurance is fresh and its declared
92
- * scope matches the checkout target exactly. `now` is injectable so the
93
- * freshness rules are testable with a pinned clock (same pattern as
94
- * validateCredential).
95
- */
96
- export function validatePurchaseAssurance(value, target, now = new Date()) {
97
- const remedy = 'run a fresh device-binding ceremony scoped to this exact merchant, amount, and ' +
98
- 'currency, and pass its output via --purchase-assurance-file (#5709)';
99
- if (value == null || typeof value !== 'object') {
100
- throw new Error(`purchase assurance is missing — ${remedy}`);
101
- }
102
- // A passkey-exempt approval (marked by the approval SERVER, never assumed
103
- // locally) carries no assurance by design — every scope/freshness check
104
- // below still applies to it unchanged.
105
- if (value.assuranceData == null && value.assuranceExempt !== true) {
106
- throw new Error(`purchase assurance requires assuranceData — ${remedy}`);
107
- }
108
- const mintedAtMs = typeof value.mintedAt === 'string' ? Date.parse(value.mintedAt) : NaN;
109
- if (!Number.isFinite(mintedAtMs)) {
110
- throw new Error(`purchase assurance requires an ISO 8601 mintedAt — ${remedy}`);
111
- }
112
- const age = now.getTime() - mintedAtMs;
113
- if (age < -PURCHASE_ASSURANCE_MAX_SKEW_MS) {
114
- throw new Error(`purchase assurance mintedAt is in the future — ${remedy}`);
115
- }
116
- if (age > PURCHASE_ASSURANCE_MAX_AGE_MS) {
117
- throw new Error(`purchase assurance is stale (minted ${value.mintedAt}, limit ` +
118
- `${PURCHASE_ASSURANCE_MAX_AGE_MS / 60000} minutes) — ${remedy}`);
119
- }
120
- let targetHost;
121
- try {
122
- targetHost = new URL(target.merchantUrl).hostname;
123
- }
124
- catch {
125
- throw new Error('VGS checkout reference merchant URL is invalid');
126
- }
127
- if (value.merchantHost !== targetHost) {
128
- throw new Error(`purchase assurance merchant mismatch: ${value.merchantHost} vs ${targetHost} — ${remedy}`);
129
- }
130
- const assuranceMinor = decimalToMinor(value.transactionAmount);
131
- const targetMinor = decimalToMinor(target.transactionAmount);
132
- if (assuranceMinor === null || assuranceMinor !== targetMinor) {
133
- throw new Error(`purchase assurance amount mismatch: ${value.transactionAmount} vs ` +
134
- `${target.transactionAmount} — ${remedy}`);
135
- }
136
- if (typeof value.transactionCurrencyCode !== 'string' ||
137
- value.transactionCurrencyCode.toUpperCase() !==
138
- String(target.transactionCurrencyCode).toUpperCase()) {
139
- throw new Error(`purchase assurance currency mismatch: ${value.transactionCurrencyCode} vs ` +
140
- `${target.transactionCurrencyCode} — ${remedy}`);
141
- }
142
- }
143
- // `now` is injectable so expiry rules are testable with a pinned clock.
144
- export function validateCredential(value, now = new Date()) {
145
- if (!/^\d{12,19}$/.test(value.networkToken)) {
146
- throw new Error('VGS credential network token must contain 12-19 digits');
147
- }
148
- if (!/^\d{3,4}$/.test(value.cryptogramValue)) {
149
- throw new Error('VGS credential short DAVV must contain 3-4 digits');
150
- }
151
- if (typeof value.cryptogramType !== 'string' || value.cryptogramType.toUpperCase() !== 'DAVV') {
152
- throw new Error(`VGS credential type ${value.cryptogramType || '<missing>'} is not DAVV`);
153
- }
154
- if (!Number.isInteger(value.expMonth) || value.expMonth < 1 || value.expMonth > 12) {
155
- throw new Error('VGS credential expiration month is invalid');
156
- }
157
- if (!Number.isInteger(value.expYear) ||
158
- value.expYear < now.getFullYear() ||
159
- (value.expYear === now.getFullYear() && value.expMonth < now.getMonth() + 1)) {
160
- throw new Error('VGS credential is expired');
161
- }
162
- if (value.cryptogramExpiresAt === undefined) {
163
- throw new Error('VGS credential expiry is missing');
164
- }
165
- const expiresAtMs = Date.parse(value.cryptogramExpiresAt);
166
- if (!Number.isFinite(expiresAtMs))
167
- throw new Error('VGS credential expiry is invalid');
168
- if (expiresAtMs - now.getTime() < 60_000) {
169
- throw new Error('VGS credential has less than 60 seconds of validity remaining');
170
- }
171
- }
172
- /**
173
- * Mints the full DPAN + short DAVV only after the executor revalidates the
174
- * reviewed merchant, amount, and currency. The payment credential remains in
175
- * memory, is never returned to the caller, and can be requested only once.
176
- */
177
- export class VgsLiveInstrument {
178
- reference;
179
- cardholderName;
180
- fetchCredential;
181
- kind = 'agentic-token';
182
- used = false;
183
- minted = null;
184
- constructor(reference, cardholderName, fetchCredential) {
185
- this.reference = reference;
186
- this.cardholderName = cardholderName;
187
- this.fetchCredential = fetchCredential;
188
- }
189
- /**
190
- * Non-null once VGS has actually issued a credential (the intent is consumed
191
- * from that moment, even if local validation later rejects the credential) —
192
- * exactly the population a VIC confirmation can be owed for.
193
- */
194
- confirmationTarget() {
195
- return this.minted;
196
- }
197
- async getCredential(ctx) {
198
- if (this.used)
199
- throw new Error('VGS live credential instrument is single-use');
200
- this.used = true;
201
- validateTarget(this.reference, ctx);
202
- if (!this.reference.tokenId || !this.reference.intentId) {
203
- throw new Error('VGS checkout reference requires tokenId and intentId');
204
- }
205
- if (!this.cardholderName.trim())
206
- throw new Error('cardholder name is required');
207
- const { tokenId, intentId, ...transaction } = this.reference;
208
- const value = await this.fetchCredential({ tokenId, intentId, transaction });
209
- this.minted = { tokenId, intentId };
210
- try {
211
- validateCredential(value);
212
- }
213
- catch (err) {
214
- // VGS already issued a cryptogram for this intent even though we refuse
215
- // to fill it; "correct inputs and retry" would silently reuse a consumed
216
- // intent, so steer the operator to a fresh one.
217
- throw new Error(`${err.message} — a credential was issued by VGS but rejected locally; obtain a fresh intent before retrying`);
218
- }
219
- return {
220
- pan: value.networkToken,
221
- expMonth: value.expMonth,
222
- expYear: value.expYear,
223
- cvc: value.cryptogramValue,
224
- cardholderName: this.cardholderName.trim(),
225
- ...(value.cryptogramExpiresAt ? { credentialExpiresAt: value.cryptogramExpiresAt } : {}),
226
- ...traceHandleFields(value),
227
- };
228
- }
229
- }
@@ -1,52 +0,0 @@
1
- import type { CheckoutOutcome } from './executor.js';
2
- import type { VicConfirmationTarget } from './vgs-live-instrument.js';
3
- export type VicTransactionStatus = 'APPROVED' | 'DECLINED';
4
- export type PostVicConfirmation = (input: {
5
- tokenId: string;
6
- intentId: string;
7
- transactionStatus: VicTransactionStatus;
8
- transactionType: 'PURCHASE';
9
- transactionTimestamp: string;
10
- transaction: {
11
- transactionAmount: string;
12
- transactionCurrencyCode: string;
13
- };
14
- }) => Promise<unknown>;
15
- /**
16
- * Why a confirmation was not posted, as a BOUNDED value rather than prose.
17
- *
18
- * `reason` below is a human sentence built for the local receipt; it embeds
19
- * upstream error text and is useless as an aggregate. These three codes are the
20
- * whole space, and they mean very different things:
21
- *
22
- * - `outcome_not_definitive` — the merchant never gave a definitive answer, so
23
- * there is nothing truthful to report. Expected, not a fault.
24
- * - `no_credential_minted` — no VIC credential existed for this run, so there
25
- * is no intent to confirm against. Expected, not a fault.
26
- * - `post_failed` — we HAD a definitive outcome and an intent to report it
27
- * against, and the POST did not land. This one is a fault: the processor
28
- * lifecycle row is never written, so the purchase can never rank above the
29
- * platform's own record no matter how well it actually went.
30
- */
31
- export type VicConfirmationSkipCode = 'outcome_not_definitive' | 'no_credential_minted' | 'post_failed';
32
- export type VicConfirmationReport = {
33
- posted: true;
34
- transactionStatus: VicTransactionStatus;
35
- } | {
36
- posted: false;
37
- code: VicConfirmationSkipCode;
38
- reason: string;
39
- };
40
- /** Definitive merchant answers map to a status; everything else maps to none. */
41
- export declare function outcomeToTransactionStatus(outcome: CheckoutOutcome): VicTransactionStatus | null;
42
- export declare function reportVicOutcome(input: {
43
- target: VicConfirmationTarget | null;
44
- outcome: CheckoutOutcome;
45
- transaction: {
46
- transactionAmount: string;
47
- transactionCurrencyCode: string;
48
- };
49
- post: PostVicConfirmation;
50
- /** Injectable for tests; defaults to now. */
51
- timestamp?: Date;
52
- }): Promise<VicConfirmationReport>;
@@ -1,45 +0,0 @@
1
- /** Definitive merchant answers map to a status; everything else maps to none. */
2
- export function outcomeToTransactionStatus(outcome) {
3
- if (outcome === 'confirmed')
4
- return 'APPROVED';
5
- if (outcome === 'declined')
6
- return 'DECLINED';
7
- return null;
8
- }
9
- export async function reportVicOutcome(input) {
10
- const transactionStatus = outcomeToTransactionStatus(input.outcome);
11
- if (!transactionStatus) {
12
- return {
13
- posted: false,
14
- code: 'outcome_not_definitive',
15
- reason: `outcome '${input.outcome}' is not a definitive merchant answer — ` +
16
- 'resolve it with the merchant, then post the confirmation manually',
17
- };
18
- }
19
- if (!input.target) {
20
- return {
21
- posted: false,
22
- code: 'no_credential_minted',
23
- reason: 'no VIC credential was minted in this run',
24
- };
25
- }
26
- try {
27
- await input.post({
28
- tokenId: input.target.tokenId,
29
- intentId: input.target.intentId,
30
- transactionStatus,
31
- transactionType: 'PURCHASE',
32
- transactionTimestamp: (input.timestamp ?? new Date()).toISOString(),
33
- transaction: input.transaction,
34
- });
35
- return { posted: true, transactionStatus };
36
- }
37
- catch (err) {
38
- return {
39
- posted: false,
40
- code: 'post_failed',
41
- reason: `confirmation POST failed: ${err.message} — the merchant-reported outcome ` +
42
- 'remains unverified; retry the confirmation for this intent out-of-band',
43
- };
44
- }
45
- }
@@ -1,98 +0,0 @@
1
- /** Signature validity ceiling. A signature is a bearer-ish artifact for as long
2
- * as it is valid, so the window stays short even if a caller asks for more. */
3
- export declare const WEB_BOT_AUTH_MAX_TTL_SECONDS = 300;
4
- /** Default validity. Long enough to survive a redirect chain and a slow TLS
5
- * handshake, short enough that a captured signature is near-useless. */
6
- export declare const WEB_BOT_AUTH_DEFAULT_TTL_SECONDS = 60;
7
- /** Label for the single signature we emit. RFC 9421 allows several per request. */
8
- export declare const WEB_BOT_AUTH_SIGNATURE_LABEL = "sig1";
9
- /** Tag fixed by the Web Bot Auth draft; verifiers select on it. */
10
- export declare const WEB_BOT_AUTH_TAG = "web-bot-auth";
11
- /** Components covered by the signature, in the order they appear in the base. */
12
- export declare const WEB_BOT_AUTH_COVERED_COMPONENTS: readonly ["@authority", "signature-agent"];
13
- /** Ed25519 private key in JWK form, as stored in the agent's runtime key file. */
14
- export interface WebBotAuthPrivateJwk {
15
- kty: 'OKP';
16
- crv: 'Ed25519';
17
- x: string;
18
- d: string;
19
- }
20
- export interface WebBotAuthSigningKey {
21
- /** RFC 7638 thumbprint. Must match a `kid` published in the directory. */
22
- keyId: string;
23
- privateJwk?: WebBotAuthPrivateJwk;
24
- signFn?: (signingInput: Uint8Array) => Promise<Uint8Array>;
25
- }
26
- export interface WebBotAuthConfig {
27
- /** Absolute https URL of the operator-hosted signature directory. */
28
- directoryUrl: string;
29
- key: WebBotAuthSigningKey;
30
- ttlSeconds?: number;
31
- }
32
- export interface WebBotAuthHeaders {
33
- 'Signature-Input': string;
34
- Signature: string;
35
- 'Signature-Agent': string;
36
- [header: string]: string;
37
- }
38
- export interface SignatureBaseParams {
39
- authority: string;
40
- directoryUrl: string;
41
- keyId: string;
42
- created: number;
43
- expires: number;
44
- }
45
- /**
46
- * Build the RFC 9421 signature base.
47
- *
48
- * The base is what actually gets signed, so its exact bytes are the contract
49
- * with every verifier — one wrong space or a reordered parameter and the
50
- * signature fails against a correct key. It is exported and pinned by a
51
- * deterministic test vector for that reason.
52
- */
53
- export declare function buildSignatureBase(params: SignatureBaseParams): string;
54
- /**
55
- * The `@signature-params` value, which appears twice: as the final line of the
56
- * signature base, and verbatim as the `Signature-Input` header value. Building
57
- * it once is what keeps those two identical — a verifier rederives the base
58
- * from the header it received, so any divergence fails every signature.
59
- */
60
- export declare function buildSignatureParams(params: SignatureBaseParams): string;
61
- export interface BuildHeadersParams {
62
- /** Host (and port, if non-default) of the request being signed. */
63
- authority: string;
64
- config: WebBotAuthConfig;
65
- /** Unix seconds. Injected so tests are deterministic and never wall-clock. */
66
- nowSeconds: number;
67
- }
68
- /**
69
- * Produce the three Web Bot Auth headers for one request authority.
70
- *
71
- * Throws on unusable key material rather than emitting an unverifiable
72
- * signature. Callers on the checkout path must treat a throw as "proceed
73
- * unsigned" — see `webBotAuthHeadersOrNone`.
74
- */
75
- export declare function buildWebBotAuthHeaders(params: BuildHeadersParams): WebBotAuthHeaders;
76
- /**
77
- * Header-or-nothing wrapper for the checkout path.
78
- *
79
- * Signing is an optional trust upgrade, never a precondition for buying
80
- * something. Unusable key material, a malformed URL, or any crypto failure
81
- * degrades to an unsigned request — which is exactly what we sent before this
82
- * module existed — rather than throwing into a live checkout.
83
- */
84
- export declare function webBotAuthHeadersOrNone(config: WebBotAuthConfig | null, targetUrl: string, nowSeconds: number): WebBotAuthHeaders | null;
85
- /**
86
- * Async version of buildWebBotAuthHeaders, supporting Turnkey or vault signFn signers.
87
- */
88
- export declare function buildWebBotAuthHeadersAsync(params: BuildHeadersParams): Promise<WebBotAuthHeaders>;
89
- export declare function webBotAuthHeadersOrNoneAsync(config: WebBotAuthConfig | null, targetUrl: string, nowSeconds: number): Promise<WebBotAuthHeaders | null>;
90
- /**
91
- * Resolve signing config from the environment. Returns `null` — meaning "send
92
- * unsigned" — unless a directory URL and a usable key are BOTH present.
93
- *
94
- * Default-off is deliberate. Until the operator directory is live and serving
95
- * this key, a signature resolves to nothing and fails verification, which is
96
- * worse than the honest unsigned request we sent before.
97
- */
98
- export declare function resolveWebBotAuthConfig(env: NodeJS.ProcessEnv, loadKey: () => WebBotAuthSigningKey | null): WebBotAuthConfig | null;
@@ -1,218 +0,0 @@
1
- /**
2
- * @purpose Web Bot Auth (RFC 9421) request signing for checkout navigations —
3
- * the client half of Trusted Agent Protocol verification.
4
- *
5
- * Cloudflare's TAP verifies an agent by checking an RFC 9421 HTTP message
6
- * signature on the request. Three headers carry it: `Signature-Input` names the
7
- * covered components and parameters, `Signature` carries the Ed25519 signature
8
- * over the derived base, and `Signature-Agent` gives the URL of the directory
9
- * that resolves `keyid` to a public key. The checkout browser previously sent
10
- * none of them, so a TAP-aware edge had nothing to verify and fell through to
11
- * ordinary bot management.
12
- *
13
- * TWO HALVES, BOTH REQUIRED. This module presents a `keyid`; the auth server
14
- * must publish that key at the `Signature-Agent` URL for anything to resolve.
15
- * Signing while the directory is absent is strictly worse than not signing,
16
- * because it advertises intent and then fails verification — which is why
17
- * signing stays OFF unless explicitly configured with a directory URL.
18
- *
19
- * KEY MATERIAL NEVER LEAVES THIS MODULE. The signing key is accepted as a
20
- * value, used once per request, and never logged, serialized, returned, or
21
- * attached to evidence. Callers get headers, never the key. This module takes
22
- * no logger for exactly that reason.
23
- */
24
- import { createPrivateKey, sign as cryptoSign } from 'node:crypto';
25
- /** Signature validity ceiling. A signature is a bearer-ish artifact for as long
26
- * as it is valid, so the window stays short even if a caller asks for more. */
27
- export const WEB_BOT_AUTH_MAX_TTL_SECONDS = 300;
28
- /** Default validity. Long enough to survive a redirect chain and a slow TLS
29
- * handshake, short enough that a captured signature is near-useless. */
30
- export const WEB_BOT_AUTH_DEFAULT_TTL_SECONDS = 60;
31
- /** Label for the single signature we emit. RFC 9421 allows several per request. */
32
- export const WEB_BOT_AUTH_SIGNATURE_LABEL = 'sig1';
33
- /** Tag fixed by the Web Bot Auth draft; verifiers select on it. */
34
- export const WEB_BOT_AUTH_TAG = 'web-bot-auth';
35
- /** Components covered by the signature, in the order they appear in the base. */
36
- export const WEB_BOT_AUTH_COVERED_COMPONENTS = ['@authority', 'signature-agent'];
37
- /** Serialize an RFC 8941 structured-field string (always double-quoted). */
38
- function sfString(value) {
39
- return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
40
- }
41
- /**
42
- * Build the RFC 9421 signature base.
43
- *
44
- * The base is what actually gets signed, so its exact bytes are the contract
45
- * with every verifier — one wrong space or a reordered parameter and the
46
- * signature fails against a correct key. It is exported and pinned by a
47
- * deterministic test vector for that reason.
48
- */
49
- export function buildSignatureBase(params) {
50
- return [
51
- `"@authority": ${params.authority}`,
52
- `"signature-agent": ${sfString(params.directoryUrl)}`,
53
- `"@signature-params": ${buildSignatureParams(params)}`,
54
- ].join('\n');
55
- }
56
- /**
57
- * The `@signature-params` value, which appears twice: as the final line of the
58
- * signature base, and verbatim as the `Signature-Input` header value. Building
59
- * it once is what keeps those two identical — a verifier rederives the base
60
- * from the header it received, so any divergence fails every signature.
61
- */
62
- export function buildSignatureParams(params) {
63
- return (`(${WEB_BOT_AUTH_COVERED_COMPONENTS.map(sfString).join(' ')})` +
64
- `;created=${params.created}` +
65
- `;expires=${params.expires}` +
66
- `;keyid=${sfString(params.keyId)}` +
67
- `;alg="ed25519"` +
68
- `;tag=${sfString(WEB_BOT_AUTH_TAG)}`);
69
- }
70
- /**
71
- * Produce the three Web Bot Auth headers for one request authority.
72
- *
73
- * Throws on unusable key material rather than emitting an unverifiable
74
- * signature. Callers on the checkout path must treat a throw as "proceed
75
- * unsigned" — see `webBotAuthHeadersOrNone`.
76
- */
77
- export function buildWebBotAuthHeaders(params) {
78
- const { authority, config, nowSeconds } = params;
79
- const ttl = Math.min(Math.max(1, Math.floor(config.ttlSeconds ?? WEB_BOT_AUTH_DEFAULT_TTL_SECONDS)), WEB_BOT_AUTH_MAX_TTL_SECONDS);
80
- const created = Math.floor(nowSeconds);
81
- const expires = created + ttl;
82
- const baseParams = {
83
- authority,
84
- directoryUrl: config.directoryUrl,
85
- keyId: config.key.keyId,
86
- created,
87
- expires,
88
- };
89
- const base = buildSignatureBase(baseParams);
90
- const signatureParams = buildSignatureParams(baseParams);
91
- // privateJwk is optional on the key so a vault-held signer can supply signFn
92
- // instead. Only the async builder can await such a signer, so refuse here with
93
- // the same explicit message rather than handing undefined to createPrivateKey
94
- // and surfacing an opaque node:crypto error.
95
- if (!config.key.privateJwk) {
96
- throw new Error(config.key.signFn
97
- ? 'WebBotAuthSigningKey with signFn requires buildWebBotAuthHeadersAsync'
98
- : 'WebBotAuthSigningKey requires either privateJwk or signFn');
99
- }
100
- const privateKey = createPrivateKey({
101
- key: config.key.privateJwk,
102
- format: 'jwk',
103
- });
104
- // Ed25519 takes no separate digest algorithm; null is the required argument.
105
- const signature = cryptoSign(null, Buffer.from(base, 'utf8'), privateKey);
106
- return {
107
- 'Signature-Input': `${WEB_BOT_AUTH_SIGNATURE_LABEL}=${signatureParams}`,
108
- Signature: `${WEB_BOT_AUTH_SIGNATURE_LABEL}=:${signature.toString('base64')}:`,
109
- 'Signature-Agent': sfString(config.directoryUrl),
110
- };
111
- }
112
- /**
113
- * Header-or-nothing wrapper for the checkout path.
114
- *
115
- * Signing is an optional trust upgrade, never a precondition for buying
116
- * something. Unusable key material, a malformed URL, or any crypto failure
117
- * degrades to an unsigned request — which is exactly what we sent before this
118
- * module existed — rather than throwing into a live checkout.
119
- */
120
- export function webBotAuthHeadersOrNone(config, targetUrl, nowSeconds) {
121
- if (!config)
122
- return null;
123
- try {
124
- const authority = new URL(targetUrl).host;
125
- if (!authority)
126
- return null;
127
- return buildWebBotAuthHeaders({ authority, config, nowSeconds });
128
- }
129
- catch {
130
- return null;
131
- }
132
- }
133
- /**
134
- * Async version of buildWebBotAuthHeaders, supporting Turnkey or vault signFn signers.
135
- */
136
- export async function buildWebBotAuthHeadersAsync(params) {
137
- const { authority, config, nowSeconds } = params;
138
- const ttl = Math.min(Math.max(1, Math.floor(config.ttlSeconds ?? WEB_BOT_AUTH_DEFAULT_TTL_SECONDS)), WEB_BOT_AUTH_MAX_TTL_SECONDS);
139
- const created = Math.floor(nowSeconds);
140
- const expires = created + ttl;
141
- const baseParams = {
142
- authority,
143
- directoryUrl: config.directoryUrl,
144
- keyId: config.key.keyId,
145
- created,
146
- expires,
147
- };
148
- const base = buildSignatureBase(baseParams);
149
- const signatureParams = buildSignatureParams(baseParams);
150
- let signature;
151
- if (config.key.signFn) {
152
- signature = await config.key.signFn(Buffer.from(base, 'utf8'));
153
- }
154
- else if (config.key.privateJwk) {
155
- const privateKey = createPrivateKey({
156
- key: config.key.privateJwk,
157
- format: 'jwk',
158
- });
159
- signature = cryptoSign(null, Buffer.from(base, 'utf8'), privateKey);
160
- }
161
- else {
162
- throw new Error('WebBotAuthSigningKey requires either privateJwk or signFn');
163
- }
164
- return {
165
- 'Signature-Input': `${WEB_BOT_AUTH_SIGNATURE_LABEL}=${signatureParams}`,
166
- Signature: `${WEB_BOT_AUTH_SIGNATURE_LABEL}=:${Buffer.from(signature).toString('base64')}:`,
167
- 'Signature-Agent': sfString(config.directoryUrl),
168
- };
169
- }
170
- export async function webBotAuthHeadersOrNoneAsync(config, targetUrl, nowSeconds) {
171
- if (!config)
172
- return null;
173
- try {
174
- const authority = new URL(targetUrl).host;
175
- if (!authority)
176
- return null;
177
- return await buildWebBotAuthHeadersAsync({ authority, config, nowSeconds });
178
- }
179
- catch {
180
- return null;
181
- }
182
- }
183
- /**
184
- * Resolve signing config from the environment. Returns `null` — meaning "send
185
- * unsigned" — unless a directory URL and a usable key are BOTH present.
186
- *
187
- * Default-off is deliberate. Until the operator directory is live and serving
188
- * this key, a signature resolves to nothing and fails verification, which is
189
- * worse than the honest unsigned request we sent before.
190
- */
191
- export function resolveWebBotAuthConfig(env, loadKey) {
192
- const directoryUrl = env.VISA_WEB_BOT_AUTH_DIRECTORY_URL?.trim();
193
- if (!directoryUrl)
194
- return null;
195
- let parsed;
196
- try {
197
- parsed = new URL(directoryUrl);
198
- }
199
- catch {
200
- return null;
201
- }
202
- // A directory fetched over plain http could be swapped in flight, which would
203
- // let an observer substitute the key set our identity is judged against.
204
- if (parsed.protocol !== 'https:')
205
- return null;
206
- let key = null;
207
- try {
208
- key = loadKey();
209
- }
210
- catch {
211
- return null;
212
- }
213
- if (!key?.keyId || (!key.signFn && (key.privateJwk?.crv !== 'Ed25519' || !key.privateJwk.d)))
214
- return null;
215
- const rawTtl = Number(env.VISA_WEB_BOT_AUTH_TTL_SECONDS);
216
- const ttlSeconds = Number.isFinite(rawTtl) && rawTtl > 0 ? rawTtl : undefined;
217
- return { directoryUrl: parsed.toString(), key, ttlSeconds };
218
- }