# Valiron trust gate on Cloudflare Workers

Run the general Valiron trust gate - the same middleware semantics as the
Express, Fastify, Next.js and generic adapters in `@valiron/sdk` - as a
Cloudflare Worker in front of your API. Agents are identified, ownership is
proven per request, the live trust profile is evaluated, and only allowed
requests reach your origin.

This document describes the current source contract on this branch. Package
publication and production deployment are separate release steps; confirm the
installed `@valiron/sdk` exposes the `edge-gate` subpath and the
`examples/cloudflare-gate-worker` template before building on them.

## Who this is for, and whether it is required

This is an optional integration for a business that sells or exposes an API and
wants agent ownership and trust checks before requests reach its backend. The
business runs the Worker in its Cloudflare account, chooses the routes, score
threshold and trust signals, and protects its origin from direct access. The
backend can use any language. Valiron still serves profile reads and sandbox
evaluation; the default verifier also reads the current owner from Valiron.

Cloudflare is not required to use Valiron. Businesses can keep Node middleware,
call the API from their own enforcement code, or use this Worker. Use one
trust-gate layer per protected route. Agents calling those routes must identify
themselves and sign fresh requests. The gate verifies agent ownership and
applies the business's trust policy. Customer permissions, benefits and payment
authorization remain application responsibilities.


## Components

- **`@valiron/sdk/edge-gate`.** A WebCrypto-only SDK subpath that loads in
  Workers and other edge runtimes without Node APIs: `runValironEdgeGate`,
  `createEdgeIdentityVerifier`, `stripEdgeGateHeaders`,
  `edgeSha256RequestDigest`, and an edge-safe `ValironClient` re-export. The
  gate decision itself is computed by the exact same `valironGateCheck`
  implementation the Node middleware uses, so statuses, error bodies, cache
  behavior and allow/deny semantics are identical.
- **Worker template.** `packages/valiron-sdk/examples/cloudflare-gate-worker/`
  is a deployable Worker: identity extraction, per-request proof
  verification, live profile evaluation, trusted-header strip/set, and
  path scoping. `packages/valiron-sdk/test/edge-gate-worker/` is a committed
  miniflare (workerd) regression harness for the template.

## Request flow

```text
Agent request
  -> Worker reads x-agent-id / x-agent-address
  -> Worker verifies the request-bound proof (before any decision, cache hits included)
  -> Worker evaluates the live profile through the Valiron operator API
  -> allow: strip client x-valiron-gate-*, set trusted decision headers, forward to origin
  -> deny: 401 / 403 / 503 response; the origin never runs
```

Decision semantics are the Node gate's, unchanged:

| Condition | Status | Code |
| --- | --- | --- |
| No identity headers | 401 | `MISSING_AGENT_IDENTITY` |
| Missing or invalid request proof | 401 | `AGENT_OWNERSHIP_REQUIRED` |
| Route not production-eligible, or score below `minScore` | 403 | `TRUST_GATE_DENIED` |
| New agent (no reputation yet) | 403 | `AGENT_EVALUATION_PENDING` |
| Evaluation error / API unreachable (after a successful proof) | 503 | `TRUST_GATE_UNAVAILABLE` (fail closed) |
| API unreachable during hosted proof verification | 401 | `AGENT_OWNERSHIP_REQUIRED` (fail closed) |

Allow requires routing `prod` or `prod_throttled` AND the combined score at
or above `minScore` (default 65). A new agent's denial triggers a background
sandbox evaluation, exactly like the Node gate.

Outage behavior depends on where the failure lands. The default wallet
verifier checks signatures locally, but first reads the current owner from
Valiron; failure of that lookup returns 401 `AGENT_OWNERSHIP_REQUIRED`.
Hosted verification failures also return 401. If proof verification succeeds
and the later trust-profile evaluation fails, the gate returns 503
`TRUST_GATE_UNAVAILABLE`. The origin is never touched on failure.

## Deploy the Worker template

Copy `packages/valiron-sdk/examples/cloudflare-gate-worker/`, configure
`wrangler.toml`, and `wrangler deploy`. Required: `VALIRON_ENDPOINT` (the
Valiron operator API), `VALIRON_API_KEY` (secret - profile routes are
operator-authenticated) and the `VALIRON_NONCE_STORE` Durable Object binding
(durable replay protection; the gate fails closed without it). Recommended:
`VALIRON_ORIGIN_SECRET` (secret forwarded to the origin as
`x-valiron-gate-secret`). Optional: `VALIRON_MIN_SCORE`,
`VALIRON_GATE_PATHS`, `VALIRON_TRUST_SIGNALS`, `VALIRON_CACHE_TTL_MS`,
`VALIRON_VERIFIER` (`hosted` selects hosted ANS verification - see below),
`VALIRON_PUBLIC_ORIGIN` (audience for the hosted variant only).

## Required trust boundary

