@agent-score/commerce 2.3.0 → 2.5.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.
Files changed (80) hide show
  1. package/README.md +6 -6
  2. package/dist/challenge/index.d.mts +9 -5
  3. package/dist/challenge/index.d.ts +9 -5
  4. package/dist/challenge/index.js +11 -4
  5. package/dist/challenge/index.js.map +1 -1
  6. package/dist/challenge/index.mjs +11 -4
  7. package/dist/challenge/index.mjs.map +1 -1
  8. package/dist/{checkout-ChyOi7aU.d.ts → checkout-McfNpZJf.d.ts} +80 -12
  9. package/dist/{checkout-Ceo1_rVJ.d.mts → checkout-o17dIxHi.d.mts} +80 -12
  10. package/dist/core.d.mts +27 -7
  11. package/dist/core.d.ts +27 -7
  12. package/dist/core.js +25 -11
  13. package/dist/core.js.map +1 -1
  14. package/dist/core.mjs +25 -11
  15. package/dist/core.mjs.map +1 -1
  16. package/dist/discovery/index.d.mts +26 -10
  17. package/dist/discovery/index.d.ts +26 -10
  18. package/dist/discovery/index.js +58 -10
  19. package/dist/discovery/index.js.map +1 -1
  20. package/dist/discovery/index.mjs +58 -10
  21. package/dist/discovery/index.mjs.map +1 -1
  22. package/dist/gate-CWP10xPQ.d.mts +339 -0
  23. package/dist/gate-CWP10xPQ.d.ts +339 -0
  24. package/dist/identity/express.d.mts +26 -1
  25. package/dist/identity/express.d.ts +26 -1
  26. package/dist/identity/express.js +599 -25
  27. package/dist/identity/express.js.map +1 -1
  28. package/dist/identity/express.mjs +595 -24
  29. package/dist/identity/express.mjs.map +1 -1
  30. package/dist/identity/fastify.d.mts +12 -2
  31. package/dist/identity/fastify.d.ts +12 -2
  32. package/dist/identity/fastify.js +607 -25
  33. package/dist/identity/fastify.js.map +1 -1
  34. package/dist/identity/fastify.mjs +603 -24
  35. package/dist/identity/fastify.mjs.map +1 -1
  36. package/dist/identity/hono.d.mts +26 -1
  37. package/dist/identity/hono.d.ts +26 -1
  38. package/dist/identity/hono.js +588 -25
  39. package/dist/identity/hono.js.map +1 -1
  40. package/dist/identity/hono.mjs +584 -24
  41. package/dist/identity/hono.mjs.map +1 -1
  42. package/dist/identity/nextjs.d.mts +3 -0
  43. package/dist/identity/nextjs.d.ts +3 -0
  44. package/dist/identity/nextjs.js +593 -25
  45. package/dist/identity/nextjs.js.map +1 -1
  46. package/dist/identity/nextjs.mjs +589 -24
  47. package/dist/identity/nextjs.mjs.map +1 -1
  48. package/dist/identity/policy.js.map +1 -1
  49. package/dist/identity/policy.mjs.map +1 -1
  50. package/dist/identity/web.d.mts +24 -1
  51. package/dist/identity/web.d.ts +24 -1
  52. package/dist/identity/web.js +593 -25
  53. package/dist/identity/web.js.map +1 -1
  54. package/dist/identity/web.mjs +589 -24
  55. package/dist/identity/web.mjs.map +1 -1
  56. package/dist/index.d.mts +129 -14
  57. package/dist/index.d.ts +129 -14
  58. package/dist/index.js +978 -99
  59. package/dist/index.js.map +1 -1
  60. package/dist/index.mjs +956 -99
  61. package/dist/index.mjs.map +1 -1
  62. package/dist/{default_rails-DtR_E9N9.d.ts → network_kind-BIJM2peR.d.ts} +22 -8
  63. package/dist/{default_rails-K25PtWrL.d.mts → network_kind-C0EMkdzz.d.mts} +22 -8
  64. package/dist/payment/index.d.mts +16 -26
  65. package/dist/payment/index.d.ts +16 -26
  66. package/dist/payment/index.js +62 -57
  67. package/dist/payment/index.js.map +1 -1
  68. package/dist/payment/index.mjs +62 -57
  69. package/dist/payment/index.mjs.map +1 -1
  70. package/dist/{pricing-B3-aKxSz.d.ts → pricing-CytRwhC2.d.ts} +1 -1
  71. package/dist/{pricing-BReyZiqN.d.mts → pricing-KHDqMLd7.d.mts} +1 -1
  72. package/dist/{rail_spec-B1239jPp.d.mts → rail_spec-BFZmW9RN.d.mts} +3 -4
  73. package/dist/{rail_spec-B1239jPp.d.ts → rail_spec-BFZmW9RN.d.ts} +3 -4
  74. package/dist/stripe-multichain/index.d.mts +2 -9
  75. package/dist/stripe-multichain/index.d.ts +2 -9
  76. package/dist/stripe-multichain/index.js.map +1 -1
  77. package/dist/stripe-multichain/index.mjs.map +1 -1
  78. package/dist/{wwwauthenticate-D_FMnPgU.d.mts → wwwauthenticate-CVaGUMjU.d.mts} +8 -6
  79. package/dist/{wwwauthenticate-D_FMnPgU.d.ts → wwwauthenticate-CVaGUMjU.d.ts} +8 -6
  80. package/package.json +14 -13
