@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
@@ -21,13 +21,16 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var fastify_exports = {};
22
22
  __export(fastify_exports, {
23
23
  agentscoreGate: () => agentscoreGate,
24
+ aipGate: () => aipGate,
24
25
  captureWallet: () => captureWallet,
25
26
  conditionalAgentscoreGate: () => conditionalAgentscoreGate,
27
+ conditionalAipGate: () => conditionalAipGate,
26
28
  default: () => fastify_default,
27
29
  getAgentScoreData: () => getAgentScoreData,
28
30
  getGateDegradedState: () => getGateDegradedState,
29
31
  getGateQuotaInfo: () => getGateQuotaInfo,
30
- getSignerVerdict: () => getSignerVerdict
32
+ getSignerVerdict: () => getSignerVerdict,
33
+ getVerifiedAit: () => getVerifiedAit
31
34
  });
32
35
  module.exports = __toCommonJS(fastify_exports);
33
36
 
@@ -164,7 +167,530 @@ function denialReasonToBody(reason) {
164
167
  return body;
165
168
  }
166
169
 
170
+ // src/aip/verify.ts
171
+ var import_jose2 = require("jose");
172
+
173
+ // src/aip/http-signature.ts
174
+ var import_jose = require("jose");
175
+ var { subtle } = globalThis.crypto;
176
+ var b64ToBytes = (b64) => {
177
+ const bin = atob(b64);
178
+ const out = new Uint8Array(bin.length);
179
+ for (let i = 0; i < bin.length; i++) {
180
+ out[i] = bin.charCodeAt(i);
181
+ }
182
+ return out;
183
+ };
184
+ var AIP_COVERED_COMPONENTS = ["@method", "@authority", "@path", "agent-identity"];
185
+ var AIP_SIGNATURE_TAG = "agent-identity";
186
+ var DEFAULT_MAX_SKEW_SECONDS = 60;
187
+ var normalizeAuthority = (authority) => {
188
+ const lower = authority.trim().toLowerCase();
189
+ const colon = lower.lastIndexOf(":");
190
+ if (colon === -1) {
191
+ return lower;
192
+ }
193
+ if (lower.includes("]") && colon < lower.indexOf("]")) {
194
+ return lower;
195
+ }
196
+ const host = lower.slice(0, colon);
197
+ const port = lower.slice(colon + 1);
198
+ if (port === "80" || port === "443") {
199
+ return host;
200
+ }
201
+ return lower;
202
+ };
203
+ var componentValue = (name, input) => {
204
+ switch (name) {
205
+ case "@method":
206
+ return input.method.toUpperCase();
207
+ case "@authority":
208
+ return normalizeAuthority(input.authority);
209
+ case "@path":
210
+ return input.path;
211
+ case "agent-identity":
212
+ return input.agentIdentity.trim();
213
+ default:
214
+ return input.extra?.[name] ?? null;
215
+ }
216
+ };
217
+ var serializeComponentList = (components) => `(${components.map((c) => `"${c}"`).join(" ")})`;
218
+ var serializeParams = (p) => {
219
+ const parts = [];
220
+ if (p.created !== void 0) {
221
+ parts.push(`created=${p.created}`);
222
+ }
223
+ if (p.expires !== void 0) {
224
+ parts.push(`expires=${p.expires}`);
225
+ }
226
+ if (p.keyid !== void 0) {
227
+ parts.push(`keyid="${p.keyid}"`);
228
+ }
229
+ if (p.alg !== void 0) {
230
+ parts.push(`alg="${p.alg}"`);
231
+ }
232
+ if (p.tag !== void 0) {
233
+ parts.push(`tag="${p.tag}"`);
234
+ }
235
+ return parts.map((s) => `;${s}`).join("");
236
+ };
237
+ var buildSignatureBase = (params, input) => {
238
+ const lines = [];
239
+ for (const name of params.components) {
240
+ const value = componentValue(name, input);
241
+ if (value === null) {
242
+ throw new MissingComponentError(name);
243
+ }
244
+ lines.push(`"${name}": ${value}`);
245
+ }
246
+ const paramsValue = serializeComponentList(params.components) + serializeParams(params);
247
+ lines.push(`"@signature-params": ${paramsValue}`);
248
+ return lines.join("\n");
249
+ };
250
+ var MissingComponentError = class extends Error {
251
+ constructor(component) {
252
+ super(`signature base missing covered component: ${component}`);
253
+ this.component = component;
254
+ this.name = "MissingComponentError";
255
+ }
256
+ component;
257
+ };
258
+ var parseSignatureInput = (header, tag = AIP_SIGNATURE_TAG) => {
259
+ const members = splitDictionary(header);
260
+ if (members.length === 0) {
261
+ return null;
262
+ }
263
+ const parsed = members.map((m) => {
264
+ const params = parseInnerListMember(m.value);
265
+ return params ? { label: m.label, params } : null;
266
+ }).filter((x) => x !== null);
267
+ if (parsed.length === 0) {
268
+ return null;
269
+ }
270
+ const tagged = parsed.find((p) => p.params.tag === tag);
271
+ if (tagged) {
272
+ return tagged;
273
+ }
274
+ if (parsed.length === 1 && parsed[0].params.tag === void 0) {
275
+ return parsed[0];
276
+ }
277
+ return null;
278
+ };
279
+ var parseSignatureValue = (header, label) => {
280
+ const members = splitDictionary(header);
281
+ const member = members.find((m) => m.label === label);
282
+ if (!member) {
283
+ return null;
284
+ }
285
+ const v = member.value.trim();
286
+ if (!v.startsWith(":") || !v.endsWith(":") || v.length < 2) {
287
+ return null;
288
+ }
289
+ const b64 = v.slice(1, -1);
290
+ try {
291
+ return b64ToBytes(b64);
292
+ } catch {
293
+ return null;
294
+ }
295
+ };
296
+ var splitDictionary = (header) => {
297
+ const out = [];
298
+ let depth = 0;
299
+ let inBytes = false;
300
+ let inString = false;
301
+ let current = "";
302
+ for (let i = 0; i < header.length; i++) {
303
+ const ch = header[i];
304
+ if (inString) {
305
+ current += ch;
306
+ if (ch === '"' && header[i - 1] !== "\\") {
307
+ inString = false;
308
+ }
309
+ continue;
310
+ }
311
+ if (ch === '"') {
312
+ inString = true;
313
+ current += ch;
314
+ continue;
315
+ }
316
+ if (ch === ":") {
317
+ inBytes = !inBytes;
318
+ current += ch;
319
+ continue;
320
+ }
321
+ if (!inBytes && ch === "(") {
322
+ depth++;
323
+ current += ch;
324
+ continue;
325
+ }
326
+ if (!inBytes && ch === ")") {
327
+ depth = Math.max(0, depth - 1);
328
+ current += ch;
329
+ continue;
330
+ }
331
+ if (!inBytes && depth === 0 && ch === ",") {
332
+ pushMember(out, current);
333
+ current = "";
334
+ continue;
335
+ }
336
+ current += ch;
337
+ }
338
+ pushMember(out, current);
339
+ return out;
340
+ };
341
+ var pushMember = (out, raw) => {
342
+ const trimmed = raw.trim();
343
+ if (!trimmed) {
344
+ return;
345
+ }
346
+ const eq = trimmed.indexOf("=");
347
+ if (eq === -1) {
348
+ return;
349
+ }
350
+ const label = trimmed.slice(0, eq).trim();
351
+ const value = trimmed.slice(eq + 1).trim();
352
+ if (label) {
353
+ out.push({ label, value });
354
+ }
355
+ };
356
+ var parseInnerListMember = (value) => {
357
+ const open = value.indexOf("(");
358
+ const close = value.indexOf(")", open + 1);
359
+ if (open === -1 || close === -1) {
360
+ return null;
361
+ }
362
+ const listBody = value.slice(open + 1, close).trim();
363
+ const components = listBody.length === 0 ? [] : (listBody.match(/"[^"]*"/g) ?? []).map((s) => s.slice(1, -1));
364
+ const params = { components };
365
+ const paramStr = value.slice(close + 1);
366
+ const re = /;\s*([a-zA-Z][a-zA-Z0-9_-]*)\s*=\s*("(?:[^"\\]|\\.)*"|-?\d+)/g;
367
+ let match;
368
+ while ((match = re.exec(paramStr)) !== null) {
369
+ const key = match[1];
370
+ const raw = match[2];
371
+ const val = raw.startsWith('"') ? raw.slice(1, -1) : Number(raw);
372
+ if (key === "created") {
373
+ params.created = val;
374
+ } else if (key === "expires") {
375
+ params.expires = val;
376
+ } else if (key === "keyid") {
377
+ params.keyid = val;
378
+ } else if (key === "tag") {
379
+ params.tag = val;
380
+ } else if (key === "alg") {
381
+ params.alg = val;
382
+ }
383
+ }
384
+ return params;
385
+ };
386
+ var verifyMessageSignature = async (input) => {
387
+ const selected = parseSignatureInput(input.signatureInput);
388
+ if (!selected) {
389
+ return { ok: false, reason: "no_aip_signature" };
390
+ }
391
+ const { label, params } = selected;
392
+ if (params.alg !== void 0 && !["ed25519", "eddsa"].includes(params.alg.toLowerCase())) {
393
+ return { ok: false, reason: "unsupported_alg" };
394
+ }
395
+ for (const required of AIP_COVERED_COMPONENTS) {
396
+ if (!params.components.includes(required)) {
397
+ return { ok: false, reason: "missing_covered_component" };
398
+ }
399
+ }
400
+ const now = input.now ?? Math.floor(Date.now() / 1e3);
401
+ const skew = input.maxSkewSeconds ?? DEFAULT_MAX_SKEW_SECONDS;
402
+ if (params.created !== void 0 && params.created > now + skew) {
403
+ return { ok: false, reason: "created_in_future" };
404
+ }
405
+ if (params.expires !== void 0 && params.expires < now - skew) {
406
+ return { ok: false, reason: "expired" };
407
+ }
408
+ if (!params.keyid) {
409
+ return { ok: false, reason: "missing_keyid" };
410
+ }
411
+ const cnf = input.cnfJwk;
412
+ if (cnf.kty !== "OKP" || cnf.crv !== "Ed25519" || typeof cnf.x !== "string" || cnf.x.length === 0) {
413
+ return { ok: false, reason: "unsupported_cnf_key" };
414
+ }
415
+ let thumbprint;
416
+ try {
417
+ thumbprint = await (0, import_jose.calculateJwkThumbprint)(input.cnfJwk, "sha256");
418
+ } catch {
419
+ return { ok: false, reason: "unsupported_cnf_key" };
420
+ }
421
+ if (params.keyid !== thumbprint) {
422
+ return { ok: false, reason: "keyid_mismatch" };
423
+ }
424
+ const sig = parseSignatureValue(input.signature, label);
425
+ if (!sig) {
426
+ return { ok: false, reason: "malformed_signature" };
427
+ }
428
+ let base;
429
+ try {
430
+ base = buildSignatureBase(params, {
431
+ method: input.method,
432
+ authority: input.authority,
433
+ path: input.path,
434
+ agentIdentity: input.agentIdentity,
435
+ extra: input.extraComponents
436
+ });
437
+ } catch (err) {
438
+ if (err instanceof MissingComponentError) {
439
+ return { ok: false, reason: "missing_covered_component" };
440
+ }
441
+ throw err;
442
+ }
443
+ let valid;
444
+ try {
445
+ const key = await (0, import_jose.importJWK)(input.cnfJwk, "EdDSA");
446
+ if (!(key instanceof CryptoKey)) {
447
+ return { ok: false, reason: "signature_invalid" };
448
+ }
449
+ valid = await subtle.verify(
450
+ { name: "Ed25519" },
451
+ key,
452
+ sig,
453
+ new TextEncoder().encode(base)
454
+ );
455
+ } catch {
456
+ return { ok: false, reason: "signature_invalid" };
457
+ }
458
+ return valid ? { ok: true, params } : { ok: false, reason: "signature_invalid" };
459
+ };
460
+
461
+ // src/aip/types.ts
462
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
463
+ var isNonEmptyString = (v) => typeof v === "string" && v.length > 0;
464
+ var isAitShape = (payload) => isObject(payload) && isObject(payload.cnf) && isObject(payload.agent);
465
+ var validateAitPayload = (payload) => {
466
+ if (!isObject(payload)) {
467
+ return { ok: false, reason: "not_an_object" };
468
+ }
469
+ if (!isNonEmptyString(payload.aip_version)) {
470
+ return { ok: false, reason: "missing_aip_version" };
471
+ }
472
+ if (!isNonEmptyString(payload.iss)) {
473
+ return { ok: false, reason: "missing_iss" };
474
+ }
475
+ if (!isNonEmptyString(payload.sub)) {
476
+ return { ok: false, reason: "missing_sub" };
477
+ }
478
+ if (typeof payload.iat !== "number") {
479
+ return { ok: false, reason: "missing_iat" };
480
+ }
481
+ if (typeof payload.exp !== "number") {
482
+ return { ok: false, reason: "missing_exp" };
483
+ }
484
+ if (!isObject(payload.cnf) || !isObject(payload.cnf.jwk)) {
485
+ return { ok: false, reason: "missing_cnf" };
486
+ }
487
+ if (!isObject(payload.agent) || !isNonEmptyString(payload.agent.provider)) {
488
+ return { ok: false, reason: "missing_agent_provider" };
489
+ }
490
+ if (payload.trust_level === "human_confirmed") {
491
+ const auth = payload.auth;
492
+ const amr = isObject(auth) ? auth.amr : void 0;
493
+ if (!Array.isArray(amr) || amr.length === 0) {
494
+ return { ok: false, reason: "human_confirmed_without_amr" };
495
+ }
496
+ }
497
+ return { ok: true, payload };
498
+ };
499
+
500
+ // src/aip/verify.ts
501
+ var verifyAit = async (ctx, opts) => {
502
+ if (ctx.agentIdentityHeaders.length === 0) {
503
+ return { ok: false, reason: "no_token" };
504
+ }
505
+ if (!ctx.signatureInput || !ctx.signature) {
506
+ return { ok: false, reason: "pop_signature_missing" };
507
+ }
508
+ let lastFailure = "malformed_token";
509
+ for (const raw of ctx.agentIdentityHeaders) {
510
+ const token = stripBearer(raw);
511
+ let header;
512
+ let payload;
513
+ try {
514
+ header = (0, import_jose2.decodeProtectedHeader)(token);
515
+ payload = (0, import_jose2.decodeJwt)(token);
516
+ } catch {
517
+ lastFailure = "malformed_token";
518
+ continue;
519
+ }
520
+ if (header.alg === void 0 || header.alg.toLowerCase() === "none") {
521
+ lastFailure = "malformed_token";
522
+ continue;
523
+ }
524
+ if (!isAitShape(payload)) {
525
+ lastFailure = "malformed_token";
526
+ continue;
527
+ }
528
+ const validated = validateAitPayload(payload);
529
+ if (!validated.ok) {
530
+ lastFailure = "invalid_claims";
531
+ continue;
532
+ }
533
+ const claims = validated.payload;
534
+ const keyLookup = await opts.jwks.getKey(claims.iss, header.kid);
535
+ if (!keyLookup.ok) {
536
+ lastFailure = keyLookup.reason === "untrusted_issuer" || keyLookup.reason === "insecure_issuer" ? "untrusted_issuer" : "key_unavailable";
537
+ continue;
538
+ }
539
+ const jwtClockTolerance = opts.maxSkewSeconds ?? 60;
540
+ try {
541
+ const idpKey = await (0, import_jose2.importJWK)(keyLookup.key, normalizeAlg(header.alg));
542
+ await (0, import_jose2.jwtVerify)(token, idpKey, {
543
+ // Pin the signature algorithm allowlist (RFC 8725 §3.1) — also rejects `alg:none`. Without
544
+ // this, jose accepts whatever alg the resolved JWK supports, so a trusted IdP publishing a
545
+ // non-Ed25519 (e.g. RSA/EC) `use:sig` key would let an attacker present an RS256/ES256
546
+ // token that verifies. Matches the server-side allowlist in core/api aip-verify.
547
+ algorithms: AIT_SIGNING_ALGS,
548
+ clockTolerance: jwtClockTolerance,
549
+ currentDate: opts.now !== void 0 ? new Date(opts.now * 1e3) : void 0
550
+ });
551
+ } catch (err) {
552
+ lastFailure = isExpiry(err) ? "expired_token" : "idp_signature_invalid";
553
+ continue;
554
+ }
555
+ const nowSec = opts.now ?? Math.floor(Date.now() / 1e3);
556
+ if (claims.iat > nowSec + jwtClockTolerance) {
557
+ lastFailure = "expired_token";
558
+ continue;
559
+ }
560
+ const popResult = await verifyMessageSignature({
561
+ method: ctx.method,
562
+ authority: ctx.authority,
563
+ path: ctx.path,
564
+ agentIdentity: raw,
565
+ signatureInput: ctx.signatureInput,
566
+ signature: ctx.signature,
567
+ cnfJwk: claims.cnf.jwk,
568
+ now: opts.now,
569
+ maxSkewSeconds: opts.maxSkewSeconds
570
+ });
571
+ if (!popResult.ok) {
572
+ lastFailure = "pop_signature_invalid";
573
+ continue;
574
+ }
575
+ return { ok: true, ait: { payload: claims, iss: claims.iss, cnfJwk: claims.cnf.jwk, token } };
576
+ }
577
+ return { ok: false, reason: lastFailure };
578
+ };
579
+ var stripBearer = (value) => {
580
+ const trimmed = value.trim();
581
+ return /^bearer\s+/i.test(trimmed) ? trimmed.replace(/^bearer\s+/i, "") : trimmed;
582
+ };
583
+ var AIT_SIGNING_ALGS = ["EdDSA", "ES256"];
584
+ var normalizeAlg = (alg) => alg.toLowerCase() === "eddsa" ? "EdDSA" : alg;
585
+ var isExpiry = (err) => typeof err === "object" && err !== null && err.code === "ERR_JWT_EXPIRED";
586
+
587
+ // src/aip/request.ts
588
+ var readNodeHeader = (headers, name) => {
589
+ const v = headers[name] ?? headers[name.toLowerCase()];
590
+ if (v === void 0) {
591
+ return void 0;
592
+ }
593
+ return Array.isArray(v) ? v.join(", ") : v;
594
+ };
595
+ var hasAgentIdentityHeaderNode = (headers) => {
596
+ const raw = readNodeHeader(headers, "agent-identity");
597
+ return raw !== void 0 && raw.split(",").some((s) => s.trim().length > 0);
598
+ };
599
+ var buildVerifyContextFromParts = (parts) => {
600
+ const agentIdentityRaw = readNodeHeader(parts.headers, "agent-identity");
601
+ const agentIdentityHeaders = agentIdentityRaw ? agentIdentityRaw.split(",").map((s) => s.trim()).filter((s) => s.length > 0) : [];
602
+ const host = parts.authority ?? readNodeHeader(parts.headers, "host") ?? "";
603
+ let path;
604
+ try {
605
+ path = new URL(parts.url, host ? `http://${host}` : "http://localhost").pathname;
606
+ } catch {
607
+ const q = parts.url.indexOf("?");
608
+ path = q === -1 ? parts.url : parts.url.slice(0, q);
609
+ }
610
+ return {
611
+ method: parts.method,
612
+ authority: host,
613
+ path,
614
+ agentIdentityHeaders,
615
+ signatureInput: readNodeHeader(parts.headers, "signature-input") ?? null,
616
+ signature: readNodeHeader(parts.headers, "signature") ?? null
617
+ };
618
+ };
619
+
620
+ // src/aip/gate.ts
621
+ var verifyFromContext = async (ctx, opts) => {
622
+ const result = await verifyAit(ctx, { jwks: opts.jwks, now: opts.now, maxSkewSeconds: opts.maxSkewSeconds });
623
+ return result.ok ? { ok: true, ait: result.ait } : { ok: false, failure: result.reason };
624
+ };
625
+ var verifyAitParts = (parts, opts) => verifyFromContext(buildVerifyContextFromParts(parts), opts);
626
+ var aipErrorCode = (failure) => {
627
+ switch (failure) {
628
+ case "no_token":
629
+ case "pop_signature_missing":
630
+ return "agent_identity_required";
631
+ case "untrusted_issuer":
632
+ return "untrusted_issuer";
633
+ case "expired_token":
634
+ return "expired_token";
635
+ case "invalid_claims":
636
+ return "insufficient_claims";
637
+ case "key_unavailable":
638
+ return "idp_unavailable";
639
+ case "malformed_token":
640
+ case "idp_signature_invalid":
641
+ case "pop_signature_invalid":
642
+ return "invalid_signature";
643
+ default:
644
+ return "invalid_signature";
645
+ }
646
+ };
647
+ var aipErrorStatus = (failure) => {
648
+ switch (failure) {
649
+ case "key_unavailable":
650
+ return 503;
651
+ case "untrusted_issuer":
652
+ case "invalid_claims":
653
+ return 403;
654
+ default:
655
+ return 401;
656
+ }
657
+ };
658
+ var aipErrorDetail = (failure) => {
659
+ switch (failure) {
660
+ case "no_token":
661
+ return "No Agent-Identity token was presented.";
662
+ case "pop_signature_missing":
663
+ return "The request is missing the RFC 9421 HTTP Message Signature that proves possession of the token-bound key.";
664
+ case "untrusted_issuer":
665
+ return "The token's issuer is not in this service's trusted-issuer list.";
666
+ case "expired_token":
667
+ return "The Agent Identity Token has expired.";
668
+ case "invalid_claims":
669
+ return "The token is missing required claims for this endpoint.";
670
+ case "malformed_token":
671
+ return "The Agent-Identity header could not be parsed as an Agent Identity Token.";
672
+ case "idp_signature_invalid":
673
+ return "The identity provider's signature on the token failed verification.";
674
+ case "pop_signature_invalid":
675
+ return "The request signature did not match the key bound to the token.";
676
+ case "key_unavailable":
677
+ return "The identity provider's signing key could not be resolved.";
678
+ default:
679
+ return "Token verification failed.";
680
+ }
681
+ };
682
+ var buildAipErrorBody = (failure) => {
683
+ const code = aipErrorCode(failure);
684
+ return {
685
+ type: `urn:aip:error:${code}`,
686
+ title: code.replace(/_/g, " "),
687
+ status: aipErrorStatus(failure),
688
+ detail: aipErrorDetail(failure)
689
+ };
690
+ };
691
+
167
692
  // src/core.ts
