@valiron/sdk 1.4.0 → 2.1.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 (49) hide show
  1. package/README.md +11 -148
  2. package/bin/valiron-card.mjs +211 -0
  3. package/dist/card.d.ts +565 -0
  4. package/dist/card.js +722 -0
  5. package/dist/clients.d.ts +6 -6
  6. package/dist/clients.js +33 -26
  7. package/dist/edge.d.ts +87 -0
  8. package/dist/edge.js +164 -0
  9. package/dist/edgeGate.d.ts +146 -0
  10. package/dist/edgeGate.js +230 -0
  11. package/dist/edgeGateVerify.d.ts +146 -0
  12. package/dist/edgeGateVerify.js +243 -0
  13. package/dist/identity.d.ts +6 -0
  14. package/dist/identity.js +6 -1
  15. package/dist/identityMiddleware.d.ts +8 -0
  16. package/dist/identityMiddleware.js +12 -4
  17. package/dist/index.d.ts +5 -10
  18. package/dist/index.js +4 -10
  19. package/dist/middleware.d.ts +20 -9
  20. package/dist/middleware.js +47 -19
  21. package/dist/operatorSdk.d.ts +11 -2
  22. package/dist/operatorSdk.js +13 -7
  23. package/dist/types.d.ts +14 -4
  24. package/docs/AGENT-READY-APIS.md +3 -181
  25. package/docs/API-REFERENCE.md +94 -546
  26. package/docs/CHAINS.md +3 -3
  27. package/docs/CLOUDFLARE-GATE-MIDDLEWARE.md +196 -0
  28. package/docs/CRAWLER-PROTECTION.md +545 -0
  29. package/docs/DASHBOARD.md +55 -23
  30. package/docs/E2E-MIDDLEWARE-INTEGRATION.md +19 -13
  31. package/docs/ERRORS.md +29 -19
  32. package/docs/IDENTITY.md +16 -14
  33. package/docs/PROVIDER-IDENTITY.md +15 -5
  34. package/docs/QUICKSTART.md +40 -24
  35. package/docs/README.md +21 -4
  36. package/docs/SANDBOX.md +7 -1
  37. package/docs/SDK-REFERENCE.md +115 -52
  38. package/docs/SECURITY-UPGRADE-2026-10-31.md +98 -0
  39. package/docs/TRUST-MODEL.md +14 -11
  40. package/docs/llms.txt +70 -302
  41. package/examples/cloudflare-gate-worker/README.md +198 -0
  42. package/examples/cloudflare-gate-worker/package.json +20 -0
  43. package/examples/cloudflare-gate-worker/worker.ts +309 -0
  44. package/examples/cloudflare-gate-worker/wrangler.toml +46 -0
  45. package/examples/cloudflare-worker/package.json +8 -0
  46. package/examples/cloudflare-worker/worker.ts +495 -0
  47. package/examples/cloudflare-worker/wrangler.toml +57 -0
  48. package/package.json +35 -5
  49. package/docs/MCP.md +0 -50
