@casys/mcp-server 0.22.0 → 0.23.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.
@@ -0,0 +1,435 @@
1
+ /**
2
+ * requestState seal/verify — HMAC-SHA256 integrity protection for MRTR tokens
3
+ * (spec 2026-07-28, SEP-2322 §Server Requirements, rule 4-5).
4
+ *
5
+ * The spec requires integrity protection whenever `requestState` influences
6
+ * authorization, resource access, or business logic. This module implements
7
+ * that protection with HMAC-SHA256 over a canonical JSON encoding — not AES-GCM,
8
+ * because the server needs the payload readable (for the binding checks in
9
+ * `verifyRequestState`) and the only threat model it addresses is CLIENT-SIDE
10
+ * TAMPERING. The client sees the token; confidentiality of individual fields is
11
+ * not required. AES-GCM would add the `nonce` / `tag` overhead of authenticated
12
+ * encryption without the benefit, since the `sub`/`method`/`paramsDigest` bindings
13
+ * already prevent cross-request / cross-user replay.
14
+ *
15
+ * Wire format (deliberately NOT JWT — JWT headers add no value here since the
16
+ * algorithm is fixed, and they invite consumers to parse the token as one):
17
+ * base64url(utf8(canonicalJson(payload))) + "." + base64url(hmacBytes)
18
+ *
19
+ * The HMAC covers the base64url-encoded JSON string (as UTF-8 bytes), not the
20
+ * raw JSON. This means the MAC is over the encoding as well as the content,
21
+ * preventing attacks that try to craft a byte string that decodes differently
22
+ * under different parsers.
23
+ *
24
+ * Canonical JSON: keys sorted lexicographically at every nesting level, no
25
+ * extra whitespace, UTF-8 encoded. Two implementations of the same payload
26
+ * always produce the same canonical form.
27
+ *
28
+ * All functions are pure and async (Web Crypto). No network, no server state.
29
+ *
30
+ * @module lib/server/mrtr/request-state
31
+ */
32
+
33
+ // ── Types ─────────────────────────────────────────────────────────────────────
34
+
35
+ /**
36
+ * Claims embedded inside the HMAC-SHA256-protected requestState token.
37
+ *
38
+ * All fields participate in the MAC: modifying any byte causes HMAC mismatch.
39
+ *
40
+ * Replay-bounding properties:
41
+ * - `sub` prevents a different user from reusing the same token.
42
+ * - `exp` limits the time window for replay.
43
+ * - `method` + `paramsDigest` prevent cross-request replay
44
+ * (a token for `tools/call(echo)` is rejected on `tools/call(exec)` or
45
+ * `resources/read`).
46
+ * - `nonce` ensures tokens minted at the same second for the same call are
47
+ * non-identical, defeating precomputation attacks.
48
+ *
49
+ * What these measures do NOT guarantee: single-use within the TTL. The spec
50
+ * explicitly warns about this. Deployers who need at-most-once semantics MUST
51
+ * consume the `nonce` in a server-side store on first use.
52
+ */
53
+ export interface RequestStatePayload {
54
+ /** Authenticated principal (JWT sub, hashed API-key, …). */
55
+ readonly sub: string;
56
+ /** JSON-RPC method of the originating request (e.g. "tools/call"). */
57
+ readonly method: string;
58
+ /**
59
+ * Hex-encoded SHA-256 of the canonical JSON of salient parameters.
60
+ *
61
+ * For tools/call: canonicalJson({ arguments: args, name: toolName })
62
+ * For resources/read: canonicalJson({ uri })
63
+ * For prompts/get: canonicalJson({ name: promptName })
64
+ *
65
+ * Binding the token to these parameters prevents cross-argument replay:
66
+ * a token minted for `tools/call(echo, {})` is rejected on
67
+ * `tools/call(exec, {cmd:"rm -rf /"})`.
68
+ */
69
+ readonly paramsDigest: string;
70
+ /** Unix epoch seconds (integer) after which the token MUST be rejected. */
71
+ readonly exp: number;
72
+ /**
73
+ * 16-byte random hex nonce, minted at seal time.
74
+ *
75
+ * Generate with: `bytesToHex(crypto.getRandomValues(new Uint8Array(16)))`.
76
+ *
77
+ * Does NOT guarantee single-use — see the module docstring. Its purpose is to
78
+ * ensure tokens minted for the same call at the same second are non-identical.
79
+ */
80
+ readonly nonce: string;
81
+ }
82
+
83
+ /** Reason a `verifyRequestState` call returned `ok: false`. */
84
+ export type RequestStateRejectionReason =
85
+ /** HMAC mismatch: one or more bytes of the payload were modified after sealing. */
86
+ | "tampered"
87
+ /** `sub` does not match the current authenticated principal. */
88
+ | "wrong_principal"
89
+ /** `exp` is in the past (or at `nowSecs`). */
90
+ | "expired"
91
+ /** `method` does not match the current JSON-RPC method. */
92
+ | "wrong_method"
93
+ /** `paramsDigest` does not match the current salient parameters. */
94
+ | "wrong_params";
95
+
96
+ /** Return value of `verifyRequestState`. */
97
+ export type VerifyResult =
98
+ | { readonly ok: true; readonly payload: RequestStatePayload }
99
+ | {
100
+ readonly ok: false;
101
+ readonly reason: RequestStateRejectionReason;
102
+ readonly message: string;
103
+ };
104
+
105
+ // ── Base64url helpers ─────────────────────────────────────────────────────────
106
+ //
107
+ // The standard `btoa` / `atob` pair works with binary strings (one char = one
108
+ // byte). For Uint8Array we convert via a loop. We avoid the spread operator
109
+ // (`String.fromCharCode(...bytes)`) because large arrays hit the call-stack
110
+ // argument limit.
111
+
112
+ function toBase64Url(bytes: Uint8Array): string {
113
+ let binary = "";
114
+ for (const byte of bytes) binary += String.fromCharCode(byte);
115
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
116
+ }
117
+
118
+ /** Returns null when the input is not valid base64url. */
119
+ function fromBase64Url(s: string): Uint8Array<ArrayBuffer> | null {
120
+ // Restore standard base64 alphabet and padding.
121
+ const padded = s + "=".repeat((4 - (s.length % 4)) % 4);
122
+ const standard = padded.replace(/-/g, "+").replace(/_/g, "/");
123
+ try {
124
+ const binary = atob(standard);
125
+ // Use new ArrayBuffer explicitly so the resulting Uint8Array carries an
126
+ // ArrayBuffer (not ArrayBufferLike), satisfying Web Crypto's BufferSource.
127
+ const buf = new ArrayBuffer(binary.length);
128
+ const bytes = new Uint8Array(buf);
129
+ for (let i = 0; i < binary.length; i++) {
130
+ bytes[i] = binary.charCodeAt(i);
131
+ }
132
+ return bytes;
133
+ } catch {
134
+ return null;
135
+ }
136
+ }
137
+
138
+ // ── Canonical JSON ─────────────────────────────────────────────────────────────
139
+ //
140
+ // Sorted keys at every nesting level; no extra whitespace; UTF-8 encoding is
141
+ // inherited from TextEncoder below. Two objects with the same fields in any
142
+ // order produce the same canonical form, so the HMAC is comparison-invariant.
143
+
144
+ function canonicalJson(value: unknown): string {
145
+ if (value === null) return "null";
146
+ if (typeof value === "boolean" || typeof value === "number") {
147
+ return JSON.stringify(value);
148
+ }
149
+ if (typeof value === "string") return JSON.stringify(value);
150
+ if (Array.isArray(value)) {
151
+ return "[" + value.map(canonicalJson).join(",") + "]";
152
+ }
153
+ if (typeof value === "object") {
154
+ const obj = value as Record<string, unknown>;
155
+ const pairs = Object.keys(obj).sort().map(
156
+ (k) => JSON.stringify(k) + ":" + canonicalJson(obj[k]),
157
+ );
158
+ return "{" + pairs.join(",") + "}";
159
+ }
160
+ // undefined, function, symbol — not representable in JSON; treat as null
161
+ return "null";
162
+ }
163
+
164
+ // ── Key management ──────────────────────────────────────────────────────────
165
+
166
+ /**
167
+ * Import a 32-byte key expressed as 64 lowercase hex characters.
168
+ * The resulting `CryptoKey` supports HMAC-SHA256 sign + verify.
169
+ *
170
+ * @throws If `hexKey` is not exactly 64 lowercase hex chars.
171
+ */
172
+ export async function importStateKey(hexKey: string): Promise<CryptoKey> {
173
+ if (!/^[0-9a-f]{64}$/.test(hexKey)) {
174
+ throw new Error(
175
+ "mrtr.signingKey must be a 64-character lowercase hex string (32 bytes). " +
176
+ "Generate with: bytesToHex(crypto.getRandomValues(new Uint8Array(32)))",
177
+ );
178
+ }
179
+ const bytes = new Uint8Array(32);
180
+ for (let i = 0; i < 32; i++) {
181
+ bytes[i] = parseInt(hexKey.slice(i * 2, i * 2 + 2), 16);
182
+ }
183
+ return await crypto.subtle.importKey(
184
+ "raw",
185
+ bytes,
186
+ { name: "HMAC", hash: "SHA-256" },
187
+ // exportable: false — the key material does not leave the Web Crypto subsystem
188
+ false,
189
+ ["sign", "verify"],
190
+ );
191
+ }
192
+
193
+ /**
194
+ * Generate a fresh 32-byte HMAC-SHA256 key.
195
+ *
196
+ * Marked `extractable: true` so `exportStateKey` can convert it to hex for
197
+ * storage. Keys at rest should be stored in a secrets manager, not logged.
198
+ */
199
+ export async function generateStateKey(): Promise<CryptoKey> {
200
+ // Specify length: 256 bits (32 bytes) to match importStateKey's expected size.
201
+ // Without this, Web Crypto defaults to the HMAC block size (512 bits = 64 bytes),
202
+ // which would make generateStateKey + exportStateKey produce 128 hex chars —
203
+ // incompatible with importStateKey which expects exactly 64.
204
+ return await crypto.subtle.generateKey(
205
+ { name: "HMAC", hash: "SHA-256", length: 256 },
206
+ /* extractable */ true,
207
+ ["sign", "verify"],
208
+ );
209
+ }
210
+
211
+ /**
212
+ * Export a `CryptoKey` to 64-char lowercase hex for storage or serialization.
213
+ *
214
+ * Only works on keys created with `generateStateKey()` (which sets
215
+ * `extractable: true`). Keys imported with `importStateKey()` are non-extractable
216
+ * by design — re-hex from the original string instead.
217
+ */
218
+ export async function exportStateKey(key: CryptoKey): Promise<string> {
219
+ const raw = await crypto.subtle.exportKey("raw", key);
220
+ const bytes = new Uint8Array(raw);
221
+ let hex = "";
222
+ for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
223
+ return hex;
224
+ }
225
+
226
+ // ── Digest of salient parameters ──────────────────────────────────────────────
227
+
228
+ /**
229
+ * Compute the hex-encoded SHA-256 of the canonical JSON of `salientParams`.
230
+ *
231
+ * Pass the result as `paramsDigest` when building a `RequestStatePayload`.
232
+ * Also pass it as `expected.paramsDigest` to `verifyRequestState` on retry
233
+ * to avoid hashing the same input twice.
234
+ *
235
+ * Canonical encoding is deterministic regardless of JS object property order,
236
+ * so the digest is stable across re-construction of the same logical value.
237
+ */
238
+ export async function paramsDigest(salientParams: unknown): Promise<string> {
239
+ const canonical = canonicalJson(salientParams);
240
+ const encoded = new TextEncoder().encode(canonical);
241
+ const hashBuffer = await crypto.subtle.digest("SHA-256", encoded);
242
+ const hashBytes = new Uint8Array(hashBuffer);
243
+ let hex = "";
244
+ for (const byte of hashBytes) hex += byte.toString(16).padStart(2, "0");
245
+ return hex;
246
+ }
247
+
248
+ // ── Seal ──────────────────────────────────────────────────────────────────────
249
+
250
+ /**
251
+ * Seal a `RequestStatePayload` into a compact, integrity-protected token.
252
+ *
253
+ * Wire format:
254
+ * base64url(utf8(canonicalJson(payload))) + "." + base64url(hmacSha256)
255
+ *
256
+ * The HMAC covers the base64url-encoded JSON string (as UTF-8 bytes), not the
257
+ * raw JSON, so the MAC binds the encoding. Both segments are base64url (no
258
+ * padding, URL-safe alphabet).
259
+ *
260
+ * @param payload - Fully-formed `RequestStatePayload`. The caller is responsible
261
+ * for generating the `nonce`; see `types.ts` for guidance.
262
+ * @param key - HMAC-SHA256 key from `importStateKey` or `generateStateKey`.
263
+ * @returns Opaque token string to carry in `InputRequiredSignal.requestState`.
264
+ */
265
+ export async function sealRequestState(
266
+ payload: RequestStatePayload,
267
+ key: CryptoKey,
268
+ ): Promise<string> {
269
+ const canonical = canonicalJson(payload);
270
+ const encodedJson = new TextEncoder().encode(canonical);
271
+ const b64uJson = toBase64Url(encodedJson);
272
+
273
+ // HMAC is computed over the UTF-8 bytes of the base64url string, not over
274
+ // the raw JSON bytes. This ensures the MAC is over the wire representation.
275
+ const hmacInput = new TextEncoder().encode(b64uJson);
276
+ const hmacBuffer = await crypto.subtle.sign("HMAC", key, hmacInput);
277
+ const hmacBytes = new Uint8Array(hmacBuffer);
278
+ const b64uHmac = toBase64Url(hmacBytes);
279
+
280
+ return `${b64uJson}.${b64uHmac}`;
281
+ }
282
+
283
+ // ── Verify ────────────────────────────────────────────────────────────────────
284
+
285
+ /**
286
+ * Verify a `requestState` token against the expected claims for the current request.
287
+ *
288
+ * The input `token` is ATTACKER-CONTROLLED (the spec requires treating it as
289
+ * such). Checks run in order: integrity first (so a tampered payload never
290
+ * reaches field comparison), then bindings from most-impactful to least.
291
+ *
292
+ * Rejection order: tampered → wrong_principal → expired → wrong_method → wrong_params
293
+ *
294
+ * Each rejection reason is distinct so the server can distinguish attack
295
+ * patterns in logs / metrics without leaking the payload to the client
296
+ * (the client receives only the generic -32602 error code and a safe message).
297
+ *
298
+ * @param token - The token as received from the client (untrusted).
299
+ * @param key - The server's HMAC-SHA256 signing key.
300
+ * @param expected - Values derived from the CURRENT (retry) request.
301
+ * @param expected.principal - Authenticated principal (JWT sub, …). Pass `""` when
302
+ * the endpoint is unauthenticated; the token's `sub`
303
+ * must also be `""` for a match.
304
+ * @param expected.method - JSON-RPC method of the retry request.
305
+ * @param expected.paramsDigest - Pre-computed digest of the retry's salient params.
306
+ * Avoids double-hashing: compute once, pass here and
307
+ * keep for business logic.
308
+ * @param expected.nowSecs - Wall-clock Unix epoch seconds. Defaults to
309
+ * `Math.floor(Date.now() / 1000)`. Override in tests.
310
+ */
311
+ export async function verifyRequestState(
312
+ token: string,
313
+ key: CryptoKey,
314
+ expected: {
315
+ readonly principal: string;
316
+ readonly method: string;
317
+ readonly paramsDigest: string;
318
+ readonly nowSecs?: number;
319
+ },
320
+ ): Promise<VerifyResult> {
321
+ // ── 1. Structural parse ─────────────────────────────────────────────────────
322
+ const dotIdx = token.indexOf(".");
323
+ if (dotIdx < 1 || dotIdx === token.length - 1) {
324
+ return {
325
+ ok: false,
326
+ reason: "tampered",
327
+ message: "Token format invalid: expected <base64url>.<base64url>",
328
+ };
329
+ }
330
+
331
+ const b64uJson = token.slice(0, dotIdx);
332
+ const b64uHmac = token.slice(dotIdx + 1);
333
+
334
+ // ── 2. HMAC integrity check ─────────────────────────────────────────────────
335
+ // Must run before any field comparison: a tampered payload must never reach
336
+ // principal/method/params comparison where it could leak information.
337
+ const hmacBytes = fromBase64Url(b64uHmac);
338
+ if (hmacBytes === null) {
339
+ return {
340
+ ok: false,
341
+ reason: "tampered",
342
+ message: "HMAC segment is not valid base64url",
343
+ };
344
+ }
345
+
346
+ const hmacInput = new TextEncoder().encode(b64uJson);
347
+ let valid: boolean;
348
+ try {
349
+ valid = await crypto.subtle.verify("HMAC", key, hmacBytes, hmacInput);
350
+ } catch {
351
+ // Key algorithm mismatch or corrupt hmacBytes — treat as tampered.
352
+ valid = false;
353
+ }
354
+ if (!valid) {
355
+ return {
356
+ ok: false,
357
+ reason: "tampered",
358
+ message:
359
+ "HMAC verification failed: payload was modified after sealing or wrong key",
360
+ };
361
+ }
362
+
363
+ // ── 3. Decode payload (JSON bytes from base64url) ──────────────────────────
364
+ const jsonBytes = fromBase64Url(b64uJson);
365
+ if (jsonBytes === null) {
366
+ // HMAC passed but base64url decode failed — structural corruption
367
+ return {
368
+ ok: false,
369
+ reason: "tampered",
370
+ message: "Payload segment is not valid base64url",
371
+ };
372
+ }
373
+
374
+ let payload: RequestStatePayload;
375
+ try {
376
+ const jsonText = new TextDecoder("utf-8", { fatal: true }).decode(
377
+ jsonBytes,
378
+ );
379
+ const parsed: unknown = JSON.parse(jsonText);
380
+ if (
381
+ parsed === null || typeof parsed !== "object" || Array.isArray(parsed)
382
+ ) {
383
+ throw new TypeError("payload must be a JSON object");
384
+ }
385
+ // Narrow to RequestStatePayload — field-level type checks happen below.
386
+ payload = parsed as RequestStatePayload;
387
+ } catch {
388
+ return {
389
+ ok: false,
390
+ reason: "tampered",
391
+ message: "Payload is not a valid JSON object",
392
+ };
393
+ }
394
+
395
+ // ── 4. Principal binding ────────────────────────────────────────────────────
396
+ if (payload.sub !== expected.principal) {
397
+ return {
398
+ ok: false,
399
+ reason: "wrong_principal",
400
+ message: "Token principal does not match the current authenticated user",
401
+ };
402
+ }
403
+
404
+ // ── 5. Expiry ──────────────────────────────────────────────────────────────
405
+ const nowSecs = expected.nowSecs ?? Math.floor(Date.now() / 1000);
406
+ if (typeof payload.exp !== "number" || payload.exp <= nowSecs) {
407
+ return {
408
+ ok: false,
409
+ reason: "expired",
410
+ message: `Token expired (exp=${payload.exp}, now=${nowSecs})`,
411
+ };
412
+ }
413
+
414
+ // ── 6. Method binding ──────────────────────────────────────────────────────
415
+ if (payload.method !== expected.method) {
416
+ return {
417
+ ok: false,
418
+ reason: "wrong_method",
419
+ message:
420
+ `Token method "${payload.method}" does not match request method "${expected.method}"`,
421
+ };
422
+ }
423
+
424
+ // ── 7. Params binding ──────────────────────────────────────────────────────
425
+ if (payload.paramsDigest !== expected.paramsDigest) {
426
+ return {
427
+ ok: false,
428
+ reason: "wrong_params",
429
+ message:
430
+ "Token paramsDigest does not match the current request parameters",
431
+ };
432
+ }
433
+
434
+ return { ok: true, payload };
435
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Type definitions for Multi Round-Trip Requests (MRTR, spec 2026-07-28, SEP-2322).
3
+ *
4
+ * MRTR entirely replaces the old server-initiated request pattern. Instead of
5
+ * the server pushing sampling/createMessage, elicitation/create or roots/list
6
+ * over a side channel, the server returns an InputRequiredResult from any
7
+ * tools/call, resources/read or prompts/get request. The client gathers the
8
+ * data and retries the ORIGINAL method under a NEW JSON-RPC id, carrying
9
+ * inputResponses (keyed by the server-assigned ids from the previous result)
10
+ * and echoing requestState verbatim if one was included.
11
+ *
12
+ * @module lib/server/mrtr/types
13
+ */
14
+
15
+ /** The three request types a server may embed in an InputRequiredResult (spec 2026-07-28). */
16
+ export type InputRequestMethod =
17
+ | "elicitation/create"
18
+ | "sampling/createMessage"
19
+ | "roots/list";
20
+
21
+ /** One slot in the inputRequests map. */
22
+ export interface InputRequestEntry {
23
+ readonly method: InputRequestMethod;
24
+ readonly params: Record<string, unknown>;
25
+ }
26
+
27
+ /**
28
+ * Return this from a tool/resource handler to trigger an MRTR round-trip.
29
+ *
30
+ * Spec rule 6 (MUST): at least one of inputRequests or requestState MUST
31
+ * be present. The framework validates this and returns -32603 Internal Error
32
+ * if both are absent -- that is a server-authoring error, not a client error.
33
+ *
34
+ * Security note: requestState passes through the client untouched and is
35
+ * therefore ATTACKER-CONTROLLED on retry. Use sealRequestState() to bind it
36
+ * cryptographically to the authenticated principal, the originating method, and
37
+ * the request parameters. Do NOT use an unprotected requestState for
38
+ * authorization or resource-access decisions.
39
+ */
40
+ export interface InputRequiredSignal {
41
+ readonly resultType: "input_required";
42
+ /**
43
+ * Map of server-assigned string ids to sub-request objects.
44
+ * Keys must be unique within the scope of the originating request (spec rule 2).
45
+ */
46
+ readonly inputRequests?: Record<string, InputRequestEntry>;
47
+ /**
48
+ * Opaque token the client must echo on retry (spec rule 2, client rule 2).
49
+ *
50
+ * When McpAppOptions.mrtr.signingKey is configured, produce this value
51
+ * by calling sealRequestState(). The sealed token binds the principal,
52
+ * method, params-digest, expiry and a random nonce under HMAC-SHA256 so the
53
+ * server can reject a tampered or replayed token on retry.
54
+ *
55
+ * Without a signing key, the value is passed through to the client and back
56
+ * as-is -- adequate only when requestState influences nothing that requires
57
+ * integrity.
58
+ */
59
+ readonly requestState?: string;
60
+ }
61
+
62
+ /**
63
+ * Configuration for the MRTR subsystem in McpAppOptions.
64
+ *
65
+ * Wire this in to McpAppOptions.mrtr before calling startHttp().
66
+ */
67
+ export interface MrtrOptions {
68
+ /**
69
+ * 64-character lowercase hex string (32 bytes) used as the HMAC-SHA256 key
70
+ * for sealing and verifying requestState tokens.
71
+ *
72
+ * Generate once per deployment with:
73
+ * bytesToHex(crypto.getRandomValues(new Uint8Array(32)))
74
+ *
75
+ * In load-balanced deployments all instances MUST share the same key; rotating
76
+ * the key immediately invalidates all in-flight requestState tokens.
77
+ *
78
+ * If absent, the framework emits a [WARN] at startup and passes requestState
79
+ * through without integrity protection. Handlers MUST NOT use unprotected
80
+ * requestState for authorization or resource-access decisions.
81
+ */
82
+ signingKey?: string;
83
+
84
+ /**
85
+ * Lifetime of a sealed requestState token in seconds.
86
+ *
87
+ * Default: 300 (5 minutes). The spec warns that these measures do NOT
88
+ * guarantee single-use. Deployers who need at-most-once semantics MUST
89
+ * enforce that invariant server-side (e.g., by consuming the nonce from a
90
+ * shared store on the first use).
91
+ */
92
+ defaultTtlSecs?: number;
93
+ }