@valiron/sdk 2.0.0 → 2.1.1

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 (38) hide show
  1. package/README.md +12 -0
  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.js +2 -2
  6. package/dist/edge.d.ts +87 -0
  7. package/dist/edge.js +164 -0
  8. package/dist/edgeGate.d.ts +146 -0
  9. package/dist/edgeGate.js +230 -0
  10. package/dist/edgeGateVerify.d.ts +146 -0
  11. package/dist/edgeGateVerify.js +243 -0
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.js +1 -0
  14. package/dist/middleware.d.ts +2 -0
  15. package/dist/middleware.js +6 -3
  16. package/dist/operatorSdk.d.ts +8 -0
  17. package/dist/operatorSdk.js +8 -0
  18. package/docs/API-REFERENCE.md +59 -80
  19. package/docs/CLOUDFLARE-GATE-MIDDLEWARE.md +196 -0
  20. package/docs/CRAWLER-PROTECTION.md +509 -25
  21. package/docs/DASHBOARD.md +72 -214
  22. package/docs/E2E-MIDDLEWARE-INTEGRATION.md +9 -46
  23. package/docs/ERRORS.md +3 -11
  24. package/docs/PROVIDER-IDENTITY.md +1 -1
  25. package/docs/QUICKSTART.md +7 -22
  26. package/docs/README.md +10 -9
  27. package/docs/SDK-REFERENCE.md +51 -7
  28. package/docs/SECURITY-UPGRADE-2026-10-31.md +3 -3
  29. package/docs/llms.txt +19 -14
  30. package/examples/cloudflare-gate-worker/README.md +198 -0
  31. package/examples/cloudflare-gate-worker/package.json +20 -0
  32. package/examples/cloudflare-gate-worker/worker.ts +309 -0
  33. package/examples/cloudflare-gate-worker/wrangler.toml +46 -0
  34. package/examples/cloudflare-worker/package.json +8 -0
  35. package/examples/cloudflare-worker/worker.ts +495 -0
  36. package/examples/cloudflare-worker/wrangler.toml +57 -0
  37. package/package.json +34 -4
  38. package/docs/AGENT-READY-APIS.md +0 -294
