lumoauth 1.0.0 → 1.3.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/dist/index.mjs CHANGED
@@ -4,6 +4,9 @@ import { Readable } from "stream";
4
4
  import { pipeline } from "stream/promises";
5
5
  import {
6
6
  LumoAuthChallenge,
7
+ missingAuthorizationDetails,
8
+ normalizeAuthorizationDetails,
9
+ parseTraceparent,
7
10
  writeChallenge
8
11
  } from "@lumoauth/mcp";
9
12
 
@@ -22,9 +25,13 @@ function inspect(body) {
22
25
  result.isBatch = Array.isArray(parsed);
23
26
  const messages = Array.isArray(parsed) ? parsed : [parsed];
24
27
  for (const message of messages) {
25
- if (typeof message !== "object" || message === null || message.id === void 0) continue;
28
+ if (typeof message !== "object" || message === null) continue;
29
+ const params = message.params;
30
+ if (!result.traceparent && typeof params?._meta?.traceparent === "string") {
31
+ result.traceparent = params._meta.traceparent;
32
+ }
33
+ if (message.id === void 0) continue;
26
34
  if (message.method === "tools/call") {
27
- const params = message.params;
28
35
  result.toolCalls.push({ id: asId(message.id), name: typeof params?.name === "string" ? params.name : "" });
29
36
  } else if (message.method === "tools/list") {
30
37
  result.toolListIds.add(JSON.stringify(message.id));
@@ -35,6 +42,28 @@ function inspect(body) {
35
42
  function refusedToolResult(id, message) {
36
43
  return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: message }], isError: true } };
37
44
  }
