@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.
- package/README.md +11 -148
- package/bin/valiron-card.mjs +211 -0
- package/dist/card.d.ts +565 -0
- package/dist/card.js +722 -0
- package/dist/clients.d.ts +6 -6
- package/dist/clients.js +33 -26
- package/dist/edge.d.ts +87 -0
- package/dist/edge.js +164 -0
- package/dist/edgeGate.d.ts +146 -0
- package/dist/edgeGate.js +230 -0
- package/dist/edgeGateVerify.d.ts +146 -0
- package/dist/edgeGateVerify.js +243 -0
- package/dist/identity.d.ts +6 -0
- package/dist/identity.js +6 -1
- package/dist/identityMiddleware.d.ts +8 -0
- package/dist/identityMiddleware.js +12 -4
- package/dist/index.d.ts +5 -10
- package/dist/index.js +4 -10
- package/dist/middleware.d.ts +20 -9
- package/dist/middleware.js +47 -19
- package/dist/operatorSdk.d.ts +11 -2
- package/dist/operatorSdk.js +13 -7
- package/dist/types.d.ts +14 -4
- package/docs/AGENT-READY-APIS.md +3 -181
- package/docs/API-REFERENCE.md +94 -546
- package/docs/CHAINS.md +3 -3
- package/docs/CLOUDFLARE-GATE-MIDDLEWARE.md +196 -0
- package/docs/CRAWLER-PROTECTION.md +545 -0
- package/docs/DASHBOARD.md +55 -23
- package/docs/E2E-MIDDLEWARE-INTEGRATION.md +19 -13
- package/docs/ERRORS.md +29 -19
- package/docs/IDENTITY.md +16 -14
- package/docs/PROVIDER-IDENTITY.md +15 -5
- package/docs/QUICKSTART.md +40 -24
- package/docs/README.md +21 -4
- package/docs/SANDBOX.md +7 -1
- package/docs/SDK-REFERENCE.md +115 -52
- package/docs/SECURITY-UPGRADE-2026-10-31.md +98 -0
- package/docs/TRUST-MODEL.md +14 -11
- package/docs/llms.txt +70 -302
- package/examples/cloudflare-gate-worker/README.md +198 -0
- package/examples/cloudflare-gate-worker/package.json +20 -0
- package/examples/cloudflare-gate-worker/worker.ts +309 -0
- package/examples/cloudflare-gate-worker/wrangler.toml +46 -0
- package/examples/cloudflare-worker/package.json +8 -0
- package/examples/cloudflare-worker/worker.ts +495 -0
- package/examples/cloudflare-worker/wrangler.toml +57 -0
- package/package.json +35 -5
- package/docs/MCP.md +0 -50
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
# Valiron trust gate on Cloudflare Workers
|
|
2
|
+
|
|
3
|
+
This template runs the general Valiron trust gate - the same middleware
|
|
4
|
+
semantics as `createValironGate` (Express), `valironFastifyPlugin`,
|
|
5
|
+
`createValironNextMiddleware` and `valironGateCheck` in `@valiron/sdk` - as a
|
|
6
|
+
Cloudflare Worker in front of your API. It is the general trust-score
|
|
7
|
+
middleware at the edge.
|
|
8
|
+
|
|
9
|
+
On every gated request the Worker:
|
|
10
|
+
|
|
11
|
+
1. Reads the agent identity (`x-agent-id` for on-chain agents, or
|
|
12
|
+
`x-agent-address` for key-based web2 agents).
|
|
13
|
+
2. Verifies a fresh, request-bound ownership proof BEFORE any decision,
|
|
14
|
+
including cache hits. The default verifier is application-owned
|
|
15
|
+
(`createEdgeWalletProofVerifier`): the agent signs each request in the
|
|
16
|
+
`valiron-wallet-request-v2` scheme (`x-agent-timestamp`,
|
|
17
|
+
`x-agent-nonce`, `x-agent-request-signature`; EVM owners sign with
|
|
18
|
+
EIP-191, Solana owners with Ed25519 - see
|
|
19
|
+
`docs/SECURITY-UPGRADE-2026-10-31.md`), and the Worker verifies the
|
|
20
|
+
signature against the agent's current registry owner wallet from the live
|
|
21
|
+
Valiron profile, enforces a 60-second timestamp window, and consumes the
|
|
22
|
+
nonce in a Durable Object so replays are rejected across all isolates. No
|
|
23
|
+
third-party identity provider is required for ordinary agents.
|
|
24
|
+
`VALIRON_VERIFIER=hosted` switches to Valiron's hosted ANS
|
|
25
|
+
provider-identity verification (`x-valiron-identity-*` headers via
|
|
26
|
+
`POST /operator/identity/verify`); that variant needs Valiron backend ANS
|
|
27
|
+
configuration and was not exercised in this template's isolated test
|
|
28
|
+
deployment.
|
|
29
|
+
3. Evaluates the agent's live trust profile through the Valiron operator API
|
|
30
|
+
(operator-authenticated - `VALIRON_API_KEY` is required) and allows only
|
|
31
|
+
when routing is `prod` / `prod_throttled` AND the combined score meets
|
|
32
|
+
`VALIRON_MIN_SCORE` (default 65).
|
|
33
|
+
4. On allow, strips client-supplied `x-valiron-gate-*` headers, sets its own
|
|
34
|
+
decision headers plus the shared `x-valiron-gate-secret`, and forwards to
|
|
35
|
+
the origin. On deny: 401 (missing identity / missing or invalid proof),
|
|
36
|
+
403 (`TRUST_GATE_DENIED` or `AGENT_EVALUATION_PENDING`), or 503
|
|
37
|
+
fail-closed when evaluation fails or the durable nonce store is not
|
|
38
|
+
configured. Because the proof is checked first, an unreachable Valiron
|
|
39
|
+
API with the hosted verifier fails closed as 401
|
|
40
|
+
`AGENT_OWNERSHIP_REQUIRED`; with the default wallet verifier an owner-lookup failure also returns
|
|
41
|
+
401. A failure during subsequent trust evaluation returns 503. The origin is
|
|
42
|
+
never touched on failure.
|
|
43
|
+
|
|
44
|
+
## Who this is for, and whether it is required
|
|
45
|
+
|
|
46
|
+
This is an optional integration for a business that sells or exposes an API and
|
|
47
|
+
wants agent ownership and trust checks before requests reach its backend. The
|
|
48
|
+
business runs the Worker in its Cloudflare account, chooses the routes, score
|
|
49
|
+
threshold and trust signals, and protects its origin from direct access. The
|
|
50
|
+
backend can use any language. Valiron still serves profile reads and sandbox
|
|
51
|
+
evaluation; the default verifier also reads the current owner from Valiron.
|
|
52
|
+
|
|
53
|
+
Cloudflare is not required to use Valiron. Businesses can keep Node middleware,
|
|
54
|
+
call the API from their own enforcement code, or use this Worker. Use one
|
|
55
|
+
trust-gate layer per protected route. Agents calling those routes must identify
|
|
56
|
+
themselves and sign fresh requests. The gate verifies agent ownership and
|
|
57
|
+
applies the business's trust policy. Customer permissions, benefits and payment
|
|
58
|
+
authorization remain application responsibilities.
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
## What has to be true before this is safe
|
|
62
|
+
|
|
63
|
+
1. **The origin must reject anything that did not pass the gate.** The
|
|
64
|
+
Worker strips client-supplied `x-valiron-gate-*` headers and sets its
|
|
65
|
+
own, and forwards `x-valiron-gate-secret` when `VALIRON_ORIGIN_SECRET` is
|
|
66
|
+
set. The origin must reject requests missing that secret (or be
|
|
67
|
+
unreachable except through Cloudflare: Authenticated Origin Pull, Tunnel,
|
|
68
|
+
or a firewall rule). Otherwise the gate is bypassable by skipping the
|
|
69
|
+
Worker.
|
|
70
|
+
2. **Replay protection is durable.** The default verifier refuses to run
|
|
71
|
+
without the `VALIRON_NONCE_STORE` Durable Object binding (503,
|
|
72
|
+
fail-closed). Nonces are claimed atomically in one named Durable Object
|
|
73
|
+
with a 121-second TTL matching the proof validity window, so a proof
|
|
74
|
+
replayed against any isolate - or after a restart - is rejected. The
|
|
75
|
+
in-memory `MemoryNonceStore` exported by the SDK is for local tests only;
|
|
76
|
+
it is not safe across isolates.
|
|
77
|
+
3. **Enforce the gate at one layer per route.** If the origin also runs
|
|
78
|
+
`createValironGate` on the same routes, agents are evaluated twice (and
|
|
79
|
+
pay twice the latency). Attach the Worker to the gated routes and do not
|
|
80
|
+
run the origin gate there, or keep the origin gate and no Worker.
|
|
81
|
+
4. **Every identified request needs a valid proof.** A request that names an
|
|
82
|
+
agent without a verifiable request-bound proof is denied
|
|
83
|
+
`401 AGENT_OWNERSHIP_REQUIRED` before trust evaluation. The default verifier needs a live owner lookup
|
|
84
|
+
to determine which key must sign. Do not weaken this to header claims alone.
|
|
85
|
+
5. **The profile cache is per isolate.** `VALIRON_CACHE_TTL_MS` (default
|
|
86
|
+
30000) matches the Node middleware's per-process cache: it bounds profile
|
|
87
|
+
re-reads inside one isolate and is not shared across isolates or colos.
|
|
88
|
+
The ownership proof is verified on every request regardless of cache.
|
|
89
|
+
Set it to `0` to disable.
|
|
90
|
+
|
|
91
|
+
## Deploy
|
|
92
|
+
|
|
93
|
+
Copy this directory, install dependencies, configure `wrangler.toml`, set the
|
|
94
|
+
secrets, and deploy:
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
cd examples/cloudflare-gate-worker
|
|
98
|
+
pnpm install # or npm install
|
|
99
|
+
wrangler secret put VALIRON_API_KEY # operator key (val_op_...)
|
|
100
|
+
wrangler secret put VALIRON_ORIGIN_SECRET # shared with your origin
|
|
101
|
+
wrangler deploy
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
| Variable | Required | Purpose |
|
|
105
|
+
| --- | --- | --- |
|
|
106
|
+
| `VALIRON_ENDPOINT` | yes | Valiron operator API base |
|
|
107
|
+
| `VALIRON_API_KEY` | yes (secret) | Operator API key for profile reads (profile routes are operator-authenticated) |
|
|
108
|
+
| `VALIRON_NONCE_STORE` | yes (binding) | Durable Object namespace for replay protection (default verifier fails closed without it) |
|
|
109
|
+
| `VALIRON_ORIGIN_SECRET` | recommended (secret) | Shared secret forwarded to the origin as `x-valiron-gate-secret` |
|
|
110
|
+
| `VALIRON_MIN_SCORE` | no | Minimum combined score (default 65) |
|
|
111
|
+
| `VALIRON_GATE_PATHS` | no | Comma-separated gated path prefixes (default `/`) |
|
|
112
|
+
| `VALIRON_TRUST_SIGNALS` | no | Comma-separated signals; unset uses the server default set |
|
|
113
|
+
| `VALIRON_CACHE_TTL_MS` | no | Per-isolate profile cache TTL in ms (default 30000, 0 disables) |
|
|
114
|
+
| `VALIRON_VERIFIER` | no | `hosted` selects hosted ANS provider-identity verification (needs backend ANS configuration; untested in this template's isolated deployment) |
|
|
115
|
+
| `VALIRON_PUBLIC_ORIGIN` | hosted only | Audience for the hosted verifier variant |
|
|
116
|
+
|
|
117
|
+
Attach the Worker to the routes you want gated. Telemetry is best-effort at
|
|
118
|
+
the edge (the SDK's batched telemetry flush is timer-driven); use Workers
|
|
119
|
+
Logs / Logpush for operational visibility.
|
|
120
|
+
|
|
121
|
+
## Agent side
|
|
122
|
+
|
|
123
|
+
Agents sign every request with the registry owner's private key in the
|
|
124
|
+
`valiron-wallet-request-v2` scheme. The SDK's hosted clients do this for you
|
|
125
|
+
via `signRequest`; from any stack the recipe is:
|
|
126
|
+
|
|
127
|
+
```typescript
|
|
128
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
129
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
130
|
+
|
|
131
|
+
const owner = privateKeyToAccount(process.env.AGENT_OWNER_PRIVATE_KEY as `0x${string}`);
|
|
132
|
+
const agentId = "25459"; // same value sent as x-agent-id
|
|
133
|
+
const chain = "ethereum"; // the agent's registry network string
|
|
134
|
+
const url = "https://api.example.com/api/paid"; // exact public URL
|
|
135
|
+
const body = JSON.stringify({ hello: "world" }); // or "" for no body
|
|
136
|
+
|
|
137
|
+
const timestamp = String(Date.now());
|
|
138
|
+
const nonce = randomBytes(24).toString("base64url");
|
|
139
|
+
const digest = createHash("sha256")
|
|
140
|
+
.update(body === "" ? "" : JSON.stringify(JSON.parse(body)))
|
|
141
|
+
.digest("hex");
|
|
142
|
+
const payload = [
|
|
143
|
+
"valiron-wallet-request-v2",
|
|
144
|
+
`agent:${agentId}`, `chain:${chain}`, `method:POST`, `url:${url}`,
|
|
145
|
+
`body-sha256:${digest}`, `timestamp:${timestamp}`, `nonce:${nonce}`,
|
|
146
|
+
].join("\n");
|
|
147
|
+
const signature = await owner.signMessage({ message: payload }); // EIP-191
|
|
148
|
+
|
|
149
|
+
await fetch(url, {
|
|
150
|
+
method: "POST",
|
|
151
|
+
headers: {
|
|
152
|
+
"x-agent-id": agentId,
|
|
153
|
+
"x-agent-timestamp": timestamp,
|
|
154
|
+
"x-agent-nonce": nonce,
|
|
155
|
+
"x-agent-request-signature": signature,
|
|
156
|
+
"content-type": "application/json",
|
|
157
|
+
},
|
|
158
|
+
body,
|
|
159
|
+
});
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Solana owners sign the same UTF-8 payload with Ed25519 and send the signature
|
|
163
|
+
base64url-encoded; key-based web2 agents send `x-agent-address` and sign with
|
|
164
|
+
that address's key using chain `key`. Sign a fresh nonce and timestamp for
|
|
165
|
+
every request and every retry: consumed nonces are rejected for 121 seconds.
|
|
166
|
+
The URL signed must be the exact public URL as Cloudflare normalizes it; a
|
|
167
|
+
mismatch fails verification closed.
|
|
168
|
+
|
|
169
|
+
## Workers-runtime regression harness
|
|
170
|
+
|
|
171
|
+
`test/edge-gate-worker/` runs this template under miniflare (real workerd, no
|
|
172
|
+
deploy): allow/deny decisions, both signing chains, proof enforcement,
|
|
173
|
+
replay rejection, fail-closed behavior, header stripping, path scoping and
|
|
174
|
+
the profile cache. See its README.
|
|
175
|
+
|
|
176
|
+
## Origin targeting and nonce expiry
|
|
177
|
+
|
|
178
|
+
For a standalone `workers.dev` deployment, set `VALIRON_ORIGIN` to the fixed
|
|
179
|
+
HTTPS origin, for example `https://origin.example.com`. It must have no
|
|
180
|
+
credentials, path, query, or fragment and must differ from the incoming
|
|
181
|
+
origin. Leave it unset only when Cloudflare zone-route origin resolution is
|
|
182
|
+
configured. The Worker verifies the original incoming URL and body before
|
|
183
|
+
rewriting the destination. Path and query are preserved; caller-provided
|
|
184
|
+
URLs and host-like paths cannot select another host. Redirects from an
|
|
185
|
+
explicit origin are returned without following them, so trusted headers and
|
|
186
|
+
the origin secret are never sent to a redirect destination. Out-of-scope
|
|
187
|
+
paths are forwarded without the gate secret and cannot access protected
|
|
188
|
+
origin routes.
|
|
189
|
+
|
|
190
|
+
Durable Object nonce claims use a storage transaction and an explicit expiry
|
|
191
|
+
timestamp, not KV-only `expirationTtl`. A scheduled alarm removes expired
|
|
192
|
+
entries. Concurrent claims have exactly one winner; a claimed nonce stays
|
|
193
|
+
blocked until its 121-second expiry, including across isolates. Expiry makes
|
|
194
|
+
the nonce reusable but does not make an old signature fresh.
|
|
195
|
+
|
|
196
|
+
The template registers sandbox-trigger promises with `ExecutionContext.waitUntil` so pending evaluations can continue after the denial response. All inbound `x-valiron-gate-*` headers, including a forged origin secret, are stripped before forwarding.
|
|
197
|
+
|
|
198
|
+
Wallet proof freshness can be tightened with `maxAgeMs`; values above 60,000 ms are rejected. Durable nonce retention is 121 seconds to cover the entire 60-second past/future validity horizon, including its boundary.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "valiron-cloudflare-gate-worker",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"description": "Valiron trust gate as a Cloudflare Worker (general middleware at the edge)",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"deploy": "wrangler deploy",
|
|
9
|
+
"dev": "wrangler dev",
|
|
10
|
+
"tail": "wrangler tail"
|
|
11
|
+
},
|
|
12
|
+
"dependencies": {
|
|
13
|
+
"@valiron/sdk": "^2.1.0",
|
|
14
|
+
"viem": "^2.21.0"
|
|
15
|
+
},
|
|
16
|
+
"devDependencies": {
|
|
17
|
+
"@cloudflare/workers-types": "^4.20241106.0",
|
|
18
|
+
"wrangler": "^3.87.0"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -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
|
+
}
|