@kya-os/verifier 1.3.4-canary.9 → 1.4.1

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/worker.js DELETED
@@ -1,302 +0,0 @@
1
- import { VerifierCore } from "./core.js";
2
- /**
3
- * Extract proof from Cloudflare Worker request
4
- */
5
- async function extractProofFromRequest(request) {
6
- try {
7
- // Try to get proof from X-XMCP-I-Proof header
8
- const proofHeader = request.headers.get("X-XMCP-I-Proof");
9
- if (proofHeader) {
10
- return JSON.parse(proofHeader);
11
- }
12
- // Try to get proof from request body if it's a POST/PUT
13
- if (request.method === "POST" || request.method === "PUT") {
14
- const contentType = request.headers.get("content-type");
15
- if (contentType?.includes("application/json")) {
16
- const body = (await request.clone().json());
17
- if (body?.meta?.proof) {
18
- return body.meta.proof;
19
- }
20
- }
21
- }
22
- return null;
23
- }
24
- catch (error) {
25
- console.warn("Failed to extract proof from request:", error);
26
- return null;
27
- }
28
- }
29
- /**
30
- * Extract audience from request
31
- */
32
- function extractAudienceFromRequest(request) {
33
- const url = new URL(request.url);
34
- return url.host;
35
- }
36
- /**
37
- * Safely parse environment integer with bounds validation
38
- * Prevents NaN bypass attacks where parseInt returns NaN and disables validators
39
- */
40
- function parseEnvInt(value, defaultValue, min, max) {
41
- if (!value)
42
- return defaultValue;
43
- const parsed = parseInt(value, 10);
44
- // Reject NaN to prevent bypass attacks
45
- if (isNaN(parsed)) {
46
- console.warn(`Invalid integer env value: ${value}, using default: ${defaultValue}`);
47
- return defaultValue;
48
- }
49
- // Clamp to safe bounds
50
- if (parsed < min) {
51
- console.warn(`Env value ${parsed} below minimum ${min}, using minimum`);
52
- return min;
53
- }
54
- if (parsed > max) {
55
- console.warn(`Env value ${parsed} above maximum ${max}, using maximum`);
56
- return max;
57
- }
58
- return parsed;
59
- }
60
- /**
61
- * Create verifier config from Worker environment
62
- *
63
- * @param env - Worker environment bindings
64
- * @param overrides - Optional config overrides
65
- * @returns WorkerVerifierConfig
66
- */
67
- export function createConfigFromEnv(env, overrides) {
68
- return {
69
- ktaBaseUrl: env.KYA_API_URL || "https://knowthat.ai",
70
- enableDelegationCheck: true,
71
- clockSkewTolerance: parseEnvInt(env.XMCP_I_TS_SKEW_SEC, 120, 0, 3600),
72
- sessionTimeout: parseEnvInt(env.XMCP_I_SESSION_TTL, 1800, 60, 86400),
73
- proofMaxAge: parseEnvInt(env.PROOF_MAX_AGE_SEC, 300, 60, 3600),
74
- kvNamespace: env.NONCE_CACHE,
75
- nonceTtl: 1800,
76
- ...overrides,
77
- };
78
- }
79
- /**
80
- * Cached config to avoid parsing env on every request
81
- */
82
- let cachedConfig = null;
83
- let cachedEnvSignature = null;
84
- /**
85
- * Create a signature from env to detect changes
86
- */
87
- function getEnvSignature(env) {
88
- return [
89
- env.KYA_API_URL || "",
90
- env.XMCP_I_TS_SKEW_SEC || "",
91
- env.XMCP_I_SESSION_TTL || "",
92
- env.PROOF_MAX_AGE_SEC || "",
93
- ].join("|");
94
- }
95
- /**
96
- * Get or create config from env with caching
97
- * Caches config per worker instance to avoid parsing env on every request
98
- */
99
- function getConfigFromEnv(env, overrides) {
100
- const signature = getEnvSignature(env);
101
- // Return cached config if env hasn't changed
102
- if (cachedConfig && cachedEnvSignature === signature && !overrides) {
103
- return cachedConfig;
104
- }
105
- // Parse env and cache result
106
- const config = createConfigFromEnv(env, overrides);
107
- if (!overrides) {
108
- cachedConfig = config;
109
- cachedEnvSignature = signature;
110
- }
111
- return config;
112
- }
113
- /**
114
- * Cloudflare Worker verifier function
115
- *
116
- * Usage with environment bindings:
117
- * ```typescript
118
- * export default {
119
- * async fetch(request: Request, env: WorkerEnv): Promise<Response> {
120
- * // Config is automatically cached per worker instance
121
- * const result = await verifyWorker(request, env);
122
- *
123
- * if (!result.success) {
124
- * return applyVerificationToResponse(result);
125
- * }
126
- *
127
- * // Continue with verified request...
128
- * }
129
- * }
130
- * ```
131
- *
132
- * @param request - The incoming request
133
- * @param envOrConfig - Worker environment or verifier configuration
134
- * @returns Promise<VerifierResult> - Verification result with headers or error
135
- */
136
- export async function verifyWorker(request, envOrConfig) {
137
- try {
138
- // Resolve config from env or use provided config (with caching)
139
- let config;
140
- if (!envOrConfig) {
141
- throw new Error("Either env or config must be provided");
142
- }
143
- else if ("kvNamespace" in envOrConfig || "ktaBaseUrl" in envOrConfig || "enableDelegationCheck" in envOrConfig) {
144
- // It's already a WorkerVerifierConfig
145
- config = envOrConfig;
146
- }
147
- else {
148
- // It's a WorkerEnv, use cached config
149
- config = getConfigFromEnv(envOrConfig);
150
- }
151
- // Extract proof from request
152
- const proof = await extractProofFromRequest(request);
153
- if (!proof) {
154
- return {
155
- success: false,
156
- error: {
157
- code: "XMCP_I_ENOIDENTITY",
158
- message: "No proof found in request",
159
- httpStatus: 401,
160
- details: {
161
- reason: "Request must include proof in X-XMCP-I-Proof header or request body",
162
- remediation: "Ensure XMCP-I client is properly configured",
163
- },
164
- },
165
- };
166
- }
167
- // Extract audience from request
168
- const audience = extractAudienceFromRequest(request);
169
- // Create verifier and verify proof
170
- const verifier = new VerifierCore(config);
171
- const result = await verifier.verify({
172
- proof,
173
- audience,
174
- timestamp: Math.floor(Date.now() / 1000),
175
- });
176
- return result;
177
- }
178
- catch (error) {
179
- return {
180
- success: false,
181
- error: {
182
- code: "XMCP_I_EVERIFY",
183
- message: error instanceof Error ? error.message : "Verification failed",
184
- httpStatus: 500,
185
- details: {
186
- reason: "Unexpected error during Worker verification",
187
- remediation: "Check request format and try again",
188
- },
189
- },
190
- };
191
- }
192
- }
193
- /**
194
- * Cloudflare Worker middleware factory
195
- *
196
- * Creates a middleware function that can be used in Worker request handlers
197
- *
198
- * @param config - Optional verifier configuration
199
- * @returns Middleware function
200
- */
201
- export function createWorkerMiddleware(config) {
202
- return async (request) => {
203
- return verifyWorker(request, config);
204
- };
205
- }
206
- /**
207
- * Helper to apply verification result to a Response
208
- *
209
- * @param result - Verification result
210
- * @param response - Response to modify
211
- * @returns Modified response with headers or error response
212
- */
213
- export function applyVerificationToResponse(result, response) {
214
- if (!result.success) {
215
- return new Response(JSON.stringify({
216
- code: result.error.code,
217
- message: result.error.message,
218
- details: result.error.details,
219
- }), {
220
- status: result.error.httpStatus,
221
- headers: {
222
- "Content-Type": "application/json",
223
- },
224
- });
225
- }
226
- // Apply headers to existing response or create new one
227
- const headers = new Headers(response?.headers);
228
- if (result.headers) {
229
- Object.entries(result.headers).forEach(([key, value]) => {
230
- headers.set(key, value);
231
- });
232
- }
233
- if (response) {
234
- return new Response(response.body, {
235
- status: response.status,
236
- statusText: response.statusText,
237
- headers,
238
- });
239
- }
240
- return new Response(null, { status: 200, headers });
241
- }
242
- /**
243
- * Complete example with environment bindings and KV nonce cache
244
- *
245
- * wrangler.toml:
246
- * ```toml
247
- * name = "my-mcp-verifier"
248
- * main = "src/index.ts"
249
- * compatibility_date = "2024-01-01"
250
- *
251
- * [[kv_namespaces]]
252
- * binding = "NONCE_CACHE"
253
- * id = "your-kv-namespace-id"
254
- *
255
- * [vars]
256
- * KYA_API_URL = "https://knowthat.ai"
257
- * ```
258
- *
259
- * src/index.ts:
260
- * ```typescript
261
- * import { verifyWorker, applyVerificationToResponse, type WorkerEnv } from "@kya-os/verifier/worker";
262
- *
263
- * export default {
264
- * async fetch(request: Request, env: WorkerEnv): Promise<Response> {
265
- * // Pass env directly - config is automatically cached per worker instance
266
- * const result = await verifyWorker(request, env);
267
- *
268
- * if (!result.success) {
269
- * return applyVerificationToResponse(result);
270
- * }
271
- *
272
- * // Access verified agent context
273
- * const agentDID = result.agentContext?.did;
274
- * const agentScopes = result.agentContext?.scopes || [];
275
- *
276
- * // Continue with verified request
277
- * const response = new Response(JSON.stringify({
278
- * message: "Verified!",
279
- * agent: result.agentContext
280
- * }), {
281
- * headers: { "Content-Type": "application/json" }
282
- * });
283
- *
284
- * // Add verification headers to response
285
- * return applyVerificationToResponse(result, response);
286
- * }
287
- * }
288
- * ```
289
- *
290
- * Deploy:
291
- * ```bash
292
- * # Create KV namespace
293
- * wrangler kv:namespace create NONCE_CACHE
294
- *
295
- * # Add secrets
296
- * wrangler secret put KYA_VOUCHED_API_KEY
297
- *
298
- * # Deploy
299
- * wrangler deploy
300
- * ```
301
- */
302
- //# sourceMappingURL=worker.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"worker.js","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAuB,MAAM,WAAW,CAAC;AAqD9D;;GAEG;AACH,KAAK,UAAU,uBAAuB,CACpC,OAAgB;IAEhB,IAAI,CAAC;QACH,8CAA8C;QAC9C,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;QAC1D,IAAI,WAAW,EAAE,CAAC;YAChB,OAAO,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QACjC,CAAC;QAED,wDAAwD;QACxD,IAAI,OAAO,CAAC,MAAM,KAAK,MAAM,IAAI,OAAO,CAAC,MAAM,KAAK,KAAK,EAAE,CAAC;YAC1D,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;YACxD,IAAI,WAAW,EAAE,QAAQ,CAAC,kBAAkB,CAAC,EAAE,CAAC;gBAC9C,MAAM,IAAI,GAAG,CAAC,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,CAAQ,CAAC;gBACnD,IAAI,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;oBACtB,OAAO,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC;gBACzB,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,uCAAuC,EAAE,KAAK,CAAC,CAAC;QAC7D,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED;;GAEG;AACH,SAAS,0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