45
+ function refusedJitToolResult(id, tool, requiredDetails) {
46
+ const hintJson = JSON.stringify(requiredDetails);
47
+ const headerValue = Buffer.from(hintJson, "utf8").toString("base64");
48
+ const types = requiredDetails.map((d) => d.type).join(", ");
49
+ const message = `Tool '${tool}' requires JIT authorization_details (${types}); authorization_details_hint=${hintJson}`;
50
+ return {
51
+ headerValue,
52
+ body: {
53
+ jsonrpc: "2.0",
54
+ id,
55
+ result: {
56
+ content: [{ type: "text", text: message }],
57
+ isError: true,
58
+ _meta: {
59
+ error: "insufficient_authorization_details",
60
+ authorization_details_hint: requiredDetails,
61
+ "Insufficient-Authorization-Details": headerValue
62
+ }
63
+ }
64
+ }
65
+ };
66
+ }
38
67
  async function filterMessage(message, ids, decide) {
39
68
  if (typeof message !== "object" || message === null) return message;
40
69
  const response = message;
@@ -188,6 +217,19 @@ function createSecureProxy(options) {
188
217
  if (caller.actor) headers.set("x-lumoauth-actor", caller.actor);
189
218
  if (caller.clientId) headers.set("x-lumoauth-client-id", caller.clientId);
190
219
  headers.set("x-lumoauth-scopes", caller.scopes.join(" "));
220
+ if (caller.traceId) headers.set("x-lumoauth-trace-id", caller.traceId);
221
+ if (caller.isJit) headers.set("x-lumoauth-is-jit", "true");
222
+ }
223
+ if (caller?.traceparent && !headers.has("traceparent")) {
224
+ headers.set("traceparent", caller.traceparent);
225
+ }
226
+ if (caller && options.vaultConnections) {
227
+ for (const [slug, connectionId] of Object.entries(options.vaultConnections)) {
228
+ const cleanSlug = slug.trim().toLowerCase().replace(/[^a-z0-9-]/g, "-");
229
+ if (!cleanSlug || !connectionId) continue;
230
+ const vaultToken = await auth.vaultToken(connectionId, caller);
231
+ headers.set(`x-lumoauth-vault-${cleanSlug}-token`, vaultToken.accessToken);
232
+ }
191
233
  }
192
234
  const controller = new AbortController();
193
235
  res.on("close", () => controller.abort());
@@ -277,21 +319,48 @@ function createSecureProxy(options) {
277
319
  }
278
320
  const body = method === "POST" ? await readBody(req, maxBody) : void 0;
279
321
  let inspection;
280
- if (body && options.toolPolicy) {
322
+ if (body && (options.toolPolicy || options.jit)) {
281
323
  inspection = inspect(body.toString("utf8"));
282
- const refused = [];
283
- for (const call of inspection.toolCalls) {
284
- if (!await auth.toolPolicy().isAllowed(caller, call.name)) refused.push(call);
324
+ if (!caller.traceparent && inspection.traceparent) {
325
+ const parsedTp = parseTraceparent(inspection.traceparent);
326
+ if (parsedTp) {
327
+ caller.traceparent = parsedTp.traceparent;
328
+ caller.traceId ?? (caller.traceId = parsedTp.traceId);
329
+ }
285
330
  }
286
- if (refused.length > 0) {
287
- const reason = (name) => `LumoAuth policy does not allow this caller to run '${name}'.`;
288
- log2(`lumoauth: refused ${refused.map((c) => c.name).join(", ")} for ${caller.sub}`);
289
- if (inspection.isBatch) {
290
- writeJson(res, 200, inspection.toolCalls.map((c) => refusedToolResult(c.id, reason(refused[0].name))));
291
- } else {
292
- writeJson(res, 200, refusedToolResult(refused[0].id, reason(refused[0].name)));
331
+ if (options.toolPolicy) {
332
+ const refused = [];
333
+ for (const call of inspection.toolCalls) {
334
+ if (!await auth.toolPolicy().isAllowed(caller, call.name)) refused.push(call);
335
+ }
336
+ if (refused.length > 0) {
337
+ const reason = (name) => `LumoAuth policy does not allow this caller to run '${name}'.`;
338
+ log2(`lumoauth: refused ${refused.map((c) => c.name).join(", ")} for ${caller.sub}`);
339
+ if (inspection.isBatch) {
340
+ writeJson(res, 200, inspection.toolCalls.map((c) => refusedToolResult(c.id, reason(refused[0].name))));
341
+ } else {
342
+ writeJson(res, 200, refusedToolResult(refused[0].id, reason(refused[0].name)));
343
+ }
344
+ return;
345
+ }
346
+ }
347
+ if (options.jit) {
348
+ for (const call of inspection.toolCalls) {
349
+ const jitSpec = options.jit[call.name];
350
+ if (!jitSpec) continue;
351
+ const required = normalizeAuthorizationDetails(jitSpec);
352
+ const missing = missingAuthorizationDetails(required, caller.authorizationDetails);
353
+ if (missing.length > 0) {
354
+ const jitRefusal = refusedJitToolResult(call.id, call.name, missing);
355
+ res.setHeader("Insufficient-Authorization-Details", jitRefusal.headerValue);
356
+ writeJson(
357
+ res,
358
+ 200,
359
+ inspection.isBatch ? inspection.toolCalls.map((c) => refusedJitToolResult(c.id, call.name, missing).body) : jitRefusal.body
360
+ );
361
+ return;
362
+ }
293
363
  }
294
- return;
295
364
  }
296
365
  }
297
366
  if (options.bridge) {
@@ -322,6 +391,144 @@ function createSecureProxy(options) {
322
391
  });
323
392
  }
324
393
 
394
+ // src/ext-authz.ts
395
+ import { createServer as createServer2 } from "http";
396
+ import {
397
+ LumoAuthChallenge as LumoAuthChallenge2,
398
+ missingAuthorizationDetails as missingAuthorizationDetails2,
399
+ normalizeAuthorizationDetails as normalizeAuthorizationDetails2,
400
+ parseTraceparent as parseTraceparent2,
401
+ writeChallenge as writeChallenge2
402
+ } from "@lumoauth/mcp";
403
+ function headerOf2(req, name) {
404
+ const value = req.headers[name];
405
+ return Array.isArray(value) ? value[0] : value;
406
+ }
407
+ async function readBody2(req, limit) {
408
+ const chunks = [];
409
+ let size = 0;
410
+ for await (const chunk of req) {
411
+ size += chunk.length;
412
+ if (size > limit) break;
413
+ chunks.push(chunk);
414
+ }
415
+ return Buffer.concat(chunks);
416
+ }
417
+ function writeJson2(res, status, body, headers = {}) {
418
+ const text = JSON.stringify(body);
419
+ res.statusCode = status;
420
+ for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
421
+ res.setHeader("Content-Type", "application/json");
422
+ res.setHeader("Content-Length", Buffer.byteLength(text));
423
+ res.end(text);
424
+ }
425
+ function createExtAuthzServer(options) {
426
+ const { auth } = options;
427
+ const log2 = options.log ?? ((line) => console.error(line));
428
+ const identityHeaders = options.identityHeaders ?? true;
429
+ const publicPaths = options.publicPaths ?? ["/healthz", "/readyz"];
430
+ const maxBody = options.maxBodyBytes ?? 1024 * 1024;
431
+ async function handle(req, res) {
432
+ const method = headerOf2(req, "x-envoy-original-method") ?? req.method ?? "GET";
433
+ const rawPath = headerOf2(req, "x-envoy-original-path") ?? headerOf2(req, "x-forwarded-uri") ?? req.url ?? "/";
434
+ const url = new URL(rawPath, "http://ext-authz.invalid");
435
+ if (publicPaths.includes(url.pathname)) {
436
+ res.statusCode = 200;
437
+ res.end();
438
+ return;
439
+ }
440
+ const discovery = await auth.discoveryResponse(method, url.pathname);
441
+ if (discovery) {
442
+ res.statusCode = discovery.status;
443
+ for (const [k, v] of Object.entries(discovery.headers)) res.setHeader(k, v);
444
+ res.end(discovery.body);
445
+ return;
446
+ }
447
+ let info;
448
+ try {
449
+ info = await auth.authenticate({ method, url: rawPath, headers: req.headers });
450
+ } catch (error) {
451
+ if (error instanceof LumoAuthChallenge2) {
452
+ writeChallenge2(res, error);
453
+ return;
454
+ }
455
+ throw error;
456
+ }
457
+ const caller = info.extra.caller;
458
+ const body = method === "POST" ? await readBody2(req, maxBody) : void 0;
459
+ if (body && body.length > 0 && (options.toolPolicy || options.jit)) {
460
+ const inspection = inspect(body.toString("utf8"));
461
+ if (!caller.traceparent && inspection.traceparent) {
462
+ const parsedTp = parseTraceparent2(inspection.traceparent);
463
+ if (parsedTp) {
464
+ caller.traceparent = parsedTp.traceparent;
465
+ caller.traceId ?? (caller.traceId = parsedTp.traceId);
466
+ }
467
+ }
468
+ if (options.toolPolicy) {
469
+ for (const call of inspection.toolCalls) {
470
+ if (!await auth.toolPolicy().isAllowed(caller, call.name)) {
471
+ log2(`lumoauth ext-authz: refused tool '${call.name}' for ${caller.sub}`);
472
+ writeJson2(
473
+ res,
474
+ 403,
475
+ refusedToolResult(call.id, `LumoAuth policy does not allow this caller to run '${call.name}'.`),
476
+ { "X-LumoAuth-Denied-Tool": call.name }
477
+ );
478
+ return;
479
+ }
480
+ }
481
+ }
482
+ if (options.jit) {
483
+ for (const call of inspection.toolCalls) {
484
+ const jitSpec = options.jit[call.name];
485
+ if (!jitSpec) continue;
486
+ const required = normalizeAuthorizationDetails2(jitSpec);
487
+ const missing = missingAuthorizationDetails2(required, caller.authorizationDetails);
488
+ if (missing.length > 0) {
489
+ const jitRefusal = refusedJitToolResult(call.id, call.name, missing);
490
+ writeJson2(res, 403, jitRefusal.body, {
491
+ "Insufficient-Authorization-Details": jitRefusal.headerValue,
492
+ "WWW-Authenticate": `Bearer error="insufficient_authorization_details", error_description="JIT step-up required for tool '${call.name}'"`
493
+ });
494
+ return;
495
+ }
496
+ }
497
+ }
498
+ }
499
+ res.statusCode = 200;
500
+ if (identityHeaders) {
501
+ res.setHeader("x-lumoauth-subject", caller.sub);
502
+ res.setHeader("x-lumoauth-subject-type", caller.isAgent ? "agent" : "user");
503
+ if (caller.agentId) res.setHeader("x-lumoauth-agent-id", caller.agentId);
504
+ if (caller.actor) res.setHeader("x-lumoauth-actor", caller.actor);
505
+ if (caller.clientId) res.setHeader("x-lumoauth-client-id", caller.clientId);
506
+ res.setHeader("x-lumoauth-scopes", caller.scopes.join(" "));
507
+ if (caller.traceId) res.setHeader("x-lumoauth-trace-id", caller.traceId);
508
+ if (caller.isJit) res.setHeader("x-lumoauth-is-jit", "true");
509
+ }
510
+ if (caller.traceparent) {
511
+ res.setHeader("traceparent", caller.traceparent);
512
+ }
513
+ if (options.vaultConnections) {
514
+ for (const [slug, connectionId] of Object.entries(options.vaultConnections)) {
515
+ const cleanSlug = slug.trim().toLowerCase().replace(/[^a-z0-9-]/g, "-");
516
+ if (!cleanSlug || !connectionId) continue;
517
+ const vaultToken = await auth.vaultToken(connectionId, caller);
518
+ res.setHeader(`x-lumoauth-vault-${cleanSlug}-token`, vaultToken.accessToken);
519
+ }
520
+ }
521
+ res.end();
522
+ }
523
+ return createServer2((req, res) => {
524
+ handle(req, res).catch((error) => {
525
+ log2(`lumoauth ext-authz: ${error.stack ?? error}`);
526
+ if (!res.headersSent) writeJson2(res, 500, { error: "server_error" });
527
+ else res.destroy();
528
+ });
529
+ });
530
+ }
531
+
325
532
  // src/stdio.ts
326
533
  import { randomUUID } from "crypto";
327
534
  import { StdioClientTransport, getDefaultEnvironment } from "@modelcontextprotocol/sdk/client/stdio.js";
@@ -484,20 +691,24 @@ async function waitForUpstream(url, child, timeoutMs = 3e4) {
484
691
  // src/cli.ts
485
692
  import { parseArgs } from "util";
486
693
  import { lumoAuth } from "@lumoauth/mcp";
487
- var VERSION = "1.0.0";
694
+ var VERSION = "1.3.0";
488
695
  var HELP = `lumoauth: put LumoAuth in front of an MCP server
489
696
 
490
697
  Usage:
491
698
  npx lumoauth secure --upstream <url> [options] [-- <command that starts it>]
492
699
  npx lumoauth secure --stdio [options] -- <stdio server command>
700
+ npx lumoauth ext-authz [options]
493
701
  npx lumoauth check [options]
494
702
 
495
703
  Commands:
496
- secure Serve the MCP server over HTTP behind LumoAuth: OAuth discovery,
497
- token checks (Bearer and DPoP) and LumoAuth's per-tool policy.
498
- The server's own code does not change.
499
- check Show what LumoAuth's registration says, the discovery document
500
- and the 401 challenge, then exit.
704
+ secure Serve the MCP server over HTTP behind LumoAuth: OAuth discovery,
705
+ token checks (Bearer and DPoP) and LumoAuth's per-tool policy.
706
+ The server's own code does not change.
707
+ ext-authz Run as an Envoy HTTP ext_authz check server for Kubernetes / service
708
+ mesh deployments, returning 200 OK with X-LumoAuth-* headers or
709
+ 401/403 RFC 9728 challenges.
710
+ check Show what LumoAuth's registration says, the discovery document
711
+ and the 401 challenge, then exit.
501
712
 
502
713
  Options:
503
714
  --org <slug> Organization (LUMOAUTH_ORG_ID)
@@ -507,11 +718,14 @@ Options:
507
718
  --issuer <url> Organization issuer, for a custom domain (LUMOAUTH_ISSUER)
508
719
  --upstream <url> The MCP endpoint to protect, e.g. http://127.0.0.1:8000/mcp
509
720
  --stdio The command after -- is a stdio MCP server
721
+ --ext-authz Run in Envoy HTTP ext_authz check mode
510
722
  --port <n> Port to listen on (PORT, default 8080)
511
723
  --host <address> Address to listen on (default 0.0.0.0)
512
724
  --path <path> Public path of the MCP endpoint (default: the Resource URI's path, or /mcp)
513
725
  --scope <scope> A scope every request needs; repeat for more
514
726
  --public <path> Forward this path without a token (health checks); repeatable
727
+ --jit <tool=type[:a]> Require a JIT/RAR grant for a tool (e.g. refund=payment:refund); repeatable
728
+ --vault <slug=conn> Inject X-LumoAuth-Vault-<Slug>-Token from Token Vault; repeatable
515
729
  --tool-policy Require LumoAuth's per-tool policy (LUMOAUTH_MCP_CLIENT_ID and _SECRET)
516
730
  --no-tool-policy Do not ask LumoAuth about tools
517
731
  --no-identity-headers Do not send X-LumoAuth-* identity headers upstream
@@ -539,7 +753,39 @@ function makeAuth(values) {
539
753
  });
540
754
  }
541
755
  var log = (line) => console.error(line);
542
- async function secure(args, command) {
756
+ function parseJitSpecs(specs) {
757
+ if (!specs || specs.length === 0) return void 0;
758
+ const out = {};
759
+ for (const raw of specs) {
760
+ const eq = raw.indexOf("=");
761
+ if (eq <= 0 || eq === raw.length - 1) {
762
+ throw new UsageError(`--jit must be <tool>=<type>[:action1,action2], got '${raw}'`);
763
+ }
764
+ const tool = raw.slice(0, eq).trim();
765
+ const rest = raw.slice(eq + 1).trim();
766
+ const [type, actionsRaw] = rest.split(":", 2);
767
+ if (!tool || !type) throw new UsageError(`--jit must be <tool>=<type>[:action1,action2], got '${raw}'`);
768
+ const actions = actionsRaw ? actionsRaw.split(",").map((a) => a.trim()).filter(Boolean) : void 0;
769
+ out[tool] = actions && actions.length > 0 ? { type, actions } : { type };
770
+ }
771
+ return out;
772
+ }
773
+ function parseVaultSpecs(specs) {
774
+ if (!specs || specs.length === 0) return void 0;
775
+ const out = {};
776
+ for (const raw of specs) {
777
+ const eq = raw.indexOf("=");
778
+ if (eq <= 0 || eq === raw.length - 1) {
779
+ throw new UsageError(`--vault must be <slug>=<connection_id>, got '${raw}'`);
780
+ }
781
+ const slug = raw.slice(0, eq).trim();
782
+ const conn = raw.slice(eq + 1).trim();
783
+ if (!slug || !conn) throw new UsageError(`--vault must be <slug>=<connection_id>, got '${raw}'`);
784
+ out[slug] = conn;
785
+ }
786
+ return out;
787
+ }
788
+ async function secure(args, command, forceExtAuthz = false) {
543
789
  const { values } = parseArgs({
544
790
  args,
545
791
  strict: true,
@@ -547,25 +793,33 @@ async function secure(args, command) {
547
793
  ...LUMOAUTH_OPTIONS,
548
794
  upstream: { type: "string" },
549
795
  stdio: { type: "boolean" },
796
+ "ext-authz": { type: "boolean" },
550
797
  port: { type: "string" },
551
798
  host: { type: "string" },
552
799
  path: { type: "string" },
553
800
  public: { type: "string", multiple: true },
801
+ jit: { type: "string", multiple: true },
802
+ vault: { type: "string", multiple: true },
554
803
  "tool-policy": { type: "boolean" },
555
804
  "no-tool-policy": { type: "boolean" },
556
805
  "no-identity-headers": { type: "boolean" }
557
806
  }
558
807
  });
559
- if (values.stdio && values.upstream) throw new UsageError("use --upstream or --stdio, not both");
560
- if (values.stdio && command.length === 0) {
561
- throw new UsageError("--stdio needs the server command after --, for example: lumoauth secure --stdio -- node server.js");
562
- }
563
- if (!values.stdio && !values.upstream) {
564
- throw new UsageError("say which server to protect: --upstream <url> for an HTTP server, or --stdio -- <command>");
565
- }
566
- if (values.upstream && !/^https?:\/\//.test(values.upstream)) {
567
- throw new UsageError(`--upstream must be an http(s) URL, got '${values.upstream}'`);
808
+ const isExtAuthz = forceExtAuthz || Boolean(values["ext-authz"]);
809
+ if (!isExtAuthz) {
810
+ if (values.stdio && values.upstream) throw new UsageError("use --upstream or --stdio, not both");
811
+ if (values.stdio && command.length === 0) {
812
+ throw new UsageError("--stdio needs the server command after --, for example: lumoauth secure --stdio -- node server.js");
813
+ }
814
+ if (!values.stdio && !values.upstream) {
815
+ throw new UsageError("say which server to protect: --upstream <url> for an HTTP server, or --stdio -- <command>");
816
+ }
817
+ if (values.upstream && !/^https?:\/\//.test(values.upstream)) {
818
+ throw new UsageError(`--upstream must be an http(s) URL, got '${values.upstream}'`);
819
+ }
568
820
  }
821
+ const jit = parseJitSpecs(values.jit);
822
+ const vaultConnections = parseVaultSpecs(values.vault);
569
823
  const auth = makeAuth(values);
570
824
  const config = await auth.ready();
571
825
  let toolPolicy = auth.hasToolPolicy && !values["no-tool-policy"];
@@ -582,6 +836,35 @@ async function secure(args, command) {
582
836
  const port = Number(values.port ?? process.env.PORT ?? 8080);
583
837
  const host = values.host ?? "0.0.0.0";
584
838
  if (!Number.isInteger(port) || port < 0 || port > 65535) throw new UsageError(`--port must be a port number, got '${values.port}'`);
839
+ if (isExtAuthz) {
840
+ const extServer = createExtAuthzServer({
841
+ auth,
842
+ toolPolicy,
843
+ identityHeaders: !values["no-identity-headers"],
844
+ publicPaths: values.public ?? ["/healthz", "/readyz"],
845
+ jit,
846
+ vaultConnections,
847
+ log
848
+ });
849
+ await new Promise((resolve, reject) => {
850
+ extServer.once("error", reject);
851
+ extServer.listen(port, host, resolve);
852
+ });
853
+ const addr = extServer.address();
854
+ const listening2 = typeof addr === "object" && addr ? `${host}:${addr.port}` : `${host}:${port}`;
855
+ log(`lumoauth: Envoy ext_authz server listening on http://${listening2}`);
856
+ log(` resource ${config.resource}${config.requireDpop ? " (DPoP required)" : ""}`);
857
+ log(` issuer ${config.issuer}`);
858
+ log(` tool policy ${toolPolicy ? `on (server ${config.serverId})` : "off"}`);
859
+ const stopExt = () => {
860
+ log("lumoauth: stopping ext-authz");
861
+ extServer.close();
862
+ setTimeout(() => process.exit(0), 200).unref();
863
+ };
864
+ process.once("SIGINT", stopExt);
865
+ process.once("SIGTERM", stopExt);
866
+ return;
867
+ }
585
868
  let child;
586
869
  if (values.upstream && command.length > 0) {
587
870
  child = startUpstream(command);
@@ -604,6 +887,8 @@ async function secure(args, command) {
604
887
  toolPolicy,
605
888
  identityHeaders: !values["no-identity-headers"],
606
889
  publicPaths: values.public ?? [],
890
+ jit,
891
+ vaultConnections,
607
892
  log
608
893
  });
609
894
  await new Promise((resolve, reject) => {
@@ -682,7 +967,9 @@ async function main(argv) {
682
967
  const [name, ...args] = own;
683
968
  switch (name) {
684
969
  case "secure":
685
- return secure(args, command);
970
+ return secure(args, command, false);
971
+ case "ext-authz":
972
+ return secure(args, command, true);
686
973
  case "check":
687
974
  return check(args);
688
975
  case "-v":
@@ -703,11 +990,13 @@ async function main(argv) {
703
990
  export {
704
991
  StdioBridge,
705
992
  allowedToolNames,
993
+ createExtAuthzServer,
706
994
  createSecureProxy,
707
995
  filterJsonBody,
708
996
  filterSseEvent,
709
997
  inspect,
710
998
  main,
999
+ refusedJitToolResult,
711
1000
  refusedToolResult,
712
1001
  startUpstream,
713
1002
  waitForUpstream