@@ -0,0 +1,309 @@
1
+ /**
2
+ * Valiron trust gate - Cloudflare Worker template (general middleware).
3
+ *
4
+ * This Worker runs the SAME general Valiron trust gate as the Node
5
+ * middleware adapters (createValironGate / valironFastifyPlugin /
6
+ * createValironNextMiddleware), at the Cloudflare edge:
7
+ *
8
+ * - Agents identify with `x-agent-id` (on-chain) or `x-agent-address`
9
+ * (key-based web2), plus a fresh request-bound ownership proof
10
+ * (`x-agent-timestamp`, `x-agent-nonce`, `x-agent-request-signature`)
11
+ * in the `valiron-wallet-request-v2` scheme (see
12
+ * docs/SECURITY-UPGRADE-2026-10-31.md). EVM owners sign with EIP-191,
13
+ * Solana owners with Ed25519.
14
+ * - Every identified request is ownership-verified BEFORE any decision,
15
+ * including profile-cache hits. The default verifier below is
16
+ * application-owned: it checks the signature against the agent's current
17
+ * registry owner wallet from the live Valiron profile and consumes the
18
+ * nonce in a Durable Object (durable replay protection). No third-party
19
+ * identity provider is required for ordinary agents.
20
+ * - The Valiron API evaluates the agent's live trust profile on every
21
+ * (uncached) request: allow only when routing is prod/prod_throttled AND
22
+ * the combined score meets VALIRON_MIN_SCORE (default 65).
23
+ * - Denied: 403 TRUST_GATE_DENIED. New agent: 403 AGENT_EVALUATION_PENDING
24
+ * (sandbox evaluation is triggered). Missing identity: 401. Missing or
25
+ * invalid proof: 401 AGENT_OWNERSHIP_REQUIRED. Evaluation failure or
26
+ * missing durable replay storage: 503, fail closed.
27
+ *
28
+ * Hosted ANS provider-identity verification (createEdgeIdentityVerifier, for
29
+ * ans:// identities via Valiron's hosted resolver) is available as an opt-in
30
+ * (VALIRON_VERIFIER=hosted). It requires Valiron backend ANS configuration;
31
+ * it was NOT exercised in this template's isolated test deployment.
32
+ *
33
+ * On allow the Worker strips client-supplied `x-valiron-gate-*` headers and
34
+ * sets its own decision headers for the origin, plus the shared
35
+ * `x-valiron-gate-secret` when VALIRON_ORIGIN_SECRET is set. The origin MUST
36
+ * reject requests without that secret (or otherwise be unreachable directly)
37
+ * - see the README's required trust boundary.
38
+ */
39
+ import { recoverMessageAddress } from "viem";
40
+ import {
41
+ ValironClient,
42
+ createEdgeIdentityVerifier,
43
+ createEdgeWalletProofVerifier,
44
+ runValironEdgeGate,
45
+ stripEdgeGateHeaders,
46
+ webCryptoSolanaVerifier,
47
+ type NonceStore,
48
+ type TrustSignal,
49
+ type ValironEdgeGateSdk,
50
+ type WalletProofCrypto,
51
+ } from "@valiron/sdk/edge-gate";
52
+
53
+ export interface Env {
54
+ /** Valiron operator API base, e.g. "https://valiron-edge-proxy.onrender.com". */
55
+ VALIRON_ENDPOINT: string;
56
+ /** Fixed HTTPS origin for standalone workers.dev deployments. No path or credentials. */
57
+ VALIRON_ORIGIN?: string;
58
+ /** Operator API key (val_op_...) for profile reads. Required: profile routes
59
+ * are operator-authenticated. Set with `wrangler secret put VALIRON_API_KEY`. */
60
+ VALIRON_API_KEY: string;
61
+ /**
62
+ * Trusted audience AND public origin for this API, e.g.
63
+ * "https://api.example.com". Only used by the hosted verifier variant: its
64
+ * signed proof binds this audience. The default wallet proof binds the
65
+ * exact public request URL instead.
66
+ */
67
+ VALIRON_PUBLIC_ORIGIN?: string;
68
+ /** Minimum combined score to allow. Default "65". */
69
+ VALIRON_MIN_SCORE?: string;
70
+ /** Comma-separated URL path prefixes to gate, e.g. "/api/paid,/api/premium". Default "/": gate everything. */
71
+ VALIRON_GATE_PATHS?: string;
72
+ /** Comma-separated trust signals (8004,sandbox,world,self,wallet,icebreaker). Unset = server default set. */
73
+ VALIRON_TRUST_SIGNALS?: string;
74
+ /** Profile cache TTL in ms per isolate (same default as the Node middleware: 30000). "0" disables. */
75
+ VALIRON_CACHE_TTL_MS?: string;
76
+ /**
77
+ * Shared secret the Worker forwards to the origin as `x-valiron-gate-secret`.
78
+ * The origin must reject requests missing it, so only gate-verified traffic
79
+ * reaches application code. Set with `wrangler secret put VALIRON_ORIGIN_SECRET`.
80
+ */
81
+ VALIRON_ORIGIN_SECRET?: string;
82
+ /**
83
+ * "hosted" selects Valiron's hosted ANS provider-identity verification
84
+ * (requires backend ANS configuration; not covered by this template's
85
+ * isolated tests). Anything else uses the default application-owned
86
+ * wallet-proof verifier.
87
+ */
88
+ VALIRON_VERIFIER?: string;
89
+ /** Durable Object namespace providing the durable nonce store (replay
90
+ * protection). REQUIRED for the default verifier; the gate fails closed
91
+ * without it. */
92
+ VALIRON_NONCE_STORE?: DurableObjectNamespace;
93
+ }
94
+
95
+ // ─── Durable replay protection ──────────────────────────────────────────────
96
+
97
+ /**
98
+ * Durable Object that atomically claims nonce scopes. One named instance is
99
+ * used for the whole gate, so a nonce replayed against ANY isolate is
100
+ * rejected. Entries expire with the proof validity horizon (121s).
101
+ */
102
+ export class NonceStoreDO {
103
+ constructor(private readonly state: DurableObjectState) {}
104
+
105
+ async fetch(request: Request): Promise<Response> {
106
+ const body = (await request.json().catch(() => null)) as
107
+ | { scope?: string; ttlSeconds?: number }
108
+ | null;
109
+ if (!body || typeof body.scope !== "string" || !body.scope || body.scope.length > 2048 ||
110
+ !Number.isInteger(body.ttlSeconds) || body.ttlSeconds! < 1 || body.ttlSeconds! > 121) {
111
+ return Response.json({ claimed: false }, { status: 400 });
112
+ }
113
+ const key = `nonce:${body.scope}`;
114
+ const expiresAt = Date.now() + body.ttlSeconds! * 1000;
115
+ const claimed = await this.state.storage.transaction(async (txn) => {
116
+ const existing = await txn.get<number | boolean>(key);
117
+ // Legacy boolean entries fail closed until removed by an operator.
118
+ if (existing === true || (typeof existing === "number" && existing > Date.now())) return false;
119
+ await txn.put(key, expiresAt);
120
+ return true;
121
+ });
122
+ if (claimed) {
123
+ const alarm = await this.state.storage.getAlarm();
124
+ if (alarm === null || alarm > expiresAt) await this.state.storage.setAlarm(expiresAt);
125
+ }
126
+ return Response.json({ claimed });
127
+ }
128
+
129
+ async alarm(): Promise<void> {
130
+ const next = await this.state.storage.transaction(async (txn) => {
131
+ const entries = await txn.list<number | boolean>({ prefix: "nonce:" });
132
+ const now = Date.now();
133
+ let nextExpiry = Infinity;
134
+ for (const [key, expiry] of entries) {
135
+ if (typeof expiry === "number" && expiry <= now) await txn.delete(key);
136
+ else if (typeof expiry === "number") nextExpiry = Math.min(nextExpiry, expiry);
137
+ }
138
+ return nextExpiry;
139
+ });
140
+ if (Number.isFinite(next)) await this.state.storage.setAlarm(next);
141
+ }
142
+ }
143
+
144
+ class DurableObjectNonceStore implements NonceStore {
145
+ constructor(private readonly namespace: DurableObjectNamespace) {}
146
+
147
+ async claim(scope: string, ttlSeconds: number): Promise<boolean> {
148
+ const stub = this.namespace.get(this.namespace.idFromName("valiron-gate-nonces"));
149
+ const res = await stub.fetch("https://nonce-store/claim", {
150
+ method: "POST",
151
+ body: JSON.stringify({ scope, ttlSeconds }),
152
+ });
153
+ if (!res.ok) return false; // fail closed when the store errors
154
+ const data = (await res.json().catch(() => null)) as { claimed?: boolean } | null;
155
+ return data?.claimed === true;
156
+ }
157
+ }
158
+
159
+ // ─── Owner resolution from the live profile ─────────────────────────────────
160
+
161
+ function isSolanaNetwork(network: string): boolean {
162
+ return network.toLowerCase().includes("solana");
163
+ }
164
+
165
+ /** Resolve the current registry owner wallet + network for one identifier
166
+ * from the live Valiron profile (operator-authenticated). On-chain agents:
167
+ * the ERC-8004/Solana registry owner. Key-based web2 agents: the agent's own
168
+ * address, with the "key" network label used by the backend for key agents. */
169
+ function makeOwnerResolver(env: Env) {
170
+ const endpoint = env.VALIRON_ENDPOINT.replace(/\/$/, "");
171
+ const headers = { authorization: `Bearer ${env.VALIRON_API_KEY}` };
172
+ return async (
173
+ identifier: string,
174
+ ): Promise<{ wallet: string; network: string; isSolana: boolean } | null> => {
175
+ if (/^0x[a-fA-F0-9]{40}$/.test(identifier)) {
176
+ // Key-based web2 agent: self-sovereign - the address signs for itself.
177
+ const res = await fetch(`${endpoint}/operator/key/${identifier}`, { headers });
178
+ if (!res.ok) return null;
179
+ return { wallet: identifier, network: "key", isSolana: false };
180
+ }
181
+ const res = await fetch(`${endpoint}/operator/agent/${encodeURIComponent(identifier)}`, { headers });
182
+ if (!res.ok) return null;
183
+ const profile = (await res.json().catch(() => null)) as {
184
+ identity?: { wallet?: string };
185
+ chain?: { network?: string };
186
+ } | null;
187
+ const wallet = profile?.identity?.wallet;
188
+ const network = profile?.chain?.network;
189
+ if (!wallet || !network) return null;
190
+ return { wallet, network, isSolana: isSolanaNetwork(network) };
191
+ };
192
+ }
193
+
194
+ // ─── Gate wiring ────────────────────────────────────────────────────────────
195
+
196
+ // One client per isolate: the gate's profile cache lives on this instance,
197
+ // exactly like the per-process cache in the Node middleware.
198
+ let sdk: ValironEdgeGateSdk | undefined;
199
+ function getSdk(env: Env): ValironEdgeGateSdk {
200
+ if (!sdk) {
201
+ sdk = new ValironClient({
202
+ endpoint: env.VALIRON_ENDPOINT,
203
+ apiKey: env.VALIRON_API_KEY,
204
+ });
205
+ }
206
+ return sdk;
207
+ }
208
+
209
+ const walletProofCrypto: WalletProofCrypto = {
210
+ recoverEvmAddress: async (message, signature) =>
211
+ (await recoverMessageAddress({ message, signature: signature as `0x${string}` })).toLowerCase(),
212
+ verifySolanaSignature: webCryptoSolanaVerifier,
213
+ };
214
+
215
+ function gatedPaths(env: Env): string[] {
216
+ const raw = env.VALIRON_GATE_PATHS ?? "/";
217
+ return raw.split(",").map((p) => p.trim()).filter(Boolean);
218
+ }
219
+
220
+ function inScope(request: Request, env: Env): boolean {
221
+ const pathname = new URL(request.url).pathname;
222
+ return gatedPaths(env).some((p) => pathname.startsWith(p));
223
+ }
224
+
225
+ function parseTrustSignals(env: Env): TrustSignal[] | undefined {
226
+ const raw = env.VALIRON_TRUST_SIGNALS?.trim();
227
+ if (!raw) return undefined;
228
+ return raw.split(",").map((s) => s.trim()).filter(Boolean) as TrustSignal[];
229
+ }
230
+
231
+ function forwardRequest(request: Request, env: Env): Request {
232
+ const outbound = stripEdgeGateHeaders(request);
233
+ if (!env.VALIRON_ORIGIN) return outbound; // Zone-route mode: Cloudflare resolves the configured origin.
234
+ const target = new URL(env.VALIRON_ORIGIN);
235
+ const incoming = new URL(request.url);
236
+ if (target.protocol !== "https:" || target.username || target.password ||
237
+ target.pathname !== "/" || target.search || target.hash || target.origin === incoming.origin) {
238
+ throw new Error("VALIRON_ORIGIN must be a fixed, distinct HTTPS origin without credentials, path, query or fragment");
239
+ }
240
+ // Never resolve an untrusted path against the target: //evil.example stays a PATH.
241
+ incoming.protocol = target.protocol;
242
+ incoming.hostname = target.hostname;
243
+ incoming.port = target.port;
244
+ const forwarded = new Request(incoming.toString(), outbound);
245
+ forwarded.headers.delete("host");
246
+ // Do not follow redirects with origin credentials or trusted gate headers.
247
+ return new Request(forwarded, { redirect: "manual" });
248
+ }
249
+
250
+ export default {
251
+ async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
252
+ // Do not clone/transfer the body stream before request-proof verification.
253
+ if (!inScope(request, env)) {
254
+ try { return await fetch(forwardRequest(request, env)); }
255
+ catch { return Response.json({ code: "TRUST_GATE_UNAVAILABLE" }, { status: 503 }); }
256
+ }
257
+
258
+ const useHosted = env.VALIRON_VERIFIER === "hosted";
259
+
260
+ // Fail closed when the default verifier has no durable replay store.
261
+ if (!useHosted && !env.VALIRON_NONCE_STORE) {
262
+ return Response.json(
263
+ {
264
+ code: "TRUST_GATE_UNAVAILABLE",
265
+ error:
266
+ "Durable nonce store (VALIRON_NONCE_STORE Durable Object binding) is not configured; refusing to verify without replay protection.",
267
+ },
268
+ { status: 503 },
269
+ );
270
+ }
271
+
272
+ const client = getSdk(env);
273
+ const outcome = await runValironEdgeGate(request, {
274
+ sdk: client,
275
+ waitUntil: (pending) => ctx.waitUntil(pending),
276
+ minScore: parseInt(env.VALIRON_MIN_SCORE ?? "65", 10),
277
+ trustSignals: parseTrustSignals(env),
278
+ cacheTtlMs: parseInt(env.VALIRON_CACHE_TTL_MS ?? "30000", 10),
279
+ // Default: application-owned wallet proof (valiron-wallet-request-v2)
280
+ // against the live registry owner, with Durable Object replay
281
+ // protection. VALIRON_VERIFIER=hosted switches to Valiron's hosted ANS
282
+ // provider-identity verification (requires backend ANS configuration;
283
+ // not covered by this template's isolated tests).
284
+ verifyRequest: useHosted
285
+ ? createEdgeIdentityVerifier({
286
+ sdk: client,
287
+ audience: env.VALIRON_PUBLIC_ORIGIN ?? new URL(request.url).origin,
288
+ })
289
+ : createEdgeWalletProofVerifier({
290
+ resolveOwner: makeOwnerResolver(env),
291
+ nonceStore: new DurableObjectNonceStore(env.VALIRON_NONCE_STORE!),
292
+ crypto: walletProofCrypto,
293
+ }),
294
+ });
295
+
296
+ if (!outcome.allowed) return outcome.response;
297
+ let outbound: Request;
298
+ try { outbound = forwardRequest(request, env); }
299
+ catch { return Response.json({ code: "TRUST_GATE_UNAVAILABLE" }, { status: 503 }); }
300
+
301
+ for (const [name, value] of Object.entries(outcome.headers)) {
302
+ outbound.headers.set(name, value);
303
+ }
304
+ if (env.VALIRON_ORIGIN_SECRET) {
305
+ outbound.headers.set("x-valiron-gate-secret", env.VALIRON_ORIGIN_SECRET);
306
+ }
307
+ return fetch(outbound);
308
+ },
309
+ };
@@ -0,0 +1,46 @@
1
+ name = "valiron-trust-gate"
2
+ main = "worker.ts"
3
+ compatibility_date = "2026-11-14"
4
+
5
+ [vars]
6
+ # Standalone workers.dev: fixed HTTPS origin (no path). Omit only for zone-route mode.
7
+ # VALIRON_ORIGIN = "https://origin.example.com"
8
+ # Valiron operator API base.
9
+ VALIRON_ENDPOINT = "https://valiron-edge-proxy.onrender.com"
10
+ # Minimum combined Valiron score to allow (the Node middleware default: 65).
11
+ VALIRON_MIN_SCORE = "65"
12
+ # Comma-separated path prefixes to gate. "/" gates every route this Worker
13
+ # is attached to.
14
+ VALIRON_GATE_PATHS = "/"
15
+ # Optional: comma-separated trust signals. Unset uses the server default set.
16
+ # VALIRON_TRUST_SIGNALS = "8004,sandbox,wallet"
17
+ # Per-isolate profile cache TTL in ms (Node middleware default: 30000).
18
+ VALIRON_CACHE_TTL_MS = "30000"
19
+ # Only for the hosted verifier variant (VALIRON_VERIFIER=hosted): the trusted
20
+ # audience this API presents. The default wallet-proof verifier binds the
21
+ # exact public request URL instead and does not need it.
22
+ # VALIRON_PUBLIC_ORIGIN = "https://api.example.com"
23
+ # "hosted" selects Valiron's hosted ANS provider-identity verification
24
+ # (requires Valiron backend ANS configuration; not covered by this
25
+ # template's isolated tests). Unset = application-owned wallet proof.
26
+ # VALIRON_VERIFIER = "hosted"
27
+
28
+ # Durable Object providing the durable nonce store (replay protection) for
29
+ # the default wallet-proof verifier. The gate fails closed without it.
30
+ [[durable_objects.bindings]]
31
+ name = "VALIRON_NONCE_STORE"
32
+ class_name = "NonceStoreDO"
33
+
34
+ [[migrations]]
35
+ tag = "v1"
36
+ new_sqlite_classes = ["NonceStoreDO"]
37
+
38
+ # Required secrets (never in this file):
39
+ # wrangler secret put VALIRON_API_KEY # operator API key (val_op_...) - profile routes are operator-authenticated
40
+ # wrangler secret put VALIRON_ORIGIN_SECRET # shared secret forwarded to the origin as x-valiron-gate-secret
41
+
42
+ # Routes: attach this Worker to the routes you want gated, and make the
43
+ # origin reject requests without x-valiron-gate-secret (or lock it to
44
+ # Cloudflare with Authenticated Origin Pull, Tunnel, or a firewall rule).
45
+ # If direct-to-origin traffic is possible, the gate is bypassable - see the
46
+ # README's required trust boundary.
@@ -0,0 +1,8 @@
1
+ {
2
+ "name": "valiron-pass-cloudflare-worker",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "scripts": { "dev": "wrangler dev", "deploy": "wrangler deploy" },
6
+ "dependencies": { "@valiron/sdk": "^2.1.0" },
7
+ "devDependencies": { "wrangler": "^3.87.0", "@cloudflare/workers-types": "^4.20241106.0" }
8
+ }