lumoauth 1.4.0 → 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.mjs CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  } from "@lumoauth/mcp";
12
12
 
13
13
  // src/jsonrpc.ts
14
+ import { InsufficientAuthorizationDetailsError } from "@lumoauth/mcp";
14
15
  function asId(value) {
15
16
  return typeof value === "string" || typeof value === "number" ? value : null;
16
17
  }
@@ -42,23 +43,20 @@ function inspect(body) {
42
43
  function refusedToolResult(id, message) {
43
44
  return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: message }], isError: true } };
44
45
  }
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}`;
46
+ function refusedJitToolResult(id, tool, requiredDetails, jitTokenError) {
47
+ const refusal = new InsufficientAuthorizationDetailsError(tool, requiredDetails, void 0, jitTokenError);
50
48
  return {
51
- headerValue,
49
+ headerValue: refusal.headerValue,
52
50
  body: {
53
51
  jsonrpc: "2.0",
54
52
  id,
55
53
  result: {
56
- content: [{ type: "text", text: message }],
54
+ content: [{ type: "text", text: refusal.message }],
57
55
  isError: true,
58
56
  _meta: {
59
57
  error: "insufficient_authorization_details",
60
- authorization_details_hint: requiredDetails,
61
- "Insufficient-Authorization-Details": headerValue
58
+ authorization_details_hint: refusal.hint,
59
+ "Insufficient-Authorization-Details": refusal.headerValue
62
60
  }
63
61
  }
64
62
  }
@@ -351,12 +349,14 @@ function createSecureProxy(options) {
351
349
  const required = normalizeAuthorizationDetails(jitSpec);
352
350
  const missing = missingAuthorizationDetails(required, caller.authorizationDetails);
353
351
  if (missing.length > 0) {
354
- const jitRefusal = refusedJitToolResult(call.id, call.name, missing);
352
+ const jitRefusal = refusedJitToolResult(call.id, call.name, missing, caller.jitTokenError);
355
353
  res.setHeader("Insufficient-Authorization-Details", jitRefusal.headerValue);
356
354
  writeJson(
357
355
  res,
358
356
  200,
359
- inspection.isBatch ? inspection.toolCalls.map((c) => refusedJitToolResult(c.id, call.name, missing).body) : jitRefusal.body
357
+ inspection.isBatch ? inspection.toolCalls.map(
358
+ (c) => refusedJitToolResult(c.id, call.name, missing, caller.jitTokenError).body
359
+ ) : jitRefusal.body
360
360
  );
361
361
  return;
362
362
  }
@@ -400,10 +400,19 @@ import {
400
400
  parseTraceparent as parseTraceparent2,
401
401
  writeChallenge as writeChallenge2
402
402
  } from "@lumoauth/mcp";
403
- function headerOf2(req, name) {
404
- const value = req.headers[name];
405
- return Array.isArray(value) ? value[0] : value;
406
- }
403
+ var IDENTITY_HEADERS = [
404
+ "x-lumoauth-subject",
405
+ "x-lumoauth-subject-type",
406
+ "x-lumoauth-agent-id",
407
+ "x-lumoauth-actor",
408
+ "x-lumoauth-client-id",
409
+ "x-lumoauth-scopes",
410
+ "x-lumoauth-trace-id",
411
+ "x-lumoauth-is-jit"
412
+ ];
413
+ var IDENTITY_PREFIX2 = "x-lumoauth-";
414
+ var JIT_TOKEN_HEADER = "x-lumoauth-jit-token";
415
+ var ENVOY_HEADERS_TO_REMOVE = "x-envoy-auth-headers-to-remove";
407
416
  async function readBody2(req, limit) {
408
417
  const chunks = [];
409
418
  let size = 0;
@@ -422,23 +431,45 @@ function writeJson2(res, status, body, headers = {}) {
422
431
  res.setHeader("Content-Length", Buffer.byteLength(text));
423
432
  res.end(text);
424
433
  }
434
+ function vaultHeaderName(slug) {
435
+ const cleanSlug = slug.trim().toLowerCase().replace(/[^a-z0-9-]/g, "-");
436
+ return cleanSlug ? `x-lumoauth-vault-${cleanSlug}-token` : void 0;
437
+ }
425
438
  function createExtAuthzServer(options) {
426
439
  const { auth } = options;
427
440
  const log2 = options.log ?? ((line) => console.error(line));
428
441
  const identityHeaders = options.identityHeaders ?? true;
429
442
  const publicPaths = options.publicPaths ?? ["/healthz", "/readyz"];
430
443
  const maxBody = options.maxBodyBytes ?? 1024 * 1024;
444
+ const vaultHeaders = Object.keys(options.vaultConnections ?? {}).map(vaultHeaderName).filter((name) => Boolean(name));
445
+ function allow(req, res, headers, body) {
446
+ const remove = /* @__PURE__ */ new Set([...IDENTITY_HEADERS, JIT_TOKEN_HEADER, ...vaultHeaders]);
447
+ for (const name of Object.keys(req.headers)) {
448
+ const lower = name.toLowerCase();
449
+ if (lower.startsWith(IDENTITY_PREFIX2)) remove.add(lower);
450
+ }
451
+ res.statusCode = 200;
452
+ for (const [name, value] of Object.entries(headers)) {
453
+ res.setHeader(name, value);
454
+ remove.delete(name.toLowerCase());
455
+ }
456
+ res.setHeader(ENVOY_HEADERS_TO_REMOVE, [...remove].join(","));
457
+ res.end(body);
458
+ }
431
459
  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 ?? "/";
460
+ const method = req.method ?? "GET";
461
+ const rawPath = req.url ?? "/";
434
462
  const url = new URL(rawPath, "http://ext-authz.invalid");
435
463
  if (publicPaths.includes(url.pathname)) {
436
- res.statusCode = 200;
437
- res.end();
464
+ allow(req, res, {});
438
465
  return;
439
466
  }
440
467
  const discovery = await auth.discoveryResponse(method, url.pathname);
441
468
  if (discovery) {
469
+ if (discovery.status === 200) {
470
+ allow(req, res, discovery.headers, discovery.body);
471
+ return;
472
+ }
442
473
  res.statusCode = discovery.status;
443
474
  for (const [k, v] of Object.entries(discovery.headers)) res.setHeader(k, v);
444
475
  res.end(discovery.body);
@@ -486,7 +517,7 @@ function createExtAuthzServer(options) {
486
517
  const required = normalizeAuthorizationDetails2(jitSpec);
487
518
  const missing = missingAuthorizationDetails2(required, caller.authorizationDetails);
488
519
  if (missing.length > 0) {
489
- const jitRefusal = refusedJitToolResult(call.id, call.name, missing);
520
+ const jitRefusal = refusedJitToolResult(call.id, call.name, missing, caller.jitTokenError);
490
521
  writeJson2(res, 403, jitRefusal.body, {
491
522
  "Insufficient-Authorization-Details": jitRefusal.headerValue,
492
523
  "WWW-Authenticate": `Bearer error="insufficient_authorization_details", error_description="JIT step-up required for tool '${call.name}'"`
@@ -496,29 +527,29 @@ function createExtAuthzServer(options) {
496
527
  }
497
528
  }
498
529
  }
499
- res.statusCode = 200;
530
+ const upstreamHeaders = {};
500
531
  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");
532
+ upstreamHeaders["x-lumoauth-subject"] = caller.sub;
533
+ upstreamHeaders["x-lumoauth-subject-type"] = caller.isAgent ? "agent" : "user";
534
+ if (caller.agentId) upstreamHeaders["x-lumoauth-agent-id"] = caller.agentId;
535
+ if (caller.actor) upstreamHeaders["x-lumoauth-actor"] = caller.actor;
536
+ if (caller.clientId) upstreamHeaders["x-lumoauth-client-id"] = caller.clientId;
537
+ upstreamHeaders["x-lumoauth-scopes"] = caller.scopes.join(" ");
538
+ if (caller.traceId) upstreamHeaders["x-lumoauth-trace-id"] = caller.traceId;
539
+ if (caller.isJit) upstreamHeaders["x-lumoauth-is-jit"] = "true";
509
540
  }
510
541
  if (caller.traceparent) {
511
- res.setHeader("traceparent", caller.traceparent);
542
+ upstreamHeaders.traceparent = caller.traceparent;
512
543
  }
513
544
  if (options.vaultConnections) {
514
545
  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;
546
+ const name = vaultHeaderName(slug);
547
+ if (!name || !connectionId) continue;
517
548
  const vaultToken = await auth.vaultToken(connectionId, caller);
518
- res.setHeader(`x-lumoauth-vault-${cleanSlug}-token`, vaultToken.accessToken);
549
+ upstreamHeaders[name] = vaultToken.accessToken;
519
550
  }
520
551
  }
521
- res.end();
552
+ allow(req, res, upstreamHeaders);
522
553
  }
523
554
  return createServer2((req, res) => {
524
555
  handle(req, res).catch((error) => {
@@ -691,7 +722,7 @@ async function waitForUpstream(url, child, timeoutMs = 3e4) {
691
722
  // src/cli.ts
692
723
  import { parseArgs } from "util";
693
724
  import { lumoAuth } from "@lumoauth/mcp";
694
- var VERSION = "1.4.0";
725
+ var VERSION = "1.5.0";
695
726
  var HELP = `lumoauth: put LumoAuth in front of an MCP server