1. **The origin must reject anything that did not pass the gate.** The
   Worker strips client-supplied `x-valiron-gate-*` headers and sets its own
   (`x-valiron-gate-decision`, `-agent-id`, `-score`, `-tier`,
   `-risk-level`, `-route`), and forwards `x-valiron-gate-secret` when
   `VALIRON_ORIGIN_SECRET` is set. The origin must reject requests missing
   that secret, or use an exclusive authenticated origin path (private Tunnel or custom
   per-zone mTLS). Cloudflare IP allowlisting or a shared origin-pull
   certificate alone does not identify this Worker. If the origin is reachable
   directly, the gate is bypassable.
2. **Replay protection is durable.** The default verifier refuses to run
   without the `VALIRON_NONCE_STORE` Durable Object binding (503,
   fail-closed). Nonces are claimed atomically in one named Durable Object
   with a 121-second TTL matching the proof validity window, so a proof
   replayed against any isolate or after a restart is rejected. The SDK's
   in-memory `MemoryNonceStore` is for local tests only.
3. **Enforce the gate at one layer per route.** Do not run the origin's
   `createValironGate` on the same routes the Worker gates; requests would be
   evaluated twice.
4. **Header claims alone never authorize.** Every identified request carries
   a fresh proof or is denied `401 AGENT_OWNERSHIP_REQUIRED` before trust
   evaluation. The default verifier first reads the current registry owner
   from a live profile to determine which key must sign.
5. **The profile cache is per isolate** (default 30000 ms, matching the Node
   gate's per-process default). It is not shared across isolates or colos.
   The ownership proof is verified on every request regardless of cache.

## Request-bound proofs

The template's default `verifyRequest` is `createEdgeWalletProofVerifier`:
application-owned verification of the `valiron-wallet-request-v2` signed
request scheme (see `SECURITY-UPGRADE-2026-10-31.md`), the same scheme the
hosted API enforces server-side. Agents send `x-agent-timestamp`,
`x-agent-nonce` and `x-agent-request-signature`: the registry owner's EIP-191
(EVM) or Ed25519 (Solana) signature over the canonical payload binding the
agent id, chain, method, the exact public URL, a canonical JSON body digest,
a millisecond timestamp (60-second window) and a fresh nonce. The Worker
verifies the signature against the agent's current registry owner wallet
from the live profile, then consumes the nonce in the Durable Object; a
replayed proof is rejected for 121 seconds. Key-based web2 agents send
`x-agent-address` and sign with that address's key (chain `key`). The sign
side ships in the SDK's hosted clients (`signRequest`) and the recipe is in
the template README.

`VALIRON_VERIFIER=hosted` switches to `createEdgeIdentityVerifier`: Valiron's
hosted ANS provider-identity verification (`POST /operator/identity/verify`,
`x-valiron-identity-*` headers from `createAgentIdentityProof`, canonical
`valiron-agent-request-v2` payload). That variant requires Valiron backend
ANS configuration and a registered `ans://` identity, and was not exercised
in the template's isolated test deployment.

Operators with their own request-signing scheme replace `verifyRequest` in
`worker.ts` - the same application-owned verifier contract as the Node
middleware (`verifyAgentRequest` in the end-to-end guide). The verifier must
bind identity, method, full URL and body, enforce freshness, and reject
replayed nonces in durable shared storage.

## What this is not

- It does not cache or replicate trust scores at the edge beyond the short
  per-isolate profile cache the Node middleware already has; the operator API
  remains the decision source.
- It grants no Cloudflare verified-agent status and changes no scoring or
  privacy behavior.

## Verification

- SDK suite: `pnpm --filter @valiron/sdk test` includes
  `test/validate-edge-gate.mjs` (decision parity with the Node gate, digest
  parity with Node `sha256RequestDigest`, header constants, verifier
  binding rules).
- Workers-runtime harness: `packages/valiron-sdk/test/edge-gate-worker/`
  (miniflare; allow/deny, both signing chains through the default
  wallet-proof verifier with real signatures, Durable Object replay
  rejection, tampered/stale/wrong-key rejection, fail-closed without the
  nonce-store binding, origin-secret forwarding, hosted-variant coverage,
  header stripping, path scoping, profile cache, digest recomputation). This
  is hermetic coverage with a mocked API; it complements a live deployment
  test and does not replace one.


## Origin targeting and nonce expiry

For a standalone `workers.dev` deployment, set `VALIRON_ORIGIN` to the fixed
HTTPS origin, for example `https://origin.example.com`. It must have no
credentials, path, query, or fragment and must differ from the incoming
origin. Leave it unset only when Cloudflare zone-route origin resolution is
configured. The Worker verifies the original incoming URL and body before
rewriting the destination. Path and query are preserved; caller-provided
URLs and host-like paths cannot select another host. Redirects from an
explicit origin are returned without following them, so trusted headers and
the origin secret are never sent to a redirect destination. Out-of-scope
paths are forwarded without the gate secret and cannot access protected
origin routes.

Durable Object nonce claims use a storage transaction and an explicit expiry
timestamp, not KV-only `expirationTtl`. A scheduled alarm removes expired
entries. Concurrent claims have exactly one winner; a claimed nonce stays
blocked until its 121-second expiry, including across isolates. Expiry makes
the nonce reusable but does not make an old signature fresh.

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.

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.