package/dist/clients.d.ts CHANGED
@@ -13,6 +13,7 @@ export declare class ValironClient {
13
13
  private timeoutConfigured;
14
14
  private debug;
15
15
  private telemetry;
16
+ private requestSigner?;
16
17
  constructor(config?: ValironConfig);
17
18
  /** Resolve the effective chain: per-call override > constructor default > undefined (server default). */
18
19
  private resolveChain;
@@ -34,7 +35,7 @@ export declare class ValironClient {
34
35
  * `GET /operator/wallet/:wallet`
35
36
  */
36
37
  getWalletProfile(wallet: string, options?: CallOptions): Promise<WalletProfile>;
37
- /** Get an explainable wallet-history risk assessment. Pro plans only. */
38
+ /** Get an explainable wallet-history risk assessment. Available on Free with an operator API key. */
38
39
  getWalletRisk(wallet: string, options?: CallOptions): Promise<WalletRiskSnapshot>;
39
40
  /**
40
41
  * Resolve a wallet address to an ERC-8004 agent ID.
@@ -131,6 +132,7 @@ export declare class ValironClient {
131
132
  merkle_root: string;
132
133
  nullifier_hash: string;
133
134
  verification_level: "orb" | "device" | "phone";
135
+ idkit_result?: unknown;
134
136
  }, options?: CallOptions): Promise<{
135
137
  ok: boolean;
136
138
  agentId: string;
@@ -160,11 +162,9 @@ export declare class ValironClient {
160
162
  */
161
163
  createSelfSession(agentId: string, request?: SelfSessionRequest, options?: CallOptions): Promise<SelfSessionResponse>;
162
164
  /**
163
- * Store a Self verified eligible-human proof and optional Self Agent ID link.
164
- * Production integrations should prefer `createSelfSession()` plus the
165
- * signed Self webhook.
166
- *
167
- * `POST /operator/self/verify/:agentId`
165
+ * @deprecated Not supported for hosted customer integrations. Use
166
+ * `createSelfSession()` and `getSelfStatus()`. Retained for compatibility;
167
+ * scheduled for removal in the next major SDK release.
168
168
  */
169
169
  verifySelf(agentId: string, proof: SelfProofPayload, options?: CallOptions): Promise<{
170
170
  ok: boolean;
package/dist/clients.js CHANGED
@@ -14,6 +14,7 @@ class ValironClient {
14
14
  this.endpoint =
15
15
  config.endpoint || "https://valiron-edge-proxy.onrender.com";
16
16
  this.apiKey = config.apiKey;
17
+ this.requestSigner = config.signRequest;
17
18
  this.defaultChain = config.chain;
18
19
  this.timeoutConfigured = config.timeout !== undefined;
19
20
  this.timeout = config.timeout ?? 10000;
@@ -38,7 +39,7 @@ class ValironClient {
38
39
  const query = options?.trustSignals?.length
39
40
  ? `?trustSignals=${encodeURIComponent([...options.trustSignals].sort().join(","))}`
40
41
  : "";
41
- const profile = await this.get(`/operator/agent/${agentId}${query}`, chain);
42
+ const profile = await this.get(`/operator/agent/${safeIdentifier(agentId)}${query}`, chain);
42
43
  // Strip internal fields that the API returns but SDK consumers should not see
43
44
  if (profile?.localReputation) {
44
45
  delete profile.localReputation.metrics;
@@ -73,7 +74,7 @@ class ValironClient {
73
74
  * `GET /operator/wallet/:wallet`
74
75
  */
75
76
  async getWalletProfile(wallet, options) {
76
- const profile = await this.get(`/operator/wallet/${wallet}`, this.resolveChain(options));
77
+ const profile = await this.get(`/operator/wallet/${safeIdentifier(wallet)}`, this.resolveChain(options));
77
78
  // Strip internal fields from local reputation
78
79
  if (profile?.localReputation) {
79
80
  delete profile.localReputation.metrics;
@@ -81,9 +82,9 @@ class ValironClient {
81
82
  }
82
83
  return profile;
83
84
  }
84
- /** Get an explainable wallet-history risk assessment. Pro plans only. */
85
+ /** Get an explainable wallet-history risk assessment. Available on Free with an operator API key. */
85
86
  async getWalletRisk(wallet, options) {
86
- return this.get(`/operator/wallet-risk/${wallet}`, this.resolveChain(options));
87
+ return this.get(`/operator/wallet-risk/${safeIdentifier(wallet)}`, this.resolveChain(options));
87
88
  }
88
89
  /**
89
90
  * Resolve a wallet address to an ERC-8004 agent ID.
@@ -95,7 +96,7 @@ class ValironClient {
95
96
  * `GET /operator/resolve-wallet/:wallet`
96
97
  */
97
98
  async resolveWallet(wallet, options) {
98
- return this.get(`/operator/resolve-wallet/${wallet}`, this.resolveChain(options));
99
+ return this.get(`/operator/resolve-wallet/${safeIdentifier(wallet)}`, this.resolveChain(options));
99
100
  }
100
101
  /**
101
102
  * Get the latest behavioral snapshot hash for an agent.
@@ -107,7 +108,7 @@ class ValironClient {
107
108
  * `GET /operator/agent/:agentId/snapshot`
108
109
  */
109
110
  async getAgentSnapshot(agentId, options) {
110
- return this.get(`/operator/agent/${agentId}/snapshot`, this.resolveChain(options));
111
+ return this.get(`/operator/agent/${safeIdentifier(agentId)}/snapshot`, this.resolveChain(options));
111
112
  }
112
113
  /**
113
114
  * Trigger real sandbox testing for an agent.
@@ -119,7 +120,7 @@ class ValironClient {
119
120
  * `POST /operator/trigger-sandbox/:agentId`
120
121
  */
121
122
  async triggerSandboxTest(agentId, options) {
122
- const result = await this.post(`/operator/trigger-sandbox/${agentId}`, undefined, this.resolveChain(options));
123
+ const result = await this.post(`/operator/trigger-sandbox/${safeIdentifier(agentId)}`, undefined, this.resolveChain(options));
123
124
  // Strip internal behavioral metrics and execution details from sandbox response
124
125
  delete result.metrics;
125
126
  delete result.testSummary;
@@ -137,7 +138,7 @@ class ValironClient {
137
138
  * `POST /operator/trigger-sandbox-key/:agentAddress`
138
139
  */
139
140
  async triggerKeyAgentSandbox(agentAddress) {
140
- const result = await this.post(`/operator/trigger-sandbox-key/${agentAddress}`);
141
+ const result = await this.post(`/operator/trigger-sandbox-key/${safeIdentifier(agentAddress)}`);
141
142
  // Strip internal behavioral metrics and execution details
142
143
  delete result.metrics;
143
144
  delete result.testSummary;
@@ -155,7 +156,7 @@ class ValironClient {
155
156
  */
156
157
  async gate(agentId, options) {
157
158
  const { chain, ...body } = options || {};
158
- const result = await this.post(`/operator/gate/${agentId}`, Object.keys(body).length > 0 ? body : undefined, chain ?? this.defaultChain);
159
+ const result = await this.post(`/operator/gate/${safeIdentifier(agentId)}`, Object.keys(body).length > 0 ? body : undefined, chain ?? this.defaultChain);
159
160
  // Strip detailed scoring reasons — SDK consumers get allow/deny + tier only
160
161
  delete result.reasons;
161
162
  return result;
@@ -173,7 +174,7 @@ class ValironClient {
173
174
  */
174
175
  async proxy(agentId, request, options) {
175
176
  const chain = this.resolveChain(options);
176
- return this.post(`/proxy/${agentId}`, request, chain);
177
+ return this.post(`/proxy/${safeIdentifier(agentId)}`, request, chain);
177
178
  }
178
179
  // ─── Key-Based Agent Identity (Web2 Agents) ─────────────────────────────
179
180
  /**
@@ -182,7 +183,7 @@ class ValironClient {
182
183
  * `POST /operator/key/:agentAddress/challenge`
183
184
  */
184
185
  async getKeyAgentChallenge(agentAddress) {
185
- return this.post(`/operator/key/${agentAddress}/challenge`);
186
+ return this.post(`/operator/key/${safeIdentifier(agentAddress)}/challenge`);
186
187
  }
187
188
  /**
188
189
  * Verify a key-based agent via challenge-response signature.
@@ -198,10 +199,10 @@ class ValironClient {
198
199
  * `GET /operator/key/:agentAddress`
199
200
  */
200
201
  async getKeyAgentProfile(agentAddress) {
201
- return this.get(`/operator/key/${agentAddress}`);
202
+ return this.get(`/operator/key/${safeIdentifier(agentAddress)}`);
202
203
  }
203
204
  async getKeyAgentIcebreaker(agentAddress) {
204
- return this.get(`/operator/key/${agentAddress}/icebreaker`);
205
+ return this.get(`/operator/key/${safeIdentifier(agentAddress)}/icebreaker`);
205
206
  }
206
207
  // ─── World ID (Proof-of-Personhood) ───────────────────────────────────
207
208
  /**
@@ -210,7 +211,7 @@ class ValironClient {
210
211
  * `POST /operator/world-id/verify/:agentId`
211
212
  */
212
213
  async verifyWorldId(agentId, proof, options) {
213
- return this.post(`/operator/world-id/verify/${agentId}`, proof, this.resolveChain(options));
214
+ return this.post(`/operator/world-id/verify/${safeIdentifier(agentId)}`, proof, this.resolveChain(options));
214
215
  }
215
216
  /**
216
217
  * Get World ID verification status for an agent.
@@ -218,7 +219,7 @@ class ValironClient {
218
219
  * `GET /operator/world-id/status/:agentId`
219
220
  */
220
221
  async getWorldIdStatus(agentId, options) {
221
- return this.get(`/operator/world-id/status/${agentId}`, this.resolveChain(options));
222
+ return this.get(`/operator/world-id/status/${safeIdentifier(agentId)}`, this.resolveChain(options));
222
223
  }
223
224
  /**
224
225
  * Get enriched human-agent trust profile (World ID + Icebreaker).
@@ -226,7 +227,7 @@ class ValironClient {
226
227
  * `GET /operator/world-id/profile/:agentId`
227
228
  */
228
229
  async getWorldIdProfile(agentId, options) {
229
- return this.get(`/operator/world-id/profile/${agentId}`, this.resolveChain(options));
230
+ return this.get(`/operator/world-id/profile/${safeIdentifier(agentId)}`, this.resolveChain(options));
230
231
  }
231
232
  // ─── Self (Eligible Human + Agent ID) ─────────────────────────────────
232
233
  /**
@@ -235,17 +236,15 @@ class ValironClient {
235
236
  * `POST /operator/self/session/:agentId`
236
237
  */
237
238
  async createSelfSession(agentId, request = {}, options) {
238
- return this.post(`/operator/self/session/${agentId}`, request, this.resolveChain(options));
239
+ return this.post(`/operator/self/session/${safeIdentifier(agentId)}`, request, this.resolveChain(options));
239
240
  }
240
241
  /**
241
- * Store a Self verified eligible-human proof and optional Self Agent ID link.
242
- * Production integrations should prefer `createSelfSession()` plus the
243
- * signed Self webhook.
244
- *
245
- * `POST /operator/self/verify/:agentId`
242
+ * @deprecated Not supported for hosted customer integrations. Use
243
+ * `createSelfSession()` and `getSelfStatus()`. Retained for compatibility;
244
+ * scheduled for removal in the next major SDK release.
246
245
  */
247
246
  async verifySelf(agentId, proof, options) {
248
- return this.post(`/operator/self/verify/${agentId}`, proof, this.resolveChain(options));
247
+ return this.post(`/operator/self/verify/${safeIdentifier(agentId)}`, proof, this.resolveChain(options));
249
248
  }
250
249
  /**
251
250
  * Get Self verification status for an agent.
@@ -253,7 +252,7 @@ class ValironClient {
253
252
  * `GET /operator/self/status/:agentId`
254
253
  */
255
254
  async getSelfStatus(agentId, options) {
256
- return this.get(`/operator/self/status/${agentId}`, this.resolveChain(options));
255
+ return this.get(`/operator/self/status/${safeIdentifier(agentId)}`, this.resolveChain(options));
257
256
  }
258
257
  /**
259
258
  * Get Self eligible-human / Agent ID profile for an agent.
@@ -261,7 +260,7 @@ class ValironClient {
261
260
  * `GET /operator/self/profile/:agentId`
262
261
  */
263
262
  async getSelfProfile(agentId, options) {
264
- return this.get(`/operator/self/profile/${agentId}`, this.resolveChain(options));
263
+ return this.get(`/operator/self/profile/${safeIdentifier(agentId)}`, this.resolveChain(options));
265
264
  }
266
265
  /** Verify a provider-backed identity proof and evaluate the supplied policy. */
267
266
  async verifyAgentIdentity(proof = {}, policy) {
@@ -321,6 +320,7 @@ class ValironClient {
321
320
  method: "GET",
322
321
  headers: this.buildHeaders(),
323
322
  signal: controller.signal,
323
+ redirect: "manual",
324
324
  });
325
325
  responseStatus = response.status;
326
326
  const methodName = this.extractMethodName(path);
@@ -408,13 +408,14 @@ class ValironClient {
408
408
  if (this.debug) {
409
409
  console.log(`[Valiron SDK] POST ${url.toString()}`, body);
410
410
  }
411
+ const signedHeaders = this.requestSigner ? await this.requestSigner({ method: "POST", url: url.toString(), body: body == null ? "" : JSON.stringify(body), chain }) : {};
411
412
  const controller = new AbortController();
412
413
  const timeoutMs = this.getTimeoutForPath(path);
413
414
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
414
415
  const start = performance.now();
415
416
  let responseStatus;
416
417
  try {
417
- const headers = this.buildHeaders();
418
+ const headers = { ...this.buildHeaders(), ...signedHeaders };
418
419
  const hasBody = body !== undefined && body !== null;
419
420
  if (!hasBody)
420
421
  delete headers["Content-Type"];
@@ -423,6 +424,7 @@ class ValironClient {
423
424
  headers,
424
425
  body: hasBody ? JSON.stringify(body) : undefined,
425
426
  signal: controller.signal,
427
+ redirect: "manual",
426
428
  });
427
429
  responseStatus = response.status;
428
430
  const methodName = this.extractMethodName(path);
@@ -551,3 +553,8 @@ class ValironClient {
551
553
  }
552
554
  }
553
555
  exports.ValironClient = ValironClient;
556
+ function safeIdentifier(value) {
557
+ if (typeof value !== "string" || !/^[A-Za-z0-9:_-]{1,256}$/.test(value) || value === "." || value === "..")
558
+ throw new types_1.ValironError("Invalid identifier", "INVALID_IDENTIFIER");
559
+ return encodeURIComponent(value);
560
+ }
package/dist/edge.d.ts ADDED
@@ -0,0 +1,87 @@
1
+ /**
2
+ * @valiron/sdk/edge - WebCrypto-only Pass verification for edge runtimes
3
+ * (Cloudflare Workers, Deno, browsers). No node:crypto, no Buffer.
4
+ *
5
+ * What this verifies, and what it cannot:
6
+ * - verifyPassToken checks Valiron's signature on a signed identity token
7
+ * (POST /card/v1/identity-tokens with format "jws") against Valiron's
8
+ * published JWKS, plus expiry and audience.
9
+ * - verifyPassProof checks the agent's per-request proof against the
10
+ * delegation key Valiron attested inside that token, bound to the exact
11
+ * method, URL and body.
12
+ * - An edge verifier CANNOT see revocations or consume proof nonces. A revoked
13
+ * delegation's tokens keep verifying until they expire (mint TTL is 300s),
14
+ * and a captured proof is replayable at the edge inside its 60-second
15
+ * window unless the deployment adds a shared replay store (the Cloudflare
16
+ * template ships a Durable Object for this). Merchant endpoints that need
17
+ * immediate revocation must keep the origin recognize path; report edge
18
+ * outcomes to POST /operator/card/v1/agent-visits/local, which re-verifies
19
+ * everything centrally and consumes the proof nonce.
20
+ */
21
+ export declare class PassEdgeError extends Error {
22
+ code: string;
23
+ constructor(code: string);
24
+ }
25
+ export interface PassTokenClaims {
26
+ v: 1;
27
+ iss: string;
28
+ aud: string;
29
+ sub: string;
30
+ delegation_id: string;
31
+ agent_name: string;
32
+ merchant_id: string;
33
+ environment: "test" | "live";
34
+ dpk: {
35
+ kty: "OKP";
36
+ crv: "Ed25519";
37
+ x: string;
38
+ };
39
+ iat: number;
40
+ exp: number;
41
+ jti: string;
42
+ }
43
+ export interface PassProofClaims {
44
+ v: 1;
45
+ aud: string;
46
+ environment: string;
47
+ delegation_id: string;
48
+ token_hash: string;
49
+ method: string;
50
+ url: string;
51
+ body_digest: string;
52
+ iat: number;
53
+ exp: number;
54
+ jti: string;
55
+ }
56
+ export interface PassJwks {
57
+ keys: {
58
+ kty: "OKP";
59
+ crv: "Ed25519";
60
+ x: string;
61
+ kid: string;
62
+ use?: string;
63
+ alg?: string;
64
+ }[];
65
+ }
66
+ /** Fetches Valiron's Pass JWKS. Long-lived isolates should cache briefly (the
67
+ * endpoint serves Cache-Control: max-age=60) and retry the fetch once on an
68
+ * unknown kid before rejecting, to ride key rotation. */
69
+ export declare function fetchPassJwks(jwksUrl: string, fetcher?: typeof fetch): Promise<PassJwks>;
70
+ /** Verifies a Valiron-signed Pass identity token: signature against the JWKS
71
+ * key named by `kid`, plus expiry, not-before and exact audience match. */
72
+ export declare function verifyPassToken(token: string, options: {
73
+ jwks: PassJwks;
74
+ audience: string;
75
+ issuer?: string;
76
+ now?: number;
77
+ }): Promise<PassTokenClaims>;
78
+ /** Verifies the per-request proof against the delegation key inside an
79
+ * already-verified token, bound to the exact method, URL and body bytes the
80
+ * merchant received. `url` must be the public URL string exactly as observed
81
+ * and `body` the exact request body bytes (empty for bodyless methods). */
82
+ export declare function verifyPassProof(token: string, tokenClaims: PassTokenClaims, proof: string, request: {
83
+ method: string;
84
+ url: string;
85
+ body?: Uint8Array | string;
86
+ now?: number;
87
+ }): Promise<PassProofClaims>;
package/dist/edge.js ADDED
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+ /**
3
+ * @valiron/sdk/edge - WebCrypto-only Pass verification for edge runtimes
4
+ * (Cloudflare Workers, Deno, browsers). No node:crypto, no Buffer.
5
+ *
6
+ * What this verifies, and what it cannot:
7
+ * - verifyPassToken checks Valiron's signature on a signed identity token
8
+ * (POST /card/v1/identity-tokens with format "jws") against Valiron's
9
+ * published JWKS, plus expiry and audience.
10
+ * - verifyPassProof checks the agent's per-request proof against the
11
+ * delegation key Valiron attested inside that token, bound to the exact
12
+ * method, URL and body.
13
+ * - An edge verifier CANNOT see revocations or consume proof nonces. A revoked
14
+ * delegation's tokens keep verifying until they expire (mint TTL is 300s),
15
+ * and a captured proof is replayable at the edge inside its 60-second
16
+ * window unless the deployment adds a shared replay store (the Cloudflare
17
+ * template ships a Durable Object for this). Merchant endpoints that need
18
+ * immediate revocation must keep the origin recognize path; report edge
19
+ * outcomes to POST /operator/card/v1/agent-visits/local, which re-verifies
20
+ * everything centrally and consumes the proof nonce.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.PassEdgeError = void 0;
24
+ exports.fetchPassJwks = fetchPassJwks;
25
+ exports.verifyPassToken = verifyPassToken;
26
+ exports.verifyPassProof = verifyPassProof;
27
+ class PassEdgeError extends Error {
28
+ constructor(code) {
29
+ super(code.replace(/_/g, " "));
30
+ this.code = code;
31
+ this.name = "PassEdgeError";
32
+ }
33
+ }
34
+ exports.PassEdgeError = PassEdgeError;
35
+ function b64urlToBytes(value) {
36
+ if (!/^[A-Za-z0-9_-]*$/.test(value))
37
+ throw new PassEdgeError("malformed_token");
38
+ const b64 = value.replace(/-/g, "+").replace(/_/g, "/");
39
+ const padded = b64 + "=".repeat((4 - (b64.length % 4)) % 4);
40
+ let binary = "";
41
+ for (let i = 0; i < padded.length; i += 4) {
42
+ const c0 = B64.indexOf(padded[i]), c1 = B64.indexOf(padded[i + 1]);
43
+ const c2 = padded[i + 2] === "=" ? 64 : B64.indexOf(padded[i + 2]);
44
+ const c3 = padded[i + 3] === "=" ? 64 : B64.indexOf(padded[i + 3]);
45
+ if (c0 < 0 || c1 < 0 || c2 < 0 || c3 < 0)
46
+ throw new PassEdgeError("malformed_token");
47
+ const acc = (c0 << 18) | (c1 << 12) | ((c2 & 63) << 6) | (c3 & 63);
48
+ binary += String.fromCharCode((acc >> 16) & 255);
49
+ if (c2 !== 64)
50
+ binary += String.fromCharCode((acc >> 8) & 255);
51
+ if (c3 !== 64)
52
+ binary += String.fromCharCode(acc & 255);
53
+ }
54
+ const out = new Uint8Array(binary.length);
55
+ for (let i = 0; i < binary.length; i++)
56
+ out[i] = binary.charCodeAt(i);
57
+ return out;
58
+ }
59
+ const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
60
+ const textBytes = (value) => new TextEncoder().encode(value);
61
+ const textFrom = (bytes) => new TextDecoder().decode(bytes);
62
+ async function sha256Hex(value) {
63
+ const digest = await crypto.subtle.digest("SHA-256", (typeof value === "string" ? textBytes(value) : value));
64
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
65
+ }
66
+ function parseJsonPart(parts, index, code) {
67
+ try {
68
+ return JSON.parse(textFrom(b64urlToBytes(parts[index])));
69
+ }
70
+ catch {
71
+ throw new PassEdgeError(code);
72
+ }
73
+ }
74
+ async function importEd25519(jwk) {
75
+ if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || typeof jwk.x !== "string")
76
+ throw new PassEdgeError("invalid_public_key");
77
+ try {
78
+ return await crypto.subtle.importKey("jwk", { kty: "OKP", crv: "Ed25519", x: jwk.x }, { name: "Ed25519" }, false, ["verify"]);
79
+ }
80
+ catch {
81
+ throw new PassEdgeError("invalid_public_key");
82
+ }
83
+ }
84
+ /** Fetches Valiron's Pass JWKS. Long-lived isolates should cache briefly (the
85
+ * endpoint serves Cache-Control: max-age=60) and retry the fetch once on an
86
+ * unknown kid before rejecting, to ride key rotation. */
87
+ async function fetchPassJwks(jwksUrl, fetcher = fetch) {
88
+ const url = new URL(jwksUrl);
89
+ if (url.protocol !== "https:" && !["localhost", "127.0.0.1"].includes(url.hostname))
90
+ throw new PassEdgeError("jwks_https_required");
91
+ const response = await fetcher(url.href, { headers: { accept: "application/json" } });
92
+ if (!response.ok)
93
+ throw new PassEdgeError("jwks_unavailable");
94
+ const body = (await response.json());
95
+ if (!body || !Array.isArray(body.keys) || !body.keys.length || body.keys.length > 10)
96
+ throw new PassEdgeError("jwks_invalid");
97
+ for (const key of body.keys)
98
+ if (key.kty !== "OKP" || key.crv !== "Ed25519" || typeof key.kid !== "string")
99
+ throw new PassEdgeError("jwks_invalid");
100
+ return body;
101
+ }
102
+ /** Verifies a Valiron-signed Pass identity token: signature against the JWKS
103
+ * key named by `kid`, plus expiry, not-before and exact audience match. */
104
+ async function verifyPassToken(token, options) {
105
+ const parts = token.split(".");
106
+ if (parts.length !== 3)
107
+ throw new PassEdgeError("malformed_token");
108
+ const header = parseJsonPart(parts, 0, "malformed_token");
109
+ if (header.alg !== "EdDSA" || typeof header.kid !== "string")
110
+ throw new PassEdgeError("malformed_token");
111
+ const jwk = options.jwks.keys.find((key) => key.kid === header.kid);
112
+ if (!jwk)
113
+ throw new PassEdgeError("unknown_key");
114
+ const key = await importEd25519(jwk);
115
+ const ok = await crypto.subtle.verify({ name: "Ed25519" }, key, b64urlToBytes(parts[2]), textBytes(`${parts[0]}.${parts[1]}`));
116
+ if (!ok)
117
+ throw new PassEdgeError("invalid_signature");
118
+ const claims = parseJsonPart(parts, 1, "malformed_token");
119
+ const now = options.now ?? Math.floor(Date.now() / 1000);
120
+ if (typeof claims.exp !== "number" || claims.exp <= now)
121
+ throw new PassEdgeError("token_expired");
122
+ if (typeof claims.iat !== "number" || claims.iat > now + 60)
123
+ throw new PassEdgeError("token_not_yet_valid");
124
+ if (claims.aud !== new URL(options.audience).origin)
125
+ throw new PassEdgeError("audience_mismatch");
126
+ if (options.issuer !== undefined && claims.iss !== options.issuer)
127
+ throw new PassEdgeError("issuer_mismatch");
128
+ if (claims.v !== 1 || !claims.dpk || !claims.delegation_id || !claims.sub)
129
+ throw new PassEdgeError("malformed_token");
130
+ return claims;
131
+ }
132
+ /** Verifies the per-request proof against the delegation key inside an
133
+ * already-verified token, bound to the exact method, URL and body bytes the
134
+ * merchant received. `url` must be the public URL string exactly as observed
135
+ * and `body` the exact request body bytes (empty for bodyless methods). */
136
+ async function verifyPassProof(token, tokenClaims, proof, request) {
137
+ const parts = proof.split(".");
138
+ if (parts.length !== 3)
139
+ throw new PassEdgeError("invalid_proof");
140
+ const header = parseJsonPart(parts, 0, "invalid_proof");
141
+ if (header.alg !== "EdDSA" || header.typ !== "valiron-pass-proof+jwt" || header.crit)
142
+ throw new PassEdgeError("invalid_proof");
143
+ const claims = parseJsonPart(parts, 1, "invalid_proof");
144
+ const key = await importEd25519(tokenClaims.dpk);
145
+ const ok = await crypto.subtle.verify({ name: "Ed25519" }, key, b64urlToBytes(parts[2]), textBytes(`${parts[0]}.${parts[1]}`));
146
+ if (!ok)
147
+ throw new PassEdgeError("invalid_signature");
148
+ const now = request.now ?? Math.floor(Date.now() / 1000);
149
+ if (!Number.isInteger(claims.iat) || !Number.isInteger(claims.exp) ||
150
+ claims.exp < claims.iat || claims.exp - claims.iat > 60 ||
151
+ claims.exp < now || claims.iat > now + 60)
152
+ throw new PassEdgeError("proof_expired");
153
+ if (claims.v !== 1 || claims.delegation_id !== tokenClaims.delegation_id ||
154
+ claims.aud !== tokenClaims.merchant_id || claims.environment !== tokenClaims.environment ||
155
+ typeof claims.jti !== "string" || claims.jti.length < 16 || claims.jti.length > 128)
156
+ throw new PassEdgeError("invalid_proof");
157
+ if (claims.token_hash !== `sha256:${await sha256Hex(token)}`)
158
+ throw new PassEdgeError("request_binding_mismatch");
159
+ if (claims.method !== request.method.toUpperCase() || claims.url !== request.url)
160
+ throw new PassEdgeError("request_binding_mismatch");
161
+ if (claims.body_digest !== `sha256:${await sha256Hex(request.body ?? "")}`)
162
+ throw new PassEdgeError("request_binding_mismatch");
163
+ return claims;
164
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Valiron trust gate for Cloudflare Workers and other WebCrypto-only edge
3
+ * runtimes: the same general trust gate the Node adapters in ./middleware
4
+ * expose (createValironGate, valironFastifyPlugin, createValironNextMiddleware,
5
+ * valironGateCheck), packaged so it loads inside workerd.
6
+ *
7
+ * Semantics are identical to the Node middleware:
8
+ *
9
+ * - identity headers: `x-agent-id` (on-chain ERC-8004 / Solana) or
10
+ * `x-agent-address` / `x-agent-key-hash` (key-based web2 agents)
11
+ * - a fresh, request-bound ownership proof is required before EVERY
12
+ * decision, including profile-cache hits (`verifyRequest`)
13
+ * - live profile evaluation through the public operator API
14
+ * (getAgentProfile / getKeyAgentProfile), with the same client-side
15
+ * profile cache (default 30s, per isolate at the edge)
16
+ * - allow only when operator routing is `prod` / `prod_throttled` AND the
17
+ * combined score meets `minScore` (default 65)
18
+ * - 401 MISSING_AGENT_IDENTITY, 401 AGENT_OWNERSHIP_REQUIRED, 403
19
+ * TRUST_GATE_DENIED or AGENT_EVALUATION_PENDING, 503 fail-closed on
20
+ * evaluation errors
21
+ *
22
+ * This module imports only ./middleware and ./clients at runtime (both free
23
+ * of Node APIs), so the `@valiron/sdk/edge-gate` subpath loads in Workers.
24
+ * The Pass-specific edge verifier is a separate subpath (`@valiron/sdk/edge`)
25
+ * and is not required for the general trust gate.
26
+ */
27
+ import { ValironClient } from "./clients";
28
+ import type { ValironSDK } from "./index";
29
+ import type { GateResult, TrustSignal } from "./types";
30
+ export { ValironClient };
31
+ export type { TrustSignal } from "./types";
32
+ /**
33
+ * The structural slice of the SDK the edge gate needs. Both `ValironSDK`
34
+ * (Node) and `ValironClient` (edge-safe) satisfy it.
35
+ */
36
+ export type ValironEdgeGateSdk = Pick<ValironSDK, "getAgentProfile" | "getKeyAgentProfile" | "triggerSandboxTest" | "triggerKeyAgentSandbox" | "verifyAgentIdentity" | "emitTelemetry">;
37
+ export interface ValironEdgeGateConfig {
38
+ /** Keep automatic sandbox work alive after the response in edge runtimes. */
39
+ waitUntil?: (pending: Promise<unknown>) => void;
40
+ /** SDK client. Use `new ValironClient({ endpoint, apiKey })` at the edge. */
41
+ sdk: ValironEdgeGateSdk;
42
+ /** Minimum Valiron score to allow (default: 65). */
43
+ minScore?: number;
44
+ /** Customer-selected scoring signals (same meaning as the Node gate). */
45
+ trustSignals?: TrustSignal[];
46
+ /**
47
+ * Profile cache TTL in ms (default: 30000). At the edge the cache lives in
48
+ * the isolate, exactly like the per-process cache in the Node middleware:
49
+ * it is not shared across isolates or colos. Set 0 to disable.
50
+ */
51
+ cacheTtlMs?: number;
52
+ /**
53
+ * REQUIRED for any request to pass: verify a fresh cryptographic proof
54
+ * bound to the claimed identifier, method, full URL and raw body, and
55
+ * reject replayed proofs. Same contract as the Node middleware's
56
+ * verifyRequest. Use createEdgeIdentityVerifier for Valiron's hosted
57
+ * provider-identity verification, or supply your application-owned
58
+ * verifier. When unset (or when it returns false) every identified request
59
+ * is denied 401 AGENT_OWNERSHIP_REQUIRED.
60
+ */
61
+ verifyRequest?: (request: Request, identifier: string) => Promise<boolean>;
62
+ /** Extract the on-chain agent ID. Defaults to the `x-agent-id` header. */
63
+ extractAgentId?: (request: Request) => string | null;
64
+ /** Extract the key-based agent address. Defaults to `x-agent-address` (falls back to `x-agent-key-hash`). */
65
+ extractAgentAddress?: (request: Request) => string | null;
66
+ }
67
+ /** Headers the edge sets on the outbound request after an allow decision. */
68
+ export declare const VALIRON_EDGE_GATE_HEADERS: readonly ["x-valiron-gate-decision", "x-valiron-gate-agent-id", "x-valiron-gate-score", "x-valiron-gate-tier", "x-valiron-gate-risk-level", "x-valiron-gate-route"];
69
+ export interface ValironEdgeGateAllowed {
70
+ allowed: true;
71
+ /** The gate result (score, tier, riskLevel, route, agentId, ...). */
72
+ result: GateResult;
73
+ /** Trusted headers to set on the outbound origin request. */
74
+ headers: Record<string, string>;
75
+ }
76
+ export interface ValironEdgeGateBlocked {
77
+ allowed: false;
78
+ /** Complete response to return to the caller (401 / 403 / 503). */
79
+ response: Response;
80
+ }
81
+ export type ValironEdgeGateOutcome = ValironEdgeGateAllowed | ValironEdgeGateBlocked;
82
+ /**
83
+ * Remove every client-supplied trusted-decision header from an inbound
84
+ * request. Run this on EVERY request the edge fronts (gated or not) before
85
+ * forwarding, so callers can never inject a gate decision. Only meaningful
86
+ * when the origin cannot be reached directly (see the template README).
87
+ */
88
+ export declare function stripEdgeGateHeaders(request: Request): Request;
89
+ /**
90
+ * Run the Valiron trust gate for one incoming request.
91
+ *
92
+ * On allow: returns the GateResult plus the trusted headers to set on the
93
+ * outbound origin request. On any block: returns the exact response the
94
+ * runtime must send back, with the same status codes and error bodies as
95
+ * the Node middleware adapters.
96
+ */
97
+ export declare function runValironEdgeGate(request: Request, config: ValironEdgeGateConfig): Promise<ValironEdgeGateOutcome>;
98
+ export declare const EDGE_IDENTITY_HEADERS: {
99
+ readonly provider: "x-valiron-identity-provider";
100
+ readonly agentId: "x-valiron-identity-agent-id";
101
+ readonly signature: "x-valiron-identity-signature";
102
+ readonly timestamp: "x-valiron-identity-timestamp";
103
+ readonly nonce: "x-valiron-identity-nonce";
104
+ readonly keyId: "x-valiron-identity-key-id";
105
+ };
106
+ /** WebCrypto equivalent of sha256RequestDigest in ./identity: `sha256:<hex>`. */
107
+ export declare function edgeSha256RequestDigest(body?: string | Uint8Array | ArrayBuffer | null): Promise<string>;
108
+ export interface EdgeIdentityVerifierConfig {
109
+ sdk: ValironEdgeGateSdk;
110
+ /**
111
+ * Trusted audience for this API, configured by the API owner (for example
112
+ * "https://api.example.com"). Required: the signed proof is bound to it.
113
+ */
114
+ audience: string;
115
+ /**
116
+ * Trusted public origin for request-URL binding. Defaults to `audience`.
117
+ * The signed proof binds the exact public URL; requests whose URL does not
118
+ * share this origin never verify.
119
+ */
120
+ origin?: string;
121
+ }
122
+ /**
123
+ * Out-of-the-box `verifyRequest` for the edge gate: Valiron's hosted
124
+ * provider-identity verification (POST /operator/identity/verify), the same
125
+ * verification the Node identity middleware (createValironIdentityGate)
126
+ * performs server-side.
127
+ *
128
+ * The agent sends `x-valiron-identity-*` headers produced by the SDK's
129
+ * createAgentIdentityProof / agentIdentityProofHeaders, signing the canonical
130
+ * `valiron-agent-request-v2` payload with the private key bound to its
131
+ * provider identity. This verifier:
132
+ *
133
+ * - requires the proof's agentId to equal the gate identifier;
134
+ * - recomputes the request body digest at the edge (WebCrypto), exactly as
135
+ * the Node gate recomputes it server-side;
136
+ * - binds method and the exact public URL (same trusted origin rule as the
137
+ * Node identity middleware);
138
+ * - asks Valiron to verify the signature, freshness and replay state, and
139
+ * returns true only for identityStatus "verified".
140
+ *
141
+ * Operators with their own request-signing scheme can pass their own
142
+ * verifyRequest to runValironEdgeGate instead; the gate contract is unchanged.
143
+ */
144
+ export declare function createEdgeIdentityVerifier(config: EdgeIdentityVerifierConfig): (request: Request, identifier: string) => Promise<boolean>;
145
+ export { MemoryNonceStore, base58Decode, base64urlToBytes, buildWalletProofPayload, createEdgeWalletProofVerifier, verifyWalletRequestProof, webCryptoSolanaVerifier, } from "./edgeGateVerify";
146
+ export type { NonceStore, WalletProofCrypto, WalletProofOwnerResolver, WalletProofResult, WalletProofVerificationConfig, } from "./edgeGateVerify";