@agent-score/commerce 2.4.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 (59) hide show
  1. package/dist/challenge/index.d.mts +5 -1
  2. package/dist/challenge/index.d.ts +5 -1
  3. package/dist/challenge/index.js +11 -4
  4. package/dist/challenge/index.js.map +1 -1
  5. package/dist/challenge/index.mjs +11 -4
  6. package/dist/challenge/index.mjs.map +1 -1
  7. package/dist/{checkout-B-MIzYzW.d.ts → checkout-McfNpZJf.d.ts} +72 -1
  8. package/dist/{checkout-Bn7ZKIBD.d.mts → checkout-o17dIxHi.d.mts} +72 -1
  9. package/dist/core.d.mts +23 -1
  10. package/dist/core.d.ts +23 -1
  11. package/dist/core.js +25 -11
  12. package/dist/core.js.map +1 -1
  13. package/dist/core.mjs +25 -11
  14. package/dist/core.mjs.map +1 -1
  15. package/dist/discovery/index.d.mts +17 -2
  16. package/dist/discovery/index.d.ts +17 -2
  17. package/dist/discovery/index.js +14 -4
  18. package/dist/discovery/index.js.map +1 -1
  19. package/dist/discovery/index.mjs +14 -4
  20. package/dist/discovery/index.mjs.map +1 -1
  21. package/dist/gate-CWP10xPQ.d.mts +339 -0
  22. package/dist/gate-CWP10xPQ.d.ts +339 -0
  23. package/dist/identity/express.d.mts +26 -1
  24. package/dist/identity/express.d.ts +26 -1
  25. package/dist/identity/express.js +587 -13
  26. package/dist/identity/express.js.map +1 -1
  27. package/dist/identity/express.mjs +583 -12
  28. package/dist/identity/express.mjs.map +1 -1
  29. package/dist/identity/fastify.d.mts +12 -2
  30. package/dist/identity/fastify.d.ts +12 -2
  31. package/dist/identity/fastify.js +595 -13
  32. package/dist/identity/fastify.js.map +1 -1
  33. package/dist/identity/fastify.mjs +591 -12
  34. package/dist/identity/fastify.mjs.map +1 -1
  35. package/dist/identity/hono.d.mts +26 -1
  36. package/dist/identity/hono.d.ts +26 -1
  37. package/dist/identity/hono.js +576 -13
  38. package/dist/identity/hono.js.map +1 -1
  39. package/dist/identity/hono.mjs +572 -12
  40. package/dist/identity/hono.mjs.map +1 -1
  41. package/dist/identity/nextjs.d.mts +3 -0
  42. package/dist/identity/nextjs.d.ts +3 -0
  43. package/dist/identity/nextjs.js +581 -13
  44. package/dist/identity/nextjs.js.map +1 -1
  45. package/dist/identity/nextjs.mjs +577 -12
  46. package/dist/identity/nextjs.mjs.map +1 -1
  47. package/dist/identity/web.d.mts +24 -1
  48. package/dist/identity/web.d.ts +24 -1
  49. package/dist/identity/web.js +581 -13
  50. package/dist/identity/web.js.map +1 -1
  51. package/dist/identity/web.mjs +577 -12
  52. package/dist/identity/web.mjs.map +1 -1
  53. package/dist/index.d.mts +119 -3
  54. package/dist/index.d.ts +119 -3
  55. package/dist/index.js +893 -35
  56. package/dist/index.js.map +1 -1
  57. package/dist/index.mjs +873 -35
  58. package/dist/index.mjs.map +1 -1
  59. package/package.json +11 -11
@@ -22,8 +22,11 @@ var nextjs_exports = {};
22
22
  __export(nextjs_exports, {
23
23
  agentscoreMiddleware: () => agentscoreMiddleware,
24
24
  conditionalAgentscoreMiddleware: () => conditionalAgentscoreMiddleware,
25
+ createAipGate: () => createAipGate,
25
26
  withAgentScoreGate: () => withAgentScoreGate,
26
- withConditionalAgentScoreGate: () => withConditionalAgentScoreGate
27
+ withAipGate: () => withAipGate,
28
+ withConditionalAgentScoreGate: () => withConditionalAgentScoreGate,
29
+ withConditionalAipGate: () => withConditionalAipGate
27
30
  });
28
31
  module.exports = __toCommonJS(nextjs_exports);
29
32
 
