@casys/mcp-server 0.26.1 → 0.27.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.
Files changed (62) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/README.md +10 -627
  4. package/esm/mod.d.ts +1 -0
  5. package/esm/mod.js +1 -0
  6. package/package.json +28 -25
  7. package/mod.ts +0 -302
  8. package/src/auth/as-metadata-proxy.ts +0 -288
  9. package/src/auth/config.ts +0 -368
  10. package/src/auth/jwt-provider.ts +0 -327
  11. package/src/auth/middleware.ts +0 -257
  12. package/src/auth/mod.ts +0 -89
  13. package/src/auth/multi-tenant-middleware.ts +0 -236
  14. package/src/auth/presets.ts +0 -351
  15. package/src/auth/provider.ts +0 -49
  16. package/src/auth/scope-middleware.ts +0 -59
  17. package/src/auth/static-token-provider.ts +0 -197
  18. package/src/auth/types.ts +0 -207
  19. package/src/client-auth/callback-server.ts +0 -166
  20. package/src/client-auth/client-id-metadata.ts +0 -260
  21. package/src/client-auth/connect.ts +0 -72
  22. package/src/client-auth/mod.ts +0 -44
  23. package/src/client-auth/provider.ts +0 -300
  24. package/src/client-auth/token-store/file-store.ts +0 -73
  25. package/src/client-auth/token-store/memory-store.ts +0 -32
  26. package/src/client-auth/types.ts +0 -95
  27. package/src/concurrency/rate-limiter.ts +0 -190
  28. package/src/concurrency/request-queue.ts +0 -140
  29. package/src/http/body.ts +0 -72
  30. package/src/http/request-guards.ts +0 -137
  31. package/src/http/wire.ts +0 -41
  32. package/src/inspector/launcher.ts +0 -131
  33. package/src/mcp-app.ts +0 -4595
  34. package/src/middleware/backpressure.ts +0 -36
  35. package/src/middleware/mod.ts +0 -21
  36. package/src/middleware/rate-limit.ts +0 -45
  37. package/src/middleware/runner.ts +0 -63
  38. package/src/middleware/types.ts +0 -104
  39. package/src/middleware/validation.ts +0 -28
  40. package/src/mrtr/capability-check.ts +0 -303
  41. package/src/mrtr/mod.ts +0 -54
  42. package/src/mrtr/replay-store.ts +0 -103
  43. package/src/mrtr/request-state.ts +0 -435
  44. package/src/mrtr/retry-guard.ts +0 -110
  45. package/src/mrtr/types.ts +0 -107
  46. package/src/observability/metrics.ts +0 -336
  47. package/src/observability/mod.ts +0 -21
  48. package/src/observability/otel.ts +0 -330
  49. package/src/runtime/runtime.deno.ts +0 -149
  50. package/src/runtime/runtime.node.ts +0 -324
  51. package/src/runtime/runtime.ts +0 -50
  52. package/src/runtime/types.ts +0 -130
  53. package/src/security/channel-hmac.ts +0 -140
  54. package/src/security/csp.ts +0 -89
  55. package/src/security/message-signer.ts +0 -223
  56. package/src/subscriptions/subscription-registry.ts +0 -558
  57. package/src/tasks/mod.ts +0 -33
  58. package/src/tasks/task-store.ts +0 -1014
  59. package/src/transport/request-headers.ts +0 -661
  60. package/src/types.ts +0 -908
  61. package/src/ui/viewer-utils.ts +0 -117
  62. package/src/validation/schema-validator.ts +0 -307