693
+ var import_node_crypto = require("crypto");
168
694
  var import_sdk = require("@agent-score/sdk");
169
695
 
170
696
  // src/address.ts
@@ -259,8 +785,9 @@ var INVALID_CREDENTIAL_INSTRUCTIONS = JSON.stringify({
259
785
  ],
260
786
  user_message: "The operator_token is not recognized. Use a different stored token, or restart the verification session flow to mint a new one."
261
787
  });
262
- function buildAgentMemoryHint() {
788
+ function buildAgentMemoryHint(aipTrustedIssuers) {
263
789
  const api = CANONICAL_AGENTSCORE_API;
790
+ const acceptsAip = aipTrustedIssuers !== void 0 && aipTrustedIssuers.length > 0;
264
791
  return {
265
792
  save_for_future_agentscore_gates: true,
266
793
  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.",
@@ -268,8 +795,12 @@ function buildAgentMemoryHint() {
268
795
  identity_check_endpoint: `${api}/v1/credentials`,
269
796
  identity_paths: {
270
797
  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.",
271
- 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."
798
+ 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.",
799
+ ...acceptsAip && {
800
+ 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.'
801
+ }
272
802
  },
803
+ ...acceptsAip && { aip_trusted_issuers: aipTrustedIssuers },
273
804
  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.",
274
805
  do_not_persist_in_memory: ["operator_token", "poll_secret"],
275
806
  persist_in_credential_store: ["operator_token"]
@@ -291,11 +822,12 @@ function createAgentScoreCore(options) {
291
822
  baseUrl: rawBaseUrl = "https://api.agentscore.sh",
292
823
  chain: gateChain,
293
824
  userAgent,
294
- createSessionOnMissing
825
+ createSessionOnMissing,
826
+ aipTrustedIssuers
295
827
  } = options;
296
828
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
297
- const agentMemoryHint = buildAgentMemoryHint();
298
- const defaultUa = `@agent-score/commerce@${"2.4.0"}`;
829
+ const agentMemoryHint = buildAgentMemoryHint(aipTrustedIssuers);
830
+ const defaultUa = `@agent-score/commerce@${"2.5.0"}`;
299
831
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
300
832
  const sdk = new import_sdk.AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
301
833
  const sessionSdkCache = /* @__PURE__ */ new Map();
@@ -313,6 +845,7 @@ function createAgentScoreCore(options) {
313
845
  return s;
314
846
  }
315
847
  const cache = new TTLCache(cacheSeconds * 1e3);
848
+ const lastSignerRaw = /* @__PURE__ */ new Map();
316
849
  async function tryMintSessionDenial(ctx) {
317
850
  if (!createSessionOnMissing) return void 0;
318
851
  try {
@@ -370,13 +903,18 @@ function createAgentScoreCore(options) {
370
903
  }
371
904
  }
372
905
  async function evaluate(identity, ctx, signer) {
373
- if (!identity || !identity.address && !identity.operatorToken) {
906
+ if (!identity || !identity.address?.trim() && !identity.operatorToken?.trim() && !identity.aipToken?.trim()) {
374
907
  if (failOpen) return { kind: "allow" };
375
908
  const sessionReason = await tryMintSessionDenial(ctx);
376
909
  if (sessionReason) return { kind: "deny", reason: sessionReason };
910
+ const acceptsAip = aipTrustedIssuers !== void 0 && aipTrustedIssuers.length > 0;
911
+ const aipStep = acceptsAip ? [
912
+ `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.`
913
+ ] : [];
377
914
  const missingIdentityInstructions = JSON.stringify({
378
915
  action: "probe_identity_then_session",
379
916
  steps: [
917
+ ...aipStep,
380
918
  "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.",
381
919
  "If step 1 is denied or you already have a stored operator_token (valid + not expired): send X-Operator-Token: opc_... and retry.",
382
920
  "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."
@@ -392,7 +930,7 @@ function createAgentScoreCore(options) {
392
930
  }
393
931
  };
394
932
  }
395
- const cacheKey = identity.operatorToken?.toLowerCase() ?? (identity.address ? normalizeAddress(identity.address) : "");
933
+ const cacheKey = identity.aipToken ? `aip:${(0, import_node_crypto.createHash)("sha256").update(identity.aipToken).digest("hex")}` : identity.operatorToken?.toLowerCase() ?? (identity.address ? normalizeAddress(identity.address) : "");
396
934
  const cached = cache.get(cacheKey);
397
935
  if (cached) {
398
936
  if (cached.allow) {
@@ -437,7 +975,7 @@ function createAgentScoreCore(options) {
437
975
  // regardless of policy.require_sanctions_clear (which gates the separate NAME screen).
438
976
  ...signer && { signer: { address: signer.address, network: signer.network } }
439
977
  };
440
- const result = identity.address ? await sdk.assess(identity.address, { ...opts, operatorToken: identity.operatorToken }) : await sdk.assess(null, { ...opts, operatorToken: identity.operatorToken });
978
+ 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 });
441
979
  data = result;
442
980
  } catch (err) {
443
981
  if (err instanceof import_sdk.PaymentRequiredError) {
@@ -508,6 +1046,9 @@ function createAgentScoreCore(options) {
508
1046
  const decisionReasons = data.decision_reasons ?? [];
509
1047
  const allow = decision === "allow" || decision == null;
510
1048
  cache.set(cacheKey, { allow, decision: decision ?? void 0, reasons: decisionReasons, raw: data });
1049
+ if (identity.address !== void 0 && identity.operatorToken === void 0 && identity.aipToken === void 0 && (data.signer_match !== void 0 || data.signer_sanctions !== void 0)) {
1050
+ lastSignerRaw.set(normalizeAddress(identity.address), data);
1051
+ }
511
1052
  if (allow) {
512
1053
  const quota = data.quota;
513
1054
  return {
@@ -572,9 +1113,7 @@ function createAgentScoreCore(options) {
572
1113
  }
573
1114
  function getSignerVerdict2(claimedAddress) {
574
1115
  const claimedNorm = normalizeAddress(claimedAddress);
575
- const cached = cache.get(claimedNorm);
576
- if (!cached) return void 0;
577
- const raw = cached.raw;
1116
+ const raw = lastSignerRaw.get(claimedNorm) ?? cache.get(claimedNorm)?.raw;
578
1117
  if (!raw) return void 0;
579
1118
  const rawMatch = raw.signer_match;
580
1119
  const rawSanctions = raw.signer_sanctions;
@@ -795,14 +1334,57 @@ var conditionalAgentscoreGatePlugin = async (fastify, options) => {
795
1334
  };
796
1335
  conditionalAgentscoreGatePlugin[/* @__PURE__ */ Symbol.for("skip-override")] = true;
797
1336
  var conditionalAgentscoreGate = conditionalAgentscoreGatePlugin;
1337
+ var AIT_STATE_KEY = "__agentscoreAit";
1338
+ function defaultAipOnDenied(_req, reply, body) {
1339
+ reply.code(body.status).header("content-type", "application/problem+json").send(body);
1340
+ }
1341
+ var aipGatePlugin = async (fastify, options) => {
1342
+ const { onDenied = defaultAipOnDenied, ...gateOpts } = options;
1343
+ fastify.addHook("preHandler", async (request, reply) => {
1344
+ const result = await verifyAitParts(
1345
+ { method: request.method, url: request.url, headers: request.headers },
1346
+ gateOpts
1347
+ );
1348
+ if (!result.ok) {
1349
+ await onDenied(request, reply, buildAipErrorBody(result.failure));
1350
+ return;
1351
+ }
1352
+ request[AIT_STATE_KEY] = result.ait;
1353
+ });
1354
+ };
1355
+ aipGatePlugin[/* @__PURE__ */ Symbol.for("skip-override")] = true;
1356
+ var aipGate = aipGatePlugin;
1357
+ var conditionalAipGatePlugin = async (fastify, options) => {
1358
+ const { onDenied = defaultAipOnDenied, ...gateOpts } = options;
1359
+ fastify.addHook("preHandler", async (request, reply) => {
1360
+ if (!hasAgentIdentityHeaderNode(request.headers)) return;
1361
+ const result = await verifyAitParts(
1362
+ { method: request.method, url: request.url, headers: request.headers },
1363
+ gateOpts
1364
+ );
1365
+ if (!result.ok) {
1366
+ await onDenied(request, reply, buildAipErrorBody(result.failure));
1367
+ return;
1368
+ }
1369
+ request[AIT_STATE_KEY] = result.ait;
1370
+ });
1371
+ };
1372
+ conditionalAipGatePlugin[/* @__PURE__ */ Symbol.for("skip-override")] = true;
1373
+ var conditionalAipGate = conditionalAipGatePlugin;
1374
+ function getVerifiedAit(request) {
1375
+ return request[AIT_STATE_KEY];
1376
+ }
798
1377
  // Annotate the CommonJS export names for ESM import in node:
799
1378
  0 && (module.exports = {
800
1379
  agentscoreGate,
1380
+ aipGate,
801
1381
  captureWallet,
802
1382
  conditionalAgentscoreGate,
1383
+ conditionalAipGate,
803
1384
  getAgentScoreData,
804
1385
  getGateDegradedState,
805
1386
  getGateQuotaInfo,
806
- getSignerVerdict
1387
+ getSignerVerdict,
1388
+ getVerifiedAit
807
1389
  });
808
1390
  //# sourceMappingURL=fastify.js.map