@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,89 +0,0 @@
1
- /**
2
- * Content Security Policy helpers for MCP Apps HTML resources.
3
- *
4
- * Provides CSP header generation and HTML meta tag injection to protect
5
- * against XSS and unauthorized resource loading in MCP App iframes.
6
- *
7
- * @module lib/server/security/csp
8
- */
9
-
10
- /** Options for generating a CSP header value. */
11
- export interface CspOptions {
12
- /** Additional allowed script sources (e.g. CDN URLs). */
13
- readonly scriptSources?: readonly string[];
14
- /** Additional allowed connect sources (e.g. WebSocket endpoints). */
15
- readonly connectSources?: readonly string[];
16
- /** Additional allowed image sources (e.g. tile servers). */
17
- readonly imgSources?: readonly string[];
18
- /** Additional allowed frame ancestors. */
19
- readonly frameAncestors?: readonly string[];
20
- /**
21
- * Allow `'unsafe-inline'` for scripts and styles (default: true).
22
- * MCP Apps typically need inline scripts/styles for single-file HTML UIs.
23
- */
24
- readonly allowInline?: boolean;
25
- }
26
-
27
- /**
28
- * Build a Content-Security-Policy header value.
29
- *
30
- * Uses `default-src 'none'` as the baseline (deny-all), then explicitly allows
31
- * only what MCP App UIs need. Inline scripts/styles are allowed by default
32
- * since MCP Apps are typically single-file HTML with inline code.
33
- *
34
- * @param options - CSP configuration
35
- * @returns CSP header value string
36
- */
37
- export function buildCspHeader(options: CspOptions = {}): string {
38
- const allowInline = options.allowInline !== false;
39
- const inlineDirective = allowInline ? " 'unsafe-inline'" : "";
40
-
41
- const scriptSrc = [
42
- `'self'${inlineDirective}`,
43
- ...(options.scriptSources ?? []),
44
- ].join(" ");
45
- const connectSrc = ["'self'", ...(options.connectSources ?? [])].join(" ");
46
- const frameAncestors = ["'self'", ...(options.frameAncestors ?? [])].join(
47
- " ",
48
- );
49
-
50
- return [
51
- `default-src 'none'`,
52
- `script-src ${scriptSrc}`,
53
- `style-src 'self'${inlineDirective}`,
54
- `img-src 'self' data: ${(options.imgSources ?? []).join(" ")}`.trim(),
55
- `font-src 'self'`,
56
- `connect-src ${connectSrc}`,
57
- `frame-ancestors ${frameAncestors}`,
58
- `base-uri 'self'`,
59
- ].join("; ");
60
- }
61
-
62
- /**
63
- * Inject a CSP meta tag into HTML content.
64
- *
65
- * Inserts `<meta http-equiv="Content-Security-Policy" content="...">` right
66
- * after the opening `<head>` tag. If no `<head>` tag exists, prepends to content.
67
- *
68
- * This provides CSP enforcement even when HTTP headers are unavailable
69
- * (e.g. STDIO transport where there are no HTTP response headers).
70
- *
71
- * @param html - Original HTML content
72
- * @param cspValue - CSP header value (from buildCspHeader)
73
- * @returns HTML with injected CSP meta tag
74
- */
75
- export function injectCspMetaTag(html: string, cspValue: string): string {
76
- const escaped = cspValue.replace(/"/g, "&quot;");
77
- const metaTag =
78
- `<meta http-equiv="Content-Security-Policy" content="${escaped}">`;
79
-
80
- // Inject right after <head> (case-insensitive, handles attributes)
81
- const headMatch = html.match(/<head[^>]*>/i);
82
- if (headMatch && headMatch.index !== undefined) {
83
- const insertPos = headMatch.index + headMatch[0].length;
84
- return html.slice(0, insertPos) + metaTag + html.slice(insertPos);
85
- }
86
-
87
- // Fallback: prepend to content
88
- return metaTag + html;
89
- }
@@ -1,223 +0,0 @@
1
- /**
2
- * HMAC-SHA256 Message Signer for PostMessage Channels
3
- *
4
- * Signs and verifies JSON-RPC messages exchanged via PostMessage.
5
- * Each message gains `_hmac` (signature) and `_seq` (monotonic counter)
6
- * fields for authentication and anti-replay protection.
7
- *
8
- * HMAC payload: `"${_seq}:${id}:${method}:${JSON.stringify(params|result|error)}"`
9
- *
10
- * Uses the Web Crypto API exclusively (Deno, Node.js 18+, browsers).
11
- *
12
- * @module server/security/message-signer
13
- */
14
-
15
- // ---------------------------------------------------------------------------
16
- // Hex utilities
17
- // ---------------------------------------------------------------------------
18
-
19
- /** Convert a Uint8Array to a lowercase hex string. */
20
- export function bytesToHex(bytes: Uint8Array): string {
21
- const out: string[] = new Array(bytes.length);
22
- for (let i = 0; i < bytes.length; i++) {
23
- out[i] = bytes[i].toString(16).padStart(2, "0");
24
- }
25
- return out.join("");
26
- }
27
-
28
- /** Convert a hex string to a Uint8Array. Returns null if invalid hex. */
29
- export function hexToBytes(hex: string): Uint8Array | null {
30
- if (hex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(hex)) return null;
31
- const bytes = new Uint8Array(hex.length / 2);
32
- for (let i = 0; i < hex.length; i += 2) {
33
- bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
34
- }
35
- return bytes;
36
- }
37
-
38
- // ---------------------------------------------------------------------------
39
- // Types
40
- // ---------------------------------------------------------------------------
41
-
42
- /** A JSON-RPC message with optional HMAC signature fields. */
43
- export interface SignedMessage {
44
- jsonrpc: "2.0";
45
- id?: string | number;
46
- method?: string;
47
- params?: unknown;
48
- result?: unknown;
49
- error?: unknown;
50
- _hmac?: string;
51
- _seq?: number;
52
- [key: string]: unknown;
53
- }
54
-
55
- /** Result of verifying a signed message. */
56
- export interface VerifyResult {
57
- /** Whether the signature is valid. */
58
- valid: boolean;
59
- /** The message with `_hmac` and `_seq` stripped. */
60
- message: SignedMessage;
61
- /** Error description when valid is false. */
62
- error?: string;
63
- }
64
-
65
- // ---------------------------------------------------------------------------
66
- // HMAC Payload
67
- // ---------------------------------------------------------------------------
68
-
69
- /**
70
- * Build the canonical HMAC payload string.
71
- *
72
- * Format: `"${seq}:${id}:${method}:${body}"`
73
- */
74
- export function buildHmacPayload(message: SignedMessage, seq: number): string {
75
- const id = message.id ?? "";
76
- const method = message.method ?? "";
77
- let body: string;
78
- if (message.params !== undefined) body = JSON.stringify(message.params);
79
- else if (message.result !== undefined) body = JSON.stringify(message.result);
80
- else if (message.error !== undefined) body = JSON.stringify(message.error);
81
- else body = "{}";
82
- return `${seq}:${id}:${method}:${body}`;
83
- }
84
-
85
- // ---------------------------------------------------------------------------
86
- // MessageSigner
87
- // ---------------------------------------------------------------------------
88
-
89
- /**
90
- * HMAC-SHA256 message signer/verifier for a single PostMessage channel.
91
- *
92
- * Maintains separate sequence counters for send and receive directions.
93
- *
94
- * @example
95
- * ```ts
96
- * const signer = new MessageSigner(secretHex);
97
- * await signer.init();
98
- *
99
- * const signed = await signer.sign({ jsonrpc: '2.0', method: 'tools/call', params: {} });
100
- * const result = await signer.verify(signed);
101
- * ```
102
- */
103
- export class MessageSigner {
104
- private cryptoKey: CryptoKey | null = null;
105
- private sendSeq = 0;
106
- private lastRecvSeq = -1;
107
- private readonly secretHex: string;
108
-
109
- /**
110
- * Generate a 32-byte (256-bit) random hex secret for channel authentication.
111
- * Uses `crypto.getRandomValues()` for cryptographic randomness.
112
- *
113
- * @returns 64-character lowercase hex string (32 bytes)
114
- */
115
- static generateSecret(): string {
116
- const bytes = new Uint8Array(32);
117
- crypto.getRandomValues(bytes);
118
- return bytesToHex(bytes);
119
- }
120
-
121
- constructor(secretHex: string) {
122
- this.secretHex = secretHex;
123
- }
124
-
125
- /**
126
- * Initialize the CryptoKey. Must be called before sign()/verify().
127
- * Idempotent.
128
- */
129
- async init(): Promise<void> {
130
- if (this.cryptoKey) return;
131
- const keyBytes = hexToBytes(this.secretHex);
132
- if (!keyBytes) {
133
- throw new Error(
134
- "[MessageSigner] Invalid secret: must be a valid hex string. " +
135
- "Use MessageSigner.generateSecret() to create one.",
136
- );
137
- }
138
- this.cryptoKey = await crypto.subtle.importKey(
139
- "raw",
140
- keyBytes.buffer as ArrayBuffer,
141
- { name: "HMAC", hash: "SHA-256" },
142
- false,
143
- ["sign", "verify"],
144
- );
145
- }
146
-
147
- /** Sign a JSON-RPC message by adding `_hmac` and `_seq` fields. */
148
- async sign(message: SignedMessage): Promise<SignedMessage> {
149
- if (!this.cryptoKey) {
150
- throw new Error(
151
- "[MessageSigner] Not initialized. Call init() before sign().",
152
- );
153
- }
154
- const seq = this.sendSeq++;
155
- const payload = buildHmacPayload(message, seq);
156
- const sig = await crypto.subtle.sign(
157
- "HMAC",
158
- this.cryptoKey,
159
- new TextEncoder().encode(payload),
160
- );
161
- return { ...message, _seq: seq, _hmac: bytesToHex(new Uint8Array(sig)) };
162
- }
163
-
164
- /**
165
- * Verify a signed message and strip `_hmac`/`_seq` fields.
166
- *
167
- * Rejects if: missing fields, replay (seq <= lastSeen), HMAC mismatch.
168
- */
169
- async verify(message: SignedMessage): Promise<VerifyResult> {
170
- if (!this.cryptoKey) {
171
- throw new Error(
172
- "[MessageSigner] Not initialized. Call init() before verify().",
173
- );
174
- }
175
- const { _hmac, _seq, ...clean } = message;
176
-
177
- if (_hmac === undefined || _seq === undefined) {
178
- return {
179
- valid: false,
180
- message: clean as SignedMessage,
181
- error: "Missing _hmac or _seq field",
182
- };
183
- }
184
- if (typeof _seq !== "number" || _seq <= this.lastRecvSeq) {
185
- return {
186
- valid: false,
187
- message: clean as SignedMessage,
188
- error:
189
- `Replay detected: _seq=${_seq} <= lastRecvSeq=${this.lastRecvSeq}`,
190
- };
191
- }
192
- const hmacBytes = hexToBytes(_hmac);
193
- if (!hmacBytes) {
194
- return {
195
- valid: false,
196
- message: clean as SignedMessage,
197
- error: "Invalid _hmac: not valid hex",
198
- };
199
- }
200
- const payload = buildHmacPayload(clean as SignedMessage, _seq);
201
- const isValid = await crypto.subtle.verify(
202
- "HMAC",
203
- this.cryptoKey,
204
- hmacBytes.buffer as ArrayBuffer,
205
- new TextEncoder().encode(payload),
206
- );
207
- if (!isValid) {
208
- return {
209
- valid: false,
210
- message: clean as SignedMessage,
211
- error: "HMAC signature mismatch",
212
- };
213
- }
214
- this.lastRecvSeq = _seq;
215
- return { valid: true, message: clean as SignedMessage };
216
- }
217
-
218
- /** Reset sequence counters (for testing). */
219
- reset(): void {
220
- this.sendSeq = 0;
221
- this.lastRecvSeq = -1;
222
- }
223
- }