@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.
- package/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/README.md +10 -627
- package/esm/mod.d.ts +1 -0
- package/esm/mod.js +1 -0
- package/package.json +28 -25
- 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/provider.ts +0 -49
- 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/mod.ts +0 -44
- 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/http/wire.ts +0 -41
- package/src/inspector/launcher.ts +0 -131
- package/src/mcp-app.ts +0 -4595
- package/src/middleware/backpressure.ts +0 -36
- package/src/middleware/mod.ts +0 -21
- package/src/middleware/rate-limit.ts +0 -45
- 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 -54
- package/src/mrtr/replay-store.ts +0 -103
- package/src/mrtr/request-state.ts +0 -435
- package/src/mrtr/retry-guard.ts +0 -110
- package/src/mrtr/types.ts +0 -107
- package/src/observability/metrics.ts +0 -336
- package/src/observability/mod.ts +0 -21
- 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/runtime/runtime.ts +0 -50
- package/src/runtime/types.ts +0 -130
- package/src/security/channel-hmac.ts +0 -140
- 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/mod.ts +0 -33
- package/src/tasks/task-store.ts +0 -1014
- package/src/transport/request-headers.ts +0 -661
- package/src/types.ts +0 -908
- package/src/ui/viewer-utils.ts +0 -117
- package/src/validation/schema-validator.ts +0 -307
|
@@ -1,324 +0,0 @@
|
|
|
1
|
-
// deno-lint-ignore-file no-process-global
|
|
2
|
-
/**
|
|
3
|
-
* Runtime adapter — Node.js implementation
|
|
4
|
-
*
|
|
5
|
-
* Implements the RuntimePort contract for Node.js.
|
|
6
|
-
* Drop-in replacement for runtime.ts (Deno) — swapped by build script.
|
|
7
|
-
*
|
|
8
|
-
* @see runtime-types.ts for the port contract
|
|
9
|
-
* @module lib/server/runtime.node
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
import { Buffer } from "node:buffer";
|
|
13
|
-
import {
|
|
14
|
-
mkdir as nodeMkdir,
|
|
15
|
-
readdir,
|
|
16
|
-
readFile,
|
|
17
|
-
rm,
|
|
18
|
-
writeFile,
|
|
19
|
-
} from "node:fs/promises";
|
|
20
|
-
import { createServer } from "node:http";
|
|
21
|
-
import type {
|
|
22
|
-
FetchHandler,
|
|
23
|
-
RuntimePort,
|
|
24
|
-
ServeHandle,
|
|
25
|
-
ServeOptions,
|
|
26
|
-
} from "./types.js";
|
|
27
|
-
|
|
28
|
-
// Re-export types so consumers import from a single module
|
|
29
|
-
export type { FetchHandler, ServeHandle, ServeOptions } from "./types.js";
|
|
30
|
-
|
|
31
|
-
class PayloadTooLargeError extends Error {
|
|
32
|
-
constructor(maxBytes: number) {
|
|
33
|
-
super(`Payload too large. Max ${maxBytes} bytes.`);
|
|
34
|
-
this.name = "PayloadTooLargeError";
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Get an environment variable.
|
|
40
|
-
*/
|
|
41
|
-
export function env(key: string): string | undefined {
|
|
42
|
-
return process.env[key];
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Read a UTF-8 text file.
|
|
47
|
-
* Returns null if the file does not exist.
|
|
48
|
-
*/
|
|
49
|
-
export async function readTextFile(path: string): Promise<string | null> {
|
|
50
|
-
try {
|
|
51
|
-
return await readFile(path, "utf-8");
|
|
52
|
-
} catch (err: unknown) {
|
|
53
|
-
if (
|
|
54
|
-
err && typeof err === "object" && "code" in err && err.code === "ENOENT"
|
|
55
|
-
) {
|
|
56
|
-
return null;
|
|
57
|
-
}
|
|
58
|
-
throw err;
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* Write a UTF-8 text file.
|
|
64
|
-
*/
|
|
65
|
-
export async function writeTextFile(
|
|
66
|
-
path: string,
|
|
67
|
-
content: string,
|
|
68
|
-
opts?: { mode?: number },
|
|
69
|
-
): Promise<void> {
|
|
70
|
-
await writeFile(path, content, { mode: opts?.mode });
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Create a directory.
|
|
75
|
-
*/
|
|
76
|
-
export async function mkdir(
|
|
77
|
-
path: string,
|
|
78
|
-
opts?: { recursive?: boolean; mode?: number },
|
|
79
|
-
): Promise<void> {
|
|
80
|
-
await nodeMkdir(path, { recursive: opts?.recursive, mode: opts?.mode });
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* Remove a file or empty directory. No-op if absent.
|
|
85
|
-
*/
|
|
86
|
-
export async function remove(path: string): Promise<void> {
|
|
87
|
-
try {
|
|
88
|
-
await rm(path);
|
|
89
|
-
} catch (err: unknown) {
|
|
90
|
-
if (isNodeNotFound(err)) {
|
|
91
|
-
return;
|
|
92
|
-
}
|
|
93
|
-
throw err;
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Read directory entry names. Returns [] if absent.
|
|
99
|
-
*/
|
|
100
|
-
export async function readDir(path: string): Promise<string[]> {
|
|
101
|
-
try {
|
|
102
|
-
return await readdir(path);
|
|
103
|
-
} catch (err: unknown) {
|
|
104
|
-
if (isNodeNotFound(err)) {
|
|
105
|
-
return [];
|
|
106
|
-
}
|
|
107
|
-
throw err;
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Start an HTTP server with a fetch-style handler.
|
|
113
|
-
* Uses node:http with a Request/Response adapter (compatible with Hono).
|
|
114
|
-
*/
|
|
115
|
-
export function serve(
|
|
116
|
-
options: ServeOptions,
|
|
117
|
-
handler: FetchHandler,
|
|
118
|
-
): ServeHandle {
|
|
119
|
-
const hostname = options.hostname ?? "0.0.0.0";
|
|
120
|
-
const maxBodyBytes = options.maxBodyBytes ?? null;
|
|
121
|
-
|
|
122
|
-
const server = createServer(async (nodeReq, nodeRes) => {
|
|
123
|
-
try {
|
|
124
|
-
const contentLength = nodeReq.headers["content-length"];
|
|
125
|
-
if (maxBodyBytes !== null && contentLength) {
|
|
126
|
-
const length = Array.isArray(contentLength)
|
|
127
|
-
? Number(contentLength[0])
|
|
128
|
-
: Number(contentLength);
|
|
129
|
-
if (!Number.isNaN(length) && length > maxBodyBytes) {
|
|
130
|
-
nodeRes.writeHead(413);
|
|
131
|
-
nodeRes.end(`Payload too large. Max ${maxBodyBytes} bytes.`);
|
|
132
|
-
return;
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// Convert Node.js IncomingMessage → Web Request
|
|
137
|
-
// Prefer Host header (correct behind reverse proxy) over bound hostname
|
|
138
|
-
const host = nodeReq.headers.host ?? `${hostname}:${options.port}`;
|
|
139
|
-
const url = `http://${host}${nodeReq.url ?? "/"}`;
|
|
140
|
-
const headers = new Headers();
|
|
141
|
-
for (const [key, value] of Object.entries(nodeReq.headers)) {
|
|
142
|
-
if (value) {
|
|
143
|
-
if (Array.isArray(value)) {
|
|
144
|
-
for (const v of value) headers.append(key, v);
|
|
145
|
-
} else {
|
|
146
|
-
headers.set(key, value);
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
const body = nodeReq.method !== "GET" && nodeReq.method !== "HEAD"
|
|
152
|
-
? await collectBody(nodeReq, maxBodyBytes)
|
|
153
|
-
: undefined;
|
|
154
|
-
|
|
155
|
-
const request = new Request(url, {
|
|
156
|
-
method: nodeReq.method ?? "GET",
|
|
157
|
-
headers,
|
|
158
|
-
body,
|
|
159
|
-
// @ts-ignore: duplex needed for streaming requests in Node 20+
|
|
160
|
-
duplex: body ? "half" : undefined,
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
// Call the fetch handler (Hono, etc.)
|
|
164
|
-
const response = await handler(request);
|
|
165
|
-
|
|
166
|
-
// Convert Web Response → Node.js ServerResponse
|
|
167
|
-
// Use raw header entries to preserve duplicate Set-Cookie headers
|
|
168
|
-
const resHeaders: Record<string, string | string[]> = {};
|
|
169
|
-
response.headers.forEach((value, key) => {
|
|
170
|
-
const existing = resHeaders[key];
|
|
171
|
-
if (existing !== undefined) {
|
|
172
|
-
resHeaders[key] = Array.isArray(existing)
|
|
173
|
-
? [...existing, value]
|
|
174
|
-
: [existing, value];
|
|
175
|
-
} else {
|
|
176
|
-
resHeaders[key] = value;
|
|
177
|
-
}
|
|
178
|
-
});
|
|
179
|
-
nodeRes.writeHead(response.status, resHeaders);
|
|
180
|
-
|
|
181
|
-
if (response.body) {
|
|
182
|
-
const reader = response.body.getReader();
|
|
183
|
-
while (true) {
|
|
184
|
-
const { done, value } = await reader.read();
|
|
185
|
-
if (done) break;
|
|
186
|
-
nodeRes.write(value);
|
|
187
|
-
}
|
|
188
|
-
nodeRes.end();
|
|
189
|
-
} else {
|
|
190
|
-
nodeRes.end();
|
|
191
|
-
}
|
|
192
|
-
} catch (err) {
|
|
193
|
-
if (err instanceof PayloadTooLargeError) {
|
|
194
|
-
if (!nodeRes.headersSent) {
|
|
195
|
-
nodeRes.writeHead(413);
|
|
196
|
-
nodeRes.end(err.message);
|
|
197
|
-
}
|
|
198
|
-
return;
|
|
199
|
-
}
|
|
200
|
-
console.error("[runtime.node] Request handler error:", err);
|
|
201
|
-
if (!nodeRes.headersSent) {
|
|
202
|
-
nodeRes.writeHead(500);
|
|
203
|
-
nodeRes.end("Internal Server Error");
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
});
|
|
207
|
-
|
|
208
|
-
server.on("error", (err) => {
|
|
209
|
-
if (options.onError) {
|
|
210
|
-
options.onError(err);
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
213
|
-
setTimeout(() => {
|
|
214
|
-
throw err;
|
|
215
|
-
}, 0);
|
|
216
|
-
});
|
|
217
|
-
|
|
218
|
-
server.listen(options.port, hostname, () => {
|
|
219
|
-
if (options.onListen) {
|
|
220
|
-
const address = server.address();
|
|
221
|
-
const port = typeof address === "object" && address !== null
|
|
222
|
-
? address.port
|
|
223
|
-
: options.port;
|
|
224
|
-
options.onListen({ hostname, port });
|
|
225
|
-
}
|
|
226
|
-
});
|
|
227
|
-
|
|
228
|
-
return {
|
|
229
|
-
shutdown: () =>
|
|
230
|
-
new Promise<void>((resolve, reject) => {
|
|
231
|
-
server.close((err) => {
|
|
232
|
-
if (err && !isNodeServerNotRunning(err)) {
|
|
233
|
-
reject(err);
|
|
234
|
-
return;
|
|
235
|
-
}
|
|
236
|
-
resolve();
|
|
237
|
-
});
|
|
238
|
-
}),
|
|
239
|
-
};
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
/**
|
|
243
|
-
* Unref a timer so it doesn't block process exit.
|
|
244
|
-
*/
|
|
245
|
-
export function unrefTimer(id: number): void {
|
|
246
|
-
// In Node.js, setTimeout returns a Timeout object (not a numeric ID).
|
|
247
|
-
// The caller passes it as `number` for Deno compat — we cast back.
|
|
248
|
-
try {
|
|
249
|
-
const timer = id as unknown as { unref?: () => void };
|
|
250
|
-
if (
|
|
251
|
-
typeof timer === "object" && timer && typeof timer.unref === "function"
|
|
252
|
-
) {
|
|
253
|
-
timer.unref();
|
|
254
|
-
}
|
|
255
|
-
} catch (err) {
|
|
256
|
-
console.warn("[runtime.node] Failed to unref timer:", err);
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
/** Compile-time contract check — ensures this module satisfies RuntimePort */
|
|
261
|
-
void ({
|
|
262
|
-
env,
|
|
263
|
-
readTextFile,
|
|
264
|
-
writeTextFile,
|
|
265
|
-
mkdir,
|
|
266
|
-
remove,
|
|
267
|
-
readDir,
|
|
268
|
-
serve,
|
|
269
|
-
unrefTimer,
|
|
270
|
-
} satisfies RuntimePort);
|
|
271
|
-
|
|
272
|
-
// ─── Internal helpers ────────────────────────────────────
|
|
273
|
-
|
|
274
|
-
/** Collect request body from Node.js IncomingMessage */
|
|
275
|
-
function collectBody(
|
|
276
|
-
req: import("node:http").IncomingMessage,
|
|
277
|
-
maxBytes: number | null,
|
|
278
|
-
): Promise<ArrayBuffer> {
|
|
279
|
-
return new Promise((resolve, reject) => {
|
|
280
|
-
const chunks: Buffer[] = [];
|
|
281
|
-
let total = 0;
|
|
282
|
-
let rejected = false;
|
|
283
|
-
req.on("data", (chunk: Buffer) => {
|
|
284
|
-
if (rejected) return;
|
|
285
|
-
total += chunk.length;
|
|
286
|
-
if (maxBytes !== null && total > maxBytes) {
|
|
287
|
-
rejected = true;
|
|
288
|
-
req.destroy();
|
|
289
|
-
reject(new PayloadTooLargeError(maxBytes));
|
|
290
|
-
return;
|
|
291
|
-
}
|
|
292
|
-
chunks.push(chunk);
|
|
293
|
-
});
|
|
294
|
-
req.on("end", () => {
|
|
295
|
-
if (!rejected) {
|
|
296
|
-
const body = Buffer.concat(chunks);
|
|
297
|
-
resolve(
|
|
298
|
-
body.buffer.slice(
|
|
299
|
-
body.byteOffset,
|
|
300
|
-
body.byteOffset + body.byteLength,
|
|
301
|
-
),
|
|
302
|
-
);
|
|
303
|
-
}
|
|
304
|
-
});
|
|
305
|
-
req.on("error", (err) => {
|
|
306
|
-
if (!rejected) {
|
|
307
|
-
reject(err);
|
|
308
|
-
}
|
|
309
|
-
});
|
|
310
|
-
});
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
function isNodeNotFound(err: unknown): boolean {
|
|
314
|
-
return Boolean(
|
|
315
|
-
err && typeof err === "object" && "code" in err && err.code === "ENOENT",
|
|
316
|
-
);
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
function isNodeServerNotRunning(err: unknown): boolean {
|
|
320
|
-
return Boolean(
|
|
321
|
-
err && typeof err === "object" && "code" in err &&
|
|
322
|
-
err.code === "ERR_SERVER_NOT_RUNNING",
|
|
323
|
-
);
|
|
324
|
-
}
|
package/src/runtime/runtime.ts
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Runtime adapter — selector
|
|
3
|
-
*
|
|
4
|
-
* Auto-detects the host runtime and forwards to the Deno or Node adapter.
|
|
5
|
-
* This is the module every consumer imports. It replaces the previous
|
|
6
|
-
* build-time file swap (runtime.ts <- runtime.node.ts), which only ever
|
|
7
|
-
* applied to mcp-server's own npm build and never to JSR consumers that
|
|
8
|
-
* bundle the Deno source for Node (e.g. @casys/mcp-erpnext via esbuild),
|
|
9
|
-
* whose bundle therefore embedded `Deno.*` calls and crashed under Node
|
|
10
|
-
* with "ReferenceError: Deno is not defined".
|
|
11
|
-
*
|
|
12
|
-
* A *dynamic* import is used on purpose so the inactive adapter is never
|
|
13
|
-
* evaluated: under Deno, runtime.node.ts — and its top-level `node:http` /
|
|
14
|
-
* `node:fs/promises` / `node:buffer` imports — never executes, which keeps
|
|
15
|
-
* capability-restricted targets like Deno Deploy (the canonical cloud
|
|
16
|
-
* target, where node:http's raw-TCP `createServer` is unsupported) safe at
|
|
17
|
-
* load time. Platforms and bundlers that statically analyze
|
|
18
|
-
* constant-specifier dynamic imports may still fetch or include the
|
|
19
|
-
* inactive module, but they never run it. Under Node, the Deno adapter is
|
|
20
|
-
* likewise never evaluated.
|
|
21
|
-
*
|
|
22
|
-
* @see types.ts for the RuntimePort contract
|
|
23
|
-
* @see runtime.deno.ts / runtime.node.ts for the implementations
|
|
24
|
-
* @module lib/server/runtime
|
|
25
|
-
*/
|
|
26
|
-
|
|
27
|
-
import type { RuntimePort } from "./types.js";
|
|
28
|
-
|
|
29
|
-
// Re-export types so consumers import from a single module
|
|
30
|
-
export type { FetchHandler, ServeHandle, ServeOptions } from "./types.js";
|
|
31
|
-
|
|
32
|
-
// Structural detection: a bare `globalThis.Deno = {}` shim (seen in some Node
|
|
33
|
-
// test setups and bundlers) must NOT be mistaken for a real Deno runtime, so
|
|
34
|
-
// probe a concrete field (`Deno.version.deno`) rather than mere existence.
|
|
35
|
-
const isDeno = typeof (globalThis as {
|
|
36
|
-
Deno?: { version?: { deno?: string } };
|
|
37
|
-
}).Deno?.version?.deno === "string";
|
|
38
|
-
|
|
39
|
-
const impl: RuntimePort = isDeno
|
|
40
|
-
? await import("./runtime.deno.js")
|
|
41
|
-
: await import("./runtime.node.js");
|
|
42
|
-
|
|
43
|
-
export const env = impl.env;
|
|
44
|
-
export const readTextFile = impl.readTextFile;
|
|
45
|
-
export const writeTextFile = impl.writeTextFile;
|
|
46
|
-
export const mkdir = impl.mkdir;
|
|
47
|
-
export const remove = impl.remove;
|
|
48
|
-
export const readDir = impl.readDir;
|
|
49
|
-
export const serve = impl.serve;
|
|
50
|
-
export const unrefTimer = impl.unrefTimer;
|
package/src/runtime/types.ts
DELETED
|
@@ -1,130 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Runtime Port — platform-agnostic contract
|
|
3
|
-
*
|
|
4
|
-
* Defines the interface that both Deno (runtime.ts) and Node.js (runtime.node.ts)
|
|
5
|
-
* must implement. This is the only file consumers need to understand the API shape.
|
|
6
|
-
*
|
|
7
|
-
* Pattern: each runtime file exports module-level functions that satisfy this port.
|
|
8
|
-
* The build script swaps runtime.ts → runtime.node.ts for Node.js distribution.
|
|
9
|
-
*
|
|
10
|
-
* @module lib/server/runtime-types
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
// ─── Environment ─────────────────────────────────────────
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Get an environment variable.
|
|
17
|
-
* Returns undefined if not set (never throws).
|
|
18
|
-
*/
|
|
19
|
-
export type EnvFn = (key: string) => string | undefined;
|
|
20
|
-
|
|
21
|
-
// ─── File System ─────────────────────────────────────────
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Read a UTF-8 text file.
|
|
25
|
-
* Returns null if the file does not exist (no throw on ENOENT/NotFound).
|
|
26
|
-
* Throws on other errors (permission denied, etc.).
|
|
27
|
-
*/
|
|
28
|
-
export type ReadTextFileFn = (path: string) => Promise<string | null>;
|
|
29
|
-
|
|
30
|
-
/** Write a UTF-8 text file. */
|
|
31
|
-
export type WriteTextFileFn = (
|
|
32
|
-
path: string,
|
|
33
|
-
content: string,
|
|
34
|
-
opts?: { mode?: number },
|
|
35
|
-
) => Promise<void>;
|
|
36
|
-
|
|
37
|
-
/** Create a directory. */
|
|
38
|
-
export type MkdirFn = (
|
|
39
|
-
path: string,
|
|
40
|
-
opts?: { recursive?: boolean; mode?: number },
|
|
41
|
-
) => Promise<void>;
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Remove a file or empty directory.
|
|
45
|
-
* Does nothing if the path does not exist.
|
|
46
|
-
*/
|
|
47
|
-
export type RemoveFn = (path: string) => Promise<void>;
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Read directory entry names.
|
|
51
|
-
* Returns [] if the directory does not exist.
|
|
52
|
-
*/
|
|
53
|
-
export type ReadDirFn = (path: string) => Promise<string[]>;
|
|
54
|
-
|
|
55
|
-
// ─── HTTP Server ─────────────────────────────────────────
|
|
56
|
-
|
|
57
|
-
/** Fetch-style request handler (Web standard) */
|
|
58
|
-
export type FetchHandler = (req: Request) => Response | Promise<Response>;
|
|
59
|
-
|
|
60
|
-
/** Options for starting an HTTP server */
|
|
61
|
-
export interface ServeOptions {
|
|
62
|
-
port: number;
|
|
63
|
-
hostname?: string;
|
|
64
|
-
onListen?: (info: { hostname: string; port: number }) => void;
|
|
65
|
-
/** Optional bind/startup error channel. */
|
|
66
|
-
onError?: (err: Error) => void;
|
|
67
|
-
/** Maximum request body size in bytes (optional, adapter-specific). */
|
|
68
|
-
maxBodyBytes?: number | null;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** Handle returned by serve(), used to shut down the server */
|
|
72
|
-
export interface ServeHandle {
|
|
73
|
-
shutdown(): Promise<void>;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* Start an HTTP server with a fetch-style handler.
|
|
78
|
-
*
|
|
79
|
-
* Deno: wraps Deno.serve()
|
|
80
|
-
* Node.js: wraps node:http.createServer() with Request/Response adapter
|
|
81
|
-
*/
|
|
82
|
-
export type ServeFn = (
|
|
83
|
-
options: ServeOptions,
|
|
84
|
-
handler: FetchHandler,
|
|
85
|
-
) => ServeHandle;
|
|
86
|
-
|
|
87
|
-
// ─── Timers ──────────────────────────────────────────────
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Unref a timer so it doesn't prevent process exit.
|
|
91
|
-
*
|
|
92
|
-
* Deno: Deno.unrefTimer(id)
|
|
93
|
-
* Node.js: timer.unref() on the Timeout object
|
|
94
|
-
*/
|
|
95
|
-
export type UnrefTimerFn = (id: number) => void;
|
|
96
|
-
|
|
97
|
-
// ─── Port interface ──────────────────────────────────────
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Complete runtime port contract.
|
|
101
|
-
*
|
|
102
|
-
* Both runtime.ts (Deno) and runtime.node.ts (Node.js) must export
|
|
103
|
-
* functions matching these signatures. Use `satisfies RuntimePort`
|
|
104
|
-
* at the bottom of each implementation to enforce at compile time.
|
|
105
|
-
*
|
|
106
|
-
* @example
|
|
107
|
-
* ```typescript
|
|
108
|
-
* // At the bottom of runtime.ts / runtime.node.ts:
|
|
109
|
-
* export const _port = {
|
|
110
|
-
* env,
|
|
111
|
-
* readTextFile,
|
|
112
|
-
* writeTextFile,
|
|
113
|
-
* mkdir,
|
|
114
|
-
* remove,
|
|
115
|
-
* readDir,
|
|
116
|
-
* serve,
|
|
117
|
-
* unrefTimer,
|
|
118
|
-
* } satisfies RuntimePort;
|
|
119
|
-
* ```
|
|
120
|
-
*/
|
|
121
|
-
export interface RuntimePort {
|
|
122
|
-
env: EnvFn;
|
|
123
|
-
readTextFile: ReadTextFileFn;
|
|
124
|
-
writeTextFile: WriteTextFileFn;
|
|
125
|
-
mkdir: MkdirFn;
|
|
126
|
-
remove: RemoveFn;
|
|
127
|
-
readDir: ReadDirFn;
|
|
128
|
-
serve: ServeFn;
|
|
129
|
-
unrefTimer: UnrefTimerFn;
|
|
130
|
-
}
|
|
@@ -1,140 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* HMAC Channel Authentication — Inline Script for PostMessage (MCP Apps)
|
|
3
|
-
*
|
|
4
|
-
* Generates an inline `<script>` that signs outgoing JSON-RPC messages
|
|
5
|
-
* from an iframe to its parent via PostMessage (HMAC-SHA256 + anti-replay).
|
|
6
|
-
*
|
|
7
|
-
* The HOST side is responsible for verifying incoming messages using
|
|
8
|
-
* `MessageSigner.verify()`. This script only handles the IFRAME side
|
|
9
|
-
* (signing outgoing).
|
|
10
|
-
*
|
|
11
|
-
* Part of @casys/mcp-server security module. See also:
|
|
12
|
-
* - message-signer.ts (MessageSigner class, HMAC sign/verify)
|
|
13
|
-
*
|
|
14
|
-
* @module server/security/channel-hmac
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
// ---------------------------------------------------------------------------
|
|
18
|
-
// Inline HMAC Script
|
|
19
|
-
// ---------------------------------------------------------------------------
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Generate the inline `<script>` tag for iframe HMAC signing.
|
|
23
|
-
*
|
|
24
|
-
* The script:
|
|
25
|
-
* 1. Embeds the channel secret (invisible to other iframes due to cross-origin)
|
|
26
|
-
* 2. Monkey-patches `window.parent.postMessage` to sign outgoing JSON-RPC
|
|
27
|
-
*
|
|
28
|
-
* Verification of incoming messages is the HOST's responsibility
|
|
29
|
-
* (via `MessageSigner.verify()`), not the iframe's.
|
|
30
|
-
*
|
|
31
|
-
* @param secret - 64-char hex secret from MessageSigner.generateSecret()
|
|
32
|
-
* @returns HTML `<script>` string ready for injection into `<head>`
|
|
33
|
-
*/
|
|
34
|
-
export function generateHmacScript(secret: string): string {
|
|
35
|
-
return `
|
|
36
|
-
<script data-mcp-channel-auth>
|
|
37
|
-
(function() {
|
|
38
|
-
'use strict';
|
|
39
|
-
|
|
40
|
-
var SECRET_HEX = '${secret}';
|
|
41
|
-
var sendSeq = 0;
|
|
42
|
-
var cryptoKeyPromise = null;
|
|
43
|
-
|
|
44
|
-
function hexToBytes(hex) {
|
|
45
|
-
var bytes = new Uint8Array(hex.length / 2);
|
|
46
|
-
for (var i = 0; i < hex.length; i += 2) {
|
|
47
|
-
bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
|
|
48
|
-
}
|
|
49
|
-
return bytes;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function bytesToHex(bytes) {
|
|
53
|
-
var hex = '';
|
|
54
|
-
for (var i = 0; i < bytes.length; i++) {
|
|
55
|
-
hex += bytes[i].toString(16).padStart(2, '0');
|
|
56
|
-
}
|
|
57
|
-
return hex;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function initKey() {
|
|
61
|
-
if (cryptoKeyPromise) return cryptoKeyPromise;
|
|
62
|
-
cryptoKeyPromise = crypto.subtle.importKey(
|
|
63
|
-
'raw', hexToBytes(SECRET_HEX),
|
|
64
|
-
{ name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
|
|
65
|
-
);
|
|
66
|
-
return cryptoKeyPromise;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function buildPayload(msg, seq) {
|
|
70
|
-
var id = msg.id != null ? msg.id : '';
|
|
71
|
-
var method = msg.method || '';
|
|
72
|
-
var body;
|
|
73
|
-
if (msg.params !== undefined) body = JSON.stringify(msg.params);
|
|
74
|
-
else if (msg.result !== undefined) body = JSON.stringify(msg.result);
|
|
75
|
-
else if (msg.error !== undefined) body = JSON.stringify(msg.error);
|
|
76
|
-
else body = '{}';
|
|
77
|
-
return seq + ':' + id + ':' + method + ':' + body;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
function signMessage(msg) {
|
|
81
|
-
var seq = sendSeq++;
|
|
82
|
-
var payload = buildPayload(msg, seq);
|
|
83
|
-
return initKey().then(function(key) {
|
|
84
|
-
return crypto.subtle.sign('HMAC', key, new TextEncoder().encode(payload));
|
|
85
|
-
}).then(function(sig) {
|
|
86
|
-
var signed = {};
|
|
87
|
-
for (var k in msg) {
|
|
88
|
-
if (Object.prototype.hasOwnProperty.call(msg, k)) signed[k] = msg[k];
|
|
89
|
-
}
|
|
90
|
-
signed._seq = seq;
|
|
91
|
-
signed._hmac = bytesToHex(new Uint8Array(sig));
|
|
92
|
-
return signed;
|
|
93
|
-
});
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// Monkey-patch outgoing postMessage (iframe -> parent)
|
|
97
|
-
var realPostMessage = window.parent.postMessage.bind(window.parent);
|
|
98
|
-
window.parent.postMessage = function(message, targetOrigin, transfer) {
|
|
99
|
-
if (message && typeof message === 'object' && message.jsonrpc === '2.0') {
|
|
100
|
-
signMessage(message).then(function(signed) {
|
|
101
|
-
realPostMessage(signed, targetOrigin, transfer);
|
|
102
|
-
}).catch(function(err) {
|
|
103
|
-
console.error('[mcp-channel-auth] Sign error:', err);
|
|
104
|
-
});
|
|
105
|
-
} else {
|
|
106
|
-
realPostMessage(message, targetOrigin, transfer);
|
|
107
|
-
}
|
|
108
|
-
};
|
|
109
|
-
|
|
110
|
-
initKey();
|
|
111
|
-
})();
|
|
112
|
-
</script>
|
|
113
|
-
`;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* Inject channel authentication script into HTML content.
|
|
118
|
-
*
|
|
119
|
-
* Inserts the HMAC signing script before `</head>` (preferred) or at the start.
|
|
120
|
-
* The injected script signs all outgoing JSON-RPC postMessages from the iframe.
|
|
121
|
-
* The HOST must verify these signatures using `MessageSigner.verify()`.
|
|
122
|
-
*
|
|
123
|
-
* @param html - HTML content to inject into
|
|
124
|
-
* @param secret - 64-char hex secret from MessageSigner.generateSecret()
|
|
125
|
-
* @returns Modified HTML with HMAC signing script injected
|
|
126
|
-
* @throws {Error} If secret is not a valid 64-char hex string
|
|
127
|
-
*/
|
|
128
|
-
export function injectChannelAuth(html: string, secret: string): string {
|
|
129
|
-
if (!/^[0-9a-f]{64}$/.test(secret)) {
|
|
130
|
-
throw new Error(
|
|
131
|
-
"[injectChannelAuth] Invalid secret: expected 64-char lowercase hex string. " +
|
|
132
|
-
"Use MessageSigner.generateSecret() to create one.",
|
|
133
|
-
);
|
|
134
|
-
}
|
|
135
|
-
const script = generateHmacScript(secret);
|
|
136
|
-
if (html.includes("</head>")) {
|
|
137
|
-
return html.replace("</head>", script + "</head>");
|
|
138
|
-
}
|
|
139
|
-
return script + html;
|
|
140
|
-
}
|