@@ -184,7 +187,520 @@ function denialReasonToBody(reason) {
184
187
  return body;
185
188
  }
186
189
 
190
+ // src/aip/verify.ts
191
+ var import_jose2 = require("jose");
192
+
193
+ // src/aip/http-signature.ts
194
+ var import_jose = require("jose");
195
+ var { subtle } = globalThis.crypto;
196
+ var b64ToBytes = (b64) => {
197
+ const bin = atob(b64);
198
+ const out = new Uint8Array(bin.length);
199
+ for (let i = 0; i < bin.length; i++) {
200
+ out[i] = bin.charCodeAt(i);
201
+ }
202
+ return out;
203
+ };
204
+ var AIP_COVERED_COMPONENTS = ["@method", "@authority", "@path", "agent-identity"];
205
+ var AIP_SIGNATURE_TAG = "agent-identity";
206
+ var DEFAULT_MAX_SKEW_SECONDS = 60;
207
+ var normalizeAuthority = (authority) => {
208
+ const lower = authority.trim().toLowerCase();
209
+ const colon = lower.lastIndexOf(":");
210
+ if (colon === -1) {
211
+ return lower;
212
+ }
213
+ if (lower.includes("]") && colon < lower.indexOf("]")) {
214
+ return lower;
215
+ }
216
+ const host = lower.slice(0, colon);
217
+ const port = lower.slice(colon + 1);
218
+ if (port === "80" || port === "443") {
219
+ return host;
220
+ }
221
+ return lower;
222
+ };
223
+ var componentValue = (name, input) => {
224
+ switch (name) {
225
+ case "@method":
226
+ return input.method.toUpperCase();
227
+ case "@authority":
228
+ return normalizeAuthority(input.authority);
229
+ case "@path":
230
+ return input.path;
231
+ case "agent-identity":
232
+ return input.agentIdentity.trim();
233
+ default:
234
+ return input.extra?.[name] ?? null;
235
+ }
236
+ };
237
+ var serializeComponentList = (components) => `(${components.map((c) => `"${c}"`).join(" ")})`;
238
+ var serializeParams = (p) => {
239
+ const parts = [];
240
+ if (p.created !== void 0) {
241
+ parts.push(`created=${p.created}`);
242
+ }
243
+ if (p.expires !== void 0) {
244
+ parts.push(`expires=${p.expires}`);
245
+ }
246
+ if (p.keyid !== void 0) {
247
+ parts.push(`keyid="${p.keyid}"`);
248
+ }
249
+ if (p.alg !== void 0) {
250
+ parts.push(`alg="${p.alg}"`);
251
+ }
252
+ if (p.tag !== void 0) {
253
+ parts.push(`tag="${p.tag}"`);
254
+ }
255
+ return parts.map((s) => `;${s}`).join("");
256
+ };
257
+ var buildSignatureBase = (params, input) => {
258
+ const lines = [];
259
+ for (const name of params.components) {
260
+ const value = componentValue(name, input);
261
+ if (value === null) {
262
+ throw new MissingComponentError(name);
263
+ }
264
+ lines.push(`"${name}": ${value}`);
265
+ }
266
+ const paramsValue = serializeComponentList(params.components) + serializeParams(params);
267
+ lines.push(`"@signature-params": ${paramsValue}`);
268
+ return lines.join("\n");
269
+ };
270
+ var MissingComponentError = class extends Error {
271
+ constructor(component) {
272
+ super(`signature base missing covered component: ${component}`);
273
+ this.component = component;
274
+ this.name = "MissingComponentError";
275
+ }
276
+ component;
277
+ };
278
+ var parseSignatureInput = (header, tag = AIP_SIGNATURE_TAG) => {
279
+ const members = splitDictionary(header);
280
+ if (members.length === 0) {
281
+ return null;
282
+ }
283
+ const parsed = members.map((m) => {
284
+ const params = parseInnerListMember(m.value);
285
+ return params ? { label: m.label, params } : null;
286
+ }).filter((x) => x !== null);
287
+ if (parsed.length === 0) {
288
+ return null;
289
+ }
290
+ const tagged = parsed.find((p) => p.params.tag === tag);
291
+ if (tagged) {
292
+ return tagged;
293
+ }
294
+ if (parsed.length === 1 && parsed[0].params.tag === void 0) {
295
+ return parsed[0];
296
+ }
297
+ return null;
298
+ };
299
+ var parseSignatureValue = (header, label) => {
300
+ const members = splitDictionary(header);
301
+ const member = members.find((m) => m.label === label);
302
+ if (!member) {
303
+ return null;
304
+ }
305
+ const v = member.value.trim();
306
+ if (!v.startsWith(":") || !v.endsWith(":") || v.length < 2) {
307
+ return null;
308
+ }
309
+ const b64 = v.slice(1, -1);
310
+ try {
311
+ return b64ToBytes(b64);
312
+ } catch {
313
+ return null;
314
+ }
315
+ };
316
+ var splitDictionary = (header) => {
317
+ const out = [];
318
+ let depth = 0;
319
+ let inBytes = false;
320
+ let inString = false;
321
+ let current = "";
322
+ for (let i = 0; i < header.length; i++) {
323
+ const ch = header[i];
324
+ if (inString) {
325
+ current += ch;
326
+ if (ch === '"' && header[i - 1] !== "\\") {
327
+ inString = false;
328
+ }
329
+ continue;
330
+ }
331
+ if (ch === '"') {
332
+ inString = true;
333
+ current += ch;
334
+ continue;
335
+ }
336
+ if (ch === ":") {
337
+ inBytes = !inBytes;
338
+ current += ch;
339
+ continue;
340
+ }
341
+ if (!inBytes && ch === "(") {
342
+ depth++;
343
+ current += ch;
344
+ continue;
345
+ }
346
+ if (!inBytes && ch === ")") {
347
+ depth = Math.max(0, depth - 1);
348
+ current += ch;
349
+ continue;
350
+ }
351
+ if (!inBytes && depth === 0 && ch === ",") {
352
+ pushMember(out, current);
353
+ current = "";
354
+ continue;
355
+ }
356
+ current += ch;
357
+ }
358
+ pushMember(out, current);
359
+ return out;
360
+ };
361
+ var pushMember = (out, raw) => {
362
+ const trimmed = raw.trim();
363
+ if (!trimmed) {
364
+ return;
365
+ }
366
+ const eq = trimmed.indexOf("=");
367
+ if (eq === -1) {
368
+ return;
369
+ }
370
+ const label = trimmed.slice(0, eq).trim();
371
+ const value = trimmed.slice(eq + 1).trim();
372
+ if (label) {
373
+ out.push({ label, value });
374
+ }
375
+ };
376
+ var parseInnerListMember = (value) => {
377
+ const open = value.indexOf("(");
378
+ const close = value.indexOf(")", open + 1);
379
+ if (open === -1 || close === -1) {
380
+ return null;
381
+ }
382
+ const listBody = value.slice(open + 1, close).trim();
383
+ const components = listBody.length === 0 ? [] : (listBody.match(/"[^"]*"/g) ?? []).map((s) => s.slice(1, -1));
384
+ const params = { components };
385
+ const paramStr = value.slice(close + 1);
386
+ const re = /;\s*([a-zA-Z][a-zA-Z0-9_-]*)\s*=\s*("(?:[^"\\]|\\.)*"|-?\d+)/g;
387
+ let match;
388
+ while ((match = re.exec(paramStr)) !== null) {
389
+ const key = match[1];
390
+ const raw = match[2];
391
+ const val = raw.startsWith('"') ? raw.slice(1, -1) : Number(raw);
392
+ if (key === "created") {
393
+ params.created = val;
394
+ } else if (key === "expires") {
395
+ params.expires = val;
396
+ } else if (key === "keyid") {
397
+ params.keyid = val;
398
+ } else if (key === "tag") {
399
+ params.tag = val;
400
+ } else if (key === "alg") {
401
+ params.alg = val;
402
+ }
403
+ }
404
+ return params;
405
+ };
406
+ var verifyMessageSignature = async (input) => {
407
+ const selected = parseSignatureInput(input.signatureInput);
408
+ if (!selected) {
409
+ return { ok: false, reason: "no_aip_signature" };
410
+ }
411
+ const { label, params } = selected;
412
+ if (params.alg !== void 0 && !["ed25519", "eddsa"].includes(params.alg.toLowerCase())) {
413
+ return { ok: false, reason: "unsupported_alg" };
414
+ }
415
+ for (const required of AIP_COVERED_COMPONENTS) {
416
+ if (!params.components.includes(required)) {
417
+ return { ok: false, reason: "missing_covered_component" };
418
+ }
419
+ }
420
+ const now = input.now ?? Math.floor(Date.now() / 1e3);
421
+ const skew = input.maxSkewSeconds ?? DEFAULT_MAX_SKEW_SECONDS;
422
+ if (params.created !== void 0 && params.created > now + skew) {
423
+ return { ok: false, reason: "created_in_future" };
424
+ }
425
+ if (params.expires !== void 0 && params.expires < now - skew) {
426
+ return { ok: false, reason: "expired" };
427
+ }
428
+ if (!params.keyid) {
429
+ return { ok: false, reason: "missing_keyid" };
430
+ }
431
+ const cnf = input.cnfJwk;
432
+ if (cnf.kty !== "OKP" || cnf.crv !== "Ed25519" || typeof cnf.x !== "string" || cnf.x.length === 0) {
433
+ return { ok: false, reason: "unsupported_cnf_key" };
434
+ }
435
+ let thumbprint;
436
+ try {
437
+ thumbprint = await (0, import_jose.calculateJwkThumbprint)(input.cnfJwk, "sha256");
438
+ } catch {
439
+ return { ok: false, reason: "unsupported_cnf_key" };
440
+ }
441
+ if (params.keyid !== thumbprint) {
442
+ return { ok: false, reason: "keyid_mismatch" };
443
+ }
444
+ const sig = parseSignatureValue(input.signature, label);
445
+ if (!sig) {
446
+ return { ok: false, reason: "malformed_signature" };
447
+ }
448
+ let base;
449
+ try {
450
+ base = buildSignatureBase(params, {
451
+ method: input.method,
452
+ authority: input.authority,
453
+ path: input.path,
454
+ agentIdentity: input.agentIdentity,
455
+ extra: input.extraComponents
456
+ });
457
+ } catch (err) {
458
+ if (err instanceof MissingComponentError) {
459
+ return { ok: false, reason: "missing_covered_component" };
460
+ }
461
+ throw err;
462
+ }
463
+ let valid;
464
+ try {
465
+ const key = await (0, import_jose.importJWK)(input.cnfJwk, "EdDSA");
466
+ if (!(key instanceof CryptoKey)) {
467
+ return { ok: false, reason: "signature_invalid" };
468
+ }
469
+ valid = await subtle.verify(
470
+ { name: "Ed25519" },
471
+ key,
472
+ sig,
473
+ new TextEncoder().encode(base)
474
+ );
475
+ } catch {
476
+ return { ok: false, reason: "signature_invalid" };
477
+ }
478
+ return valid ? { ok: true, params } : { ok: false, reason: "signature_invalid" };
479
+ };
480
+
481
+ // src/aip/types.ts
482
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
483
+ var isNonEmptyString = (v) => typeof v === "string" && v.length > 0;
484
+ var isAitShape = (payload) => isObject(payload) && isObject(payload.cnf) && isObject(payload.agent);
485
+ var validateAitPayload = (payload) => {
486
+ if (!isObject(payload)) {
487
+ return { ok: false, reason: "not_an_object" };
488
+ }
489
+ if (!isNonEmptyString(payload.aip_version)) {
490
+ return { ok: false, reason: "missing_aip_version" };
491
+ }
492
+ if (!isNonEmptyString(payload.iss)) {
493
+ return { ok: false, reason: "missing_iss" };
494
+ }
495
+ if (!isNonEmptyString(payload.sub)) {
496
+ return { ok: false, reason: "missing_sub" };
497
+ }
498
+ if (typeof payload.iat !== "number") {
499
+ return { ok: false, reason: "missing_iat" };
500
+ }
501
+ if (typeof payload.exp !== "number") {
502
+ return { ok: false, reason: "missing_exp" };
503
+ }
504
+ if (!isObject(payload.cnf) || !isObject(payload.cnf.jwk)) {
505
+ return { ok: false, reason: "missing_cnf" };
506
+ }
507
+ if (!isObject(payload.agent) || !isNonEmptyString(payload.agent.provider)) {
508
+ return { ok: false, reason: "missing_agent_provider" };
509
+ }
510
+ if (payload.trust_level === "human_confirmed") {
511
+ const auth = payload.auth;
512
+ const amr = isObject(auth) ? auth.amr : void 0;
513
+ if (!Array.isArray(amr) || amr.length === 0) {
514
+ return { ok: false, reason: "human_confirmed_without_amr" };
515
+ }
516
+ }
517
+ return { ok: true, payload };
518
+ };
519
+
520
+ // src/aip/verify.ts
521
+ var AGENT_IDENTITY_HEADER = "agent-identity";
522
+ var verifyAit = async (ctx, opts) => {
523
+ if (ctx.agentIdentityHeaders.length === 0) {
524
+ return { ok: false, reason: "no_token" };
525
+ }
526
+ if (!ctx.signatureInput || !ctx.signature) {
527
+ return { ok: false, reason: "pop_signature_missing" };
528
+ }
529
+ let lastFailure = "malformed_token";
530
+ for (const raw of ctx.agentIdentityHeaders) {
531
+ const token = stripBearer(raw);
532
+ let header;
533
+ let payload;
534
+ try {
535
+ header = (0, import_jose2.decodeProtectedHeader)(token);
536
+ payload = (0, import_jose2.decodeJwt)(token);
537
+ } catch {
538
+ lastFailure = "malformed_token";
539
+ continue;
540
+ }
541
+ if (header.alg === void 0 || header.alg.toLowerCase() === "none") {
542
+ lastFailure = "malformed_token";
543
+ continue;
544
+ }
545
+ if (!isAitShape(payload)) {
546
+ lastFailure = "malformed_token";
547
+ continue;
548
+ }
549
+ const validated = validateAitPayload(payload);
550
+ if (!validated.ok) {
551
+ lastFailure = "invalid_claims";
552
+ continue;
553
+ }
554
+ const claims = validated.payload;
555
+ const keyLookup = await opts.jwks.getKey(claims.iss, header.kid);
556
+ if (!keyLookup.ok) {
557
+ lastFailure = keyLookup.reason === "untrusted_issuer" || keyLookup.reason === "insecure_issuer" ? "untrusted_issuer" : "key_unavailable";
558
+ continue;
559
+ }
560
+ const jwtClockTolerance = opts.maxSkewSeconds ?? 60;
561
+ try {
562
+ const idpKey = await (0, import_jose2.importJWK)(keyLookup.key, normalizeAlg(header.alg));
563
+ await (0, import_jose2.jwtVerify)(token, idpKey, {
564
+ // Pin the signature algorithm allowlist (RFC 8725 §3.1) — also rejects `alg:none`. Without
565
+ // this, jose accepts whatever alg the resolved JWK supports, so a trusted IdP publishing a
566
+ // non-Ed25519 (e.g. RSA/EC) `use:sig` key would let an attacker present an RS256/ES256
567
+ // token that verifies. Matches the server-side allowlist in core/api aip-verify.
568
+ algorithms: AIT_SIGNING_ALGS,
569
+ clockTolerance: jwtClockTolerance,
570
+ currentDate: opts.now !== void 0 ? new Date(opts.now * 1e3) : void 0
571
+ });
572
+ } catch (err) {
573
+ lastFailure = isExpiry(err) ? "expired_token" : "idp_signature_invalid";
574
+ continue;
575
+ }
576
+ const nowSec = opts.now ?? Math.floor(Date.now() / 1e3);
577
+ if (claims.iat > nowSec + jwtClockTolerance) {
578
+ lastFailure = "expired_token";
579
+ continue;
580
+ }
581
+ const popResult = await verifyMessageSignature({
582
+ method: ctx.method,
583
+ authority: ctx.authority,
584
+ path: ctx.path,
585
+ agentIdentity: raw,
586
+ signatureInput: ctx.signatureInput,
587
+ signature: ctx.signature,
588
+ cnfJwk: claims.cnf.jwk,
589
+ now: opts.now,
590
+ maxSkewSeconds: opts.maxSkewSeconds
591
+ });
592
+ if (!popResult.ok) {
593
+ lastFailure = "pop_signature_invalid";
594
+ continue;
595
+ }
596
+ return { ok: true, ait: { payload: claims, iss: claims.iss, cnfJwk: claims.cnf.jwk, token } };
597
+ }
598
+ return { ok: false, reason: lastFailure };
599
+ };
600
+ var stripBearer = (value) => {
601
+ const trimmed = value.trim();
602
+ return /^bearer\s+/i.test(trimmed) ? trimmed.replace(/^bearer\s+/i, "") : trimmed;
603
+ };
604
+ var AIT_SIGNING_ALGS = ["EdDSA", "ES256"];
605
+ var normalizeAlg = (alg) => alg.toLowerCase() === "eddsa" ? "EdDSA" : alg;
606
+ var isExpiry = (err) => typeof err === "object" && err !== null && err.code === "ERR_JWT_EXPIRED";
607
+
608
+ // src/aip/request.ts
609
+ var readAgentIdentityHeaders = (headers) => {
610
+ const raw = headers.get(AGENT_IDENTITY_HEADER);
611
+ if (!raw) {
612
+ return [];
613
+ }
614
+ return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
615
+ };
616
+ var deriveAuthority = (req, url) => req.headers.get("host") ?? url.host;
617
+ var buildVerifyContextFromRequest = (req) => {
618
+ const url = new URL(req.url);
619
+ return {
620
+ method: req.method,
621
+ authority: deriveAuthority(req, url),
622
+ path: url.pathname,
623
+ agentIdentityHeaders: readAgentIdentityHeaders(req.headers),
624
+ signatureInput: req.headers.get("signature-input"),
625
+ signature: req.headers.get("signature")
626
+ };
627
+ };
628
+ var hasAgentIdentityHeader = (req) => readAgentIdentityHeaders(req.headers).length > 0;
629
+
630
+ // src/aip/gate.ts
631
+ var verifyFromContext = async (ctx, opts) => {
632
+ const result = await verifyAit(ctx, { jwks: opts.jwks, now: opts.now, maxSkewSeconds: opts.maxSkewSeconds });
633
+ return result.ok ? { ok: true, ait: result.ait } : { ok: false, failure: result.reason };
634
+ };
635
+ var verifyAitRequest = (req, opts) => verifyFromContext(buildVerifyContextFromRequest(req), opts);
636
+ var aipErrorCode = (failure) => {
637
+ switch (failure) {
638
+ case "no_token":
639
+ case "pop_signature_missing":
640
+ return "agent_identity_required";
641
+ case "untrusted_issuer":
642
+ return "untrusted_issuer";
643
+ case "expired_token":
644
+ return "expired_token";
645
+ case "invalid_claims":
646
+ return "insufficient_claims";
647
+ case "key_unavailable":
648
+ return "idp_unavailable";
649
+ case "malformed_token":
650
+ case "idp_signature_invalid":
651
+ case "pop_signature_invalid":
652
+ return "invalid_signature";
653
+ default:
654
+ return "invalid_signature";
655
+ }
656
+ };
657
+ var aipErrorStatus = (failure) => {
658
+ switch (failure) {
659
+ case "key_unavailable":
660
+ return 503;
661
+ case "untrusted_issuer":
662
+ case "invalid_claims":
663
+ return 403;
664
+ default:
665
+ return 401;
666
+ }
667
+ };
668
+ var aipErrorDetail = (failure) => {
669
+ switch (failure) {
670
+ case "no_token":
671
+ return "No Agent-Identity token was presented.";
672
+ case "pop_signature_missing":
673
+ return "The request is missing the RFC 9421 HTTP Message Signature that proves possession of the token-bound key.";
674
+ case "untrusted_issuer":
675
+ return "The token's issuer is not in this service's trusted-issuer list.";
676
+ case "expired_token":
677
+ return "The Agent Identity Token has expired.";
678
+ case "invalid_claims":
679
+ return "The token is missing required claims for this endpoint.";
680
+ case "malformed_token":
681
+ return "The Agent-Identity header could not be parsed as an Agent Identity Token.";
682
+ case "idp_signature_invalid":
683
+ return "The identity provider's signature on the token failed verification.";
684
+ case "pop_signature_invalid":
685
+ return "The request signature did not match the key bound to the token.";
686
+ case "key_unavailable":
687
+ return "The identity provider's signing key could not be resolved.";
688
+ default:
689
+ return "Token verification failed.";
690
+ }
691
+ };
692
+ var buildAipErrorBody = (failure) => {
693
+ const code = aipErrorCode(failure);
694
+ return {
695
+ type: `urn:aip:error:${code}`,
696
+ title: code.replace(/_/g, " "),
697
+ status: aipErrorStatus(failure),
698
+ detail: aipErrorDetail(failure)
699
+ };
700
+ };
701
+
187
702
  // src/core.ts
