@astrasyncai/verification-gateway 2.0.1 → 2.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/dist/adapter-interface/interface.d.mts +2 -2
- package/dist/adapter-interface/interface.d.ts +2 -2
- package/dist/adapters/express.d.mts +2 -2
- package/dist/adapters/express.d.ts +2 -2
- package/dist/adapters/express.js +42 -20
- package/dist/adapters/express.js.map +1 -1
- package/dist/adapters/express.mjs +42 -20
- package/dist/adapters/express.mjs.map +1 -1
- package/dist/adapters/nextjs.d.mts +2 -2
- package/dist/adapters/nextjs.d.ts +2 -2
- package/dist/adapters/nextjs.js +43 -20
- package/dist/adapters/nextjs.js.map +1 -1
- package/dist/adapters/nextjs.mjs +43 -20
- package/dist/adapters/nextjs.mjs.map +1 -1
- package/dist/adapters/sdk.d.mts +2 -2
- package/dist/adapters/sdk.d.ts +2 -2
- package/dist/adapters/sdk.js +25 -16
- package/dist/adapters/sdk.js.map +1 -1
- package/dist/adapters/sdk.mjs +25 -16
- package/dist/adapters/sdk.mjs.map +1 -1
- package/dist/agent/index.d.mts +2 -2
- package/dist/agent/index.d.ts +2 -2
- package/dist/agent/index.js +100 -1
- package/dist/agent/index.js.map +1 -1
- package/dist/agent/index.mjs +101 -1
- package/dist/agent/index.mjs.map +1 -1
- package/dist/browser/background.js +58 -16
- package/dist/browser/background.js.map +1 -1
- package/dist/browser/background.mjs +61 -16
- package/dist/browser/background.mjs.map +1 -1
- package/dist/browser/browser-adapter.d.mts +2 -2
- package/dist/browser/browser-adapter.d.ts +2 -2
- package/dist/cli/index.d.mts +2 -2
- package/dist/cli/index.d.ts +2 -2
- package/dist/cursor/cursor-adapter.d.mts +2 -2
- package/dist/cursor/cursor-adapter.d.ts +2 -2
- package/dist/cursor/extension.d.mts +2 -2
- package/dist/cursor/extension.d.ts +2 -2
- package/dist/cursor/extension.js +58 -16
- package/dist/cursor/extension.js.map +1 -1
- package/dist/cursor/extension.mjs +61 -16
- package/dist/cursor/extension.mjs.map +1 -1
- package/dist/{express-CtwDIZyF.d.mts → express-C9KqJNWV.d.mts} +1 -1
- package/dist/{express-Bcl-uBUE.d.ts → express-DpwYW08E.d.ts} +1 -1
- package/dist/gateway/gateway.d.mts +2 -2
- package/dist/gateway/gateway.d.ts +2 -2
- package/dist/gateway/gateway.js +58 -16
- package/dist/gateway/gateway.js.map +1 -1
- package/dist/gateway/gateway.mjs +61 -16
- package/dist/gateway/gateway.mjs.map +1 -1
- package/dist/git-trigger/git-hooks.d.mts +2 -2
- package/dist/git-trigger/git-hooks.d.ts +2 -2
- package/dist/{index-BY8yQ8N8.d.mts → index-BMZdjGT4.d.mts} +46 -3
- package/dist/index-DlsYN3Et.d.mts +1397 -0
- package/dist/{index-CtYSYwn3.d.ts → index-Dm2xA6j1.d.ts} +46 -3
- package/dist/index-gM-lgX_X.d.ts +1397 -0
- package/dist/index.d.mts +8 -7
- package/dist/index.d.ts +8 -7
- package/dist/index.js +2489 -66
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2492 -66
- package/dist/index.mjs.map +1 -1
- package/dist/local-evaluator/evaluator.d.mts +2 -2
- package/dist/local-evaluator/evaluator.d.ts +2 -2
- package/dist/{nextjs-BQyMCSx_.d.mts → nextjs-BEqidT0U.d.mts} +1 -1
- package/dist/{nextjs-CEldnIJ9.d.ts → nextjs-yNzimC3a.d.ts} +1 -1
- package/dist/{sdk-BhvuJSrH.d.mts → sdk-7fa9H0qa.d.mts} +1 -1
- package/dist/{sdk-BlyVSC_S.d.ts → sdk-CP9C9Qu0.d.ts} +1 -1
- package/dist/transport/index.d.mts +3 -2
- package/dist/transport/index.d.ts +3 -2
- package/dist/transport/index.js +2384 -2
- package/dist/transport/index.js.map +1 -1
- package/dist/transport/index.mjs +2327 -1
- package/dist/transport/index.mjs.map +1 -1
- package/dist/{types-CxQwJKbd.d.mts → types-CrVMq_Td.d.mts} +30 -3
- package/dist/{types-CxQwJKbd.d.ts → types-CrVMq_Td.d.ts} +30 -3
- package/dist/{types-jJnPXStc.d.mts → types-DE0ooQJ6.d.mts} +1 -1
- package/dist/{types-79qS7aON.d.ts → types-rigu2bH3.d.ts} +1 -1
- package/dist/ui/index.d.mts +1 -1
- package/dist/ui/index.d.ts +1 -1
- package/package.json +17 -3
- package/dist/index-B1ThcGZl.d.mts +0 -89
- package/dist/index-DnoXfdFd.d.ts +0 -89
package/dist/transport/index.mjs
CHANGED
|
@@ -128,6 +128,2283 @@ function extractMcpCredentials(params) {
|
|
|
128
128
|
return credentials;
|
|
129
129
|
}
|
|
130
130
|
|
|
131
|
+
// src/transport/purpose-mapping.ts
|
|
132
|
+
var UCP_ROUTES = [
|
|
133
|
+
{ method: "POST", pattern: /^\/checkout[-_]sessions\/?$/, purpose: "commerce.checkout.create" },
|
|
134
|
+
{
|
|
135
|
+
method: "PUT",
|
|
136
|
+
pattern: /^\/checkout[-_]sessions\/[^/]+\/?$/,
|
|
137
|
+
purpose: "commerce.checkout.update"
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
method: "POST",
|
|
141
|
+
pattern: /^\/checkout[-_]sessions\/[^/]+\/complete\/?$/,
|
|
142
|
+
purpose: "commerce.payment.execute"
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
method: "POST",
|
|
146
|
+
pattern: /^\/checkout[-_]sessions\/[^/]+\/cancel\/?$/,
|
|
147
|
+
purpose: "commerce.checkout.cancel"
|
|
148
|
+
}
|
|
149
|
+
];
|
|
150
|
+
var ACP_ROUTES = [
|
|
151
|
+
{ method: "POST", pattern: /^\/checkout_sessions\/?$/, purpose: "commerce.checkout.create" },
|
|
152
|
+
{
|
|
153
|
+
method: "POST",
|
|
154
|
+
pattern: /^\/checkout_sessions\/[^/]+\/?$/,
|
|
155
|
+
purpose: "commerce.checkout.update"
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
method: "POST",
|
|
159
|
+
pattern: /^\/checkout_sessions\/[^/]+\/complete\/?$/,
|
|
160
|
+
purpose: "commerce.payment.execute"
|
|
161
|
+
},
|
|
162
|
+
{
|
|
163
|
+
method: "POST",
|
|
164
|
+
pattern: /^\/checkout_sessions\/[^/]+\/cancel\/?$/,
|
|
165
|
+
purpose: "commerce.checkout.cancel"
|
|
166
|
+
},
|
|
167
|
+
{
|
|
168
|
+
method: "POST",
|
|
169
|
+
pattern: /^\/agentic_commerce\/delegate_payment\/?$/,
|
|
170
|
+
purpose: "commerce.delegation.payment"
|
|
171
|
+
}
|
|
172
|
+
];
|
|
173
|
+
function mapUCPRequestToPurpose(method, path) {
|
|
174
|
+
const normalizedMethod = method.toUpperCase();
|
|
175
|
+
const normalizedPath = stripQuery(path);
|
|
176
|
+
for (const route of UCP_ROUTES) {
|
|
177
|
+
if (route.method === normalizedMethod && route.pattern.test(normalizedPath)) {
|
|
178
|
+
return route.purpose;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
function mapACPRequestToPurpose(method, path) {
|
|
184
|
+
const normalizedMethod = method.toUpperCase();
|
|
185
|
+
const normalizedPath = stripQuery(path);
|
|
186
|
+
for (const route of ACP_ROUTES) {
|
|
187
|
+
if (route.method === normalizedMethod && route.pattern.test(normalizedPath)) {
|
|
188
|
+
return route.purpose;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
function mapAP2MandateToPurpose(mandateType) {
|
|
194
|
+
switch (mandateType) {
|
|
195
|
+
case "intent_mandate":
|
|
196
|
+
return "commerce.delegation.intent";
|
|
197
|
+
case "cart_mandate":
|
|
198
|
+
return "commerce.checkout.confirm";
|
|
199
|
+
case "payment_mandate":
|
|
200
|
+
return "commerce.payment.execute";
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function mapVIMandateToPurpose(mandateType) {
|
|
204
|
+
switch (mandateType) {
|
|
205
|
+
case "checkout":
|
|
206
|
+
return "commerce.checkout.confirm";
|
|
207
|
+
case "payment":
|
|
208
|
+
return "commerce.payment.execute";
|
|
209
|
+
case "checkout.open":
|
|
210
|
+
return "commerce.delegation.checkout";
|
|
211
|
+
case "payment.open":
|
|
212
|
+
return "commerce.delegation.payment";
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
function mapRFC9421TagToPurpose(tag) {
|
|
216
|
+
if (tag === "purchase") return "commerce.payment.execute";
|
|
217
|
+
return "commerce.browsing";
|
|
218
|
+
}
|
|
219
|
+
function mapMPPRequestToPurpose(intent, amount) {
|
|
220
|
+
if (typeof amount === "number" && amount === 0) return "commerce.identity_probe";
|
|
221
|
+
if (intent === "session") return "commerce.payment.stream";
|
|
222
|
+
return "commerce.payment.execute";
|
|
223
|
+
}
|
|
224
|
+
function mapX402RequestToPurpose(amount) {
|
|
225
|
+
if (typeof amount === "number" && amount === 0) return "commerce.identity_probe";
|
|
226
|
+
return "commerce.payment.execute";
|
|
227
|
+
}
|
|
228
|
+
function stripQuery(path) {
|
|
229
|
+
const q = path.indexOf("?");
|
|
230
|
+
return q === -1 ? path : path.slice(0, q);
|
|
231
|
+
}
|
|
232
|
+
var STRIPE_WEBHOOK_INFORMATIONAL_EVENTS = [
|
|
233
|
+
"payment_intent.succeeded",
|
|
234
|
+
"payment_intent.payment_failed",
|
|
235
|
+
"charge.refunded",
|
|
236
|
+
"checkout.session.completed",
|
|
237
|
+
"customer.subscription.created"
|
|
238
|
+
];
|
|
239
|
+
function isStripeWebhookInformational(eventType) {
|
|
240
|
+
return STRIPE_WEBHOOK_INFORMATIONAL_EVENTS.includes(eventType);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// src/transport/transaction-value.ts
|
|
244
|
+
function extractUCPTransactionValue(input) {
|
|
245
|
+
const totals = input.totals ?? [];
|
|
246
|
+
const total = totals.find((t) => t.type === "total") ?? totals[0];
|
|
247
|
+
if (!total || typeof total.amount !== "number" || !total.currency) return null;
|
|
248
|
+
return {
|
|
249
|
+
protocol: "ucp",
|
|
250
|
+
amount: total.amount / 100,
|
|
251
|
+
currency: total.currency,
|
|
252
|
+
source: `totals[type=${total.type ?? "unknown"}].amount`
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
function extractACPTransactionValue(input) {
|
|
256
|
+
const totals = input.totals ?? [];
|
|
257
|
+
const total = totals.find((t) => t.type === "total") ?? totals[0];
|
|
258
|
+
if (!total || typeof total.amount !== "number" || !total.currency) return null;
|
|
259
|
+
return {
|
|
260
|
+
protocol: "acp",
|
|
261
|
+
amount: total.amount / 100,
|
|
262
|
+
currency: total.currency,
|
|
263
|
+
source: `totals[type=${total.type ?? "unknown"}].amount`
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
function extractVITransactionValue(claims) {
|
|
267
|
+
const l3a = claims.l3aPaymentAmount;
|
|
268
|
+
if (l3a && typeof l3a.amount === "number" && l3a.currency) {
|
|
269
|
+
return {
|
|
270
|
+
protocol: "vi",
|
|
271
|
+
amount: l3a.amount,
|
|
272
|
+
currency: l3a.currency,
|
|
273
|
+
source: "L3a.payment.amount"
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
const bound = claims.constraints?.paymentAmount;
|
|
277
|
+
if (bound && typeof bound.max === "number" && bound.currency) {
|
|
278
|
+
return {
|
|
279
|
+
protocol: "vi",
|
|
280
|
+
amount: bound.max,
|
|
281
|
+
currency: bound.currency,
|
|
282
|
+
source: "L2.payment.constraints.amount.max"
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
function extractAP2TransactionValue(mandate) {
|
|
288
|
+
const amt = mandate?.payment_details_total?.amount;
|
|
289
|
+
if (!amt || !amt.currency) return null;
|
|
290
|
+
const n = typeof amt.value === "string" ? Number(amt.value) : amt.value;
|
|
291
|
+
if (typeof n !== "number" || !Number.isFinite(n)) return null;
|
|
292
|
+
return {
|
|
293
|
+
protocol: "ap2",
|
|
294
|
+
amount: n,
|
|
295
|
+
currency: amt.currency,
|
|
296
|
+
source: "payment_mandate.payment_details_total.amount"
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
function extractMPPTransactionValue(challenge) {
|
|
300
|
+
const req = challenge.request;
|
|
301
|
+
if (!req || typeof req.amount !== "number" || !req.currency) return null;
|
|
302
|
+
return {
|
|
303
|
+
protocol: "mpp",
|
|
304
|
+
amount: req.amount,
|
|
305
|
+
currency: req.currency,
|
|
306
|
+
source: `challenge.request.amount (method=${challenge.method ?? "unknown"})`
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
function extractX402TransactionValue(req) {
|
|
310
|
+
const amount = req.maxAmountRequired ?? req.amount;
|
|
311
|
+
const currency = req.currency ?? req.asset;
|
|
312
|
+
if (typeof amount !== "number" || !currency) return null;
|
|
313
|
+
return {
|
|
314
|
+
protocol: "x402",
|
|
315
|
+
amount,
|
|
316
|
+
currency,
|
|
317
|
+
source: req.maxAmountRequired !== void 0 ? "maxAmountRequired" : "amount"
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// src/transport/rfc9421.ts
|
|
322
|
+
import { parseDictionary } from "structured-headers";
|
|
323
|
+
function parseRFC9421(headers) {
|
|
324
|
+
const sigInput = readHeader(headers, "signature-input");
|
|
325
|
+
const sig = readHeader(headers, "signature");
|
|
326
|
+
if (!sigInput || !sig) return null;
|
|
327
|
+
let inputDict;
|
|
328
|
+
let sigDict;
|
|
329
|
+
try {
|
|
330
|
+
inputDict = parseDictionary(sigInput);
|
|
331
|
+
sigDict = parseDictionary(sig);
|
|
332
|
+
} catch {
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
const signatures = [];
|
|
336
|
+
for (const [label, entry] of inputDict) {
|
|
337
|
+
const innerList = Array.isArray(entry) ? entry[0] : entry.value;
|
|
338
|
+
const params = Array.isArray(entry) ? entry[1] : entry.params;
|
|
339
|
+
if (!Array.isArray(innerList) || !params) continue;
|
|
340
|
+
const covered = [];
|
|
341
|
+
for (const item of innerList) {
|
|
342
|
+
const [bare] = Array.isArray(item) ? item : [item];
|
|
343
|
+
if (typeof bare === "string") covered.push(bare);
|
|
344
|
+
else if (bare && typeof bare === "object" && "toString" in bare) covered.push(String(bare));
|
|
345
|
+
}
|
|
346
|
+
const paramsMap = params;
|
|
347
|
+
const kid = coerceString(paramsMap.get("keyid"));
|
|
348
|
+
if (!kid) continue;
|
|
349
|
+
const sigEntry = sigDict.get(label);
|
|
350
|
+
if (!sigEntry) continue;
|
|
351
|
+
const sigBare = Array.isArray(sigEntry) ? sigEntry[0] : sigEntry.value;
|
|
352
|
+
const signatureBase64 = extractBase64(sigBare);
|
|
353
|
+
if (!signatureBase64) continue;
|
|
354
|
+
signatures.push({
|
|
355
|
+
label,
|
|
356
|
+
kid,
|
|
357
|
+
alg: coerceString(paramsMap.get("alg")),
|
|
358
|
+
covered,
|
|
359
|
+
signatureBase64,
|
|
360
|
+
created: coerceNumber(paramsMap.get("created")),
|
|
361
|
+
expires: coerceNumber(paramsMap.get("expires")),
|
|
362
|
+
nonce: coerceString(paramsMap.get("nonce")),
|
|
363
|
+
tag: coerceString(paramsMap.get("tag"))
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
if (signatures.length === 0) return null;
|
|
367
|
+
return { signatures };
|
|
368
|
+
}
|
|
369
|
+
function readHeader(headers, name) {
|
|
370
|
+
for (const key of Object.keys(headers)) {
|
|
371
|
+
if (key.toLowerCase() === name) {
|
|
372
|
+
const raw = headers[key];
|
|
373
|
+
if (typeof raw === "string") return raw;
|
|
374
|
+
if (Array.isArray(raw)) return raw.join(", ");
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
function coerceString(value) {
|
|
381
|
+
if (typeof value === "string") return value;
|
|
382
|
+
if (value == null) return void 0;
|
|
383
|
+
if (typeof value === "object" && "toString" in value) {
|
|
384
|
+
const s = String(value);
|
|
385
|
+
return s.length > 0 ? s : void 0;
|
|
386
|
+
}
|
|
387
|
+
return void 0;
|
|
388
|
+
}
|
|
389
|
+
function coerceNumber(value) {
|
|
390
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
391
|
+
if (typeof value === "bigint") return Number(value);
|
|
392
|
+
return void 0;
|
|
393
|
+
}
|
|
394
|
+
function extractBase64(value) {
|
|
395
|
+
if (value instanceof Uint8Array) return bufferToBase64(value);
|
|
396
|
+
if (value instanceof ArrayBuffer) return bufferToBase64(new Uint8Array(value));
|
|
397
|
+
if (ArrayBuffer.isView(value)) {
|
|
398
|
+
const v = value;
|
|
399
|
+
return bufferToBase64(new Uint8Array(v.buffer, v.byteOffset, v.byteLength));
|
|
400
|
+
}
|
|
401
|
+
if (typeof value === "string") {
|
|
402
|
+
if (value.startsWith(":") && value.endsWith(":")) return value.slice(1, -1);
|
|
403
|
+
return value;
|
|
404
|
+
}
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
function bufferToBase64(bytes) {
|
|
408
|
+
return Buffer.from(bytes).toString("base64");
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// src/transport/rfc9421-verify.ts
|
|
412
|
+
import { httpbis } from "http-message-signatures";
|
|
413
|
+
async function verifyRFC9421(request, options) {
|
|
414
|
+
const { resolver } = options;
|
|
415
|
+
const tolerance = options.clockSkewSec ?? 300;
|
|
416
|
+
const nowSec = options.now ? options.now() : Math.floor(Date.now() / 1e3);
|
|
417
|
+
let resolvedKid;
|
|
418
|
+
let resolvedAlg;
|
|
419
|
+
const keyLookup = async (parameters) => {
|
|
420
|
+
const kid = typeof parameters.keyid === "string" ? parameters.keyid : void 0;
|
|
421
|
+
if (!kid) return null;
|
|
422
|
+
resolvedKid = kid;
|
|
423
|
+
const alg = typeof parameters.alg === "string" ? parameters.alg : void 0;
|
|
424
|
+
if (alg) resolvedAlg = alg;
|
|
425
|
+
const origin = safeOrigin(request.url);
|
|
426
|
+
const jwk = await resolver.resolve(kid, { origin, algorithm: alg });
|
|
427
|
+
if (!jwk) return null;
|
|
428
|
+
const created = toUnixSeconds(parameters.created);
|
|
429
|
+
const expires = toUnixSeconds(parameters.expires);
|
|
430
|
+
if (created !== void 0 && Math.abs(nowSec - created) > tolerance) return null;
|
|
431
|
+
if (expires !== void 0 && nowSec > expires + tolerance) return null;
|
|
432
|
+
return jwkToVerifyingKey(kid, jwk, alg);
|
|
433
|
+
};
|
|
434
|
+
try {
|
|
435
|
+
const result = await httpbis.verifyMessage(
|
|
436
|
+
{
|
|
437
|
+
keyLookup
|
|
438
|
+
},
|
|
439
|
+
normalizeRequest(request)
|
|
440
|
+
);
|
|
441
|
+
if (result === true) {
|
|
442
|
+
return {
|
|
443
|
+
ok: true,
|
|
444
|
+
kid: resolvedKid,
|
|
445
|
+
registry: resolver.name,
|
|
446
|
+
algorithm: resolvedAlg
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
return {
|
|
450
|
+
ok: false,
|
|
451
|
+
kid: resolvedKid,
|
|
452
|
+
registry: resolver.name,
|
|
453
|
+
algorithm: resolvedAlg,
|
|
454
|
+
error: result === false ? "signature invalid" : "no signature found"
|
|
455
|
+
};
|
|
456
|
+
} catch (err) {
|
|
457
|
+
return {
|
|
458
|
+
ok: false,
|
|
459
|
+
kid: resolvedKid,
|
|
460
|
+
registry: resolver.name,
|
|
461
|
+
algorithm: resolvedAlg,
|
|
462
|
+
error: err instanceof Error ? err.message : "verification error"
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
function normalizeRequest(request) {
|
|
467
|
+
return {
|
|
468
|
+
method: request.method.toUpperCase(),
|
|
469
|
+
url: request.url,
|
|
470
|
+
headers: request.headers
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
function safeOrigin(url) {
|
|
474
|
+
try {
|
|
475
|
+
return new URL(url).origin;
|
|
476
|
+
} catch {
|
|
477
|
+
return void 0;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
async function jwkToVerifyingKey(id, jwk, alg) {
|
|
481
|
+
const algorithm = alg ?? inferAlgFromJwk(jwk);
|
|
482
|
+
const { subtle } = await getCrypto();
|
|
483
|
+
const importAlg = webCryptoImportAlgFor(algorithm);
|
|
484
|
+
const verifyAlg = webCryptoAlgFor(algorithm);
|
|
485
|
+
if (!importAlg || !verifyAlg) {
|
|
486
|
+
return {
|
|
487
|
+
id,
|
|
488
|
+
algs: alg ? [alg] : void 0,
|
|
489
|
+
verify: async () => false
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
const key = await subtle.importKey("jwk", jwk, importAlg, false, ["verify"]);
|
|
493
|
+
return {
|
|
494
|
+
id,
|
|
495
|
+
algs: alg ? [alg] : void 0,
|
|
496
|
+
verify: async (data, signature) => {
|
|
497
|
+
try {
|
|
498
|
+
return await subtle.verify(verifyAlg, key, toArrayBuffer(signature), toArrayBuffer(data));
|
|
499
|
+
} catch {
|
|
500
|
+
return false;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
function inferAlgFromJwk(jwk) {
|
|
506
|
+
if (jwk.kty === "OKP" && jwk.crv === "Ed25519") return "ed25519";
|
|
507
|
+
if (jwk.kty === "EC" && jwk.crv === "P-256") return "ecdsa-p256-sha256";
|
|
508
|
+
if (jwk.kty === "EC" && jwk.crv === "P-384") return "ecdsa-p384-sha384";
|
|
509
|
+
if (jwk.kty === "RSA") return "rsa-v1_5-sha256";
|
|
510
|
+
return "ecdsa-p256-sha256";
|
|
511
|
+
}
|
|
512
|
+
function webCryptoAlgFor(rfc9421Alg) {
|
|
513
|
+
switch (rfc9421Alg) {
|
|
514
|
+
case "ed25519":
|
|
515
|
+
return { name: "Ed25519" };
|
|
516
|
+
case "ecdsa-p256-sha256":
|
|
517
|
+
return { name: "ECDSA", hash: "SHA-256" };
|
|
518
|
+
case "ecdsa-p384-sha384":
|
|
519
|
+
return { name: "ECDSA", hash: "SHA-384" };
|
|
520
|
+
case "rsa-v1_5-sha256":
|
|
521
|
+
return { name: "RSASSA-PKCS1-v1_5" };
|
|
522
|
+
case "rsa-pss-sha512":
|
|
523
|
+
return { name: "RSA-PSS", saltLength: 64 };
|
|
524
|
+
default:
|
|
525
|
+
return null;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
function webCryptoImportAlgFor(rfc9421Alg) {
|
|
529
|
+
switch (rfc9421Alg) {
|
|
530
|
+
case "ed25519":
|
|
531
|
+
return { name: "Ed25519" };
|
|
532
|
+
case "ecdsa-p256-sha256":
|
|
533
|
+
return { name: "ECDSA", namedCurve: "P-256" };
|
|
534
|
+
case "ecdsa-p384-sha384":
|
|
535
|
+
return { name: "ECDSA", namedCurve: "P-384" };
|
|
536
|
+
case "rsa-v1_5-sha256":
|
|
537
|
+
return { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
|
|
538
|
+
case "rsa-pss-sha512":
|
|
539
|
+
return { name: "RSA-PSS", hash: "SHA-512" };
|
|
540
|
+
default:
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
function toArrayBuffer(buf) {
|
|
545
|
+
const out = new ArrayBuffer(buf.byteLength);
|
|
546
|
+
new Uint8Array(out).set(buf);
|
|
547
|
+
return out;
|
|
548
|
+
}
|
|
549
|
+
function toUnixSeconds(v) {
|
|
550
|
+
if (typeof v === "number" && Number.isFinite(v)) return v;
|
|
551
|
+
if (v instanceof Date) return Math.floor(v.getTime() / 1e3);
|
|
552
|
+
if (typeof v === "string") {
|
|
553
|
+
const parsed = Date.parse(v);
|
|
554
|
+
if (Number.isFinite(parsed)) return Math.floor(parsed / 1e3);
|
|
555
|
+
}
|
|
556
|
+
return void 0;
|
|
557
|
+
}
|
|
558
|
+
async function getCrypto() {
|
|
559
|
+
if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
|
|
560
|
+
return { subtle: globalThis.crypto.subtle };
|
|
561
|
+
}
|
|
562
|
+
const nodeCrypto = await import("crypto");
|
|
563
|
+
return { subtle: nodeCrypto.webcrypto.subtle };
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// src/transport/ucp.ts
|
|
567
|
+
function extractUCPContext(request) {
|
|
568
|
+
const { method, url } = request;
|
|
569
|
+
if (!method || !url) return null;
|
|
570
|
+
const parsedUrl = safeParseUrl(url);
|
|
571
|
+
const path = parsedUrl?.pathname ?? url.split("?")[0];
|
|
572
|
+
const purpose = mapUCPRequestToPurpose(method, path);
|
|
573
|
+
const endpoint = `${method.toUpperCase()} ${path}`;
|
|
574
|
+
const sessionId = extractSessionId(path);
|
|
575
|
+
const body = request.body ?? {};
|
|
576
|
+
const totals = Array.isArray(body.totals) ? body.totals : void 0;
|
|
577
|
+
const paymentMethod = coerceString2(body.payment_method ?? body.paymentMethod);
|
|
578
|
+
const manifestUrl = coerceString2(body.manifest_url ?? body.manifestUrl);
|
|
579
|
+
const merchantDomain = extractMerchantDomain(body, parsedUrl);
|
|
580
|
+
return {
|
|
581
|
+
sessionId,
|
|
582
|
+
endpoint,
|
|
583
|
+
purpose,
|
|
584
|
+
merchantDomain,
|
|
585
|
+
totals,
|
|
586
|
+
paymentMethod,
|
|
587
|
+
manifestUrl
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
async function fetchUCPManifest(manifestUrl, options = {}) {
|
|
591
|
+
const timeoutMs = options.timeoutMs ?? 3e3;
|
|
592
|
+
const controller = new AbortController();
|
|
593
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
594
|
+
try {
|
|
595
|
+
const res = await fetch(manifestUrl, { signal: controller.signal });
|
|
596
|
+
if (!res.ok) return null;
|
|
597
|
+
return await res.json();
|
|
598
|
+
} catch {
|
|
599
|
+
return null;
|
|
600
|
+
} finally {
|
|
601
|
+
clearTimeout(timer);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
function validateUCPManifest(manifest, options = {}) {
|
|
605
|
+
if (options.validator) return options.validator(manifest);
|
|
606
|
+
const errors = [];
|
|
607
|
+
if (!manifest || typeof manifest !== "object") {
|
|
608
|
+
return { ok: false, errors: ["manifest is not an object"] };
|
|
609
|
+
}
|
|
610
|
+
const m = manifest;
|
|
611
|
+
if (typeof m.version !== "string") errors.push("version is required and must be a string");
|
|
612
|
+
if (!Array.isArray(m.capabilities)) errors.push("capabilities must be an array");
|
|
613
|
+
if (!m.endpoints || typeof m.endpoints !== "object") errors.push("endpoints must be an object");
|
|
614
|
+
return { ok: errors.length === 0, errors };
|
|
615
|
+
}
|
|
616
|
+
function safeParseUrl(url) {
|
|
617
|
+
try {
|
|
618
|
+
return new URL(url, "http://placeholder.invalid");
|
|
619
|
+
} catch {
|
|
620
|
+
return null;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
function extractSessionId(path) {
|
|
624
|
+
const match = path.match(/\/checkout[-_]sessions\/([^/?#]+)/);
|
|
625
|
+
return match?.[1];
|
|
626
|
+
}
|
|
627
|
+
function extractMerchantDomain(body, parsedUrl) {
|
|
628
|
+
const explicit = coerceString2(body.merchant_domain ?? body.merchantDomain);
|
|
629
|
+
if (explicit) return explicit;
|
|
630
|
+
if (parsedUrl && parsedUrl.hostname !== "placeholder.invalid") return parsedUrl.hostname;
|
|
631
|
+
return void 0;
|
|
632
|
+
}
|
|
633
|
+
function coerceString2(v) {
|
|
634
|
+
return typeof v === "string" && v.length > 0 ? v : void 0;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// src/transport/acp.ts
|
|
638
|
+
function extractACPContext(request) {
|
|
639
|
+
const { method, url } = request;
|
|
640
|
+
if (!method || !url) return null;
|
|
641
|
+
const path = stripQuery2(url.startsWith("http") ? new URL(url).pathname : url);
|
|
642
|
+
const endpoint = classifyEndpoint(method, path);
|
|
643
|
+
const purpose = mapACPRequestToPurpose(method, path);
|
|
644
|
+
const sessionId = extractSessionId2(path);
|
|
645
|
+
const headers = request.headers ?? {};
|
|
646
|
+
const signatureHeader = readHeader2(headers, "signature");
|
|
647
|
+
const timestampHeader = readHeader2(headers, "timestamp");
|
|
648
|
+
const idempotencyKey = readHeader2(headers, "idempotency-key");
|
|
649
|
+
const apiVersion = readHeader2(headers, "api-version");
|
|
650
|
+
const bearer = extractBearer(readHeader2(headers, "authorization"));
|
|
651
|
+
const body = request.body ?? {};
|
|
652
|
+
const merchantId = coerceString3(body.merchant_id ?? body.merchantId);
|
|
653
|
+
const totals = Array.isArray(body.totals) ? body.totals : void 0;
|
|
654
|
+
const fulfillmentOption = extractFulfillmentOption(body);
|
|
655
|
+
const paymentToken = extractPaymentToken(body);
|
|
656
|
+
return {
|
|
657
|
+
endpoint,
|
|
658
|
+
purpose,
|
|
659
|
+
sessionId,
|
|
660
|
+
merchantId,
|
|
661
|
+
apiVersion,
|
|
662
|
+
bearer,
|
|
663
|
+
signatureHeader,
|
|
664
|
+
timestampHeader,
|
|
665
|
+
idempotencyKey,
|
|
666
|
+
paymentToken,
|
|
667
|
+
totals,
|
|
668
|
+
fulfillmentOption,
|
|
669
|
+
rawBody: request.rawBody
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
function classifyEndpoint(method, path) {
|
|
673
|
+
const m = method.toUpperCase();
|
|
674
|
+
if (m !== "POST") return "unknown";
|
|
675
|
+
if (/^\/agentic_commerce\/delegate_payment\/?$/.test(path)) return "delegate_payment";
|
|
676
|
+
if (/^\/checkout_sessions\/?$/.test(path)) return "checkout_sessions.create";
|
|
677
|
+
if (/^\/checkout_sessions\/[^/]+\/?$/.test(path)) return "checkout_sessions.update";
|
|
678
|
+
if (/^\/checkout_sessions\/[^/]+\/complete\/?$/.test(path)) return "checkout_sessions.complete";
|
|
679
|
+
if (/^\/checkout_sessions\/[^/]+\/cancel\/?$/.test(path)) return "checkout_sessions.cancel";
|
|
680
|
+
return "unknown";
|
|
681
|
+
}
|
|
682
|
+
function extractSessionId2(path) {
|
|
683
|
+
const match = path.match(/\/checkout_sessions\/([^/?#]+)/);
|
|
684
|
+
return match?.[1];
|
|
685
|
+
}
|
|
686
|
+
function extractBearer(authHeader) {
|
|
687
|
+
if (!authHeader) return void 0;
|
|
688
|
+
const match = authHeader.match(/^Bearer\s+(.+)$/i);
|
|
689
|
+
return match ? match[1].trim() : void 0;
|
|
690
|
+
}
|
|
691
|
+
function extractPaymentToken(body) {
|
|
692
|
+
const paymentData = body.payment_data;
|
|
693
|
+
if (!paymentData) return void 0;
|
|
694
|
+
const raw = coerceString3(paymentData.token);
|
|
695
|
+
const provider = coerceString3(paymentData.provider);
|
|
696
|
+
if (!raw) return { raw: void 0, type: null, provider };
|
|
697
|
+
const type = classifyPaymentToken(raw);
|
|
698
|
+
return { raw, type, provider };
|
|
699
|
+
}
|
|
700
|
+
function classifyPaymentToken(token) {
|
|
701
|
+
if (token.startsWith("spt_")) return "stripe-spt";
|
|
702
|
+
if (token.startsWith("vt_")) return "acp-vt";
|
|
703
|
+
return "other";
|
|
704
|
+
}
|
|
705
|
+
function extractFulfillmentOption(body) {
|
|
706
|
+
const direct = coerceString3(body.fulfillment_option ?? body.fulfillmentOption);
|
|
707
|
+
if (direct) return direct;
|
|
708
|
+
const options = body.fulfillment_options;
|
|
709
|
+
if (Array.isArray(options) && options.length > 0) {
|
|
710
|
+
const first = options[0];
|
|
711
|
+
if (first && typeof first === "object") {
|
|
712
|
+
const id = coerceString3(first.id);
|
|
713
|
+
if (id) return id;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
return void 0;
|
|
717
|
+
}
|
|
718
|
+
function readHeader2(headers, name) {
|
|
719
|
+
for (const key of Object.keys(headers)) {
|
|
720
|
+
if (key.toLowerCase() === name) {
|
|
721
|
+
const raw = headers[key];
|
|
722
|
+
if (typeof raw === "string") return raw;
|
|
723
|
+
if (Array.isArray(raw)) return raw[0];
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
return void 0;
|
|
727
|
+
}
|
|
728
|
+
function stripQuery2(path) {
|
|
729
|
+
const q = path.indexOf("?");
|
|
730
|
+
return q === -1 ? path : path.slice(0, q);
|
|
731
|
+
}
|
|
732
|
+
function coerceString3(v) {
|
|
733
|
+
return typeof v === "string" && v.length > 0 ? v : void 0;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// src/transport/vi.ts
|
|
737
|
+
import { splitSdJwt, decodeSdJwtSync } from "@sd-jwt/decode";
|
|
738
|
+
import { createHash } from "crypto";
|
|
739
|
+
function extractVIClaims(sdJwtCompact) {
|
|
740
|
+
if (!sdJwtCompact || typeof sdJwtCompact !== "string") return null;
|
|
741
|
+
let decoded;
|
|
742
|
+
try {
|
|
743
|
+
decoded = decodeSdJwtSync(sdJwtCompact, sha256Sync);
|
|
744
|
+
} catch {
|
|
745
|
+
return null;
|
|
746
|
+
}
|
|
747
|
+
const split = safeSplit(sdJwtCompact);
|
|
748
|
+
const payload = decoded.jwt?.payload ?? {};
|
|
749
|
+
const disclosures = decoded.disclosures ?? [];
|
|
750
|
+
const claims = applyDisclosures(
|
|
751
|
+
payload,
|
|
752
|
+
disclosures
|
|
753
|
+
);
|
|
754
|
+
const mandateType = coerceMandateType(
|
|
755
|
+
claims.mandate_type ?? claims.mandateType ?? payload.mandate_type ?? payload.mandateType
|
|
756
|
+
);
|
|
757
|
+
if (!mandateType) return null;
|
|
758
|
+
const kid = coerceString4(
|
|
759
|
+
decoded.jwt?.header?.kid ?? claims.kid ?? payload.kid
|
|
760
|
+
);
|
|
761
|
+
const executionMode = coerceExecutionMode(claims.execution_mode ?? claims.executionMode);
|
|
762
|
+
const credentialProvider = coerceString4(claims.iss ?? payload.iss);
|
|
763
|
+
const constraints = extractConstraints(
|
|
764
|
+
claims.constraints ?? claims.default_constraints ?? {}
|
|
765
|
+
);
|
|
766
|
+
const transactionId = coerceString4(claims.transaction_id ?? claims.transactionId);
|
|
767
|
+
const checkoutHash = coerceString4(
|
|
768
|
+
claims.checkout_hash ?? claims.conditional_transaction_id ?? claims.payment_reference?.checkout_hash
|
|
769
|
+
);
|
|
770
|
+
return {
|
|
771
|
+
mandateType,
|
|
772
|
+
kid,
|
|
773
|
+
executionMode,
|
|
774
|
+
credentialProvider,
|
|
775
|
+
constraints,
|
|
776
|
+
checkoutHash,
|
|
777
|
+
transactionId,
|
|
778
|
+
rawLayers: split
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
function safeSplit(compact) {
|
|
782
|
+
try {
|
|
783
|
+
const { jwt, kbJwt } = splitSdJwt(compact);
|
|
784
|
+
return { l3: jwt, l2: kbJwt };
|
|
785
|
+
} catch {
|
|
786
|
+
return {};
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
function applyDisclosures(payload, disclosures) {
|
|
790
|
+
const result = { ...payload };
|
|
791
|
+
for (const d of disclosures) {
|
|
792
|
+
if (d.key && d.value !== void 0 && !(d.key in result)) {
|
|
793
|
+
result[d.key] = d.value;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
return result;
|
|
797
|
+
}
|
|
798
|
+
function extractConstraints(raw) {
|
|
799
|
+
return {
|
|
800
|
+
allowedMerchants: toAllowedPartyArray(raw.allowed_merchants ?? raw.allowedMerchants),
|
|
801
|
+
allowedPayees: toAllowedPartyArray(raw.allowed_payees ?? raw.allowedPayees),
|
|
802
|
+
lineItems: toLineItemArray(raw.line_items ?? raw.lineItems),
|
|
803
|
+
paymentAmount: toPaymentAmount(raw.payment_amount ?? raw.paymentAmount),
|
|
804
|
+
budgetLimit: toBudgetLimit(raw.budget_limit ?? raw.budgetLimit ?? raw.budget),
|
|
805
|
+
recurrence: toRecurrence(raw.recurrence),
|
|
806
|
+
agentRecurrence: toRecurrence(raw.agent_recurrence ?? raw.agentRecurrence)
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
function toAllowedPartyArray(v) {
|
|
810
|
+
if (!Array.isArray(v)) return void 0;
|
|
811
|
+
const out = [];
|
|
812
|
+
for (const item of v) {
|
|
813
|
+
if (item && typeof item === "object") {
|
|
814
|
+
const r = item;
|
|
815
|
+
out.push({
|
|
816
|
+
id: coerceString4(r.id),
|
|
817
|
+
name: coerceString4(r.name),
|
|
818
|
+
website: coerceString4(r.website)
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
return out.length > 0 ? out : void 0;
|
|
823
|
+
}
|
|
824
|
+
function toLineItemArray(v) {
|
|
825
|
+
if (!Array.isArray(v)) return void 0;
|
|
826
|
+
const out = [];
|
|
827
|
+
for (const item of v) {
|
|
828
|
+
if (item && typeof item === "object") {
|
|
829
|
+
const r = item;
|
|
830
|
+
const acc = r.acceptable_items ?? r.acceptableItems;
|
|
831
|
+
out.push({
|
|
832
|
+
id: coerceString4(r.id),
|
|
833
|
+
acceptableItems: Array.isArray(acc) ? acc.filter((a) => typeof a === "string") : void 0,
|
|
834
|
+
quantity: coerceNumber2(r.quantity)
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
return out.length > 0 ? out : void 0;
|
|
839
|
+
}
|
|
840
|
+
function toPaymentAmount(v) {
|
|
841
|
+
if (!v || typeof v !== "object") return void 0;
|
|
842
|
+
const r = v;
|
|
843
|
+
return {
|
|
844
|
+
currency: coerceString4(r.currency),
|
|
845
|
+
min: coerceNumber2(r.min),
|
|
846
|
+
max: coerceNumber2(r.max)
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
function toBudgetLimit(v) {
|
|
850
|
+
if (!v || typeof v !== "object") return void 0;
|
|
851
|
+
const r = v;
|
|
852
|
+
return {
|
|
853
|
+
currency: coerceString4(r.currency),
|
|
854
|
+
max: coerceNumber2(r.max)
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
function toRecurrence(v) {
|
|
858
|
+
if (!v || typeof v !== "object") return void 0;
|
|
859
|
+
const r = v;
|
|
860
|
+
return {
|
|
861
|
+
frequency: coerceString4(r.frequency),
|
|
862
|
+
startDate: coerceString4(r.start_date ?? r.startDate),
|
|
863
|
+
endDate: coerceString4(r.end_date ?? r.endDate),
|
|
864
|
+
maxOccurrences: coerceNumber2(r.max_occurrences ?? r.maxOccurrences)
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
function coerceMandateType(v) {
|
|
868
|
+
if (v === "checkout" || v === "payment" || v === "checkout.open" || v === "payment.open") {
|
|
869
|
+
return v;
|
|
870
|
+
}
|
|
871
|
+
return null;
|
|
872
|
+
}
|
|
873
|
+
function coerceExecutionMode(v) {
|
|
874
|
+
return v === "Immediate" || v === "Autonomous" || v === "Both" ? v : void 0;
|
|
875
|
+
}
|
|
876
|
+
function coerceString4(v) {
|
|
877
|
+
return typeof v === "string" && v.length > 0 ? v : void 0;
|
|
878
|
+
}
|
|
879
|
+
function coerceNumber2(v) {
|
|
880
|
+
if (typeof v === "number" && Number.isFinite(v)) return v;
|
|
881
|
+
if (typeof v === "string") {
|
|
882
|
+
const n = Number(v);
|
|
883
|
+
return Number.isFinite(n) ? n : void 0;
|
|
884
|
+
}
|
|
885
|
+
return void 0;
|
|
886
|
+
}
|
|
887
|
+
function sha256Sync(data) {
|
|
888
|
+
const buf = typeof data === "string" ? Buffer.from(data, "utf-8") : Buffer.from(new Uint8Array(data));
|
|
889
|
+
const hash = createHash("sha256").update(buf).digest();
|
|
890
|
+
return new Uint8Array(hash.buffer, hash.byteOffset, hash.byteLength);
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// src/transport/stripe-webhook.ts
|
|
894
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
895
|
+
function verifyStripeWebhook(payload, signatureHeader, secret, options = {}) {
|
|
896
|
+
if (!signatureHeader) return { ok: false, error: "missing Stripe-Signature header" };
|
|
897
|
+
if (!secret) return { ok: false, error: "missing webhook secret" };
|
|
898
|
+
const parsed = parseStripeSignature(signatureHeader);
|
|
899
|
+
if (!parsed.timestamp) return { ok: false, error: "malformed Stripe-Signature (missing t=)" };
|
|
900
|
+
if (parsed.v1Signatures.length === 0) {
|
|
901
|
+
return { ok: false, error: "malformed Stripe-Signature (no v1=)" };
|
|
902
|
+
}
|
|
903
|
+
const tolerance = options.toleranceSec ?? 300;
|
|
904
|
+
const now = options.now ? options.now() : Math.floor(Date.now() / 1e3);
|
|
905
|
+
if (Math.abs(now - parsed.timestamp) > tolerance) {
|
|
906
|
+
return {
|
|
907
|
+
ok: false,
|
|
908
|
+
timestamp: parsed.timestamp,
|
|
909
|
+
error: `timestamp outside tolerance (${tolerance}s)`
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
const signedPayload = `${parsed.timestamp}.${payload}`;
|
|
913
|
+
const expected = createHmac("sha256", secret).update(signedPayload).digest();
|
|
914
|
+
for (const candidateHex of parsed.v1Signatures) {
|
|
915
|
+
const candidate = hexToBuffer(candidateHex);
|
|
916
|
+
if (!candidate) continue;
|
|
917
|
+
if (candidate.length !== expected.length) continue;
|
|
918
|
+
if (timingSafeEqual(candidate, expected)) {
|
|
919
|
+
return { ok: true, timestamp: parsed.timestamp };
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
return { ok: false, timestamp: parsed.timestamp, error: "signature mismatch" };
|
|
923
|
+
}
|
|
924
|
+
function parseStripeSignature(header) {
|
|
925
|
+
let timestamp = null;
|
|
926
|
+
const v1Signatures = [];
|
|
927
|
+
for (const part of header.split(",")) {
|
|
928
|
+
const [rawKey, rawValue] = part.split("=");
|
|
929
|
+
if (!rawKey || !rawValue) continue;
|
|
930
|
+
const key = rawKey.trim();
|
|
931
|
+
const value = rawValue.trim();
|
|
932
|
+
if (key === "t") {
|
|
933
|
+
const n = Number(value);
|
|
934
|
+
if (Number.isFinite(n)) timestamp = n;
|
|
935
|
+
} else if (key === "v1") {
|
|
936
|
+
v1Signatures.push(value);
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
return { timestamp, v1Signatures };
|
|
940
|
+
}
|
|
941
|
+
function hexToBuffer(hex) {
|
|
942
|
+
if (!/^[0-9a-fA-F]+$/.test(hex) || hex.length % 2 !== 0) return null;
|
|
943
|
+
return Buffer.from(hex, "hex");
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
// src/transport/constraint-eval.ts
|
|
947
|
+
function evaluateVIConstraints(input) {
|
|
948
|
+
const { constraints, transaction } = input;
|
|
949
|
+
const results = {};
|
|
950
|
+
if (constraints.allowedMerchants && constraints.allowedMerchants.length > 0) {
|
|
951
|
+
results.merchant = evaluateAllowlist(
|
|
952
|
+
"merchant",
|
|
953
|
+
constraints.allowedMerchants,
|
|
954
|
+
transaction.merchant
|
|
955
|
+
);
|
|
956
|
+
}
|
|
957
|
+
if (constraints.allowedPayees && constraints.allowedPayees.length > 0) {
|
|
958
|
+
results.payee = evaluateAllowlist("payee", constraints.allowedPayees, transaction.payee);
|
|
959
|
+
}
|
|
960
|
+
if (constraints.lineItems && constraints.lineItems.length > 0) {
|
|
961
|
+
results.lineItems = evaluateLineItems(constraints.lineItems, transaction.lineItems ?? []);
|
|
962
|
+
}
|
|
963
|
+
if (constraints.paymentAmount) {
|
|
964
|
+
results.amount = evaluatePaymentAmount(constraints.paymentAmount, transaction);
|
|
965
|
+
}
|
|
966
|
+
const reasons = [];
|
|
967
|
+
let ok = true;
|
|
968
|
+
for (const [key, r] of Object.entries(results)) {
|
|
969
|
+
if (!r.ok) {
|
|
970
|
+
ok = false;
|
|
971
|
+
reasons.push(r.reason ?? `${key} failed`);
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
return { ok, results, reasons };
|
|
975
|
+
}
|
|
976
|
+
function evaluatePaymentMethodAllowlist(input) {
|
|
977
|
+
const allow = input.allowedMethods ?? [];
|
|
978
|
+
if (allow.length === 0) return { ok: true };
|
|
979
|
+
if (!input.requestedMethod) {
|
|
980
|
+
return { ok: false, reason: "no payment method in request; allowlist configured" };
|
|
981
|
+
}
|
|
982
|
+
const lowered = input.requestedMethod.toLowerCase();
|
|
983
|
+
const allowed = allow.some((m) => m.toLowerCase() === lowered);
|
|
984
|
+
if (!allowed) {
|
|
985
|
+
return {
|
|
986
|
+
ok: false,
|
|
987
|
+
reason: `payment method "${input.requestedMethod}" not in allowlist [${allow.join(", ")}]`
|
|
988
|
+
};
|
|
989
|
+
}
|
|
990
|
+
return { ok: true };
|
|
991
|
+
}
|
|
992
|
+
function evaluateSpendingLimit(input) {
|
|
993
|
+
const { limit, requested } = input;
|
|
994
|
+
if (!limit || typeof limit.amount !== "number") return { ok: true };
|
|
995
|
+
if (!requested || typeof requested.amount !== "number") return { ok: true };
|
|
996
|
+
if (limit.currency && requested.currency && limit.currency !== requested.currency) {
|
|
997
|
+
return {
|
|
998
|
+
ok: false,
|
|
999
|
+
reason: `currency mismatch: limit ${limit.currency} vs requested ${requested.currency}`
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
if (requested.amount > limit.amount) {
|
|
1003
|
+
return {
|
|
1004
|
+
ok: false,
|
|
1005
|
+
reason: `requested ${requested.amount} ${requested.currency ?? ""} exceeds limit ${limit.amount} ${limit.currency ?? ""}`.trim()
|
|
1006
|
+
};
|
|
1007
|
+
}
|
|
1008
|
+
return { ok: true };
|
|
1009
|
+
}
|
|
1010
|
+
function evaluateAllowlist(kind, allowlist, actual) {
|
|
1011
|
+
if (!actual || !actual.id && !actual.website) {
|
|
1012
|
+
return { ok: false, reason: `no ${kind} in transaction; allowlist configured` };
|
|
1013
|
+
}
|
|
1014
|
+
for (const entry of allowlist) {
|
|
1015
|
+
if (entry.id && actual.id && entry.id === actual.id) return { ok: true };
|
|
1016
|
+
if (entry.website && actual.website && domainsMatch(entry.website, actual.website)) {
|
|
1017
|
+
return { ok: true };
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
const allowedDescriptors = allowlist.map(describeParty).join(", ");
|
|
1021
|
+
const actualDescriptor = describeParty(actual);
|
|
1022
|
+
return {
|
|
1023
|
+
ok: false,
|
|
1024
|
+
reason: `${kind} ${actualDescriptor} not in allowlist [${allowedDescriptors}]`
|
|
1025
|
+
};
|
|
1026
|
+
}
|
|
1027
|
+
function evaluateLineItems(allowlist, actualItems) {
|
|
1028
|
+
if (actualItems.length === 0) {
|
|
1029
|
+
return { ok: false, reason: "no line items in transaction; allowlist configured" };
|
|
1030
|
+
}
|
|
1031
|
+
const reasons = [];
|
|
1032
|
+
for (const item of actualItems) {
|
|
1033
|
+
const match = allowlist.find(
|
|
1034
|
+
(a) => a.id && a.id === item.id || (a.acceptableItems ?? []).includes(item.id ?? "")
|
|
1035
|
+
);
|
|
1036
|
+
if (!match) {
|
|
1037
|
+
reasons.push(`line item "${item.id ?? "(unnamed)"}" not in allowlist`);
|
|
1038
|
+
continue;
|
|
1039
|
+
}
|
|
1040
|
+
if (typeof match.quantity === "number" && typeof item.quantity === "number" && item.quantity > match.quantity) {
|
|
1041
|
+
reasons.push(
|
|
1042
|
+
`line item "${item.id}" quantity ${item.quantity} exceeds allowed ${match.quantity}`
|
|
1043
|
+
);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
return reasons.length === 0 ? { ok: true } : { ok: false, reason: reasons.join("; ") };
|
|
1047
|
+
}
|
|
1048
|
+
function evaluatePaymentAmount(bound, transaction) {
|
|
1049
|
+
if (typeof transaction.amount !== "number") {
|
|
1050
|
+
return { ok: false, reason: "no amount in transaction; paymentAmount bound configured" };
|
|
1051
|
+
}
|
|
1052
|
+
if (bound.currency && transaction.currency && bound.currency !== transaction.currency) {
|
|
1053
|
+
return {
|
|
1054
|
+
ok: false,
|
|
1055
|
+
reason: `currency mismatch: bound ${bound.currency} vs transaction ${transaction.currency}`
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
1058
|
+
if (typeof bound.min === "number" && transaction.amount < bound.min) {
|
|
1059
|
+
return {
|
|
1060
|
+
ok: false,
|
|
1061
|
+
reason: `amount ${transaction.amount} below min ${bound.min}`
|
|
1062
|
+
};
|
|
1063
|
+
}
|
|
1064
|
+
if (typeof bound.max === "number" && transaction.amount > bound.max) {
|
|
1065
|
+
return {
|
|
1066
|
+
ok: false,
|
|
1067
|
+
reason: `amount ${transaction.amount} above max ${bound.max}`
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
return { ok: true };
|
|
1071
|
+
}
|
|
1072
|
+
function domainsMatch(allow, actual) {
|
|
1073
|
+
const a = normalizeDomain(allow);
|
|
1074
|
+
const b = normalizeDomain(actual);
|
|
1075
|
+
return a === b || b.endsWith(`.${a}`);
|
|
1076
|
+
}
|
|
1077
|
+
function normalizeDomain(value) {
|
|
1078
|
+
try {
|
|
1079
|
+
const withScheme = /^https?:\/\//.test(value) ? value : `https://${value}`;
|
|
1080
|
+
return new URL(withScheme).hostname.toLowerCase();
|
|
1081
|
+
} catch {
|
|
1082
|
+
return value.toLowerCase();
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
function describeParty(party) {
|
|
1086
|
+
if (party.id) return `id:${party.id}`;
|
|
1087
|
+
if (party.website) return party.website;
|
|
1088
|
+
if (party.name) return party.name;
|
|
1089
|
+
return "(unnamed)";
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
// src/transport/identity-binding.ts
|
|
1093
|
+
async function bindIdentity(claims, resolver) {
|
|
1094
|
+
const resolutions = [];
|
|
1095
|
+
for (const claim2 of claims) {
|
|
1096
|
+
if (!claim2.value) {
|
|
1097
|
+
resolutions.push({ claim: claim2, agentId: null });
|
|
1098
|
+
continue;
|
|
1099
|
+
}
|
|
1100
|
+
const agentId = await resolver(claim2);
|
|
1101
|
+
resolutions.push({ claim: claim2, agentId });
|
|
1102
|
+
}
|
|
1103
|
+
const resolvedIds = resolutions.map((r) => r.agentId).filter((id) => typeof id === "string" && id.length > 0);
|
|
1104
|
+
const unique = Array.from(new Set(resolvedIds));
|
|
1105
|
+
const mismatchAcrossLayers = unique.length > 1;
|
|
1106
|
+
const mappedAstraSyncAgentId = unique.length === 1 ? unique[0] : void 0;
|
|
1107
|
+
return {
|
|
1108
|
+
claims,
|
|
1109
|
+
mappedAstraSyncAgentId,
|
|
1110
|
+
mismatchAcrossLayers,
|
|
1111
|
+
resolutions
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
var claim = {
|
|
1115
|
+
viKid: (value) => ({ protocol: "vi", field: "kid", value }),
|
|
1116
|
+
ap2AgentId: (value) => ({ protocol: "ap2", field: "agent_id", value }),
|
|
1117
|
+
acpBearer: (value) => ({ protocol: "acp", field: "bearer", value }),
|
|
1118
|
+
mppSource: (value) => ({ protocol: "mpp", field: "source", value }),
|
|
1119
|
+
x402Wallet: (value) => ({ protocol: "x402", field: "wallet", value }),
|
|
1120
|
+
agentPayKid: (value) => ({ protocol: "agentpay", field: "kid", value }),
|
|
1121
|
+
tapKid: (value) => ({ protocol: "tap", field: "kid", value }),
|
|
1122
|
+
webBotAuthKid: (value) => ({
|
|
1123
|
+
protocol: "webbotauth",
|
|
1124
|
+
field: "kid",
|
|
1125
|
+
value
|
|
1126
|
+
})
|
|
1127
|
+
};
|
|
1128
|
+
|
|
1129
|
+
// src/transport/ap2.ts
|
|
1130
|
+
import { decodeSdJwtSync as decodeSdJwtSync2 } from "@sd-jwt/decode";
|
|
1131
|
+
import { createHash as createHash2 } from "crypto";
|
|
1132
|
+
function extractAP2Mandate(sdJwtCompact) {
|
|
1133
|
+
if (!sdJwtCompact || typeof sdJwtCompact !== "string") return null;
|
|
1134
|
+
let decoded;
|
|
1135
|
+
try {
|
|
1136
|
+
decoded = decodeSdJwtSync2(sdJwtCompact, sha256Sync2);
|
|
1137
|
+
} catch {
|
|
1138
|
+
return null;
|
|
1139
|
+
}
|
|
1140
|
+
const payload = decoded.jwt?.payload ?? {};
|
|
1141
|
+
const disclosures = decoded.disclosures ?? [];
|
|
1142
|
+
const claims = applyDisclosures2(
|
|
1143
|
+
payload,
|
|
1144
|
+
disclosures
|
|
1145
|
+
);
|
|
1146
|
+
const type = coerceMandateType2(claims.type ?? claims.mandate_type ?? claims.mandateType);
|
|
1147
|
+
if (!type) return null;
|
|
1148
|
+
if (type === "intent_mandate") return buildIntent(claims);
|
|
1149
|
+
if (type === "cart_mandate") return buildCart(claims);
|
|
1150
|
+
return buildPayment(claims);
|
|
1151
|
+
}
|
|
1152
|
+
function extractAP2Mandates(input) {
|
|
1153
|
+
const intent = input.intent ? extractAP2Mandate(input.intent) : null;
|
|
1154
|
+
const cart = input.cart ? extractAP2Mandate(input.cart) : null;
|
|
1155
|
+
const payment = input.payment ? extractAP2Mandate(input.payment) : null;
|
|
1156
|
+
return {
|
|
1157
|
+
intent: intent ?? void 0,
|
|
1158
|
+
cart: cart ?? void 0,
|
|
1159
|
+
payment: payment ?? void 0,
|
|
1160
|
+
rawLayers: {
|
|
1161
|
+
intentJwt: input.intent,
|
|
1162
|
+
cartJwt: input.cart,
|
|
1163
|
+
paymentJwt: input.payment
|
|
1164
|
+
}
|
|
1165
|
+
};
|
|
1166
|
+
}
|
|
1167
|
+
function buildIntent(claims) {
|
|
1168
|
+
return {
|
|
1169
|
+
type: "intent_mandate",
|
|
1170
|
+
agent_id: coerceString5(claims.agent_id ?? claims.agentId),
|
|
1171
|
+
user_id: coerceString5(claims.user_id ?? claims.userId ?? claims.sub),
|
|
1172
|
+
merchant_category: coerceString5(claims.merchant_category ?? claims.merchantCategory),
|
|
1173
|
+
allowedMerchantDomains: toStringArray(
|
|
1174
|
+
claims.allowed_merchant_domains ?? claims.allowedMerchantDomains
|
|
1175
|
+
),
|
|
1176
|
+
paymentMethods: toStringArray(claims.payment_methods ?? claims.paymentMethods),
|
|
1177
|
+
expires: coerceString5(claims.expires ?? claims.exp),
|
|
1178
|
+
payment_details_total: toPaymentDetails(claims.payment_details_total ?? claims.total),
|
|
1179
|
+
raw: claims
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
function buildCart(claims) {
|
|
1183
|
+
return {
|
|
1184
|
+
type: "cart_mandate",
|
|
1185
|
+
agent_id: coerceString5(claims.agent_id ?? claims.agentId),
|
|
1186
|
+
intent_mandate_id: coerceString5(claims.intent_mandate_id ?? claims.intentMandateId),
|
|
1187
|
+
merchant_id: coerceString5(claims.merchant_id ?? claims.merchantId),
|
|
1188
|
+
line_items: toLineItems(claims.line_items ?? claims.lineItems),
|
|
1189
|
+
payment_details_total: toPaymentDetails(claims.payment_details_total ?? claims.total),
|
|
1190
|
+
expires: coerceString5(claims.expires ?? claims.exp),
|
|
1191
|
+
raw: claims
|
|
1192
|
+
};
|
|
1193
|
+
}
|
|
1194
|
+
function buildPayment(claims) {
|
|
1195
|
+
return {
|
|
1196
|
+
type: "payment_mandate",
|
|
1197
|
+
agent_id: coerceString5(claims.agent_id ?? claims.agentId),
|
|
1198
|
+
cart_mandate_id: coerceString5(claims.cart_mandate_id ?? claims.cartMandateId),
|
|
1199
|
+
payment_method: coerceString5(claims.payment_method ?? claims.paymentMethod),
|
|
1200
|
+
payment_details_total: toPaymentDetails(claims.payment_details_total ?? claims.total),
|
|
1201
|
+
credential_provider: coerceString5(claims.credential_provider ?? claims.credentialProvider),
|
|
1202
|
+
raw: claims
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
function toPaymentDetails(v) {
|
|
1206
|
+
if (!v || typeof v !== "object") return void 0;
|
|
1207
|
+
const r = v;
|
|
1208
|
+
const amount = r.amount;
|
|
1209
|
+
return {
|
|
1210
|
+
amount: amount ? {
|
|
1211
|
+
value: coerceStringOrNumber(amount.value),
|
|
1212
|
+
currency: coerceString5(amount.currency)
|
|
1213
|
+
} : void 0,
|
|
1214
|
+
label: coerceString5(r.label)
|
|
1215
|
+
};
|
|
1216
|
+
}
|
|
1217
|
+
function toLineItems(v) {
|
|
1218
|
+
if (!Array.isArray(v)) return void 0;
|
|
1219
|
+
const items = [];
|
|
1220
|
+
for (const item of v) {
|
|
1221
|
+
if (!item || typeof item !== "object") continue;
|
|
1222
|
+
const r = item;
|
|
1223
|
+
const price = r.price;
|
|
1224
|
+
items.push({
|
|
1225
|
+
id: coerceString5(r.id),
|
|
1226
|
+
quantity: coerceNumber3(r.quantity),
|
|
1227
|
+
price: price ? {
|
|
1228
|
+
value: coerceStringOrNumber(price.value),
|
|
1229
|
+
currency: coerceString5(price.currency)
|
|
1230
|
+
} : void 0
|
|
1231
|
+
});
|
|
1232
|
+
}
|
|
1233
|
+
return items.length > 0 ? items : void 0;
|
|
1234
|
+
}
|
|
1235
|
+
function toStringArray(v) {
|
|
1236
|
+
if (!Array.isArray(v)) return void 0;
|
|
1237
|
+
const out = v.filter((i) => typeof i === "string" && i.length > 0);
|
|
1238
|
+
return out.length > 0 ? out : void 0;
|
|
1239
|
+
}
|
|
1240
|
+
function applyDisclosures2(payload, disclosures) {
|
|
1241
|
+
const result = { ...payload };
|
|
1242
|
+
for (const d of disclosures) {
|
|
1243
|
+
if (d.key && d.value !== void 0 && !(d.key in result)) {
|
|
1244
|
+
result[d.key] = d.value;
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
return result;
|
|
1248
|
+
}
|
|
1249
|
+
function coerceMandateType2(v) {
|
|
1250
|
+
if (v === "intent_mandate" || v === "cart_mandate" || v === "payment_mandate") return v;
|
|
1251
|
+
return null;
|
|
1252
|
+
}
|
|
1253
|
+
function coerceString5(v) {
|
|
1254
|
+
return typeof v === "string" && v.length > 0 ? v : void 0;
|
|
1255
|
+
}
|
|
1256
|
+
function coerceNumber3(v) {
|
|
1257
|
+
if (typeof v === "number" && Number.isFinite(v)) return v;
|
|
1258
|
+
if (typeof v === "string") {
|
|
1259
|
+
const n = Number(v);
|
|
1260
|
+
return Number.isFinite(n) ? n : void 0;
|
|
1261
|
+
}
|
|
1262
|
+
return void 0;
|
|
1263
|
+
}
|
|
1264
|
+
function coerceStringOrNumber(v) {
|
|
1265
|
+
if (typeof v === "number" && Number.isFinite(v)) return v;
|
|
1266
|
+
if (typeof v === "string" && v.length > 0) return v;
|
|
1267
|
+
return void 0;
|
|
1268
|
+
}
|
|
1269
|
+
function sha256Sync2(data) {
|
|
1270
|
+
const buf = typeof data === "string" ? Buffer.from(data, "utf-8") : Buffer.from(new Uint8Array(data));
|
|
1271
|
+
const hash = createHash2("sha256").update(buf).digest();
|
|
1272
|
+
return new Uint8Array(hash.buffer, hash.byteOffset, hash.byteLength);
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
// src/transport/ap2-verify.ts
|
|
1276
|
+
function verifyAP2Chain(input) {
|
|
1277
|
+
const { triple } = input;
|
|
1278
|
+
const errors = [];
|
|
1279
|
+
const intentPresent = triple.intent !== void 0;
|
|
1280
|
+
const cartRefOk = checkCartRef(triple, errors);
|
|
1281
|
+
const paymentRefOk = checkPaymentRef(triple, errors);
|
|
1282
|
+
const { ok: agentIdContinuity, agentId } = checkAgentContinuity(triple, errors);
|
|
1283
|
+
const paymentMethodAllowed = checkPaymentMethod(triple, errors);
|
|
1284
|
+
const totalsConsistent = checkTotals(triple, errors);
|
|
1285
|
+
const expiryOk = checkExpiries(triple, input.clockSkewSec ?? 300, input.now, errors);
|
|
1286
|
+
const ok = cartRefOk && paymentRefOk && agentIdContinuity && paymentMethodAllowed && totalsConsistent && expiryOk;
|
|
1287
|
+
return {
|
|
1288
|
+
ok,
|
|
1289
|
+
checks: {
|
|
1290
|
+
intentPresent,
|
|
1291
|
+
cartRefOk,
|
|
1292
|
+
paymentRefOk,
|
|
1293
|
+
agentIdContinuity,
|
|
1294
|
+
paymentMethodAllowed,
|
|
1295
|
+
totalsConsistent,
|
|
1296
|
+
expiryOk
|
|
1297
|
+
},
|
|
1298
|
+
agentId,
|
|
1299
|
+
errors
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
function checkCartRef(triple, errors) {
|
|
1303
|
+
const cart = triple.cart;
|
|
1304
|
+
if (!cart) return true;
|
|
1305
|
+
if (!cart.intent_mandate_id) return true;
|
|
1306
|
+
const intentId = triple.intent?.raw?.id;
|
|
1307
|
+
if (intentId && cart.intent_mandate_id !== intentId) {
|
|
1308
|
+
errors.push(
|
|
1309
|
+
`cart.intent_mandate_id (${cart.intent_mandate_id}) does not match intent.id (${intentId})`
|
|
1310
|
+
);
|
|
1311
|
+
return false;
|
|
1312
|
+
}
|
|
1313
|
+
return true;
|
|
1314
|
+
}
|
|
1315
|
+
function checkPaymentRef(triple, errors) {
|
|
1316
|
+
const payment = triple.payment;
|
|
1317
|
+
if (!payment) return true;
|
|
1318
|
+
if (!payment.cart_mandate_id) return true;
|
|
1319
|
+
const cartId = triple.cart?.raw?.id;
|
|
1320
|
+
if (cartId && payment.cart_mandate_id !== cartId) {
|
|
1321
|
+
errors.push(
|
|
1322
|
+
`payment.cart_mandate_id (${payment.cart_mandate_id}) does not match cart.id (${cartId})`
|
|
1323
|
+
);
|
|
1324
|
+
return false;
|
|
1325
|
+
}
|
|
1326
|
+
return true;
|
|
1327
|
+
}
|
|
1328
|
+
function checkAgentContinuity(triple, errors) {
|
|
1329
|
+
const ids = [triple.intent?.agent_id, triple.cart?.agent_id, triple.payment?.agent_id].filter(
|
|
1330
|
+
(id) => typeof id === "string" && id.length > 0
|
|
1331
|
+
);
|
|
1332
|
+
if (ids.length === 0) return { ok: true };
|
|
1333
|
+
const unique = new Set(ids);
|
|
1334
|
+
if (unique.size > 1) {
|
|
1335
|
+
errors.push(`agent_id mismatch across mandates: ${Array.from(unique).join(", ")}`);
|
|
1336
|
+
return { ok: false, agentId: void 0 };
|
|
1337
|
+
}
|
|
1338
|
+
return { ok: true, agentId: ids[0] };
|
|
1339
|
+
}
|
|
1340
|
+
function checkPaymentMethod(triple, errors) {
|
|
1341
|
+
const paymentMethod = triple.payment?.payment_method;
|
|
1342
|
+
const allowed = triple.intent?.paymentMethods;
|
|
1343
|
+
if (!paymentMethod || !allowed || allowed.length === 0) return true;
|
|
1344
|
+
if (!allowed.includes(paymentMethod)) {
|
|
1345
|
+
errors.push(
|
|
1346
|
+
`payment_method "${paymentMethod}" not in intent.paymentMethods [${allowed.join(", ")}]`
|
|
1347
|
+
);
|
|
1348
|
+
return false;
|
|
1349
|
+
}
|
|
1350
|
+
return true;
|
|
1351
|
+
}
|
|
1352
|
+
function checkTotals(triple, errors) {
|
|
1353
|
+
const intentTotal = toNumericAmount(triple.intent?.payment_details_total);
|
|
1354
|
+
const cartTotal = toNumericAmount(triple.cart?.payment_details_total);
|
|
1355
|
+
const paymentTotal = toNumericAmount(triple.payment?.payment_details_total);
|
|
1356
|
+
if (intentTotal && cartTotal && intentTotal.currency === cartTotal.currency) {
|
|
1357
|
+
if (cartTotal.value > intentTotal.value) {
|
|
1358
|
+
errors.push(
|
|
1359
|
+
`cart total ${cartTotal.value} ${cartTotal.currency} exceeds intent cap ${intentTotal.value}`
|
|
1360
|
+
);
|
|
1361
|
+
return false;
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
if (cartTotal && paymentTotal && cartTotal.currency === paymentTotal.currency) {
|
|
1365
|
+
if (paymentTotal.value > cartTotal.value) {
|
|
1366
|
+
errors.push(
|
|
1367
|
+
`payment total ${paymentTotal.value} ${paymentTotal.currency} exceeds cart total ${cartTotal.value}`
|
|
1368
|
+
);
|
|
1369
|
+
return false;
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
return true;
|
|
1373
|
+
}
|
|
1374
|
+
function checkExpiries(triple, toleranceSec, nowFn, errors) {
|
|
1375
|
+
const now = nowFn ? nowFn() : Math.floor(Date.now() / 1e3);
|
|
1376
|
+
let ok = true;
|
|
1377
|
+
for (const [name, mandate] of [
|
|
1378
|
+
["intent", triple.intent],
|
|
1379
|
+
["cart", triple.cart]
|
|
1380
|
+
]) {
|
|
1381
|
+
if (!mandate?.expires) continue;
|
|
1382
|
+
const parsed = parseExpiry(mandate.expires);
|
|
1383
|
+
if (parsed === null) {
|
|
1384
|
+
errors.push(`${name}.expires unparseable`);
|
|
1385
|
+
ok = false;
|
|
1386
|
+
continue;
|
|
1387
|
+
}
|
|
1388
|
+
if (now > parsed + toleranceSec) {
|
|
1389
|
+
errors.push(`${name} mandate expired at ${mandate.expires}`);
|
|
1390
|
+
ok = false;
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
return ok;
|
|
1394
|
+
}
|
|
1395
|
+
function toNumericAmount(total) {
|
|
1396
|
+
if (!total?.amount?.value || !total.amount.currency) return null;
|
|
1397
|
+
const n = typeof total.amount.value === "string" ? Number(total.amount.value) : total.amount.value;
|
|
1398
|
+
if (!Number.isFinite(n)) return null;
|
|
1399
|
+
return { value: n, currency: total.amount.currency };
|
|
1400
|
+
}
|
|
1401
|
+
function parseExpiry(value) {
|
|
1402
|
+
const asInt = Number(value);
|
|
1403
|
+
if (Number.isFinite(asInt) && asInt > 0) {
|
|
1404
|
+
return asInt >= 1e12 ? Math.floor(asInt / 1e3) : Math.floor(asInt);
|
|
1405
|
+
}
|
|
1406
|
+
const parsedDate = Date.parse(value);
|
|
1407
|
+
if (Number.isFinite(parsedDate)) return Math.floor(parsedDate / 1e3);
|
|
1408
|
+
return null;
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
// src/transport/acp-verify.ts
|
|
1412
|
+
async function verifyACPSignature(input) {
|
|
1413
|
+
if (!input.signatureHeader) {
|
|
1414
|
+
return { ok: false, error: "missing Signature header" };
|
|
1415
|
+
}
|
|
1416
|
+
const freshness = checkTimestamp(input.timestampHeader, input.clockSkewSec ?? 300, input.now);
|
|
1417
|
+
if (!freshness.ok) {
|
|
1418
|
+
return { ok: false, error: freshness.error, timestampStale: true };
|
|
1419
|
+
}
|
|
1420
|
+
const signatureBytes = decodeBase64(input.signatureHeader);
|
|
1421
|
+
if (!signatureBytes) {
|
|
1422
|
+
return { ok: false, error: "signature header is not valid base64" };
|
|
1423
|
+
}
|
|
1424
|
+
const bodyBytes = new TextEncoder().encode(input.rawBody);
|
|
1425
|
+
const { subtle } = await getSubtle();
|
|
1426
|
+
for (const candidate of input.candidateKeys) {
|
|
1427
|
+
const declaredAlg = normalizeAlgorithm(candidate.alg);
|
|
1428
|
+
const algsToTry = declaredAlg && declaredAlg !== "unsupported" ? [declaredAlg] : ["ed25519", "es256"];
|
|
1429
|
+
for (const alg of algsToTry) {
|
|
1430
|
+
try {
|
|
1431
|
+
const verified = await tryVerify(subtle, candidate.jwk, signatureBytes, bodyBytes, alg);
|
|
1432
|
+
if (verified) return { ok: true, algorithm: alg };
|
|
1433
|
+
} catch {
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
return {
|
|
1438
|
+
ok: false,
|
|
1439
|
+
algorithm: "unsupported",
|
|
1440
|
+
error: "no candidate key verified the signature under Ed25519 or ES256"
|
|
1441
|
+
};
|
|
1442
|
+
}
|
|
1443
|
+
async function tryVerify(subtle, jwk, signature, body, alg) {
|
|
1444
|
+
if (alg === "ed25519") {
|
|
1445
|
+
if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519") return false;
|
|
1446
|
+
const key = await subtle.importKey("jwk", jwk, { name: "Ed25519" }, false, [
|
|
1447
|
+
"verify"
|
|
1448
|
+
]);
|
|
1449
|
+
return await subtle.verify({ name: "Ed25519" }, key, toBuf(signature), toBuf(body));
|
|
1450
|
+
}
|
|
1451
|
+
if (alg === "es256") {
|
|
1452
|
+
if (jwk.kty !== "EC" || jwk.crv !== "P-256") return false;
|
|
1453
|
+
const key = await subtle.importKey(
|
|
1454
|
+
"jwk",
|
|
1455
|
+
jwk,
|
|
1456
|
+
{ name: "ECDSA", namedCurve: "P-256" },
|
|
1457
|
+
false,
|
|
1458
|
+
["verify"]
|
|
1459
|
+
);
|
|
1460
|
+
return await subtle.verify(
|
|
1461
|
+
{ name: "ECDSA", hash: "SHA-256" },
|
|
1462
|
+
key,
|
|
1463
|
+
toBuf(signature),
|
|
1464
|
+
toBuf(body)
|
|
1465
|
+
);
|
|
1466
|
+
}
|
|
1467
|
+
return false;
|
|
1468
|
+
}
|
|
1469
|
+
function toBuf(bytes) {
|
|
1470
|
+
const out = new ArrayBuffer(bytes.byteLength);
|
|
1471
|
+
new Uint8Array(out).set(bytes);
|
|
1472
|
+
return out;
|
|
1473
|
+
}
|
|
1474
|
+
function checkTimestamp(headerValue, toleranceSec, nowFn) {
|
|
1475
|
+
if (!headerValue) return { ok: false, error: "missing Timestamp header" };
|
|
1476
|
+
const ts = parseTimestamp(headerValue);
|
|
1477
|
+
if (ts === null) return { ok: false, error: "unparseable Timestamp header" };
|
|
1478
|
+
const now = nowFn ? nowFn() : Math.floor(Date.now() / 1e3);
|
|
1479
|
+
if (Math.abs(now - ts) > toleranceSec) {
|
|
1480
|
+
return { ok: false, error: `timestamp outside ${toleranceSec}s tolerance` };
|
|
1481
|
+
}
|
|
1482
|
+
return { ok: true };
|
|
1483
|
+
}
|
|
1484
|
+
function parseTimestamp(value) {
|
|
1485
|
+
const asInt = Number(value);
|
|
1486
|
+
if (Number.isFinite(asInt) && asInt > 0) {
|
|
1487
|
+
return asInt >= 1e12 ? Math.floor(asInt / 1e3) : Math.floor(asInt);
|
|
1488
|
+
}
|
|
1489
|
+
const parsedDate = Date.parse(value);
|
|
1490
|
+
if (Number.isFinite(parsedDate)) return Math.floor(parsedDate / 1e3);
|
|
1491
|
+
return null;
|
|
1492
|
+
}
|
|
1493
|
+
function normalizeAlgorithm(alg) {
|
|
1494
|
+
if (!alg) return void 0;
|
|
1495
|
+
const lowered = alg.toLowerCase();
|
|
1496
|
+
if (lowered === "ed25519" || lowered === "eddsa") return "ed25519";
|
|
1497
|
+
if (lowered === "es256" || lowered.startsWith("ecdsa-p256")) return "es256";
|
|
1498
|
+
return "unsupported";
|
|
1499
|
+
}
|
|
1500
|
+
function decodeBase64(value) {
|
|
1501
|
+
try {
|
|
1502
|
+
const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
|
|
1503
|
+
const pad = normalized.length % 4 === 0 ? "" : "=".repeat(4 - normalized.length % 4);
|
|
1504
|
+
return new Uint8Array(Buffer.from(normalized + pad, "base64"));
|
|
1505
|
+
} catch {
|
|
1506
|
+
return null;
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
async function getSubtle() {
|
|
1510
|
+
if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
|
|
1511
|
+
return { subtle: globalThis.crypto.subtle };
|
|
1512
|
+
}
|
|
1513
|
+
const nodeCrypto = await import("crypto");
|
|
1514
|
+
return { subtle: nodeCrypto.webcrypto.subtle };
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
// src/transport/mpp.ts
|
|
1518
|
+
import { Challenge, Credential, Receipt } from "mppx";
|
|
1519
|
+
function extractMPPFromRequest(request) {
|
|
1520
|
+
const auth = readHeader3(request.headers, "authorization");
|
|
1521
|
+
if (!auth || !/^\s*Payment\s+/i.test(auth)) return null;
|
|
1522
|
+
try {
|
|
1523
|
+
const credential = Credential.deserialize(auth);
|
|
1524
|
+
return {
|
|
1525
|
+
kind: "credential",
|
|
1526
|
+
credential: {
|
|
1527
|
+
challenge: summarizeChallenge(credential.challenge),
|
|
1528
|
+
source: credential.source,
|
|
1529
|
+
payload: credential.payload
|
|
1530
|
+
},
|
|
1531
|
+
rawBody: request.rawBody
|
|
1532
|
+
};
|
|
1533
|
+
} catch {
|
|
1534
|
+
return { kind: "error", error: { type: "invalid-credential-encoding" } };
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
function extractMPPFromResponse(response) {
|
|
1538
|
+
if (response.status === 402) {
|
|
1539
|
+
const challenges = collectChallenges(response);
|
|
1540
|
+
if (challenges.length === 0) return null;
|
|
1541
|
+
const methods = Array.from(new Set(challenges.map((c) => c.method)));
|
|
1542
|
+
return {
|
|
1543
|
+
kind: "challenge",
|
|
1544
|
+
challenges,
|
|
1545
|
+
offeredMethods: methods
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
const receiptHeader = readHeader3(response.headers, "payment-receipt");
|
|
1549
|
+
if (receiptHeader) {
|
|
1550
|
+
try {
|
|
1551
|
+
const parsed = Receipt.deserialize(receiptHeader);
|
|
1552
|
+
const r = parsed;
|
|
1553
|
+
return {
|
|
1554
|
+
kind: "receipt",
|
|
1555
|
+
receipt: {
|
|
1556
|
+
method: coerceString6(r.method),
|
|
1557
|
+
reference: coerceString6(r.reference),
|
|
1558
|
+
externalId: coerceString6(r.externalId ?? r.external_id),
|
|
1559
|
+
status: coerceString6(r.status),
|
|
1560
|
+
timestamp: coerceString6(r.timestamp),
|
|
1561
|
+
raw: r
|
|
1562
|
+
}
|
|
1563
|
+
};
|
|
1564
|
+
} catch {
|
|
1565
|
+
return { kind: "error", error: { type: "invalid-receipt-encoding" } };
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
const contentType = readHeader3(response.headers, "content-type");
|
|
1569
|
+
if (contentType && /application\/problem\+json/i.test(contentType)) {
|
|
1570
|
+
const body = typeof response.body === "object" && response.body !== null ? response.body : {};
|
|
1571
|
+
return {
|
|
1572
|
+
kind: "error",
|
|
1573
|
+
error: {
|
|
1574
|
+
type: coerceString6(body.type),
|
|
1575
|
+
title: coerceString6(body.title),
|
|
1576
|
+
detail: coerceString6(body.detail)
|
|
1577
|
+
}
|
|
1578
|
+
};
|
|
1579
|
+
}
|
|
1580
|
+
return null;
|
|
1581
|
+
}
|
|
1582
|
+
function extractMPPContext(message) {
|
|
1583
|
+
if ("request" in message) return extractMPPFromRequest(message.request);
|
|
1584
|
+
if ("response" in message) return extractMPPFromResponse(message.response);
|
|
1585
|
+
if (typeof message.status === "number") {
|
|
1586
|
+
return extractMPPFromResponse(message);
|
|
1587
|
+
}
|
|
1588
|
+
return extractMPPFromRequest(message);
|
|
1589
|
+
}
|
|
1590
|
+
function collectChallenges(response) {
|
|
1591
|
+
const wwwAuth = readHeader3(response.headers, "www-authenticate");
|
|
1592
|
+
if (!wwwAuth) return [];
|
|
1593
|
+
const headers = new Headers();
|
|
1594
|
+
headers.set("www-authenticate", wwwAuth);
|
|
1595
|
+
const out = [];
|
|
1596
|
+
try {
|
|
1597
|
+
const list = Challenge.fromHeadersList(headers);
|
|
1598
|
+
for (const ch of list) {
|
|
1599
|
+
out.push(summarizeChallenge(ch));
|
|
1600
|
+
}
|
|
1601
|
+
} catch {
|
|
1602
|
+
}
|
|
1603
|
+
return out;
|
|
1604
|
+
}
|
|
1605
|
+
function summarizeChallenge(ch) {
|
|
1606
|
+
const raw = ch;
|
|
1607
|
+
return {
|
|
1608
|
+
id: coerceString6(raw.id) ?? "",
|
|
1609
|
+
realm: coerceString6(raw.realm) ?? "",
|
|
1610
|
+
method: coerceString6(raw.method) ?? "",
|
|
1611
|
+
intent: coerceString6(raw.intent) ?? "",
|
|
1612
|
+
request: raw.request ?? {},
|
|
1613
|
+
expires: coerceString6(raw.expires),
|
|
1614
|
+
digest: coerceString6(raw.digest),
|
|
1615
|
+
description: coerceString6(raw.description),
|
|
1616
|
+
opaque: raw.opaque
|
|
1617
|
+
};
|
|
1618
|
+
}
|
|
1619
|
+
function readHeader3(headers, name) {
|
|
1620
|
+
for (const key of Object.keys(headers)) {
|
|
1621
|
+
if (key.toLowerCase() === name) {
|
|
1622
|
+
const raw = headers[key];
|
|
1623
|
+
if (typeof raw === "string") return raw;
|
|
1624
|
+
if (Array.isArray(raw)) return raw.join(", ");
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
return void 0;
|
|
1628
|
+
}
|
|
1629
|
+
function coerceString6(v) {
|
|
1630
|
+
return typeof v === "string" && v.length > 0 ? v : void 0;
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
// src/transport/mpp-verify.ts
|
|
1634
|
+
import { BodyDigest } from "mppx";
|
|
1635
|
+
function verifyMPP(input) {
|
|
1636
|
+
const { context } = input;
|
|
1637
|
+
const tolerance = input.clockSkewSec ?? 300;
|
|
1638
|
+
const nowSec = input.now ? input.now() : Math.floor(Date.now() / 1e3);
|
|
1639
|
+
const challenge = context.credential?.challenge ?? (context.challenges && context.challenges[0]);
|
|
1640
|
+
const source = context.credential?.source;
|
|
1641
|
+
const method = challenge?.method;
|
|
1642
|
+
let expiryOk = true;
|
|
1643
|
+
if (challenge?.expires) {
|
|
1644
|
+
const parsedExpiry = Date.parse(challenge.expires);
|
|
1645
|
+
if (!Number.isFinite(parsedExpiry)) {
|
|
1646
|
+
return {
|
|
1647
|
+
ok: false,
|
|
1648
|
+
expiryOk: false,
|
|
1649
|
+
bodyDigestOk: null,
|
|
1650
|
+
source,
|
|
1651
|
+
method,
|
|
1652
|
+
error: "unparseable challenge.expires"
|
|
1653
|
+
};
|
|
1654
|
+
}
|
|
1655
|
+
const expiresSec = Math.floor(parsedExpiry / 1e3);
|
|
1656
|
+
if (nowSec > expiresSec + tolerance) {
|
|
1657
|
+
expiryOk = false;
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
let bodyDigestOk = null;
|
|
1661
|
+
if (challenge?.digest && input.rawBody !== void 0) {
|
|
1662
|
+
try {
|
|
1663
|
+
if (!/^sha-256=/.test(challenge.digest)) {
|
|
1664
|
+
bodyDigestOk = false;
|
|
1665
|
+
} else {
|
|
1666
|
+
bodyDigestOk = BodyDigest.verify(challenge.digest, input.rawBody);
|
|
1667
|
+
}
|
|
1668
|
+
} catch {
|
|
1669
|
+
bodyDigestOk = false;
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
const ok = expiryOk && (bodyDigestOk === null || bodyDigestOk === true);
|
|
1673
|
+
const errors = [];
|
|
1674
|
+
if (!expiryOk) errors.push("challenge expired");
|
|
1675
|
+
if (bodyDigestOk === false) errors.push("body digest mismatch");
|
|
1676
|
+
return {
|
|
1677
|
+
ok,
|
|
1678
|
+
expiryOk,
|
|
1679
|
+
bodyDigestOk,
|
|
1680
|
+
source,
|
|
1681
|
+
method,
|
|
1682
|
+
error: errors.length > 0 ? errors.join("; ") : void 0
|
|
1683
|
+
};
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
// src/transport/x402.ts
|
|
1687
|
+
import {
|
|
1688
|
+
validatePaymentRequired,
|
|
1689
|
+
validatePaymentPayload
|
|
1690
|
+
} from "@x402/core/schemas";
|
|
1691
|
+
import { safeBase64Decode } from "@x402/core/utils";
|
|
1692
|
+
function extractX402FromRequest(request) {
|
|
1693
|
+
const headerValue = readHeader4(request.headers, "x-payment");
|
|
1694
|
+
if (request.body && typeof request.body === "object") {
|
|
1695
|
+
const parsed = tryParsePayload(request.body);
|
|
1696
|
+
if (parsed) return buildPayloadContext(parsed, "body");
|
|
1697
|
+
}
|
|
1698
|
+
if (headerValue) {
|
|
1699
|
+
try {
|
|
1700
|
+
const decoded = safeBase64Decode(headerValue);
|
|
1701
|
+
if (decoded) {
|
|
1702
|
+
const json = JSON.parse(decoded);
|
|
1703
|
+
const parsed = tryParsePayload(json);
|
|
1704
|
+
if (parsed) return buildPayloadContext(parsed, "header");
|
|
1705
|
+
}
|
|
1706
|
+
} catch {
|
|
1707
|
+
return {
|
|
1708
|
+
kind: "error",
|
|
1709
|
+
version: 1,
|
|
1710
|
+
source: "header",
|
|
1711
|
+
error: { type: "invalid-x402-payload" }
|
|
1712
|
+
};
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
return null;
|
|
1716
|
+
}
|
|
1717
|
+
function extractX402FromResponse(response) {
|
|
1718
|
+
if (response.status !== 402) return null;
|
|
1719
|
+
if (response.body && typeof response.body === "object") {
|
|
1720
|
+
const parsed = tryParseRequired(response.body);
|
|
1721
|
+
if (parsed) return buildRequiredContext(parsed, "body");
|
|
1722
|
+
}
|
|
1723
|
+
const headerValue = readHeader4(response.headers, "x-payment-required");
|
|
1724
|
+
if (headerValue) {
|
|
1725
|
+
try {
|
|
1726
|
+
const decoded = safeBase64Decode(headerValue);
|
|
1727
|
+
if (decoded) {
|
|
1728
|
+
const json = JSON.parse(decoded);
|
|
1729
|
+
const parsed = tryParseRequired(json);
|
|
1730
|
+
if (parsed) return buildRequiredContext(parsed, "header");
|
|
1731
|
+
}
|
|
1732
|
+
} catch {
|
|
1733
|
+
return {
|
|
1734
|
+
kind: "error",
|
|
1735
|
+
version: 1,
|
|
1736
|
+
source: "header",
|
|
1737
|
+
error: { type: "invalid-x402-required" }
|
|
1738
|
+
};
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
return null;
|
|
1742
|
+
}
|
|
1743
|
+
function extractX402Context(message) {
|
|
1744
|
+
if ("request" in message) return extractX402FromRequest(message.request);
|
|
1745
|
+
if ("response" in message) return extractX402FromResponse(message.response);
|
|
1746
|
+
if (typeof message.status === "number") {
|
|
1747
|
+
return extractX402FromResponse(message);
|
|
1748
|
+
}
|
|
1749
|
+
return extractX402FromRequest(message);
|
|
1750
|
+
}
|
|
1751
|
+
function tryParseRequired(data) {
|
|
1752
|
+
try {
|
|
1753
|
+
return validatePaymentRequired(data);
|
|
1754
|
+
} catch {
|
|
1755
|
+
return null;
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
function tryParsePayload(data) {
|
|
1759
|
+
try {
|
|
1760
|
+
return validatePaymentPayload(data);
|
|
1761
|
+
} catch {
|
|
1762
|
+
return null;
|
|
1763
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
function buildRequiredContext(parsed, source) {
|
|
1766
|
+
const asRecord = parsed;
|
|
1767
|
+
const version = coerceVersion(asRecord.x402Version);
|
|
1768
|
+
const accepts = asRecord.accepts ?? [];
|
|
1769
|
+
return {
|
|
1770
|
+
kind: "required",
|
|
1771
|
+
version,
|
|
1772
|
+
source,
|
|
1773
|
+
paymentRequired: {
|
|
1774
|
+
resource: resolveResource(asRecord.resource),
|
|
1775
|
+
accepts: accepts.map(summarizeRequirement),
|
|
1776
|
+
extensions: asRecord.extensions,
|
|
1777
|
+
error: typeof asRecord.error === "string" ? asRecord.error : void 0
|
|
1778
|
+
}
|
|
1779
|
+
};
|
|
1780
|
+
}
|
|
1781
|
+
function buildPayloadContext(parsed, source) {
|
|
1782
|
+
const asRecord = parsed;
|
|
1783
|
+
const version = coerceVersion(asRecord.x402Version);
|
|
1784
|
+
const accepted = asRecord.accepted;
|
|
1785
|
+
const payload = asRecord.payload ?? {};
|
|
1786
|
+
return {
|
|
1787
|
+
kind: "payload",
|
|
1788
|
+
version,
|
|
1789
|
+
source,
|
|
1790
|
+
paymentPayload: {
|
|
1791
|
+
scheme: accepted?.scheme ?? (typeof asRecord.scheme === "string" ? asRecord.scheme : ""),
|
|
1792
|
+
network: accepted?.network ?? (typeof asRecord.network === "string" ? asRecord.network : ""),
|
|
1793
|
+
payload,
|
|
1794
|
+
extensions: asRecord.extensions
|
|
1795
|
+
}
|
|
1796
|
+
};
|
|
1797
|
+
}
|
|
1798
|
+
function summarizeRequirement(req) {
|
|
1799
|
+
const r = req;
|
|
1800
|
+
const amount = r.amount ?? r.maxAmountRequired ?? "0";
|
|
1801
|
+
return {
|
|
1802
|
+
scheme: r.scheme ?? "",
|
|
1803
|
+
network: r.network ?? "",
|
|
1804
|
+
asset: r.asset ?? "",
|
|
1805
|
+
amount: String(amount),
|
|
1806
|
+
payTo: r.payTo ?? "",
|
|
1807
|
+
maxTimeoutSeconds: typeof r.maxTimeoutSeconds === "number" ? r.maxTimeoutSeconds : void 0,
|
|
1808
|
+
resource: typeof r.resource === "string" ? r.resource : void 0,
|
|
1809
|
+
description: typeof r.description === "string" ? r.description : void 0
|
|
1810
|
+
};
|
|
1811
|
+
}
|
|
1812
|
+
function resolveResource(v) {
|
|
1813
|
+
if (typeof v === "string") return v;
|
|
1814
|
+
if (v && typeof v === "object" && "url" in v && typeof v.url === "string") {
|
|
1815
|
+
return v.url;
|
|
1816
|
+
}
|
|
1817
|
+
return "";
|
|
1818
|
+
}
|
|
1819
|
+
function coerceVersion(v) {
|
|
1820
|
+
if (v === 1 || v === 2) return v;
|
|
1821
|
+
return null;
|
|
1822
|
+
}
|
|
1823
|
+
function readHeader4(headers, name) {
|
|
1824
|
+
if (!headers) return void 0;
|
|
1825
|
+
for (const key of Object.keys(headers)) {
|
|
1826
|
+
if (key.toLowerCase() === name) {
|
|
1827
|
+
const raw = headers[key];
|
|
1828
|
+
if (typeof raw === "string") return raw;
|
|
1829
|
+
if (Array.isArray(raw)) return raw[0];
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
return void 0;
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
// src/transport/vi-verify.ts
|
|
1836
|
+
import { createHash as createHash3, webcrypto } from "crypto";
|
|
1837
|
+
async function verifyVIChain(input) {
|
|
1838
|
+
const errors = [];
|
|
1839
|
+
const tolerance = input.clockSkewSec ?? 300;
|
|
1840
|
+
const now = input.now ? input.now() : Math.floor(Date.now() / 1e3);
|
|
1841
|
+
const { l1, l2, l3a, l3b } = input.layers;
|
|
1842
|
+
const l1SigOk = l1 ? await input.verifySignature(l1, null) : null;
|
|
1843
|
+
if (l1 && !l1SigOk) errors.push("L1 signature invalid");
|
|
1844
|
+
const l1Cnf = extractCnfJwk(l1?.payload);
|
|
1845
|
+
const l2SigOk = await input.verifySignature(l2, l1Cnf ?? null);
|
|
1846
|
+
if (!l2SigOk) errors.push("L2 signature invalid");
|
|
1847
|
+
const l2Cnf = extractCnfJwk(l2.payload);
|
|
1848
|
+
const l3aSigOk = l3a ? await input.verifySignature(l3a, l2Cnf ?? null) : null;
|
|
1849
|
+
if (l3a && !l3aSigOk) errors.push("L3a signature invalid");
|
|
1850
|
+
const l3bSigOk = l3b ? await input.verifySignature(l3b, l2Cnf ?? null) : null;
|
|
1851
|
+
if (l3b && !l3bSigOk) errors.push("L3b signature invalid");
|
|
1852
|
+
let l1BindsL2 = true;
|
|
1853
|
+
if (l1Cnf) {
|
|
1854
|
+
const l2KeyFromHeader = await jwkForLayer(l2);
|
|
1855
|
+
l1BindsL2 = l2KeyFromHeader ? await thumbprintsMatch(l1Cnf, l2KeyFromHeader) : false;
|
|
1856
|
+
if (!l1BindsL2) errors.push("L1.cnf.jwk does not bind L2 signing key");
|
|
1857
|
+
}
|
|
1858
|
+
let l2BindsL3 = true;
|
|
1859
|
+
if (l2Cnf && (l3a || l3b)) {
|
|
1860
|
+
const l3Layer = l3a ?? l3b;
|
|
1861
|
+
const l3KeyFromHeader = await jwkForLayer(l3Layer);
|
|
1862
|
+
l2BindsL3 = l3KeyFromHeader ? await thumbprintsMatch(l2Cnf, l3KeyFromHeader) : false;
|
|
1863
|
+
if (!l2BindsL3) errors.push("L2.cnf.jwk does not bind L3 signing key");
|
|
1864
|
+
}
|
|
1865
|
+
let l3aL3bTxnIdMatch = null;
|
|
1866
|
+
if (l3a && l3b) {
|
|
1867
|
+
const a = coerceString7(l3a.payload.transaction_id ?? l3a.payload.transactionId);
|
|
1868
|
+
const b = coerceString7(l3b.payload.transaction_id ?? l3b.payload.transactionId);
|
|
1869
|
+
if (a && b) {
|
|
1870
|
+
l3aL3bTxnIdMatch = a === b;
|
|
1871
|
+
if (!l3aL3bTxnIdMatch) {
|
|
1872
|
+
errors.push(`L3a.transaction_id (${a}) does not match L3b.transaction_id (${b})`);
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
let checkoutHashOk = null;
|
|
1877
|
+
if (l3b) {
|
|
1878
|
+
const declaredHash = coerceString7(
|
|
1879
|
+
l3b.payload.checkout_hash ?? l3b.payload.conditional_transaction_id ?? l3b.payload.payment_reference?.checkout_hash
|
|
1880
|
+
);
|
|
1881
|
+
if (declaredHash) {
|
|
1882
|
+
const computed = computeCheckoutHashFromL2(l2);
|
|
1883
|
+
checkoutHashOk = computed ? declaredHash === computed : false;
|
|
1884
|
+
if (!checkoutHashOk) {
|
|
1885
|
+
errors.push("L3b.checkout_hash does not match SHA-256 of L2 checkout disclosure");
|
|
1886
|
+
}
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
const expiryOk = checkExpiryAcross([l1, l2, l3a, l3b], tolerance, now, errors);
|
|
1890
|
+
const ok = l1SigOk !== false && l2SigOk && l3aSigOk !== false && l3bSigOk !== false && l1BindsL2 && l2BindsL3 && l3aL3bTxnIdMatch !== false && checkoutHashOk !== false && expiryOk;
|
|
1891
|
+
return {
|
|
1892
|
+
ok,
|
|
1893
|
+
checks: {
|
|
1894
|
+
l1SigOk,
|
|
1895
|
+
l2SigOk,
|
|
1896
|
+
l3aSigOk,
|
|
1897
|
+
l3bSigOk,
|
|
1898
|
+
l1BindsL2,
|
|
1899
|
+
l2BindsL3,
|
|
1900
|
+
l3aL3bTxnIdMatch,
|
|
1901
|
+
checkoutHashOk,
|
|
1902
|
+
expiryOk
|
|
1903
|
+
},
|
|
1904
|
+
errors
|
|
1905
|
+
};
|
|
1906
|
+
}
|
|
1907
|
+
function extractCnfJwk(payload) {
|
|
1908
|
+
if (!payload) return null;
|
|
1909
|
+
const cnf = payload.cnf;
|
|
1910
|
+
if (!cnf) return null;
|
|
1911
|
+
const jwk = cnf.jwk;
|
|
1912
|
+
return jwk ?? null;
|
|
1913
|
+
}
|
|
1914
|
+
async function jwkForLayer(layer) {
|
|
1915
|
+
const fromHeader = extractCnfJwk(layer.header);
|
|
1916
|
+
if (fromHeader) return fromHeader;
|
|
1917
|
+
const fromPayload = extractCnfJwk(layer.payload);
|
|
1918
|
+
return fromPayload;
|
|
1919
|
+
}
|
|
1920
|
+
async function thumbprintsMatch(a, b) {
|
|
1921
|
+
try {
|
|
1922
|
+
const ta = await jwkThumbprint(a);
|
|
1923
|
+
const tb = await jwkThumbprint(b);
|
|
1924
|
+
return ta === tb;
|
|
1925
|
+
} catch {
|
|
1926
|
+
return false;
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
async function jwkThumbprint(jwk) {
|
|
1930
|
+
const canonical = canonicalJwk(jwk);
|
|
1931
|
+
const bytes = new TextEncoder().encode(JSON.stringify(canonical));
|
|
1932
|
+
const subtle = webcrypto.subtle;
|
|
1933
|
+
const buffer = await new Promise((resolve, reject) => {
|
|
1934
|
+
const source = new ArrayBuffer(bytes.byteLength);
|
|
1935
|
+
new Uint8Array(source).set(bytes);
|
|
1936
|
+
subtle.digest("SHA-256", source).then(resolve).catch(reject);
|
|
1937
|
+
});
|
|
1938
|
+
return Buffer.from(new Uint8Array(buffer)).toString("base64url").replace(/=+$/, "");
|
|
1939
|
+
}
|
|
1940
|
+
function canonicalJwk(jwk) {
|
|
1941
|
+
if (jwk.kty === "EC") {
|
|
1942
|
+
return { crv: jwk.crv ?? "", kty: "EC", x: jwk.x ?? "", y: jwk.y ?? "" };
|
|
1943
|
+
}
|
|
1944
|
+
if (jwk.kty === "OKP") {
|
|
1945
|
+
return { crv: jwk.crv ?? "", kty: "OKP", x: jwk.x ?? "" };
|
|
1946
|
+
}
|
|
1947
|
+
if (jwk.kty === "RSA") {
|
|
1948
|
+
return { e: jwk.e ?? "", kty: "RSA", n: jwk.n ?? "" };
|
|
1949
|
+
}
|
|
1950
|
+
return { kty: jwk.kty ?? "" };
|
|
1951
|
+
}
|
|
1952
|
+
function computeCheckoutHashFromL2(l2) {
|
|
1953
|
+
const checkoutDisclosure = l2.payload.checkout ?? l2.payload.checkout_mandate;
|
|
1954
|
+
if (!checkoutDisclosure) return null;
|
|
1955
|
+
const canonical = canonicalStringify(checkoutDisclosure);
|
|
1956
|
+
const hash = createHash3("sha256").update(canonical).digest("base64url").replace(/=+$/, "");
|
|
1957
|
+
return hash;
|
|
1958
|
+
}
|
|
1959
|
+
function canonicalStringify(value) {
|
|
1960
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
1961
|
+
if (Array.isArray(value)) return "[" + value.map(canonicalStringify).join(",") + "]";
|
|
1962
|
+
const entries = Object.entries(value).sort(
|
|
1963
|
+
([a], [b]) => a < b ? -1 : a > b ? 1 : 0
|
|
1964
|
+
);
|
|
1965
|
+
return "{" + entries.map(([k, v]) => JSON.stringify(k) + ":" + canonicalStringify(v)).join(",") + "}";
|
|
1966
|
+
}
|
|
1967
|
+
function checkExpiryAcross(layers, toleranceSec, nowSec, errors) {
|
|
1968
|
+
let ok = true;
|
|
1969
|
+
const names = ["L1", "L2", "L3a", "L3b"];
|
|
1970
|
+
layers.forEach((layer, idx) => {
|
|
1971
|
+
if (!layer) return;
|
|
1972
|
+
const exp = toUnixSeconds2(layer.payload.exp ?? layer.payload.expires);
|
|
1973
|
+
if (exp === void 0) return;
|
|
1974
|
+
if (nowSec > exp + toleranceSec) {
|
|
1975
|
+
errors.push(`${names[idx]} mandate expired at ${exp}`);
|
|
1976
|
+
ok = false;
|
|
1977
|
+
}
|
|
1978
|
+
});
|
|
1979
|
+
return ok;
|
|
1980
|
+
}
|
|
1981
|
+
function toUnixSeconds2(v) {
|
|
1982
|
+
if (typeof v === "number" && Number.isFinite(v)) return v;
|
|
1983
|
+
if (typeof v === "string") {
|
|
1984
|
+
const asInt = Number(v);
|
|
1985
|
+
if (Number.isFinite(asInt) && asInt > 0) {
|
|
1986
|
+
return asInt >= 1e12 ? Math.floor(asInt / 1e3) : Math.floor(asInt);
|
|
1987
|
+
}
|
|
1988
|
+
const parsed = Date.parse(v);
|
|
1989
|
+
if (Number.isFinite(parsed)) return Math.floor(parsed / 1e3);
|
|
1990
|
+
}
|
|
1991
|
+
return void 0;
|
|
1992
|
+
}
|
|
1993
|
+
function coerceString7(v) {
|
|
1994
|
+
return typeof v === "string" && v.length > 0 ? v : void 0;
|
|
1995
|
+
}
|
|
1996
|
+
|
|
1997
|
+
// src/transport/commerce-pipeline.ts
|
|
1998
|
+
async function runCommercePipeline(input) {
|
|
1999
|
+
const trustSignals = [];
|
|
2000
|
+
const signatures = {};
|
|
2001
|
+
const timings = { extractMs: 0, verifyMs: 0, evalMs: 0 };
|
|
2002
|
+
const extractStart = performance.now();
|
|
2003
|
+
const purpose = resolvePurpose(input);
|
|
2004
|
+
const transactionValue = resolveTransactionValue(input);
|
|
2005
|
+
const identityClaims = collectIdentityClaims(input);
|
|
2006
|
+
const paymentToken = resolvePaymentToken(input);
|
|
2007
|
+
timings.extractMs = Math.round(performance.now() - extractStart);
|
|
2008
|
+
const verifyStart = performance.now();
|
|
2009
|
+
let hardDeny = false;
|
|
2010
|
+
if (input.vi?.verifyInput) {
|
|
2011
|
+
signatures.vi = await verifyVIChain(input.vi.verifyInput);
|
|
2012
|
+
if (!signatures.vi.ok) hardDeny = true;
|
|
2013
|
+
}
|
|
2014
|
+
if (input.ap2) {
|
|
2015
|
+
signatures.ap2 = verifyAP2Chain({
|
|
2016
|
+
triple: input.ap2.triple,
|
|
2017
|
+
clockSkewSec: input.clockSkewSec,
|
|
2018
|
+
now: input.now
|
|
2019
|
+
});
|
|
2020
|
+
if (!signatures.ap2.ok) hardDeny = true;
|
|
2021
|
+
}
|
|
2022
|
+
if (input.acp?.verifyInput) {
|
|
2023
|
+
signatures.acp = await verifyACPSignature(input.acp.verifyInput);
|
|
2024
|
+
if (!signatures.acp.ok && signatures.acp.timestampStale) hardDeny = true;
|
|
2025
|
+
if (signatures.acp.algorithm === "unsupported") {
|
|
2026
|
+
trustSignals.push("acp-signature-algorithm-unsupported");
|
|
2027
|
+
} else if (!signatures.acp.ok) {
|
|
2028
|
+
hardDeny = true;
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
if (input.rfc9421) {
|
|
2032
|
+
signatures.rfc9421 = await verifyRFC9421(input.rfc9421.request, input.rfc9421.verifyOptions);
|
|
2033
|
+
if (!signatures.rfc9421.ok) hardDeny = true;
|
|
2034
|
+
}
|
|
2035
|
+
if (input.mpp) {
|
|
2036
|
+
signatures.mpp = verifyMPP({
|
|
2037
|
+
context: input.mpp.context,
|
|
2038
|
+
rawBody: input.mpp.rawBody,
|
|
2039
|
+
clockSkewSec: input.clockSkewSec,
|
|
2040
|
+
now: input.now
|
|
2041
|
+
});
|
|
2042
|
+
if (!signatures.mpp.ok) hardDeny = true;
|
|
2043
|
+
if (input.mpp.context.credential?.source) {
|
|
2044
|
+
trustSignals.push(`mpp-source-${shortSource(input.mpp.context.credential.source)}`);
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
if (input.stripeWebhook) {
|
|
2048
|
+
signatures.stripeWebhook = verifyStripeWebhook(
|
|
2049
|
+
input.stripeWebhook.payload,
|
|
2050
|
+
input.stripeWebhook.signatureHeader,
|
|
2051
|
+
input.stripeWebhook.secret,
|
|
2052
|
+
{ now: input.now ? () => input.now() : void 0 }
|
|
2053
|
+
);
|
|
2054
|
+
if (!signatures.stripeWebhook.ok) {
|
|
2055
|
+
trustSignals.push("stripe-webhook-hmac-failed");
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
timings.verifyMs = Math.round(performance.now() - verifyStart);
|
|
2059
|
+
let identity;
|
|
2060
|
+
if (input.identityResolver && identityClaims.length > 0) {
|
|
2061
|
+
const bound = await bindIdentity(identityClaims, input.identityResolver);
|
|
2062
|
+
identity = {
|
|
2063
|
+
claims: identityClaims,
|
|
2064
|
+
mappedAstraSyncAgentId: bound.mappedAstraSyncAgentId,
|
|
2065
|
+
mismatchAcrossLayers: bound.mismatchAcrossLayers
|
|
2066
|
+
};
|
|
2067
|
+
if (bound.mismatchAcrossLayers) trustSignals.push("identity-mismatch-across-layers");
|
|
2068
|
+
} else if (identityClaims.length > 0) {
|
|
2069
|
+
identity = {
|
|
2070
|
+
claims: identityClaims,
|
|
2071
|
+
mappedAstraSyncAgentId: void 0,
|
|
2072
|
+
mismatchAcrossLayers: false
|
|
2073
|
+
};
|
|
2074
|
+
}
|
|
2075
|
+
const evalStart = performance.now();
|
|
2076
|
+
const constraints = runConstraintEval(input);
|
|
2077
|
+
if (constraints && !constraints.ok) hardDeny = true;
|
|
2078
|
+
timings.evalMs = Math.round(performance.now() - evalStart);
|
|
2079
|
+
if (paymentToken?.type === "stripe-spt") trustSignals.push("stripe-spt-present");
|
|
2080
|
+
if (paymentToken?.type === "acp-vt") trustSignals.push("acp-vault-token-present");
|
|
2081
|
+
if (paymentToken?.type === "tempo-tx") trustSignals.push("tempo-transaction-present");
|
|
2082
|
+
const mppReceipt = input.mpp?.context.receipt;
|
|
2083
|
+
return {
|
|
2084
|
+
protocol: input.protocol,
|
|
2085
|
+
purpose,
|
|
2086
|
+
transactionValue,
|
|
2087
|
+
signatures,
|
|
2088
|
+
identity,
|
|
2089
|
+
paymentToken,
|
|
2090
|
+
mppMethodsOffered: input.mpp?.context.offeredMethods,
|
|
2091
|
+
constraints,
|
|
2092
|
+
receipt: mppReceipt ? {
|
|
2093
|
+
method: mppReceipt.method,
|
|
2094
|
+
reference: mppReceipt.reference,
|
|
2095
|
+
status: mppReceipt.status,
|
|
2096
|
+
timestamp: mppReceipt.timestamp
|
|
2097
|
+
} : void 0,
|
|
2098
|
+
trustSignals,
|
|
2099
|
+
timings,
|
|
2100
|
+
ok: !hardDeny
|
|
2101
|
+
};
|
|
2102
|
+
}
|
|
2103
|
+
function resolvePurpose(input) {
|
|
2104
|
+
if (input.vi?.claims.mandateType) {
|
|
2105
|
+
return mapVIMandateToPurpose(input.vi.claims.mandateType);
|
|
2106
|
+
}
|
|
2107
|
+
if (input.ap2?.triple.payment) return "commerce.payment.execute";
|
|
2108
|
+
if (input.ap2?.triple.cart) return "commerce.checkout.confirm";
|
|
2109
|
+
if (input.ap2?.triple.intent) return "commerce.delegation.intent";
|
|
2110
|
+
if (input.ucp?.endpoint) {
|
|
2111
|
+
const [method, path] = input.ucp.endpoint.split(" ");
|
|
2112
|
+
return mapUCPRequestToPurpose(method ?? "POST", path ?? "/");
|
|
2113
|
+
}
|
|
2114
|
+
if (input.acp?.context.endpoint) {
|
|
2115
|
+
switch (input.acp.context.endpoint) {
|
|
2116
|
+
case "checkout_sessions.create":
|
|
2117
|
+
return "commerce.checkout.create";
|
|
2118
|
+
case "checkout_sessions.update":
|
|
2119
|
+
return "commerce.checkout.update";
|
|
2120
|
+
case "checkout_sessions.complete":
|
|
2121
|
+
return "commerce.payment.execute";
|
|
2122
|
+
case "checkout_sessions.cancel":
|
|
2123
|
+
return "commerce.checkout.cancel";
|
|
2124
|
+
case "delegate_payment":
|
|
2125
|
+
return "commerce.delegation.payment";
|
|
2126
|
+
default:
|
|
2127
|
+
return mapACPRequestToPurpose("POST", "/checkout_sessions");
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
if (input.rfc9421?.tag) {
|
|
2131
|
+
return mapRFC9421TagToPurpose(
|
|
2132
|
+
input.rfc9421.tag === "browse" || input.rfc9421.tag === "purchase" ? input.rfc9421.tag : void 0
|
|
2133
|
+
);
|
|
2134
|
+
}
|
|
2135
|
+
if (input.mpp?.context.credential?.challenge || input.mpp?.context.challenges?.[0]) {
|
|
2136
|
+
const challenge = input.mpp.context.credential?.challenge ?? input.mpp.context.challenges?.[0];
|
|
2137
|
+
const amount = parseFloat(String(challenge?.request?.amount ?? "NaN"));
|
|
2138
|
+
return mapMPPRequestToPurpose(
|
|
2139
|
+
challenge?.intent === "session" ? "session" : "charge",
|
|
2140
|
+
Number.isFinite(amount) ? amount : void 0
|
|
2141
|
+
);
|
|
2142
|
+
}
|
|
2143
|
+
if (input.x402?.paymentRequired) {
|
|
2144
|
+
const amt = input.x402.paymentRequired.accepts[0]?.amount;
|
|
2145
|
+
return mapX402RequestToPurpose(Number(amt));
|
|
2146
|
+
}
|
|
2147
|
+
if (input.x402?.paymentPayload) return "commerce.payment.execute";
|
|
2148
|
+
return null;
|
|
2149
|
+
}
|
|
2150
|
+
function resolveTransactionValue(input) {
|
|
2151
|
+
if (input.vi?.claims) {
|
|
2152
|
+
const v = extractVITransactionValue({
|
|
2153
|
+
constraints: input.vi.claims.constraints,
|
|
2154
|
+
l3aPaymentAmount: input.vi.claims.constraints.paymentAmount && typeof input.vi.claims.constraints.paymentAmount.max === "number" ? {
|
|
2155
|
+
amount: input.vi.claims.constraints.paymentAmount.max,
|
|
2156
|
+
currency: input.vi.claims.constraints.paymentAmount.currency
|
|
2157
|
+
} : void 0
|
|
2158
|
+
});
|
|
2159
|
+
if (v) return v;
|
|
2160
|
+
}
|
|
2161
|
+
if (input.ucp?.totals) {
|
|
2162
|
+
const v = extractUCPTransactionValue({ totals: input.ucp.totals });
|
|
2163
|
+
if (v) return v;
|
|
2164
|
+
}
|
|
2165
|
+
if (input.acp?.context.totals) {
|
|
2166
|
+
const v = extractACPTransactionValue({ totals: input.acp.context.totals });
|
|
2167
|
+
if (v) return v;
|
|
2168
|
+
}
|
|
2169
|
+
if (input.mpp?.context.credential?.challenge) {
|
|
2170
|
+
const ch = input.mpp.context.credential.challenge;
|
|
2171
|
+
const v = extractMPPTransactionValue({ method: ch.method, request: ch.request });
|
|
2172
|
+
if (v) return v;
|
|
2173
|
+
}
|
|
2174
|
+
if (input.x402?.paymentRequired) {
|
|
2175
|
+
const first = input.x402.paymentRequired.accepts[0];
|
|
2176
|
+
if (first) {
|
|
2177
|
+
const v = extractX402TransactionValue({
|
|
2178
|
+
maxAmountRequired: Number(first.amount),
|
|
2179
|
+
asset: first.asset
|
|
2180
|
+
});
|
|
2181
|
+
if (v) return v;
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
return void 0;
|
|
2185
|
+
}
|
|
2186
|
+
function collectIdentityClaims(input) {
|
|
2187
|
+
const claims = [];
|
|
2188
|
+
if (input.vi?.claims.kid)
|
|
2189
|
+
claims.push({ protocol: "vi", field: "kid", value: input.vi.claims.kid });
|
|
2190
|
+
if (input.ap2?.triple) {
|
|
2191
|
+
const agentId = input.ap2.triple.intent?.agent_id ?? input.ap2.triple.cart?.agent_id ?? input.ap2.triple.payment?.agent_id;
|
|
2192
|
+
if (agentId) claims.push({ protocol: "ap2", field: "agent_id", value: agentId });
|
|
2193
|
+
}
|
|
2194
|
+
if (input.acp?.context.bearer) {
|
|
2195
|
+
claims.push({ protocol: "acp", field: "bearer", value: input.acp.context.bearer });
|
|
2196
|
+
}
|
|
2197
|
+
if (input.mpp?.context.credential?.source) {
|
|
2198
|
+
claims.push({ protocol: "mpp", field: "source", value: input.mpp.context.credential.source });
|
|
2199
|
+
}
|
|
2200
|
+
if (input.rfc9421) {
|
|
2201
|
+
}
|
|
2202
|
+
return claims;
|
|
2203
|
+
}
|
|
2204
|
+
function resolvePaymentToken(input) {
|
|
2205
|
+
if (input.acp?.context.paymentToken?.type) {
|
|
2206
|
+
return { present: true, type: input.acp.context.paymentToken.type };
|
|
2207
|
+
}
|
|
2208
|
+
const mppMethod = input.mpp?.context.credential?.challenge?.method;
|
|
2209
|
+
if (mppMethod === "tempo") return { present: true, type: "tempo-tx" };
|
|
2210
|
+
if (mppMethod === "stripe") return { present: true, type: "stripe-spt" };
|
|
2211
|
+
return void 0;
|
|
2212
|
+
}
|
|
2213
|
+
function runConstraintEval(input) {
|
|
2214
|
+
const transaction = input.transaction ?? {};
|
|
2215
|
+
const results = {};
|
|
2216
|
+
const reasons = [];
|
|
2217
|
+
let hasAny = false;
|
|
2218
|
+
if (input.vi?.claims) {
|
|
2219
|
+
const viResult = evaluateVIConstraints({
|
|
2220
|
+
constraints: input.vi.claims.constraints,
|
|
2221
|
+
transaction
|
|
2222
|
+
});
|
|
2223
|
+
for (const [k, v] of Object.entries(viResult.results)) {
|
|
2224
|
+
results[k] = v;
|
|
2225
|
+
if (!v.ok && v.reason) reasons.push(v.reason);
|
|
2226
|
+
}
|
|
2227
|
+
if (Object.keys(viResult.results).length > 0) hasAny = true;
|
|
2228
|
+
}
|
|
2229
|
+
const registered = input.registeredConstraints;
|
|
2230
|
+
if (registered?.allowedPaymentMethods) {
|
|
2231
|
+
const pm = evaluatePaymentMethodAllowlist({
|
|
2232
|
+
allowedMethods: registered.allowedPaymentMethods,
|
|
2233
|
+
requestedMethod: transaction.paymentMethod
|
|
2234
|
+
});
|
|
2235
|
+
results.paymentMethod = pm;
|
|
2236
|
+
if (!pm.ok && pm.reason) reasons.push(pm.reason);
|
|
2237
|
+
hasAny = true;
|
|
2238
|
+
}
|
|
2239
|
+
if (registered?.spendingLimit) {
|
|
2240
|
+
const sp = evaluateSpendingLimit({
|
|
2241
|
+
limit: registered.spendingLimit,
|
|
2242
|
+
requested: { amount: transaction.amount, currency: transaction.currency }
|
|
2243
|
+
});
|
|
2244
|
+
results.spendingLimit = sp;
|
|
2245
|
+
if (!sp.ok && sp.reason) reasons.push(sp.reason);
|
|
2246
|
+
hasAny = true;
|
|
2247
|
+
}
|
|
2248
|
+
if (!hasAny) return void 0;
|
|
2249
|
+
return { ok: reasons.length === 0, results, reasons };
|
|
2250
|
+
}
|
|
2251
|
+
function shortSource(source) {
|
|
2252
|
+
return source.replace(/^did:[a-z0-9]+:/, "").slice(0, 16);
|
|
2253
|
+
}
|
|
2254
|
+
|
|
2255
|
+
// src/transport/extractor-registry.ts
|
|
2256
|
+
var registry = /* @__PURE__ */ new Map();
|
|
2257
|
+
function registerTransportExtractor(extractor) {
|
|
2258
|
+
if (!extractor || typeof extractor.name !== "string" || extractor.name.length === 0) {
|
|
2259
|
+
throw new Error("registerTransportExtractor: extractor must have a non-empty name");
|
|
2260
|
+
}
|
|
2261
|
+
registry.set(extractor.name, extractor);
|
|
2262
|
+
}
|
|
2263
|
+
function getTransportExtractors() {
|
|
2264
|
+
return Array.from(registry.values());
|
|
2265
|
+
}
|
|
2266
|
+
function getTransportExtractor(name) {
|
|
2267
|
+
return registry.get(name);
|
|
2268
|
+
}
|
|
2269
|
+
function clearTransportExtractors() {
|
|
2270
|
+
registry.clear();
|
|
2271
|
+
}
|
|
2272
|
+
async function runMatchingExtractors(request) {
|
|
2273
|
+
const out = {};
|
|
2274
|
+
for (const extractor of registry.values()) {
|
|
2275
|
+
if (!extractor.match(request)) continue;
|
|
2276
|
+
const result = await extractor.extract(request);
|
|
2277
|
+
if (result !== null && result !== void 0) out[extractor.name] = result;
|
|
2278
|
+
}
|
|
2279
|
+
return out;
|
|
2280
|
+
}
|
|
2281
|
+
|
|
2282
|
+
// src/transport/registry/visa.ts
|
|
2283
|
+
import { createRemoteJWKSet } from "jose";
|
|
2284
|
+
var DEFAULT_VISA_JWKS_URL = "https://mcp.visa.com/.well-known/jwks";
|
|
2285
|
+
function createVisaRegistry(options = {}) {
|
|
2286
|
+
const url = new URL(options.jwksUrl ?? DEFAULT_VISA_JWKS_URL);
|
|
2287
|
+
const jwks = createRemoteJWKSet(url, {
|
|
2288
|
+
cacheMaxAge: options.cacheMaxAge,
|
|
2289
|
+
cooldownDuration: options.cooldownDuration
|
|
2290
|
+
});
|
|
2291
|
+
return {
|
|
2292
|
+
name: "visa",
|
|
2293
|
+
async resolve(kid, context) {
|
|
2294
|
+
if (!kid) return null;
|
|
2295
|
+
try {
|
|
2296
|
+
const key = await jwks({
|
|
2297
|
+
kid,
|
|
2298
|
+
alg: context?.algorithm ?? "ES256",
|
|
2299
|
+
typ: "JWT"
|
|
2300
|
+
});
|
|
2301
|
+
return exportJwkFromKeyLike(key);
|
|
2302
|
+
} catch {
|
|
2303
|
+
return null;
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
};
|
|
2307
|
+
}
|
|
2308
|
+
async function exportJwkFromKeyLike(keyLike) {
|
|
2309
|
+
if (!keyLike) return null;
|
|
2310
|
+
if (typeof keyLike === "object" && "kty" in keyLike) {
|
|
2311
|
+
return keyLike;
|
|
2312
|
+
}
|
|
2313
|
+
const { exportJWK } = await import("jose");
|
|
2314
|
+
try {
|
|
2315
|
+
return await exportJWK(keyLike);
|
|
2316
|
+
} catch {
|
|
2317
|
+
return null;
|
|
2318
|
+
}
|
|
2319
|
+
}
|
|
2320
|
+
|
|
2321
|
+
// src/transport/registry/mastercard.ts
|
|
2322
|
+
function createMastercardRegistry(options = {}) {
|
|
2323
|
+
const cache = /* @__PURE__ */ new Map();
|
|
2324
|
+
const ttlSec = options.cacheTtlSec ?? 3600;
|
|
2325
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
2326
|
+
let warned = false;
|
|
2327
|
+
return {
|
|
2328
|
+
name: "mastercard",
|
|
2329
|
+
async resolve(kid) {
|
|
2330
|
+
if (!kid) return null;
|
|
2331
|
+
if (!options.registryUrl) {
|
|
2332
|
+
if (!warned && !options.silent) {
|
|
2333
|
+
warned = true;
|
|
2334
|
+
console.warn(
|
|
2335
|
+
"[mastercard-registry] registryUrl not configured \u2014 key resolution disabled. Kid lookups will return null until a partnership registry is supplied."
|
|
2336
|
+
);
|
|
2337
|
+
}
|
|
2338
|
+
return null;
|
|
2339
|
+
}
|
|
2340
|
+
const cached = cache.get(kid);
|
|
2341
|
+
if (cached && cached.expiresAt > Date.now()) return cached.jwk;
|
|
2342
|
+
try {
|
|
2343
|
+
const res = await fetchFn(options.registryUrl);
|
|
2344
|
+
if (!res.ok) return null;
|
|
2345
|
+
const body = await res.json();
|
|
2346
|
+
const keys = body.keys ?? [];
|
|
2347
|
+
for (const k of keys) {
|
|
2348
|
+
if (k.kid === kid) {
|
|
2349
|
+
cache.set(kid, { jwk: k, expiresAt: Date.now() + ttlSec * 1e3 });
|
|
2350
|
+
return k;
|
|
2351
|
+
}
|
|
2352
|
+
}
|
|
2353
|
+
return null;
|
|
2354
|
+
} catch {
|
|
2355
|
+
return null;
|
|
2356
|
+
}
|
|
2357
|
+
}
|
|
2358
|
+
};
|
|
2359
|
+
}
|
|
2360
|
+
|
|
2361
|
+
// src/transport/registry/web-bot-auth.ts
|
|
2362
|
+
var DIRECTORY_PATH = "/.well-known/http-message-signatures-directory";
|
|
2363
|
+
function createWebBotAuthRegistry(options = {}) {
|
|
2364
|
+
const cache = /* @__PURE__ */ new Map();
|
|
2365
|
+
const ttlSec = options.cacheTtlSec ?? 3600;
|
|
2366
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
2367
|
+
return {
|
|
2368
|
+
name: "web-bot-auth",
|
|
2369
|
+
async resolve(kid, context) {
|
|
2370
|
+
if (!kid) return null;
|
|
2371
|
+
const directoryUrl = resolveDirectoryUrl(options.directoryUrl, context?.origin);
|
|
2372
|
+
if (!directoryUrl) return null;
|
|
2373
|
+
const cached = cache.get(directoryUrl);
|
|
2374
|
+
const now = Date.now();
|
|
2375
|
+
if (cached && cached.expiresAt > now) {
|
|
2376
|
+
return findKeyByKid(cached.keys, kid);
|
|
2377
|
+
}
|
|
2378
|
+
try {
|
|
2379
|
+
const res = await fetchFn(directoryUrl);
|
|
2380
|
+
if (!res.ok) return null;
|
|
2381
|
+
const body = await res.json();
|
|
2382
|
+
const keys = body.keys ?? [];
|
|
2383
|
+
cache.set(directoryUrl, { keys, expiresAt: now + ttlSec * 1e3 });
|
|
2384
|
+
return findKeyByKid(keys, kid);
|
|
2385
|
+
} catch {
|
|
2386
|
+
return null;
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
};
|
|
2390
|
+
}
|
|
2391
|
+
function resolveDirectoryUrl(explicit, origin) {
|
|
2392
|
+
if (explicit) return explicit;
|
|
2393
|
+
if (!origin) return null;
|
|
2394
|
+
try {
|
|
2395
|
+
const url = new URL(origin);
|
|
2396
|
+
return `${url.origin}${DIRECTORY_PATH}`;
|
|
2397
|
+
} catch {
|
|
2398
|
+
return null;
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
function findKeyByKid(keys, kid) {
|
|
2402
|
+
for (const k of keys) {
|
|
2403
|
+
if (k.kid === kid) return k;
|
|
2404
|
+
}
|
|
2405
|
+
return null;
|
|
2406
|
+
}
|
|
2407
|
+
|
|
131
2408
|
// src/transport/index.ts
|
|
132
2409
|
function detectProtocol(context) {
|
|
133
2410
|
if (context.metadata && typeof context.metadata === "object") {
|
|
@@ -163,14 +2440,63 @@ function extractCredentialsFromProtocol(protocol, context) {
|
|
|
163
2440
|
}
|
|
164
2441
|
}
|
|
165
2442
|
export {
|
|
2443
|
+
STRIPE_WEBHOOK_INFORMATIONAL_EVENTS,
|
|
166
2444
|
applyCredentials,
|
|
2445
|
+
bindIdentity,
|
|
2446
|
+
claim,
|
|
2447
|
+
clearTransportExtractors,
|
|
2448
|
+
createMastercardRegistry,
|
|
2449
|
+
createVisaRegistry,
|
|
2450
|
+
createWebBotAuthRegistry,
|
|
167
2451
|
detectProtocol,
|
|
2452
|
+
evaluatePaymentMethodAllowlist,
|
|
2453
|
+
evaluateSpendingLimit,
|
|
2454
|
+
evaluateVIConstraints,
|
|
168
2455
|
extractA2ACredentials,
|
|
2456
|
+
extractACPContext,
|
|
2457
|
+
extractACPTransactionValue,
|
|
2458
|
+
extractAP2Mandate,
|
|
2459
|
+
extractAP2Mandates,
|
|
2460
|
+
extractAP2TransactionValue,
|
|
169
2461
|
extractCredentialsFromProtocol,
|
|
170
2462
|
extractHttpCredentials,
|
|
2463
|
+
extractMPPContext,
|
|
2464
|
+
extractMPPFromRequest,
|
|
2465
|
+
extractMPPFromResponse,
|
|
2466
|
+
extractMPPTransactionValue,
|
|
171
2467
|
extractMcpCredentials,
|
|
2468
|
+
extractUCPContext,
|
|
2469
|
+
extractUCPTransactionValue,
|
|
2470
|
+
extractVIClaims,
|
|
2471
|
+
extractVITransactionValue,
|
|
2472
|
+
extractX402Context,
|
|
2473
|
+
extractX402FromRequest,
|
|
2474
|
+
extractX402FromResponse,
|
|
2475
|
+
extractX402TransactionValue,
|
|
2476
|
+
fetchUCPManifest,
|
|
2477
|
+
getTransportExtractor,
|
|
2478
|
+
getTransportExtractors,
|
|
2479
|
+
isStripeWebhookInformational,
|
|
2480
|
+
mapACPRequestToPurpose,
|
|
2481
|
+
mapAP2MandateToPurpose,
|
|
2482
|
+
mapMPPRequestToPurpose,
|
|
2483
|
+
mapRFC9421TagToPurpose,
|
|
2484
|
+
mapUCPRequestToPurpose,
|
|
2485
|
+
mapVIMandateToPurpose,
|
|
2486
|
+
mapX402RequestToPurpose,
|
|
2487
|
+
parseRFC9421,
|
|
2488
|
+
registerTransportExtractor,
|
|
2489
|
+
runCommercePipeline,
|
|
2490
|
+
runMatchingExtractors,
|
|
172
2491
|
setA2AMetadata,
|
|
173
2492
|
setHttpHeaders,
|
|
174
|
-
setMcpMeta
|
|
2493
|
+
setMcpMeta,
|
|
2494
|
+
validateUCPManifest,
|
|
2495
|
+
verifyACPSignature,
|
|
2496
|
+
verifyAP2Chain,
|
|
2497
|
+
verifyMPP,
|
|
2498
|
+
verifyRFC9421,
|
|
2499
|
+
verifyStripeWebhook,
|
|
2500
|
+
verifyVIChain
|
|
175
2501
|
};
|
|
176
2502
|
//# sourceMappingURL=index.mjs.map
|