@casys/mcp-server 0.26.0 → 0.27.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/CHANGELOG.md +1779 -0
- package/LICENSE +21 -0
- package/README.md +19 -5
- package/esm/_dnt.polyfills.d.ts +12 -0
- package/esm/_dnt.polyfills.d.ts.map +1 -0
- package/esm/_dnt.polyfills.js +15 -0
- package/esm/_dnt.shims.d.ts +2 -0
- package/esm/_dnt.shims.d.ts.map +1 -0
- package/esm/_dnt.shims.js +57 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts +33 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.js +48 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts +106 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.js +636 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts +67 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.js +1393 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts +44 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.js +117 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.js +103 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.js +32 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.js +96 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.js +159 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.js +14 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.js +10 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.js +22 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.js +29 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.js +19 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.js +30 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.js +10 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.js +14 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.js +9 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.js +81 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts +3 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.js +20 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts +32 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.js +6 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts +4 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.js +13 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts +51 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.js +53 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts +79 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.js +91 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts +100 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.js +33 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts +111 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts.map +1 -0
- package/esm/deps/jsr.io/@std/yaml/1.2.0/types.js +104 -0
- package/esm/mod.d.ts +102 -0
- package/esm/mod.d.ts.map +1 -0
- package/esm/mod.js +103 -0
- package/esm/package.json +3 -0
- package/esm/src/auth/as-metadata-proxy.d.ts +112 -0
- package/esm/src/auth/as-metadata-proxy.d.ts.map +1 -0
- package/esm/src/auth/as-metadata-proxy.js +171 -0
- package/esm/src/auth/config.d.ts +117 -0
- package/esm/src/auth/config.d.ts.map +1 -0
- package/esm/src/auth/config.js +219 -0
- package/esm/src/auth/jwt-provider.d.ts +157 -0
- package/esm/src/auth/jwt-provider.d.ts.map +1 -0
- package/esm/src/auth/jwt-provider.js +187 -0
- package/esm/src/auth/middleware.d.ts +61 -0
- package/esm/src/auth/middleware.d.ts.map +1 -0
- package/esm/src/auth/middleware.js +209 -0
- package/esm/src/auth/mod.d.ts +23 -0
- package/esm/src/auth/mod.d.ts.map +1 -0
- package/esm/src/auth/mod.js +27 -0
- package/esm/src/auth/multi-tenant-middleware.d.ts +131 -0
- package/esm/src/auth/multi-tenant-middleware.d.ts.map +1 -0
- package/esm/src/auth/multi-tenant-middleware.js +128 -0
- package/esm/src/auth/presets.d.ts +231 -0
- package/esm/src/auth/presets.d.ts.map +1 -0
- package/esm/src/auth/presets.js +223 -0
- package/{src/auth/provider.ts → esm/src/auth/provider.d.ts} +13 -15
- package/esm/src/auth/provider.d.ts.map +1 -0
- package/esm/src/auth/provider.js +34 -0
- package/esm/src/auth/scope-middleware.d.ts +30 -0
- package/esm/src/auth/scope-middleware.d.ts.map +1 -0
- package/esm/src/auth/scope-middleware.js +48 -0
- package/esm/src/auth/static-token-provider.d.ts +155 -0
- package/esm/src/auth/static-token-provider.d.ts.map +1 -0
- package/esm/src/auth/static-token-provider.js +256 -0
- package/esm/src/auth/types.d.ts +151 -0
- package/esm/src/auth/types.d.ts.map +1 -0
- package/esm/src/auth/types.js +64 -0
- package/esm/src/client-auth/callback-server.d.ts +34 -0
- package/esm/src/client-auth/callback-server.d.ts.map +1 -0
- package/esm/src/client-auth/callback-server.js +141 -0
- package/esm/src/client-auth/client-id-metadata.d.ts +29 -0
- package/esm/src/client-auth/client-id-metadata.d.ts.map +1 -0
- package/esm/src/client-auth/client-id-metadata.js +149 -0
- package/esm/src/client-auth/connect.d.ts +32 -0
- package/esm/src/client-auth/connect.d.ts.map +1 -0
- package/esm/src/client-auth/connect.js +47 -0
- package/esm/src/client-auth/mod.d.ts +19 -0
- package/esm/src/client-auth/mod.d.ts.map +1 -0
- package/{src/client-auth/mod.ts → esm/src/client-auth/mod.js} +1 -26
- package/esm/src/client-auth/provider.d.ts +78 -0
- package/esm/src/client-auth/provider.d.ts.map +1 -0
- package/esm/src/client-auth/provider.js +246 -0
- package/esm/src/client-auth/token-store/file-store.d.ts +20 -0
- package/esm/src/client-auth/token-store/file-store.d.ts.map +1 -0
- package/esm/src/client-auth/token-store/file-store.js +62 -0
- package/esm/src/client-auth/token-store/memory-store.d.ts +14 -0
- package/esm/src/client-auth/token-store/memory-store.d.ts.map +1 -0
- package/esm/src/client-auth/token-store/memory-store.js +25 -0
- package/esm/src/client-auth/types.d.ts +89 -0
- package/esm/src/client-auth/types.d.ts.map +1 -0
- package/esm/src/client-auth/types.js +10 -0
- package/esm/src/concurrency/rate-limiter.d.ts +87 -0
- package/esm/src/concurrency/rate-limiter.d.ts.map +1 -0
- package/esm/src/concurrency/rate-limiter.js +165 -0
- package/esm/src/concurrency/request-queue.d.ts +71 -0
- package/esm/src/concurrency/request-queue.d.ts.map +1 -0
- package/esm/src/concurrency/request-queue.js +128 -0
- package/esm/src/http/body.d.ts +20 -0
- package/esm/src/http/body.d.ts.map +1 -0
- package/esm/src/http/body.js +63 -0
- package/esm/src/http/request-guards.d.ts +54 -0
- package/esm/src/http/request-guards.d.ts.map +1 -0
- package/esm/src/http/request-guards.js +114 -0
- package/esm/src/http/wire.d.ts +26 -0
- package/esm/src/http/wire.d.ts.map +1 -0
- package/{src/http/wire.ts → esm/src/http/wire.js} +13 -19
- package/esm/src/inspector/launcher.d.ts +48 -0
- package/esm/src/inspector/launcher.d.ts.map +1 -0
- package/esm/src/inspector/launcher.js +100 -0
- package/esm/src/mcp-app.d.ts +728 -0
- package/esm/src/mcp-app.d.ts.map +1 -0
- package/esm/src/mcp-app.js +3530 -0
- package/{src/middleware/backpressure.ts → esm/src/middleware/backpressure.d.ts} +2 -14
- package/esm/src/middleware/backpressure.d.ts.map +1 -0
- package/esm/src/middleware/backpressure.js +31 -0
- package/esm/src/middleware/mod.d.ts +11 -0
- package/esm/src/middleware/mod.d.ts.map +1 -0
- package/{src/middleware/mod.ts → esm/src/middleware/mod.js} +0 -10
- package/{src/middleware/rate-limit.ts → esm/src/middleware/rate-limit.d.ts} +2 -25
- package/esm/src/middleware/rate-limit.d.ts.map +1 -0
- package/esm/src/middleware/rate-limit.js +33 -0
- package/esm/src/middleware/runner.d.ts +32 -0
- package/esm/src/middleware/runner.d.ts.map +1 -0
- package/esm/src/middleware/runner.js +49 -0
- package/esm/src/middleware/types.d.ts +76 -0
- package/esm/src/middleware/types.d.ts.map +1 -0
- package/esm/src/middleware/types.js +9 -0
- package/esm/src/middleware/validation.d.ts +24 -0
- package/esm/src/middleware/validation.d.ts.map +1 -0
- package/esm/src/middleware/validation.js +30 -0
- package/esm/src/mrtr/capability-check.d.ts +75 -0
- package/esm/src/mrtr/capability-check.d.ts.map +1 -0
- package/esm/src/mrtr/capability-check.js +233 -0
- package/esm/src/mrtr/mod.d.ts +18 -0
- package/esm/src/mrtr/mod.d.ts.map +1 -0
- package/esm/src/mrtr/mod.js +12 -0
- package/esm/src/mrtr/replay-store.d.ts +50 -0
- package/esm/src/mrtr/replay-store.d.ts.map +1 -0
- package/esm/src/mrtr/replay-store.js +61 -0
- package/esm/src/mrtr/request-state.d.ts +181 -0
- package/esm/src/mrtr/request-state.d.ts.map +1 -0
- package/esm/src/mrtr/request-state.js +313 -0
- package/esm/src/mrtr/retry-guard.d.ts +61 -0
- package/esm/src/mrtr/retry-guard.d.ts.map +1 -0
- package/esm/src/mrtr/retry-guard.js +53 -0
- package/esm/src/mrtr/types.d.ts +99 -0
- package/esm/src/mrtr/types.d.ts.map +1 -0
- package/esm/src/mrtr/types.js +14 -0
- package/esm/src/observability/metrics.d.ts +104 -0
- package/esm/src/observability/metrics.d.ts.map +1 -0
- package/esm/src/observability/metrics.js +207 -0
- package/{src/observability/mod.ts → esm/src/observability/mod.d.ts} +2 -11
- package/esm/src/observability/mod.d.ts.map +1 -0
- package/esm/src/observability/mod.js +11 -0
- package/esm/src/observability/otel.d.ts +73 -0
- package/esm/src/observability/otel.d.ts.map +1 -0
- package/esm/src/observability/otel.js +260 -0
- package/esm/src/runtime/runtime.d.ts +10 -0
- package/esm/src/runtime/runtime.d.ts.map +1 -0
- package/esm/src/runtime/runtime.deno.d.ts +50 -0
- package/esm/src/runtime/runtime.deno.d.ts.map +1 -0
- package/esm/src/runtime/runtime.deno.js +120 -0
- package/{src/runtime/runtime.ts → esm/src/runtime/runtime.js} +5 -14
- package/esm/src/runtime/runtime.node.d.ts +51 -0
- package/esm/src/runtime/runtime.node.d.ts.map +1 -0
- package/esm/src/runtime/runtime.node.js +268 -0
- package/{src/runtime/types.ts → esm/src/runtime/types.d.ts} +28 -51
- package/esm/src/runtime/types.d.ts.map +1 -0
- package/esm/src/runtime/types.js +12 -0
- package/esm/src/security/channel-hmac.d.ts +43 -0
- package/esm/src/security/channel-hmac.d.ts.map +1 -0
- package/{src/security/channel-hmac.ts → esm/src/security/channel-hmac.js} +12 -17
- package/esm/src/security/csp.d.ts +50 -0
- package/esm/src/security/csp.d.ts.map +1 -0
- package/esm/src/security/csp.js +63 -0
- package/esm/src/security/message-signer.d.ts +88 -0
- package/esm/src/security/message-signer.d.ts.map +1 -0
- package/esm/src/security/message-signer.js +166 -0
- package/esm/src/subscriptions/subscription-registry.d.ts +256 -0
- package/esm/src/subscriptions/subscription-registry.d.ts.map +1 -0
- package/esm/src/subscriptions/subscription-registry.js +406 -0
- package/{src/tasks/mod.ts → esm/src/tasks/mod.d.ts} +3 -23
- package/esm/src/tasks/mod.d.ts.map +1 -0
- package/esm/src/tasks/mod.js +11 -0
- package/esm/src/tasks/task-store.d.ts +342 -0
- package/esm/src/tasks/task-store.d.ts.map +1 -0
- package/esm/src/tasks/task-store.js +649 -0
- package/esm/src/transport/request-headers.d.ts +145 -0
- package/esm/src/transport/request-headers.d.ts.map +1 -0
- package/esm/src/transport/request-headers.js +525 -0
- package/esm/src/types.d.ts +776 -0
- package/esm/src/types.d.ts.map +1 -0
- package/esm/src/types.js +92 -0
- package/esm/src/ui/viewer-utils.d.ts +45 -0
- package/esm/src/ui/viewer-utils.d.ts.map +1 -0
- package/esm/src/ui/viewer-utils.js +97 -0
- package/esm/src/validation/schema-validator.d.ts +115 -0
- package/esm/src/validation/schema-validator.d.ts.map +1 -0
- package/esm/src/validation/schema-validator.js +249 -0
- package/package.json +35 -23
- package/mod.ts +0 -302
- package/src/auth/as-metadata-proxy.ts +0 -288
- package/src/auth/config.ts +0 -368
- package/src/auth/jwt-provider.ts +0 -327
- package/src/auth/middleware.ts +0 -257
- package/src/auth/mod.ts +0 -89
- package/src/auth/multi-tenant-middleware.ts +0 -236
- package/src/auth/presets.ts +0 -351
- package/src/auth/scope-middleware.ts +0 -59
- package/src/auth/static-token-provider.ts +0 -197
- package/src/auth/types.ts +0 -207
- package/src/client-auth/callback-server.ts +0 -166
- package/src/client-auth/client-id-metadata.ts +0 -260
- package/src/client-auth/connect.ts +0 -72
- package/src/client-auth/provider.ts +0 -300
- package/src/client-auth/token-store/file-store.ts +0 -73
- package/src/client-auth/token-store/memory-store.ts +0 -32
- package/src/client-auth/types.ts +0 -95
- package/src/concurrency/rate-limiter.ts +0 -190
- package/src/concurrency/request-queue.ts +0 -140
- package/src/http/body.ts +0 -72
- package/src/http/request-guards.ts +0 -137
- package/src/inspector/launcher.ts +0 -131
- package/src/mcp-app.ts +0 -4426
- package/src/middleware/runner.ts +0 -63
- package/src/middleware/types.ts +0 -104
- package/src/middleware/validation.ts +0 -28
- package/src/mrtr/capability-check.ts +0 -303
- package/src/mrtr/mod.ts +0 -46
- package/src/mrtr/replay-store.ts +0 -103
- package/src/mrtr/request-state.ts +0 -435
- package/src/mrtr/types.ts +0 -107
- package/src/observability/metrics.ts +0 -336
- package/src/observability/otel.ts +0 -330
- package/src/runtime/runtime.deno.ts +0 -149
- package/src/runtime/runtime.node.ts +0 -324
- package/src/security/csp.ts +0 -89
- package/src/security/message-signer.ts +0 -223
- package/src/subscriptions/subscription-registry.ts +0 -558
- package/src/tasks/task-store.ts +0 -1014
- package/src/testdata/stdio-e2e-server.ts +0 -110
- package/src/transport/request-headers.ts +0 -661
- package/src/types.ts +0 -907
- package/src/ui/viewer-utils.ts +0 -117
- package/src/validation/schema-validator.ts +0 -307
|
@@ -0,0 +1,313 @@
|
|
|
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
|
+
// ── Base64url helpers ─────────────────────────────────────────────────────────
|
|
33
|
+
//
|
|
34
|
+
// The standard `btoa` / `atob` pair works with binary strings (one char = one
|
|
35
|
+
// byte). For Uint8Array we convert via a loop. We avoid the spread operator
|
|
36
|
+
// (`String.fromCharCode(...bytes)`) because large arrays hit the call-stack
|
|
37
|
+
// argument limit.
|
|
38
|
+
function toBase64Url(bytes) {
|
|
39
|
+
let binary = "";
|
|
40
|
+
for (const byte of bytes)
|
|
41
|
+
binary += String.fromCharCode(byte);
|
|
42
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
43
|
+
}
|
|
44
|
+
/** Returns null when the input is not valid base64url. */
|
|
45
|
+
function fromBase64Url(s) {
|
|
46
|
+
// Restore standard base64 alphabet and padding.
|
|
47
|
+
const padded = s + "=".repeat((4 - (s.length % 4)) % 4);
|
|
48
|
+
const standard = padded.replace(/-/g, "+").replace(/_/g, "/");
|
|
49
|
+
try {
|
|
50
|
+
const binary = atob(standard);
|
|
51
|
+
// Use new ArrayBuffer explicitly so the resulting Uint8Array carries an
|
|
52
|
+
// ArrayBuffer (not ArrayBufferLike), satisfying Web Crypto's BufferSource.
|
|
53
|
+
const buf = new ArrayBuffer(binary.length);
|
|
54
|
+
const bytes = new Uint8Array(buf);
|
|
55
|
+
for (let i = 0; i < binary.length; i++) {
|
|
56
|
+
bytes[i] = binary.charCodeAt(i);
|
|
57
|
+
}
|
|
58
|
+
return bytes;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// ── Canonical JSON ─────────────────────────────────────────────────────────────
|
|
65
|
+
//
|
|
66
|
+
// Sorted keys at every nesting level; no extra whitespace; UTF-8 encoding is
|
|
67
|
+
// inherited from TextEncoder below. Two objects with the same fields in any
|
|
68
|
+
// order produce the same canonical form, so the HMAC is comparison-invariant.
|
|
69
|
+
function canonicalJson(value) {
|
|
70
|
+
if (value === null)
|
|
71
|
+
return "null";
|
|
72
|
+
if (typeof value === "boolean" || typeof value === "number") {
|
|
73
|
+
return JSON.stringify(value);
|
|
74
|
+
}
|
|
75
|
+
if (typeof value === "string")
|
|
76
|
+
return JSON.stringify(value);
|
|
77
|
+
if (Array.isArray(value)) {
|
|
78
|
+
return "[" + value.map(canonicalJson).join(",") + "]";
|
|
79
|
+
}
|
|
80
|
+
if (typeof value === "object") {
|
|
81
|
+
const obj = value;
|
|
82
|
+
const pairs = Object.keys(obj).sort().map((k) => JSON.stringify(k) + ":" + canonicalJson(obj[k]));
|
|
83
|
+
return "{" + pairs.join(",") + "}";
|
|
84
|
+
}
|
|
85
|
+
// undefined, function, symbol — not representable in JSON; treat as null
|
|
86
|
+
return "null";
|
|
87
|
+
}
|
|
88
|
+
// ── Key management ──────────────────────────────────────────────────────────
|
|
89
|
+
/**
|
|
90
|
+
* Import a 32-byte key expressed as 64 lowercase hex characters.
|
|
91
|
+
* The resulting `CryptoKey` supports HMAC-SHA256 sign + verify.
|
|
92
|
+
*
|
|
93
|
+
* @throws If `hexKey` is not exactly 64 lowercase hex chars.
|
|
94
|
+
*/
|
|
95
|
+
export async function importStateKey(hexKey) {
|
|
96
|
+
if (!/^[0-9a-f]{64}$/.test(hexKey)) {
|
|
97
|
+
throw new Error("mrtr.signingKey must be a 64-character lowercase hex string (32 bytes). " +
|
|
98
|
+
"Generate with: bytesToHex(crypto.getRandomValues(new Uint8Array(32)))");
|
|
99
|
+
}
|
|
100
|
+
const bytes = new Uint8Array(32);
|
|
101
|
+
for (let i = 0; i < 32; i++) {
|
|
102
|
+
bytes[i] = parseInt(hexKey.slice(i * 2, i * 2 + 2), 16);
|
|
103
|
+
}
|
|
104
|
+
return await crypto.subtle.importKey("raw", bytes, { name: "HMAC", hash: "SHA-256" },
|
|
105
|
+
// exportable: false — the key material does not leave the Web Crypto subsystem
|
|
106
|
+
false, ["sign", "verify"]);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Generate a fresh 32-byte HMAC-SHA256 key.
|
|
110
|
+
*
|
|
111
|
+
* Marked `extractable: true` so `exportStateKey` can convert it to hex for
|
|
112
|
+
* storage. Keys at rest should be stored in a secrets manager, not logged.
|
|
113
|
+
*/
|
|
114
|
+
export async function generateStateKey() {
|
|
115
|
+
// Specify length: 256 bits (32 bytes) to match importStateKey's expected size.
|
|
116
|
+
// Without this, Web Crypto defaults to the HMAC block size (512 bits = 64 bytes),
|
|
117
|
+
// which would make generateStateKey + exportStateKey produce 128 hex chars —
|
|
118
|
+
// incompatible with importStateKey which expects exactly 64.
|
|
119
|
+
return await crypto.subtle.generateKey({ name: "HMAC", hash: "SHA-256", length: 256 },
|
|
120
|
+
/* extractable */ true, ["sign", "verify"]);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Export a `CryptoKey` to 64-char lowercase hex for storage or serialization.
|
|
124
|
+
*
|
|
125
|
+
* Only works on keys created with `generateStateKey()` (which sets
|
|
126
|
+
* `extractable: true`). Keys imported with `importStateKey()` are non-extractable
|
|
127
|
+
* by design — re-hex from the original string instead.
|
|
128
|
+
*/
|
|
129
|
+
export async function exportStateKey(key) {
|
|
130
|
+
const raw = await crypto.subtle.exportKey("raw", key);
|
|
131
|
+
const bytes = new Uint8Array(raw);
|
|
132
|
+
let hex = "";
|
|
133
|
+
for (const byte of bytes)
|
|
134
|
+
hex += byte.toString(16).padStart(2, "0");
|
|
135
|
+
return hex;
|
|
136
|
+
}
|
|
137
|
+
// ── Digest of salient parameters ──────────────────────────────────────────────
|
|
138
|
+
/**
|
|
139
|
+
* Compute the hex-encoded SHA-256 of the canonical JSON of `salientParams`.
|
|
140
|
+
*
|
|
141
|
+
* Pass the result as `paramsDigest` when building a `RequestStatePayload`.
|
|
142
|
+
* Also pass it as `expected.paramsDigest` to `verifyRequestState` on retry
|
|
143
|
+
* to avoid hashing the same input twice.
|
|
144
|
+
*
|
|
145
|
+
* Canonical encoding is deterministic regardless of JS object property order,
|
|
146
|
+
* so the digest is stable across re-construction of the same logical value.
|
|
147
|
+
*/
|
|
148
|
+
export async function paramsDigest(salientParams) {
|
|
149
|
+
const canonical = canonicalJson(salientParams);
|
|
150
|
+
const encoded = new TextEncoder().encode(canonical);
|
|
151
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", encoded);
|
|
152
|
+
const hashBytes = new Uint8Array(hashBuffer);
|
|
153
|
+
let hex = "";
|
|
154
|
+
for (const byte of hashBytes)
|
|
155
|
+
hex += byte.toString(16).padStart(2, "0");
|
|
156
|
+
return hex;
|
|
157
|
+
}
|
|
158
|
+
// ── Seal ──────────────────────────────────────────────────────────────────────
|
|
159
|
+
/**
|
|
160
|
+
* Seal a `RequestStatePayload` into a compact, integrity-protected token.
|
|
161
|
+
*
|
|
162
|
+
* Wire format:
|
|
163
|
+
* base64url(utf8(canonicalJson(payload))) + "." + base64url(hmacSha256)
|
|
164
|
+
*
|
|
165
|
+
* The HMAC covers the base64url-encoded JSON string (as UTF-8 bytes), not the
|
|
166
|
+
* raw JSON, so the MAC binds the encoding. Both segments are base64url (no
|
|
167
|
+
* padding, URL-safe alphabet).
|
|
168
|
+
*
|
|
169
|
+
* @param payload - Fully-formed `RequestStatePayload`. The caller is responsible
|
|
170
|
+
* for generating the `nonce`; see `types.ts` for guidance.
|
|
171
|
+
* @param key - HMAC-SHA256 key from `importStateKey` or `generateStateKey`.
|
|
172
|
+
* @returns Opaque token string to carry in `InputRequiredSignal.requestState`.
|
|
173
|
+
*/
|
|
174
|
+
export async function sealRequestState(payload, key) {
|
|
175
|
+
const canonical = canonicalJson(payload);
|
|
176
|
+
const encodedJson = new TextEncoder().encode(canonical);
|
|
177
|
+
const b64uJson = toBase64Url(encodedJson);
|
|
178
|
+
// HMAC is computed over the UTF-8 bytes of the base64url string, not over
|
|
179
|
+
// the raw JSON bytes. This ensures the MAC is over the wire representation.
|
|
180
|
+
const hmacInput = new TextEncoder().encode(b64uJson);
|
|
181
|
+
const hmacBuffer = await crypto.subtle.sign("HMAC", key, hmacInput);
|
|
182
|
+
const hmacBytes = new Uint8Array(hmacBuffer);
|
|
183
|
+
const b64uHmac = toBase64Url(hmacBytes);
|
|
184
|
+
return `${b64uJson}.${b64uHmac}`;
|
|
185
|
+
}
|
|
186
|
+
// ── Verify ────────────────────────────────────────────────────────────────────
|
|
187
|
+
/**
|
|
188
|
+
* Verify a `requestState` token against the expected claims for the current request.
|
|
189
|
+
*
|
|
190
|
+
* The input `token` is ATTACKER-CONTROLLED (the spec requires treating it as
|
|
191
|
+
* such). Checks run in order: integrity first (so a tampered payload never
|
|
192
|
+
* reaches field comparison), then bindings from most-impactful to least.
|
|
193
|
+
*
|
|
194
|
+
* Rejection order: tampered → wrong_principal → expired → wrong_method → wrong_params
|
|
195
|
+
*
|
|
196
|
+
* Each rejection reason is distinct so the server can distinguish attack
|
|
197
|
+
* patterns in logs / metrics without leaking the payload to the client
|
|
198
|
+
* (the client receives only the generic -32602 error code and a safe message).
|
|
199
|
+
*
|
|
200
|
+
* @param token - The token as received from the client (untrusted).
|
|
201
|
+
* @param key - The server's HMAC-SHA256 signing key.
|
|
202
|
+
* @param expected - Values derived from the CURRENT (retry) request.
|
|
203
|
+
* @param expected.principal - Authenticated principal (JWT sub, …). Pass `""` when
|
|
204
|
+
* the endpoint is unauthenticated; the token's `sub`
|
|
205
|
+
* must also be `""` for a match.
|
|
206
|
+
* @param expected.method - JSON-RPC method of the retry request.
|
|
207
|
+
* @param expected.paramsDigest - Pre-computed digest of the retry's salient params.
|
|
208
|
+
* Avoids double-hashing: compute once, pass here and
|
|
209
|
+
* keep for business logic.
|
|
210
|
+
* @param expected.nowSecs - Wall-clock Unix epoch seconds. Defaults to
|
|
211
|
+
* `Math.floor(Date.now() / 1000)`. Override in tests.
|
|
212
|
+
*/
|
|
213
|
+
export async function verifyRequestState(token, key, expected) {
|
|
214
|
+
// ── 1. Structural parse ─────────────────────────────────────────────────────
|
|
215
|
+
const dotIdx = token.indexOf(".");
|
|
216
|
+
if (dotIdx < 1 || dotIdx === token.length - 1) {
|
|
217
|
+
return {
|
|
218
|
+
ok: false,
|
|
219
|
+
reason: "tampered",
|
|
220
|
+
message: "Token format invalid: expected <base64url>.<base64url>",
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
const b64uJson = token.slice(0, dotIdx);
|
|
224
|
+
const b64uHmac = token.slice(dotIdx + 1);
|
|
225
|
+
// ── 2. HMAC integrity check ─────────────────────────────────────────────────
|
|
226
|
+
// Must run before any field comparison: a tampered payload must never reach
|
|
227
|
+
// principal/method/params comparison where it could leak information.
|
|
228
|
+
const hmacBytes = fromBase64Url(b64uHmac);
|
|
229
|
+
if (hmacBytes === null) {
|
|
230
|
+
return {
|
|
231
|
+
ok: false,
|
|
232
|
+
reason: "tampered",
|
|
233
|
+
message: "HMAC segment is not valid base64url",
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
const hmacInput = new TextEncoder().encode(b64uJson);
|
|
237
|
+
let valid;
|
|
238
|
+
try {
|
|
239
|
+
valid = await crypto.subtle.verify("HMAC", key, hmacBytes, hmacInput);
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
// Key algorithm mismatch or corrupt hmacBytes — treat as tampered.
|
|
243
|
+
valid = false;
|
|
244
|
+
}
|
|
245
|
+
if (!valid) {
|
|
246
|
+
return {
|
|
247
|
+
ok: false,
|
|
248
|
+
reason: "tampered",
|
|
249
|
+
message: "HMAC verification failed: payload was modified after sealing or wrong key",
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
// ── 3. Decode payload (JSON bytes from base64url) ──────────────────────────
|
|
253
|
+
const jsonBytes = fromBase64Url(b64uJson);
|
|
254
|
+
if (jsonBytes === null) {
|
|
255
|
+
// HMAC passed but base64url decode failed — structural corruption
|
|
256
|
+
return {
|
|
257
|
+
ok: false,
|
|
258
|
+
reason: "tampered",
|
|
259
|
+
message: "Payload segment is not valid base64url",
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
let payload;
|
|
263
|
+
try {
|
|
264
|
+
const jsonText = new TextDecoder("utf-8", { fatal: true }).decode(jsonBytes);
|
|
265
|
+
const parsed = JSON.parse(jsonText);
|
|
266
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
267
|
+
throw new TypeError("payload must be a JSON object");
|
|
268
|
+
}
|
|
269
|
+
// Narrow to RequestStatePayload — field-level type checks happen below.
|
|
270
|
+
payload = parsed;
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
return {
|
|
274
|
+
ok: false,
|
|
275
|
+
reason: "tampered",
|
|
276
|
+
message: "Payload is not a valid JSON object",
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
// ── 4. Principal binding ────────────────────────────────────────────────────
|
|
280
|
+
if (payload.sub !== expected.principal) {
|
|
281
|
+
return {
|
|
282
|
+
ok: false,
|
|
283
|
+
reason: "wrong_principal",
|
|
284
|
+
message: "Token principal does not match the current authenticated user",
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
// ── 5. Expiry ──────────────────────────────────────────────────────────────
|
|
288
|
+
const nowSecs = expected.nowSecs ?? Math.floor(Date.now() / 1000);
|
|
289
|
+
if (typeof payload.exp !== "number" || payload.exp <= nowSecs) {
|
|
290
|
+
return {
|
|
291
|
+
ok: false,
|
|
292
|
+
reason: "expired",
|
|
293
|
+
message: `Token expired (exp=${payload.exp}, now=${nowSecs})`,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
// ── 6. Method binding ──────────────────────────────────────────────────────
|
|
297
|
+
if (payload.method !== expected.method) {
|
|
298
|
+
return {
|
|
299
|
+
ok: false,
|
|
300
|
+
reason: "wrong_method",
|
|
301
|
+
message: `Token method "${payload.method}" does not match request method "${expected.method}"`,
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
// ── 7. Params binding ──────────────────────────────────────────────────────
|
|
305
|
+
if (payload.paramsDigest !== expected.paramsDigest) {
|
|
306
|
+
return {
|
|
307
|
+
ok: false,
|
|
308
|
+
reason: "wrong_params",
|
|
309
|
+
message: "Token paramsDigest does not match the current request parameters",
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
return { ok: true, payload };
|
|
313
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
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
|
+
import type { MrtrReplayStore } from "./replay-store.js";
|
|
12
|
+
import { type RequestStateRejectionReason } from "./request-state.js";
|
|
13
|
+
/** Bind a requestState to the retry that is attempting to spend it. */
|
|
14
|
+
export interface MrtrRetryBindings {
|
|
15
|
+
readonly principal: string;
|
|
16
|
+
readonly method: string;
|
|
17
|
+
readonly paramsDigest: string;
|
|
18
|
+
}
|
|
19
|
+
/** Inputs required to decide whether one MRTR retry is admissible. */
|
|
20
|
+
export interface GuardMrtrRetryInput {
|
|
21
|
+
/** Presence matters; response contents remain untrusted handler input. */
|
|
22
|
+
readonly inputResponses?: Record<string, unknown>;
|
|
23
|
+
/** Attacker-controlled state echoed by the client, when any. */
|
|
24
|
+
readonly requestState?: string;
|
|
25
|
+
/** Null deliberately represents the explicitly unprotected deployment mode. */
|
|
26
|
+
readonly key: CryptoKey | null;
|
|
27
|
+
/** Required only when a signed requestState is presented. */
|
|
28
|
+
readonly replayStore: MrtrReplayStore | null;
|
|
29
|
+
readonly bindings: MrtrRetryBindings;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Transport-neutral admission outcome.
|
|
33
|
+
*
|
|
34
|
+
* `accepted.retryVerified` is deliberately tri-state: absent for a first leg,
|
|
35
|
+
* false for the configured unprotected mode, and true only after signature,
|
|
36
|
+
* binding and atomic nonce reservation all succeeded.
|
|
37
|
+
*/
|
|
38
|
+
export type MrtrRetryGuardOutcome = {
|
|
39
|
+
readonly kind: "accepted";
|
|
40
|
+
readonly retryVerified?: boolean;
|
|
41
|
+
} | {
|
|
42
|
+
readonly kind: "missing_state";
|
|
43
|
+
} | {
|
|
44
|
+
readonly kind: "invalid_state";
|
|
45
|
+
readonly reason: RequestStateRejectionReason;
|
|
46
|
+
} | {
|
|
47
|
+
readonly kind: "replay_store_unavailable";
|
|
48
|
+
readonly reason: "missing" | "consume_failed";
|
|
49
|
+
} | {
|
|
50
|
+
readonly kind: "replayed";
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Decide whether a retried request may enter application code.
|
|
54
|
+
*
|
|
55
|
+
* A signed state is verified and its nonce is atomically reserved before the
|
|
56
|
+
* handler runs. This intentionally gives at-most-once admission, not exactly
|
|
57
|
+
* once completion: a transport adapter must never move consumption after a
|
|
58
|
+
* business side effect.
|
|
59
|
+
*/
|
|
60
|
+
export declare function guardMrtrRetry(input: GuardMrtrRetryInput): Promise<MrtrRetryGuardOutcome>;
|
|
61
|
+
//# sourceMappingURL=retry-guard.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retry-guard.d.ts","sourceRoot":"","sources":["../../../src/src/mrtr/retry-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EACL,KAAK,2BAA2B,EAEjC,MAAM,oBAAoB,CAAC;AAE5B,uEAAuE;AACvE,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;CAC/B;AAED,sEAAsE;AACtE,MAAM,WAAW,mBAAmB;IAClC,0EAA0E;IAC1E,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClD,gEAAgE;IAChE,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,+EAA+E;IAC/E,QAAQ,CAAC,GAAG,EAAE,SAAS,GAAG,IAAI,CAAC;IAC/B,6DAA6D;IAC7D,QAAQ,CAAC,WAAW,EAAE,eAAe,GAAG,IAAI,CAAC;IAC7C,QAAQ,CAAC,QAAQ,EAAE,iBAAiB,CAAC;CACtC;AAED;;;;;;GAMG;AACH,MAAM,MAAM,qBAAqB,GAC7B;IAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,OAAO,CAAA;CAAE,GAC/D;IAAE,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAA;CAAE,GAClC;IACA,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC;IAC/B,QAAQ,CAAC,MAAM,EAAE,2BAA2B,CAAC;CAC9C,GACC;IACA,QAAQ,CAAC,IAAI,EAAE,0BAA0B,CAAC;IAC1C,QAAQ,CAAC,MAAM,EAAE,SAAS,GAAG,gBAAgB,CAAC;CAC/C,GACC;IAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAA;CAAE,CAAC;AAElC;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,KAAK,EAAE,mBAAmB,GACzB,OAAO,CAAC,qBAAqB,CAAC,CA0ChC"}
|
|
@@ -0,0 +1,53 @@
|
|
|
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
|
+
import { verifyRequestState, } from "./request-state.js";
|
|
12
|
+
/**
|
|
13
|
+
* Decide whether a retried request may enter application code.
|
|
14
|
+
*
|
|
15
|
+
* A signed state is verified and its nonce is atomically reserved before the
|
|
16
|
+
* handler runs. This intentionally gives at-most-once admission, not exactly
|
|
17
|
+
* once completion: a transport adapter must never move consumption after a
|
|
18
|
+
* business side effect.
|
|
19
|
+
*/
|
|
20
|
+
export async function guardMrtrRetry(input) {
|
|
21
|
+
const hasInputResponses = input.inputResponses !== undefined;
|
|
22
|
+
const { requestState, key } = input;
|
|
23
|
+
if (hasInputResponses && requestState === undefined && key !== null) {
|
|
24
|
+
return { kind: "missing_state" };
|
|
25
|
+
}
|
|
26
|
+
if (requestState === undefined) {
|
|
27
|
+
return { kind: "accepted" };
|
|
28
|
+
}
|
|
29
|
+
if (key === null) {
|
|
30
|
+
return { kind: "accepted", retryVerified: false };
|
|
31
|
+
}
|
|
32
|
+
const verdict = await verifyRequestState(requestState, key, input.bindings);
|
|
33
|
+
if (!verdict.ok) {
|
|
34
|
+
return { kind: "invalid_state", reason: verdict.reason };
|
|
35
|
+
}
|
|
36
|
+
if (input.replayStore === null) {
|
|
37
|
+
return { kind: "replay_store_unavailable", reason: "missing" };
|
|
38
|
+
}
|
|
39
|
+
let consumed;
|
|
40
|
+
try {
|
|
41
|
+
const result = await input.replayStore.consume(verdict.payload.nonce, verdict.payload.exp);
|
|
42
|
+
if (result !== true && result !== false) {
|
|
43
|
+
throw new Error("mrtr.replayStore.consume() must return a boolean");
|
|
44
|
+
}
|
|
45
|
+
consumed = result;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return { kind: "replay_store_unavailable", reason: "consume_failed" };
|
|
49
|
+
}
|
|
50
|
+
return consumed
|
|
51
|
+
? { kind: "accepted", retryVerified: true }
|
|
52
|
+
: { kind: "replayed" };
|
|
53
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
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
|
+
/** The three request types a server may embed in an InputRequiredResult (spec 2026-07-28). */
|
|
15
|
+
export type InputRequestMethod = "elicitation/create" | "sampling/createMessage" | "roots/list";
|
|
16
|
+
/** One slot in the inputRequests map. */
|
|
17
|
+
export interface InputRequestEntry {
|
|
18
|
+
readonly method: InputRequestMethod;
|
|
19
|
+
readonly params: Record<string, unknown>;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Return this from a tool/resource handler to trigger an MRTR round-trip.
|
|
23
|
+
*
|
|
24
|
+
* Spec rule 6 (MUST): at least one of inputRequests or requestState MUST
|
|
25
|
+
* be present. The framework validates this and returns -32603 Internal Error
|
|
26
|
+
* if both are absent -- that is a server-authoring error, not a client error.
|
|
27
|
+
*
|
|
28
|
+
* Security note: requestState passes through the client untouched and is
|
|
29
|
+
* therefore ATTACKER-CONTROLLED on retry. Use sealRequestState() to bind it
|
|
30
|
+
* cryptographically to the authenticated principal, the originating method, and
|
|
31
|
+
* the request parameters. Do NOT use an unprotected requestState for
|
|
32
|
+
* authorization or resource-access decisions.
|
|
33
|
+
*/
|
|
34
|
+
export interface InputRequiredSignal {
|
|
35
|
+
readonly resultType: "input_required";
|
|
36
|
+
/**
|
|
37
|
+
* Map of server-assigned string ids to sub-request objects.
|
|
38
|
+
* Keys must be unique within the scope of the originating request (spec rule 2).
|
|
39
|
+
*/
|
|
40
|
+
readonly inputRequests?: Record<string, InputRequestEntry>;
|
|
41
|
+
/**
|
|
42
|
+
* Opaque token the client must echo on retry (spec rule 2, client rule 2).
|
|
43
|
+
*
|
|
44
|
+
* When McpAppOptions.mrtr.signingKey is configured, produce this value
|
|
45
|
+
* by calling sealRequestState(). The sealed token binds the principal,
|
|
46
|
+
* method, params-digest, expiry and a random nonce under HMAC-SHA256 so the
|
|
47
|
+
* server can reject a tampered or replayed token on retry.
|
|
48
|
+
*
|
|
49
|
+
* Without a signing key, the value is passed through to the client and back
|
|
50
|
+
* as-is -- adequate only when requestState influences nothing that requires
|
|
51
|
+
* integrity.
|
|
52
|
+
*/
|
|
53
|
+
readonly requestState?: string;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Configuration for the MRTR subsystem in McpAppOptions.
|
|
57
|
+
*
|
|
58
|
+
* Wire this in to McpAppOptions.mrtr before calling start() or startHttp().
|
|
59
|
+
*/
|
|
60
|
+
export interface MrtrOptions {
|
|
61
|
+
/**
|
|
62
|
+
* 64-character lowercase hex string (32 bytes) used as the HMAC-SHA256 key
|
|
63
|
+
* for sealing and verifying requestState tokens.
|
|
64
|
+
*
|
|
65
|
+
* Generate once per deployment with:
|
|
66
|
+
* bytesToHex(crypto.getRandomValues(new Uint8Array(32)))
|
|
67
|
+
*
|
|
68
|
+
* In load-balanced deployments all instances MUST share the same key; rotating
|
|
69
|
+
* the key immediately invalidates all in-flight requestState tokens.
|
|
70
|
+
*
|
|
71
|
+
* If absent, the framework emits a [WARN] at startup and passes requestState
|
|
72
|
+
* through without integrity protection. Handlers MUST NOT use unprotected
|
|
73
|
+
* requestState for authorization or resource-access decisions.
|
|
74
|
+
*/
|
|
75
|
+
signingKey?: string;
|
|
76
|
+
/**
|
|
77
|
+
* Lifetime of a sealed requestState token in seconds.
|
|
78
|
+
*
|
|
79
|
+
* Default: 300 (5 minutes). The spec warns that these measures do NOT
|
|
80
|
+
* guarantee single-use. Deployers who need at-most-once semantics MUST
|
|
81
|
+
* enforce that invariant server-side (e.g., by consuming the nonce from a
|
|
82
|
+
* shared store on the first use).
|
|
83
|
+
*/
|
|
84
|
+
defaultTtlSecs?: number;
|
|
85
|
+
/**
|
|
86
|
+
* Atomic store used to reject a second use of the same signed requestState.
|
|
87
|
+
*
|
|
88
|
+
* With a signing key and no explicit store, McpApp uses a process-local
|
|
89
|
+
* MemoryMrtrReplayStore. That protects one continuously running process only:
|
|
90
|
+
* a restart loses its reservations. Every instance in a load-balanced
|
|
91
|
+
* deployment MUST receive the same durable shared store implementation.
|
|
92
|
+
*
|
|
93
|
+
* The nonce is consumed before the handler runs. This provides at-most-once
|
|
94
|
+
* admission, not exactly-once completion: if the handler commits a mutation
|
|
95
|
+
* and its response is lost, the same token is still rejected on retry.
|
|
96
|
+
*/
|
|
97
|
+
replayStore?: import("./replay-store.js").MrtrReplayStore;
|
|
98
|
+
}
|
|
99
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/src/mrtr/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,8FAA8F;AAC9F,MAAM,MAAM,kBAAkB,GAC1B,oBAAoB,GACpB,wBAAwB,GACxB,YAAY,CAAC;AAEjB,yCAAyC;AACzC,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,MAAM,EAAE,kBAAkB,CAAC;IACpC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC1C;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,UAAU,EAAE,gBAAgB,CAAC;IACtC;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;IAC3D;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;CAChC;AAED;;;;GAIG;AACH,MAAM,WAAW,WAAW;IAC1B;;;;;;;;;;;;;OAaG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;;;;;OAOG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB;;;;;;;;;;;OAWG;IACH,WAAW,CAAC,EAAE,OAAO,mBAAmB,EAAE,eAAe,CAAC;CAC3D"}
|
|
@@ -0,0 +1,14 @@
|
|
|
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
|
+
export {};
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server Metrics Collector for @casys/mcp-server
|
|
3
|
+
*
|
|
4
|
+
* In-memory counters, histograms, and gauges with Prometheus text format export.
|
|
5
|
+
* Designed to be embedded in McpApp — no external dependencies.
|
|
6
|
+
*
|
|
7
|
+
* @module lib/server/observability/metrics
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Histogram bucket
|
|
11
|
+
*/
|
|
12
|
+
interface HistogramBucket {
|
|
13
|
+
le: number;
|
|
14
|
+
count: number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Latency histogram with cumulative buckets
|
|
18
|
+
*/
|
|
19
|
+
interface Histogram {
|
|
20
|
+
buckets: HistogramBucket[];
|
|
21
|
+
sum: number;
|
|
22
|
+
count: number;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Metrics snapshot returned by getMetrics()
|
|
26
|
+
*/
|
|
27
|
+
export interface ServerMetricsSnapshot {
|
|
28
|
+
counters: {
|
|
29
|
+
tool_calls_total: number;
|
|
30
|
+
tool_calls_success: number;
|
|
31
|
+
tool_calls_failed: number;
|
|
32
|
+
requests_rate_limited: number;
|
|
33
|
+
requests_rejected_backpressure: number;
|
|
34
|
+
auth_success: number;
|
|
35
|
+
auth_failed: number;
|
|
36
|
+
auth_cache_hits: number;
|
|
37
|
+
};
|
|
38
|
+
histograms: {
|
|
39
|
+
tool_call_duration_ms: Histogram;
|
|
40
|
+
};
|
|
41
|
+
gauges: {
|
|
42
|
+
active_requests: number;
|
|
43
|
+
queued_requests: number;
|
|
44
|
+
rate_limiter_keys: number;
|
|
45
|
+
};
|
|
46
|
+
collected_at: number;
|
|
47
|
+
uptime_seconds: number;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Server metrics collector.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```typescript
|
|
54
|
+
* const metrics = new ServerMetrics();
|
|
55
|
+
* metrics.recordToolCall("my_tool", true, 42);
|
|
56
|
+
* console.log(metrics.toPrometheusFormat());
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export declare class ServerMetrics {
|
|
60
|
+
private startTime;
|
|
61
|
+
private toolCallsTotal;
|
|
62
|
+
private toolCallsSuccess;
|
|
63
|
+
private toolCallsFailed;
|
|
64
|
+
private requestsRateLimited;
|
|
65
|
+
private requestsRejectedBackpressure;
|
|
66
|
+
private authSuccess;
|
|
67
|
+
private authFailed;
|
|
68
|
+
private authCacheHits;
|
|
69
|
+
private toolCallDuration;
|
|
70
|
+
private perTool;
|
|
71
|
+
private activeRequests;
|
|
72
|
+
private queuedRequests;
|
|
73
|
+
private rateLimiterKeys;
|
|
74
|
+
/**
|
|
75
|
+
* Record a completed tool call
|
|
76
|
+
*/
|
|
77
|
+
recordToolCall(toolName: string, success: boolean, durationMs: number): void;
|
|
78
|
+
recordRateLimited(): void;
|
|
79
|
+
recordBackpressureRejected(): void;
|
|
80
|
+
recordAuth(success: boolean): void;
|
|
81
|
+
recordAuthCacheHit(): void;
|
|
82
|
+
/**
|
|
83
|
+
* Update gauge values (called periodically or on-demand)
|
|
84
|
+
*/
|
|
85
|
+
setGauges(gauges: {
|
|
86
|
+
activeRequests?: number;
|
|
87
|
+
queuedRequests?: number;
|
|
88
|
+
rateLimiterKeys?: number;
|
|
89
|
+
}): void;
|
|
90
|
+
/**
|
|
91
|
+
* Get current metrics snapshot
|
|
92
|
+
*/
|
|
93
|
+
getSnapshot(): ServerMetricsSnapshot;
|
|
94
|
+
/**
|
|
95
|
+
* Prometheus text format export
|
|
96
|
+
*/
|
|
97
|
+
toPrometheusFormat(prefix?: string): string;
|
|
98
|
+
/**
|
|
99
|
+
* Reset all metrics
|
|
100
|
+
*/
|
|
101
|
+
reset(): void;
|
|
102
|
+
}
|
|
103
|
+
export {};
|
|
104
|
+
//# sourceMappingURL=metrics.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"metrics.d.ts","sourceRoot":"","sources":["../../../src/src/observability/metrics.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;GAEG;AACH,UAAU,eAAe;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;GAEG;AACH,UAAU,SAAS;IACjB,OAAO,EAAE,eAAe,EAAE,CAAC;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;CACf;AAyBD;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE;QACR,gBAAgB,EAAE,MAAM,CAAC;QACzB,kBAAkB,EAAE,MAAM,CAAC;QAC3B,iBAAiB,EAAE,MAAM,CAAC;QAC1B,qBAAqB,EAAE,MAAM,CAAC;QAC9B,8BAA8B,EAAE,MAAM,CAAC;QACvC,YAAY,EAAE,MAAM,CAAC;QACrB,WAAW,EAAE,MAAM,CAAC;QACpB,eAAe,EAAE,MAAM,CAAC;KACzB,CAAC;IACF,UAAU,EAAE;QACV,qBAAqB,EAAE,SAAS,CAAC;KAClC,CAAC;IACF,MAAM,EAAE;QACN,eAAe,EAAE,MAAM,CAAC;QACxB,eAAe,EAAE,MAAM,CAAC;QACxB,iBAAiB,EAAE,MAAM,CAAC;KAC3B,CAAC;IACF,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;CACxB;AAYD;;;;;;;;;GASG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,SAAS,CAAc;IAG/B,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,gBAAgB,CAAK;IAC7B,OAAO,CAAC,eAAe,CAAK;IAC5B,OAAO,CAAC,mBAAmB,CAAK;IAChC,OAAO,CAAC,4BAA4B,CAAK;IACzC,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,aAAa,CAAK;IAG1B,OAAO,CAAC,gBAAgB,CAAqB;IAG7C,OAAO,CAAC,OAAO,CAAqC;IAGpD,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,eAAe,CAAK;IAE5B;;OAEG;IACH,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI;IAqB5E,iBAAiB,IAAI,IAAI;IAIzB,0BAA0B,IAAI,IAAI;IAIlC,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;IAKlC,kBAAkB,IAAI,IAAI;IAI1B;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE;QAChB,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,eAAe,CAAC,EAAE,MAAM,CAAC;KAC1B,GAAG,IAAI;IAYR;;OAEG;IACH,WAAW,IAAI,qBAAqB;IAyBpC;;OAEG;IACH,kBAAkB,CAAC,MAAM,SAAe,GAAG,MAAM;IA0GjD;;OAEG;IACH,KAAK,IAAI,IAAI;CAgBd"}
|