lumoauth 1.3.1 → 1.5.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.js CHANGED
@@ -28,6 +28,7 @@ __export(src_exports, {
28
28
  filterSseEvent: () => filterSseEvent,
29
29
  inspect: () => inspect,
30
30
  main: () => main,
31
+ publicRequestUrl: () => publicRequestUrl,
31
32
  refusedJitToolResult: () => refusedJitToolResult,
32
33
  refusedToolResult: () => refusedToolResult,
33
34
  startUpstream: () => startUpstream,
@@ -39,9 +40,10 @@ module.exports = __toCommonJS(src_exports);
39
40
  var import_node_http = require("http");
40
41
  var import_node_stream = require("stream");
41
42
  var import_promises = require("stream/promises");
42
- var import_mcp = require("@lumoauth/mcp");
43
+ var import_mcp2 = require("@lumoauth/mcp");
43
44
 
44
45
  // src/jsonrpc.ts
46
+ var import_mcp = require("@lumoauth/mcp");
45
47
  function asId(value) {
46
48
  return typeof value === "string" || typeof value === "number" ? value : null;
47
49
  }
@@ -73,23 +75,20 @@ function inspect(body) {
73
75
  function refusedToolResult(id, message) {
74
76
  return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: message }], isError: true } };
75
77
  }
