# Security upgrade: request-bound identity

This guide describes the hardened source contract. Check the installed package supports these APIs and coordinate its release with your backend; a source merge does not publish packages or upgrade external clients.

Reputation belongs to an agent; an `x-agent-id` or `x-agent-address` header alone does not prove that the caller controls it.

## Trust gate integrations

`createValironGate`, `valironFastifyPlugin` and `createValironNextMiddleware` require `verifyRequest(request, identifier)`. `valironGateCheck` requires `verifyRequest(identifier)`. The callback must cryptographically verify the current caller against the registry owner or provider-bound key, bind the proof to the API audience, HTTP method, full URL and body, enforce a short timestamp window, and atomically reject replayed nonces in shared storage. It runs before every decision, including reputation-cache hits. An absent or invalid verifier denies the request. Never implement it as a header-presence check.

For provider-backed identities, use the built-in identity middleware described in [Provider identity](PROVIDER-IDENTITY.md). Configure its `audience` and trusted `origin`; the middleware computes request context and the raw-body digest locally. New signatures use `valiron-agent-request-v2`. Existing v1 proofs cannot authorize a request.

New agents remain denied while their real sandbox evaluation is pending. Provisional simulations do not establish behavioral reputation.

## Hosted wrappers, gates and proxy

SDK clients can provide a `signRequest({ method, url, body, chain })` callback in `ValironConfig`. It returns the proof headers for the actual URL and serialized body; signing finishes before the network timeout starts. The signer must create a new nonce and timestamp for each call.

Signed wallet requests use these headers: `x-agent-timestamp` (milliseconds), `x-agent-nonce` (24–128 URL-safe characters), and `x-agent-request-signature`. EVM owners sign the UTF-8 payload using EIP-191. Solana owners sign the same payload using Ed25519 and encode signatures as base64url.

```text
valiron-wallet-request-v2
agent:<exact-request-agent-id>
chain:<normalized-chain>
method:<UPPERCASE-method>
url:<absolute-public-request-URL>
body-sha256:<lowercase-SHA256-hex>
timestamp:<milliseconds>
nonce:<fresh-nonce>
```

The body hash covers `JSON.stringify` of the parsed JSON body, or the empty string for a request without a body. The server checks the current registry owner and atomically consumes the nonce. Send a newly signed request for each retry. Provider-identity middleware instead hashes exact raw body bytes; these are separate proof protocols.

Only admitted requests consume a hosted wrapper's monthly quota. Crawler Protection applies local rate and access decisions before monthly admission; monthly exhaustion still prevents origin work.

## Identity enrollment and endpoints

World ID enrollment requires an authenticated Valiron operator, an owner-signed request and the complete, unmodified production IDKit result. Browser assertions and partial proofs are rejected. The server verifies the proof before persisting a link, derives credential strength from the verified credential, and ignores older records without server-verification provenance. Current enrollment accepts the proof-of-human credential. Existing device-only links must not be treated as biometric proof.

Self enrollment also requires operator authentication and owner approval. Newly created sessions carry ownership provenance; old sessions cannot create new trusted links. Sandbox probes use short-lived, agent-scoped capabilities rather than exposing observer-control secrets.

SDK API endpoints remain configurable. Crawler activation can use an explicitly configured HTTPS endpoint at `/operator/crawlers/activation`. Configure only a service you control and trust: it receives the operator credential. Redirects are rejected.

Operator usage analytics now require explicit `analytics: true`. Raw IP addresses, user agents, query strings and paths are not transmitted.

## Upgrade checklist

1. Configure application-owned verifiers for local gates and paywalls. An invalid or absent verifier returns `AGENT_OWNERSHIP_REQUIRED` (401); failed trust checks return 403.
2. Configure hosted request signers and migrate provider identities to proof v2. Each payment retry also needs a new identity nonce.
3. Re-verify older World ID/Self links and re-register operator/chain-scoped webhook subscriptions. Expect cold reputation decisions to deny until a real evaluation completes.
4. Enable operator analytics only with explicit `analytics: true`; SDK diagnostic telemetry remains separately configured.
5. Validate stale, replayed, wrong-subject, wrong-method, wrong-URL and altered-body proofs as well as valid requests. Missing verification, quota storage or required identity infrastructure must fail closed.

## Example: sign one hosted EVM gate request

This Node.js example signs for one configured registry agent and chain. The private key must belong to that agent's current registry owner. Use a wallet/key manager in production; never send the owner key to the API seller. A Solana signer must instead produce the Ed25519/base64url signature described above.

```typescript
import { createHash, randomBytes } from "node:crypto";
import { privateKeyToAccount } from "viem/accounts";
import { ValironSDK } from "@valiron/sdk";

const agentId = "25459";
const chain = "ethereum";
const endpoint = "https://valiron-edge-proxy.onrender.com";
const key = process.env.AGENT_OWNER_PRIVATE_KEY;
if (!key) throw new Error("Configure your agent owner's signer");
const owner = privateKeyToAccount(key as `0x${string}`);
const sdk = new ValironSDK({
  apiKey: process.env.VALIRON_API_KEY,
  chain,
  endpoint,
  async signRequest(request) {
    const target = new URL(request.url);
    if (target.origin !== endpoint || target.pathname !== `/operator/gate/${agentId}` ||
        request.chain !== chain || request.method !== "POST") {
      throw new Error("This signer is scoped to one agent gate");
    }
    const timestamp = String(Date.now());
    const nonce = randomBytes(24).toString("base64url");
    const digest = createHash("sha256").update(request.body).digest("hex");
    const message = [
      "valiron-wallet-request-v2", `agent:${agentId}`, `chain:${chain}`,
      `method:${request.method}`, `url:${request.url}`, `body-sha256:${digest}`,
      `timestamp:${timestamp}`, `nonce:${nonce}`,
    ].join("\n");
    return {
      "x-agent-timestamp": timestamp,
      "x-agent-nonce": nonce,
      "x-agent-request-signature": await owner.signMessage({ message }),
    };
  },
});
const result = await sdk.gate(agentId);
if (!result.allow) throw new Error("Agent not admitted");
```

Use a separately scoped signer for proxy or enrollment operations rather than removing the destination check. This wallet-request protocol is distinct from provider proof v2, which hashes raw bytes and binds an explicit API audience.