@@ -131,7 +131,520 @@ function denialReasonToBody(reason) {
131
131
  return body;
132
132
  }
133
133
 
134
+ // src/aip/verify.ts
135
+ import { decodeJwt, decodeProtectedHeader, importJWK as importJWK2, jwtVerify } from "jose";
136
+
137
+ // src/aip/http-signature.ts
138
+ import { calculateJwkThumbprint, importJWK } from "jose";
139
+ var { subtle } = globalThis.crypto;
140
+ var b64ToBytes = (b64) => {
141
+ const bin = atob(b64);
142
+ const out = new Uint8Array(bin.length);
143
+ for (let i = 0; i < bin.length; i++) {
144
+ out[i] = bin.charCodeAt(i);
145
+ }
146
+ return out;
147
+ };
148
+ var AIP_COVERED_COMPONENTS = ["@method", "@authority", "@path", "agent-identity"];
149
+ var AIP_SIGNATURE_TAG = "agent-identity";
150
+ var DEFAULT_MAX_SKEW_SECONDS = 60;
151
+ var normalizeAuthority = (authority) => {
152
+ const lower = authority.trim().toLowerCase();
153
+ const colon = lower.lastIndexOf(":");
154
+ if (colon === -1) {
155
+ return lower;
156
+ }
157
+ if (lower.includes("]") && colon < lower.indexOf("]")) {
158
+ return lower;
159
+ }
160
+ const host = lower.slice(0, colon);
161
+ const port = lower.slice(colon + 1);
162
+ if (port === "80" || port === "443") {
163
+ return host;
164
+ }
165
+ return lower;
166
+ };
167
+ var componentValue = (name, input) => {
168
+ switch (name) {
169
+ case "@method":
170
+ return input.method.toUpperCase();
171
+ case "@authority":
172
+ return normalizeAuthority(input.authority);
173
+ case "@path":
174
+ return input.path;
175
+ case "agent-identity":
176
+ return input.agentIdentity.trim();
177
+ default:
178
+ return input.extra?.[name] ?? null;
179
+ }
180
+ };
181
+ var serializeComponentList = (components) => `(${components.map((c) => `"${c}"`).join(" ")})`;
182
+ var serializeParams = (p) => {
183
+ const parts = [];
184
+ if (p.created !== void 0) {
185
+ parts.push(`created=${p.created}`);
186
+ }
187
+ if (p.expires !== void 0) {
188
+ parts.push(`expires=${p.expires}`);
189
+ }
190
+ if (p.keyid !== void 0) {
191
+ parts.push(`keyid="${p.keyid}"`);
192
+ }
193
+ if (p.alg !== void 0) {
194
+ parts.push(`alg="${p.alg}"`);
195
+ }
196
+ if (p.tag !== void 0) {
197
+ parts.push(`tag="${p.tag}"`);
198
+ }
199
+ return parts.map((s) => `;${s}`).join("");
200
+ };
201
+ var buildSignatureBase = (params, input) => {
202
+ const lines = [];
203
+ for (const name of params.components) {
204
+ const value = componentValue(name, input);
205
+ if (value === null) {
206
+ throw new MissingComponentError(name);
207
+ }
208
+ lines.push(`"${name}": ${value}`);
209
+ }
210
+ const paramsValue = serializeComponentList(params.components) + serializeParams(params);
211
+ lines.push(`"@signature-params": ${paramsValue}`);
212
+ return lines.join("\n");
213
+ };
214
+ var MissingComponentError = class extends Error {
215
+ constructor(component) {
216
+ super(`signature base missing covered component: ${component}`);
217
+ this.component = component;
218
+ this.name = "MissingComponentError";
219
+ }
220
+ component;
221
+ };
222
+ var parseSignatureInput = (header, tag = AIP_SIGNATURE_TAG) => {
223
+ const members = splitDictionary(header);
224
+ if (members.length === 0) {
225
+ return null;
226
+ }
227
+ const parsed = members.map((m) => {
228
+ const params = parseInnerListMember(m.value);
229
+ return params ? { label: m.label, params } : null;
230
+ }).filter((x) => x !== null);
231
+ if (parsed.length === 0) {
232
+ return null;
233
+ }
234
+ const tagged = parsed.find((p) => p.params.tag === tag);
235
+ if (tagged) {
236
+ return tagged;
237
+ }
238
+ if (parsed.length === 1 && parsed[0].params.tag === void 0) {
239
+ return parsed[0];
240
+ }
241
+ return null;
242
+ };
243
+ var parseSignatureValue = (header, label) => {
244
+ const members = splitDictionary(header);
245
+ const member = members.find((m) => m.label === label);
246
+ if (!member) {
247
+ return null;
248
+ }
249
+ const v = member.value.trim();
250
+ if (!v.startsWith(":") || !v.endsWith(":") || v.length < 2) {
251
+ return null;
252
+ }
253
+ const b64 = v.slice(1, -1);
254
+ try {
255
+ return b64ToBytes(b64);
256
+ } catch {
257
+ return null;
258
+ }
259
+ };
260
+ var splitDictionary = (header) => {
261
+ const out = [];
262
+ let depth = 0;
263
+ let inBytes = false;
264
+ let inString = false;
265
+ let current = "";
266
+ for (let i = 0; i < header.length; i++) {
267
+ const ch = header[i];
268
+ if (inString) {
269
+ current += ch;
270
+ if (ch === '"' && header[i - 1] !== "\\") {
271
+ inString = false;
272
+ }
273
+ continue;
274
+ }
275
+ if (ch === '"') {
276
+ inString = true;
277
+ current += ch;
278
+ continue;
279
+ }
280
+ if (ch === ":") {
281
+ inBytes = !inBytes;
282
+ current += ch;
283
+ continue;
284
+ }
285
+ if (!inBytes && ch === "(") {
286
+ depth++;
287
+ current += ch;
288
+ continue;
289
+ }
290
+ if (!inBytes && ch === ")") {
291
+ depth = Math.max(0, depth - 1);
292
+ current += ch;
293
+ continue;
294
+ }
295
+ if (!inBytes && depth === 0 && ch === ",") {
296
+ pushMember(out, current);
297
+ current = "";
298
+ continue;
299
+ }
300
+ current += ch;
301
+ }
302
+ pushMember(out, current);
303
+ return out;
304
+ };
305
+ var pushMember = (out, raw) => {
306
+ const trimmed = raw.trim();
307
+ if (!trimmed) {
308
+ return;
309
+ }
310
+ const eq = trimmed.indexOf("=");
311
+ if (eq === -1) {
312
+ return;
313
+ }
314
+ const label = trimmed.slice(0, eq).trim();
315
+ const value = trimmed.slice(eq + 1).trim();
316
+ if (label) {
317
+ out.push({ label, value });
318
+ }
319
+ };
320
+ var parseInnerListMember = (value) => {
321
+ const open = value.indexOf("(");
322
+ const close = value.indexOf(")", open + 1);
323
+ if (open === -1 || close === -1) {
324
+ return null;
325
+ }
326
+ const listBody = value.slice(open + 1, close).trim();
327
+ const components = listBody.length === 0 ? [] : (listBody.match(/"[^"]*"/g) ?? []).map((s) => s.slice(1, -1));
328
+ const params = { components };
329
+ const paramStr = value.slice(close + 1);
330
+ const re = /;\s*([a-zA-Z][a-zA-Z0-9_-]*)\s*=\s*("(?:[^"\\]|\\.)*"|-?\d+)/g;
331
+ let match;
332
+ while ((match = re.exec(paramStr)) !== null) {
333
+ const key = match[1];
334
+ const raw = match[2];
335
+ const val = raw.startsWith('"') ? raw.slice(1, -1) : Number(raw);
336
+ if (key === "created") {
337
+ params.created = val;
338
+ } else if (key === "expires") {
339
+ params.expires = val;
340
+ } else if (key === "keyid") {
341
+ params.keyid = val;
342
+ } else if (key === "tag") {
343
+ params.tag = val;
344
+ } else if (key === "alg") {
345
+ params.alg = val;
346
+ }
347
+ }
348
+ return params;
349
+ };
350
+ var verifyMessageSignature = async (input) => {
351
+ const selected = parseSignatureInput(input.signatureInput);
352
+ if (!selected) {
353
+ return { ok: false, reason: "no_aip_signature" };
354
+ }
355
+ const { label, params } = selected;
356
+ if (params.alg !== void 0 && !["ed25519", "eddsa"].includes(params.alg.toLowerCase())) {
357
+ return { ok: false, reason: "unsupported_alg" };
358
+ }
359
+ for (const required of AIP_COVERED_COMPONENTS) {
360
+ if (!params.components.includes(required)) {
361
+ return { ok: false, reason: "missing_covered_component" };
362
+ }
363
+ }
364
+ const now = input.now ?? Math.floor(Date.now() / 1e3);
365
+ const skew = input.maxSkewSeconds ?? DEFAULT_MAX_SKEW_SECONDS;
366
+ if (params.created !== void 0 && params.created > now + skew) {
367
+ return { ok: false, reason: "created_in_future" };
368
+ }
369
+ if (params.expires !== void 0 && params.expires < now - skew) {
370
+ return { ok: false, reason: "expired" };
371
+ }
372
+ if (!params.keyid) {
373
+ return { ok: false, reason: "missing_keyid" };
374
+ }
375
+ const cnf = input.cnfJwk;
376
+ if (cnf.kty !== "OKP" || cnf.crv !== "Ed25519" || typeof cnf.x !== "string" || cnf.x.length === 0) {
377
+ return { ok: false, reason: "unsupported_cnf_key" };
378
+ }
379
+ let thumbprint;
380
+ try {
381
+ thumbprint = await calculateJwkThumbprint(input.cnfJwk, "sha256");
382
+ } catch {
383
+ return { ok: false, reason: "unsupported_cnf_key" };
384
+ }
385
+ if (params.keyid !== thumbprint) {
386
+ return { ok: false, reason: "keyid_mismatch" };
387
+ }
388
+ const sig = parseSignatureValue(input.signature, label);
389
+ if (!sig) {
390
+ return { ok: false, reason: "malformed_signature" };
391
+ }
392
+ let base;
393
+ try {
394
+ base = buildSignatureBase(params, {
395
+ method: input.method,
396
+ authority: input.authority,
397
+ path: input.path,
398
+ agentIdentity: input.agentIdentity,
399
+ extra: input.extraComponents
400
+ });
401
+ } catch (err) {
402
+ if (err instanceof MissingComponentError) {
403
+ return { ok: false, reason: "missing_covered_component" };
404
+ }
405
+ throw err;
406
+ }
407
+ let valid;
408
+ try {
409
+ const key = await importJWK(input.cnfJwk, "EdDSA");
410
+ if (!(key instanceof CryptoKey)) {
411
+ return { ok: false, reason: "signature_invalid" };
412
+ }
413
+ valid = await subtle.verify(
414
+ { name: "Ed25519" },
415
+ key,
416
+ sig,
417
+ new TextEncoder().encode(base)
418
+ );
419
+ } catch {
420
+ return { ok: false, reason: "signature_invalid" };
421
+ }
422
+ return valid ? { ok: true, params } : { ok: false, reason: "signature_invalid" };
423
+ };
424
+
425
+ // src/aip/types.ts
426
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
427
+ var isNonEmptyString = (v) => typeof v === "string" && v.length > 0;
428
+ var isAitShape = (payload) => isObject(payload) && isObject(payload.cnf) && isObject(payload.agent);
429
+ var validateAitPayload = (payload) => {
430
+ if (!isObject(payload)) {
431
+ return { ok: false, reason: "not_an_object" };
432
+ }
433
+ if (!isNonEmptyString(payload.aip_version)) {
434
+ return { ok: false, reason: "missing_aip_version" };
435
+ }
436
+ if (!isNonEmptyString(payload.iss)) {
437
+ return { ok: false, reason: "missing_iss" };
438
+ }
439
+ if (!isNonEmptyString(payload.sub)) {
440
+ return { ok: false, reason: "missing_sub" };
441
+ }
442
+ if (typeof payload.iat !== "number") {
443
+ return { ok: false, reason: "missing_iat" };
444
+ }
445
+ if (typeof payload.exp !== "number") {
446
+ return { ok: false, reason: "missing_exp" };
447
+ }
448
+ if (!isObject(payload.cnf) || !isObject(payload.cnf.jwk)) {
449
+ return { ok: false, reason: "missing_cnf" };
450
+ }
451
+ if (!isObject(payload.agent) || !isNonEmptyString(payload.agent.provider)) {
452
+ return { ok: false, reason: "missing_agent_provider" };
453
+ }
454
+ if (payload.trust_level === "human_confirmed") {
455
+ const auth = payload.auth;
456
+ const amr = isObject(auth) ? auth.amr : void 0;
457
+ if (!Array.isArray(amr) || amr.length === 0) {
458
+ return { ok: false, reason: "human_confirmed_without_amr" };
459
+ }
460
+ }
461
+ return { ok: true, payload };
462
+ };
463
+
464
+ // src/aip/verify.ts
465
+ var AGENT_IDENTITY_HEADER = "agent-identity";
466
+ var verifyAit = async (ctx, opts) => {
467
+ if (ctx.agentIdentityHeaders.length === 0) {
468
+ return { ok: false, reason: "no_token" };
469
+ }
470
+ if (!ctx.signatureInput || !ctx.signature) {
471
+ return { ok: false, reason: "pop_signature_missing" };
472
+ }
473
+ let lastFailure = "malformed_token";
474
+ for (const raw of ctx.agentIdentityHeaders) {
475
+ const token = stripBearer(raw);
476
+ let header;
477
+ let payload;
478
+ try {
479
+ header = decodeProtectedHeader(token);
480
+ payload = decodeJwt(token);
481
+ } catch {
482
+ lastFailure = "malformed_token";
483
+ continue;
484
+ }
485
+ if (header.alg === void 0 || header.alg.toLowerCase() === "none") {
486
+ lastFailure = "malformed_token";
487
+ continue;
488
+ }
489
+ if (!isAitShape(payload)) {
490
+ lastFailure = "malformed_token";
491
+ continue;
492
+ }
493
+ const validated = validateAitPayload(payload);
494
+ if (!validated.ok) {
495
+ lastFailure = "invalid_claims";
496
+ continue;
497
+ }
498
+ const claims = validated.payload;
499
+ const keyLookup = await opts.jwks.getKey(claims.iss, header.kid);
500
+ if (!keyLookup.ok) {
501
+ lastFailure = keyLookup.reason === "untrusted_issuer" || keyLookup.reason === "insecure_issuer" ? "untrusted_issuer" : "key_unavailable";
502
+ continue;
503
+ }
504
+ const jwtClockTolerance = opts.maxSkewSeconds ?? 60;
505
+ try {
506
+ const idpKey = await importJWK2(keyLookup.key, normalizeAlg(header.alg));
507
+ await jwtVerify(token, idpKey, {
508
+ // Pin the signature algorithm allowlist (RFC 8725 §3.1) — also rejects `alg:none`. Without
509
+ // this, jose accepts whatever alg the resolved JWK supports, so a trusted IdP publishing a
510
+ // non-Ed25519 (e.g. RSA/EC) `use:sig` key would let an attacker present an RS256/ES256
511
+ // token that verifies. Matches the server-side allowlist in core/api aip-verify.
512
+ algorithms: AIT_SIGNING_ALGS,
513
+ clockTolerance: jwtClockTolerance,
514
+ currentDate: opts.now !== void 0 ? new Date(opts.now * 1e3) : void 0
515
+ });
516
+ } catch (err) {
517
+ lastFailure = isExpiry(err) ? "expired_token" : "idp_signature_invalid";
518
+ continue;
519
+ }
520
+ const nowSec = opts.now ?? Math.floor(Date.now() / 1e3);
521
+ if (claims.iat > nowSec + jwtClockTolerance) {
522
+ lastFailure = "expired_token";
523
+ continue;
524
+ }
525
+ const popResult = await verifyMessageSignature({
526
+ method: ctx.method,
527
+ authority: ctx.authority,
528
+ path: ctx.path,
529
+ agentIdentity: raw,
530
+ signatureInput: ctx.signatureInput,
531
+ signature: ctx.signature,
532
+ cnfJwk: claims.cnf.jwk,
533
+ now: opts.now,
534
+ maxSkewSeconds: opts.maxSkewSeconds
535
+ });
536
+ if (!popResult.ok) {
537
+ lastFailure = "pop_signature_invalid";
538
+ continue;
539
+ }
540
+ return { ok: true, ait: { payload: claims, iss: claims.iss, cnfJwk: claims.cnf.jwk, token } };
541
+ }
542
+ return { ok: false, reason: lastFailure };
543
+ };
544
+ var stripBearer = (value) => {
545
+ const trimmed = value.trim();
546
+ return /^bearer\s+/i.test(trimmed) ? trimmed.replace(/^bearer\s+/i, "") : trimmed;
547
+ };
548
+ var AIT_SIGNING_ALGS = ["EdDSA", "ES256"];
549
+ var normalizeAlg = (alg) => alg.toLowerCase() === "eddsa" ? "EdDSA" : alg;
550
+ var isExpiry = (err) => typeof err === "object" && err !== null && err.code === "ERR_JWT_EXPIRED";
551
+
552
+ // src/aip/request.ts
553
+ var readAgentIdentityHeaders = (headers) => {
554
+ const raw = headers.get(AGENT_IDENTITY_HEADER);
555
+ if (!raw) {
556
+ return [];
557
+ }
558
+ return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
559
+ };
560
+ var deriveAuthority = (req, url) => req.headers.get("host") ?? url.host;
561
+ var buildVerifyContextFromRequest = (req) => {
562
+ const url = new URL(req.url);
563
+ return {
564
+ method: req.method,
565
+ authority: deriveAuthority(req, url),
566
+ path: url.pathname,
567
+ agentIdentityHeaders: readAgentIdentityHeaders(req.headers),
568
+ signatureInput: req.headers.get("signature-input"),
569
+ signature: req.headers.get("signature")
570
+ };
571
+ };
572
+ var hasAgentIdentityHeader = (req) => readAgentIdentityHeaders(req.headers).length > 0;
573
+
574
+ // src/aip/gate.ts
575
+ var verifyFromContext = async (ctx, opts) => {
576
+ const result = await verifyAit(ctx, { jwks: opts.jwks, now: opts.now, maxSkewSeconds: opts.maxSkewSeconds });
577
+ return result.ok ? { ok: true, ait: result.ait } : { ok: false, failure: result.reason };
578
+ };
579
+ var verifyAitRequest = (req, opts) => verifyFromContext(buildVerifyContextFromRequest(req), opts);
580
+ var aipErrorCode = (failure) => {
581
+ switch (failure) {
582
+ case "no_token":
583
+ case "pop_signature_missing":
584
+ return "agent_identity_required";
585
+ case "untrusted_issuer":
586
+ return "untrusted_issuer";
587
+ case "expired_token":
588
+ return "expired_token";
589
+ case "invalid_claims":
590
+ return "insufficient_claims";
591
+ case "key_unavailable":
592
+ return "idp_unavailable";
593
+ case "malformed_token":
594
+ case "idp_signature_invalid":
595
+ case "pop_signature_invalid":
596
+ return "invalid_signature";
597
+ default:
598
+ return "invalid_signature";
599
+ }
600
+ };
601
+ var aipErrorStatus = (failure) => {
602
+ switch (failure) {
603
+ case "key_unavailable":
604
+ return 503;
605
+ case "untrusted_issuer":
606
+ case "invalid_claims":
607
+ return 403;
608
+ default:
609
+ return 401;
610
+ }
611
+ };
612
+ var aipErrorDetail = (failure) => {
613
+ switch (failure) {
614
+ case "no_token":
615
+ return "No Agent-Identity token was presented.";
616
+ case "pop_signature_missing":
617
+ return "The request is missing the RFC 9421 HTTP Message Signature that proves possession of the token-bound key.";
618
+ case "untrusted_issuer":
619
+ return "The token's issuer is not in this service's trusted-issuer list.";
620
+ case "expired_token":
621
+ return "The Agent Identity Token has expired.";
622
+ case "invalid_claims":
623
+ return "The token is missing required claims for this endpoint.";
624
+ case "malformed_token":
625
+ return "The Agent-Identity header could not be parsed as an Agent Identity Token.";
626
+ case "idp_signature_invalid":
627
+ return "The identity provider's signature on the token failed verification.";
628
+ case "pop_signature_invalid":
629
+ return "The request signature did not match the key bound to the token.";
630
+ case "key_unavailable":
631
+ return "The identity provider's signing key could not be resolved.";
632
+ default:
633
+ return "Token verification failed.";
634
+ }
635
+ };
636
+ var buildAipErrorBody = (failure) => {
637
+ const code = aipErrorCode(failure);
638
+ return {
639
+ type: `urn:aip:error:${code}`,
640
+ title: code.replace(/_/g, " "),
641
+ status: aipErrorStatus(failure),
642
+ detail: aipErrorDetail(failure)
643
+ };
644
+ };
645
+
134
646
  // src/core.ts