703
+ var import_node_crypto = require("crypto");
188
704
  var import_sdk = require("@agent-score/sdk");
189
705
 
190
706
  // src/address.ts
@@ -279,8 +795,9 @@ var INVALID_CREDENTIAL_INSTRUCTIONS = JSON.stringify({
279
795
  ],
280
796
  user_message: "The operator_token is not recognized. Use a different stored token, or restart the verification session flow to mint a new one."
281
797
  });
282
- function buildAgentMemoryHint() {
798
+ function buildAgentMemoryHint(aipTrustedIssuers) {
283
799
  const api = CANONICAL_AGENTSCORE_API;
800
+ const acceptsAip = aipTrustedIssuers !== void 0 && aipTrustedIssuers.length > 0;
284
801
  return {
285
802
  save_for_future_agentscore_gates: true,
286
803
  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.",
@@ -288,8 +805,12 @@ function buildAgentMemoryHint() {
288
805
  identity_check_endpoint: `${api}/v1/credentials`,
289
806
  identity_paths: {
290
807
  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.",
291
- 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."
808
+ 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.",
809
+ ...acceptsAip && {
810
+ 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.'
811
+ }
292
812
  },
813
+ ...acceptsAip && { aip_trusted_issuers: aipTrustedIssuers },
293
814
  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.",
294
815
  do_not_persist_in_memory: ["operator_token", "poll_secret"],
295
816
  persist_in_credential_store: ["operator_token"]
@@ -311,11 +832,12 @@ function createAgentScoreCore(options) {
311
832
  baseUrl: rawBaseUrl = "https://api.agentscore.sh",
312
833
  chain: gateChain,
313
834
  userAgent,
314
- createSessionOnMissing
835
+ createSessionOnMissing,
836
+ aipTrustedIssuers
315
837
  } = options;
316
838
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
317
- const agentMemoryHint = buildAgentMemoryHint();
318
- const defaultUa = `@agent-score/commerce@${"2.4.0"}`;
839
+ const agentMemoryHint = buildAgentMemoryHint(aipTrustedIssuers);
840
+ const defaultUa = `@agent-score/commerce@${"2.5.0"}`;
319
841
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
320
842
  const sdk = new import_sdk.AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
321
843
  const sessionSdkCache = /* @__PURE__ */ new Map();
@@ -333,6 +855,7 @@ function createAgentScoreCore(options) {
333
855
  return s;
334
856
  }
335
857
  const cache = new TTLCache(cacheSeconds * 1e3);
858
+ const lastSignerRaw = /* @__PURE__ */ new Map();
336
859
  async function tryMintSessionDenial(ctx) {
337
860
  if (!createSessionOnMissing) return void 0;
338
861
  try {
@@ -390,13 +913,18 @@ function createAgentScoreCore(options) {
390
913
  }
391
914
  }
392
915
  async function evaluate(identity, ctx, signer) {
393
- if (!identity || !identity.address && !identity.operatorToken) {
916
+ if (!identity || !identity.address?.trim() && !identity.operatorToken?.trim() && !identity.aipToken?.trim()) {
394
917
  if (failOpen) return { kind: "allow" };
395
918
  const sessionReason = await tryMintSessionDenial(ctx);
396
919
  if (sessionReason) return { kind: "deny", reason: sessionReason };
920
+ const acceptsAip = aipTrustedIssuers !== void 0 && aipTrustedIssuers.length > 0;
921
+ const aipStep = acceptsAip ? [
922
+ `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.`
923
+ ] : [];
397
924
  const missingIdentityInstructions = JSON.stringify({
398
925
  action: "probe_identity_then_session",
399
926
  steps: [
927
+ ...aipStep,
400
928
  "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.",
401
929
  "If step 1 is denied or you already have a stored operator_token (valid + not expired): send X-Operator-Token: opc_... and retry.",
402
930
  "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."
@@ -412,7 +940,7 @@ function createAgentScoreCore(options) {
412
940
  }
413
941
  };
414
942
  }
415
- const cacheKey = identity.operatorToken?.toLowerCase() ?? (identity.address ? normalizeAddress(identity.address) : "");
943
+ const cacheKey = identity.aipToken ? `aip:${(0, import_node_crypto.createHash)("sha256").update(identity.aipToken).digest("hex")}` : identity.operatorToken?.toLowerCase() ?? (identity.address ? normalizeAddress(identity.address) : "");
416
944
  const cached = cache.get(cacheKey);
417
945
  if (cached) {
418
946
  if (cached.allow) {
@@ -457,7 +985,7 @@ function createAgentScoreCore(options) {
457
985
  // regardless of policy.require_sanctions_clear (which gates the separate NAME screen).
458
986
  ...signer && { signer: { address: signer.address, network: signer.network } }
459
987
  };
460
- const result = identity.address ? await sdk.assess(identity.address, { ...opts, operatorToken: identity.operatorToken }) : await sdk.assess(null, { ...opts, operatorToken: identity.operatorToken });
988
+ 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 });
461
989
  data = result;
462
990
  } catch (err) {
463
991
  if (err instanceof import_sdk.PaymentRequiredError) {
@@ -528,6 +1056,9 @@ function createAgentScoreCore(options) {
528
1056
  const decisionReasons = data.decision_reasons ?? [];
529
1057
  const allow = decision === "allow" || decision == null;
530
1058
  cache.set(cacheKey, { allow, decision: decision ?? void 0, reasons: decisionReasons, raw: data });
1059
+ if (identity.address !== void 0 && identity.operatorToken === void 0 && identity.aipToken === void 0 && (data.signer_match !== void 0 || data.signer_sanctions !== void 0)) {
1060
+ lastSignerRaw.set(normalizeAddress(identity.address), data);
1061
+ }
531
1062
  if (allow) {
532
1063
  const quota = data.quota;
533
1064
  return {
@@ -592,9 +1123,7 @@ function createAgentScoreCore(options) {
592
1123
  }
593
1124
  function getSignerVerdict(claimedAddress) {
594
1125
  const claimedNorm = normalizeAddress(claimedAddress);
595
- const cached = cache.get(claimedNorm);
596
- if (!cached) return void 0;
597
- const raw = cached.raw;
1126
+ const raw = lastSignerRaw.get(claimedNorm) ?? cache.get(claimedNorm)?.raw;
598
1127
  if (!raw) return void 0;
599
1128
  const rawMatch = raw.signer_match;
600
1129
  const rawSanctions = raw.signer_sanctions;
@@ -724,6 +1253,42 @@ function createAgentScoreGate(options) {
724
1253
  return { allowed: false, response };
725
1254
  };
726
1255
  }
1256
+ var defaultAipResponse = (body) => new Response(JSON.stringify(body), { status: body.status, headers: { "content-type": "application/problem+json" } });
1257
+ function createAipGate(options) {
1258
+ const { onDenied, ...gateOpts } = options;
1259
+ return async (req) => {
1260
+ const result = await verifyAitRequest(req, gateOpts);
1261
+ if (result.ok) {
1262
+ return { allowed: true, ait: result.ait };
1263
+ }
1264
+ const body = buildAipErrorBody(result.failure);
1265
+ const response = onDenied ? await onDenied(req, body) : defaultAipResponse(body);
1266
+ return { allowed: false, response };
1267
+ };
1268
+ }
1269
+ function withAipGate(options, handler) {
1270
+ const guard = createAipGate(options);
1271
+ return async (req, ctx) => {
1272
+ const result = await guard(req);
1273
+ if (!result.allowed) {
1274
+ return result.response;
1275
+ }
1276
+ return handler(req, { ait: result.ait }, ctx);
1277
+ };
1278
+ }
1279
+ function withConditionalAipGate(options, handler) {
1280
+ const guard = createAipGate(options);
1281
+ return async (req, ctx) => {
1282
+ if (!hasAgentIdentityHeader(req)) {
1283
+ return handler(req, {}, ctx);
1284
+ }
1285
+ const result = await guard(req);
1286
+ if (!result.allowed) {
1287
+ return result.response;
1288
+ }
1289
+ return handler(req, { ait: result.ait }, ctx);
1290
+ };
1291
+ }
727
1292
 
728
1293
  // src/identity/nextjs.ts
729
1294
  function withAgentScoreGate(options, handler) {
@@ -773,7 +1338,10 @@ function conditionalAgentscoreMiddleware(options) {
773
1338
  0 && (module.exports = {
774
1339
  agentscoreMiddleware,
775
1340
  conditionalAgentscoreMiddleware,
1341
+ createAipGate,
776
1342
  withAgentScoreGate,
777
- withConditionalAgentScoreGate
1343
+ withAipGate,
1344
+ withConditionalAgentScoreGate,
1345
+ withConditionalAipGate
778
1346
  });
779
1347
  //# sourceMappingURL=nextjs.js.map