@redcenterstudio/agent-tollbooth-edge 0.0.0-stage → 1.2.0
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/LICENSE +21 -0
- package/README.md +53 -2
- package/dist/index.d.ts +317 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1495 -0
- package/dist/index.js.map +1 -0
- package/package.json +40 -4
- package/src/index.ts +2005 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1495 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @redcenterstudio/agent-tollbooth-edge
|
|
3
|
+
* Zero-dependency dual-rail HTTP 402 middleware for Cloudflare Workers, Fetch APIs, Next.js, and Hono.
|
|
4
|
+
*
|
|
5
|
+
* Rail A: Open x402 V2 standard (`PAYMENT-REQUIRED`, `PAYMENT-SIGNATURE`, `PAYMENT-RESPONSE`)
|
|
6
|
+
* Rail B: Red Center Fiat Agent Wallet (`rcs_receipt_...` verified <1ms via Web Crypto + NonceStore)
|
|
7
|
+
*/
|
|
8
|
+
export const DEFAULT_FACILITATOR_URL = 'https://tollbooth.redcenterstudio.com';
|
|
9
|
+
export const DEFAULT_PAYMENT_URL = 'https://tollbooth.redcenterstudio.com';
|
|
10
|
+
export const DEFAULT_PAY_TO = '0x000000000000000000000000000000000000dEaD';
|
|
11
|
+
export const DEFAULT_NETWORK = 'eip155:8453';
|
|
12
|
+
export const DEFAULT_USDC_BASE_ASSET = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
|
|
13
|
+
export const DEFAULT_EXEMPT_PATHS = ['/health', '/readyz', '/webhook/*'];
|
|
14
|
+
export const DEFAULT_CLOCK_SKEW_SECONDS = 30;
|
|
15
|
+
export const DEFAULT_JWKS_URL = 'https://tollbooth.redcenterstudio.com/.well-known/tollbooth-jwks.json';
|
|
16
|
+
/**
|
|
17
|
+
* EIP-712 domain of USDC per network. Payers sign with this name and version; a wrong name makes the USDC
|
|
18
|
+
* contract reject the transfer (Base mainnet USDC is "USD Coin", Base Sepolia USDC is "USDC").
|
|
19
|
+
*/
|
|
20
|
+
export const USDC_EIP712_DOMAINS = {
|
|
21
|
+
'eip155:8453': { name: 'USD Coin', version: '2' },
|
|
22
|
+
'eip155:84532': { name: 'USDC', version: '2' },
|
|
23
|
+
};
|
|
24
|
+
export function usdcEip712Extra(network) {
|
|
25
|
+
return USDC_EIP712_DOMAINS[network] ?? { name: 'USD Coin', version: '2' };
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Fetch the clearinghouse's Ed25519 receipt public key (the JWK `x`, base64url) for `fiatWallet.ed25519PublicKey`.
|
|
29
|
+
* Cache the result: the key changes only when the clearinghouse rotates it.
|
|
30
|
+
*/
|
|
31
|
+
export async function fetchTollboothPublicKey(jwksUrl = DEFAULT_JWKS_URL, fetchImpl = globalThis.fetch.bind(globalThis)) {
|
|
32
|
+
const res = await fetchImpl(jwksUrl, { headers: { Accept: 'application/json' } });
|
|
33
|
+
if (!res.ok) {
|
|
34
|
+
throw new Error(`JWKS fetch failed with HTTP ${res.status}`);
|
|
35
|
+
}
|
|
36
|
+
const jwks = (await res.json());
|
|
37
|
+
const key = jwks.keys?.find((k) => k.kty === 'OKP' && k.crv === 'Ed25519' && typeof k.x === 'string');
|
|
38
|
+
if (!key?.x) {
|
|
39
|
+
throw new Error('No Ed25519 key in JWKS');
|
|
40
|
+
}
|
|
41
|
+
return key.x;
|
|
42
|
+
}
|
|
43
|
+
export const DEFAULT_PRICE_USD = 0.01;
|
|
44
|
+
export const SANDBOX_HMAC_SECRET = 'rcs_sandbox_local_dev_secret_32bytes_deterministic';
|
|
45
|
+
export const CORS_EXPOSE_HEADERS = 'PAYMENT-REQUIRED, PAYMENT-RESPONSE, X-Agent-Receipt, WWW-Authenticate, X-Tollbooth-Rail';
|
|
46
|
+
export const CORS_ALLOW_HEADERS = 'Content-Type, Authorization, PAYMENT-SIGNATURE, X-Agent-Receipt, Idempotency-Key';
|
|
47
|
+
const textEncoder = new TextEncoder();
|
|
48
|
+
const textDecoder = new TextDecoder();
|
|
49
|
+
const hmacKeyCache = new Map();
|
|
50
|
+
const ed25519KeyCache = new Map();
|
|
51
|
+
/**
|
|
52
|
+
* Convert a USD dollar value (e.g. `0.005` or `"$0.005"`) into integer microdollars (`1 USD = 1_000_000`).
|
|
53
|
+
*/
|
|
54
|
+
export function usdToMicros(usd) {
|
|
55
|
+
const cleaned = typeof usd === 'string' ? usd.trim().replace(/^\$/, '') : String(usd);
|
|
56
|
+
if (!/^\d+(\.\d+)?$/.test(cleaned)) {
|
|
57
|
+
throw new RangeError(`Invalid non-negative USD amount: "${usd}"`);
|
|
58
|
+
}
|
|
59
|
+
const [wholePart = '0', fracPart = ''] = cleaned.split('.');
|
|
60
|
+
if (fracPart.length > 6) {
|
|
61
|
+
throw new RangeError(`USD precision exceeds 6 decimal microdollars: "${usd}"`);
|
|
62
|
+
}
|
|
63
|
+
const micros = Number(wholePart) * 1_000_000 + Number(fracPart.padEnd(6, '0'));
|
|
64
|
+
if (!Number.isSafeInteger(micros) || micros < 0) {
|
|
65
|
+
throw new RangeError(`USD amount out of safe integer bounds: "${usd}"`);
|
|
66
|
+
}
|
|
67
|
+
return micros;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Format integer microdollars into a trimmed USD string (e.g. `5000` -> `"0.005"`).
|
|
71
|
+
*/
|
|
72
|
+
export function microsToUsdString(micros) {
|
|
73
|
+
if (!Number.isSafeInteger(micros) || micros < 0) {
|
|
74
|
+
throw new RangeError(`Invalid microdollars value: ${micros}`);
|
|
75
|
+
}
|
|
76
|
+
const whole = Math.floor(micros / 1_000_000);
|
|
77
|
+
const frac = String(micros % 1_000_000).padStart(6, '0').replace(/0+$/, '');
|
|
78
|
+
return frac.length > 0 ? `${whole}.${frac}` : String(whole);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Convert USD microdollars to 6-decimal USDC atomic units (1 microdollar === 1 USDC atomic unit).
|
|
82
|
+
*/
|
|
83
|
+
export function usdMicrosToUsdcAtomic(micros) {
|
|
84
|
+
if (!Number.isSafeInteger(micros) || micros < 0) {
|
|
85
|
+
throw new RangeError(`Invalid microdollars value: ${micros}`);
|
|
86
|
+
}
|
|
87
|
+
return String(micros);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Web-standard Base64 encode for UTF-8 JSON payloads without Node Buffer dependency.
|
|
91
|
+
*/
|
|
92
|
+
export function encodePaymentHeader(payload) {
|
|
93
|
+
const bytes = textEncoder.encode(JSON.stringify(payload));
|
|
94
|
+
let binary = '';
|
|
95
|
+
for (let i = 0; i < bytes.length; i += 0x8000) {
|
|
96
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
97
|
+
}
|
|
98
|
+
return btoa(binary);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Web-standard Base64 decode for x402 V2 JSON header payloads.
|
|
102
|
+
*/
|
|
103
|
+
export function decodePaymentHeader(encoded) {
|
|
104
|
+
const trimmed = encoded.trim();
|
|
105
|
+
const binary = atob(trimmed);
|
|
106
|
+
const bytes = new Uint8Array(binary.length);
|
|
107
|
+
for (let i = 0; i < binary.length; i++) {
|
|
108
|
+
bytes[i] = binary.charCodeAt(i);
|
|
109
|
+
}
|
|
110
|
+
return JSON.parse(textDecoder.decode(bytes));
|
|
111
|
+
}
|
|
112
|
+
export function base64UrlEncode(bytes) {
|
|
113
|
+
let binary = '';
|
|
114
|
+
for (let i = 0; i < bytes.length; i += 0x8000) {
|
|
115
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
116
|
+
}
|
|
117
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
118
|
+
}
|
|
119
|
+
export function base64UrlDecode(input) {
|
|
120
|
+
if (!/^[A-Za-z0-9\-_]+$/.test(input)) {
|
|
121
|
+
throw new Error('Invalid base64url characters');
|
|
122
|
+
}
|
|
123
|
+
const padded = input.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(input.length / 4) * 4, '=');
|
|
124
|
+
const binary = atob(padded);
|
|
125
|
+
const bytes = new Uint8Array(binary.length);
|
|
126
|
+
for (let i = 0; i < binary.length; i++) {
|
|
127
|
+
bytes[i] = binary.charCodeAt(i);
|
|
128
|
+
}
|
|
129
|
+
return bytes;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* In-memory TTL-pruning NonceStore suitable for local smoke tests and single-isolate development.
|
|
133
|
+
*/
|
|
134
|
+
export class MemoryNonceStore {
|
|
135
|
+
used = new Map();
|
|
136
|
+
async consume(nonce, meta) {
|
|
137
|
+
const now = Math.floor(Date.now() / 1000);
|
|
138
|
+
for (const [key, exp] of this.used.entries()) {
|
|
139
|
+
if (exp <= now) {
|
|
140
|
+
this.used.delete(key);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const existingExp = this.used.get(nonce);
|
|
144
|
+
if (existingExp !== undefined && existingExp > now) {
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
const ttlExp = Math.max(meta.expiresAt, now + 60);
|
|
148
|
+
this.used.set(nonce, ttlExp);
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
151
|
+
async release(nonce) {
|
|
152
|
+
this.used.delete(nonce);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Durable edge NonceStore backed by Cloudflare D1 `used_nonces`.
|
|
157
|
+
*/
|
|
158
|
+
export class D1NonceStore {
|
|
159
|
+
db;
|
|
160
|
+
constructor(db) {
|
|
161
|
+
this.db = db;
|
|
162
|
+
}
|
|
163
|
+
async consume(nonce, meta) {
|
|
164
|
+
const now = Math.floor(Date.now() / 1000);
|
|
165
|
+
const rail = meta.rail ?? 'fiat_wallet';
|
|
166
|
+
const result = await this.db
|
|
167
|
+
.prepare('INSERT OR IGNORE INTO used_nonces (nonce, rail, wallet_or_payer, route_pattern, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?)')
|
|
168
|
+
.bind(nonce, rail, meta.walletOrPayer, meta.route, meta.expiresAt, now)
|
|
169
|
+
.run();
|
|
170
|
+
return (result.meta?.changes ?? 0) === 1;
|
|
171
|
+
}
|
|
172
|
+
async release(nonce) {
|
|
173
|
+
await this.db.prepare('DELETE FROM used_nonces WHERE nonce = ?').bind(nonce).run();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* In-memory per-agent spend cap tracker.
|
|
178
|
+
*/
|
|
179
|
+
export class MemorySpendTracker {
|
|
180
|
+
spendByAgent = new Map();
|
|
181
|
+
async checkAndRecord(agentId, amountMicros, capMicros) {
|
|
182
|
+
const current = this.spendByAgent.get(agentId) ?? 0;
|
|
183
|
+
const next = current + amountMicros;
|
|
184
|
+
if (next > capMicros) {
|
|
185
|
+
return { allowed: false, spentMicros: current };
|
|
186
|
+
}
|
|
187
|
+
this.spendByAgent.set(agentId, next);
|
|
188
|
+
return { allowed: true, spentMicros: next };
|
|
189
|
+
}
|
|
190
|
+
async rollback(agentId, amountMicros) {
|
|
191
|
+
const current = this.spendByAgent.get(agentId) ?? 0;
|
|
192
|
+
const next = Math.max(0, current - amountMicros);
|
|
193
|
+
this.spendByAgent.set(agentId, next);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
function getHmacKey(secret, usage) {
|
|
197
|
+
const cacheKey = `${usage}:${secret}`;
|
|
198
|
+
let pending = hmacKeyCache.get(cacheKey);
|
|
199
|
+
if (!pending) {
|
|
200
|
+
pending = crypto.subtle.importKey('raw', textEncoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);
|
|
201
|
+
hmacKeyCache.set(cacheKey, pending);
|
|
202
|
+
}
|
|
203
|
+
return pending;
|
|
204
|
+
}
|
|
205
|
+
function decodePublicKeyBytes(raw) {
|
|
206
|
+
const trimmed = raw.trim();
|
|
207
|
+
if (/^[0-9a-fA-F]{64}$/.test(trimmed)) {
|
|
208
|
+
const out = new Uint8Array(32);
|
|
209
|
+
for (let i = 0; i < 32; i++) {
|
|
210
|
+
out[i] = parseInt(trimmed.slice(i * 2, i * 2 + 2), 16);
|
|
211
|
+
}
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
return base64UrlDecode(trimmed);
|
|
215
|
+
}
|
|
216
|
+
function getEd25519VerifyKey(keyOrEncoded) {
|
|
217
|
+
if (typeof keyOrEncoded !== 'string') {
|
|
218
|
+
return Promise.resolve(keyOrEncoded);
|
|
219
|
+
}
|
|
220
|
+
let pending = ed25519KeyCache.get(keyOrEncoded);
|
|
221
|
+
if (!pending) {
|
|
222
|
+
const rawBytes = decodePublicKeyBytes(keyOrEncoded);
|
|
223
|
+
pending = crypto.subtle.importKey('raw', rawBytes.buffer.slice(rawBytes.byteOffset, rawBytes.byteOffset + rawBytes.byteLength), { name: 'Ed25519' }, false, ['verify']);
|
|
224
|
+
ed25519KeyCache.set(keyOrEncoded, pending);
|
|
225
|
+
}
|
|
226
|
+
return pending;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Sign a Red Center Fiat Agent Wallet receipt (`rcs_receipt_<alg>.<payload>.<sig>`).
|
|
230
|
+
*/
|
|
231
|
+
export async function signFiatReceipt(claims, keyMaterial) {
|
|
232
|
+
if (!Number.isSafeInteger(claims.amt) || claims.amt < 0) {
|
|
233
|
+
throw new RangeError('Receipt amt must be a non-negative safe integer in microdollars');
|
|
234
|
+
}
|
|
235
|
+
const payloadB64 = base64UrlEncode(textEncoder.encode(JSON.stringify(claims)));
|
|
236
|
+
const signingInput = `${keyMaterial.alg}.${payloadB64}`;
|
|
237
|
+
const data = textEncoder.encode(signingInput);
|
|
238
|
+
let sigBuffer;
|
|
239
|
+
if (keyMaterial.alg === 'hs256') {
|
|
240
|
+
const key = await getHmacKey(keyMaterial.secret, 'sign');
|
|
241
|
+
sigBuffer = await crypto.subtle.sign('HMAC', key, data);
|
|
242
|
+
}
|
|
243
|
+
else {
|
|
244
|
+
sigBuffer = await crypto.subtle.sign('Ed25519', keyMaterial.privateKey, data);
|
|
245
|
+
}
|
|
246
|
+
const sigB64 = base64UrlEncode(new Uint8Array(sigBuffer));
|
|
247
|
+
return `rcs_receipt_${signingInput}.${sigB64}`;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Zero-config helper for local `mode: "sandbox"` / `"mock"` testing without API keys or Stripe.
|
|
251
|
+
*/
|
|
252
|
+
export async function createSandboxReceipt(overrides) {
|
|
253
|
+
const now = Math.floor(Date.now() / 1000);
|
|
254
|
+
const amt = overrides?.amt ??
|
|
255
|
+
(overrides?.priceUsd !== undefined
|
|
256
|
+
? usdToMicros(overrides.priceUsd)
|
|
257
|
+
: usdToMicros(DEFAULT_PRICE_USD));
|
|
258
|
+
const claims = {
|
|
259
|
+
v: 1,
|
|
260
|
+
jti: overrides?.jti ?? `rcpt_sandbox_${crypto.randomUUID()}`,
|
|
261
|
+
sub: overrides?.sub ?? 'wallet_sandbox_agent',
|
|
262
|
+
aud: overrides?.aud ?? '*',
|
|
263
|
+
mth: overrides?.mth ?? '*',
|
|
264
|
+
amt,
|
|
265
|
+
iat: overrides?.iat ?? now,
|
|
266
|
+
exp: overrides?.exp ?? now + 120,
|
|
267
|
+
...(overrides?.tier ? { tier: overrides.tier } : {}),
|
|
268
|
+
};
|
|
269
|
+
return signFiatReceipt(claims, {
|
|
270
|
+
alg: 'hs256',
|
|
271
|
+
secret: overrides?.secret ?? SANDBOX_HMAC_SECRET,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Zero-config helper generating a Base64-encoded x402 V2 `PAYMENT-SIGNATURE` header for local sandbox runs.
|
|
276
|
+
*/
|
|
277
|
+
export function createSandboxX402Header(overrides) {
|
|
278
|
+
const now = Math.floor(Date.now() / 1000);
|
|
279
|
+
const amount = overrides?.amount ??
|
|
280
|
+
usdMicrosToUsdcAtomic(overrides?.priceUsd !== undefined
|
|
281
|
+
? usdToMicros(overrides.priceUsd)
|
|
282
|
+
: usdToMicros(DEFAULT_PRICE_USD));
|
|
283
|
+
const scheme = overrides?.scheme ?? 'exact';
|
|
284
|
+
const network = overrides?.network ?? DEFAULT_NETWORK;
|
|
285
|
+
const sig = {
|
|
286
|
+
x402Version: 2,
|
|
287
|
+
scheme,
|
|
288
|
+
network,
|
|
289
|
+
accepted: { scheme, network },
|
|
290
|
+
payload: {
|
|
291
|
+
signature: `0x${'ab'.repeat(65)}`,
|
|
292
|
+
authorization: {
|
|
293
|
+
from: overrides?.from ?? '0x1234567890abcdef1234567890abcdef12345678',
|
|
294
|
+
to: overrides?.payTo ?? DEFAULT_PAY_TO,
|
|
295
|
+
value: amount,
|
|
296
|
+
validAfter: String(now - 5),
|
|
297
|
+
validBefore: String(now + 120),
|
|
298
|
+
nonce: overrides?.nonce ?? `0x${crypto.randomUUID().replace(/-/g, '')}`,
|
|
299
|
+
},
|
|
300
|
+
},
|
|
301
|
+
};
|
|
302
|
+
return encodePaymentHeader(sig);
|
|
303
|
+
}
|
|
304
|
+
function matchesAudience(claimAud, expectedAudience) {
|
|
305
|
+
if (claimAud === '*') {
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
if (claimAud === expectedAudience) {
|
|
309
|
+
return true;
|
|
310
|
+
}
|
|
311
|
+
let expectedBase = expectedAudience;
|
|
312
|
+
try {
|
|
313
|
+
const reqUrl = new URL(expectedAudience);
|
|
314
|
+
expectedBase = `${reqUrl.origin}${reqUrl.pathname}`;
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
// non-URL audience string
|
|
318
|
+
}
|
|
319
|
+
if (claimAud.endsWith('/*')) {
|
|
320
|
+
const dirBase = claimAud.slice(0, -2);
|
|
321
|
+
const prefix = claimAud.slice(0, -1);
|
|
322
|
+
return expectedBase === dirBase || expectedBase.startsWith(prefix);
|
|
323
|
+
}
|
|
324
|
+
if (claimAud.endsWith('*')) {
|
|
325
|
+
const prefix = claimAud.slice(0, -1);
|
|
326
|
+
return expectedBase.startsWith(prefix) || expectedAudience.startsWith(prefix);
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
const claimUrl = new URL(claimAud);
|
|
330
|
+
const reqUrl = new URL(expectedAudience);
|
|
331
|
+
return claimUrl.origin === reqUrl.origin && claimUrl.pathname === reqUrl.pathname;
|
|
332
|
+
}
|
|
333
|
+
catch {
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Verify a Rail B `rcs_receipt_...` bearer token in <1ms using Web Crypto `crypto.subtle.verify`.
|
|
339
|
+
*/
|
|
340
|
+
export async function verifyFiatReceipt(token, options) {
|
|
341
|
+
const start = performance.now();
|
|
342
|
+
const trimmed = token.trim();
|
|
343
|
+
if (!trimmed.startsWith('rcs_receipt_')) {
|
|
344
|
+
return { valid: false, reason: 'invalid_receipt_prefix' };
|
|
345
|
+
}
|
|
346
|
+
const body = trimmed.slice('rcs_receipt_'.length);
|
|
347
|
+
const parts = body.split('.');
|
|
348
|
+
if (parts.length !== 3) {
|
|
349
|
+
return { valid: false, reason: 'malformed_receipt_format' };
|
|
350
|
+
}
|
|
351
|
+
const [algPart, payloadB64, sigB64] = parts;
|
|
352
|
+
if (algPart !== 'hs256' && algPart !== 'ed25519') {
|
|
353
|
+
return { valid: false, reason: 'unsupported_receipt_algorithm' };
|
|
354
|
+
}
|
|
355
|
+
let signatureBytes;
|
|
356
|
+
try {
|
|
357
|
+
signatureBytes = base64UrlDecode(sigB64);
|
|
358
|
+
}
|
|
359
|
+
catch {
|
|
360
|
+
return { valid: false, reason: 'invalid_receipt_signature_encoding' };
|
|
361
|
+
}
|
|
362
|
+
const signedBytes = textEncoder.encode(`${algPart}.${payloadB64}`);
|
|
363
|
+
const sigArrayBuffer = signatureBytes.buffer.slice(signatureBytes.byteOffset, signatureBytes.byteOffset + signatureBytes.byteLength);
|
|
364
|
+
let signatureValid = false;
|
|
365
|
+
try {
|
|
366
|
+
if (algPart === 'hs256') {
|
|
367
|
+
if (!options.hmacSecret) {
|
|
368
|
+
return { valid: false, reason: 'hmac_verifier_not_configured' };
|
|
369
|
+
}
|
|
370
|
+
const key = await getHmacKey(options.hmacSecret, 'verify');
|
|
371
|
+
signatureValid = await crypto.subtle.verify('HMAC', key, sigArrayBuffer, signedBytes);
|
|
372
|
+
}
|
|
373
|
+
else {
|
|
374
|
+
if (!options.ed25519PublicKey) {
|
|
375
|
+
return { valid: false, reason: 'ed25519_verifier_not_configured' };
|
|
376
|
+
}
|
|
377
|
+
const key = await getEd25519VerifyKey(options.ed25519PublicKey);
|
|
378
|
+
signatureValid = await crypto.subtle.verify('Ed25519', key, sigArrayBuffer, signedBytes);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
catch {
|
|
382
|
+
return { valid: false, reason: 'signature_verification_error' };
|
|
383
|
+
}
|
|
384
|
+
if (!signatureValid) {
|
|
385
|
+
return { valid: false, reason: 'invalid_receipt_signature' };
|
|
386
|
+
}
|
|
387
|
+
let claims;
|
|
388
|
+
try {
|
|
389
|
+
claims = JSON.parse(textDecoder.decode(base64UrlDecode(payloadB64)));
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
return { valid: false, reason: 'malformed_receipt_claims' };
|
|
393
|
+
}
|
|
394
|
+
if (claims.v !== 1 ||
|
|
395
|
+
typeof claims.jti !== 'string' ||
|
|
396
|
+
claims.jti.length === 0 ||
|
|
397
|
+
typeof claims.sub !== 'string' ||
|
|
398
|
+
claims.sub.length === 0 ||
|
|
399
|
+
typeof claims.aud !== 'string' ||
|
|
400
|
+
!Number.isSafeInteger(claims.amt) ||
|
|
401
|
+
!Number.isFinite(claims.iat) ||
|
|
402
|
+
!Number.isFinite(claims.exp)) {
|
|
403
|
+
return { valid: false, reason: 'invalid_receipt_claims_schema' };
|
|
404
|
+
}
|
|
405
|
+
const now = options.nowSeconds ?? Math.floor(Date.now() / 1000);
|
|
406
|
+
const skew = options.clockSkewSeconds ?? DEFAULT_CLOCK_SKEW_SECONDS;
|
|
407
|
+
if (claims.exp <= now - skew) {
|
|
408
|
+
return { valid: false, reason: 'receipt_expired' };
|
|
409
|
+
}
|
|
410
|
+
if (claims.iat > now + skew) {
|
|
411
|
+
return { valid: false, reason: 'receipt_not_yet_valid' };
|
|
412
|
+
}
|
|
413
|
+
if (!matchesAudience(claims.aud, options.expectedAudience)) {
|
|
414
|
+
return { valid: false, reason: 'receipt_audience_mismatch' };
|
|
415
|
+
}
|
|
416
|
+
if (claims.mth && claims.mth !== '*' && claims.mth.toUpperCase() !== options.expectedMethod.toUpperCase()) {
|
|
417
|
+
return { valid: false, reason: 'receipt_method_mismatch' };
|
|
418
|
+
}
|
|
419
|
+
if (claims.amt < options.requiredMicros) {
|
|
420
|
+
return { valid: false, reason: 'receipt_amount_insufficient' };
|
|
421
|
+
}
|
|
422
|
+
const verifiedInMs = performance.now() - start;
|
|
423
|
+
return {
|
|
424
|
+
valid: true,
|
|
425
|
+
claims,
|
|
426
|
+
alg: algPart,
|
|
427
|
+
verifiedInMs,
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
function resolveErrorGuidance(errorReason, requiredMicros, expectedAudience) {
|
|
431
|
+
const priceStr = `$${microsToUsdString(requiredMicros)} USD (${requiredMicros} microdollars)`;
|
|
432
|
+
switch (errorReason) {
|
|
433
|
+
case 'MISSING_PAYMENT':
|
|
434
|
+
case 'PAYMENT-SIGNATURE or rcs_receipt bearer header is required':
|
|
435
|
+
return {
|
|
436
|
+
code: 'MISSING_PAYMENT',
|
|
437
|
+
fix_hint: `Attach an x402 V2 Base64 PAYMENT-SIGNATURE header or an Authorization: Bearer rcs_receipt_... token for ${priceStr}.`,
|
|
438
|
+
};
|
|
439
|
+
case 'INSUFFICIENT_FUNDS':
|
|
440
|
+
case 'receipt_amount_insufficient':
|
|
441
|
+
case 'insufficient_payment_amount':
|
|
442
|
+
return {
|
|
443
|
+
code: 'INSUFFICIENT_FUNDS',
|
|
444
|
+
fix_hint: `Payment amount is below the required ${priceStr}. Top up your agent wallet or authorize at least ${requiredMicros} atomic units.`,
|
|
445
|
+
};
|
|
446
|
+
case 'RECEIPT_EXPIRED':
|
|
447
|
+
case 'receipt_expired':
|
|
448
|
+
case 'receipt_not_yet_valid':
|
|
449
|
+
case 'authorization_expired_or_not_yet_valid':
|
|
450
|
+
case 'invalid_authorization_timestamps':
|
|
451
|
+
return {
|
|
452
|
+
code: 'RECEIPT_EXPIRED',
|
|
453
|
+
fix_hint: 'Receipt or x402 authorization timestamp is outside the allowed +/-30s window. Issue a fresh receipt or re-sign with current timestamps.',
|
|
454
|
+
};
|
|
455
|
+
case 'NONCE_REPLAYED':
|
|
456
|
+
case 'nonce_replayed':
|
|
457
|
+
case 'nonce_already_used':
|
|
458
|
+
return {
|
|
459
|
+
code: 'NONCE_REPLAYED',
|
|
460
|
+
fix_hint: 'This payment nonce/jti was already redeemed. Generate a new unique nonce or request a fresh receipt before retrying.',
|
|
461
|
+
};
|
|
462
|
+
case 'agent_spend_cap_exceeded':
|
|
463
|
+
return {
|
|
464
|
+
code: 'SPEND_CAP_EXCEEDED',
|
|
465
|
+
fix_hint: 'Per-agent spend cap reached. Increase perAgentSpendCapMicros or daily_spend_cap_micros on the wallet before retrying.',
|
|
466
|
+
};
|
|
467
|
+
case 'pro_pass_required_for_upto':
|
|
468
|
+
return {
|
|
469
|
+
code: 'PRO_PASS_REQUIRED',
|
|
470
|
+
fix_hint: 'The metered upto scheme requires Tollbooth Pro Pass. Set proPass: true (or switch the route scheme to "exact").',
|
|
471
|
+
};
|
|
472
|
+
case 'facilitator_verify_http_error':
|
|
473
|
+
case 'facilitator_settlement_failed':
|
|
474
|
+
case 'facilitator_settlement_rejected':
|
|
475
|
+
case 'facilitator_unreachable':
|
|
476
|
+
case 'fiat_wallet_not_enabled':
|
|
477
|
+
case 'hmac_verifier_not_configured':
|
|
478
|
+
case 'ed25519_verifier_not_configured':
|
|
479
|
+
case 'signature_verification_error':
|
|
480
|
+
return {
|
|
481
|
+
code: 'FACILITATOR_ERROR',
|
|
482
|
+
fix_hint: 'Verify facilitatorUrl and RECEIPT_SIGNING_SECRET / ed25519PublicKey configuration, or pass mode: "sandbox" for zero-config local testing.',
|
|
483
|
+
};
|
|
484
|
+
default:
|
|
485
|
+
return {
|
|
486
|
+
code: 'INVALID_SIGNATURE',
|
|
487
|
+
fix_hint: `Signature or payload validation failed (${errorReason}). Verify payload formatting, signing key, network, payTo, and audience (${expectedAudience}).`,
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
function escapeHtml(text) {
|
|
492
|
+
return text
|
|
493
|
+
.replace(/&/g, '&')
|
|
494
|
+
.replace(/</g, '<')
|
|
495
|
+
.replace(/>/g, '>')
|
|
496
|
+
.replace(/"/g, '"')
|
|
497
|
+
.replace(/'/g, ''');
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Self-contained Red Center Studio HTML 402 Checkout Card rendered when
|
|
501
|
+
* a browser sends `Accept: text/html` to a gated endpoint.
|
|
502
|
+
*/
|
|
503
|
+
export function renderDefault402HtmlPage(challenge, request) {
|
|
504
|
+
const url = new URL(request.url);
|
|
505
|
+
const accept = challenge.accepts[0];
|
|
506
|
+
const amountAtomic = accept?.amount ?? String(challenge.priceMicros);
|
|
507
|
+
const payTo = accept?.payTo ?? DEFAULT_PAY_TO;
|
|
508
|
+
const network = accept?.network ?? DEFAULT_NETWORK;
|
|
509
|
+
const scheme = accept?.scheme ?? 'exact';
|
|
510
|
+
const railsText = challenge.acceptedRails.includes('rcs-fiat-wallet')
|
|
511
|
+
? 'x402 V2 (USDC) + Red Center Fiat Wallet'
|
|
512
|
+
: 'x402 V2 (USDC)';
|
|
513
|
+
const safeCurl = `curl -H "PAYMENT-SIGNATURE: <base64_x402_v2>" "${request.url}"\ncurl -H "Authorization: Bearer rcs_receipt_..." "${request.url}"\n# payTo: ${payTo}`;
|
|
514
|
+
return `<!DOCTYPE html>
|
|
515
|
+
<html lang="en">
|
|
516
|
+
<head>
|
|
517
|
+
<meta charset="utf-8" />
|
|
518
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
519
|
+
<meta name="theme-color" content="#24181a" />
|
|
520
|
+
<title>402 Payment Required — Agent Tollbooth 402 | Red Center Studio</title>
|
|
521
|
+
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
522
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
523
|
+
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Archivo:wght@700;800&family=IBM+Plex+Mono:wght@500&family=IBM+Plex+Sans:wght@400;500;600;700&display=swap" />
|
|
524
|
+
<style>
|
|
525
|
+
:root {
|
|
526
|
+
--ironstone: #24181a;
|
|
527
|
+
--ironstone-2: #32211f;
|
|
528
|
+
--ochre: #d9622b;
|
|
529
|
+
--ochre-deep: #a63d14;
|
|
530
|
+
--oxide: #7a2e1d;
|
|
531
|
+
--spinifex: #e3a23c;
|
|
532
|
+
--gum: #4f7f63;
|
|
533
|
+
--sand: #f5efe6;
|
|
534
|
+
--card: #fffcf8;
|
|
535
|
+
--line: #e3d7c8;
|
|
536
|
+
--ink: #2a1a16;
|
|
537
|
+
--muted: #6b5a52;
|
|
538
|
+
--on-dark: #f3e9de;
|
|
539
|
+
--on-dark-muted: #cbb9ab;
|
|
540
|
+
--display: "Archivo", "Helvetica Neue", Arial, sans-serif;
|
|
541
|
+
--body: "IBM Plex Sans", "Segoe UI", system-ui, sans-serif;
|
|
542
|
+
--mono: "IBM Plex Mono", ui-monospace, Menlo, monospace;
|
|
543
|
+
}
|
|
544
|
+
* { box-sizing: border-box; }
|
|
545
|
+
html { -webkit-text-size-adjust: 100%; }
|
|
546
|
+
body {
|
|
547
|
+
margin: 0;
|
|
548
|
+
min-height: 100vh;
|
|
549
|
+
display: flex;
|
|
550
|
+
flex-direction: column;
|
|
551
|
+
background: var(--sand);
|
|
552
|
+
color: var(--ink);
|
|
553
|
+
font: 400 16px/1.6 var(--body);
|
|
554
|
+
}
|
|
555
|
+
a { color: var(--ochre-deep); }
|
|
556
|
+
.site-head { background: var(--ironstone); color: var(--on-dark); }
|
|
557
|
+
.head-wrap {
|
|
558
|
+
max-width: 760px;
|
|
559
|
+
margin: 0 auto;
|
|
560
|
+
padding: 14px 20px;
|
|
561
|
+
display: flex;
|
|
562
|
+
align-items: center;
|
|
563
|
+
justify-content: space-between;
|
|
564
|
+
gap: 14px;
|
|
565
|
+
flex-wrap: wrap;
|
|
566
|
+
}
|
|
567
|
+
.brand {
|
|
568
|
+
display: inline-flex;
|
|
569
|
+
align-items: center;
|
|
570
|
+
gap: 10px;
|
|
571
|
+
font: 500 12px/1 var(--mono);
|
|
572
|
+
letter-spacing: 0.16em;
|
|
573
|
+
text-transform: uppercase;
|
|
574
|
+
color: var(--on-dark);
|
|
575
|
+
text-decoration: none;
|
|
576
|
+
}
|
|
577
|
+
.brand::before {
|
|
578
|
+
content: "";
|
|
579
|
+
width: 22px;
|
|
580
|
+
height: 22px;
|
|
581
|
+
flex: none;
|
|
582
|
+
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 22 22'%3E%3CclipPath id='s'%3E%3Ccircle cx='11' cy='11' r='11'/%3E%3C/clipPath%3E%3Cg clip-path='url(%23s)'%3E%3Crect width='22' height='12.5' fill='%23d9622b'/%3E%3Crect y='14.5' width='22' height='2.5' fill='%23d9622b'/%3E%3Crect y='19' width='22' height='2.5' fill='%23a63d14'/%3E%3C/g%3E%3C/svg%3E") center / contain no-repeat;
|
|
583
|
+
}
|
|
584
|
+
.head-link {
|
|
585
|
+
font: 600 14px/1 var(--body);
|
|
586
|
+
color: var(--spinifex);
|
|
587
|
+
text-decoration: none;
|
|
588
|
+
}
|
|
589
|
+
.head-link:hover { text-decoration: underline; }
|
|
590
|
+
.strata {
|
|
591
|
+
display: block;
|
|
592
|
+
height: 8px;
|
|
593
|
+
background: linear-gradient(to bottom, var(--oxide) 0 25%, var(--ochre-deep) 25% 50%, var(--ochre) 50% 75%, var(--spinifex) 75% 100%);
|
|
594
|
+
}
|
|
595
|
+
.stage {
|
|
596
|
+
flex: 1;
|
|
597
|
+
display: flex;
|
|
598
|
+
align-items: center;
|
|
599
|
+
justify-content: center;
|
|
600
|
+
padding: 18px 20px 24px;
|
|
601
|
+
}
|
|
602
|
+
@keyframes cardRise {
|
|
603
|
+
from { opacity: 0; transform: translateY(10px); }
|
|
604
|
+
to { opacity: 1; transform: translateY(0); }
|
|
605
|
+
}
|
|
606
|
+
@keyframes softPulse {
|
|
607
|
+
0%, 100% { box-shadow: 0 0 0 0 rgba(79, 127, 99, 0.35); }
|
|
608
|
+
50% { box-shadow: 0 0 0 5px rgba(79, 127, 99, 0); }
|
|
609
|
+
}
|
|
610
|
+
.card {
|
|
611
|
+
width: 100%;
|
|
612
|
+
max-width: 650px;
|
|
613
|
+
background: var(--card);
|
|
614
|
+
border: 1px solid var(--line);
|
|
615
|
+
border-top: 3px solid var(--ochre);
|
|
616
|
+
border-radius: 2px;
|
|
617
|
+
padding: 20px 24px;
|
|
618
|
+
box-shadow: 0 14px 36px rgba(36, 24, 26, 0.11);
|
|
619
|
+
animation: cardRise 0.35s ease-out both;
|
|
620
|
+
}
|
|
621
|
+
.badges { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin-bottom: 10px; }
|
|
622
|
+
.badge {
|
|
623
|
+
display: inline-flex;
|
|
624
|
+
align-items: center;
|
|
625
|
+
gap: 6px;
|
|
626
|
+
padding: 4px 9px;
|
|
627
|
+
border: 1px solid;
|
|
628
|
+
border-radius: 2px;
|
|
629
|
+
font: 500 11.5px/1.2 var(--mono);
|
|
630
|
+
letter-spacing: 0.1em;
|
|
631
|
+
text-transform: uppercase;
|
|
632
|
+
}
|
|
633
|
+
.badge-ochre { background: #fbeee4; color: var(--ochre-deep); border-color: var(--ochre-deep); }
|
|
634
|
+
.badge-gum { background: #eaf2ec; color: #2f5a41; border-color: var(--gum); }
|
|
635
|
+
.dot {
|
|
636
|
+
width: 6px;
|
|
637
|
+
height: 6px;
|
|
638
|
+
border-radius: 50%;
|
|
639
|
+
background: var(--gum);
|
|
640
|
+
display: inline-block;
|
|
641
|
+
animation: softPulse 2.2s ease-in-out infinite;
|
|
642
|
+
}
|
|
643
|
+
h1 {
|
|
644
|
+
margin: 0 0 4px;
|
|
645
|
+
font: 800 clamp(24px, 3.8vw, 31px)/1.08 var(--display);
|
|
646
|
+
letter-spacing: -0.02em;
|
|
647
|
+
color: var(--ink);
|
|
648
|
+
}
|
|
649
|
+
.desc { margin: 0 0 12px; color: var(--muted); font-size: 15px; line-height: 1.45; }
|
|
650
|
+
.facts {
|
|
651
|
+
display: grid;
|
|
652
|
+
grid-template-columns: repeat(2, minmax(0, 1fr));
|
|
653
|
+
gap: 8px 18px;
|
|
654
|
+
margin-bottom: 11px;
|
|
655
|
+
padding: 11px 14px;
|
|
656
|
+
background: var(--sand);
|
|
657
|
+
border: 1px solid var(--line);
|
|
658
|
+
border-radius: 2px;
|
|
659
|
+
}
|
|
660
|
+
.fact-wide { grid-column: 1 / -1; padding-top: 8px; border-top: 1px solid var(--line); }
|
|
661
|
+
.label {
|
|
662
|
+
font: 500 11.5px/1.4 var(--mono);
|
|
663
|
+
letter-spacing: 0.14em;
|
|
664
|
+
text-transform: uppercase;
|
|
665
|
+
color: var(--ochre-deep);
|
|
666
|
+
}
|
|
667
|
+
.val {
|
|
668
|
+
font-size: 14.5px;
|
|
669
|
+
font-weight: 600;
|
|
670
|
+
color: var(--ink);
|
|
671
|
+
overflow-wrap: anywhere;
|
|
672
|
+
margin-top: 2px;
|
|
673
|
+
font-variant-numeric: tabular-nums;
|
|
674
|
+
}
|
|
675
|
+
.price {
|
|
676
|
+
font: 800 24px/1.1 var(--display);
|
|
677
|
+
letter-spacing: -0.02em;
|
|
678
|
+
color: var(--ink);
|
|
679
|
+
font-variant-numeric: tabular-nums;
|
|
680
|
+
}
|
|
681
|
+
.hint {
|
|
682
|
+
background: #fbeee4;
|
|
683
|
+
border-left: 3px solid var(--ochre);
|
|
684
|
+
padding: 9px 13px;
|
|
685
|
+
border-radius: 2px;
|
|
686
|
+
font-size: 13.5px;
|
|
687
|
+
line-height: 1.45;
|
|
688
|
+
color: var(--ink);
|
|
689
|
+
margin-bottom: 11px;
|
|
690
|
+
overflow-wrap: anywhere;
|
|
691
|
+
}
|
|
692
|
+
.rails {
|
|
693
|
+
display: grid;
|
|
694
|
+
grid-template-columns: repeat(2, minmax(0, 1fr));
|
|
695
|
+
gap: 10px;
|
|
696
|
+
margin-bottom: 11px;
|
|
697
|
+
}
|
|
698
|
+
.rail-box {
|
|
699
|
+
padding: 11px 13px;
|
|
700
|
+
background: #fff;
|
|
701
|
+
border: 1px solid var(--line);
|
|
702
|
+
border-left: 3px solid var(--spinifex);
|
|
703
|
+
border-radius: 2px;
|
|
704
|
+
transition: transform 0.15s ease, border-color 0.15s ease;
|
|
705
|
+
}
|
|
706
|
+
.rail-box:hover {
|
|
707
|
+
transform: translateY(-1px);
|
|
708
|
+
border-color: #d6c4b0;
|
|
709
|
+
border-left-color: var(--ochre);
|
|
710
|
+
}
|
|
711
|
+
.rail-box h2 {
|
|
712
|
+
margin: 0 0 3px;
|
|
713
|
+
font: 700 14.5px/1.25 var(--body);
|
|
714
|
+
color: var(--ink);
|
|
715
|
+
}
|
|
716
|
+
.rail-box p {
|
|
717
|
+
margin: 0;
|
|
718
|
+
font-size: 13px;
|
|
719
|
+
line-height: 1.4;
|
|
720
|
+
color: var(--muted);
|
|
721
|
+
overflow-wrap: anywhere;
|
|
722
|
+
}
|
|
723
|
+
.code-shell {
|
|
724
|
+
border: 1px solid #3c2a27;
|
|
725
|
+
border-radius: 2px;
|
|
726
|
+
overflow: hidden;
|
|
727
|
+
margin-bottom: 13px;
|
|
728
|
+
background: var(--ironstone);
|
|
729
|
+
}
|
|
730
|
+
.code-bar {
|
|
731
|
+
display: flex;
|
|
732
|
+
align-items: center;
|
|
733
|
+
justify-content: space-between;
|
|
734
|
+
gap: 10px;
|
|
735
|
+
padding: 7px 12px;
|
|
736
|
+
background: #1a1112;
|
|
737
|
+
border-bottom: 1px solid rgba(243, 233, 222, 0.12);
|
|
738
|
+
}
|
|
739
|
+
.code-title {
|
|
740
|
+
display: inline-flex;
|
|
741
|
+
align-items: center;
|
|
742
|
+
gap: 8px;
|
|
743
|
+
font: 500 11px/1 var(--mono);
|
|
744
|
+
letter-spacing: 0.12em;
|
|
745
|
+
text-transform: uppercase;
|
|
746
|
+
color: var(--on-dark-muted);
|
|
747
|
+
}
|
|
748
|
+
.term-dots { display: inline-flex; gap: 5px; }
|
|
749
|
+
.term-dots i { width: 7px; height: 7px; border-radius: 50%; background: rgba(243, 233, 222, 0.3); display: inline-block; }
|
|
750
|
+
.term-dots i:first-child { background: var(--ochre); }
|
|
751
|
+
.term-dots i:nth-child(2) { background: var(--spinifex); }
|
|
752
|
+
.code {
|
|
753
|
+
background: var(--ironstone);
|
|
754
|
+
color: var(--on-dark);
|
|
755
|
+
padding: 11px 13px;
|
|
756
|
+
font: 500 12px/1.45 var(--mono);
|
|
757
|
+
white-space: pre-wrap;
|
|
758
|
+
overflow-wrap: anywhere;
|
|
759
|
+
margin: 0;
|
|
760
|
+
}
|
|
761
|
+
.copy-btn {
|
|
762
|
+
min-height: 26px;
|
|
763
|
+
padding: 3px 11px;
|
|
764
|
+
background: var(--card);
|
|
765
|
+
color: var(--ink);
|
|
766
|
+
border: 1px solid var(--line);
|
|
767
|
+
border-radius: 2px;
|
|
768
|
+
font: 600 12px/1 var(--body);
|
|
769
|
+
cursor: pointer;
|
|
770
|
+
}
|
|
771
|
+
.copy-btn:hover { background: var(--spinifex); border-color: var(--spinifex); }
|
|
772
|
+
.sim-banner {
|
|
773
|
+
display: none;
|
|
774
|
+
margin-bottom: 12px;
|
|
775
|
+
padding: 10px 13px;
|
|
776
|
+
background: #eaf2ec;
|
|
777
|
+
border: 1px solid #b8d3c1;
|
|
778
|
+
border-left: 3px solid var(--gum);
|
|
779
|
+
border-radius: 2px;
|
|
780
|
+
font: 500 12.5px/1.45 var(--mono);
|
|
781
|
+
color: #214530;
|
|
782
|
+
overflow-wrap: anywhere;
|
|
783
|
+
animation: cardRise 0.25s ease-out both;
|
|
784
|
+
}
|
|
785
|
+
.sim-banner.show { display: block; }
|
|
786
|
+
.actions { display: flex; gap: 9px; flex-wrap: wrap; align-items: center; }
|
|
787
|
+
.btn {
|
|
788
|
+
display: inline-flex;
|
|
789
|
+
align-items: center;
|
|
790
|
+
justify-content: center;
|
|
791
|
+
text-align: center;
|
|
792
|
+
min-height: 44px;
|
|
793
|
+
padding: 9px 18px;
|
|
794
|
+
border: 1px solid transparent;
|
|
795
|
+
border-radius: 2px;
|
|
796
|
+
font: 600 14.5px/1.2 var(--body);
|
|
797
|
+
text-decoration: none;
|
|
798
|
+
cursor: pointer;
|
|
799
|
+
transition: background 0.15s, color 0.15s, border-color 0.15s;
|
|
800
|
+
}
|
|
801
|
+
.btn-primary { background: var(--ochre); color: #1e1412; }
|
|
802
|
+
.btn-primary:hover { background: var(--spinifex); }
|
|
803
|
+
.btn-ghost { background: transparent; color: var(--ink); border-color: var(--ink); }
|
|
804
|
+
.btn-ghost:hover { background: var(--ink); color: var(--sand); }
|
|
805
|
+
.btn-sand { background: var(--sand); color: var(--ink); border-color: #b9a898; }
|
|
806
|
+
.btn-sand:hover { border-color: var(--ochre-deep); background: #fbeee4; }
|
|
807
|
+
.meta-foot {
|
|
808
|
+
margin-top: 11px;
|
|
809
|
+
font: 400 12.5px/1.4 var(--body);
|
|
810
|
+
color: var(--muted);
|
|
811
|
+
}
|
|
812
|
+
@media (prefers-reduced-motion: reduce) { .card, .dot, .sim-banner { animation: none; } }
|
|
813
|
+
@media (max-width: 640px) {
|
|
814
|
+
.stage { padding: 18px 14px 32px; align-items: flex-start; }
|
|
815
|
+
.card { padding: 18px 16px; }
|
|
816
|
+
.facts, .rails { grid-template-columns: 1fr; gap: 10px; }
|
|
817
|
+
.actions { flex-direction: column; align-items: stretch; }
|
|
818
|
+
.btn { width: 100%; min-height: 48px; }
|
|
819
|
+
}
|
|
820
|
+
</style>
|
|
821
|
+
</head>
|
|
822
|
+
<body>
|
|
823
|
+
<header class="site-head">
|
|
824
|
+
<div class="head-wrap">
|
|
825
|
+
<a class="brand" href="https://redcenterstudio.com/" rel="noopener noreferrer">Red Center Studio</a>
|
|
826
|
+
<a class="head-link" href="${escapeHtml(challenge.paymentUrl)}" rel="noopener noreferrer">Clearinghouse Portal</a>
|
|
827
|
+
</div>
|
|
828
|
+
<span class="strata" aria-hidden="true"></span>
|
|
829
|
+
</header>
|
|
830
|
+
<main class="stage">
|
|
831
|
+
<article class="card">
|
|
832
|
+
<div class="badges">
|
|
833
|
+
<span class="badge badge-ochre">HTTP 402 · ${escapeHtml(challenge.code)}</span>
|
|
834
|
+
<span class="badge badge-gum"><span class="dot"></span>${escapeHtml(railsText)}</span>
|
|
835
|
+
</div>
|
|
836
|
+
<h1>402 Payment Required</h1>
|
|
837
|
+
<p class="desc">${escapeHtml(challenge.resource.description)}</p>
|
|
838
|
+
<div class="facts">
|
|
839
|
+
<div>
|
|
840
|
+
<div class="label">Endpoint</div>
|
|
841
|
+
<div class="val">${escapeHtml(request.method.toUpperCase())} ${escapeHtml(url.pathname)}</div>
|
|
842
|
+
</div>
|
|
843
|
+
<div>
|
|
844
|
+
<div class="label">Price (${escapeHtml(scheme)})</div>
|
|
845
|
+
<div class="val price">$${escapeHtml(challenge.priceUsd)} USD</div>
|
|
846
|
+
</div>
|
|
847
|
+
<div class="fact-wide">
|
|
848
|
+
<div class="label">x402 Settlement Destination</div>
|
|
849
|
+
<div class="val">${escapeHtml(network)} · ${escapeHtml(amountAtomic)} USDC · payTo <code>${escapeHtml(payTo)}</code></div>
|
|
850
|
+
</div>
|
|
851
|
+
</div>
|
|
852
|
+
<div class="rails">
|
|
853
|
+
<div class="rail-box">
|
|
854
|
+
<h2>Pay with Fiat Agent Wallet</h2>
|
|
855
|
+
<p>Top up with Stripe on Red Center Studio and pass a prepaid <code>rcs_receipt_...</code> bearer token for <1ms edge verification.</p>
|
|
856
|
+
</div>
|
|
857
|
+
<div class="rail-box">
|
|
858
|
+
<h2>Pay with Crypto (x402 V2)</h2>
|
|
859
|
+
<p>Sign a Base USDC payment payload on <code>${escapeHtml(network)}</code> to <code>${escapeHtml(payTo)}</code> and retry with <code>PAYMENT-SIGNATURE</code>.</p>
|
|
860
|
+
</div>
|
|
861
|
+
</div>
|
|
862
|
+
<div class="hint"><strong>Next step:</strong> ${escapeHtml(challenge.fix_hint)}</div>
|
|
863
|
+
<div class="code-shell">
|
|
864
|
+
<div class="code-bar">
|
|
865
|
+
<span class="code-title"><span class="term-dots"><i></i><i></i><i></i></span>HTTP 402 Retry Snippet · x402 V2 & Bearer Receipt</span>
|
|
866
|
+
<button class="copy-btn" type="button" onclick="var b=this;navigator.clipboard&&navigator.clipboard.writeText(document.getElementById('curl-cmd').textContent).then(function(){b.textContent='Copied';b.style.borderColor='#4f7f63';b.style.color='#2f5a41';setTimeout(function(){b.textContent='Copy';b.style.borderColor='';b.style.color='';},1500);})">Copy</button>
|
|
867
|
+
</div>
|
|
868
|
+
<pre class="code" id="curl-cmd">${escapeHtml(safeCurl)}</pre>
|
|
869
|
+
</div>
|
|
870
|
+
<div id="retry-status" class="sim-banner" role="status" aria-live="polite"></div>
|
|
871
|
+
<div class="actions">
|
|
872
|
+
<a class="btn btn-primary" href="${escapeHtml(challenge.paymentUrl)}" rel="noopener noreferrer">Fund Agent Wallet</a>
|
|
873
|
+
<button id="sim-retry-btn" class="btn btn-sand" type="button" onclick="var b=this,s=document.getElementById('retry-status');b.disabled=true;b.textContent='Verifying...';s.className='sim-banner show';s.textContent='Signing sandbox rcs_receipt_... via Web Crypto HMAC-SHA256...';setTimeout(function(){b.disabled=false;b.textContent='Verified (200 OK)';s.textContent='[200 SETTLED] Edge HMAC check passed in 0.4ms | PAYMENT-RESPONSE verified | ${escapeHtml(request.method.toUpperCase())} ${escapeHtml(url.pathname)} unlocked ($${escapeHtml(challenge.priceUsd)} USD)';},320);">Simulate <1ms Receipt Retry</button>
|
|
874
|
+
<a class="btn btn-ghost" href="https://redcenterstudio.com/services/ai-tollbooth-setup/" rel="noopener noreferrer">See AI Tollbooth Setup</a>
|
|
875
|
+
</div>
|
|
876
|
+
<p class="meta-foot">Powered by Agent Tollbooth 402 · <a href="https://redcenterstudio.com/" rel="noopener noreferrer">Red Center Studio</a></p>
|
|
877
|
+
</article>
|
|
878
|
+
</main>
|
|
879
|
+
</body>
|
|
880
|
+
</html>`;
|
|
881
|
+
}
|
|
882
|
+
function matchPathPattern(pattern, pathname) {
|
|
883
|
+
if (pattern === '*' || pattern === '/*') {
|
|
884
|
+
return true;
|
|
885
|
+
}
|
|
886
|
+
if (pattern.endsWith('/*')) {
|
|
887
|
+
const prefix = pattern.slice(0, -1);
|
|
888
|
+
return pathname === pattern.slice(0, -2) || pathname.startsWith(prefix);
|
|
889
|
+
}
|
|
890
|
+
const patternParts = pattern.split('/').filter(Boolean);
|
|
891
|
+
const pathParts = pathname.split('/').filter(Boolean);
|
|
892
|
+
if (patternParts.length !== pathParts.length) {
|
|
893
|
+
return false;
|
|
894
|
+
}
|
|
895
|
+
for (let i = 0; i < patternParts.length; i++) {
|
|
896
|
+
const seg = patternParts[i];
|
|
897
|
+
if (seg === '*') {
|
|
898
|
+
continue;
|
|
899
|
+
}
|
|
900
|
+
if (seg.startsWith(':')) {
|
|
901
|
+
if (!pathParts[i]) {
|
|
902
|
+
return false;
|
|
903
|
+
}
|
|
904
|
+
continue;
|
|
905
|
+
}
|
|
906
|
+
if (seg !== pathParts[i]) {
|
|
907
|
+
return false;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
return true;
|
|
911
|
+
}
|
|
912
|
+
function isMethodMatch(routeMethod, reqMethod) {
|
|
913
|
+
if (!routeMethod) {
|
|
914
|
+
return true;
|
|
915
|
+
}
|
|
916
|
+
const upper = reqMethod.toUpperCase();
|
|
917
|
+
if (Array.isArray(routeMethod)) {
|
|
918
|
+
return routeMethod.some((m) => m.toUpperCase() === upper || m === '*');
|
|
919
|
+
}
|
|
920
|
+
return routeMethod === '*' || routeMethod.toUpperCase() === upper;
|
|
921
|
+
}
|
|
922
|
+
function extractFiatReceiptToken(request) {
|
|
923
|
+
const custom = request.headers.get('X-Agent-Receipt');
|
|
924
|
+
if (custom) {
|
|
925
|
+
const trimmed = custom.trim();
|
|
926
|
+
if (trimmed.startsWith('rcs_receipt_')) {
|
|
927
|
+
return trimmed;
|
|
928
|
+
}
|
|
929
|
+
const customBearer = /^Bearer\s+(rcs_receipt_\S+)$/i.exec(trimmed);
|
|
930
|
+
if (customBearer?.[1]) {
|
|
931
|
+
return customBearer[1];
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
const auth = request.headers.get('Authorization');
|
|
935
|
+
if (auth) {
|
|
936
|
+
const match = /^Bearer\s+(rcs_receipt_\S+)$/i.exec(auth.trim());
|
|
937
|
+
if (match?.[1]) {
|
|
938
|
+
return match[1];
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
return null;
|
|
942
|
+
}
|
|
943
|
+
function createSandboxFacilitatorFetch() {
|
|
944
|
+
return async (input, init) => {
|
|
945
|
+
const url = typeof input === 'string' ? input : input.toString();
|
|
946
|
+
const rawBody = init?.body ? String(init.body) : '{}';
|
|
947
|
+
const body = JSON.parse(rawBody);
|
|
948
|
+
if (url.endsWith('/verify')) {
|
|
949
|
+
const ok = body.paymentPayload?.x402Version === 2 &&
|
|
950
|
+
Boolean(body.paymentPayload?.payload?.signature) &&
|
|
951
|
+
Boolean(body.paymentPayload?.payload?.authorization?.nonce);
|
|
952
|
+
return Response.json({
|
|
953
|
+
isValid: ok,
|
|
954
|
+
invalidReason: ok ? null : 'invalid_sandbox_payload',
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
if (url.endsWith('/settle')) {
|
|
958
|
+
const nonce = body.paymentPayload?.payload?.authorization?.nonce ?? 'sandbox';
|
|
959
|
+
return Response.json({
|
|
960
|
+
success: true,
|
|
961
|
+
txHash: `0xsandbox_${nonce.replace(/^0x/, '').slice(0, 32)}`,
|
|
962
|
+
network: body.paymentRequirements?.network ?? DEFAULT_NETWORK,
|
|
963
|
+
settledAmount: body.settleAmount ?? body.paymentRequirements?.amount ?? '10000',
|
|
964
|
+
errorReason: null,
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
return Response.json({ error: 'unsupported_sandbox_route' }, { status: 404 });
|
|
968
|
+
};
|
|
969
|
+
}
|
|
970
|
+
function normalizeConfig(config) {
|
|
971
|
+
const mode = config.mode ?? 'hybrid';
|
|
972
|
+
const defaultMicros = config.priceMicros ??
|
|
973
|
+
(config.priceUsd !== undefined ? usdToMicros(config.priceUsd) : usdToMicros(DEFAULT_PRICE_USD));
|
|
974
|
+
const payTo = config.payTo ?? DEFAULT_PAY_TO;
|
|
975
|
+
const isSandbox = mode === 'sandbox' || mode === 'mock';
|
|
976
|
+
const fiatWallet = isSandbox
|
|
977
|
+
? {
|
|
978
|
+
clearinghouseUrl: config.fiatWallet?.clearinghouseUrl ??
|
|
979
|
+
config.facilitatorUrl ??
|
|
980
|
+
`${DEFAULT_FACILITATOR_URL}/sandbox`,
|
|
981
|
+
clockSkewSeconds: config.fiatWallet?.clockSkewSeconds ??
|
|
982
|
+
config.clockSkewSeconds ??
|
|
983
|
+
DEFAULT_CLOCK_SKEW_SECONDS,
|
|
984
|
+
...config.fiatWallet,
|
|
985
|
+
hmacSecret: config.fiatWallet?.hmacSecret ?? SANDBOX_HMAC_SECRET,
|
|
986
|
+
}
|
|
987
|
+
: config.fiatWallet;
|
|
988
|
+
const rawRoutes = config.routes && config.routes.length > 0
|
|
989
|
+
? config.routes
|
|
990
|
+
: [{ pattern: '/*', scheme: 'exact', priceMicros: defaultMicros }];
|
|
991
|
+
const normalizedRoutes = rawRoutes.map((r) => ({
|
|
992
|
+
...r,
|
|
993
|
+
resolvedPriceMicros: r.priceMicros ??
|
|
994
|
+
(r.priceUsd !== undefined ? usdToMicros(r.priceUsd) : defaultMicros),
|
|
995
|
+
}));
|
|
996
|
+
return {
|
|
997
|
+
...config,
|
|
998
|
+
payTo,
|
|
999
|
+
mode,
|
|
1000
|
+
clockSkewSeconds: config.clockSkewSeconds ?? DEFAULT_CLOCK_SKEW_SECONDS,
|
|
1001
|
+
fiatWallet,
|
|
1002
|
+
fetchImpl: config.fetchImpl ?? (isSandbox ? createSandboxFacilitatorFetch() : undefined),
|
|
1003
|
+
normalizedRoutes,
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
function buildPaymentRequiredChallenge(request, config, route, errorReason) {
|
|
1007
|
+
const scheme = route.scheme ?? 'exact';
|
|
1008
|
+
const network = route.network ?? config.network ?? DEFAULT_NETWORK;
|
|
1009
|
+
const asset = route.asset ?? config.asset ?? DEFAULT_USDC_BASE_ASSET;
|
|
1010
|
+
const payTo = route.payTo ?? config.payTo;
|
|
1011
|
+
const maxTimeoutSeconds = route.maxTimeoutSeconds ?? 60;
|
|
1012
|
+
const priceMicros = route.resolvedPriceMicros;
|
|
1013
|
+
const amount = usdMicrosToUsdcAtomic(priceMicros);
|
|
1014
|
+
const paymentUrl = config.paymentUrl ?? DEFAULT_PAYMENT_URL;
|
|
1015
|
+
const guidance = resolveErrorGuidance(errorReason, priceMicros, request.url);
|
|
1016
|
+
const acceptedRails = config.fiatWallet
|
|
1017
|
+
? ['x402-v2', 'rcs-fiat-wallet']
|
|
1018
|
+
: ['x402-v2'];
|
|
1019
|
+
const extensions = {};
|
|
1020
|
+
if (config.fiatWallet) {
|
|
1021
|
+
extensions.fiatAgentWallet = {
|
|
1022
|
+
clearinghouseUrl: config.fiatWallet.clearinghouseUrl ?? config.facilitatorUrl ?? DEFAULT_FACILITATOR_URL,
|
|
1023
|
+
headers: ['Authorization: Bearer rcs_receipt_...', 'X-Agent-Receipt'],
|
|
1024
|
+
priceMicros,
|
|
1025
|
+
currency: 'USD_MICROS',
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
return {
|
|
1029
|
+
x402Version: 2,
|
|
1030
|
+
code: guidance.code,
|
|
1031
|
+
error: errorReason,
|
|
1032
|
+
fix_hint: guidance.fix_hint,
|
|
1033
|
+
priceUsd: microsToUsdString(priceMicros),
|
|
1034
|
+
priceMicros,
|
|
1035
|
+
acceptedRails,
|
|
1036
|
+
paymentUrl,
|
|
1037
|
+
resource: {
|
|
1038
|
+
url: request.url,
|
|
1039
|
+
description: route.description ?? `Paid API resource (${request.method} ${new URL(request.url).pathname})`,
|
|
1040
|
+
mimeType: route.mimeType ?? 'application/json',
|
|
1041
|
+
},
|
|
1042
|
+
accepts: [
|
|
1043
|
+
{
|
|
1044
|
+
scheme,
|
|
1045
|
+
network,
|
|
1046
|
+
amount,
|
|
1047
|
+
asset,
|
|
1048
|
+
payTo,
|
|
1049
|
+
maxTimeoutSeconds,
|
|
1050
|
+
extra: usdcEip712Extra(network),
|
|
1051
|
+
},
|
|
1052
|
+
],
|
|
1053
|
+
extensions,
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
function create402Response(request, config, challenge) {
|
|
1057
|
+
const encodedRequired = encodePaymentHeader(challenge);
|
|
1058
|
+
const headers = new Headers({
|
|
1059
|
+
'PAYMENT-REQUIRED': encodedRequired,
|
|
1060
|
+
'WWW-Authenticate': `x402, Bearer realm="agent-tollbooth-402", error="${challenge.code}"`,
|
|
1061
|
+
'Access-Control-Expose-Headers': CORS_EXPOSE_HEADERS,
|
|
1062
|
+
'Cache-Control': 'no-store',
|
|
1063
|
+
});
|
|
1064
|
+
const acceptHeader = request.headers.get('Accept') ?? '';
|
|
1065
|
+
if (acceptHeader.includes('text/html')) {
|
|
1066
|
+
const html = config.proPass && config.customPaymentPageHtml
|
|
1067
|
+
? typeof config.customPaymentPageHtml === 'function'
|
|
1068
|
+
? config.customPaymentPageHtml(challenge, request)
|
|
1069
|
+
: config.customPaymentPageHtml
|
|
1070
|
+
: renderDefault402HtmlPage(challenge, request);
|
|
1071
|
+
headers.set('Content-Type', 'text/html; charset=utf-8');
|
|
1072
|
+
return new Response(html, { status: 402, headers });
|
|
1073
|
+
}
|
|
1074
|
+
headers.set('Content-Type', 'application/json; charset=utf-8');
|
|
1075
|
+
return new Response(JSON.stringify(challenge), { status: 402, headers });
|
|
1076
|
+
}
|
|
1077
|
+
function attachCorsExposeHeaders(response, includePreflight = false) {
|
|
1078
|
+
const headers = new Headers(response.headers);
|
|
1079
|
+
headers.set('Access-Control-Expose-Headers', CORS_EXPOSE_HEADERS);
|
|
1080
|
+
if (includePreflight) {
|
|
1081
|
+
if (!headers.has('Access-Control-Allow-Headers')) {
|
|
1082
|
+
headers.set('Access-Control-Allow-Headers', CORS_ALLOW_HEADERS);
|
|
1083
|
+
}
|
|
1084
|
+
if (!headers.has('Access-Control-Allow-Methods')) {
|
|
1085
|
+
headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
return new Response(response.body, {
|
|
1089
|
+
status: response.status,
|
|
1090
|
+
statusText: response.statusText,
|
|
1091
|
+
headers,
|
|
1092
|
+
});
|
|
1093
|
+
}
|
|
1094
|
+
function cloneWithPaymentResponse(response, paymentResponse, rail) {
|
|
1095
|
+
const headers = new Headers(response.headers);
|
|
1096
|
+
headers.set('PAYMENT-RESPONSE', encodePaymentHeader(paymentResponse));
|
|
1097
|
+
headers.set('X-Tollbooth-Rail', rail);
|
|
1098
|
+
headers.set('Access-Control-Expose-Headers', CORS_EXPOSE_HEADERS);
|
|
1099
|
+
return new Response(response.body, {
|
|
1100
|
+
status: response.status,
|
|
1101
|
+
statusText: response.statusText,
|
|
1102
|
+
headers,
|
|
1103
|
+
});
|
|
1104
|
+
}
|
|
1105
|
+
function parseBigIntAmount(value) {
|
|
1106
|
+
if (!/^\d+$/.test(value)) {
|
|
1107
|
+
return null;
|
|
1108
|
+
}
|
|
1109
|
+
return BigInt(value);
|
|
1110
|
+
}
|
|
1111
|
+
async function evaluateTollboothRequest(request, rawConfig, defaultNonceStore, defaultSpendTracker) {
|
|
1112
|
+
if (request.method.toUpperCase() === 'OPTIONS') {
|
|
1113
|
+
return { isPreflight: true };
|
|
1114
|
+
}
|
|
1115
|
+
const config = normalizeConfig(rawConfig);
|
|
1116
|
+
const url = new URL(request.url);
|
|
1117
|
+
const exemptPaths = config.exemptPaths ?? [...DEFAULT_EXEMPT_PATHS];
|
|
1118
|
+
if (exemptPaths.some((pat) => matchPathPattern(pat, url.pathname))) {
|
|
1119
|
+
return {};
|
|
1120
|
+
}
|
|
1121
|
+
const route = config.normalizedRoutes.find((r) => matchPathPattern(r.pattern, url.pathname) && isMethodMatch(r.method, request.method));
|
|
1122
|
+
if (!route) {
|
|
1123
|
+
return {};
|
|
1124
|
+
}
|
|
1125
|
+
const scheme = route.scheme ?? 'exact';
|
|
1126
|
+
const proPassEnabled = route.proPass ?? config.proPass ?? false;
|
|
1127
|
+
if (scheme === 'upto' && !proPassEnabled) {
|
|
1128
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'pro_pass_required_for_upto');
|
|
1129
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1130
|
+
}
|
|
1131
|
+
const nonceStore = config.nonceStore ?? defaultNonceStore;
|
|
1132
|
+
const spendTracker = config.spendTracker ?? defaultSpendTracker;
|
|
1133
|
+
const nowSec = config.nowSeconds ? config.nowSeconds() : Math.floor(Date.now() / 1000);
|
|
1134
|
+
const requiredMicros = route.resolvedPriceMicros;
|
|
1135
|
+
// Rail B: Red Center Fiat Agent Wallet (<1ms Web Crypto verification)
|
|
1136
|
+
const receiptToken = extractFiatReceiptToken(request);
|
|
1137
|
+
if (receiptToken) {
|
|
1138
|
+
if (!config.fiatWallet) {
|
|
1139
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'fiat_wallet_not_enabled');
|
|
1140
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1141
|
+
}
|
|
1142
|
+
const verifyResult = await verifyFiatReceipt(receiptToken, {
|
|
1143
|
+
...config.fiatWallet,
|
|
1144
|
+
clockSkewSeconds: config.fiatWallet.clockSkewSeconds ?? config.clockSkewSeconds,
|
|
1145
|
+
expectedAudience: request.url,
|
|
1146
|
+
expectedMethod: request.method,
|
|
1147
|
+
requiredMicros,
|
|
1148
|
+
nowSeconds: nowSec,
|
|
1149
|
+
});
|
|
1150
|
+
if (!verifyResult.valid || !verifyResult.claims) {
|
|
1151
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, verifyResult.reason ?? 'invalid_receipt_signature');
|
|
1152
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1153
|
+
}
|
|
1154
|
+
const claims = verifyResult.claims;
|
|
1155
|
+
const consumed = await nonceStore.consume(claims.jti, {
|
|
1156
|
+
walletOrPayer: claims.sub,
|
|
1157
|
+
route: route.pattern,
|
|
1158
|
+
expiresAt: claims.exp,
|
|
1159
|
+
rail: 'fiat_wallet',
|
|
1160
|
+
});
|
|
1161
|
+
if (!consumed) {
|
|
1162
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'nonce_replayed');
|
|
1163
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1164
|
+
}
|
|
1165
|
+
let spendRecorded = false;
|
|
1166
|
+
if (config.perAgentSpendCapMicros !== undefined) {
|
|
1167
|
+
const capCheck = await spendTracker.checkAndRecord(claims.sub, requiredMicros, config.perAgentSpendCapMicros);
|
|
1168
|
+
if (!capCheck.allowed) {
|
|
1169
|
+
if (nonceStore.release) {
|
|
1170
|
+
await nonceStore.release(claims.jti);
|
|
1171
|
+
}
|
|
1172
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'agent_spend_cap_exceeded');
|
|
1173
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1174
|
+
}
|
|
1175
|
+
spendRecorded = true;
|
|
1176
|
+
}
|
|
1177
|
+
return {
|
|
1178
|
+
finalizeResponse: async (downstreamResponse) => {
|
|
1179
|
+
if (downstreamResponse.status >= 500) {
|
|
1180
|
+
if (nonceStore.release) {
|
|
1181
|
+
await nonceStore.release(claims.jti);
|
|
1182
|
+
}
|
|
1183
|
+
if (spendRecorded && spendTracker.rollback) {
|
|
1184
|
+
await spendTracker.rollback(claims.sub, requiredMicros);
|
|
1185
|
+
}
|
|
1186
|
+
return downstreamResponse;
|
|
1187
|
+
}
|
|
1188
|
+
return cloneWithPaymentResponse(downstreamResponse, {
|
|
1189
|
+
success: true,
|
|
1190
|
+
transaction: claims.jti,
|
|
1191
|
+
network: 'rcs:fiat-wallet',
|
|
1192
|
+
payer: claims.sub,
|
|
1193
|
+
settledAmount: String(requiredMicros),
|
|
1194
|
+
rail: 'fiat_wallet',
|
|
1195
|
+
errorReason: null,
|
|
1196
|
+
}, 'fiat_wallet');
|
|
1197
|
+
},
|
|
1198
|
+
};
|
|
1199
|
+
}
|
|
1200
|
+
// Rail A: Open x402 V2 Standard
|
|
1201
|
+
const paymentSigHeader = request.headers.get('PAYMENT-SIGNATURE');
|
|
1202
|
+
if (!paymentSigHeader) {
|
|
1203
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'PAYMENT-SIGNATURE or rcs_receipt bearer header is required');
|
|
1204
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1205
|
+
}
|
|
1206
|
+
let parsedSig;
|
|
1207
|
+
try {
|
|
1208
|
+
parsedSig = decodePaymentHeader(paymentSigHeader);
|
|
1209
|
+
}
|
|
1210
|
+
catch {
|
|
1211
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'malformed_payment_signature');
|
|
1212
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1213
|
+
}
|
|
1214
|
+
const sigScheme = parsedSig.accepted?.scheme ?? parsedSig.scheme;
|
|
1215
|
+
const sigNetwork = parsedSig.accepted?.network ?? parsedSig.network;
|
|
1216
|
+
const expectedNetwork = route.network ?? config.network ?? DEFAULT_NETWORK;
|
|
1217
|
+
const expectedAsset = route.asset ?? config.asset ?? DEFAULT_USDC_BASE_ASSET;
|
|
1218
|
+
const expectedPayTo = route.payTo ?? config.payTo;
|
|
1219
|
+
const requiredAtomicStr = usdMicrosToUsdcAtomic(requiredMicros);
|
|
1220
|
+
const requiredAtomic = BigInt(requiredAtomicStr);
|
|
1221
|
+
if (parsedSig.x402Version !== 2 || !parsedSig.payload?.authorization || !parsedSig.payload?.signature) {
|
|
1222
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'invalid_x402_payload');
|
|
1223
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1224
|
+
}
|
|
1225
|
+
if (sigScheme !== scheme) {
|
|
1226
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'scheme_mismatch');
|
|
1227
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1228
|
+
}
|
|
1229
|
+
if (sigNetwork !== expectedNetwork) {
|
|
1230
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'network_mismatch');
|
|
1231
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1232
|
+
}
|
|
1233
|
+
const auth = parsedSig.payload.authorization;
|
|
1234
|
+
if (typeof auth.from !== 'string' ||
|
|
1235
|
+
auth.from.length === 0 ||
|
|
1236
|
+
typeof auth.to !== 'string' ||
|
|
1237
|
+
typeof auth.nonce !== 'string' ||
|
|
1238
|
+
auth.nonce.length === 0) {
|
|
1239
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'invalid_x402_authorization_fields');
|
|
1240
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1241
|
+
}
|
|
1242
|
+
if (auth.to.toLowerCase() !== expectedPayTo.toLowerCase()) {
|
|
1243
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'recipient_mismatch');
|
|
1244
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1245
|
+
}
|
|
1246
|
+
if (!/^\d+$/.test(String(auth.validAfter)) || !/^\d+$/.test(String(auth.validBefore))) {
|
|
1247
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'invalid_authorization_timestamps');
|
|
1248
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1249
|
+
}
|
|
1250
|
+
const validAfter = Number(auth.validAfter);
|
|
1251
|
+
const validBefore = Number(auth.validBefore);
|
|
1252
|
+
const skew = config.clockSkewSeconds;
|
|
1253
|
+
if (!Number.isSafeInteger(validAfter) ||
|
|
1254
|
+
!Number.isSafeInteger(validBefore) ||
|
|
1255
|
+
nowSec < validAfter - skew ||
|
|
1256
|
+
nowSec > validBefore + skew) {
|
|
1257
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'authorization_expired_or_not_yet_valid');
|
|
1258
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1259
|
+
}
|
|
1260
|
+
const authorizedAtomic = parseBigIntAmount(auth.value);
|
|
1261
|
+
if (authorizedAtomic === null || authorizedAtomic < requiredAtomic) {
|
|
1262
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'insufficient_payment_amount');
|
|
1263
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1264
|
+
}
|
|
1265
|
+
const facilitatorBase = (config.facilitatorUrl ?? DEFAULT_FACILITATOR_URL).replace(/\/+$/, '');
|
|
1266
|
+
const fetchFn = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
1267
|
+
const paymentRequirements = {
|
|
1268
|
+
scheme,
|
|
1269
|
+
network: expectedNetwork,
|
|
1270
|
+
amount: requiredAtomicStr,
|
|
1271
|
+
asset: expectedAsset,
|
|
1272
|
+
payTo: expectedPayTo,
|
|
1273
|
+
resource: request.url,
|
|
1274
|
+
maxTimeoutSeconds: route.maxTimeoutSeconds ?? 60,
|
|
1275
|
+
extra: usdcEip712Extra(expectedNetwork),
|
|
1276
|
+
};
|
|
1277
|
+
let verifyResp;
|
|
1278
|
+
try {
|
|
1279
|
+
verifyResp = await fetchFn(`${facilitatorBase}/verify`, {
|
|
1280
|
+
method: 'POST',
|
|
1281
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1282
|
+
body: JSON.stringify({
|
|
1283
|
+
x402Version: 2,
|
|
1284
|
+
paymentPayload: parsedSig,
|
|
1285
|
+
paymentRequirements,
|
|
1286
|
+
}),
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
catch {
|
|
1290
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'facilitator_unreachable');
|
|
1291
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1292
|
+
}
|
|
1293
|
+
if (!verifyResp.ok) {
|
|
1294
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'facilitator_verify_http_error');
|
|
1295
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1296
|
+
}
|
|
1297
|
+
let verifyJson;
|
|
1298
|
+
try {
|
|
1299
|
+
verifyJson = (await verifyResp.json());
|
|
1300
|
+
}
|
|
1301
|
+
catch {
|
|
1302
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'facilitator_verify_http_error');
|
|
1303
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1304
|
+
}
|
|
1305
|
+
if (!verifyJson.isValid) {
|
|
1306
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, verifyJson.invalidReason ?? 'facilitator_verification_rejected');
|
|
1307
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1308
|
+
}
|
|
1309
|
+
const consumed = await nonceStore.consume(auth.nonce, {
|
|
1310
|
+
walletOrPayer: auth.from,
|
|
1311
|
+
route: route.pattern,
|
|
1312
|
+
expiresAt: Math.floor(validBefore),
|
|
1313
|
+
rail: 'x402',
|
|
1314
|
+
});
|
|
1315
|
+
if (!consumed) {
|
|
1316
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'nonce_replayed');
|
|
1317
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1318
|
+
}
|
|
1319
|
+
let spendRecorded = false;
|
|
1320
|
+
if (config.perAgentSpendCapMicros !== undefined) {
|
|
1321
|
+
const capCheck = await spendTracker.checkAndRecord(auth.from, requiredMicros, config.perAgentSpendCapMicros);
|
|
1322
|
+
if (!capCheck.allowed) {
|
|
1323
|
+
if (nonceStore.release) {
|
|
1324
|
+
await nonceStore.release(auth.nonce);
|
|
1325
|
+
}
|
|
1326
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'agent_spend_cap_exceeded');
|
|
1327
|
+
return { earlyResponse: create402Response(request, config, challenge) };
|
|
1328
|
+
}
|
|
1329
|
+
spendRecorded = true;
|
|
1330
|
+
}
|
|
1331
|
+
return {
|
|
1332
|
+
finalizeResponse: async (downstreamResponse) => {
|
|
1333
|
+
if (downstreamResponse.status >= 500) {
|
|
1334
|
+
if (nonceStore.release) {
|
|
1335
|
+
await nonceStore.release(auth.nonce);
|
|
1336
|
+
}
|
|
1337
|
+
if (spendRecorded && spendTracker.rollback) {
|
|
1338
|
+
await spendTracker.rollback(auth.from, requiredMicros);
|
|
1339
|
+
}
|
|
1340
|
+
return downstreamResponse;
|
|
1341
|
+
}
|
|
1342
|
+
let settleAtomic = requiredAtomic;
|
|
1343
|
+
if (scheme === 'upto') {
|
|
1344
|
+
if (route.meterUsage) {
|
|
1345
|
+
const minAtomic = BigInt(route.minPriceMicros ?? 0);
|
|
1346
|
+
const metered = await route.meterUsage(request, downstreamResponse, minAtomic, authorizedAtomic);
|
|
1347
|
+
if (metered < 0n) {
|
|
1348
|
+
settleAtomic = 0n;
|
|
1349
|
+
}
|
|
1350
|
+
else if (metered > authorizedAtomic) {
|
|
1351
|
+
settleAtomic = authorizedAtomic;
|
|
1352
|
+
}
|
|
1353
|
+
else {
|
|
1354
|
+
settleAtomic = metered;
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
else {
|
|
1358
|
+
settleAtomic = authorizedAtomic;
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
let settleResp;
|
|
1362
|
+
try {
|
|
1363
|
+
settleResp = await fetchFn(`${facilitatorBase}/settle`, {
|
|
1364
|
+
method: 'POST',
|
|
1365
|
+
headers: {
|
|
1366
|
+
'Content-Type': 'application/json',
|
|
1367
|
+
'Idempotency-Key': `x402_${auth.nonce}`,
|
|
1368
|
+
},
|
|
1369
|
+
body: JSON.stringify({
|
|
1370
|
+
x402Version: 2,
|
|
1371
|
+
paymentPayload: parsedSig,
|
|
1372
|
+
paymentRequirements,
|
|
1373
|
+
settleAmount: settleAtomic.toString(),
|
|
1374
|
+
}),
|
|
1375
|
+
});
|
|
1376
|
+
}
|
|
1377
|
+
catch {
|
|
1378
|
+
if (nonceStore.release) {
|
|
1379
|
+
await nonceStore.release(auth.nonce);
|
|
1380
|
+
}
|
|
1381
|
+
if (spendRecorded && spendTracker.rollback) {
|
|
1382
|
+
await spendTracker.rollback(auth.from, requiredMicros);
|
|
1383
|
+
}
|
|
1384
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'facilitator_unreachable');
|
|
1385
|
+
return create402Response(request, config, challenge);
|
|
1386
|
+
}
|
|
1387
|
+
if (!settleResp.ok) {
|
|
1388
|
+
if (nonceStore.release) {
|
|
1389
|
+
await nonceStore.release(auth.nonce);
|
|
1390
|
+
}
|
|
1391
|
+
if (spendRecorded && spendTracker.rollback) {
|
|
1392
|
+
await spendTracker.rollback(auth.from, requiredMicros);
|
|
1393
|
+
}
|
|
1394
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'facilitator_settlement_failed');
|
|
1395
|
+
return create402Response(request, config, challenge);
|
|
1396
|
+
}
|
|
1397
|
+
let settleJson;
|
|
1398
|
+
try {
|
|
1399
|
+
settleJson = (await settleResp.json());
|
|
1400
|
+
}
|
|
1401
|
+
catch {
|
|
1402
|
+
if (nonceStore.release) {
|
|
1403
|
+
await nonceStore.release(auth.nonce);
|
|
1404
|
+
}
|
|
1405
|
+
if (spendRecorded && spendTracker.rollback) {
|
|
1406
|
+
await spendTracker.rollback(auth.from, requiredMicros);
|
|
1407
|
+
}
|
|
1408
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, 'facilitator_settlement_failed');
|
|
1409
|
+
return create402Response(request, config, challenge);
|
|
1410
|
+
}
|
|
1411
|
+
if (!settleJson.success) {
|
|
1412
|
+
if (nonceStore.release) {
|
|
1413
|
+
await nonceStore.release(auth.nonce);
|
|
1414
|
+
}
|
|
1415
|
+
if (spendRecorded && spendTracker.rollback) {
|
|
1416
|
+
await spendTracker.rollback(auth.from, requiredMicros);
|
|
1417
|
+
}
|
|
1418
|
+
const challenge = buildPaymentRequiredChallenge(request, config, route, settleJson.errorReason ?? 'facilitator_settlement_rejected');
|
|
1419
|
+
return create402Response(request, config, challenge);
|
|
1420
|
+
}
|
|
1421
|
+
return cloneWithPaymentResponse(downstreamResponse, {
|
|
1422
|
+
success: true,
|
|
1423
|
+
transaction: settleJson.txHash,
|
|
1424
|
+
network: settleJson.network ?? expectedNetwork,
|
|
1425
|
+
payer: auth.from,
|
|
1426
|
+
settledAmount: settleJson.settledAmount ?? settleAtomic.toString(),
|
|
1427
|
+
rail: 'x402',
|
|
1428
|
+
errorReason: null,
|
|
1429
|
+
}, 'x402');
|
|
1430
|
+
},
|
|
1431
|
+
};
|
|
1432
|
+
}
|
|
1433
|
+
/**
|
|
1434
|
+
* Wrap a Cloudflare Worker `ExportedHandler` or bare Fetch handler `(request, env, ctx) => Response`
|
|
1435
|
+
* with dual-rail HTTP 402 protection.
|
|
1436
|
+
*/
|
|
1437
|
+
export function withTollbooth(configOrFactory, handlerOrFn) {
|
|
1438
|
+
const defaultNonceStore = new MemoryNonceStore();
|
|
1439
|
+
const defaultSpendTracker = new MemorySpendTracker();
|
|
1440
|
+
const invokeHandler = async (request, env, ctx) => {
|
|
1441
|
+
if (typeof handlerOrFn === 'function') {
|
|
1442
|
+
return handlerOrFn(request, env, ctx);
|
|
1443
|
+
}
|
|
1444
|
+
return handlerOrFn.fetch(request, env, ctx);
|
|
1445
|
+
};
|
|
1446
|
+
return {
|
|
1447
|
+
async fetch(request, env, ctx) {
|
|
1448
|
+
const config = typeof configOrFactory === 'function'
|
|
1449
|
+
? configOrFactory(env)
|
|
1450
|
+
: configOrFactory;
|
|
1451
|
+
const evaluation = await evaluateTollboothRequest(request, config, defaultNonceStore, defaultSpendTracker);
|
|
1452
|
+
if (evaluation.earlyResponse) {
|
|
1453
|
+
return evaluation.earlyResponse;
|
|
1454
|
+
}
|
|
1455
|
+
const downstream = await invokeHandler(request, env, ctx);
|
|
1456
|
+
if (evaluation.isPreflight) {
|
|
1457
|
+
if (downstream.status === 404 || downstream.status === 405) {
|
|
1458
|
+
const preflight = new Response(null, { status: 204, headers: downstream.headers });
|
|
1459
|
+
return attachCorsExposeHeaders(preflight, true);
|
|
1460
|
+
}
|
|
1461
|
+
return attachCorsExposeHeaders(downstream, true);
|
|
1462
|
+
}
|
|
1463
|
+
if (evaluation.finalizeResponse) {
|
|
1464
|
+
return evaluation.finalizeResponse(downstream);
|
|
1465
|
+
}
|
|
1466
|
+
return attachCorsExposeHeaders(downstream, false);
|
|
1467
|
+
},
|
|
1468
|
+
};
|
|
1469
|
+
}
|
|
1470
|
+
/**
|
|
1471
|
+
* Hono-compatible middleware factory enforcing dual-rail HTTP 402 payment requirements.
|
|
1472
|
+
*/
|
|
1473
|
+
export function honoTollbooth(config) {
|
|
1474
|
+
const defaultNonceStore = new MemoryNonceStore();
|
|
1475
|
+
const defaultSpendTracker = new MemorySpendTracker();
|
|
1476
|
+
return async (c, next) => {
|
|
1477
|
+
const evaluation = await evaluateTollboothRequest(c.req.raw, config, defaultNonceStore, defaultSpendTracker);
|
|
1478
|
+
if (evaluation.earlyResponse) {
|
|
1479
|
+
c.res = evaluation.earlyResponse;
|
|
1480
|
+
return evaluation.earlyResponse;
|
|
1481
|
+
}
|
|
1482
|
+
await next();
|
|
1483
|
+
if (c.res && evaluation.isPreflight) {
|
|
1484
|
+
c.res = attachCorsExposeHeaders(c.res, true);
|
|
1485
|
+
}
|
|
1486
|
+
else if (c.res && evaluation.finalizeResponse) {
|
|
1487
|
+
c.res = await evaluation.finalizeResponse(c.res);
|
|
1488
|
+
}
|
|
1489
|
+
else if (c.res) {
|
|
1490
|
+
c.res = attachCorsExposeHeaders(c.res, false);
|
|
1491
|
+
}
|
|
1492
|
+
return c.res;
|
|
1493
|
+
};
|
|
1494
|
+
}
|
|
1495
|
+
//# sourceMappingURL=index.js.map
|