@@ -1,103 +0,0 @@
1
- /**
2
- * Atomic nonce consumption for MRTR requestState tokens.
3
- *
4
- * Integrity verification proves that a token was minted by the server and is
5
- * bound to the current request. A replay store adds the separate single-use
6
- * property by reserving the signed nonce before business logic runs.
7
- */
8
-
9
- /**
10
- * Store used to consume a verified MRTR nonce exactly once.
11
- *
12
- * Implementations MUST make the check-and-reserve operation atomic. Return
13
- * `true` only for the caller that reserved the nonce, `false` when it was
14
- * already consumed, and throw when availability cannot be established.
15
- *
16
- * `expiresAt` is the signed token expiry as Unix epoch seconds. Stores should
17
- * remove the reservation after that time; retaining it longer is safe but
18
- * wastes capacity.
19
- *
20
- * A load-balanced deployment MUST provide one shared implementation to every
21
- * McpApp instance. Redis can implement the contract with `SET key 1 NX EXAT`.
22
- */
23
- export interface MrtrReplayStore {
24
- consume(nonce: string, expiresAt: number): boolean | Promise<boolean>;
25
- }
26
-
27
- export interface MemoryMrtrReplayStoreOptions {
28
- /**
29
- * Maximum live reservations before the store fails closed.
30
- *
31
- * Default: 100,000.
32
- */
33
- maxEntries?: number;
34
-
35
- /** Test seam for the current Unix epoch time in seconds. */
36
- nowSecs?: () => number;
37
- }
38
-
39
- /**
40
- * Process-local replay protection.
41
- *
42
- * This is the safe default for one continuously running McpApp process. It
43
- * cannot coordinate separate processes or survive a restart; horizontally
44
- * scaled or restart-safe deployments must inject a durable shared
45
- * `MrtrReplayStore`.
46
- */
47
- export class MemoryMrtrReplayStore implements MrtrReplayStore {
48
- private readonly entries = new Map<string, number>();
49
- private readonly maxEntries: number;
50
- private readonly nowSecs: () => number;
51
-
52
- constructor(options: MemoryMrtrReplayStoreOptions = {}) {
53
- const maxEntries = options.maxEntries ?? 100_000;
54
- if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) {
55
- throw new Error(
56
- `MemoryMrtrReplayStore maxEntries must be a positive integer (got ${maxEntries})`,
57
- );
58
- }
59
- this.maxEntries = maxEntries;
60
- this.nowSecs = options.nowSecs ?? (() => Math.floor(Date.now() / 1000));
61
- }
62
-
63
- consume(nonce: string, expiresAt: number): boolean {
64
- if (!/^[0-9a-f]{32}$/.test(nonce)) {
65
- throw new Error("MRTR replay nonce must be 32 lowercase hex characters");
66
- }
67
- if (!Number.isSafeInteger(expiresAt) || expiresAt < 0) {
68
- throw new Error(
69
- "MRTR replay expiry must be a non-negative safe-integer Unix timestamp",
70
- );
71
- }
72
-
73
- const now = this.nowSecs();
74
- if (!Number.isSafeInteger(now) || now < 0) {
75
- throw new Error(
76
- "MRTR replay clock must return a non-negative safe-integer Unix timestamp",
77
- );
78
- }
79
- const existingExpiry = this.entries.get(nonce);
80
- if (existingExpiry !== undefined) {
81
- if (existingExpiry > now) return false;
82
- this.entries.delete(nonce);
83
- }
84
-
85
- if (expiresAt <= now) return false;
86
-
87
- if (this.entries.size >= this.maxEntries) {
88
- for (const [storedNonce, storedExpiry] of this.entries) {
89
- if (storedExpiry <= now) this.entries.delete(storedNonce);
90
- }
91
- if (this.entries.size >= this.maxEntries) {
92
- throw new Error(
93
- `MRTR replay store capacity exceeded (${this.maxEntries} live nonces)`,
94
- );
95
- }
96
- }
97
-
98
- // No await may occur between the check and this write. In one JS process,
99
- // that makes the reservation atomic across concurrent request continuations.
100
- this.entries.set(nonce, expiresAt);
101
- return true;
102
- }
103
- }
@@ -1,435 +0,0 @@
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
- }
@@ -1,110 +0,0 @@
1
- /**
2
- * MRTR retry admission policy.
3
- *
4
- * This module owns the transport-independent decision whether a retried
5
- * request may reach application code. HTTP and stdio adapt its outcomes to
6
- * their respective error envelopes; neither transport reimplements HMAC
7
- * verification or nonce consumption.
8
- *
9
- * @module lib/server/mrtr/retry-guard
10
- */
11
-
12
- import type { MrtrReplayStore } from "./replay-store.js";
13
- import {
14
- type RequestStateRejectionReason,
15
- verifyRequestState,
16
- } from "./request-state.js";
17
-
18
- /** Bind a requestState to the retry that is attempting to spend it. */
19
- export interface MrtrRetryBindings {
20
- readonly principal: string;
21
- readonly method: string;
22
- readonly paramsDigest: string;
23
- }
24
-
25
- /** Inputs required to decide whether one MRTR retry is admissible. */
26
- export interface GuardMrtrRetryInput {
27
- /** Presence matters; response contents remain untrusted handler input. */
28
- readonly inputResponses?: Record<string, unknown>;
29
- /** Attacker-controlled state echoed by the client, when any. */
30
- readonly requestState?: string;
31
- /** Null deliberately represents the explicitly unprotected deployment mode. */
32
- readonly key: CryptoKey | null;
33
- /** Required only when a signed requestState is presented. */
34
- readonly replayStore: MrtrReplayStore | null;
35
- readonly bindings: MrtrRetryBindings;
36
- }
37
-
38
- /**
39
- * Transport-neutral admission outcome.
40
- *
41
- * `accepted.retryVerified` is deliberately tri-state: absent for a first leg,
42
- * false for the configured unprotected mode, and true only after signature,
43
- * binding and atomic nonce reservation all succeeded.
44
- */
45
- export type MrtrRetryGuardOutcome =
46
- | { readonly kind: "accepted"; readonly retryVerified?: boolean }
47
- | { readonly kind: "missing_state" }
48
- | {
49
- readonly kind: "invalid_state";
50
- readonly reason: RequestStateRejectionReason;
51
- }
52
- | {
53
- readonly kind: "replay_store_unavailable";
54
- readonly reason: "missing" | "consume_failed";
55
- }
56
- | { readonly kind: "replayed" };
57
-
58
- /**
59
- * Decide whether a retried request may enter application code.
60
- *
61
- * A signed state is verified and its nonce is atomically reserved before the
62
- * handler runs. This intentionally gives at-most-once admission, not exactly
63
- * once completion: a transport adapter must never move consumption after a
64
- * business side effect.
65
- */
66
- export async function guardMrtrRetry(
67
- input: GuardMrtrRetryInput,
68
- ): Promise<MrtrRetryGuardOutcome> {
69
- const hasInputResponses = input.inputResponses !== undefined;
70
- const { requestState, key } = input;
71
-
72
- if (hasInputResponses && requestState === undefined && key !== null) {
73
- return { kind: "missing_state" };
74
- }
75
-
76
- if (requestState === undefined) {
77
- return { kind: "accepted" };
78
- }
79
-
80
- if (key === null) {
81
- return { kind: "accepted", retryVerified: false };
82
- }
83
-
84
- const verdict = await verifyRequestState(requestState, key, input.bindings);
85
- if (!verdict.ok) {
86
- return { kind: "invalid_state", reason: verdict.reason };
87
- }
88
-
89
- if (input.replayStore === null) {
90
- return { kind: "replay_store_unavailable", reason: "missing" };
91
- }
92
-
93
- let consumed: boolean;
94
- try {
95
- const result = await input.replayStore.consume(
96
- verdict.payload.nonce,
97
- verdict.payload.exp,
98
- );
99
- if (result !== true && result !== false) {
100
- throw new Error("mrtr.replayStore.consume() must return a boolean");
101
- }
102
- consumed = result;
103
- } catch {
104
- return { kind: "replay_store_unavailable", reason: "consume_failed" };
105
- }
106
-
107
- return consumed
108
- ? { kind: "accepted", retryVerified: true }
109
- : { kind: "replayed" };
110
- }