@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,495 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Valiron Pass - Cloudflare Worker template.
|
|
3
|
+
*
|
|
4
|
+
* Two recognition modes, selected by PASS_MODE:
|
|
5
|
+
*
|
|
6
|
+
* - "online" (DEFAULT, recommended): every Pass presentation is verified
|
|
7
|
+
* locally AND authorized synchronously by the Valiron API, which re-verifies
|
|
8
|
+
* the token and proof, checks delegation/owner status, and consumes the
|
|
9
|
+
* proof nonce atomically BEFORE the benefit is granted. The API's decision
|
|
10
|
+
* is authoritative: rejections (invalid/revoked/replayed) deny the request,
|
|
11
|
+
* and any API failure fails closed. This is the only mode with pre-access
|
|
12
|
+
* revocation enforcement.
|
|
13
|
+
*
|
|
14
|
+
* - "edge" (bounded-stale, NOT approved for production without an explicit
|
|
15
|
+
* security sign-off): verifies locally from a cached JWKS and grants the
|
|
16
|
+
* benefit immediately; the outcome is reported durably afterwards. A
|
|
17
|
+
* revoked delegation keeps passing until its token expires (up to the
|
|
18
|
+
* token's 300s TTL) and central nonce consumption happens after access.
|
|
19
|
+
* This mode is refused unless PASS_EDGE_UNSAFE_ACK is set to exactly
|
|
20
|
+
* "bounded-stale-verification-accepted".
|
|
21
|
+
*
|
|
22
|
+
* Reporting durability: with PASS_REPORT_QUEUE bound (wrangler.toml), reports
|
|
23
|
+
* go through a Cloudflare Queue with automatic retries and a dead-letter
|
|
24
|
+
* queue - a report is never silently lost. Without a queue, the Worker falls
|
|
25
|
+
* back to a bounded direct retry and logs a console.error on final failure.
|
|
26
|
+
*
|
|
27
|
+
* The Worker forwards a verified, request-bound identity to the origin over
|
|
28
|
+
* headers the origin can trust ONLY because this Worker strips
|
|
29
|
+
* client-supplied copies and the origin is locked to Cloudflare (see
|
|
30
|
+
* README - required trust boundary).
|
|
31
|
+
*/
|
|
32
|
+
import {
|
|
33
|
+
PassEdgeError,
|
|
34
|
+
fetchPassJwks,
|
|
35
|
+
verifyPassProof,
|
|
36
|
+
verifyPassToken,
|
|
37
|
+
type PassJwks,
|
|
38
|
+
} from "@valiron/sdk/edge";
|
|
39
|
+
|
|
40
|
+
export interface Env {
|
|
41
|
+
/** Public origin this Worker fronts, e.g. "https://shop.example.com". */
|
|
42
|
+
PUBLIC_ORIGIN: string;
|
|
43
|
+
/** Valiron Pass JWKS endpoint, e.g. "https://valiron-edge-proxy.onrender.com/card/v1/pass/jwks". */
|
|
44
|
+
VALIRON_PASS_JWKS_URL: string;
|
|
45
|
+
/** Valiron API base for edge outcome reporting. */
|
|
46
|
+
VALIRON_API_BASE: string;
|
|
47
|
+
/** Merchant API credential with the enforcement:write scope (secret). */
|
|
48
|
+
VALIRON_MERCHANT_KEY: string;
|
|
49
|
+
/** Origin must verify this secret on protected routes, or have an equivalent
|
|
50
|
+
* exclusive authenticated path from this Worker. Cloudflare IPs alone do not
|
|
51
|
+
* authenticate a particular Worker. */
|
|
52
|
+
VALIRON_ORIGIN_SECRET?: string;
|
|
53
|
+
/** "online" (default) or "edge". See the header comment. */
|
|
54
|
+
PASS_MODE?: string;
|
|
55
|
+
/** Must equal "bounded-stale-verification-accepted" to enable PASS_MODE=edge. */
|
|
56
|
+
PASS_EDGE_UNSAFE_ACK?: string;
|
|
57
|
+
/** "true" rejects requests without a valid Pass; default passes them through. */
|
|
58
|
+
REQUIRE_PASS?: string;
|
|
59
|
+
/** Fallback per-agent allowance inside the 60-second benefit window, used
|
|
60
|
+
* in explicitly acknowledged edge mode. Online uses the current offer. */
|
|
61
|
+
PASS_RATE_LIMIT_REQUESTS?: string;
|
|
62
|
+
/** Optional id of the offer this route enforces. When set, every report names
|
|
63
|
+
* it (the central endpoint then requires the agent to be eligible for it) and
|
|
64
|
+
* the Worker confirms the outcome with POST /operator/card/v1/agent-visits/:id/enforcement,
|
|
65
|
+
* which is what records the offer's enforcement test in the test environment
|
|
66
|
+
* (the gate for publishing the offer live). Leave unset to enforce the
|
|
67
|
+
* generic benefit without attributing visits to an offer. */
|
|
68
|
+
VALIRON_OFFER_ID?: string;
|
|
69
|
+
/** Test/diagnostic override for replay-record retention in milliseconds
|
|
70
|
+
* (default 150_000). Clamped to a 121_000 ms floor - the longest a proof
|
|
71
|
+
* can stay verifiable after first use - so it cannot shorten production
|
|
72
|
+
* replay protection. */
|
|
73
|
+
PASS_REPLAY_TTL_MS?: string;
|
|
74
|
+
PASS_REPLAY_GUARD: DurableObjectNamespace;
|
|
75
|
+
/** Durable report delivery (edge mode). Bind the queue in wrangler.toml. */
|
|
76
|
+
PASS_REPORT_QUEUE?: Queue;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const EDGE_ACK = "bounded-stale-verification-accepted";
|
|
80
|
+
const REPORT_TIMEOUT_MS = 3_000;
|
|
81
|
+
|
|
82
|
+
let jwksCache: { jwks: PassJwks; at: number } | undefined;
|
|
83
|
+
async function passJwks(env: Env, refresh = false): Promise<PassJwks> {
|
|
84
|
+
if (!refresh && jwksCache && Date.now() - jwksCache.at < 60_000) return jwksCache.jwks;
|
|
85
|
+
const jwks = await fetchPassJwks(env.VALIRON_PASS_JWKS_URL);
|
|
86
|
+
jwksCache = { jwks, at: Date.now() };
|
|
87
|
+
return jwks;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Trusted-header namespace. The origin may trust headers in this namespace
|
|
92
|
+
* ONLY because this Worker removes every client-supplied header under these
|
|
93
|
+
* prefixes and then sets its own (README - required trust boundary). Match
|
|
94
|
+
* whole prefixes, never a fixed name list, so a future x-valiron-pass-* or
|
|
95
|
+
* x-valiron-cf-* field can never be spoofed through by a client. Header
|
|
96
|
+
* names are lowercase in the Headers API.
|
|
97
|
+
*/
|
|
98
|
+
const TRUSTED_HEADER_PREFIXES = ["x-valiron-pass-", "x-valiron-cf-"];
|
|
99
|
+
|
|
100
|
+
function stripClientHeaders(request: Request): Request {
|
|
101
|
+
const headers = new Headers(request.headers);
|
|
102
|
+
// Collect first, then delete: mutating a Headers object while iterating
|
|
103
|
+
// it is not safe across runtimes.
|
|
104
|
+
const strip: string[] = [];
|
|
105
|
+
headers.forEach((_value, name) => {
|
|
106
|
+
if (TRUSTED_HEADER_PREFIXES.some((prefix) => name.startsWith(prefix))) strip.push(name);
|
|
107
|
+
});
|
|
108
|
+
for (const name of strip) headers.delete(name);
|
|
109
|
+
return new Request(request, { headers });
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export default {
|
|
113
|
+
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
|
114
|
+
const token = request.headers.get("x-valiron-card-token");
|
|
115
|
+
const proof = request.headers.get("x-valiron-card-proof");
|
|
116
|
+
if (!token || !proof) {
|
|
117
|
+
if (token || proof || env.REQUIRE_PASS === "true")
|
|
118
|
+
return Response.json({ code: "pass_proof_required" }, { status: 401 });
|
|
119
|
+
return fetch(new Request(stripClientHeaders(request), { redirect: "manual" }));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const mode = env.PASS_MODE ?? "online";
|
|
123
|
+
if (mode === "edge" && env.PASS_EDGE_UNSAFE_ACK !== EDGE_ACK) {
|
|
124
|
+
// Bounded-stale recognition is a security regression from the default;
|
|
125
|
+
// it must be an explicit, documented decision, never a silent fallback.
|
|
126
|
+
return Response.json(
|
|
127
|
+
{ code: "edge_mode_not_acknowledged" },
|
|
128
|
+
{ status: 500 },
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
try {
|
|
133
|
+
// Cloudflare's own bot verdicts (when the zone provides them) are
|
|
134
|
+
// observability only; the Pass proof is the access decision.
|
|
135
|
+
const cf = (request as any).cf?.botManagement;
|
|
136
|
+
|
|
137
|
+
let jwks = await passJwks(env);
|
|
138
|
+
let claims;
|
|
139
|
+
try {
|
|
140
|
+
claims = await verifyPassToken(token, { jwks, audience: env.PUBLIC_ORIGIN });
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (error instanceof PassEdgeError && error.code === "unknown_key") {
|
|
143
|
+
jwks = await passJwks(env, true); // ride key rotation once
|
|
144
|
+
claims = await verifyPassToken(token, { jwks, audience: env.PUBLIC_ORIGIN });
|
|
145
|
+
} else throw error;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const body = ["GET", "HEAD"].includes(request.method)
|
|
149
|
+
? undefined
|
|
150
|
+
: new Uint8Array(await request.clone().arrayBuffer());
|
|
151
|
+
const proofClaims = await verifyPassProof(token, claims, proof, {
|
|
152
|
+
method: request.method,
|
|
153
|
+
url: request.url,
|
|
154
|
+
body,
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
const guard = env.PASS_REPLAY_GUARD.get(env.PASS_REPLAY_GUARD.idFromName(
|
|
158
|
+
`${claims.merchant_id}:${claims.environment}:${claims.sub}:${env.VALIRON_OFFER_ID ?? new URL(request.url).pathname}`,
|
|
159
|
+
));
|
|
160
|
+
// Online authorization resolves the current benefit before the atomic
|
|
161
|
+
// replay/rate claim. No previous request can overwrite this decision.
|
|
162
|
+
let limit = parseInt(env.PASS_RATE_LIMIT_REQUESTS ?? "60", 10);
|
|
163
|
+
let allowed = false;
|
|
164
|
+
// The Pass benefit is a rate limit: enforce it at ONE layer per route.
|
|
165
|
+
// This Worker enforces; configure the origin to skip its own Pass
|
|
166
|
+
// middleware for these routes (README: edge OR origin, never both).
|
|
167
|
+
const report = {
|
|
168
|
+
token, proof,
|
|
169
|
+
request: {
|
|
170
|
+
method: request.method,
|
|
171
|
+
publicUrl: request.url,
|
|
172
|
+
bodyDigest: `sha256:${await sha256Hex(body ?? "")}`,
|
|
173
|
+
requestId: crypto.randomUUID(),
|
|
174
|
+
},
|
|
175
|
+
allowed: mode === "edge" ? false : null,
|
|
176
|
+
...(env.VALIRON_OFFER_ID && mode !== "edge" ? { offerId: env.VALIRON_OFFER_ID } : {}),
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
let confirmVisitId: string | undefined;
|
|
180
|
+
if (mode !== "edge") {
|
|
181
|
+
// Online default: the central endpoint re-verifies the token and
|
|
182
|
+
// proof, checks delegation/owner status, and consumes the proof nonce
|
|
183
|
+
// atomically BEFORE the benefit - its decision is authoritative, and
|
|
184
|
+
// the Worker honors it: rejections deny the request, failures close.
|
|
185
|
+
const decision = await decideReport(env, report);
|
|
186
|
+
if (decision.outcome === "rejected")
|
|
187
|
+
return Response.json({ code: decision.code }, { status: 401 });
|
|
188
|
+
if (decision.outcome === "unavailable") {
|
|
189
|
+
console.error("pass_recognition_unavailable", decision.detail);
|
|
190
|
+
return Response.json({ code: "pass_recognition_unavailable" }, { status: 503 });
|
|
191
|
+
}
|
|
192
|
+
confirmVisitId = decision.visitId;
|
|
193
|
+
const currentLimit = currentOfferLimit(decision.offers, env.VALIRON_OFFER_ID);
|
|
194
|
+
if (currentLimit === undefined)
|
|
195
|
+
return Response.json({ code: "pass_recognition_unavailable" }, { status: 503 });
|
|
196
|
+
limit = currentLimit;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const consume = await guard.fetch(
|
|
200
|
+
`https://guard/consume?jti=${encodeURIComponent(proofClaims.jti)}&default=${limit}`,
|
|
201
|
+
);
|
|
202
|
+
if (consume.status === 409) throw new PassEdgeError("proof_replayed");
|
|
203
|
+
if (consume.status !== 200 && consume.status !== 429)
|
|
204
|
+
return Response.json({ code: "pass_replay_guard_unavailable" }, { status: 503 });
|
|
205
|
+
allowed = consume.status === 200;
|
|
206
|
+
if (mode === "edge") {
|
|
207
|
+
report.allowed = allowed;
|
|
208
|
+
if (env.PASS_REPORT_QUEUE) ctx.waitUntil(env.PASS_REPORT_QUEUE.send(report));
|
|
209
|
+
else ctx.waitUntil(reportWithRetry(env, report));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (!allowed) {
|
|
213
|
+
// The denial is the enforced outcome: record it as such.
|
|
214
|
+
if (confirmVisitId) ctx.waitUntil(confirmWithRetry(env, confirmVisitId, false));
|
|
215
|
+
return Response.json({ code: "quota_exceeded" }, { status: 429, headers: { "Retry-After": "60" } });
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const outbound = stripClientHeaders(request);
|
|
219
|
+
if (env.VALIRON_ORIGIN_SECRET)
|
|
220
|
+
outbound.headers.set("x-valiron-pass-origin-secret", env.VALIRON_ORIGIN_SECRET);
|
|
221
|
+
outbound.headers.set("x-valiron-pass-subject", claims.sub);
|
|
222
|
+
outbound.headers.set("x-valiron-pass-delegation", claims.delegation_id);
|
|
223
|
+
outbound.headers.set("x-valiron-pass-agent", claims.agent_name);
|
|
224
|
+
outbound.headers.set("x-valiron-pass-environment", claims.environment);
|
|
225
|
+
outbound.headers.set("x-valiron-pass-mode", mode === "edge" ? "edge-bounded-stale" : "online-verified");
|
|
226
|
+
if (cf?.verifiedBot === true) outbound.headers.set("x-valiron-cf-verified-bot", "1");
|
|
227
|
+
if (typeof cf?.score === "number") outbound.headers.set("x-valiron-cf-score", String(cf.score));
|
|
228
|
+
const originResponse = await fetch(new Request(outbound, { redirect: "manual" }));
|
|
229
|
+
// Confirm an allowed outcome only after the origin actually answered
|
|
230
|
+
// without a server error. A thrown fetch or 5xx confirms nothing, so a
|
|
231
|
+
// broken origin can never mark the offer's enforcement test as passed.
|
|
232
|
+
if (confirmVisitId) {
|
|
233
|
+
if (originResponse.status < 500) ctx.waitUntil(confirmWithRetry(env, confirmVisitId, true));
|
|
234
|
+
else console.error("pass_enforcement_confirm_skipped", JSON.stringify({ origin_status: originResponse.status }));
|
|
235
|
+
}
|
|
236
|
+
return originResponse;
|
|
237
|
+
} catch (error) {
|
|
238
|
+
const invalid = error instanceof PassEdgeError;
|
|
239
|
+
const code = invalid ? error.code : "pass_verification_unavailable";
|
|
240
|
+
return Response.json({ code }, { status: invalid ? 401 : 503 });
|
|
241
|
+
}
|
|
242
|
+
},
|
|
243
|
+
|
|
244
|
+
/** Queue consumer: durable report delivery for PASS_MODE=edge. A failed
|
|
245
|
+
* delivery retries the message; after max_retries it lands in the
|
|
246
|
+
* dead-letter queue (see wrangler.toml) instead of vanishing. Duplicate
|
|
247
|
+
* deliveries are idempotent (409 = already recorded). */
|
|
248
|
+
async queue(batch: MessageBatch<unknown>, env: Env): Promise<void> {
|
|
249
|
+
for (const message of batch.messages) {
|
|
250
|
+
try {
|
|
251
|
+
await deliverReport(env, message.body);
|
|
252
|
+
message.ack();
|
|
253
|
+
} catch (error) {
|
|
254
|
+
console.error("pass_report_retry", String(error));
|
|
255
|
+
message.retry();
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
type ReportDecision =
|
|
262
|
+
| { outcome: "accepted"; offers?: OfferBenefit[]; visitId?: string }
|
|
263
|
+
| { outcome: "rejected"; code: string }
|
|
264
|
+
| { outcome: "unavailable"; detail: string };
|
|
265
|
+
|
|
266
|
+
interface OfferBenefit {
|
|
267
|
+
id: string;
|
|
268
|
+
benefit?: { type?: string; requests?: number; windowSeconds?: number };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** The current eligible per-window allowance across the decision's offers
|
|
272
|
+
* (rate_limit benefits only). Undefined when the endpoint returned no offers
|
|
273
|
+
* field - online mode fails closed on this contract violation. */
|
|
274
|
+
function currentOfferLimit(offers: OfferBenefit[] | undefined, offerId?: string): number | undefined {
|
|
275
|
+
if (!Array.isArray(offers)) return undefined;
|
|
276
|
+
const limits = offers
|
|
277
|
+
.filter((o) => !offerId || o.id === offerId)
|
|
278
|
+
.map((o) => o?.benefit)
|
|
279
|
+
.filter((b) => b?.type === "rate_limit" && Number.isSafeInteger(b?.requests) && (b.requests as number) > 0)
|
|
280
|
+
.map((b) => b.requests as number);
|
|
281
|
+
return limits.length ? Math.max(...limits) : 0; // empty offers: no current benefit
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Online path: the endpoint's answer is the authorization decision. 2xx is
|
|
285
|
+
* accepted only with the contract body `{ ok: true }`; 401/403 reject the
|
|
286
|
+
* pass itself; 409 means the proof nonce was already consumed (replay);
|
|
287
|
+
* anything else is an availability failure. */
|
|
288
|
+
async function decideReport(env: Env, body: unknown): Promise<ReportDecision> {
|
|
289
|
+
let response: Response;
|
|
290
|
+
try {
|
|
291
|
+
response = await postReport(env, body);
|
|
292
|
+
} catch (error) {
|
|
293
|
+
return { outcome: "unavailable", detail: String(error) };
|
|
294
|
+
}
|
|
295
|
+
if (response.status === 409) return { outcome: "rejected", code: "proof_replayed" };
|
|
296
|
+
if (response.status === 401 || response.status === 403 || response.status === 400) {
|
|
297
|
+
const code = await readErrorCode(response);
|
|
298
|
+
return { outcome: "rejected", code: code ?? "pass_rejected" };
|
|
299
|
+
}
|
|
300
|
+
if (!response.ok) return { outcome: "unavailable", detail: `report_status:${response.status}` };
|
|
301
|
+
const data = await response.json().catch(() => undefined);
|
|
302
|
+
if ((data as { ok?: boolean } | undefined)?.ok !== true) {
|
|
303
|
+
return { outcome: "unavailable", detail: "report_contract_violation" };
|
|
304
|
+
}
|
|
305
|
+
const visitId = (data as { visitId?: unknown }).visitId;
|
|
306
|
+
return {
|
|
307
|
+
outcome: "accepted",
|
|
308
|
+
offers: (data as { offers?: OfferBenefit[] }).offers,
|
|
309
|
+
visitId: typeof visitId === "string" ? visitId : undefined,
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function readErrorCode(response: Response): Promise<string | undefined> {
|
|
314
|
+
const data = await response.json().catch(() => undefined);
|
|
315
|
+
const code = (data as { code?: unknown } | undefined)?.code;
|
|
316
|
+
return typeof code === "string" && /^[a-z0-9_]{1,64}$/.test(code) ? code : undefined;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Report-only delivery (edge mode / queue consumer). 2xx with `{ ok: true }`
|
|
320
|
+
* is delivered; 409 is ALSO delivered - the nonce is already consumed and the
|
|
321
|
+
* visit recorded, so a duplicate delivery (queue retry after a lost response)
|
|
322
|
+
* must not retry forever. Anything else throws for retry. */
|
|
323
|
+
async function deliverReport(env: Env, body: unknown): Promise<void> {
|
|
324
|
+
const response = await postReport(env, body);
|
|
325
|
+
if (response.status === 409) return;
|
|
326
|
+
if (!response.ok) throw new Error(`report_rejected:${response.status}`);
|
|
327
|
+
const data = await response.json().catch(() => undefined);
|
|
328
|
+
if ((data as { ok?: boolean } | undefined)?.ok !== true) {
|
|
329
|
+
throw new Error("report_contract_violation");
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** Confirm the enforcement outcome of an accepted visit against the offer named
|
|
334
|
+
* by VALIRON_OFFER_ID. Idempotent for the same outcome and offer, and the visit
|
|
335
|
+
* must be under 60 seconds old, so this runs right after the decision. It
|
|
336
|
+
* never changes the response already decided for the request. Network errors,
|
|
337
|
+
* 408, 429 and 5xx retry with the same bounded backoff as report delivery;
|
|
338
|
+
* other 4xx statuses are final. A dropped confirmation is logged, never silent. */
|
|
339
|
+
async function confirmWithRetry(env: Env, visitId: string, allowed: boolean, attempts = 3): Promise<void> {
|
|
340
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
341
|
+
let detail: string;
|
|
342
|
+
let retryable = true;
|
|
343
|
+
try {
|
|
344
|
+
const response = await fetch(
|
|
345
|
+
`${env.VALIRON_API_BASE}/operator/card/v1/agent-visits/${encodeURIComponent(visitId)}/enforcement`,
|
|
346
|
+
{
|
|
347
|
+
method: "POST",
|
|
348
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${env.VALIRON_MERCHANT_KEY}` },
|
|
349
|
+
body: JSON.stringify({ offerId: env.VALIRON_OFFER_ID, allowed }),
|
|
350
|
+
signal: AbortSignal.timeout(REPORT_TIMEOUT_MS),
|
|
351
|
+
},
|
|
352
|
+
);
|
|
353
|
+
if (response.ok) return;
|
|
354
|
+
detail = `status:${response.status}`;
|
|
355
|
+
retryable = response.status === 408 || response.status === 429 || response.status >= 500;
|
|
356
|
+
} catch (error) {
|
|
357
|
+
detail = String(error);
|
|
358
|
+
}
|
|
359
|
+
if (!retryable || attempt === attempts) {
|
|
360
|
+
console.error("pass_enforcement_confirm_dropped", JSON.stringify({ attempts: attempt, detail }));
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
await new Promise((resolve) => setTimeout(resolve, 250 * attempt));
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** One central report call with a hard timeout. */
|
|
368
|
+
async function postReport(env: Env, body: unknown): Promise<Response> {
|
|
369
|
+
return fetch(`${env.VALIRON_API_BASE}/operator/card/v1/agent-visits/local`, {
|
|
370
|
+
method: "POST",
|
|
371
|
+
headers: {
|
|
372
|
+
"content-type": "application/json",
|
|
373
|
+
authorization: `Bearer ${env.VALIRON_MERCHANT_KEY}`,
|
|
374
|
+
},
|
|
375
|
+
body: JSON.stringify(body),
|
|
376
|
+
signal: AbortSignal.timeout(REPORT_TIMEOUT_MS),
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Direct-delivery fallback when no queue is bound: bounded retries, then a
|
|
381
|
+
* loud console.error (visible in Workers Logs / Logpush) - never a silent
|
|
382
|
+
* swallow. A delayed report is NOT pre-access revocation enforcement; bind
|
|
383
|
+
* PASS_REPORT_QUEUE or use PASS_MODE=online. */
|
|
384
|
+
async function reportWithRetry(env: Env, body: unknown, attempts = 3): Promise<void> {
|
|
385
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
386
|
+
try {
|
|
387
|
+
await deliverReport(env, body);
|
|
388
|
+
return;
|
|
389
|
+
} catch (error) {
|
|
390
|
+
if (attempt === attempts) {
|
|
391
|
+
console.error("pass_report_dropped", JSON.stringify({ attempts, error: String(error) }));
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
await new Promise((resolve) => setTimeout(resolve, 250 * attempt));
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
async function sha256Hex(value: Uint8Array | string): Promise<string> {
|
|
400
|
+
const digest = await crypto.subtle.digest(
|
|
401
|
+
"SHA-256",
|
|
402
|
+
typeof value === "string" ? new TextEncoder().encode(value) : value,
|
|
403
|
+
);
|
|
404
|
+
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** One Durable Object per delegation thumbprint: strongly consistent jti
|
|
408
|
+
* consumption AND benefit rate counting, so a captured proof cannot be
|
|
409
|
+
* replayed and the per-window allowance holds across isolates and colos.
|
|
410
|
+
* Each consume call carries the current online decision's limit (or the
|
|
411
|
+
* static edge-mode limit). Limits are never stored between requests, so
|
|
412
|
+
* concurrent requests cannot overwrite each other's offer policy.
|
|
413
|
+
*
|
|
414
|
+
* Durable Object storage has no TTL option, so expiry is explicit. Every
|
|
415
|
+
* replay/rate record carries an `exp` timestamp; expired records are swept
|
|
416
|
+
* on that agent's next consume, which keeps storage bounded for ACTIVE
|
|
417
|
+
* agents. This is not timed eviction: a gone agent's last records remain
|
|
418
|
+
* until it returns (they can never be re-admitted, only swept).
|
|
419
|
+
*
|
|
420
|
+
* Retention must exceed the longest time a proof stays verifiable after its
|
|
421
|
+
* first presentation, or an expiring record could re-admit a still-valid
|
|
422
|
+
* proof. Per verifyPassProof (src/edge.ts): a proof verifies while
|
|
423
|
+
* now <= exp, exp - iat <= 60s, and iat may be up to 60s in the future, so
|
|
424
|
+
* the worst case is 120s + 1s integer-second inclusivity. The floor is
|
|
425
|
+
* 121s; the default 150s adds a clock-skew margin. PASS_REPLAY_TTL_MS is
|
|
426
|
+
* clamped to the floor, so the test/diagnostic override cannot shorten
|
|
427
|
+
* production replay protection. */
|
|
428
|
+
const PROOF_MAX_VERIFIABLE_MS = 121_000;
|
|
429
|
+
const DEFAULT_REPLAY_TTL_MS = 150_000;
|
|
430
|
+
const RATE_WINDOW_MS = 60_000;
|
|
431
|
+
|
|
432
|
+
interface ExpiringRecord {
|
|
433
|
+
value: number;
|
|
434
|
+
exp: number;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
export class ReplayGuard implements DurableObject {
|
|
438
|
+
constructor(private state: DurableObjectState, private env: Env) {}
|
|
439
|
+
|
|
440
|
+
private replayTtlMs(): number {
|
|
441
|
+
const parsed = parseInt(this.env.PASS_REPLAY_TTL_MS ?? "", 10);
|
|
442
|
+
if (!Number.isSafeInteger(parsed) || parsed <= 0) return DEFAULT_REPLAY_TTL_MS;
|
|
443
|
+
return Math.max(parsed, PROOF_MAX_VERIFIABLE_MS);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
async fetch(request: Request): Promise<Response> {
|
|
447
|
+
const url = new URL(request.url);
|
|
448
|
+
const jti = url.searchParams.get("jti");
|
|
449
|
+
if (!jti || jti.length > 128) return new Response(null, { status: 400 });
|
|
450
|
+
const now = Date.now();
|
|
451
|
+
const ttl = this.replayTtlMs();
|
|
452
|
+
const fallbackLimit = parseInt(url.searchParams.get("default") ?? "60", 10);
|
|
453
|
+
|
|
454
|
+
if (!Number.isSafeInteger(fallbackLimit) || fallbackLimit < 0 || fallbackLimit > 100000)
|
|
455
|
+
return new Response(null, { status: 400 });
|
|
456
|
+
|
|
457
|
+
// One storage transaction: the jti check-and-claim, the stale sweep and
|
|
458
|
+
// the rate-window increment commit atomically (the closure is retried
|
|
459
|
+
// whole on a write conflict), so simultaneous requests cannot
|
|
460
|
+
// double-spend a proof or the per-window allowance.
|
|
461
|
+
const outcome = await this.state.storage.transaction(async (txn) => {
|
|
462
|
+
// Delete expired nonces as well as rate windows; unique proof IDs
|
|
463
|
+
// otherwise accumulate forever even for active agents.
|
|
464
|
+
const nonces = await txn.list<ExpiringRecord>({ prefix: "jti:" });
|
|
465
|
+
const expired = [...nonces].filter(([, record]) => record.exp <= now).map(([key]) => key);
|
|
466
|
+
if (expired.length) await txn.delete(expired);
|
|
467
|
+
const jtiKey = `jti:${jti}`;
|
|
468
|
+
const seen = await txn.get<ExpiringRecord>(jtiKey);
|
|
469
|
+
if (seen && typeof seen.exp === "number" && seen.exp > now) return "replay" as const;
|
|
470
|
+
// Expired record: sweep it and re-claim. Only reachable once the proof
|
|
471
|
+
// itself is unverifiable, because retention exceeds proof validity.
|
|
472
|
+
if (seen) await txn.delete(jtiKey);
|
|
473
|
+
await txn.put(jtiKey, { value: now, exp: now + ttl } satisfies ExpiringRecord);
|
|
474
|
+
|
|
475
|
+
const limit = fallbackLimit;
|
|
476
|
+
const window = Math.floor(now / RATE_WINDOW_MS);
|
|
477
|
+
const windowKey = `rate:w:${window}`;
|
|
478
|
+
const windowExp = (window + 1) * RATE_WINDOW_MS + ttl;
|
|
479
|
+
let count = 0;
|
|
480
|
+
const stale: string[] = [];
|
|
481
|
+
const windows = await txn.list<ExpiringRecord>({ prefix: "rate:w:" });
|
|
482
|
+
for (const [key, record] of windows) {
|
|
483
|
+
if (!record || typeof record.exp !== "number" || record.exp <= now) stale.push(key);
|
|
484
|
+
else if (key === windowKey) count = record.value;
|
|
485
|
+
}
|
|
486
|
+
if (stale.length > 0) await txn.delete(stale);
|
|
487
|
+
count += 1;
|
|
488
|
+
await txn.put(windowKey, { value: count, exp: windowExp } satisfies ExpiringRecord);
|
|
489
|
+
return (count > limit ? "limited" : "ok") as const;
|
|
490
|
+
});
|
|
491
|
+
if (outcome === "replay") return new Response(null, { status: 409 });
|
|
492
|
+
if (outcome === "limited") return new Response(null, { status: 429 });
|
|
493
|
+
return new Response(null, { status: 200 });
|
|
494
|
+
}
|
|
495
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
name = "valiron-pass-edge"
|
|
2
|
+
main = "worker.ts"
|
|
3
|
+
compatibility_date = "2026-11-14"
|
|
4
|
+
|
|
5
|
+
[vars]
|
|
6
|
+
PUBLIC_ORIGIN = "https://shop.example.com"
|
|
7
|
+
# Replace with your Valiron API host. https://api.valiron.co is a placeholder that does not resolve yet.
|
|
8
|
+
VALIRON_PASS_JWKS_URL = "https://valiron-edge-proxy.onrender.com/card/v1/pass/jwks"
|
|
9
|
+
VALIRON_API_BASE = "https://valiron-edge-proxy.onrender.com"
|
|
10
|
+
REQUIRE_PASS = "false"
|
|
11
|
+
# Static per-agent allowance per 60s window in acknowledged edge mode only.
|
|
12
|
+
# Online mode uses the current eligible offer on every request.
|
|
13
|
+
PASS_RATE_LIMIT_REQUESTS = "60"
|
|
14
|
+
# Test/diagnostic only: replay-record retention in ms (default 150000).
|
|
15
|
+
# Clamped to a 121000 ms floor (the longest a proof stays verifiable after
|
|
16
|
+
# first use), so it cannot shorten production replay protection.
|
|
17
|
+
# PASS_REPLAY_TTL_MS = "150000"
|
|
18
|
+
# Optional: tie this Worker to one merchant offer so enforcement is confirmed
|
|
19
|
+
# centrally (needed before that offer can be published live). Agents not eligible
|
|
20
|
+
# for the offer get 403 visit_or_offer_invalid and are denied. Unset = no change.
|
|
21
|
+
# VALIRON_OFFER_ID = "<offer id>"
|
|
22
|
+
# "online" (default): the Valiron API authorizes each Pass synchronously
|
|
23
|
+
# (re-verifies token+proof, checks revocation, consumes the nonce) BEFORE the
|
|
24
|
+
# benefit, and any failure fails closed. "edge" is bounded-stale (revocation
|
|
25
|
+
# lags up to the token TTL) and is refused unless you also set
|
|
26
|
+
# PASS_EDGE_UNSAFE_ACK below - see worker.ts.
|
|
27
|
+
PASS_MODE = "online"
|
|
28
|
+
# PASS_MODE = "edge"
|
|
29
|
+
# PASS_EDGE_UNSAFE_ACK = "bounded-stale-verification-accepted"
|
|
30
|
+
|
|
31
|
+
# wrangler secret put VALIRON_MERCHANT_KEY
|
|
32
|
+
# wrangler secret put VALIRON_ORIGIN_SECRET # verify x-valiron-pass-origin-secret at protected origin routes
|
|
33
|
+
|
|
34
|
+
# Durable report delivery for PASS_MODE=edge (Cloudflare retries failed
|
|
35
|
+
# reports; poison messages land in the dead-letter queue). Create once:
|
|
36
|
+
# wrangler queues create valiron-pass-reports
|
|
37
|
+
# wrangler queues create valiron-pass-reports-dlq
|
|
38
|
+
[[queues.producers]]
|
|
39
|
+
binding = "PASS_REPORT_QUEUE"
|
|
40
|
+
queue = "valiron-pass-reports"
|
|
41
|
+
|
|
42
|
+
[[queues.consumers]]
|
|
43
|
+
queue = "valiron-pass-reports"
|
|
44
|
+
max_retries = 5
|
|
45
|
+
dead_letter_queue = "valiron-pass-reports-dlq"
|
|
46
|
+
|
|
47
|
+
# Workers Static Assets / routes: attach this Worker only to the routes where
|
|
48
|
+
# the Pass benefit applies, and disable the origin Pass middleware there.
|
|
49
|
+
|
|
50
|
+
[[durable_objects.bindings]]
|
|
51
|
+
name = "PASS_REPLAY_GUARD"
|
|
52
|
+
class_name = "ReplayGuard"
|
|
53
|
+
|
|
54
|
+
[[migrations]]
|
|
55
|
+
tag = "v1"
|
|
56
|
+
new_sqlite_classes = ["ReplayGuard"]
|
|
57
|
+
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@valiron/sdk",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Official TypeScript SDK for Valiron
|
|
3
|
+
"version": "2.1.0",
|
|
4
|
+
"description": "Official TypeScript SDK for Valiron agent identity and API protection",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "https://github.com/vatsashah45/Valiron.git",
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"clean": "node -e \"const fs=require('fs');fs.rmSync('dist',{recursive:true,force:true});\"",
|
|
21
21
|
"build": "pnpm clean && tsc",
|
|
22
22
|
"dev": "tsc --watch",
|
|
23
|
-
"test": "node test/validate-telemetry.mjs && node test/validate.mjs && node test/validate-examples.mjs && node test/validate-middleware.mjs && node test/validate-provider-identity.mjs && node --import tsx test/test-identity.ts",
|
|
23
|
+
"test": "node test/validate-telemetry.mjs && node test/validate.mjs && node test/validate-examples.mjs && node test/validate-middleware.mjs && node test/validate-provider-identity.mjs && node --import tsx test/test-identity.ts && node test/validate-security.mjs && node test/validate-edge-gate.mjs && node test/validate-edge-package.mjs && node test/validate-edge.mjs",
|
|
24
24
|
"prepublishOnly": "pnpm build"
|
|
25
25
|
},
|
|
26
26
|
"keywords": [
|
|
@@ -40,14 +40,38 @@
|
|
|
40
40
|
"typescript": "^5.9.3"
|
|
41
41
|
},
|
|
42
42
|
"exports": {
|
|
43
|
+
"./edge-gate": {
|
|
44
|
+
"types": "./dist/edgeGate.d.ts",
|
|
45
|
+
"default": "./dist/edgeGate.js"
|
|
46
|
+
},
|
|
47
|
+
"./pass": {
|
|
48
|
+
"types": "./dist/card.d.ts",
|
|
49
|
+
"default": "./dist/card.js"
|
|
50
|
+
},
|
|
51
|
+
"./card": {
|
|
52
|
+
"types": "./dist/card.d.ts",
|
|
53
|
+
"default": "./dist/card.js"
|
|
54
|
+
},
|
|
43
55
|
".": {
|
|
44
56
|
"types": "./dist/index.d.ts",
|
|
45
57
|
"default": "./dist/index.js"
|
|
58
|
+
},
|
|
59
|
+
"./edge": {
|
|
60
|
+
"types": "./dist/edge.d.ts",
|
|
61
|
+
"default": "./dist/edge.js"
|
|
46
62
|
}
|
|
47
63
|
},
|
|
48
64
|
"files": [
|
|
65
|
+
"dist/card.js",
|
|
66
|
+
"dist/card.d.ts",
|
|
67
|
+
"bin/valiron-card.mjs",
|
|
49
68
|
"dist/clients.js",
|
|
50
69
|
"dist/clients.d.ts",
|
|
70
|
+
"dist/edgeGate.js",
|
|
71
|
+
"dist/edgeGate.d.ts",
|
|
72
|
+
"dist/edgeGateVerify.js",
|
|
73
|
+
"dist/edgeGateVerify.d.ts",
|
|
74
|
+
"examples/cloudflare-gate-worker",
|
|
51
75
|
"dist/identity.js",
|
|
52
76
|
"dist/identity.d.ts",
|
|
53
77
|
"dist/identityMiddleware.js",
|
|
@@ -64,6 +88,12 @@
|
|
|
64
88
|
"dist/types.d.ts",
|
|
65
89
|
"docs/*.md",
|
|
66
90
|
"docs/llms.txt",
|
|
67
|
-
"README.md"
|
|
68
|
-
|
|
91
|
+
"README.md",
|
|
92
|
+
"dist/edge.js",
|
|
93
|
+
"dist/edge.d.ts",
|
|
94
|
+
"examples/cloudflare-worker/worker.ts",
|
|
95
|
+
"examples/cloudflare-worker/wrangler.toml",
|
|
96
|
+
"examples/cloudflare-worker/package.json"
|
|
97
|
+
],
|
|
98
|
+
"bin": { "valiron-card": "bin/valiron-card.mjs", "valiron-pass": "bin/valiron-card.mjs" }
|
|
69
99
|
}
|
package/docs/MCP.md
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
# Valiron MCP Server
|
|
2
|
-
|
|
3
|
-
Connect your MCP client to **https://www.valiron.co/mcp** with **Streamable HTTP** transport. This public server requires no API key. Use the canonical `www` URL directly to avoid redirects during POST requests.
|
|
4
|
-
|
|
5
|
-
For clients that accept a remote server configuration:
|
|
6
|
-
|
|
7
|
-
```json
|
|
8
|
-
{
|
|
9
|
-
"mcpServers": {
|
|
10
|
-
"valiron": {
|
|
11
|
-
"url": "https://www.valiron.co/mcp"
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
```
|
|
16
|
-
|
|
17
|
-
Client configuration formats vary; select Streamable HTTP when your client asks for the transport.
|
|
18
|
-
|
|
19
|
-
## Tools
|
|
20
|
-
|
|
21
|
-
| Tool | Input | Result |
|
|
22
|
-
| --- | --- | --- |
|
|
23
|
-
| `get_api_health` | `{}` | Live Valiron API health, supported chains, and default chain |
|
|
24
|
-
| `get_agent_profile` | `{"agentId":"42","chain":"ethereum"}` | Allowlisted identity and trust summary for a registered ERC-8004 or Solana agent |
|
|
25
|
-
| `get_integration_docs` | `{"topic":"quickstart"}` | Valiron documentation; topics: `quickstart`, `api`, `identity`, `integration`, `errors` |
|
|
26
|
-
|
|
27
|
-
The `https://www.valiron.co/api` MCP resource also lists developer links. Profile lookups do not grant access, verify the caller's identity, or run new sandbox tests. MCP exposes public reads only; operator keys, paid signals, account changes, sandbox execution, and access decisions use the [REST API](./API-REFERENCE.md) or SDK. Never put operator secrets in tool arguments.
|
|
28
|
-
|
|
29
|
-
## Transport
|
|
30
|
-
|
|
31
|
-
The server uses stateless Streamable HTTP with JSON responses. POST MCP JSON-RPC messages with `Content-Type: application/json` and `Accept: application/json, text/event-stream`. It does not assign session IDs or offer a persistent GET event stream; GET and DELETE return 405. The SDK negotiates supported protocol versions during initialization.
|
|
32
|
-
|
|
33
|
-
```sh
|
|
34
|
-
curl https://www.valiron.co/mcp \
|
|
35
|
-
-H 'Content-Type: application/json' \
|
|
36
|
-
-H 'Accept: application/json, text/event-stream' \
|
|
37
|
-
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"example","version":"1.0.0"}}}'
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
Requests are limited to 16 KiB. Process-local admission limits allow 120 requests per minute and 8 concurrent requests per instance; a 429 includes `Retry-After`. Upstream calls time out after 10 seconds and responses are limited to 256 KiB. API failures are returned as MCP tool errors. Browser requests with an Origin header must originate from `https://www.valiron.co` or `https://valiron.co`; server-to-server clients can omit Origin.
|
|
41
|
-
|
|
42
|
-
## Other interfaces
|
|
43
|
-
|
|
44
|
-
- [Valiron developer portal](https://www.valiron.co/developers)
|
|
45
|
-
- [Valiron OpenAPI specification](https://www.valiron.co/openapi.json)
|
|
46
|
-
- [Valiron authentication](https://www.valiron.co/auth.md)
|
|
47
|
-
- [Valiron API discovery](https://www.valiron.co/api)
|
|
48
|
-
- [Valiron MCP discovery metadata](https://www.valiron.co/.well-known/mcp.json)
|
|
49
|
-
|
|
50
|
-
The profile tool strips behavioral metrics, evidence storage links, RPC URLs, and provider verification metadata even if an older upstream API returns them.
|