@valiron/sdk 2.0.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/dist/clients.js CHANGED
@@ -320,7 +320,7 @@ class ValironClient {
320
320
  method: "GET",
321
321
  headers: this.buildHeaders(),
322
322
  signal: controller.signal,
323
- redirect: "error",
323
+ redirect: "manual",
324
324
  });
325
325
  responseStatus = response.status;
326
326
  const methodName = this.extractMethodName(path);
@@ -424,7 +424,7 @@ class ValironClient {
424
424
  headers,
425
425
  body: hasBody ? JSON.stringify(body) : undefined,
426
426
  signal: controller.signal,
427
- redirect: "error",
427
+ redirect: "manual",
428
428
  });
429
429
  responseStatus = response.status;
430
430
  const methodName = this.extractMethodName(path);
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";
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+ /**
3
+ * Valiron trust gate for Cloudflare Workers and other WebCrypto-only edge
4
+ * runtimes: the same general trust gate the Node adapters in ./middleware
5
+ * expose (createValironGate, valironFastifyPlugin, createValironNextMiddleware,
6
+ * valironGateCheck), packaged so it loads inside workerd.
7
+ *
8
+ * Semantics are identical to the Node middleware:
9
+ *
10
+ * - identity headers: `x-agent-id` (on-chain ERC-8004 / Solana) or
11
+ * `x-agent-address` / `x-agent-key-hash` (key-based web2 agents)
12
+ * - a fresh, request-bound ownership proof is required before EVERY
13
+ * decision, including profile-cache hits (`verifyRequest`)
14
+ * - live profile evaluation through the public operator API
15
+ * (getAgentProfile / getKeyAgentProfile), with the same client-side
16
+ * profile cache (default 30s, per isolate at the edge)
17
+ * - allow only when operator routing is `prod` / `prod_throttled` AND the
18
+ * combined score meets `minScore` (default 65)
19
+ * - 401 MISSING_AGENT_IDENTITY, 401 AGENT_OWNERSHIP_REQUIRED, 403
20
+ * TRUST_GATE_DENIED or AGENT_EVALUATION_PENDING, 503 fail-closed on
21
+ * evaluation errors
22
+ *
23
+ * This module imports only ./middleware and ./clients at runtime (both free
24
+ * of Node APIs), so the `@valiron/sdk/edge-gate` subpath loads in Workers.
25
+ * The Pass-specific edge verifier is a separate subpath (`@valiron/sdk/edge`)
26
+ * and is not required for the general trust gate.
27
+ */
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.webCryptoSolanaVerifier = exports.verifyWalletRequestProof = exports.createEdgeWalletProofVerifier = exports.buildWalletProofPayload = exports.base64urlToBytes = exports.base58Decode = exports.MemoryNonceStore = exports.EDGE_IDENTITY_HEADERS = exports.VALIRON_EDGE_GATE_HEADERS = exports.ValironClient = void 0;
30
+ exports.stripEdgeGateHeaders = stripEdgeGateHeaders;
31
+ exports.runValironEdgeGate = runValironEdgeGate;
32
+ exports.edgeSha256RequestDigest = edgeSha256RequestDigest;
33
+ exports.createEdgeIdentityVerifier = createEdgeIdentityVerifier;
34
+ const middleware_1 = require("./middleware");
35
+ const clients_1 = require("./clients");
36
+ Object.defineProperty(exports, "ValironClient", { enumerable: true, get: function () { return clients_1.ValironClient; } });
37
+ /** Headers the edge sets on the outbound request after an allow decision. */
38
+ exports.VALIRON_EDGE_GATE_HEADERS = [
39
+ "x-valiron-gate-decision",
40
+ "x-valiron-gate-agent-id",
41
+ "x-valiron-gate-score",
42
+ "x-valiron-gate-tier",
43
+ "x-valiron-gate-risk-level",
44
+ "x-valiron-gate-route",
45
+ ];
46
+ function defaultExtractAgentId(request) {
47
+ return request.headers.get("x-agent-id");
48
+ }
49
+ function defaultExtractAgentAddress(request) {
50
+ return (request.headers.get("x-agent-address") ||
51
+ request.headers.get("x-agent-key-hash"));
52
+ }
53
+ /**
54
+ * Remove every client-supplied trusted-decision header from an inbound
55
+ * request. Run this on EVERY request the edge fronts (gated or not) before
56
+ * forwarding, so callers can never inject a gate decision. Only meaningful
57
+ * when the origin cannot be reached directly (see the template README).
58
+ */
59
+ function stripEdgeGateHeaders(request) {
60
+ const headers = new Headers(request.headers);
61
+ const names = [];
62
+ headers.forEach((_value, name) => names.push(name));
63
+ for (const name of names) {
64
+ if (name.toLowerCase().startsWith("x-valiron-gate-"))
65
+ headers.delete(name);
66
+ }
67
+ return new Request(request, { headers });
68
+ }
69
+ /**
70
+ * Run the Valiron trust gate for one incoming request.
71
+ *
72
+ * On allow: returns the GateResult plus the trusted headers to set on the
73
+ * outbound origin request. On any block: returns the exact response the
74
+ * runtime must send back, with the same status codes and error bodies as
75
+ * the Node middleware adapters.
76
+ */
77
+ async function runValironEdgeGate(request, config) {
78
+ const extractAgentId = config.extractAgentId || defaultExtractAgentId;
79
+ const extractAgentAddress = config.extractAgentAddress || defaultExtractAgentAddress;
80
+ const agentId = extractAgentId(request);
81
+ const agentAddress = agentId ? null : extractAgentAddress(request);
82
+ const gate = await (0, middleware_1.valironGateCheck)(config.sdk, {
83
+ agentId,
84
+ agentAddress,
85
+ minScore: config.minScore,
86
+ trustSignals: config.trustSignals,
87
+ cacheTtlMs: config.cacheTtlMs,
88
+ waitUntil: config.waitUntil,
89
+ verifyRequest: config.verifyRequest
90
+ ? (identifier) => config.verifyRequest(request, identifier)
91
+ : undefined,
92
+ });
93
+ if (gate.ok && gate.allow && gate.result) {
94
+ const result = gate.result;
95
+ return {
96
+ allowed: true,
97
+ result,
98
+ headers: {
99
+ "x-valiron-gate-decision": "allow",
100
+ "x-valiron-gate-agent-id": result.agentId,
101
+ "x-valiron-gate-score": String(result.score),
102
+ "x-valiron-gate-tier": String(result.tier),
103
+ "x-valiron-gate-risk-level": String(result.riskLevel),
104
+ "x-valiron-gate-route": String(result.route),
105
+ },
106
+ };
107
+ }
108
+ return {
109
+ allowed: false,
110
+ response: Response.json(gate.body ?? { code: "TRUST_GATE_UNAVAILABLE" }, {
111
+ status: gate.status,
112
+ }),
113
+ };
114
+ }
115
+ // ─── Hosted provider-identity verifier ──────────────────────────────────────
116
+ //
117
+ // Header names mirror AGENT_IDENTITY_HEADERS in ./identity. They are
118
+ // re-declared here (not imported) because ./identity uses Node crypto, which
119
+ // workerd does not provide. test/validate-edge-gate.mjs asserts the two stay
120
+ // in sync.
121
+ exports.EDGE_IDENTITY_HEADERS = {
122
+ provider: "x-valiron-identity-provider",
123
+ agentId: "x-valiron-identity-agent-id",
124
+ signature: "x-valiron-identity-signature",
125
+ timestamp: "x-valiron-identity-timestamp",
126
+ nonce: "x-valiron-identity-nonce",
127
+ keyId: "x-valiron-identity-key-id",
128
+ };
129
+ /** WebCrypto equivalent of sha256RequestDigest in ./identity: `sha256:<hex>`. */
130
+ async function edgeSha256RequestDigest(body) {
131
+ const bytes = body == null
132
+ ? new Uint8Array(0)
133
+ : typeof body === "string"
134
+ ? new TextEncoder().encode(body)
135
+ : body instanceof ArrayBuffer
136
+ ? new Uint8Array(body)
137
+ : body;
138
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
139
+ const hex = Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
140
+ return `sha256:${hex}`;
141
+ }
142
+ /**
143
+ * Out-of-the-box `verifyRequest` for the edge gate: Valiron's hosted
144
+ * provider-identity verification (POST /operator/identity/verify), the same
145
+ * verification the Node identity middleware (createValironIdentityGate)
146
+ * performs server-side.
147
+ *
148
+ * The agent sends `x-valiron-identity-*` headers produced by the SDK's
149
+ * createAgentIdentityProof / agentIdentityProofHeaders, signing the canonical
150
+ * `valiron-agent-request-v2` payload with the private key bound to its
151
+ * provider identity. This verifier:
152
+ *
153
+ * - requires the proof's agentId to equal the gate identifier;
154
+ * - recomputes the request body digest at the edge (WebCrypto), exactly as
155
+ * the Node gate recomputes it server-side;
156
+ * - binds method and the exact public URL (same trusted origin rule as the
157
+ * Node identity middleware);
158
+ * - asks Valiron to verify the signature, freshness and replay state, and
159
+ * returns true only for identityStatus "verified".
160
+ *
161
+ * Operators with their own request-signing scheme can pass their own
162
+ * verifyRequest to runValironEdgeGate instead; the gate contract is unchanged.
163
+ */
164
+ function createEdgeIdentityVerifier(config) {
165
+ return async (request, identifier) => {
166
+ const read = (name) => request.headers.get(name) ?? undefined;
167
+ const proof = {
168
+ provider: read(exports.EDGE_IDENTITY_HEADERS.provider),
169
+ agentId: read(exports.EDGE_IDENTITY_HEADERS.agentId),
170
+ signature: read(exports.EDGE_IDENTITY_HEADERS.signature),
171
+ timestamp: read(exports.EDGE_IDENTITY_HEADERS.timestamp),
172
+ nonce: read(exports.EDGE_IDENTITY_HEADERS.nonce),
173
+ keyId: read(exports.EDGE_IDENTITY_HEADERS.keyId),
174
+ };
175
+ if (!proof.provider ||
176
+ !proof.agentId ||
177
+ !proof.signature ||
178
+ !proof.timestamp ||
179
+ !proof.nonce) {
180
+ return false;
181
+ }
182
+ // The proof must bind the exact identity the gate is evaluating.
183
+ if (proof.agentId !== identifier)
184
+ return false;
185
+ const origin = config.origin ?? config.audience;
186
+ let url;
187
+ try {
188
+ const parsed = new URL(request.url);
189
+ if (parsed.origin !== new URL(origin).origin)
190
+ return false;
191
+ url = parsed.toString();
192
+ }
193
+ catch {
194
+ return false;
195
+ }
196
+ const body = ["GET", "HEAD"].includes(request.method)
197
+ ? undefined
198
+ : new Uint8Array(await request.clone().arrayBuffer());
199
+ const requestDigest = await edgeSha256RequestDigest(body);
200
+ const payload = {
201
+ provider: proof.provider,
202
+ agentId: proof.agentId,
203
+ signature: proof.signature,
204
+ timestamp: proof.timestamp,
205
+ nonce: proof.nonce,
206
+ requestDigest,
207
+ audience: config.audience,
208
+ method: request.method.toUpperCase(),
209
+ url,
210
+ ...(proof.keyId ? { keyId: proof.keyId } : {}),
211
+ };
212
+ try {
213
+ const identity = await config.sdk.verifyAgentIdentity(payload);
214
+ return identity.identityStatus === "verified";
215
+ }
216
+ catch {
217
+ return false;
218
+ }
219
+ };
220
+ }
221
+ // Application-owned wallet proof verification (valiron-wallet-request-v2):
222
+ // the default verifier for ordinary non-ANS agents at the edge.
223
+ var edgeGateVerify_1 = require("./edgeGateVerify");
224
+ Object.defineProperty(exports, "MemoryNonceStore", { enumerable: true, get: function () { return edgeGateVerify_1.MemoryNonceStore; } });
225
+ Object.defineProperty(exports, "base58Decode", { enumerable: true, get: function () { return edgeGateVerify_1.base58Decode; } });
226
+ Object.defineProperty(exports, "base64urlToBytes", { enumerable: true, get: function () { return edgeGateVerify_1.base64urlToBytes; } });
227
+ Object.defineProperty(exports, "buildWalletProofPayload", { enumerable: true, get: function () { return edgeGateVerify_1.buildWalletProofPayload; } });
228
+ Object.defineProperty(exports, "createEdgeWalletProofVerifier", { enumerable: true, get: function () { return edgeGateVerify_1.createEdgeWalletProofVerifier; } });
229
+ Object.defineProperty(exports, "verifyWalletRequestProof", { enumerable: true, get: function () { return edgeGateVerify_1.verifyWalletRequestProof; } });
230
+ Object.defineProperty(exports, "webCryptoSolanaVerifier", { enumerable: true, get: function () { return edgeGateVerify_1.webCryptoSolanaVerifier; } });