@agent-score/commerce 1.0.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 (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +306 -0
  3. package/dist/_response-DmziuJz6.d.mts +137 -0
  4. package/dist/_response-rbK0zM7y.d.ts +137 -0
  5. package/dist/api/index.d.mts +1 -0
  6. package/dist/api/index.d.ts +1 -0
  7. package/dist/api/index.js +37 -0
  8. package/dist/api/index.js.map +1 -0
  9. package/dist/api/index.mjs +14 -0
  10. package/dist/api/index.mjs.map +1 -0
  11. package/dist/challenge/index.d.mts +523 -0
  12. package/dist/challenge/index.d.ts +523 -0
  13. package/dist/challenge/index.js +354 -0
  14. package/dist/challenge/index.js.map +1 -0
  15. package/dist/challenge/index.mjs +318 -0
  16. package/dist/challenge/index.mjs.map +1 -0
  17. package/dist/core.d.mts +252 -0
  18. package/dist/core.d.ts +252 -0
  19. package/dist/core.js +500 -0
  20. package/dist/core.js.map +1 -0
  21. package/dist/core.mjs +472 -0
  22. package/dist/core.mjs.map +1 -0
  23. package/dist/discovery/index.d.mts +382 -0
  24. package/dist/discovery/index.d.ts +382 -0
  25. package/dist/discovery/index.js +675 -0
  26. package/dist/discovery/index.js.map +1 -0
  27. package/dist/discovery/index.mjs +630 -0
  28. package/dist/discovery/index.mjs.map +1 -0
  29. package/dist/identity/express.d.mts +44 -0
  30. package/dist/identity/express.d.ts +44 -0
  31. package/dist/identity/express.js +777 -0
  32. package/dist/identity/express.js.map +1 -0
  33. package/dist/identity/express.mjs +738 -0
  34. package/dist/identity/express.mjs.map +1 -0
  35. package/dist/identity/fastify.d.mts +63 -0
  36. package/dist/identity/fastify.d.ts +63 -0
  37. package/dist/identity/fastify.js +780 -0
  38. package/dist/identity/fastify.js.map +1 -0
  39. package/dist/identity/fastify.mjs +741 -0
  40. package/dist/identity/fastify.mjs.map +1 -0
  41. package/dist/identity/hono.d.mts +83 -0
  42. package/dist/identity/hono.d.ts +83 -0
  43. package/dist/identity/hono.js +779 -0
  44. package/dist/identity/hono.js.map +1 -0
  45. package/dist/identity/hono.mjs +740 -0
  46. package/dist/identity/hono.mjs.map +1 -0
  47. package/dist/identity/nextjs.d.mts +62 -0
  48. package/dist/identity/nextjs.d.ts +62 -0
  49. package/dist/identity/nextjs.js +784 -0
  50. package/dist/identity/nextjs.js.map +1 -0
  51. package/dist/identity/nextjs.mjs +747 -0
  52. package/dist/identity/nextjs.mjs.map +1 -0
  53. package/dist/identity/policy.d.mts +115 -0
  54. package/dist/identity/policy.d.ts +115 -0
  55. package/dist/identity/policy.js +81 -0
  56. package/dist/identity/policy.js.map +1 -0
  57. package/dist/identity/policy.mjs +53 -0
  58. package/dist/identity/policy.mjs.map +1 -0
  59. package/dist/identity/web.d.mts +82 -0
  60. package/dist/identity/web.d.ts +82 -0
  61. package/dist/identity/web.js +775 -0
  62. package/dist/identity/web.js.map +1 -0
  63. package/dist/identity/web.mjs +738 -0
  64. package/dist/identity/web.mjs.map +1 -0
  65. package/dist/index.d.mts +252 -0
  66. package/dist/index.d.ts +252 -0
  67. package/dist/index.js +432 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/index.mjs +388 -0
  70. package/dist/index.mjs.map +1 -0
  71. package/dist/payment/index.d.mts +716 -0
  72. package/dist/payment/index.d.ts +716 -0
  73. package/dist/payment/index.js +691 -0
  74. package/dist/payment/index.js.map +1 -0
  75. package/dist/payment/index.mjs +639 -0
  76. package/dist/payment/index.mjs.map +1 -0
  77. package/dist/signer-Cvdwn6Cs.d.mts +48 -0
  78. package/dist/signer-Cvdwn6Cs.d.ts +48 -0
  79. package/dist/stripe-multichain/index.d.mts +221 -0
  80. package/dist/stripe-multichain/index.d.ts +221 -0
  81. package/dist/stripe-multichain/index.js +243 -0
  82. package/dist/stripe-multichain/index.js.map +1 -0
  83. package/dist/stripe-multichain/index.mjs +199 -0
  84. package/dist/stripe-multichain/index.mjs.map +1 -0
  85. package/dist/wwwauthenticate-CU1eNvMQ.d.mts +37 -0
  86. package/dist/wwwauthenticate-CU1eNvMQ.d.ts +37 -0
  87. package/package.json +172 -0
package/dist/core.mjs ADDED
@@ -0,0 +1,472 @@
1
+ // src/address.ts
2
+ var SOLANA_BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
3
+ var isSolanaAddress = (address) => SOLANA_BASE58_RE.test(address) && !address.startsWith("0x");
4
+ var normalizeAddress = (address) => {
5
+ if (isSolanaAddress(address)) {
6
+ return address;
7
+ }
8
+ return address.toLowerCase();
9
+ };
10
+
11
+ // src/cache.ts
12
+ var TTLCache = class {
13
+ constructor(defaultTtlMs, maxSize = 1e4) {
14
+ this.defaultTtlMs = defaultTtlMs;
15
+ this.maxSize = maxSize;
16
+ }
17
+ defaultTtlMs;
18
+ store = /* @__PURE__ */ new Map();
19
+ maxSize;
20
+ get(key) {
21
+ const entry = this.store.get(key);
22
+ if (!entry) return void 0;
23
+ if (Date.now() > entry.expiresAt) {
24
+ this.store.delete(key);
25
+ return void 0;
26
+ }
27
+ return entry.value;
28
+ }
29
+ set(key, value, ttlMs) {
30
+ if (this.store.size >= this.maxSize) {
31
+ this.sweep();
32
+ }
33
+ if (this.store.size >= this.maxSize) {
34
+ this.evictOldest(this.store.size - this.maxSize + 1);
35
+ }
36
+ this.store.set(key, {
37
+ value,
38
+ expiresAt: Date.now() + (ttlMs ?? this.defaultTtlMs)
39
+ });
40
+ }
41
+ /** Remove all expired entries. */
42
+ sweep() {
43
+ const now = Date.now();
44
+ for (const [k, v] of this.store) {
45
+ if (now > v.expiresAt) {
46
+ this.store.delete(k);
47
+ }
48
+ }
49
+ }
50
+ /** Evict the oldest `count` entries by insertion order. */
51
+ evictOldest(count) {
52
+ let removed = 0;
53
+ for (const key of this.store.keys()) {
54
+ if (removed >= count) break;
55
+ this.store.delete(key);
56
+ removed++;
57
+ }
58
+ }
59
+ };
60
+
61
+ // src/core.ts
62
+ function stripTrailingSlashes(s) {
63
+ let end = s.length;
64
+ while (end > 0 && s.charCodeAt(end - 1) === 47) end--;
65
+ return end === s.length ? s : s.slice(0, end);
66
+ }
67
+ var CANONICAL_AGENTSCORE_API = "https://api.agentscore.sh";
68
+ var WALLET_SIGNER_MISMATCH_INSTRUCTIONS = JSON.stringify({
69
+ action: "resign_or_switch_to_operator_token",
70
+ steps: [
71
+ "Preferred: re-submit the payment signed by expected_signer (or any entry in linked_wallets \u2014 same-operator wallets are fungible) and retry with the same X-Wallet-Address.",
72
+ "Alternative: drop X-Wallet-Address and retry with X-Operator-Token. Use a stored opc_... if you have one; otherwise retry this request with NO identity header \u2014 the merchant will mint a verification session in the 403 body (verify_url + poll_secret). Share verify_url with the user, poll, receive a fresh opc_..."
73
+ ],
74
+ user_message: "The payment signer resolves to a different operator than X-Wallet-Address. Re-sign from expected_signer or any linked_wallets entry, or switch to X-Operator-Token."
75
+ });
76
+ var WALLET_AUTH_REQUIRES_WALLET_SIGNING_INSTRUCTIONS = JSON.stringify({
77
+ action: "switch_to_operator_token",
78
+ steps: [
79
+ "This payment rail (Stripe SPT, card) carries no wallet signature \u2014 X-Wallet-Address cannot be verified against the payment.",
80
+ "Drop X-Wallet-Address and retry with X-Operator-Token. If you do not have a stored opc_..., retry with no identity header to receive a verification session."
81
+ ],
82
+ user_message: "Wallet-address identity is only supported on wallet-signing rails (Tempo MPP, x402). On Stripe or card, use X-Operator-Token instead."
83
+ });
84
+ var INVALID_CREDENTIAL_INSTRUCTIONS = JSON.stringify({
85
+ action: "switch_token_or_restart_session",
86
+ steps: [
87
+ "The X-Operator-Token you sent does not match any credential. This is a permanent state \u2014 retrying with the same token will keep failing.",
88
+ "If you have other stored opc_... credentials, retry with one of them.",
89
+ "Otherwise drop X-Operator-Token and retry with no identity header \u2014 the merchant will mint a fresh verification session in the 403 body (verify_url + poll_secret) so the user can re-verify and you can poll for a new operator_token."
90
+ ],
91
+ user_message: "The operator_token is not recognized. Use a different stored token, or restart the verification session flow to mint a new one."
92
+ });
93
+ function buildAgentMemoryHint() {
94
+ const api = CANONICAL_AGENTSCORE_API;
95
+ return {
96
+ save_for_future_agentscore_gates: true,
97
+ 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.",
98
+ quickstart: "https://docs.agentscore.sh/guides/agent-identity",
99
+ identity_check_endpoint: `${api}/v1/credentials`,
100
+ identity_paths: {
101
+ 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.",
102
+ 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."
103
+ },
104
+ 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.",
105
+ do_not_persist_in_memory: ["operator_token", "poll_secret"],
106
+ persist_in_credential_store: ["operator_token"]
107
+ };
108
+ }
109
+ function createAgentScoreCore(options) {
110
+ if (!options.apiKey) {
111
+ throw new Error("AgentScore API key is required. Get one at https://agentscore.sh/sign-up");
112
+ }
113
+ const {
114
+ apiKey,
115
+ requireKyc,
116
+ requireSanctionsClear,
117
+ minAge,
118
+ blockedJurisdictions,
119
+ allowedJurisdictions,
120
+ failOpen = false,
121
+ cacheSeconds = 300,
122
+ baseUrl: rawBaseUrl = "https://api.agentscore.sh",
123
+ chain: gateChain,
124
+ userAgent,
125
+ createSessionOnMissing
126
+ } = options;
127
+ const baseUrl = stripTrailingSlashes(rawBaseUrl);
128
+ const agentMemoryHint = buildAgentMemoryHint();
129
+ const defaultUa = `@agent-score/commerce@${"1.0.0"}`;
130
+ const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
131
+ const API_TIMEOUT_MS = 1e4;
132
+ const cache = new TTLCache(cacheSeconds * 1e3);
133
+ async function evaluate(identity, ctx) {
134
+ if (!identity || !identity.address && !identity.operatorToken) {
135
+ if (failOpen) return { kind: "allow" };
136
+ if (createSessionOnMissing) {
137
+ try {
138
+ const sessionBody = {};
139
+ if (createSessionOnMissing.context != null) sessionBody.context = createSessionOnMissing.context;
140
+ if (createSessionOnMissing.productName != null) sessionBody.product_name = createSessionOnMissing.productName;
141
+ if (createSessionOnMissing.getSessionOptions && ctx !== void 0) {
142
+ try {
143
+ const dynamic = await createSessionOnMissing.getSessionOptions(ctx);
144
+ if (dynamic?.context != null) sessionBody.context = dynamic.context;
145
+ if (dynamic?.productName != null) sessionBody.product_name = dynamic.productName;
146
+ } catch (err) {
147
+ console.warn("[gate] createSessionOnMissing.getSessionOptions hook failed:", err instanceof Error ? err.message : err);
148
+ }
149
+ }
150
+ const sessionBaseUrl = stripTrailingSlashes(createSessionOnMissing.baseUrl ?? "https://api.agentscore.sh");
151
+ const sessionRes = await fetch(`${sessionBaseUrl}/v1/sessions`, {
152
+ method: "POST",
153
+ headers: {
154
+ "X-API-Key": createSessionOnMissing.apiKey,
155
+ "Content-Type": "application/json",
156
+ Accept: "application/json",
157
+ "User-Agent": userAgentHeader
158
+ },
159
+ body: JSON.stringify(sessionBody),
160
+ signal: AbortSignal.timeout(API_TIMEOUT_MS)
161
+ });
162
+ if (sessionRes.ok) {
163
+ const data = await sessionRes.json();
164
+ if (typeof data.session_id !== "string" || typeof data.poll_secret !== "string" || typeof data.verify_url !== "string") {
165
+ console.warn("[gate] /v1/sessions returned 200 without required fields \u2014 falling back to bare missing_identity");
166
+ } else {
167
+ let extra;
168
+ if (createSessionOnMissing.onBeforeSession && ctx !== void 0) {
169
+ try {
170
+ const sessionMeta = {
171
+ session_id: data.session_id,
172
+ verify_url: data.verify_url,
173
+ poll_secret: data.poll_secret,
174
+ poll_url: data.poll_url,
175
+ expires_at: data.expires_at
176
+ };
177
+ const result = await createSessionOnMissing.onBeforeSession(ctx, sessionMeta);
178
+ if (result && typeof result === "object") extra = result;
179
+ } catch (err) {
180
+ console.warn("[gate] createSessionOnMissing.onBeforeSession hook failed:", err instanceof Error ? err.message : err);
181
+ }
182
+ }
183
+ const apiNextSteps = data.next_steps;
184
+ return {
185
+ kind: "deny",
186
+ reason: {
187
+ code: "identity_verification_required",
188
+ verify_url: data.verify_url,
189
+ session_id: data.session_id,
190
+ poll_secret: data.poll_secret,
191
+ poll_url: data.poll_url,
192
+ agent_instructions: apiNextSteps ? JSON.stringify(apiNextSteps) : void 0,
193
+ agent_memory: agentMemoryHint,
194
+ ...extra && { extra }
195
+ }
196
+ };
197
+ }
198
+ }
199
+ } catch (err) {
200
+ console.warn("[gate] createSessionOnMissing path failed \u2014 falling back to bare missing_identity:", err instanceof Error ? err.message : err);
201
+ }
202
+ }
203
+ const missingIdentityInstructions = JSON.stringify({
204
+ action: "probe_identity_then_session",
205
+ steps: [
206
+ "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.",
207
+ "If step 1 is denied or you already have a stored operator_token (valid + not expired): send X-Operator-Token: opc_... and retry.",
208
+ "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."
209
+ ],
210
+ user_message: "Try X-Wallet-Address first if you have a wallet and the merchant accepts Tempo/x402; fall back to a stored X-Operator-Token, then to the session/verify flow described in agent_memory.bootstrap."
211
+ });
212
+ return {
213
+ kind: "deny",
214
+ reason: {
215
+ code: "missing_identity",
216
+ agent_instructions: missingIdentityInstructions,
217
+ agent_memory: agentMemoryHint
218
+ }
219
+ };
220
+ }
221
+ const cacheKey = identity.operatorToken?.toLowerCase() ?? (identity.address ? normalizeAddress(identity.address) : "");
222
+ const cached = cache.get(cacheKey);
223
+ if (cached) {
224
+ if (cached.allow) {
225
+ return { kind: "allow", data: cached.raw };
226
+ }
227
+ return {
228
+ kind: "deny",
229
+ reason: {
230
+ code: "wallet_not_trusted",
231
+ decision: cached.decision,
232
+ reasons: cached.reasons,
233
+ verify_url: cached.raw?.verify_url,
234
+ data: cached.raw
235
+ }
236
+ };
237
+ }
238
+ try {
239
+ const body = {};
240
+ if (identity.address) body.address = identity.address;
241
+ if (identity.operatorToken) body.operator_token = identity.operatorToken;
242
+ if (gateChain) body.chain = gateChain;
243
+ const policy = {};
244
+ if (requireKyc != null) policy.require_kyc = requireKyc;
245
+ if (requireSanctionsClear != null) policy.require_sanctions_clear = requireSanctionsClear;
246
+ if (minAge != null) policy.min_age = minAge;
247
+ if (blockedJurisdictions != null) policy.blocked_jurisdictions = blockedJurisdictions;
248
+ if (allowedJurisdictions != null) policy.allowed_jurisdictions = allowedJurisdictions;
249
+ if (Object.keys(policy).length > 0) body.policy = policy;
250
+ const response = await fetch(`${baseUrl}/v1/assess`, {
251
+ method: "POST",
252
+ headers: {
253
+ "X-API-Key": apiKey,
254
+ "Content-Type": "application/json",
255
+ Accept: "application/json",
256
+ "User-Agent": userAgentHeader
257
+ },
258
+ body: JSON.stringify(body),
259
+ signal: AbortSignal.timeout(API_TIMEOUT_MS)
260
+ });
261
+ if (response.status === 402) {
262
+ if (failOpen) return { kind: "allow" };
263
+ return { kind: "deny", reason: { code: "payment_required" } };
264
+ }
265
+ if (response.status === 401) {
266
+ try {
267
+ const errData = await response.clone().json();
268
+ const code = errData?.error?.code;
269
+ if (code === "token_expired") {
270
+ return {
271
+ kind: "deny",
272
+ reason: {
273
+ code,
274
+ data: errData,
275
+ ...typeof errData.verify_url === "string" ? { verify_url: errData.verify_url } : {},
276
+ ...typeof errData.session_id === "string" ? { session_id: errData.session_id } : {},
277
+ ...typeof errData.poll_secret === "string" ? { poll_secret: errData.poll_secret } : {},
278
+ ...typeof errData.poll_url === "string" ? { poll_url: errData.poll_url } : {},
279
+ ...errData.next_steps ? { agent_instructions: JSON.stringify(errData.next_steps) } : {},
280
+ ...errData.agent_memory ? { agent_memory: errData.agent_memory } : {}
281
+ }
282
+ };
283
+ }
284
+ if (code === "invalid_credential") {
285
+ return {
286
+ kind: "deny",
287
+ reason: {
288
+ code: "invalid_credential",
289
+ agent_instructions: INVALID_CREDENTIAL_INSTRUCTIONS,
290
+ agent_memory: agentMemoryHint
291
+ }
292
+ };
293
+ }
294
+ if (code) {
295
+ console.warn(`[gate] /v1/assess returned 401 ${code} \u2014 no specific handler, surfacing as api_error.`);
296
+ }
297
+ } catch (err) {
298
+ console.warn("[gate] /v1/assess 401 body parse failed:", err instanceof Error ? err.message : err);
299
+ }
300
+ }
301
+ if (response.status >= 400 && response.status < 500 && response.status !== 402) {
302
+ try {
303
+ const errData = await response.clone().json();
304
+ const code = errData?.error?.code;
305
+ if (code && code !== "token_expired" && code !== "invalid_credential") {
306
+ console.warn(
307
+ `[gate] /v1/assess returned ${response.status} ${code} \u2014 surfacing as api_error. Validate input shape before invoking the gate to avoid this.`
308
+ );
309
+ }
310
+ } catch {
311
+ }
312
+ }
313
+ if (!response.ok) {
314
+ throw new Error(`AgentScore API returned ${response.status}`);
315
+ }
316
+ const data = await response.json();
317
+ const decision = data.decision;
318
+ const decisionReasons = data.decision_reasons ?? [];
319
+ const allow = decision === "allow" || decision == null;
320
+ cache.set(cacheKey, { allow, decision: decision ?? void 0, reasons: decisionReasons, raw: data });
321
+ if (allow) {
322
+ return { kind: "allow", data };
323
+ }
324
+ return {
325
+ kind: "deny",
326
+ reason: {
327
+ code: "wallet_not_trusted",
328
+ decision: decision ?? void 0,
329
+ reasons: decisionReasons,
330
+ verify_url: data.verify_url,
331
+ data
332
+ }
333
+ };
334
+ } catch (err) {
335
+ console.warn("[gate] /v1/assess call failed \u2014 surfacing as api_error:", err instanceof Error ? err.message : err);
336
+ if (failOpen) return { kind: "allow" };
337
+ return { kind: "deny", reason: { code: "api_error" } };
338
+ }
339
+ }
340
+ async function captureWallet(options2) {
341
+ try {
342
+ const body = {
343
+ operator_token: options2.operatorToken,
344
+ wallet_address: options2.walletAddress,
345
+ network: options2.network
346
+ };
347
+ if (options2.idempotencyKey) body.idempotency_key = options2.idempotencyKey;
348
+ await fetch(`${baseUrl}/v1/credentials/wallets`, {
349
+ method: "POST",
350
+ headers: {
351
+ "X-API-Key": apiKey,
352
+ "Content-Type": "application/json",
353
+ Accept: "application/json",
354
+ "User-Agent": userAgentHeader
355
+ },
356
+ body: JSON.stringify(body),
357
+ signal: AbortSignal.timeout(API_TIMEOUT_MS)
358
+ });
359
+ } catch (err) {
360
+ console.warn("[agentscore-commerce] captureWallet failed:", err instanceof Error ? err.message : err);
361
+ }
362
+ }
363
+ async function resolveWalletToOperator(walletAddress) {
364
+ const wallet = normalizeAddress(walletAddress);
365
+ const extractFromCached = (raw) => {
366
+ const op = raw.resolved_operator;
367
+ const links = raw.linked_wallets;
368
+ return {
369
+ operator: typeof op === "string" ? op : null,
370
+ linkedWallets: Array.isArray(links) ? links.filter((w) => typeof w === "string") : []
371
+ };
372
+ };
373
+ const plainCached = cache.get(wallet);
374
+ if (plainCached?.raw) {
375
+ return { ok: true, ...extractFromCached(plainCached.raw) };
376
+ }
377
+ const resolveCached = cache.get(`resolve:${wallet}`);
378
+ if (resolveCached?.raw) {
379
+ return { ok: true, ...extractFromCached(resolveCached.raw) };
380
+ }
381
+ try {
382
+ const response = await fetch(`${baseUrl}/v1/assess`, {
383
+ method: "POST",
384
+ headers: {
385
+ "X-API-Key": apiKey,
386
+ "Content-Type": "application/json",
387
+ Accept: "application/json",
388
+ "User-Agent": userAgentHeader
389
+ },
390
+ body: JSON.stringify({ address: walletAddress }),
391
+ signal: AbortSignal.timeout(API_TIMEOUT_MS)
392
+ });
393
+ if (!response.ok) return { ok: false };
394
+ const data = await response.json();
395
+ cache.set(`resolve:${wallet}`, { allow: true, raw: data });
396
+ return { ok: true, ...extractFromCached(data) };
397
+ } catch (err) {
398
+ console.warn("[gate] resolveWalletToOperator failed \u2014 returning { ok:false }:", err instanceof Error ? err.message : err);
399
+ return { ok: false };
400
+ }
401
+ }
402
+ function reportSignerEvent(kind) {
403
+ try {
404
+ const pending = fetch(`${baseUrl}/v1/telemetry/signer-match`, {
405
+ method: "POST",
406
+ headers: {
407
+ "X-API-Key": apiKey,
408
+ "Content-Type": "application/json",
409
+ Accept: "application/json",
410
+ "User-Agent": userAgentHeader
411
+ },
412
+ body: JSON.stringify({ kind }),
413
+ signal: AbortSignal.timeout(API_TIMEOUT_MS)
414
+ });
415
+ if (pending && typeof pending.catch === "function") {
416
+ pending.catch((err) => {
417
+ console.warn("[agentscore-commerce] signer-match telemetry failed:", err instanceof Error ? err.message : err);
418
+ });
419
+ }
420
+ } catch {
421
+ }
422
+ }
423
+ async function verifyWalletSignerMatch(options2) {
424
+ const { claimedWallet, signer } = options2;
425
+ if (!signer) {
426
+ reportSignerEvent("wallet_auth_requires_wallet_signing");
427
+ return {
428
+ kind: "wallet_auth_requires_wallet_signing",
429
+ claimedWallet,
430
+ agentInstructions: WALLET_AUTH_REQUIRES_WALLET_SIGNING_INSTRUCTIONS
431
+ };
432
+ }
433
+ const claimedNorm = normalizeAddress(claimedWallet);
434
+ const signerNorm = normalizeAddress(signer);
435
+ if (claimedNorm === signerNorm) {
436
+ reportSignerEvent("pass");
437
+ return { kind: "pass", claimedOperator: null, signerOperator: null };
438
+ }
439
+ const [claimedResolve, signerResolve] = await Promise.all([
440
+ resolveWalletToOperator(claimedNorm),
441
+ resolveWalletToOperator(signerNorm)
442
+ ]);
443
+ if (!claimedResolve.ok || !signerResolve.ok) {
444
+ reportSignerEvent("api_error");
445
+ return { kind: "api_error", claimedWallet: claimedNorm };
446
+ }
447
+ const claimedOperator = claimedResolve.operator;
448
+ const signerOperator = signerResolve.operator;
449
+ if (claimedOperator && signerOperator && claimedOperator === signerOperator) {
450
+ reportSignerEvent("pass");
451
+ return { kind: "pass", claimedOperator, signerOperator };
452
+ }
453
+ reportSignerEvent("wallet_signer_mismatch");
454
+ return {
455
+ kind: "wallet_signer_mismatch",
456
+ claimedOperator,
457
+ actualSignerOperator: signerOperator,
458
+ expectedSigner: claimedNorm,
459
+ actualSigner: signerNorm,
460
+ // Populated from /v1/assess.linked_wallets on the claimed wallet — the full set of
461
+ // wallets the agent CAN sign with to satisfy the claim (same-operator rule).
462
+ linkedWallets: claimedResolve.linkedWallets,
463
+ agentInstructions: WALLET_SIGNER_MISMATCH_INSTRUCTIONS
464
+ };
465
+ }
466
+ return { evaluate, captureWallet, verifyWalletSignerMatch };
467
+ }
468
+ export {
469
+ buildAgentMemoryHint,
470
+ createAgentScoreCore
471
+ };
472
+ //# sourceMappingURL=core.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/address.ts","../src/cache.ts","../src/core.ts"],"sourcesContent":["// Network-aware address normalization. EVM addresses (0x + 40 hex) are\n// case-insensitive in the protocol — we lowercase them so DB lookups against\n// `address_lower`-style columns work. Solana addresses are base58 and are\n// case-sensitive — we MUST preserve the input verbatim, never lowercase.\n//\n// Must produce identical output to the API normalizer (`core/api/src/lib/address.ts`)\n// so the gate, API, and merchants normalize the same way. If the two ever drift,\n// captured wallets won't resolve and signer-match silently breaks.\n\nconst SOLANA_BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\nconst EVM_RE = /^0x[0-9a-fA-F]{40}$/;\n\nexport const isValidEvmAddress = (address: string): boolean => EVM_RE.test(address);\n\nexport const isSolanaAddress = (address: string): boolean =>\n SOLANA_BASE58_RE.test(address) && !address.startsWith('0x');\n\nexport const isValidAddress = (address: string): boolean =>\n isValidEvmAddress(address) || isSolanaAddress(address);\n\nexport const normalizeAddress = (address: string): string => {\n if (isSolanaAddress(address)) { return address; }\n return address.toLowerCase();\n};\n","export class TTLCache<T> {\n private store = new Map<string, { value: T; expiresAt: number }>();\n private maxSize: number;\n\n constructor(private defaultTtlMs: number, maxSize = 10000) {\n this.maxSize = maxSize;\n }\n\n get(key: string): T | undefined {\n const entry = this.store.get(key);\n if (!entry) return undefined;\n if (Date.now() > entry.expiresAt) {\n this.store.delete(key);\n return undefined;\n }\n return entry.value;\n }\n\n set(key: string, value: T, ttlMs?: number): void {\n if (this.store.size >= this.maxSize) {\n this.sweep();\n }\n if (this.store.size >= this.maxSize) {\n this.evictOldest(this.store.size - this.maxSize + 1);\n }\n this.store.set(key, {\n value,\n expiresAt: Date.now() + (ttlMs ?? this.defaultTtlMs),\n });\n }\n\n /** Remove all expired entries. */\n private sweep(): void {\n const now = Date.now();\n for (const [k, v] of this.store) {\n if (now > v.expiresAt) {\n this.store.delete(k);\n }\n }\n }\n\n /** Evict the oldest `count` entries by insertion order. */\n private evictOldest(count: number): void {\n let removed = 0;\n for (const key of this.store.keys()) {\n if (removed >= count) break;\n this.store.delete(key);\n removed++;\n }\n }\n}\n","import { normalizeAddress } from './address';\nimport { TTLCache } from './cache';\n\n// Character-based trim avoids a CodeQL polynomial-redos false positive on\n// `/\\/+$/` patterns that report library-input strings.\nfunction stripTrailingSlashes(s: string): string {\n let end = s.length;\n while (end > 0 && s.charCodeAt(end - 1) === 47 /* '/' */) end--;\n return end === s.length ? s : s.slice(0, end);\n}\n\ndeclare const __VERSION__: string;\n\n// ---------------------------------------------------------------------------\n// Public types (framework-agnostic)\n// ---------------------------------------------------------------------------\n\nexport interface AgentIdentity {\n address?: string;\n operatorToken?: string;\n}\n\n/**\n * Session metadata returned from `POST /v1/sessions`. Surfaced to the `onBeforeSession`\n * hook so merchants can correlate an AgentScore session with their own resume token\n * (e.g. a pending-order id).\n */\nexport interface SessionMetadata {\n session_id: string;\n verify_url: string;\n poll_secret: string;\n poll_url: string;\n expires_at?: string;\n}\n\n/**\n * Configuration for auto-creating a verification session when no identity is present.\n *\n * The static `context` / `productName` options are sent on every session request. For\n * per-request context (e.g. the specific product the agent was trying to buy), pass\n * a `getSessionOptions` callback that returns dynamic values; its return is merged\n * over the static defaults.\n *\n * `onBeforeSession` is a side-effect hook that runs after the session is minted but\n * before the 403 is built. Use it to pre-create a reservation/draft/pending-order\n * row in your DB so agents can resume via a merchant-specific id. Return value is\n * merged into `DenialReason.extra`, so it surfaces in both the default 403 body and\n * in a custom `onDenied` handler.\n */\nexport interface CreateSessionOnMissing<TCtx = unknown> {\n apiKey: string;\n baseUrl?: string;\n context?: string;\n productName?: string;\n /** Per-request override of `context` / `productName`. Invoked with the framework context. */\n getSessionOptions?: (ctx: TCtx) => Promise<{ context?: string; productName?: string }>\n | { context?: string; productName?: string };\n /** Side-effect hook that runs after the session is minted. Return value is merged\n * into `DenialReason.extra` so custom `onDenied` handlers can include merchant-specific\n * fields (e.g. `order_id`) in the 403 response. Hook errors are logged and swallowed —\n * a failing side effect should not block the 403 from reaching the agent. */\n onBeforeSession?: (ctx: TCtx, session: SessionMetadata) => Promise<Record<string, unknown>>\n | Record<string, unknown>;\n}\n\nexport interface AgentScoreCoreOptions {\n /** AgentScore API key. Required. */\n apiKey: string;\n /** Require KYC verification. */\n requireKyc?: boolean;\n /** Require operator to be clear of sanctions. */\n requireSanctionsClear?: boolean;\n /** Minimum operator age bracket (18 or 21). */\n minAge?: number;\n /** List of blocked jurisdictions (blocklist). */\n blockedJurisdictions?: string[];\n /** List of allowed jurisdictions (allowlist — only these pass). */\n allowedJurisdictions?: string[];\n /** If true, allow the request through when the API is unreachable. Defaults to false. */\n failOpen?: boolean;\n /** How long to cache results, in seconds. Defaults to 300. */\n cacheSeconds?: number;\n /** AgentScore API base URL. Defaults to \"https://api.agentscore.sh\". */\n baseUrl?: string;\n /** Optional chain to filter scoring to. */\n chain?: string;\n /** Prepended to the default User-Agent as `\"{userAgent} (@agent-score/commerce@{version})\"`. Use to attribute API calls to your app. */\n userAgent?: string;\n /** When set and no identity is found, create a verification session instead of denying immediately. */\n createSessionOnMissing?: CreateSessionOnMissing;\n}\n\nexport type DenialCode =\n | 'wallet_not_trusted'\n | 'missing_identity'\n | 'api_error'\n | 'payment_required'\n | 'identity_verification_required'\n // Wallet-signer binding: claimed X-Wallet-Address must resolve to the same operator as\n // the payment signer; wallet-auth is rejected on rails with no wallet signer.\n | 'wallet_signer_mismatch'\n | 'wallet_auth_requires_wallet_signing'\n // Granular credential-state denials passed through from /v1/assess.\n // - `token_expired`: revoked + TTL-expired (the API unifies these). The 401 body carries\n // an auto-minted session, forwarded into DenialReason for one-shot recovery.\n // - `invalid_credential`: the token doesn't exist at all (typo, never minted, fabricated).\n // No auto-session is minted by the API for this case — agents should switch to a\n // different stored token or drop the header to bootstrap a fresh session.\n | 'token_expired'\n | 'invalid_credential';\n\n/**\n * Cross-merchant pattern hint emitted on bootstrap denials and session-create responses.\n * LLM-hosted agents should persist this to long-term memory so future AgentScore encounters skip\n * the cold-start session flow. Contents are the pattern, not secrets.\n */\nexport interface AgentMemoryHint {\n save_for_future_agentscore_gates: true;\n pattern_summary: string;\n quickstart: string;\n identity_check_endpoint: string;\n list_wallets_endpoint?: string;\n identity_paths: { wallet: string; operator_token: string };\n bootstrap: string;\n do_not_persist_in_memory: string[];\n persist_in_credential_store: string[];\n}\n\nexport interface DenialReason {\n code: DenialCode;\n /** Human-readable explanation. When omitted, `denialReasonToBody` substitutes a per-code default. */\n message?: string;\n decision?: string;\n reasons?: string[];\n verify_url?: string;\n session_id?: string;\n poll_secret?: string;\n poll_url?: string;\n agent_instructions?: string;\n /** Cross-merchant memory hint. Emitted on bootstrap denials only by default. */\n agent_memory?: AgentMemoryHint;\n /** Full assess response when the denial came from `/v1/assess`. Lets consumers access fields\n * not promoted to first-class DenialReason properties (e.g., `policy_result`). Undefined for\n * denials that did not originate from an assess call (missing_identity, api_error,\n * payment_required, identity_verification_required). */\n data?: AgentScoreData;\n /** Extra fields returned from the `createSessionOnMissing.onBeforeSession` hook. Merged\n * into the default 403 body; custom `onDenied` handlers can spread these into their own\n * response shape (e.g. to include a merchant-minted `order_id`). */\n extra?: Record<string, unknown>;\n // ---------------------------------------------------------------------------\n // Wallet-signer-match fields — populated for wallet_signer_mismatch only.\n // ---------------------------------------------------------------------------\n /** Operator id resolved from `X-Wallet-Address`. */\n claimed_operator?: string;\n /** Operator id the actual payment signer resolves to. `null` when the signer wallet isn't\n * linked to any operator (treat as a different identity). */\n actual_signer_operator?: string | null;\n /** The wallet the agent claimed via header. Echoed back for self-correction. */\n expected_signer?: string;\n /** The wallet that actually signed the payment. */\n actual_signer?: string;\n /** Wallets the claimed operator could sign with (if enumerable). Present when non-empty. */\n linked_wallets?: string[];\n}\n\nexport interface AgentScoreData {\n decision: string | null;\n decision_reasons: string[];\n identity_method?: string;\n operator_verification?: {\n level: string;\n operator_type: string | null;\n verified_at: string | null;\n };\n /** Account-level KYC facts that apply to every operator under the same account.\n * Populated when the API returns account_verification (post-KYC operator). */\n account_verification?: {\n kyc_level?: string;\n sanctions_clear?: boolean;\n age_bracket?: string;\n jurisdiction?: string;\n verified_at?: string | null;\n };\n resolved_operator?: string | null;\n /** Wallets linked to the same operator as the resolved identity. Capped at 100 entries\n * by the API. Useful for advertising in 402 challenges so wallet-auth agents know which\n * alt-signers will satisfy `wallet_signer_mismatch`. */\n linked_wallets?: string[];\n verify_url?: string;\n policy_result?: {\n all_passed: boolean;\n checks: Array<{\n rule: string;\n passed: boolean;\n required?: unknown;\n actual?: unknown;\n }>;\n } | null;\n}\n\n/**\n * Outcome from `AgentScoreCore.evaluate()`. Adapters map this to framework-specific responses.\n *\n * - `{ kind: 'allow', data }` — the request passed the policy. `data` is present on a normal\n * allow; `undefined` when fail-open short-circuited (identity missing, API unreachable,\n * timeout, or 402 paid-tier required).\n * - `{ kind: 'deny', reason }` — the request was denied. Adapters should render a 403 with the\n * reason, or invoke the caller's custom denial handler.\n */\nexport type EvaluateOutcome =\n | { kind: 'allow'; data?: AgentScoreData }\n | { kind: 'deny'; reason: DenialReason };\n\nexport interface CaptureWalletOptions {\n /** Operator credential (`opc_...`) that the agent authenticated with. */\n operatorToken: string;\n /** Signer wallet recovered from the payment payload. */\n walletAddress: string;\n /** Key-derivation family — `\"evm\"` for any EVM chain, `\"solana\"` for Solana. */\n network: 'evm' | 'solana';\n /** Optional stable key for the logical payment (e.g., payment intent id, tx hash). When the\n * same key is seen again for the same (credential, wallet, network), the server no-ops —\n * prevents agent retries from inflating transaction_count. */\n idempotencyKey?: string;\n}\n\nexport interface VerifyWalletSignerMatchOptions {\n /** The wallet claimed via `X-Wallet-Address`. */\n claimedWallet: string;\n /** The signer wallet recovered from the payment credential. `null` means the rail carries\n * no wallet signer (SPT, card) — the helper returns `wallet_auth_requires_wallet_signing`. */\n signer: string | null;\n /** Network of the signer. EVM covers every EVM chain; `solana` lives in its own namespace. */\n network?: 'evm' | 'solana';\n}\n\nexport type VerifyWalletSignerResult =\n | { kind: 'pass'; claimedOperator: string | null; signerOperator: string | null }\n | {\n kind: 'wallet_signer_mismatch';\n claimedOperator: string | null;\n actualSignerOperator: string | null;\n expectedSigner: string;\n actualSigner: string;\n linkedWallets: string[];\n /** JSON-encoded action copy (action + steps + user_message). Spread into the 403 body\n * verbatim so agents get a concrete recovery path inside the denial response itself. */\n agentInstructions: string;\n }\n | {\n kind: 'wallet_auth_requires_wallet_signing';\n claimedWallet: string;\n agentInstructions: string;\n }\n // Transient — the resolve call to /v1/assess failed or timed out. Caller should\n // retry or surface as 503. Distinct from wallet_signer_mismatch (which is an actual\n // security reject) so legitimate users don't get rejected on network flakes.\n | { kind: 'api_error'; claimedWallet: string };\n\nexport interface AgentScoreCore {\n /**\n * Evaluate the request's identity against the configured policy.\n * @param identity - extracted identity (wallet address and/or operator token)\n * @param ctx - optional framework-specific context (Hono c, Express req, etc.) passed\n * through to `createSessionOnMissing` hooks. Opaque to core.\n */\n evaluate(identity: AgentIdentity | undefined, ctx?: unknown): Promise<EvaluateOutcome>;\n /** Report a wallet seen paying under an operator credential. Fire-and-forget; silently\n * swallows non-fatal errors because capture is informational, not on the critical path. */\n captureWallet(options: CaptureWalletOptions): Promise<void>;\n /**\n * Verify the payment signer resolves to the same operator as the claimed `X-Wallet-Address`.\n *\n * Returns `pass` when the signer is linked to the same operator as the claimed wallet\n * (byte-equal wallets pass trivially; other wallets linked to the same operator also pass —\n * multi-wallet agents work without ergonomic pain). Returns `wallet_signer_mismatch` when\n * the signer resolves to a different (or no) operator. Returns `wallet_auth_requires_wallet_signing`\n * when the signer is `null` (SPT, card — rails that carry no wallet signature).\n *\n * Call this AFTER the gate evaluates (so the claimed wallet's operator is cached) and\n * AFTER the payment credential is parsed (so the signer is known). Merchants should call\n * it before settling payment.\n */\n verifyWalletSignerMatch(options: VerifyWalletSignerMatchOptions): Promise<VerifyWalletSignerResult>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\ninterface AssessResult {\n allow: boolean;\n decision?: string;\n reasons?: string[];\n raw?: unknown;\n}\n\n/**\n * Build the cross-merchant memory hint emitted on bootstrap denials. Base URLs are\n * derived from the gate's AgentScore API base so self-hosted / staging deployments get\n * correct pointers. Contents describe the AgentScore identity substrate in transferable\n * terms; merchant-specific context lives in other `agent_instructions` fields.\n */\n// Canonical production AgentScore API — used as the authoritative source for endpoint pointers\n// emitted to agent memory regardless of how a given merchant configured their gate's baseUrl.\n// Hardcoded so a malicious merchant can't set `baseUrl: \"evil.com\"` and phish agents into\n// sending their credentials to attacker-controlled endpoints.\nconst CANONICAL_AGENTSCORE_API = 'https://api.agentscore.sh';\n\n// JSON-encoded action copy emitted on wallet-signer-match denials. Spread into 403 bodies\n// by merchants so agents get a concrete recovery path inside the denial response itself —\n// no discovery-doc round trip required.\nconst WALLET_SIGNER_MISMATCH_INSTRUCTIONS = JSON.stringify({\n action: 'resign_or_switch_to_operator_token',\n steps: [\n 'Preferred: re-submit the payment signed by expected_signer (or any entry in linked_wallets — same-operator wallets are fungible) and retry with the same X-Wallet-Address.',\n 'Alternative: drop X-Wallet-Address and retry with X-Operator-Token. Use a stored opc_... if you have one; otherwise retry this request with NO identity header — the merchant will mint a verification session in the 403 body (verify_url + poll_secret). Share verify_url with the user, poll, receive a fresh opc_...',\n ],\n user_message:\n 'The payment signer resolves to a different operator than X-Wallet-Address. Re-sign from expected_signer or any linked_wallets entry, or switch to X-Operator-Token.',\n});\n\nconst WALLET_AUTH_REQUIRES_WALLET_SIGNING_INSTRUCTIONS = JSON.stringify({\n action: 'switch_to_operator_token',\n steps: [\n 'This payment rail (Stripe SPT, card) carries no wallet signature — X-Wallet-Address cannot be verified against the payment.',\n 'Drop X-Wallet-Address and retry with X-Operator-Token. If you do not have a stored opc_..., retry with no identity header to receive a verification session.',\n ],\n user_message:\n 'Wallet-address identity is only supported on wallet-signing rails (Tempo MPP, x402). On Stripe or card, use X-Operator-Token instead.',\n});\n\n// `invalid_credential` is permanent — the token doesn't exist (typo, never minted, fabricated).\n// Distinct from `token_expired` (which carries an auto-session for one-shot recovery): the\n// API doesn't auto-mint a session here because the client may simply have a different valid\n// token to try. Agents should switch tokens or drop the header to bootstrap a session.\nconst INVALID_CREDENTIAL_INSTRUCTIONS = JSON.stringify({\n action: 'switch_token_or_restart_session',\n steps: [\n 'The X-Operator-Token you sent does not match any credential. This is a permanent state — retrying with the same token will keep failing.',\n 'If you have other stored opc_... credentials, retry with one of them.',\n 'Otherwise drop X-Operator-Token and retry with no identity header — the merchant will mint a fresh verification session in the 403 body (verify_url + poll_secret) so the user can re-verify and you can poll for a new operator_token.',\n ],\n user_message:\n 'The operator_token is not recognized. Use a different stored token, or restart the verification session flow to mint a new one.',\n});\n\nexport function buildAgentMemoryHint(): AgentMemoryHint {\n // Memory pointers always point at the canonical production API — merchants must not be\n // able to redirect the cross-merchant memory surface, since that would be a phishing\n // vector for the verify URL.\n const api = CANONICAL_AGENTSCORE_API;\n return {\n save_for_future_agentscore_gates: true,\n pattern_summary:\n 'AgentScore is a cross-merchant identity substrate for agent commerce. Any endpoint that ' +\n 'returns 403 missing_identity / identity_verification_required or 402 challenges referencing AgentScore uses ' +\n 'the same identity system. One KYC works across all AgentScore merchants — no re-verification ' +\n 'per site. Save this pattern (and the endpoints below) to persistent memory so future ' +\n 'AgentScore encounters skip the cold-start session flow.',\n quickstart: 'https://docs.agentscore.sh/guides/agent-identity',\n identity_check_endpoint: `${api}/v1/credentials`,\n identity_paths: {\n wallet:\n 'If paying from a crypto wallet you have used before on any AgentScore merchant, send ' +\n '`X-Wallet-Address: 0x...`. Shortest path; no token lifecycle to manage.',\n operator_token:\n 'For any rail (Stripe SPT, card, or a wallet you have not linked yet), send ' +\n '`X-Operator-Token: opc_...`. Reusable across merchants until the token expires.',\n },\n bootstrap:\n 'If you have neither a linked wallet nor a valid operator_token, follow the session/verify ' +\n 'flow in the per-request `agent_instructions` block. This happens at most once per agent ' +\n 'identity — after first verification, the operator_token and any subsequently used wallet ' +\n 'are reusable everywhere.',\n do_not_persist_in_memory: ['operator_token', 'poll_secret'],\n persist_in_credential_store: ['operator_token'],\n };\n}\n\n// ---------------------------------------------------------------------------\n// Core factory\n// ---------------------------------------------------------------------------\n\nexport function createAgentScoreCore(options: AgentScoreCoreOptions): AgentScoreCore {\n if (!options.apiKey) {\n throw new Error('AgentScore API key is required. Get one at https://agentscore.sh/sign-up');\n }\n\n const {\n apiKey,\n requireKyc,\n requireSanctionsClear,\n minAge,\n blockedJurisdictions,\n allowedJurisdictions,\n failOpen = false,\n cacheSeconds = 300,\n baseUrl: rawBaseUrl = 'https://api.agentscore.sh',\n chain: gateChain,\n userAgent,\n createSessionOnMissing,\n } = options;\n\n const baseUrl = stripTrailingSlashes(rawBaseUrl);\n const agentMemoryHint = buildAgentMemoryHint();\n\n const defaultUa = `@agent-score/commerce@${__VERSION__}`;\n const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;\n\n const API_TIMEOUT_MS = 10_000;\n\n const cache = new TTLCache<AssessResult>(cacheSeconds * 1000);\n\n async function evaluate(identity: AgentIdentity | undefined, ctx?: unknown): Promise<EvaluateOutcome> {\n // Treat \"returned identity object with no usable fields\" the same as \"no identity at all\" —\n // otherwise a misbehaving custom extractIdentity would send an empty body to /v1/assess.\n if (!identity || (!identity.address && !identity.operatorToken)) {\n if (failOpen) return { kind: 'allow' };\n\n if (createSessionOnMissing) {\n try {\n // Start with static context/productName; let getSessionOptions override per-request.\n const sessionBody: { context?: string; product_name?: string } = {};\n if (createSessionOnMissing.context != null) sessionBody.context = createSessionOnMissing.context;\n if (createSessionOnMissing.productName != null) sessionBody.product_name = createSessionOnMissing.productName;\n\n if (createSessionOnMissing.getSessionOptions && ctx !== undefined) {\n try {\n const dynamic = await createSessionOnMissing.getSessionOptions(ctx);\n if (dynamic?.context != null) sessionBody.context = dynamic.context;\n if (dynamic?.productName != null) sessionBody.product_name = dynamic.productName;\n } catch (err) {\n console.warn('[gate] createSessionOnMissing.getSessionOptions hook failed:', err instanceof Error ? err.message : err);\n }\n }\n\n const sessionBaseUrl = stripTrailingSlashes(createSessionOnMissing.baseUrl ?? 'https://api.agentscore.sh');\n const sessionRes = await fetch(`${sessionBaseUrl}/v1/sessions`, {\n method: 'POST',\n headers: {\n 'X-API-Key': createSessionOnMissing.apiKey,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': userAgentHeader,\n },\n body: JSON.stringify(sessionBody),\n signal: AbortSignal.timeout(API_TIMEOUT_MS),\n });\n\n if (sessionRes.ok) {\n const data = (await sessionRes.json()) as Record<string, unknown>;\n\n // Validate required fields before trusting the response. A misbehaving\n // (or mocked-wrong) API could 200 without session_id/poll_secret/verify_url,\n // which would propagate `undefined` into the 403 body and leave the agent\n // stuck — treat that as a session-create failure and fall back to the bare\n // missing_identity denial with the probe strategy copy.\n if (\n typeof data.session_id !== 'string' ||\n typeof data.poll_secret !== 'string' ||\n typeof data.verify_url !== 'string'\n ) {\n console.warn('[gate] /v1/sessions returned 200 without required fields — falling back to bare missing_identity');\n // fall through to the bare denial below\n } else {\n\n // Run onBeforeSession side-effect hook. Errors are swallowed — a failing DB\n // write (e.g. can't insert pending order) should not block the 403.\n let extra: Record<string, unknown> | undefined;\n if (createSessionOnMissing.onBeforeSession && ctx !== undefined) {\n try {\n const sessionMeta = {\n session_id: data.session_id as string,\n verify_url: data.verify_url as string,\n poll_secret: data.poll_secret as string,\n poll_url: data.poll_url as string,\n expires_at: data.expires_at as string | undefined,\n };\n const result = await createSessionOnMissing.onBeforeSession(ctx, sessionMeta);\n if (result && typeof result === 'object') extra = result;\n } catch (err) {\n console.warn('[gate] createSessionOnMissing.onBeforeSession hook failed:', err instanceof Error ? err.message : err);\n }\n }\n\n // The API emits `next_steps` (structured object) on /v1/sessions success.\n // Stringify it into the gate's `agent_instructions` contract so merchants\n // get the same JSON-encoded {action, steps, user_message} envelope as every\n // other gate-emitted denial.\n const apiNextSteps = data.next_steps as Record<string, unknown> | undefined;\n return {\n kind: 'deny',\n reason: {\n code: 'identity_verification_required',\n verify_url: data.verify_url as string,\n session_id: data.session_id as string,\n poll_secret: data.poll_secret as string,\n poll_url: data.poll_url as string | undefined,\n agent_instructions: apiNextSteps ? JSON.stringify(apiNextSteps) : undefined,\n agent_memory: agentMemoryHint,\n ...(extra && { extra }),\n },\n };\n }\n }\n } catch (err) {\n // Session-mint failed (network, /v1/sessions returned non-2xx, body parse error,\n // onBeforeSession threw inside the inner try). Falling through to bare\n // missing_identity is correct — agents still get a 403 with a probe-strategy\n // hint. But the silent catch used to mask /v1/sessions schema drift and\n // unreachable-API issues for hours, so log loudly.\n console.warn('[gate] createSessionOnMissing path failed — falling back to bare missing_identity:', err instanceof Error ? err.message : err);\n }\n }\n\n // Bare missing-identity denial (no session was auto-created). Describe the probe\n // strategy so agents without memory can recover: try wallet first on signing rails,\n // fall back to stored opc_..., fall back to session flow (noting that only\n // auto-session merchants return verify_url + poll data on the retry).\n const missingIdentityInstructions = JSON.stringify({\n action: 'probe_identity_then_session',\n steps: [\n 'If you have a wallet AND this merchant accepts a wallet-signing rail (Tempo MPP or x402 — 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 — share it with the user to claim the wallet + complete KYC, then retry.',\n 'If step 1 is denied or you already have a stored operator_token (valid + not expired): send X-Operator-Token: opc_... and retry.',\n '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 — 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 — 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.',\n ],\n user_message:\n 'Try X-Wallet-Address first if you have a wallet and the merchant accepts Tempo/x402; fall back to a stored X-Operator-Token, then to the session/verify flow described in agent_memory.bootstrap.',\n });\n return {\n kind: 'deny',\n reason: {\n code: 'missing_identity',\n agent_instructions: missingIdentityInstructions,\n agent_memory: agentMemoryHint,\n },\n };\n }\n\n // operator_token is opaque + ASCII-only — lowercasing is safe. Wallet addresses go\n // through normalizeAddress because Solana base58 is case-sensitive and lowercasing\n // would corrupt the cache key (a Solana cache miss every time, plus collision risk\n // with mixed-case variants of the same operator).\n const cacheKey = identity.operatorToken?.toLowerCase() ?? (identity.address ? normalizeAddress(identity.address) : '');\n\n const cached = cache.get(cacheKey);\n if (cached) {\n if (cached.allow) {\n return { kind: 'allow', data: cached.raw as AgentScoreData };\n }\n return {\n kind: 'deny',\n reason: {\n code: 'wallet_not_trusted',\n decision: cached.decision,\n reasons: cached.reasons,\n verify_url: (cached.raw as Record<string, unknown> | undefined)?.verify_url as string | undefined,\n data: cached.raw as AgentScoreData | undefined,\n },\n };\n }\n\n try {\n const body: Record<string, unknown> = {};\n if (identity.address) body.address = identity.address;\n if (identity.operatorToken) body.operator_token = identity.operatorToken;\n if (gateChain) body.chain = gateChain;\n\n const policy: Record<string, unknown> = {};\n if (requireKyc != null) policy.require_kyc = requireKyc;\n if (requireSanctionsClear != null) policy.require_sanctions_clear = requireSanctionsClear;\n if (minAge != null) policy.min_age = minAge;\n if (blockedJurisdictions != null) policy.blocked_jurisdictions = blockedJurisdictions;\n if (allowedJurisdictions != null) policy.allowed_jurisdictions = allowedJurisdictions;\n if (Object.keys(policy).length > 0) body.policy = policy;\n\n const response = await fetch(`${baseUrl}/v1/assess`, {\n method: 'POST',\n headers: {\n 'X-API-Key': apiKey,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': userAgentHeader,\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(API_TIMEOUT_MS),\n });\n\n if (response.status === 402) {\n if (failOpen) return { kind: 'allow' };\n return { kind: 'deny', reason: { code: 'payment_required' } };\n }\n\n // Pass through the API's token_expired 401 (covers both expired and revoked\n // credentials — the API deliberately doesn't distinguish). The 401 body carries\n // an auto-minted session (verify_url + session_id + poll_secret + next_steps +\n // agent_memory) so agents can recover without holding an API key. Forward all of\n // that into the DenialReason so the gate's 403 body includes the session fields.\n if (response.status === 401) {\n try {\n const errData = (await response.clone().json()) as {\n error?: { code?: string };\n session_id?: unknown;\n poll_secret?: unknown;\n verify_url?: unknown;\n poll_url?: unknown;\n next_steps?: unknown;\n agent_memory?: unknown;\n };\n const code = errData?.error?.code;\n if (code === 'token_expired') {\n return {\n kind: 'deny',\n reason: {\n code,\n data: errData as unknown as AgentScoreData,\n ...(typeof errData.verify_url === 'string' ? { verify_url: errData.verify_url } : {}),\n ...(typeof errData.session_id === 'string' ? { session_id: errData.session_id } : {}),\n ...(typeof errData.poll_secret === 'string' ? { poll_secret: errData.poll_secret } : {}),\n ...(typeof errData.poll_url === 'string' ? { poll_url: errData.poll_url } : {}),\n ...(errData.next_steps ? { agent_instructions: JSON.stringify(errData.next_steps) } : {}),\n ...(errData.agent_memory ? { agent_memory: errData.agent_memory as AgentMemoryHint } : {}),\n },\n };\n }\n // The API returns this when the operator_token doesn't exist at all (typo,\n // never minted, fabricated). Distinct from token_expired — no auto-session\n // is issued because the agent may have other valid tokens to try first.\n // Without this branch the gate would fall through to api_error → 503 retry,\n // which loops forever on a permanent state.\n if (code === 'invalid_credential') {\n return {\n kind: 'deny',\n reason: {\n code: 'invalid_credential',\n agent_instructions: INVALID_CREDENTIAL_INSTRUCTIONS,\n agent_memory: agentMemoryHint,\n },\n };\n }\n // Unknown 401 code — log so we notice if the API adds a new credential-state\n // code without us mapping it. Falls through to api_error below.\n if (code) {\n console.warn(`[gate] /v1/assess returned 401 ${code} — no specific handler, surfacing as api_error.`);\n }\n } catch (err) {\n // Body wasn't the expected JSON shape. Don't crash the request, but DO log —\n // a silent swallow here used to mask /v1/sessions schema drift for hours.\n console.warn('[gate] /v1/assess 401 body parse failed:', err instanceof Error ? err.message : err);\n }\n }\n\n // 4xx with a structured error body that ISN'T 401/402: log it so operators see\n // misclassifications instead of opaque 503 retries. Most common cause: a merchant\n // that didn't validate input shape before invoking the gate (invalid_address,\n // invalid_identity). We still fall through to api_error so behavior is unchanged\n // for callers — just visible now.\n if (response.status >= 400 && response.status < 500 && response.status !== 402) {\n try {\n const errData = (await response.clone().json()) as { error?: { code?: string; message?: string } };\n const code = errData?.error?.code;\n if (code && code !== 'token_expired' && code !== 'invalid_credential') {\n console.warn(\n `[gate] /v1/assess returned ${response.status} ${code} — surfacing as api_error. ` +\n 'Validate input shape before invoking the gate to avoid this.',\n );\n }\n } catch {\n // Body wasn't JSON or didn't have the expected shape — silent fall-through.\n }\n }\n\n if (!response.ok) {\n throw new Error(`AgentScore API returned ${response.status}`);\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n const decision = data.decision as string | null | undefined;\n const decisionReasons = (data.decision_reasons as string[]) ?? [];\n const allow = decision === 'allow' || decision == null;\n\n cache.set(cacheKey, { allow, decision: decision ?? undefined, reasons: decisionReasons, raw: data });\n\n if (allow) {\n return { kind: 'allow', data: data as unknown as AgentScoreData };\n }\n\n return {\n kind: 'deny',\n reason: {\n code: 'wallet_not_trusted',\n decision: decision ?? undefined,\n reasons: decisionReasons,\n verify_url: data.verify_url as string | undefined,\n data: data as unknown as AgentScoreData,\n },\n };\n } catch (err) {\n // Network failure, AbortSignal timeout, JSON parse error on a 2xx, or the\n // explicit `throw new Error(...)` for an unhandled non-ok status. Log so ops\n // can distinguish \"API down\" from \"merchant config wrong\" — without this,\n // every transient blip looked identical to a misconfigured base URL.\n console.warn('[gate] /v1/assess call failed — surfacing as api_error:', err instanceof Error ? err.message : err);\n if (failOpen) return { kind: 'allow' };\n return { kind: 'deny', reason: { code: 'api_error' } };\n }\n }\n\n async function captureWallet(options: CaptureWalletOptions): Promise<void> {\n try {\n const body: Record<string, unknown> = {\n operator_token: options.operatorToken,\n wallet_address: options.walletAddress,\n network: options.network,\n };\n if (options.idempotencyKey) body.idempotency_key = options.idempotencyKey;\n await fetch(`${baseUrl}/v1/credentials/wallets`, {\n method: 'POST',\n headers: {\n 'X-API-Key': apiKey,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': userAgentHeader,\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(API_TIMEOUT_MS),\n });\n } catch (err) {\n // Fire-and-forget: don't throw. Log so a persistent capture outage is visible\n // to merchant ops — otherwise wallet↔operator linkage silently stops.\n console.warn('[agentscore-commerce] captureWallet failed:', err instanceof Error ? err.message : err);\n }\n }\n\n /**\n * Resolve a wallet to its operator id via /v1/assess.\n *\n * Returns:\n * - `{ ok: true, operator: <id> }` — wallet is linked to that operator\n * - `{ ok: true, operator: null }` — wallet is valid but not linked to any operator\n * - `{ ok: false }` — the API call failed (network, timeout, non-2xx). Distinguishable so\n * callers can emit `api_error` instead of falsely asserting \"no operator linked\".\n *\n * Checks the main evaluate() cache before making a fresh call — if the gate already\n * resolved this wallet during identity evaluation, we have the resolved_operator already.\n */\n async function resolveWalletToOperator(\n walletAddress: string,\n ): Promise<{ ok: true; operator: string | null; linkedWallets: string[] } | { ok: false }> {\n // Network-aware: lowercases EVM, preserves Solana base58 case. The DB stores both\n // formats verbatim in operator_credential_wallets.wallet_address; lowercasing a\n // Solana address would never match.\n const wallet = normalizeAddress(walletAddress);\n\n // Cache lookup — first the plain cache (populated by evaluate() for identity-headered wallets).\n // Saves a second /v1/assess call when the gate already looked up this wallet.\n const extractFromCached = (raw: Record<string, unknown>): { operator: string | null; linkedWallets: string[] } => {\n const op = raw.resolved_operator;\n const links = raw.linked_wallets;\n return {\n operator: typeof op === 'string' ? op : null,\n linkedWallets: Array.isArray(links) ? (links as unknown[]).filter((w): w is string => typeof w === 'string') : [],\n };\n };\n\n const plainCached = cache.get(wallet);\n if (plainCached?.raw) {\n return { ok: true, ...extractFromCached(plainCached.raw as Record<string, unknown>) };\n }\n const resolveCached = cache.get(`resolve:${wallet}`);\n if (resolveCached?.raw) {\n return { ok: true, ...extractFromCached(resolveCached.raw as Record<string, unknown>) };\n }\n\n try {\n const response = await fetch(`${baseUrl}/v1/assess`, {\n method: 'POST',\n headers: {\n 'X-API-Key': apiKey,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': userAgentHeader,\n },\n body: JSON.stringify({ address: walletAddress }),\n signal: AbortSignal.timeout(API_TIMEOUT_MS),\n });\n if (!response.ok) return { ok: false };\n const data = (await response.json()) as Record<string, unknown>;\n cache.set(`resolve:${wallet}`, { allow: true, raw: data });\n return { ok: true, ...extractFromCached(data) };\n } catch (err) {\n // Network/timeout/parse on the wallet→operator resolve path. Caller maps\n // `{ok:false}` to `wallet_signer_mismatch.kind === 'api_error'`, which already\n // surfaces as 503 — but log here too so multi-wallet match failures aren't\n // silently indistinguishable from \"operator simply has no linked wallet\".\n console.warn('[gate] resolveWalletToOperator failed — returning { ok:false }:', err instanceof Error ? err.message : err);\n return { ok: false };\n }\n }\n\n function reportSignerEvent(kind: 'pass' | 'wallet_signer_mismatch' | 'wallet_auth_requires_wallet_signing' | 'api_error'): void {\n // Fire-and-forget: surfaces mismatch-catch rate + api_error SLO on the dashboard.\n // Never blocks, awaits, or throws — telemetry failure must not affect the gate's decision.\n try {\n const pending = fetch(`${baseUrl}/v1/telemetry/signer-match`, {\n method: 'POST',\n headers: {\n 'X-API-Key': apiKey,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': userAgentHeader,\n },\n body: JSON.stringify({ kind }),\n signal: AbortSignal.timeout(API_TIMEOUT_MS),\n });\n if (pending && typeof pending.catch === 'function') {\n pending.catch((err) => {\n console.warn('[agentscore-commerce] signer-match telemetry failed:', err instanceof Error ? err.message : err);\n });\n }\n } catch {\n // Thrown synchronously (e.g., fetch unavailable in test harness) — swallow silently.\n }\n }\n\n async function verifyWalletSignerMatch(\n options: VerifyWalletSignerMatchOptions,\n ): Promise<VerifyWalletSignerResult> {\n const { claimedWallet, signer } = options;\n\n if (!signer) {\n reportSignerEvent('wallet_auth_requires_wallet_signing');\n return {\n kind: 'wallet_auth_requires_wallet_signing',\n claimedWallet,\n agentInstructions: WALLET_AUTH_REQUIRES_WALLET_SIGNING_INSTRUCTIONS,\n };\n }\n\n // Network-aware normalization: lowercase EVM, preserve Solana base58. The byte-equal\n // short-circuit and downstream cache-key derivation MUST match how the DB stores\n // wallets; lowercasing Solana would corrupt both.\n const claimedNorm = normalizeAddress(claimedWallet);\n const signerNorm = normalizeAddress(signer);\n\n // Byte-equal short-circuit — no API lookup; same wallet ≡ same operator by definition.\n if (claimedNorm === signerNorm) {\n reportSignerEvent('pass');\n return { kind: 'pass', claimedOperator: null, signerOperator: null };\n }\n\n const [claimedResolve, signerResolve] = await Promise.all([\n resolveWalletToOperator(claimedNorm),\n resolveWalletToOperator(signerNorm),\n ]);\n\n // Transient API failure on either resolve → emit api_error. Caller should retry or\n // surface 503 rather than falsely reject a legitimate user on a network flake.\n if (!claimedResolve.ok || !signerResolve.ok) {\n reportSignerEvent('api_error');\n return { kind: 'api_error', claimedWallet: claimedNorm };\n }\n\n const claimedOperator = claimedResolve.operator;\n const signerOperator = signerResolve.operator;\n\n if (claimedOperator && signerOperator && claimedOperator === signerOperator) {\n reportSignerEvent('pass');\n return { kind: 'pass', claimedOperator, signerOperator };\n }\n\n reportSignerEvent('wallet_signer_mismatch');\n return {\n kind: 'wallet_signer_mismatch',\n claimedOperator,\n actualSignerOperator: signerOperator,\n expectedSigner: claimedNorm,\n actualSigner: signerNorm,\n // Populated from /v1/assess.linked_wallets on the claimed wallet — the full set of\n // wallets the agent CAN sign with to satisfy the claim (same-operator rule).\n linkedWallets: claimedResolve.linkedWallets,\n agentInstructions: WALLET_SIGNER_MISMATCH_INSTRUCTIONS,\n };\n }\n\n return { evaluate, captureWallet, verifyWalletSignerMatch };\n}\n"],"mappings":";AASA,IAAM,mBAAmB;AAKlB,IAAM,kBAAkB,CAAC,YAC9B,iBAAiB,KAAK,OAAO,KAAK,CAAC,QAAQ,WAAW,IAAI;AAKrD,IAAM,mBAAmB,CAAC,YAA4B;AAC3D,MAAI,gBAAgB,OAAO,GAAG;AAAE,WAAO;AAAA,EAAS;AAChD,SAAO,QAAQ,YAAY;AAC7B;;;ACvBO,IAAM,WAAN,MAAkB;AAAA,EAIvB,YAAoB,cAAsB,UAAU,KAAO;AAAvC;AAClB,SAAK,UAAU;AAAA,EACjB;AAAA,EAFoB;AAAA,EAHZ,QAAQ,oBAAI,IAA6C;AAAA,EACzD;AAAA,EAMR,IAAI,KAA4B;AAC9B,UAAM,QAAQ,KAAK,MAAM,IAAI,GAAG;AAChC,QAAI,CAAC,MAAO,QAAO;AACnB,QAAI,KAAK,IAAI,IAAI,MAAM,WAAW;AAChC,WAAK,MAAM,OAAO,GAAG;AACrB,aAAO;AAAA,IACT;AACA,WAAO,MAAM;AAAA,EACf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