647
+ import { createHash } from "crypto";
135
648
  import {
136
649
  AgentScore,
137
650
  InvalidCredentialError,
@@ -233,8 +746,9 @@ var INVALID_CREDENTIAL_INSTRUCTIONS = JSON.stringify({
233
746
  ],
234
747
  user_message: "The operator_token is not recognized. Use a different stored token, or restart the verification session flow to mint a new one."
235
748
  });
236
- function buildAgentMemoryHint() {
749
+ function buildAgentMemoryHint(aipTrustedIssuers) {
237
750
  const api = CANONICAL_AGENTSCORE_API;
751
+ const acceptsAip = aipTrustedIssuers !== void 0 && aipTrustedIssuers.length > 0;
238
752
  return {
239
753
  save_for_future_agentscore_gates: true,
240
754
  pattern_summary: "AgentScore is a cross-merchant identity substrate for agent commerce. Any endpoint that returns 403 missing_identity / identity_verification_required or 402 challenges referencing AgentScore uses the same identity system. One KYC works across all AgentScore merchants \u2014 no re-verification per site. Save this pattern (and the endpoints below) to persistent memory so future AgentScore encounters skip the cold-start session flow.",
@@ -242,8 +756,12 @@ function buildAgentMemoryHint() {
242
756
  identity_check_endpoint: `${api}/v1/credentials`,
243
757
  identity_paths: {
244
758
  wallet: "If paying from a crypto wallet you have used before on any AgentScore merchant, send `X-Wallet-Address: 0x...`. Shortest path; no token lifecycle to manage.",
245
- operator_token: "For any rail (Stripe SPT, card, or a wallet you have not linked yet), send `X-Operator-Token: opc_...`. Reusable across merchants until the token expires."
759
+ operator_token: "For any rail (Stripe SPT, card, or a wallet you have not linked yet), send `X-Operator-Token: opc_...`. Reusable across merchants until the token expires.",
760
+ ...acceptsAip && {
761
+ agent_identity: 'If you hold an AIP Agent Identity Token from a trusted issuer (see aip_trusted_issuers), present it: send the JWT in an `Agent-Identity` header plus an RFC 9421 HTTP Message Signature (Signature-Input + Signature over @method @authority @path agent-identity, tag="agent-identity") signed with the token-bound cnf key. The merchant verifies it and applies its policy \u2014 no separate AgentScore credential needed.'
762
+ }
246
763
  },
764
+ ...acceptsAip && { aip_trusted_issuers: aipTrustedIssuers },
247
765
  bootstrap: "If you have neither a linked wallet nor a valid operator_token, follow the session/verify flow in the per-request `agent_instructions` block. This happens at most once per agent identity \u2014 after first verification, the operator_token and any subsequently used wallet are reusable everywhere.",
248
766
  do_not_persist_in_memory: ["operator_token", "poll_secret"],
249
767
  persist_in_credential_store: ["operator_token"]
@@ -265,11 +783,12 @@ function createAgentScoreCore(options) {
265
783
  baseUrl: rawBaseUrl = "https://api.agentscore.sh",
266
784
  chain: gateChain,
267
785
  userAgent,
268
- createSessionOnMissing
786
+ createSessionOnMissing,
787
+ aipTrustedIssuers
269
788
  } = options;
270
789
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
271
- const agentMemoryHint = buildAgentMemoryHint();
272
- const defaultUa = `@agent-score/commerce@${"2.3.0"}`;
790
+ const agentMemoryHint = buildAgentMemoryHint(aipTrustedIssuers);
791
+ const defaultUa = `@agent-score/commerce@${"2.5.0"}`;
273
792
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
274
793
  const sdk = new AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
275
794
  const sessionSdkCache = /* @__PURE__ */ new Map();
@@ -287,6 +806,7 @@ function createAgentScoreCore(options) {
287
806
  return s;
288
807
  }
289
808
  const cache = new TTLCache(cacheSeconds * 1e3);
809
+ const lastSignerRaw = /* @__PURE__ */ new Map();
290
810
  async function tryMintSessionDenial(ctx) {
291
811
  if (!createSessionOnMissing) return void 0;
292
812
  try {
@@ -344,13 +864,18 @@ function createAgentScoreCore(options) {
344
864
  }
345
865
  }
346
866
  async function evaluate(identity, ctx, signer) {
347
- if (!identity || !identity.address && !identity.operatorToken) {
867
+ if (!identity || !identity.address?.trim() && !identity.operatorToken?.trim() && !identity.aipToken?.trim()) {
348
868
  if (failOpen) return { kind: "allow" };
349
869
  const sessionReason = await tryMintSessionDenial(ctx);
350
870
  if (sessionReason) return { kind: "deny", reason: sessionReason };
871
+ const acceptsAip = aipTrustedIssuers !== void 0 && aipTrustedIssuers.length > 0;
872
+ const aipStep = acceptsAip ? [
873
+ `If you hold an AIP Agent Identity Token from a trusted issuer (${aipTrustedIssuers.join(", ")}): present it \u2014 send the JWT in an Agent-Identity header plus an RFC 9421 HTTP Message Signature (Signature-Input + Signature over @method @authority @path agent-identity, tag="agent-identity") signed with the token-bound cnf key. This satisfies identity in one round trip without an AgentScore credential.`
874
+ ] : [];
351
875
  const missingIdentityInstructions = JSON.stringify({
352
876
  action: "probe_identity_then_session",
353
877
  steps: [
878
+ ...aipStep,
354
879
  "If you have a wallet AND this merchant accepts a wallet-signing rail (Tempo MPP or x402 \u2014 see openapi.json x-payment-info): send X-Wallet-Address and retry. If the wallet is already linked to an AgentScore operator (via prior SIWE claim or prior captureWallet), this passes in one round trip. If the wallet is unlinked or the account has no KYC, the 403 will include a verify_url \u2014 share it with the user to claim the wallet + complete KYC, then retry.",
355
880
  "If step 1 is denied or you already have a stored operator_token (valid + not expired): send X-Operator-Token: opc_... and retry.",
356
881
  "If neither applies: retry with NO identity header. Merchants that auto-create verification sessions (most AgentScore merchants do) return verify_url + session_id + poll_secret in the 403 body \u2014 share verify_url with the user, then poll poll_url every 5s with the X-Poll-Secret header until status=verified (the poll returns a one-time operator_token). If the retry returns the same bare 403, this merchant does not support self-service session bootstrapping \u2014 direct the user to https://agentscore.sh/sign-up to create an AgentScore identity and mint an operator_token from their dashboard (https://agentscore.sh/dashboard/verify). The user hands the opc_... to you, and you retry with X-Operator-Token."
@@ -366,7 +891,7 @@ function createAgentScoreCore(options) {
366
891
  }
367
892
  };
368
893
  }
369
- const cacheKey = identity.operatorToken?.toLowerCase() ?? (identity.address ? normalizeAddress(identity.address) : "");
894
+ const cacheKey = identity.aipToken ? `aip:${createHash("sha256").update(identity.aipToken).digest("hex")}` : identity.operatorToken?.toLowerCase() ?? (identity.address ? normalizeAddress(identity.address) : "");
370
895
  const cached = cache.get(cacheKey);
371
896
  if (cached) {
372
897
  if (cached.allow) {
@@ -411,7 +936,7 @@ function createAgentScoreCore(options) {
411
936
  // regardless of policy.require_sanctions_clear (which gates the separate NAME screen).
412
937
  ...signer && { signer: { address: signer.address, network: signer.network } }
413
938
  };
414
- const result = identity.address ? await sdk.assess(identity.address, { ...opts, operatorToken: identity.operatorToken }) : await sdk.assess(null, { ...opts, operatorToken: identity.operatorToken });
939
+ const result = identity.aipToken ? await sdk.assess(null, { ...opts, aipToken: identity.aipToken }) : identity.address ? await sdk.assess(identity.address, { ...opts, operatorToken: identity.operatorToken }) : await sdk.assess(null, { ...opts, operatorToken: identity.operatorToken });
415
940
  data = result;
416
941
  } catch (err) {
417
942
  if (err instanceof PaymentRequiredError) {
@@ -482,6 +1007,9 @@ function createAgentScoreCore(options) {
482
1007
  const decisionReasons = data.decision_reasons ?? [];
483
1008
  const allow = decision === "allow" || decision == null;
484
1009
  cache.set(cacheKey, { allow, decision: decision ?? void 0, reasons: decisionReasons, raw: data });
1010
+ if (identity.address !== void 0 && identity.operatorToken === void 0 && identity.aipToken === void 0 && (data.signer_match !== void 0 || data.signer_sanctions !== void 0)) {
1011
+ lastSignerRaw.set(normalizeAddress(identity.address), data);
1012
+ }
485
1013
  if (allow) {
486
1014
  const quota = data.quota;
487
1015
  return {
@@ -546,9 +1074,7 @@ function createAgentScoreCore(options) {
546
1074
  }
547
1075
  function getSignerVerdict(claimedAddress) {
548
1076
  const claimedNorm = normalizeAddress(claimedAddress);
549
- const cached = cache.get(claimedNorm);
550
- if (!cached) return void 0;
551
- const raw = cached.raw;
1077
+ const raw = lastSignerRaw.get(claimedNorm) ?? cache.get(claimedNorm)?.raw;
552
1078
  if (!raw) return void 0;
553
1079
  const rawMatch = raw.signer_match;
554
1080
  const rawSanctions = raw.signer_sanctions;
@@ -626,6 +1152,18 @@ async function extractSolanaSignerFromCredential(credential) {
626
1152
  }
627
1153
  }
628
1154
  async function extractPaymentSigner(request, x402PaymentHeader) {
1155
+ if (x402PaymentHeader) {
1156
+ try {
1157
+ const decoded = atob(x402PaymentHeader);
1158
+ const parsed = JSON.parse(decoded);
1159
+ const from = parsed?.payload?.authorization?.from;
1160
+ if (typeof from === "string" && /^0x[0-9a-fA-F]{40}$/.test(from)) {
1161
+ return { address: from.toLowerCase(), network: "evm" };
1162
+ }
1163
+ } catch (err) {
1164
+ console.warn("[gate] x402 signer extraction failed:", err instanceof Error ? err.message : err);
1165
+ }
1166
+ }
629
1167
  const authHeader = request.headers.get("authorization");
630
1168
  if (authHeader) {
631
1169
  try {
@@ -645,18 +1183,6 @@ async function extractPaymentSigner(request, x402PaymentHeader) {
645
1183
  console.warn("[gate] MPP signer extraction failed:", err instanceof Error ? err.message : err);
646
1184
  }
647
1185
  }
648
- if (x402PaymentHeader) {
649
- try {
650
- const decoded = atob(x402PaymentHeader);
651
- const parsed = JSON.parse(decoded);
652
- const from = parsed?.payload?.authorization?.from;
653
- if (typeof from === "string" && /^0x[0-9a-fA-F]{40}$/.test(from)) {
654
- return { address: from.toLowerCase(), network: "evm" };
655
- }
656
- } catch (err) {
657
- console.warn("[gate] x402 signer extraction failed:", err instanceof Error ? err.message : err);
658
- }
659
- }
660
1186
  return null;
661
1187
  }
662
1188
  function readX402PaymentHeader(request) {
@@ -734,10 +1260,49 @@ function withConditionalAgentScoreGate(options, handler) {
734
1260
  return wrapped(req, ctx);
735
1261
  };
736
1262
  }
1263
+ var defaultAipResponse = (body) => new Response(JSON.stringify(body), { status: body.status, headers: { "content-type": "application/problem+json" } });
1264
+ function createAipGate(options) {
1265
+ const { onDenied, ...gateOpts } = options;
1266
+ return async (req) => {
1267
+ const result = await verifyAitRequest(req, gateOpts);
1268
+ if (result.ok) {
1269
+ return { allowed: true, ait: result.ait };
1270
+ }
1271
+ const body = buildAipErrorBody(result.failure);
1272
+ const response = onDenied ? await onDenied(req, body) : defaultAipResponse(body);
1273
+ return { allowed: false, response };
1274
+ };
1275
+ }
1276
+ function withAipGate(options, handler) {
1277
+ const guard = createAipGate(options);
1278
+ return async (req, ctx) => {
1279
+ const result = await guard(req);
1280
+ if (!result.allowed) {
1281
+ return result.response;
1282
+ }
1283
+ return handler(req, { ait: result.ait }, ctx);
1284
+ };
1285
+ }
1286
+ function withConditionalAipGate(options, handler) {
1287
+ const guard = createAipGate(options);
1288
+ return async (req, ctx) => {
1289
+ if (!hasAgentIdentityHeader(req)) {
1290
+ return handler(req, {}, ctx);
1291
+ }
1292
+ const result = await guard(req);
1293
+ if (!result.allowed) {
1294
+ return result.response;
1295
+ }
1296
+ return handler(req, { ait: result.ait }, ctx);
1297
+ };
1298
+ }
737
1299
  export {
738
1300
  createAgentScoreGate,
1301
+ createAipGate,
739
1302
  createConditionalAgentScoreGate,
740
1303
  withAgentScoreGate,
741
- withConditionalAgentScoreGate
1304
+ withAipGate,
1305
+ withConditionalAgentScoreGate,
1306
+ withConditionalAipGate
742
1307
  };
743
1308
  //# sourceMappingURL=web.mjs.map