lumoauth 0.0.0-stage → 1.2.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/README.md +214 -2
- package/dist/cli.js +711 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.mts +107 -0
- package/dist/index.d.ts +107 -0
- package/dist/index.js +744 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +715 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +54 -5
package/dist/cli.js
ADDED
|
@@ -0,0 +1,711 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
// src/cli.ts
|
|
5
|
+
var import_node_util = require("util");
|
|
6
|
+
var import_mcp2 = require("@lumoauth/mcp");
|
|
7
|
+
|
|
8
|
+
// src/proxy.ts
|
|
9
|
+
var import_node_http = require("http");
|
|
10
|
+
var import_node_stream = require("stream");
|
|
11
|
+
var import_promises = require("stream/promises");
|
|
12
|
+
var import_mcp = require("@lumoauth/mcp");
|
|
13
|
+
|
|
14
|
+
// src/jsonrpc.ts
|
|
15
|
+
function asId(value) {
|
|
16
|
+
return typeof value === "string" || typeof value === "number" ? value : null;
|
|
17
|
+
}
|
|
18
|
+
function inspect(body) {
|
|
19
|
+
const result = { toolCalls: [], toolListIds: /* @__PURE__ */ new Set(), isBatch: false };
|
|
20
|
+
let parsed;
|
|
21
|
+
try {
|
|
22
|
+
parsed = JSON.parse(body);
|
|
23
|
+
} catch {
|
|
24
|
+
return result;
|
|
25
|
+
}
|
|
26
|
+
result.isBatch = Array.isArray(parsed);
|
|
27
|
+
const messages = Array.isArray(parsed) ? parsed : [parsed];
|
|
28
|
+
for (const message of messages) {
|
|
29
|
+
if (typeof message !== "object" || message === null || message.id === void 0) continue;
|
|
30
|
+
if (message.method === "tools/call") {
|
|
31
|
+
const params = message.params;
|
|
32
|
+
result.toolCalls.push({ id: asId(message.id), name: typeof params?.name === "string" ? params.name : "" });
|
|
33
|
+
} else if (message.method === "tools/list") {
|
|
34
|
+
result.toolListIds.add(JSON.stringify(message.id));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
function refusedToolResult(id, message) {
|
|
40
|
+
return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: message }], isError: true } };
|
|
41
|
+
}
|
|
42
|
+
async function filterMessage(message, ids, decide) {
|
|
43
|
+
if (typeof message !== "object" || message === null) return message;
|
|
44
|
+
const response = message;
|
|
45
|
+
if (!ids.has(JSON.stringify(response.id)) || !Array.isArray(response.result?.tools)) return message;
|
|
46
|
+
const tools = response.result.tools;
|
|
47
|
+
const allowed = await decide(tools.map((t) => typeof t.name === "string" ? t.name : ""));
|
|
48
|
+
return { ...response, result: { ...response.result, tools: tools.filter((t) => typeof t.name === "string" && allowed.has(t.name)) } };
|
|
49
|
+
}
|
|
50
|
+
async function filterJsonBody(body, ids, decide) {
|
|
51
|
+
let parsed;
|
|
52
|
+
try {
|
|
53
|
+
parsed = JSON.parse(body);
|
|
54
|
+
} catch {
|
|
55
|
+
return body;
|
|
56
|
+
}
|
|
57
|
+
const filtered = Array.isArray(parsed) ? await Promise.all(parsed.map((m) => filterMessage(m, ids, decide))) : await filterMessage(parsed, ids, decide);
|
|
58
|
+
return JSON.stringify(filtered);
|
|
59
|
+
}
|
|
60
|
+
async function filterSseEvent(event, ids, decide) {
|
|
61
|
+
const lines = event.split(/\r?\n/);
|
|
62
|
+
const dataLines = lines.filter((line) => line.startsWith("data:"));
|
|
63
|
+
if (dataLines.length === 0) return event;
|
|
64
|
+
const data = dataLines.map((line) => line.slice(5).replace(/^ /, "")).join("\n");
|
|
65
|
+
let message;
|
|
66
|
+
try {
|
|
67
|
+
message = JSON.parse(data);
|
|
68
|
+
} catch {
|
|
69
|
+
return event;
|
|
70
|
+
}
|
|
71
|
+
const filtered = await filterMessage(message, ids, decide);
|
|
72
|
+
if (filtered === message) return event;
|
|
73
|
+
const others = lines.filter((line) => !line.startsWith("data:") && line !== "");
|
|
74
|
+
return [...others, `data: ${JSON.stringify(filtered)}`].join("\n");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// src/proxy.ts
|
|
78
|
+
var HOP_BY_HOP = ["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade"];
|
|
79
|
+
var REQUEST_DROP = /* @__PURE__ */ new Set([...HOP_BY_HOP, "host", "content-length", "authorization", "dpop", "accept-encoding"]);
|
|
80
|
+
var RESPONSE_DROP = /* @__PURE__ */ new Set([...HOP_BY_HOP, "content-length", "content-encoding", "set-cookie"]);
|
|
81
|
+
var IDENTITY_PREFIX = "x-lumoauth-";
|
|
82
|
+
var SessionOwners = class {
|
|
83
|
+
constructor() {
|
|
84
|
+
this.owners = /* @__PURE__ */ new Map();
|
|
85
|
+
}
|
|
86
|
+
/** `true` when `owner` may use `sessionId`; an unknown session is bound to it. */
|
|
87
|
+
claim(sessionId, owner) {
|
|
88
|
+
const current = this.owners.get(sessionId);
|
|
89
|
+
if (current === void 0) {
|
|
90
|
+
this.bind(sessionId, owner);
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
return current === owner;
|
|
94
|
+
}
|
|
95
|
+
bind(sessionId, owner) {
|
|
96
|
+
if (this.owners.size >= 5e4) {
|
|
97
|
+
const oldest = this.owners.keys().next().value;
|
|
98
|
+
if (oldest !== void 0) this.owners.delete(oldest);
|
|
99
|
+
}
|
|
100
|
+
this.owners.set(sessionId, owner);
|
|
101
|
+
}
|
|
102
|
+
forget(sessionId) {
|
|
103
|
+
this.owners.delete(sessionId);
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
function principal(caller) {
|
|
107
|
+
return JSON.stringify([caller.issuer, caller.sub, caller.clientId ?? null]);
|
|
108
|
+
}
|
|
109
|
+
function headerOf(req, name) {
|
|
110
|
+
const value = req.headers[name];
|
|
111
|
+
return Array.isArray(value) ? value[0] : value;
|
|
112
|
+
}
|
|
113
|
+
function writeSimple(res, response) {
|
|
114
|
+
res.statusCode = response.status;
|
|
115
|
+
for (const [name, value] of Object.entries(response.headers)) res.setHeader(name, value);
|
|
116
|
+
res.end(response.body);
|
|
117
|
+
}
|
|
118
|
+
function writeJson(res, status, body) {
|
|
119
|
+
const text = JSON.stringify(body);
|
|
120
|
+
res.statusCode = status;
|
|
121
|
+
res.setHeader("Content-Type", "application/json");
|
|
122
|
+
res.setHeader("Content-Length", Buffer.byteLength(text));
|
|
123
|
+
res.end(text);
|
|
124
|
+
}
|
|
125
|
+
var BodyTooLargeError = class extends Error {
|
|
126
|
+
};
|
|
127
|
+
async function readBody(req, limit) {
|
|
128
|
+
const chunks = [];
|
|
129
|
+
let size = 0;
|
|
130
|
+
for await (const chunk of req) {
|
|
131
|
+
size += chunk.length;
|
|
132
|
+
if (size > limit) throw new BodyTooLargeError();
|
|
133
|
+
chunks.push(chunk);
|
|
134
|
+
}
|
|
135
|
+
return Buffer.concat(chunks);
|
|
136
|
+
}
|
|
137
|
+
async function* sseEvents(body, transform) {
|
|
138
|
+
const decoder = new TextDecoder();
|
|
139
|
+
let buffer = "";
|
|
140
|
+
for await (const chunk of import_node_stream.Readable.fromWeb(body)) {
|
|
141
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
142
|
+
let match;
|
|
143
|
+
while ((match = /\r?\n\r?\n/.exec(buffer)) !== null) {
|
|
144
|
+
const event = buffer.slice(0, match.index);
|
|
145
|
+
buffer = buffer.slice(match.index + match[0].length);
|
|
146
|
+
yield await transform(event) + match[0];
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
buffer += decoder.decode();
|
|
150
|
+
if (buffer) yield buffer;
|
|
151
|
+
}
|
|
152
|
+
async function allowedToolNames(auth, caller, names) {
|
|
153
|
+
const policy = auth.toolPolicy();
|
|
154
|
+
const allowed = /* @__PURE__ */ new Set();
|
|
155
|
+
for (let i = 0; i < names.length; i += 8) {
|
|
156
|
+
await Promise.all(
|
|
157
|
+
names.slice(i, i + 8).map(async (name) => {
|
|
158
|
+
if (name && await policy.isAllowed(caller, name)) allowed.add(name);
|
|
159
|
+
})
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
return allowed;
|
|
163
|
+
}
|
|
164
|
+
function createSecureProxy(options) {
|
|
165
|
+
const { auth } = options;
|
|
166
|
+
const log2 = options.log ?? ((line) => console.error(line));
|
|
167
|
+
if (!options.upstream && !options.bridge) throw new Error("createSecureProxy needs an upstream URL or a stdio bridge");
|
|
168
|
+
const upstream = new URL(options.upstream ?? "http://stdio.invalid/");
|
|
169
|
+
const maxBody = options.maxBodyBytes ?? 4 * 1024 * 1024;
|
|
170
|
+
const sessions = new SessionOwners();
|
|
171
|
+
function targetFor(pathname, search) {
|
|
172
|
+
const target = new URL(upstream.href);
|
|
173
|
+
target.pathname = pathname === options.path ? upstream.pathname : pathname;
|
|
174
|
+
target.search = search;
|
|
175
|
+
return target.href;
|
|
176
|
+
}
|
|
177
|
+
async function forward(req, res, url, body, caller, inspection) {
|
|
178
|
+
const headers = new Headers();
|
|
179
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
180
|
+
const lower = name.toLowerCase();
|
|
181
|
+
if (value === void 0 || REQUEST_DROP.has(lower) || lower.startsWith(IDENTITY_PREFIX)) continue;
|
|
182
|
+
for (const item of Array.isArray(value) ? value : [value]) headers.append(lower, item);
|
|
183
|
+
}
|
|
184
|
+
headers.set("accept-encoding", "identity");
|
|
185
|
+
if (req.headers.host) headers.set("x-forwarded-host", req.headers.host);
|
|
186
|
+
const remote = req.socket.remoteAddress;
|
|
187
|
+
if (remote) headers.set("x-forwarded-for", [headerOf(req, "x-forwarded-for"), remote].filter(Boolean).join(", "));
|
|
188
|
+
if (caller && options.identityHeaders) {
|
|
189
|
+
headers.set("x-lumoauth-subject", caller.sub);
|
|
190
|
+
headers.set("x-lumoauth-subject-type", caller.isAgent ? "agent" : "user");
|
|
191
|
+
if (caller.agentId) headers.set("x-lumoauth-agent-id", caller.agentId);
|
|
192
|
+
if (caller.actor) headers.set("x-lumoauth-actor", caller.actor);
|
|
193
|
+
if (caller.clientId) headers.set("x-lumoauth-client-id", caller.clientId);
|
|
194
|
+
headers.set("x-lumoauth-scopes", caller.scopes.join(" "));
|
|
195
|
+
}
|
|
196
|
+
const controller = new AbortController();
|
|
197
|
+
res.on("close", () => controller.abort());
|
|
198
|
+
let answer;
|
|
199
|
+
try {
|
|
200
|
+
answer = await fetch(targetFor(url.pathname, url.search), {
|
|
201
|
+
method: req.method,
|
|
202
|
+
headers,
|
|
203
|
+
// undici takes a Buffer; the DOM typings only list ArrayBuffer views.
|
|
204
|
+
body: body && body.length > 0 ? body : void 0,
|
|
205
|
+
redirect: "manual",
|
|
206
|
+
signal: controller.signal
|
|
207
|
+
});
|
|
208
|
+
} catch (error) {
|
|
209
|
+
if (controller.signal.aborted) return;
|
|
210
|
+
log2(`lumoauth: upstream ${upstream.origin} is not reachable: ${error.message}`);
|
|
211
|
+
writeJson(res, 502, { error: "bad_gateway", error_description: "The MCP server is not reachable" });
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
const sessionId = answer.headers.get("mcp-session-id");
|
|
215
|
+
if (sessionId && caller) {
|
|
216
|
+
if (req.method === "DELETE" && answer.ok) sessions.forget(sessionId);
|
|
217
|
+
else sessions.bind(sessionId, principal(caller));
|
|
218
|
+
}
|
|
219
|
+
res.statusCode = answer.status;
|
|
220
|
+
answer.headers.forEach((value, name) => {
|
|
221
|
+
if (!RESPONSE_DROP.has(name)) res.setHeader(name, value);
|
|
222
|
+
});
|
|
223
|
+
const cookies = answer.headers.getSetCookie();
|
|
224
|
+
if (cookies.length > 0) res.setHeader("set-cookie", cookies);
|
|
225
|
+
if (!answer.body) {
|
|
226
|
+
res.end();
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const listIds = inspection?.toolListIds;
|
|
230
|
+
const contentType = answer.headers.get("content-type") ?? "";
|
|
231
|
+
if (caller && listIds && listIds.size > 0) {
|
|
232
|
+
const decide = (names) => allowedToolNames(auth, caller, names);
|
|
233
|
+
if (contentType.includes("application/json")) {
|
|
234
|
+
const filtered = await filterJsonBody(await answer.text(), listIds, decide);
|
|
235
|
+
res.setHeader("content-length", Buffer.byteLength(filtered));
|
|
236
|
+
res.end(filtered);
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (contentType.includes("text/event-stream")) {
|
|
240
|
+
res.flushHeaders();
|
|
241
|
+
await (0, import_promises.pipeline)(import_node_stream.Readable.from(sseEvents(answer.body, (event) => filterSseEvent(event, listIds, decide))), res).catch(() => {
|
|
242
|
+
});
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (contentType.includes("text/event-stream")) res.flushHeaders();
|
|
247
|
+
await (0, import_promises.pipeline)(import_node_stream.Readable.fromWeb(answer.body), res).catch(() => {
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
async function handle(req, res) {
|
|
251
|
+
const method = req.method ?? "GET";
|
|
252
|
+
const url = new URL(req.url ?? "/", "http://proxy.invalid");
|
|
253
|
+
const discovery = await auth.discoveryResponse(method, url.pathname);
|
|
254
|
+
if (discovery) {
|
|
255
|
+
writeSimple(res, discovery);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
if (options.bridge && url.pathname !== options.path) {
|
|
259
|
+
writeJson(res, 404, { error: "not_found" });
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (!options.bridge && options.publicPaths.includes(url.pathname)) {
|
|
263
|
+
await forward(req, res, url, await readBody(req, maxBody), void 0, void 0);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
let info;
|
|
267
|
+
try {
|
|
268
|
+
info = await auth.authenticate({ method, url: req.url ?? "/", headers: req.headers });
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (error instanceof import_mcp.LumoAuthChallenge) {
|
|
271
|
+
(0, import_mcp.writeChallenge)(res, error);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
throw error;
|
|
275
|
+
}
|
|
276
|
+
const caller = info.extra.caller;
|
|
277
|
+
const sessionId = headerOf(req, "mcp-session-id");
|
|
278
|
+
if (!options.bridge && sessionId && !sessions.claim(sessionId, principal(caller))) {
|
|
279
|
+
writeJson(res, 404, { jsonrpc: "2.0", id: null, error: { code: -32001, message: "Session not found" } });
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
const body = method === "POST" ? await readBody(req, maxBody) : void 0;
|
|
283
|
+
let inspection;
|
|
284
|
+
if (body && options.toolPolicy) {
|
|
285
|
+
inspection = inspect(body.toString("utf8"));
|
|
286
|
+
const refused = [];
|
|
287
|
+
for (const call of inspection.toolCalls) {
|
|
288
|
+
if (!await auth.toolPolicy().isAllowed(caller, call.name)) refused.push(call);
|
|
289
|
+
}
|
|
290
|
+
if (refused.length > 0) {
|
|
291
|
+
const reason = (name) => `LumoAuth policy does not allow this caller to run '${name}'.`;
|
|
292
|
+
log2(`lumoauth: refused ${refused.map((c) => c.name).join(", ")} for ${caller.sub}`);
|
|
293
|
+
if (inspection.isBatch) {
|
|
294
|
+
writeJson(res, 200, inspection.toolCalls.map((c) => refusedToolResult(c.id, reason(refused[0].name))));
|
|
295
|
+
} else {
|
|
296
|
+
writeJson(res, 200, refusedToolResult(refused[0].id, reason(refused[0].name)));
|
|
297
|
+
}
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (options.bridge) {
|
|
302
|
+
let parsed;
|
|
303
|
+
if (body && body.length > 0) {
|
|
304
|
+
try {
|
|
305
|
+
parsed = JSON.parse(body.toString("utf8"));
|
|
306
|
+
} catch {
|
|
307
|
+
writeJson(res, 400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
await options.bridge.handle(req, res, info, parsed);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
await forward(req, res, url, body, caller, inspection);
|
|
315
|
+
}
|
|
316
|
+
return (0, import_node_http.createServer)((req, res) => {
|
|
317
|
+
handle(req, res).catch((error) => {
|
|
318
|
+
if (error instanceof BodyTooLargeError) {
|
|
319
|
+
writeJson(res, 413, { error: "request_too_large" });
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
log2(`lumoauth: ${error.stack ?? error}`);
|
|
323
|
+
if (!res.headersSent) writeJson(res, 500, { error: "server_error" });
|
|
324
|
+
else res.destroy();
|
|
325
|
+
});
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// src/stdio.ts
|
|
330
|
+
var import_node_crypto = require("crypto");
|
|
331
|
+
var import_stdio = require("@modelcontextprotocol/sdk/client/stdio.js");
|
|
332
|
+
var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
|
|
333
|
+
var import_types = require("@modelcontextprotocol/sdk/types.js");
|
|
334
|
+
function principal2(caller) {
|
|
335
|
+
return JSON.stringify([caller.issuer, caller.sub, caller.clientId ?? null]);
|
|
336
|
+
}
|
|
337
|
+
function jsonRpcError(res, status, message) {
|
|
338
|
+
const body = JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32e3, message } });
|
|
339
|
+
res.statusCode = status;
|
|
340
|
+
res.setHeader("Content-Type", "application/json");
|
|
341
|
+
res.end(body);
|
|
342
|
+
}
|
|
343
|
+
var StdioBridge = class {
|
|
344
|
+
constructor(options) {
|
|
345
|
+
this.options = options;
|
|
346
|
+
this.sessions = /* @__PURE__ */ new Map();
|
|
347
|
+
this.log = options.log ?? ((line) => console.error(line));
|
|
348
|
+
}
|
|
349
|
+
async handle(req, res, info, body) {
|
|
350
|
+
const caller = info.extra.caller;
|
|
351
|
+
const request = req;
|
|
352
|
+
request.auth = info;
|
|
353
|
+
const sessionId = req.headers["mcp-session-id"];
|
|
354
|
+
if (typeof sessionId === "string") {
|
|
355
|
+
const session2 = this.sessions.get(sessionId);
|
|
356
|
+
if (!session2 || session2.owner !== principal2(caller)) {
|
|
357
|
+
jsonRpcError(res, 404, "Session not found");
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
await session2.http.handleRequest(request, res, body);
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
if (req.method !== "POST" || !(0, import_types.isInitializeRequest)(body)) {
|
|
364
|
+
jsonRpcError(res, 400, "Bad Request: start a session with an initialize request");
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
const params = body.params;
|
|
368
|
+
if (!import_types.SUPPORTED_PROTOCOL_VERSIONS.includes(params.protocolVersion)) {
|
|
369
|
+
params.protocolVersion = import_types.LATEST_PROTOCOL_VERSION;
|
|
370
|
+
}
|
|
371
|
+
const session = await this.open(principal2(caller));
|
|
372
|
+
await session.http.handleRequest(request, res, body);
|
|
373
|
+
}
|
|
374
|
+
async open(owner) {
|
|
375
|
+
const [command, ...args] = this.options.command;
|
|
376
|
+
const env = { ...(0, import_stdio.getDefaultEnvironment)() };
|
|
377
|
+
for (const [name, value] of Object.entries(process.env)) if (value !== void 0) env[name] = value;
|
|
378
|
+
const child = new import_stdio.StdioClientTransport({ command, args, env, stderr: "inherit" });
|
|
379
|
+
let session;
|
|
380
|
+
const http = new import_streamableHttp.StreamableHTTPServerTransport({
|
|
381
|
+
sessionIdGenerator: () => (0, import_node_crypto.randomUUID)(),
|
|
382
|
+
onsessioninitialized: (id) => {
|
|
383
|
+
if (session) this.sessions.set(id, session);
|
|
384
|
+
},
|
|
385
|
+
onsessionclosed: (id) => {
|
|
386
|
+
this.sessions.delete(id);
|
|
387
|
+
void child.close();
|
|
388
|
+
}
|
|
389
|
+
});
|
|
390
|
+
session = { http, child, owner, listRequests: /* @__PURE__ */ new Map(), progress: /* @__PURE__ */ new Map() };
|
|
391
|
+
const current = session;
|
|
392
|
+
http.onmessage = (message, extra) => {
|
|
393
|
+
const record = message;
|
|
394
|
+
const caller = extra?.authInfo?.extra?.caller;
|
|
395
|
+
if (record.method === "tools/list" && record.id !== void 0 && caller && this.options.filterTools) {
|
|
396
|
+
current.listRequests.set(JSON.stringify(record.id), caller);
|
|
397
|
+
}
|
|
398
|
+
const meta = record.params?._meta;
|
|
399
|
+
if (meta?.progressToken !== void 0 && record.id !== void 0) current.progress.set(meta.progressToken, record.id);
|
|
400
|
+
child.send(message).catch((error) => this.log(`lumoauth: cannot reach the stdio server: ${error.message}`));
|
|
401
|
+
};
|
|
402
|
+
child.onmessage = (message) => {
|
|
403
|
+
void this.relay(current, message);
|
|
404
|
+
};
|
|
405
|
+
http.onclose = () => {
|
|
406
|
+
void child.close();
|
|
407
|
+
};
|
|
408
|
+
child.onclose = () => {
|
|
409
|
+
void http.close();
|
|
410
|
+
};
|
|
411
|
+
child.onerror = (error) => this.log(`lumoauth: stdio server error: ${error.message}`);
|
|
412
|
+
await child.start();
|
|
413
|
+
await http.start();
|
|
414
|
+
return current;
|
|
415
|
+
}
|
|
416
|
+
async relay(session, message) {
|
|
417
|
+
const record = message;
|
|
418
|
+
let outgoing = message;
|
|
419
|
+
if (record.id !== void 0 && !("method" in record)) {
|
|
420
|
+
const key = JSON.stringify(record.id);
|
|
421
|
+
const caller = session.listRequests.get(key);
|
|
422
|
+
const result = record.result;
|
|
423
|
+
if (caller && this.options.filterTools && Array.isArray(result?.tools)) {
|
|
424
|
+
session.listRequests.delete(key);
|
|
425
|
+
const names = result.tools.map((tool) => typeof tool.name === "string" ? tool.name : "");
|
|
426
|
+
const allowed = await this.options.filterTools(caller, names);
|
|
427
|
+
outgoing = {
|
|
428
|
+
...record,
|
|
429
|
+
result: { ...result, tools: result.tools.filter((t) => typeof t.name === "string" && allowed.has(t.name)) }
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
for (const [token, requestId] of session.progress) if (requestId === record.id) session.progress.delete(token);
|
|
433
|
+
}
|
|
434
|
+
let relatedRequestId;
|
|
435
|
+
if (record.method === "notifications/progress") {
|
|
436
|
+
const token = record.params?.progressToken;
|
|
437
|
+
if (token !== void 0) relatedRequestId = session.progress.get(token);
|
|
438
|
+
}
|
|
439
|
+
await session.http.send(outgoing, relatedRequestId !== void 0 ? { relatedRequestId } : void 0).catch((error) => this.log(`lumoauth: cannot deliver a message to the client: ${error.message}`));
|
|
440
|
+
}
|
|
441
|
+
async close() {
|
|
442
|
+
await Promise.all([...this.sessions.values()].map((s) => s.http.close()));
|
|
443
|
+
this.sessions.clear();
|
|
444
|
+
}
|
|
445
|
+
};
|
|
446
|
+
|
|
447
|
+
// src/supervise.ts
|
|
448
|
+
var import_node_child_process = require("child_process");
|
|
449
|
+
var import_node_net = require("net");
|
|
450
|
+
function startUpstream(command) {
|
|
451
|
+
const [file, ...args] = command;
|
|
452
|
+
return (0, import_node_child_process.spawn)(file, args, { stdio: "inherit", env: process.env });
|
|
453
|
+
}
|
|
454
|
+
function canConnect(host, port) {
|
|
455
|
+
return new Promise((resolve) => {
|
|
456
|
+
const socket = (0, import_node_net.connect)({ host, port });
|
|
457
|
+
socket.setTimeout(1e3);
|
|
458
|
+
socket.once("connect", () => {
|
|
459
|
+
socket.destroy();
|
|
460
|
+
resolve(true);
|
|
461
|
+
});
|
|
462
|
+
socket.once("timeout", () => {
|
|
463
|
+
socket.destroy();
|
|
464
|
+
resolve(false);
|
|
465
|
+
});
|
|
466
|
+
socket.once("error", () => resolve(false));
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
async function waitForUpstream(url, child, timeoutMs = 3e4) {
|
|
470
|
+
const target = new URL(url);
|
|
471
|
+
const host = target.hostname.replace(/^\[|\]$/g, "");
|
|
472
|
+
const port = Number(target.port) || (target.protocol === "https:" ? 443 : 80);
|
|
473
|
+
const deadline = Date.now() + timeoutMs;
|
|
474
|
+
while (Date.now() < deadline) {
|
|
475
|
+
if (child && child.exitCode !== null) {
|
|
476
|
+
throw new Error(`the upstream command exited with code ${child.exitCode} before it started listening`);
|
|
477
|
+
}
|
|
478
|
+
if (await canConnect(host, port)) return;
|
|
479
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
480
|
+
}
|
|
481
|
+
throw new Error(`nothing accepted connections at ${target.host} within ${Math.round(timeoutMs / 1e3)} s`);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// src/cli.ts
|
|
485
|
+
var VERSION = "1.2.0";
|
|
486
|
+
var HELP = `lumoauth: put LumoAuth in front of an MCP server
|
|
487
|
+
|
|
488
|
+
Usage:
|
|
489
|
+
npx lumoauth secure --upstream <url> [options] [-- <command that starts it>]
|
|
490
|
+
npx lumoauth secure --stdio [options] -- <stdio server command>
|
|
491
|
+
npx lumoauth check [options]
|
|
492
|
+
|
|
493
|
+
Commands:
|
|
494
|
+
secure Serve the MCP server over HTTP behind LumoAuth: OAuth discovery,
|
|
495
|
+
token checks (Bearer and DPoP) and LumoAuth's per-tool policy.
|
|
496
|
+
The server's own code does not change.
|
|
497
|
+
check Show what LumoAuth's registration says, the discovery document
|
|
498
|
+
and the 401 challenge, then exit.
|
|
499
|
+
|
|
500
|
+
Options:
|
|
501
|
+
--org <slug> Organization (LUMOAUTH_ORG_ID)
|
|
502
|
+
--server <id> Registered MCP server id, mcp_... (LUMOAUTH_MCP_SERVER_ID)
|
|
503
|
+
--resource <uri> Resource URI, when there is no server id (LUMOAUTH_MCP_RESOURCE)
|
|
504
|
+
--lumoauth-url <url> LumoAuth instance (LUMOAUTH_URL, default https://app.lumoauth.dev)
|
|
505
|
+
--issuer <url> Organization issuer, for a custom domain (LUMOAUTH_ISSUER)
|
|
506
|
+
--upstream <url> The MCP endpoint to protect, e.g. http://127.0.0.1:8000/mcp
|
|
507
|
+
--stdio The command after -- is a stdio MCP server
|
|
508
|
+
--port <n> Port to listen on (PORT, default 8080)
|
|
509
|
+
--host <address> Address to listen on (default 0.0.0.0)
|
|
510
|
+
--path <path> Public path of the MCP endpoint (default: the Resource URI's path, or /mcp)
|
|
511
|
+
--scope <scope> A scope every request needs; repeat for more
|
|
512
|
+
--public <path> Forward this path without a token (health checks); repeatable
|
|
513
|
+
--tool-policy Require LumoAuth's per-tool policy (LUMOAUTH_MCP_CLIENT_ID and _SECRET)
|
|
514
|
+
--no-tool-policy Do not ask LumoAuth about tools
|
|
515
|
+
--no-identity-headers Do not send X-LumoAuth-* identity headers upstream
|
|
516
|
+
-h, --help Show this help
|
|
517
|
+
-v, --version Show the version
|
|
518
|
+
`;
|
|
519
|
+
var LUMOAUTH_OPTIONS = {
|
|
520
|
+
org: { type: "string" },
|
|
521
|
+
server: { type: "string" },
|
|
522
|
+
resource: { type: "string" },
|
|
523
|
+
"lumoauth-url": { type: "string" },
|
|
524
|
+
issuer: { type: "string" },
|
|
525
|
+
scope: { type: "string", multiple: true }
|
|
526
|
+
};
|
|
527
|
+
var UsageError = class extends Error {
|
|
528
|
+
};
|
|
529
|
+
function makeAuth(values) {
|
|
530
|
+
return (0, import_mcp2.lumoAuth)({
|
|
531
|
+
orgId: values.org,
|
|
532
|
+
serverId: values.server,
|
|
533
|
+
resource: values.resource,
|
|
534
|
+
lumoauthUrl: values["lumoauth-url"],
|
|
535
|
+
issuer: values.issuer,
|
|
536
|
+
requiredScopes: values.scope
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
var log = (line) => console.error(line);
|
|
540
|
+
async function secure(args, command) {
|
|
541
|
+
const { values } = (0, import_node_util.parseArgs)({
|
|
542
|
+
args,
|
|
543
|
+
strict: true,
|
|
544
|
+
options: {
|
|
545
|
+
...LUMOAUTH_OPTIONS,
|
|
546
|
+
upstream: { type: "string" },
|
|
547
|
+
stdio: { type: "boolean" },
|
|
548
|
+
port: { type: "string" },
|
|
549
|
+
host: { type: "string" },
|
|
550
|
+
path: { type: "string" },
|
|
551
|
+
public: { type: "string", multiple: true },
|
|
552
|
+
"tool-policy": { type: "boolean" },
|
|
553
|
+
"no-tool-policy": { type: "boolean" },
|
|
554
|
+
"no-identity-headers": { type: "boolean" }
|
|
555
|
+
}
|
|
556
|
+
});
|
|
557
|
+
if (values.stdio && values.upstream) throw new UsageError("use --upstream or --stdio, not both");
|
|
558
|
+
if (values.stdio && command.length === 0) {
|
|
559
|
+
throw new UsageError("--stdio needs the server command after --, for example: lumoauth secure --stdio -- node server.js");
|
|
560
|
+
}
|
|
561
|
+
if (!values.stdio && !values.upstream) {
|
|
562
|
+
throw new UsageError("say which server to protect: --upstream <url> for an HTTP server, or --stdio -- <command>");
|
|
563
|
+
}
|
|
564
|
+
if (values.upstream && !/^https?:\/\//.test(values.upstream)) {
|
|
565
|
+
throw new UsageError(`--upstream must be an http(s) URL, got '${values.upstream}'`);
|
|
566
|
+
}
|
|
567
|
+
const auth = makeAuth(values);
|
|
568
|
+
const config = await auth.ready();
|
|
569
|
+
let toolPolicy = auth.hasToolPolicy && !values["no-tool-policy"];
|
|
570
|
+
if (values["tool-policy"]) {
|
|
571
|
+
if (!auth.hasToolPolicy) {
|
|
572
|
+
throw new UsageError(
|
|
573
|
+
"--tool-policy needs LUMOAUTH_MCP_CLIENT_ID and LUMOAUTH_MCP_CLIENT_SECRET: the MCP server's own OAuth client, with the client_credentials grant and the mcp:authorize scope"
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
toolPolicy = true;
|
|
577
|
+
}
|
|
578
|
+
const resourcePath = new URL(config.resource).pathname.replace(/\/+$/, "");
|
|
579
|
+
const path = values.path ?? (resourcePath || "/mcp");
|
|
580
|
+
const port = Number(values.port ?? process.env.PORT ?? 8080);
|
|
581
|
+
const host = values.host ?? "0.0.0.0";
|
|
582
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new UsageError(`--port must be a port number, got '${values.port}'`);
|
|
583
|
+
let child;
|
|
584
|
+
if (values.upstream && command.length > 0) {
|
|
585
|
+
child = startUpstream(command);
|
|
586
|
+
child.on("exit", (code, signal) => {
|
|
587
|
+
log(`lumoauth: the upstream command stopped (${signal ?? `exit code ${code}`})`);
|
|
588
|
+
process.exit(code ?? 1);
|
|
589
|
+
});
|
|
590
|
+
await waitForUpstream(values.upstream, child);
|
|
591
|
+
}
|
|
592
|
+
const bridge = values.stdio ? new StdioBridge({
|
|
593
|
+
command,
|
|
594
|
+
filterTools: toolPolicy ? (caller, names) => allowedToolNames(auth, caller, names) : void 0,
|
|
595
|
+
log
|
|
596
|
+
}) : void 0;
|
|
597
|
+
const server = createSecureProxy({
|
|
598
|
+
auth,
|
|
599
|
+
upstream: values.upstream,
|
|
600
|
+
bridge,
|
|
601
|
+
path,
|
|
602
|
+
toolPolicy,
|
|
603
|
+
identityHeaders: !values["no-identity-headers"],
|
|
604
|
+
publicPaths: values.public ?? [],
|
|
605
|
+
log
|
|
606
|
+
});
|
|
607
|
+
await new Promise((resolve, reject) => {
|
|
608
|
+
server.once("error", reject);
|
|
609
|
+
server.listen(port, host, resolve);
|
|
610
|
+
});
|
|
611
|
+
const address = server.address();
|
|
612
|
+
const listening = typeof address === "object" && address ? `${host}:${address.port}` : `${host}:${port}`;
|
|
613
|
+
log(`lumoauth: ${values.stdio ? `stdio server '${command.join(" ")}'` : values.upstream} is protected by LumoAuth`);
|
|
614
|
+
log(` listening http://${listening}${path}`);
|
|
615
|
+
log(` resource ${config.resource}${config.requireDpop ? " (DPoP required)" : ""}`);
|
|
616
|
+
log(` issuer ${config.issuer}`);
|
|
617
|
+
log(` discovery ${config.resourceMetadataUrl}`);
|
|
618
|
+
log(` tool policy ${toolPolicy ? `on (server ${config.serverId})` : "off"}`);
|
|
619
|
+
if (config.resource.startsWith("https://")) {
|
|
620
|
+
log(" Clients must reach this proxy at the Resource URI, through your TLS proxy or tunnel.");
|
|
621
|
+
}
|
|
622
|
+
const stop = () => {
|
|
623
|
+
log("lumoauth: stopping");
|
|
624
|
+
server.close();
|
|
625
|
+
void bridge?.close();
|
|
626
|
+
child?.removeAllListeners("exit");
|
|
627
|
+
child?.kill("SIGTERM");
|
|
628
|
+
setTimeout(() => process.exit(0), 200).unref();
|
|
629
|
+
};
|
|
630
|
+
process.once("SIGINT", stop);
|
|
631
|
+
process.once("SIGTERM", stop);
|
|
632
|
+
}
|
|
633
|
+
async function check(args) {
|
|
634
|
+
const { values } = (0, import_node_util.parseArgs)({ args, strict: true, options: LUMOAUTH_OPTIONS });
|
|
635
|
+
const auth = makeAuth(values);
|
|
636
|
+
const config = await auth.ready();
|
|
637
|
+
const out = (line = "") => console.log(line);
|
|
638
|
+
out("LumoAuth");
|
|
639
|
+
out(` issuer ${config.issuer}`);
|
|
640
|
+
out(` MCP server ${config.serverId ?? "(none: resource given directly)"}`);
|
|
641
|
+
out(` resource ${config.resource}`);
|
|
642
|
+
out(` scopes ${config.scopesSupported.join(" ") || "(none advertised)"}`);
|
|
643
|
+
out(` DPoP ${config.requireDpop ? "required" : "accepted, not required"}`);
|
|
644
|
+
out(` tool policy ${auth.hasToolPolicy ? `configured (client ${auth.clientId})` : "not configured"}`);
|
|
645
|
+
out();
|
|
646
|
+
out(`Discovery document, served at ${config.resourceMetadataUrl}:`);
|
|
647
|
+
out(JSON.stringify(await auth.protectedResourceMetadata(), null, 2));
|
|
648
|
+
out();
|
|
649
|
+
out("401 challenge:");
|
|
650
|
+
out(` WWW-Authenticate: ${auth.challenge(config, 401, { scope: config.requiredScopes }).wwwAuthenticate}`);
|
|
651
|
+
out();
|
|
652
|
+
const discoveryUrl = `${config.issuer}/.well-known/openid-configuration`;
|
|
653
|
+
try {
|
|
654
|
+
const response = await fetch(discoveryUrl, { headers: { Accept: "application/json" } });
|
|
655
|
+
const metadata = await response.json();
|
|
656
|
+
const pkce = Array.isArray(metadata.code_challenge_methods_supported) && metadata.code_challenge_methods_supported.includes("S256");
|
|
657
|
+
out(`Authorization server (${discoveryUrl}):`);
|
|
658
|
+
out(` issuer matches ${metadata.issuer === config.issuer ? "yes" : `NO (${String(metadata.issuer)})`}`);
|
|
659
|
+
out(` PKCE S256 ${pkce ? "yes" : "NO: MCP clients refuse authorization servers without it"}`);
|
|
660
|
+
out(` client metadata docs ${metadata.client_id_metadata_document_supported === true ? "yes" : "no"}`);
|
|
661
|
+
out(` dynamic registration ${typeof metadata.registration_endpoint === "string" ? "yes" : "no"}`);
|
|
662
|
+
} catch (error) {
|
|
663
|
+
out(`Authorization server: cannot read ${discoveryUrl}: ${error.message}`);
|
|
664
|
+
process.exitCode = 1;
|
|
665
|
+
}
|
|
666
|
+
if (auth.hasToolPolicy) {
|
|
667
|
+
try {
|
|
668
|
+
auth.toolPolicy();
|
|
669
|
+
out(" per-tool policy client configured; decisions are asked on first use");
|
|
670
|
+
} catch (error) {
|
|
671
|
+
out(` per-tool policy ${error.message}`);
|
|
672
|
+
process.exitCode = 1;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
async function main(argv) {
|
|
677
|
+
const separator = argv.indexOf("--");
|
|
678
|
+
const own = separator >= 0 ? argv.slice(0, separator) : argv;
|
|
679
|
+
const command = separator >= 0 ? argv.slice(separator + 1) : [];
|
|
680
|
+
const [name, ...args] = own;
|
|
681
|
+
switch (name) {
|
|
682
|
+
case "secure":
|
|
683
|
+
return secure(args, command);
|
|
684
|
+
case "check":
|
|
685
|
+
return check(args);
|
|
686
|
+
case "-v":
|
|
687
|
+
case "--version":
|
|
688
|
+
case "version":
|
|
689
|
+
console.log(VERSION);
|
|
690
|
+
return;
|
|
691
|
+
case void 0:
|
|
692
|
+
case "-h":
|
|
693
|
+
case "--help":
|
|
694
|
+
case "help":
|
|
695
|
+
console.log(HELP);
|
|
696
|
+
return;
|
|
697
|
+
default:
|
|
698
|
+
throw new UsageError(`unknown command '${name}'. Run 'lumoauth --help'.`);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
function run(argv) {
|
|
702
|
+
main(argv).catch((error) => {
|
|
703
|
+
console.error(`lumoauth: ${error.message}`);
|
|
704
|
+
if (error instanceof UsageError) console.error("Run 'lumoauth --help' for the options.");
|
|
705
|
+
process.exit(1);
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
// src/bin.ts
|
|
710
|
+
run(process.argv.slice(2));
|
|
711
|
+
//# sourceMappingURL=cli.js.map
|