696
727
 
697
728
  Usage:
@@ -722,10 +753,16 @@ Options:
722
753
  --port <n> Port to listen on (PORT, default 8080)
723
754
  --host <address> Address to listen on (default 0.0.0.0)
724
755
  --path <path> Public path of the MCP endpoint (default: the Resource URI's path, or /mcp)
756
+ --public-url <url> Public URL of this service's root, for the DPoP check: a proof
757
+ must name this URL plus the request path (default: the
758
+ Resource URI's origin). Set it when a proxy in front
759
+ removes a path prefix, e.g. https://gw.example.com/invoices
725
760
  --scope <scope> A scope every request needs; repeat for more
726
761
  --public <path> Forward this path without a token (health checks); repeatable
727
762
  --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
763
+ --vault <slug=conn> Inject X-LumoAuth-Vault-<Slug>-Token from Token Vault; repeatable.
764
+ Needs an agent: AGENT_CLIENT_ID and AGENT_CLIENT_SECRET,
765
+ or LUMOAUTH_AGENT_TOKEN
729
766
  --tool-policy Require LumoAuth's per-tool policy (LUMOAUTH_MCP_CLIENT_ID and _SECRET)
730
767
  --no-tool-policy Do not ask LumoAuth about tools
731
768
  --no-identity-headers Do not send X-LumoAuth-* identity headers upstream
@@ -742,16 +779,33 @@ var LUMOAUTH_OPTIONS = {
742
779
  };
743
780
  var UsageError = class extends Error {
744
781
  };
745
- function makeAuth(values) {
782
+ function makeAuth(values, publicUrl) {
746
783
  return lumoAuth({
747
784
  orgId: values.org,
748
785
  serverId: values.server,
749
786
  resource: values.resource,
750
787
  lumoauthUrl: values["lumoauth-url"],
751
788
  issuer: values.issuer,
752
- requiredScopes: values.scope
789
+ requiredScopes: values.scope,
790
+ requestUrl: publicUrl ? publicRequestUrl(publicUrl) : void 0
753
791
  });
754
792
  }
793
+ function publicRequestUrl(publicUrl) {
794
+ let base;
795
+ try {
796
+ base = new URL(publicUrl);
797
+ } catch {
798
+ throw new UsageError(`--public-url must be an absolute URL, got '${publicUrl}'`);
799
+ }
800
+ if (base.protocol !== "https:" && base.protocol !== "http:" || base.search || base.hash) {
801
+ throw new UsageError(`--public-url must be an http(s) URL without a query, got '${publicUrl}'`);
802
+ }
803
+ const root = `${base.origin}${base.pathname.replace(/\/+$/, "")}`;
804
+ return (request) => {
805
+ const path = /^https?:\/\//i.test(request.url) ? new URL(request.url).pathname : request.url.split("?")[0];
806
+ return `${root}${path.startsWith("/") ? path : `/${path}`}`;
807
+ };
808
+ }
755
809
  var log = (line) => console.error(line);
756
810
  function parseJitSpecs(specs) {
757
811
  if (!specs || specs.length === 0) return void 0;
@@ -802,7 +856,8 @@ async function secure(args, command, forceExtAuthz = false) {
802
856
  vault: { type: "string", multiple: true },
803
857
  "tool-policy": { type: "boolean" },
804
858
  "no-tool-policy": { type: "boolean" },
805
- "no-identity-headers": { type: "boolean" }
859
+ "no-identity-headers": { type: "boolean" },
860
+ "public-url": { type: "string" }
806
861
  }
807
862
  });
808
863
  const isExtAuthz = forceExtAuthz || Boolean(values["ext-authz"]);
@@ -820,7 +875,7 @@ async function secure(args, command, forceExtAuthz = false) {
820
875
  }
821
876
  const jit = parseJitSpecs(values.jit);
822
877
  const vaultConnections = parseVaultSpecs(values.vault);
823
- const auth = makeAuth(values);
878
+ const auth = makeAuth(values, values["public-url"]);
824
879
  const config = await auth.ready();
825
880
  let toolPolicy = auth.hasToolPolicy && !values["no-tool-policy"];
826
881
  if (values["tool-policy"]) {
@@ -917,6 +972,25 @@ async function secure(args, command, forceExtAuthz = false) {
917
972
  process.once("SIGINT", stop);
918
973
  process.once("SIGTERM", stop);
919
974
  }
975
+ async function dynamicRegistration(endpoint) {
976
+ if (typeof endpoint !== "string") return "no";
977
+ let status;
978
+ try {
979
+ const response = await fetch(endpoint, {
980
+ method: "POST",
981
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
982
+ body: "{}"
983
+ });
984
+ status = response.status;
985
+ await response.body?.cancel();
986
+ } catch (error) {
987
+ return `unknown (${endpoint}: ${error.message})`;
988
+ }
989
+ if (status === 400) return "yes";
990
+ if (status === 401) return "no: registration needs an initial access token, so MCP clients cannot register by themselves";
991
+ if (status === 403) return "no: not enabled for this organization (clients need a client metadata document or a registered client ID)";
992
+ return `unknown (HTTP ${status} from ${endpoint})`;
993
+ }
920
994
  async function check(args) {
921
995
  const { values } = parseArgs({ args, strict: true, options: LUMOAUTH_OPTIONS });
922
996
  const auth = makeAuth(values);
@@ -945,7 +1019,7 @@ async function check(args) {
945
1019
  out(` issuer matches ${metadata.issuer === config.issuer ? "yes" : `NO (${String(metadata.issuer)})`}`);
946
1020
  out(` PKCE S256 ${pkce ? "yes" : "NO: MCP clients refuse authorization servers without it"}`);
947
1021
  out(` client metadata docs ${metadata.client_id_metadata_document_supported === true ? "yes" : "no"}`);
948
- out(` dynamic registration ${typeof metadata.registration_endpoint === "string" ? "yes" : "no"}`);
1022
+ out(` dynamic registration ${await dynamicRegistration(metadata.registration_endpoint)}`);
949
1023
  } catch (error) {
950
1024
  out(`Authorization server: cannot read ${discoveryUrl}: ${error.message}`);
951
1025
  process.exitCode = 1;
@@ -996,6 +1070,7 @@ export {
996
1070
  filterSseEvent,
997
1071
  inspect,
998
1072
  main,
1073
+ publicRequestUrl,
999
1074
  refusedJitToolResult,
1000
1075
  refusedToolResult,
1001
1076
  startUpstream,