76
- function refusedJitToolResult(id, tool, requiredDetails) {
77
- const hintJson = JSON.stringify(requiredDetails);
78
- const headerValue = Buffer.from(hintJson, "utf8").toString("base64");
79
- const types = requiredDetails.map((d) => d.type).join(", ");
80
- const message = `Tool '${tool}' requires JIT authorization_details (${types}); authorization_details_hint=${hintJson}`;
78
+ function refusedJitToolResult(id, tool, requiredDetails, jitTokenError) {
79
+ const refusal = new import_mcp.InsufficientAuthorizationDetailsError(tool, requiredDetails, void 0, jitTokenError);
81
80
  return {
82
- headerValue,
81
+ headerValue: refusal.headerValue,
83
82
  body: {
84
83
  jsonrpc: "2.0",
85
84
  id,
86
85
  result: {
87
- content: [{ type: "text", text: message }],
86
+ content: [{ type: "text", text: refusal.message }],
88
87
  isError: true,
89
88
  _meta: {
90
89
  error: "insufficient_authorization_details",
91
- authorization_details_hint: requiredDetails,
92
- "Insufficient-Authorization-Details": headerValue
90
+ authorization_details_hint: refusal.hint,
91
+ "Insufficient-Authorization-Details": refusal.headerValue
93
92
  }
94
93
  }
95
94
  }
@@ -336,8 +335,8 @@ function createSecureProxy(options) {
336
335
  try {
337
336
  info = await auth.authenticate({ method, url: req.url ?? "/", headers: req.headers });
338
337
  } catch (error) {
339
- if (error instanceof import_mcp.LumoAuthChallenge) {
340
- (0, import_mcp.writeChallenge)(res, error);
338
+ if (error instanceof import_mcp2.LumoAuthChallenge) {
339
+ (0, import_mcp2.writeChallenge)(res, error);
341
340
  return;
342
341
  }
343
342
  throw error;
@@ -353,7 +352,7 @@ function createSecureProxy(options) {
353
352
  if (body && (options.toolPolicy || options.jit)) {
354
353
  inspection = inspect(body.toString("utf8"));
355
354
  if (!caller.traceparent && inspection.traceparent) {
356
- const parsedTp = (0, import_mcp.parseTraceparent)(inspection.traceparent);
355
+ const parsedTp = (0, import_mcp2.parseTraceparent)(inspection.traceparent);
357
356
  if (parsedTp) {
358
357
  caller.traceparent = parsedTp.traceparent;
359
358
  caller.traceId ?? (caller.traceId = parsedTp.traceId);
@@ -379,15 +378,17 @@ function createSecureProxy(options) {
379
378
  for (const call of inspection.toolCalls) {
380
379
  const jitSpec = options.jit[call.name];
381
380
  if (!jitSpec) continue;
382
- const required = (0, import_mcp.normalizeAuthorizationDetails)(jitSpec);
383
- const missing = (0, import_mcp.missingAuthorizationDetails)(required, caller.authorizationDetails);
381
+ const required = (0, import_mcp2.normalizeAuthorizationDetails)(jitSpec);
382
+ const missing = (0, import_mcp2.missingAuthorizationDetails)(required, caller.authorizationDetails);
384
383
  if (missing.length > 0) {
385
- const jitRefusal = refusedJitToolResult(call.id, call.name, missing);
384
+ const jitRefusal = refusedJitToolResult(call.id, call.name, missing, caller.jitTokenError);
386
385
  res.setHeader("Insufficient-Authorization-Details", jitRefusal.headerValue);
387
386
  writeJson(
388
387
  res,
389
388
  200,
390
- inspection.isBatch ? inspection.toolCalls.map((c) => refusedJitToolResult(c.id, call.name, missing).body) : jitRefusal.body
389
+ inspection.isBatch ? inspection.toolCalls.map(
390
+ (c) => refusedJitToolResult(c.id, call.name, missing, caller.jitTokenError).body
391
+ ) : jitRefusal.body
391
392
  );
392
393
  return;
393
394
  }
@@ -424,11 +425,20 @@ function createSecureProxy(options) {
424
425
 
425
426
  // src/ext-authz.ts
426
427
  var import_node_http2 = require("http");
427
- var import_mcp2 = require("@lumoauth/mcp");
428
- function headerOf2(req, name) {
429
- const value = req.headers[name];
430
- return Array.isArray(value) ? value[0] : value;
431
- }
428
+ var import_mcp3 = require("@lumoauth/mcp");
429
+ var IDENTITY_HEADERS = [
430
+ "x-lumoauth-subject",
431
+ "x-lumoauth-subject-type",
432
+ "x-lumoauth-agent-id",
433
+ "x-lumoauth-actor",
434
+ "x-lumoauth-client-id",
435
+ "x-lumoauth-scopes",
436
+ "x-lumoauth-trace-id",
437
+ "x-lumoauth-is-jit"
438
+ ];
439
+ var IDENTITY_PREFIX2 = "x-lumoauth-";
440
+ var JIT_TOKEN_HEADER = "x-lumoauth-jit-token";
441
+ var ENVOY_HEADERS_TO_REMOVE = "x-envoy-auth-headers-to-remove";
432
442
  async function readBody2(req, limit) {
433
443
  const chunks = [];
434
444
  let size = 0;
@@ -447,23 +457,45 @@ function writeJson2(res, status, body, headers = {}) {
447
457
  res.setHeader("Content-Length", Buffer.byteLength(text));
448
458
  res.end(text);
449
459
  }
460
+ function vaultHeaderName(slug) {
461
+ const cleanSlug = slug.trim().toLowerCase().replace(/[^a-z0-9-]/g, "-");
462
+ return cleanSlug ? `x-lumoauth-vault-${cleanSlug}-token` : void 0;
463
+ }
450
464
  function createExtAuthzServer(options) {
451
465
  const { auth } = options;
452
466
  const log2 = options.log ?? ((line) => console.error(line));
453
467
  const identityHeaders = options.identityHeaders ?? true;
454
468
  const publicPaths = options.publicPaths ?? ["/healthz", "/readyz"];
455
469
  const maxBody = options.maxBodyBytes ?? 1024 * 1024;
470
+ const vaultHeaders = Object.keys(options.vaultConnections ?? {}).map(vaultHeaderName).filter((name) => Boolean(name));
471
+ function allow(req, res, headers, body) {
472
+ const remove = /* @__PURE__ */ new Set([...IDENTITY_HEADERS, JIT_TOKEN_HEADER, ...vaultHeaders]);
473
+ for (const name of Object.keys(req.headers)) {
474
+ const lower = name.toLowerCase();
475
+ if (lower.startsWith(IDENTITY_PREFIX2)) remove.add(lower);
476
+ }
477
+ res.statusCode = 200;
478
+ for (const [name, value] of Object.entries(headers)) {
479
+ res.setHeader(name, value);
480
+ remove.delete(name.toLowerCase());
481
+ }
482
+ res.setHeader(ENVOY_HEADERS_TO_REMOVE, [...remove].join(","));
483
+ res.end(body);
484
+ }
456
485
  async function handle(req, res) {
457
- const method = headerOf2(req, "x-envoy-original-method") ?? req.method ?? "GET";
458
- const rawPath = headerOf2(req, "x-envoy-original-path") ?? headerOf2(req, "x-forwarded-uri") ?? req.url ?? "/";
486
+ const method = req.method ?? "GET";
487
+ const rawPath = req.url ?? "/";
459
488
  const url = new URL(rawPath, "http://ext-authz.invalid");
460
489
  if (publicPaths.includes(url.pathname)) {
461
- res.statusCode = 200;
462
- res.end();
490
+ allow(req, res, {});
463
491
  return;
464
492
  }
465
493
  const discovery = await auth.discoveryResponse(method, url.pathname);
466
494
  if (discovery) {
495
+ if (discovery.status === 200) {
496
+ allow(req, res, discovery.headers, discovery.body);
497
+ return;
498
+ }
467
499
  res.statusCode = discovery.status;
468
500
  for (const [k, v] of Object.entries(discovery.headers)) res.setHeader(k, v);
469
501
  res.end(discovery.body);
@@ -473,8 +505,8 @@ function createExtAuthzServer(options) {
473
505
  try {
474
506
  info = await auth.authenticate({ method, url: rawPath, headers: req.headers });
475
507
  } catch (error) {
476
- if (error instanceof import_mcp2.LumoAuthChallenge) {
477
- (0, import_mcp2.writeChallenge)(res, error);
508
+ if (error instanceof import_mcp3.LumoAuthChallenge) {
509
+ (0, import_mcp3.writeChallenge)(res, error);
478
510
  return;
479
511
  }
480
512
  throw error;
@@ -484,7 +516,7 @@ function createExtAuthzServer(options) {
484
516
  if (body && body.length > 0 && (options.toolPolicy || options.jit)) {
485
517
  const inspection = inspect(body.toString("utf8"));
486
518
  if (!caller.traceparent && inspection.traceparent) {
487
- const parsedTp = (0, import_mcp2.parseTraceparent)(inspection.traceparent);
519
+ const parsedTp = (0, import_mcp3.parseTraceparent)(inspection.traceparent);
488
520
  if (parsedTp) {
489
521
  caller.traceparent = parsedTp.traceparent;
490
522
  caller.traceId ?? (caller.traceId = parsedTp.traceId);
@@ -508,10 +540,10 @@ function createExtAuthzServer(options) {
508
540
  for (const call of inspection.toolCalls) {
509
541
  const jitSpec = options.jit[call.name];
510
542
  if (!jitSpec) continue;
511
- const required = (0, import_mcp2.normalizeAuthorizationDetails)(jitSpec);
512
- const missing = (0, import_mcp2.missingAuthorizationDetails)(required, caller.authorizationDetails);
543
+ const required = (0, import_mcp3.normalizeAuthorizationDetails)(jitSpec);
544
+ const missing = (0, import_mcp3.missingAuthorizationDetails)(required, caller.authorizationDetails);
513
545
  if (missing.length > 0) {
514
- const jitRefusal = refusedJitToolResult(call.id, call.name, missing);
546
+ const jitRefusal = refusedJitToolResult(call.id, call.name, missing, caller.jitTokenError);
515
547
  writeJson2(res, 403, jitRefusal.body, {
516
548
  "Insufficient-Authorization-Details": jitRefusal.headerValue,
517
549
  "WWW-Authenticate": `Bearer error="insufficient_authorization_details", error_description="JIT step-up required for tool '${call.name}'"`
@@ -521,29 +553,29 @@ function createExtAuthzServer(options) {
521
553
  }
522
554
  }
523
555
  }
524
- res.statusCode = 200;
556
+ const upstreamHeaders = {};
525
557
  if (identityHeaders) {
526
- res.setHeader("x-lumoauth-subject", caller.sub);
527
- res.setHeader("x-lumoauth-subject-type", caller.isAgent ? "agent" : "user");
528
- if (caller.agentId) res.setHeader("x-lumoauth-agent-id", caller.agentId);
529
- if (caller.actor) res.setHeader("x-lumoauth-actor", caller.actor);
530
- if (caller.clientId) res.setHeader("x-lumoauth-client-id", caller.clientId);
531
- res.setHeader("x-lumoauth-scopes", caller.scopes.join(" "));
532
- if (caller.traceId) res.setHeader("x-lumoauth-trace-id", caller.traceId);
533
- if (caller.isJit) res.setHeader("x-lumoauth-is-jit", "true");
558
+ upstreamHeaders["x-lumoauth-subject"] = caller.sub;
559
+ upstreamHeaders["x-lumoauth-subject-type"] = caller.isAgent ? "agent" : "user";
560
+ if (caller.agentId) upstreamHeaders["x-lumoauth-agent-id"] = caller.agentId;
561
+ if (caller.actor) upstreamHeaders["x-lumoauth-actor"] = caller.actor;
562
+ if (caller.clientId) upstreamHeaders["x-lumoauth-client-id"] = caller.clientId;
563
+ upstreamHeaders["x-lumoauth-scopes"] = caller.scopes.join(" ");
564
+ if (caller.traceId) upstreamHeaders["x-lumoauth-trace-id"] = caller.traceId;
565
+ if (caller.isJit) upstreamHeaders["x-lumoauth-is-jit"] = "true";
534
566
  }
535
567
  if (caller.traceparent) {
536
- res.setHeader("traceparent", caller.traceparent);
568
+ upstreamHeaders.traceparent = caller.traceparent;
537
569
  }
538
570
  if (options.vaultConnections) {
539
571
  for (const [slug, connectionId] of Object.entries(options.vaultConnections)) {
540
- const cleanSlug = slug.trim().toLowerCase().replace(/[^a-z0-9-]/g, "-");
541
- if (!cleanSlug || !connectionId) continue;
572
+ const name = vaultHeaderName(slug);
573
+ if (!name || !connectionId) continue;
542
574
  const vaultToken = await auth.vaultToken(connectionId, caller);
543
- res.setHeader(`x-lumoauth-vault-${cleanSlug}-token`, vaultToken.accessToken);
575
+ upstreamHeaders[name] = vaultToken.accessToken;
544
576
  }
545
577
  }
546
- res.end();
578
+ allow(req, res, upstreamHeaders);
547
579
  }
548
580
  return (0, import_node_http2.createServer)((req, res) => {
549
581
  handle(req, res).catch((error) => {
@@ -711,8 +743,8 @@ async function waitForUpstream(url, child, timeoutMs = 3e4) {
711
743
 
712
744
  // src/cli.ts
713
745
  var import_node_util = require("util");
714
- var import_mcp3 = require("@lumoauth/mcp");
715
- var VERSION = "1.3.1";
746
+ var import_mcp4 = require("@lumoauth/mcp");
747
+ var VERSION = "1.5.0";
716
748
  var HELP = `lumoauth: put LumoAuth in front of an MCP server
717
749
 
718
750
  Usage:
@@ -743,10 +775,16 @@ Options:
743
775
  --port <n> Port to listen on (PORT, default 8080)
744
776
  --host <address> Address to listen on (default 0.0.0.0)
745
777
  --path <path> Public path of the MCP endpoint (default: the Resource URI's path, or /mcp)
778
+ --public-url <url> Public URL of this service's root, for the DPoP check: a proof
779
+ must name this URL plus the request path (default: the
780
+ Resource URI's origin). Set it when a proxy in front
781
+ removes a path prefix, e.g. https://gw.example.com/invoices
746
782
  --scope <scope> A scope every request needs; repeat for more
747
783
  --public <path> Forward this path without a token (health checks); repeatable
748
784
  --jit <tool=type[:a]> Require a JIT/RAR grant for a tool (e.g. refund=payment:refund); repeatable
749
- --vault <slug=conn> Inject X-LumoAuth-Vault-<Slug>-Token from Token Vault; repeatable
785
+ --vault <slug=conn> Inject X-LumoAuth-Vault-<Slug>-Token from Token Vault; repeatable.
786
+ Needs an agent: AGENT_CLIENT_ID and AGENT_CLIENT_SECRET,
787
+ or LUMOAUTH_AGENT_TOKEN
750
788
  --tool-policy Require LumoAuth's per-tool policy (LUMOAUTH_MCP_CLIENT_ID and _SECRET)
751
789
  --no-tool-policy Do not ask LumoAuth about tools
752
790
  --no-identity-headers Do not send X-LumoAuth-* identity headers upstream
@@ -763,16 +801,33 @@ var LUMOAUTH_OPTIONS = {
763
801
  };
764
802
  var UsageError = class extends Error {
765
803
  };
766
- function makeAuth(values) {
767
- return (0, import_mcp3.lumoAuth)({
804
+ function makeAuth(values, publicUrl) {
805
+ return (0, import_mcp4.lumoAuth)({
768
806
  orgId: values.org,
769
807
  serverId: values.server,
770
808
  resource: values.resource,
771
809
  lumoauthUrl: values["lumoauth-url"],
772
810
  issuer: values.issuer,
773
- requiredScopes: values.scope
811
+ requiredScopes: values.scope,
812
+ requestUrl: publicUrl ? publicRequestUrl(publicUrl) : void 0
774
813
  });
775
814
  }
815
+ function publicRequestUrl(publicUrl) {
816
+ let base;
817
+ try {
818
+ base = new URL(publicUrl);
819
+ } catch {
820
+ throw new UsageError(`--public-url must be an absolute URL, got '${publicUrl}'`);
821
+ }
822
+ if (base.protocol !== "https:" && base.protocol !== "http:" || base.search || base.hash) {
823
+ throw new UsageError(`--public-url must be an http(s) URL without a query, got '${publicUrl}'`);
824
+ }
825
+ const root = `${base.origin}${base.pathname.replace(/\/+$/, "")}`;
826
+ return (request) => {
827
+ const path = /^https?:\/\//i.test(request.url) ? new URL(request.url).pathname : request.url.split("?")[0];
828
+ return `${root}${path.startsWith("/") ? path : `/${path}`}`;
829
+ };
830
+ }
776
831
  var log = (line) => console.error(line);
777
832
  function parseJitSpecs(specs) {
778
833
  if (!specs || specs.length === 0) return void 0;
@@ -823,7 +878,8 @@ async function secure(args, command, forceExtAuthz = false) {
823
878
  vault: { type: "string", multiple: true },
824
879
  "tool-policy": { type: "boolean" },
825
880
  "no-tool-policy": { type: "boolean" },
826
- "no-identity-headers": { type: "boolean" }
881
+ "no-identity-headers": { type: "boolean" },
882
+ "public-url": { type: "string" }
827
883
  }
828
884
  });
829
885
  const isExtAuthz = forceExtAuthz || Boolean(values["ext-authz"]);
@@ -841,7 +897,7 @@ async function secure(args, command, forceExtAuthz = false) {
841
897
  }
842
898
  const jit = parseJitSpecs(values.jit);
843
899
  const vaultConnections = parseVaultSpecs(values.vault);
844
- const auth = makeAuth(values);
900
+ const auth = makeAuth(values, values["public-url"]);
845
901
  const config = await auth.ready();
846
902
  let toolPolicy = auth.hasToolPolicy && !values["no-tool-policy"];
847
903
  if (values["tool-policy"]) {
@@ -938,6 +994,25 @@ async function secure(args, command, forceExtAuthz = false) {
938
994
  process.once("SIGINT", stop);
939
995
  process.once("SIGTERM", stop);
940
996
  }
997
+ async function dynamicRegistration(endpoint) {
998
+ if (typeof endpoint !== "string") return "no";
999
+ let status;
1000
+ try {
1001
+ const response = await fetch(endpoint, {
1002
+ method: "POST",
1003
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
1004
+ body: "{}"
1005
+ });
1006
+ status = response.status;
1007
+ await response.body?.cancel();
1008
+ } catch (error) {
1009
+ return `unknown (${endpoint}: ${error.message})`;
1010
+ }
1011
+ if (status === 400) return "yes";
1012
+ if (status === 401) return "no: registration needs an initial access token, so MCP clients cannot register by themselves";
1013
+ if (status === 403) return "no: not enabled for this organization (clients need a client metadata document or a registered client ID)";
1014
+ return `unknown (HTTP ${status} from ${endpoint})`;
1015
+ }
941
1016
  async function check(args) {
942
1017
  const { values } = (0, import_node_util.parseArgs)({ args, strict: true, options: LUMOAUTH_OPTIONS });
943
1018
  const auth = makeAuth(values);
@@ -966,7 +1041,7 @@ async function check(args) {
966
1041
  out(` issuer matches ${metadata.issuer === config.issuer ? "yes" : `NO (${String(metadata.issuer)})`}`);
967
1042
  out(` PKCE S256 ${pkce ? "yes" : "NO: MCP clients refuse authorization servers without it"}`);
968
1043
  out(` client metadata docs ${metadata.client_id_metadata_document_supported === true ? "yes" : "no"}`);
969
- out(` dynamic registration ${typeof metadata.registration_endpoint === "string" ? "yes" : "no"}`);
1044
+ out(` dynamic registration ${await dynamicRegistration(metadata.registration_endpoint)}`);
970
1045
  } catch (error) {
971
1046
  out(`Authorization server: cannot read ${discoveryUrl}: ${error.message}`);
972
1047
  process.exitCode = 1;
@@ -1018,6 +1093,7 @@ async function main(argv) {
1018
1093
  filterSseEvent,
1019
1094
  inspect,
1020
1095
  main,
1096
+ publicRequestUrl,
1021
1097
  refusedJitToolResult,
1022
1098
  refusedToolResult,
1023
1099
  startUpstream,