@codemem/mcp 0.39.1 → 0.40.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/http.js CHANGED
@@ -1,23 +1,23 @@
1
1
  #!/usr/bin/env node
2
- import { t as e } from "./server-pfLtHrsT.js";
3
- import { createServer as t } from "node:http";
4
- import { isIP as n, isIPv6 as r } from "node:net";
5
- import { pathToFileURL as i } from "node:url";
6
- import { MemoryStore as a, resolveDbPath as o } from "@codemem/core";
7
- import { requireBearerAuth as s } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
8
- import { createOAuthMetadata as c, getOAuthProtectedResourceMetadataUrl as l, mcpAuthRouter as u } from "@modelcontextprotocol/sdk/server/auth/router.js";
9
- import { StreamableHTTPServerTransport as d } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
10
- import f from "express";
11
- import { Buffer as p } from "node:buffer";
12
- import { createHash as m, createHmac as h, createPublicKey as g, randomBytes as _, randomUUID as v, timingSafeEqual as y, verify as b } from "node:crypto";
13
- import { existsSync as x, mkdirSync as S, readFileSync as C, renameSync as ee, writeFileSync as w } from "node:fs";
14
- import { chmod as T } from "node:fs/promises";
15
- import { homedir as E } from "node:os";
16
- import { dirname as D, join as te } from "node:path";
17
- import { AccessDeniedError as ne, InvalidClientError as re, InvalidClientMetadataError as O, InvalidGrantError as k, InvalidRequestError as ie, InvalidTokenError as ae, ServerError as oe, TemporarilyUnavailableError as A, UnsupportedResponseTypeError as se } from "@modelcontextprotocol/sdk/server/auth/errors.js";
18
- import { OAuthProtectedResourceMetadataSchema as ce, OAuthTokensSchema as le } from "@modelcontextprotocol/sdk/shared/auth.js";
2
+ import { n as e, t } from "./server-BshtPXit.js";
3
+ import { createHash as n, createHmac as r, createPublicKey as i, randomBytes as a, randomUUID as o, timingSafeEqual as s, verify as c } from "node:crypto";
4
+ import { createServer as l } from "node:http";
5
+ import { isIP as u, isIPv6 as d } from "node:net";
6
+ import { pathToFileURL as f } from "node:url";
7
+ import { MemoryStore as p, resolveDbPath as m } from "@codemem/core";
8
+ import { requireBearerAuth as h } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
9
+ import { createOAuthMetadata as g, getOAuthProtectedResourceMetadataUrl as ee, mcpAuthRouter as te } from "@modelcontextprotocol/sdk/server/auth/router.js";
10
+ import { StreamableHTTPServerTransport as ne } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
11
+ import re from "express";
12
+ import { Buffer as _ } from "node:buffer";
13
+ import { existsSync as v, mkdirSync as y, readFileSync as ie, renameSync as b, writeFileSync as x } from "node:fs";
14
+ import { chmod as S } from "node:fs/promises";
15
+ import { homedir as C } from "node:os";
16
+ import { dirname as w, join as T } from "node:path";
17
+ import { AccessDeniedError as E, InvalidClientError as ae, InvalidClientMetadataError as D, InvalidGrantError as O, InvalidRequestError as oe, InvalidTokenError as se, ServerError as ce, TemporarilyUnavailableError as k, UnsupportedResponseTypeError as le } from "@modelcontextprotocol/sdk/server/auth/errors.js";
18
+ import { OAuthProtectedResourceMetadataSchema as ue, OAuthTokensSchema as de } from "@modelcontextprotocol/sdk/shared/auth.js";
19
19
  //#region \0rolldown/runtime.js
20
- var j = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), M = /* @__PURE__ */ j(((e) => {
20
+ var A = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), j = /* @__PURE__ */ A(((e) => {
21
21
  Object.defineProperty(e, "__esModule", { value: !0 }), e.isInSubnet = t, e.isCorrect = n, e.numberToPaddedHex = r, e.stringToPaddedHex = i, e.testBit = a;
22
22
  function t(e) {
23
23
  return this.subnetMask < e.subnetMask ? !1 : this.mask(e.subnetMask) === e.mask();
@@ -39,15 +39,15 @@ var j = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t
39
39
  let r = n - t;
40
40
  return e.substring(r, r + 1) === "1";
41
41
  }
42
- })), ue = /* @__PURE__ */ j(((e) => {
42
+ })), fe = /* @__PURE__ */ A(((e) => {
43
43
  Object.defineProperty(e, "__esModule", { value: !0 }), e.RE_SUBNET_STRING = e.RE_ADDRESS = e.GROUPS = e.BITS = void 0, e.BITS = 32, e.GROUPS = 4, e.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g, e.RE_SUBNET_STRING = /\/\d{1,2}$/;
44
- })), N = /* @__PURE__ */ j(((e) => {
44
+ })), pe = /* @__PURE__ */ A(((e) => {
45
45
  Object.defineProperty(e, "__esModule", { value: !0 }), e.AddressError = void 0, e.AddressError = class extends Error {
46
46
  constructor(e, t) {
47
47
  super(e), this.name = "AddressError", this.parseMessage = t;
48
48
  }
49
49
  };
50
- })), de = /* @__PURE__ */ j(((e) => {
50
+ })), me = /* @__PURE__ */ A(((e) => {
51
51
  var t = e && e.__createBinding || (Object.create ? (function(e, t, n, r) {
52
52
  r === void 0 && (r = n);
53
53
  var i = Object.getOwnPropertyDescriptor(t, n);
@@ -73,7 +73,7 @@ var j = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t
73
73
  return n(r, e), r;
74
74
  };
75
75
  Object.defineProperty(e, "__esModule", { value: !0 }), e.Address4 = void 0;
76
- var i = r(M()), a = r(ue()), o = N();
76
+ var i = r(j()), a = r(fe()), o = pe();
77
77
  e.Address4 = class e {
78
78
  constructor(e) {
79
79
  this.groups = a.GROUPS, this.parsedAddress = [], this.parsedSubnet = "", this.subnet = "/32", this.subnetMask = 32, this.v4 = !0, this.isCorrect = i.isCorrect(a.BITS), this.isInSubnet = i.isInSubnet, this.address = e;
@@ -181,7 +181,7 @@ var j = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t
181
181
  return this.address.replace(a.RE_ADDRESS, `<span class="hover-group group-v4 group-6">${e.slice(0, 2).join(".")}</span>.<span class="hover-group group-v4 group-7">${e.slice(2, 4).join(".")}</span>`);
182
182
  }
183
183
  };
184
- })), fe = /* @__PURE__ */ j(((e) => {
184
+ })), he = /* @__PURE__ */ A(((e) => {
185
185
  Object.defineProperty(e, "__esModule", { value: !0 }), e.RE_URL_WITH_PORT = e.RE_URL = e.RE_ZONE_STRING = e.RE_SUBNET_STRING = e.RE_BAD_ADDRESS = e.RE_BAD_CHARACTERS = e.TYPES = e.SCOPES = e.GROUPS = e.BITS = void 0, e.BITS = 128, e.GROUPS = 8, e.SCOPES = {
186
186
  0: "Reserved",
187
187
  1: "Interface local",
@@ -215,7 +215,7 @@ var j = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t
215
215
  "ff00::/8": "Multicast",
216
216
  "fe80::/10": "Link-local unicast"
217
217
  }, e.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi, e.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi, e.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/, e.RE_ZONE_STRING = /%.*$/, e.RE_URL = /^\[{0,1}([0-9a-f:]+)\]{0,1}/, e.RE_URL_WITH_PORT = /\[([0-9a-f:]+)\]:([0-9]{1,5})/;
218
- })), pe = /* @__PURE__ */ j(((e) => {
218
+ })), ge = /* @__PURE__ */ A(((e) => {
219
219
  Object.defineProperty(e, "__esModule", { value: !0 }), e.escapeHtml = t, e.spanAllZeroes = n, e.spanAll = r, e.spanLeadingZeroes = a, e.simpleGroup = o;
220
220
  function t(e) {
221
221
  return e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
@@ -235,7 +235,7 @@ var j = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t
235
235
  function o(e, t = 0) {
236
236
  return e.split(":").map((e, n) => /group-v4/.test(e) ? e : `<span class="hover-group group-${n + t}">${i(e)}</span>`);
237
237
  }
238
- })), me = /* @__PURE__ */ j(((e) => {
238
+ })), _e = /* @__PURE__ */ A(((e) => {
239
239
  var t = e && e.__createBinding || (Object.create ? (function(e, t, n, r) {
240
240
  r === void 0 && (r = n);
241
241
  var i = Object.getOwnPropertyDescriptor(t, n);
@@ -261,7 +261,7 @@ var j = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t
261
261
  return n(r, e), r;
262
262
  };
263
263
  Object.defineProperty(e, "__esModule", { value: !0 }), e.ADDRESS_BOUNDARY = void 0, e.groupPossibilities = a, e.padGroup = o, e.simpleRegularExpression = s, e.possibleElisions = c;
264
- var i = r(fe());
264
+ var i = r(he());
265
265
  function a(e) {
266
266
  return `(${e.join("|")})`;
267
267
  }
@@ -289,7 +289,7 @@ var j = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t
289
289
  for (let t = 1; t < e - 1; t++) for (let n = 1; n < e - t; n++) o.push(`(0{1,4}:){${n}}:(0{1,4}:){${e - n - t - 1}}0{1,4}`);
290
290
  return a(o);
291
291
  }
292
- })), he = /* @__PURE__ */ j(((e) => {
292
+ })), ve = /* @__PURE__ */ A(((e) => {
293
293
  var t = e && e.__createBinding || (Object.create ? (function(e, t, n, r) {
294
294
  r === void 0 && (r = n);
295
295
  var i = Object.getOwnPropertyDescriptor(t, n);
@@ -315,7 +315,7 @@ var j = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t
315
315
  return n(r, e), r;
316
316
  };
317
317
  Object.defineProperty(e, "__esModule", { value: !0 }), e.Address6 = void 0;
318
- var i = r(M()), a = r(ue()), o = r(fe()), s = r(pe()), c = de(), l = me(), u = N(), d = M();
318
+ var i = r(j()), a = r(fe()), o = r(he()), s = r(ge()), c = me(), l = _e(), u = pe(), d = j();
319
319
  function f(e) {
320
320
  if (!e) throw Error("Assertion failed.");
321
321
  }
@@ -335,7 +335,7 @@ var j = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t
335
335
  function g(e) {
336
336
  return parseInt(e, 16).toString(16).padStart(4, "0");
337
337
  }
338
- function _(e) {
338
+ function ee(e) {
339
339
  return e & 255;
340
340
  }
341
341
  e.Address6 = class e {
@@ -561,10 +561,10 @@ var j = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t
561
561
  return n;
562
562
  }
563
563
  toUnsignedByteArray() {
564
- return this.toByteArray().map(_);
564
+ return this.toByteArray().map(ee);
565
565
  }
566
566
  static fromByteArray(e) {
567
- return this.fromUnsignedByteArray(e.map(_));
567
+ return this.fromUnsignedByteArray(e.map(ee));
568
568
  }
569
569
  static fromUnsignedByteArray(t) {
570
570
  let n = BigInt("256"), r = BigInt("0"), i = BigInt("1");
@@ -633,7 +633,7 @@ var j = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t
633
633
  return new RegExp(this.regularExpressionString(e), "i");
634
634
  }
635
635
  };
636
- })), ge = (/* @__PURE__ */ j(((e) => {
636
+ })), ye = (/* @__PURE__ */ A(((e) => {
637
637
  var t = e && e.__createBinding || (Object.create ? (function(e, t, n, r) {
638
638
  r === void 0 && (r = n);
639
639
  var i = Object.getOwnPropertyDescriptor(t, n);
@@ -659,37 +659,37 @@ var j = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t
659
659
  return n(r, e), r;
660
660
  };
661
661
  Object.defineProperty(e, "__esModule", { value: !0 }), e.v6 = e.AddressError = e.Address6 = e.Address4 = void 0;
662
- var i = de();
662
+ var i = me();
663
663
  Object.defineProperty(e, "Address4", {
664
664
  enumerable: !0,
665
665
  get: function() {
666
666
  return i.Address4;
667
667
  }
668
668
  });
669
- var a = he();
669
+ var a = ve();
670
670
  Object.defineProperty(e, "Address6", {
671
671
  enumerable: !0,
672
672
  get: function() {
673
673
  return a.Address6;
674
674
  }
675
675
  });
676
- var o = N();
676
+ var o = pe();
677
677
  Object.defineProperty(e, "AddressError", {
678
678
  enumerable: !0,
679
679
  get: function() {
680
680
  return o.AddressError;
681
681
  }
682
- }), e.v6 = { helpers: r(pe()) };
682
+ }), e.v6 = { helpers: r(ge()) };
683
683
  })))();
684
- function _e(e, t = 56) {
685
- if (r(e)) {
686
- let n = new ge.Address6(e);
684
+ function be(e, t = 56) {
685
+ if (d(e)) {
686
+ let n = new ye.Address6(e);
687
687
  if (n.is4()) return n.to4().correctForm();
688
- if (t) return new ge.Address6(`${e}/${t}`).networkForm();
688
+ if (t) return new ye.Address6(`${e}/${t}`).networkForm();
689
689
  }
690
690
  return e;
691
691
  }
692
- var ve = class {
692
+ var xe = class {
693
693
  constructor(e) {
694
694
  this.validations = e, this.previous = /* @__PURE__ */ new Map(), this.current = /* @__PURE__ */ new Map(), this.localKeys = !0;
695
695
  }
@@ -732,110 +732,110 @@ var ve = class {
732
732
  clearExpired() {
733
733
  this.previous = this.current, this.current = /* @__PURE__ */ new Map();
734
734
  }
735
- }, ye = {
735
+ }, Se = {
736
736
  warn(...e) {
737
737
  console.warn(...e.reverse());
738
738
  },
739
739
  error(...e) {
740
740
  console.error(...e.reverse());
741
741
  }
742
- }, be = [
742
+ }, Ce = [
743
743
  "draft-6",
744
744
  "draft-7",
745
745
  "draft-8"
746
- ], P = (e, t) => {
746
+ ], M = (e, t) => {
747
747
  let n;
748
748
  if (t) {
749
749
  let e = Math.ceil((t.getTime() - Date.now()) / 1e3);
750
750
  n = Math.max(0, e);
751
751
  } else n = Math.ceil(e / 1e3);
752
752
  return n;
753
- }, xe = (e) => {
754
- let t = m("sha256");
753
+ }, we = (e) => {
754
+ let t = n("sha256");
755
755
  t.update(e);
756
- let n = t.digest("hex").slice(0, 12);
757
- return p.from(n).toString("base64");
758
- }, Se = (e, t) => {
756
+ let r = t.digest("hex").slice(0, 12);
757
+ return _.from(r).toString("base64");
758
+ }, Te = (e, t) => {
759
759
  e.headersSent || (e.setHeader("X-RateLimit-Limit", t.limit.toString()), e.setHeader("X-RateLimit-Remaining", t.remaining.toString()), t.resetTime instanceof Date && (e.setHeader("Date", (/* @__PURE__ */ new Date()).toUTCString()), e.setHeader("X-RateLimit-Reset", Math.ceil(t.resetTime.getTime() / 1e3).toString())));
760
- }, Ce = (e, t, n) => {
760
+ }, Ee = (e, t, n) => {
761
761
  if (e.headersSent) return;
762
- let r = Math.ceil(n / 1e3), i = P(n, t.resetTime);
762
+ let r = Math.ceil(n / 1e3), i = M(n, t.resetTime);
763
763
  e.setHeader("RateLimit-Policy", `${t.limit};w=${r}`), e.setHeader("RateLimit-Limit", t.limit.toString()), e.setHeader("RateLimit-Remaining", t.remaining.toString()), typeof i == "number" && e.setHeader("RateLimit-Reset", i.toString());
764
- }, we = (e, t, n) => {
764
+ }, De = (e, t, n) => {
765
765
  if (e.headersSent) return;
766
- let r = Math.ceil(n / 1e3), i = P(n, t.resetTime);
766
+ let r = Math.ceil(n / 1e3), i = M(n, t.resetTime);
767
767
  e.setHeader("RateLimit-Policy", `${t.limit};w=${r}`), e.setHeader("RateLimit", `limit=${t.limit}, remaining=${t.remaining}, reset=${i}`);
768
- }, Te = (e, t, n, r, i) => {
768
+ }, Oe = (e, t, n, r, i) => {
769
769
  if (e.headersSent) return;
770
- let a = Math.ceil(n / 1e3), o = P(n, t.resetTime), s = xe(i), c = `r=${t.remaining}; t=${o}`, l = `q=${t.limit}; w=${a}; pk=:${s}:`;
770
+ let a = Math.ceil(n / 1e3), o = M(n, t.resetTime), s = we(i), c = `r=${t.remaining}; t=${o}`, l = `q=${t.limit}; w=${a}; pk=:${s}:`;
771
771
  e.append("RateLimit", `"${r}"; ${c}`), e.append("RateLimit-Policy", `"${r}"; ${l}`);
772
- }, Ee = (e, t, n) => {
772
+ }, ke = (e, t, n) => {
773
773
  if (e.headersSent) return;
774
- let r = P(n, t.resetTime);
774
+ let r = M(n, t.resetTime);
775
775
  e.setHeader("Retry-After", r.toString());
776
- }, De = (e) => {
776
+ }, Ae = (e) => {
777
777
  let t = {};
778
778
  for (let n of Object.keys(e)) {
779
779
  let r = n;
780
780
  e[r] !== void 0 && (t[r] = e[r]);
781
781
  }
782
782
  return t;
783
- }, F = class extends Error {
783
+ }, N = class extends Error {
784
784
  constructor(e, t) {
785
785
  let n = `https://express-rate-limit.github.io/${e}/`;
786
786
  super(`${t} See ${n} for more information.`), this.name = this.constructor.name, this.code = e, this.help = n;
787
787
  }
788
- }, I = class extends F {}, Oe = /* @__PURE__ */ new Set(), ke = /* @__PURE__ */ new WeakMap(), Ae = {
788
+ }, P = class extends N {}, je = /* @__PURE__ */ new Set(), Me = /* @__PURE__ */ new WeakMap(), Ne = {
789
789
  enabled: { default: !0 },
790
790
  disable() {
791
791
  for (let e of Object.keys(this.enabled)) this.enabled[e] = !1;
792
792
  },
793
793
  ip(e) {
794
- if (e === void 0) throw new F("ERR_ERL_UNDEFINED_IP_ADDRESS", "An undefined 'request.ip' was detected. This might indicate a misconfiguration or the connection being destroyed prematurely.");
795
- if (!n(e)) throw new F("ERR_ERL_INVALID_IP_ADDRESS", `An invalid 'request.ip' (${e}) was detected. Consider passing a custom 'keyGenerator' function to the rate limiter.`);
794
+ if (e === void 0) throw new N("ERR_ERL_UNDEFINED_IP_ADDRESS", "An undefined 'request.ip' was detected. This might indicate a misconfiguration or the connection being destroyed prematurely.");
795
+ if (!u(e)) throw new N("ERR_ERL_INVALID_IP_ADDRESS", `An invalid 'request.ip' (${e}) was detected. Consider passing a custom 'keyGenerator' function to the rate limiter.`);
796
796
  },
797
797
  trustProxy(e) {
798
- if (e.app.get("trust proxy") === !0) throw new F("ERR_ERL_PERMISSIVE_TRUST_PROXY", "The Express 'trust proxy' setting is true, which allows anyone to trivially bypass IP-based rate limiting.");
798
+ if (e.app.get("trust proxy") === !0) throw new N("ERR_ERL_PERMISSIVE_TRUST_PROXY", "The Express 'trust proxy' setting is true, which allows anyone to trivially bypass IP-based rate limiting.");
799
799
  },
800
800
  xForwardedForHeader(e) {
801
- if (e.headers["x-forwarded-for"] && e.app.get("trust proxy") === !1) throw new F("ERR_ERL_UNEXPECTED_X_FORWARDED_FOR", "The 'X-Forwarded-For' header is set but the Express 'trust proxy' setting is false (default). This could indicate a misconfiguration which would prevent express-rate-limit from accurately identifying users.");
801
+ if (e.headers["x-forwarded-for"] && e.app.get("trust proxy") === !1) throw new N("ERR_ERL_UNEXPECTED_X_FORWARDED_FOR", "The 'X-Forwarded-For' header is set but the Express 'trust proxy' setting is false (default). This could indicate a misconfiguration which would prevent express-rate-limit from accurately identifying users.");
802
802
  },
803
803
  forwardedHeader(e) {
804
- if (e.headers.forwarded && e.ip === e.socket?.remoteAddress) throw new F("ERR_ERL_FORWARDED_HEADER", "The 'Forwarded' header (standardized X-Forwarded-For) is set but currently being ignored. Add a custom keyGenerator to use a value from this header.");
804
+ if (e.headers.forwarded && e.ip === e.socket?.remoteAddress) throw new N("ERR_ERL_FORWARDED_HEADER", "The 'Forwarded' header (standardized X-Forwarded-For) is set but currently being ignored. Add a custom keyGenerator to use a value from this header.");
805
805
  },
806
806
  positiveHits(e) {
807
- if (typeof e != "number" || e < 1 || e !== Math.round(e)) throw new F("ERR_ERL_INVALID_HITS", `The totalHits value returned from the store must be a positive integer, got ${e}`);
807
+ if (typeof e != "number" || e < 1 || e !== Math.round(e)) throw new N("ERR_ERL_INVALID_HITS", `The totalHits value returned from the store must be a positive integer, got ${e}`);
808
808
  },
809
809
  unsharedStore(e) {
810
- if (Oe.has(e)) {
810
+ if (je.has(e)) {
811
811
  let t = e?.localKeys ? "" : " (with a unique prefix)";
812
- throw new F("ERR_ERL_STORE_REUSE", `A Store instance must not be shared across multiple rate limiters. Create a new instance of ${e.constructor.name}${t} for each limiter instead.`);
812
+ throw new N("ERR_ERL_STORE_REUSE", `A Store instance must not be shared across multiple rate limiters. Create a new instance of ${e.constructor.name}${t} for each limiter instead.`);
813
813
  }
814
- Oe.add(e);
814
+ je.add(e);
815
815
  },
816
816
  singleCount(e, t, n) {
817
- let r = ke.get(e);
818
- r || (r = /* @__PURE__ */ new Map(), ke.set(e, r));
817
+ let r = Me.get(e);
818
+ r || (r = /* @__PURE__ */ new Map(), Me.set(e, r));
819
819
  let i = t.localKeys ? t : t.constructor.name, a = r.get(i);
820
820
  a || (a = [], r.set(i, a));
821
821
  let o = `${t.prefix ?? ""}${n}`;
822
- if (a.includes(o)) throw new F("ERR_ERL_DOUBLE_COUNT", `The hit count for ${n} was incremented more than once for a single request.`);
822
+ if (a.includes(o)) throw new N("ERR_ERL_DOUBLE_COUNT", `The hit count for ${n} was incremented more than once for a single request.`);
823
823
  a.push(o);
824
824
  },
825
825
  limit(e) {
826
- if (e === 0) throw new I("WRN_ERL_MAX_ZERO", "Setting limit or max to 0 disables rate limiting in express-rate-limit v6 and older, but will cause all requests to be blocked in v7");
826
+ if (e === 0) throw new P("WRN_ERL_MAX_ZERO", "Setting limit or max to 0 disables rate limiting in express-rate-limit v6 and older, but will cause all requests to be blocked in v7");
827
827
  },
828
828
  draftPolliHeaders(e) {
829
- if (e) throw new I("WRN_ERL_DEPRECATED_DRAFT_POLLI_HEADERS", "The draft_polli_ratelimit_headers configuration option is deprecated and has been removed in express-rate-limit v7, please set standardHeaders: 'draft-6' instead.");
829
+ if (e) throw new P("WRN_ERL_DEPRECATED_DRAFT_POLLI_HEADERS", "The draft_polli_ratelimit_headers configuration option is deprecated and has been removed in express-rate-limit v7, please set standardHeaders: 'draft-6' instead.");
830
830
  },
831
831
  onLimitReached(e) {
832
- if (e) throw new I("WRN_ERL_DEPRECATED_ON_LIMIT_REACHED", "The onLimitReached configuration option is deprecated and has been removed in express-rate-limit v7.");
832
+ if (e) throw new P("WRN_ERL_DEPRECATED_ON_LIMIT_REACHED", "The onLimitReached configuration option is deprecated and has been removed in express-rate-limit v7.");
833
833
  },
834
834
  headersDraftVersion(e) {
835
- if (typeof e != "string" || !be.includes(e)) throw new F("ERR_ERL_HEADERS_UNSUPPORTED_DRAFT_VERSION", `standardHeaders: only the following versions of the IETF draft specification are supported: ${be.join(", ")}.`);
835
+ if (typeof e != "string" || !Ce.includes(e)) throw new N("ERR_ERL_HEADERS_UNSUPPORTED_DRAFT_VERSION", `standardHeaders: only the following versions of the IETF draft specification are supported: ${Ce.join(", ")}.`);
836
836
  },
837
837
  headersResetTime(e) {
838
- if (!e) throw new F("ERR_ERL_HEADERS_NO_RESET", "standardHeaders: 'draft-7' requires a 'resetTime', but the store did not provide one. The 'windowMs' value will be used instead, which may cause clients to wait longer than necessary.");
838
+ if (!e) throw new N("ERR_ERL_HEADERS_NO_RESET", "standardHeaders: 'draft-7' requires a 'resetTime', but the store did not provide one. The 'windowMs' value will be used instead, which may cause clients to wait longer than necessary.");
839
839
  },
840
840
  knownOptions(e) {
841
841
  if (!e) return;
@@ -862,54 +862,54 @@ var ve = class {
862
862
  passOnStoreError: !0,
863
863
  logger: !0
864
864
  }).concat("draft_polli_ratelimit_headers", "delayAfter", "delayMs", "maxDelayMs");
865
- for (let n of Object.keys(e)) if (!t.includes(n)) throw new F("ERR_ERL_UNKNOWN_OPTION", `Unexpected configuration option: ${n}`);
865
+ for (let n of Object.keys(e)) if (!t.includes(n)) throw new N("ERR_ERL_UNKNOWN_OPTION", `Unexpected configuration option: ${n}`);
866
866
  },
867
867
  validationsConfig() {
868
868
  let e = Object.keys(this).filter((e) => !["enabled", "disable"].includes(e));
869
869
  e.push("default");
870
- for (let t of Object.keys(this.enabled)) if (!e.includes(t)) throw new F("ERR_ERL_UNKNOWN_VALIDATION", `options.validate.${t} is not recognized. Supported validate options are: ${e.join(", ")}.`);
870
+ for (let t of Object.keys(this.enabled)) if (!e.includes(t)) throw new N("ERR_ERL_UNKNOWN_VALIDATION", `options.validate.${t} is not recognized. Supported validate options are: ${e.join(", ")}.`);
871
871
  },
872
872
  creationStack(e) {
873
873
  let { stack: t } = /* @__PURE__ */ Error("express-rate-limit validation check (set options.validate.creationStack=false to disable)");
874
- if (t?.includes("Layer.handle [as handle_request]") || t?.includes("Layer.handleRequest")) throw e.localKeys ? new F("ERR_ERL_CREATED_IN_REQUEST_HANDLER", "express-rate-limit instance should be created at app initialization, not when responding to a request.") : new F("ERR_ERL_CREATED_IN_REQUEST_HANDLER", "express-rate-limit instance should *usually* be created at app initialization, not when responding to a request.");
874
+ if (t?.includes("Layer.handle [as handle_request]") || t?.includes("Layer.handleRequest")) throw e.localKeys ? new N("ERR_ERL_CREATED_IN_REQUEST_HANDLER", "express-rate-limit instance should be created at app initialization, not when responding to a request.") : new N("ERR_ERL_CREATED_IN_REQUEST_HANDLER", "express-rate-limit instance should *usually* be created at app initialization, not when responding to a request.");
875
875
  },
876
876
  ipv6Subnet(e) {
877
- if (e !== !1 && (!Number.isInteger(e) || e < 32 || e > 64)) throw new F("ERR_ERL_IPV6_SUBNET", `Unexpected ipv6Subnet value: ${e}. Expected an integer between 32 and 64 (usually 48-64).`);
877
+ if (e !== !1 && (!Number.isInteger(e) || e < 32 || e > 64)) throw new N("ERR_ERL_IPV6_SUBNET", `Unexpected ipv6Subnet value: ${e}. Expected an integer between 32 and 64 (usually 48-64).`);
878
878
  },
879
879
  ipv6SubnetOrKeyGenerator(e) {
880
- if (e.ipv6Subnet !== void 0 && e.keyGenerator) throw new F("ERR_ERL_IPV6SUBNET_OR_KEYGENERATOR", "Incompatible options: the 'ipv6Subnet' option is ignored when a custom 'keyGenerator' function is also set.");
880
+ if (e.ipv6Subnet !== void 0 && e.keyGenerator) throw new N("ERR_ERL_IPV6SUBNET_OR_KEYGENERATOR", "Incompatible options: the 'ipv6Subnet' option is ignored when a custom 'keyGenerator' function is also set.");
881
881
  },
882
882
  keyGeneratorIpFallback(e) {
883
883
  if (!e) return;
884
884
  let t = e.toString();
885
- if ((t.includes("req.ip") || t.includes("request.ip")) && !t.includes("ipKeyGenerator")) throw new F("ERR_ERL_KEY_GEN_IPV6", "Custom keyGenerator appears to use request IP without calling the ipKeyGenerator helper function for IPv6 addresses. This could allow IPv6 users to bypass limits.");
885
+ if ((t.includes("req.ip") || t.includes("request.ip")) && !t.includes("ipKeyGenerator")) throw new N("ERR_ERL_KEY_GEN_IPV6", "Custom keyGenerator appears to use request IP without calling the ipKeyGenerator helper function for IPv6 addresses. This could allow IPv6 users to bypass limits.");
886
886
  },
887
887
  windowMs(e) {
888
888
  let t = 2 ** 31 - 1;
889
- if (typeof e != "number" || Number.isNaN(e) || e < 1 || e > t) throw new F("ERR_ERL_WINDOW_MS", `Invalid windowMs value: ${e}${typeof e == "number" ? "" : ` (${typeof e})`}, must be a number between 1 and ${t} when using the default MemoryStore`);
889
+ if (typeof e != "number" || Number.isNaN(e) || e < 1 || e > t) throw new N("ERR_ERL_WINDOW_MS", `Invalid windowMs value: ${e}${typeof e == "number" ? "" : ` (${typeof e})`}, must be a number between 1 and ${t} when using the default MemoryStore`);
890
890
  }
891
891
  };
892
- function je(e) {
892
+ function Pe(e) {
893
893
  if (typeof e != "object" || typeof e.error != "function" || typeof e.warn != "function") throw TypeError("Provided logger does not implement the Logger interface");
894
894
  }
895
- var Me = (e, t) => {
896
- je(t);
895
+ var Fe = (e, t) => {
896
+ Pe(t);
897
897
  let n;
898
898
  n = typeof e == "boolean" ? { default: e } : {
899
899
  default: !0,
900
900
  ...e
901
901
  };
902
902
  let r = { enabled: n };
903
- for (let [e, i] of Object.entries(Ae)) typeof i == "function" && (r[e] = (...a) => {
903
+ for (let [e, i] of Object.entries(Ne)) typeof i == "function" && (r[e] = (...a) => {
904
904
  if (n[e] ?? n.default) try {
905
905
  i.apply(r, a);
906
906
  } catch (e) {
907
- e instanceof I ? t.warn(e) : t.error(e);
907
+ e instanceof P ? t.warn(e) : t.error(e);
908
908
  }
909
909
  });
910
910
  return r;
911
- }, Ne = (e) => typeof e.incr == "function" && typeof e.increment != "function", Pe = (e) => {
912
- if (!Ne(e)) return e;
911
+ }, Ie = (e) => typeof e.incr == "function" && typeof e.increment != "function", Le = (e) => {
912
+ if (!Ie(e)) return e;
913
913
  let t = e;
914
914
  class n {
915
915
  async increment(e) {
@@ -934,26 +934,26 @@ var Me = (e, t) => {
934
934
  }
935
935
  }
936
936
  return new n();
937
- }, Fe = (e) => {
937
+ }, Re = (e) => {
938
938
  let { validations: t, ...n } = e;
939
939
  return {
940
940
  ...n,
941
941
  validate: t.enabled
942
942
  };
943
- }, Ie = (e) => {
944
- let t = De(e), n = e.logger ?? ye, i = Me(t?.validate ?? !0, n);
945
- i.validationsConfig(), i.knownOptions(e), i.draftPolliHeaders(t.draft_polli_ratelimit_headers), i.onLimitReached(t.onLimitReached), t.ipv6Subnet !== void 0 && typeof t.ipv6Subnet != "function" && i.ipv6Subnet(t.ipv6Subnet), i.keyGeneratorIpFallback(t.keyGenerator), i.ipv6SubnetOrKeyGenerator(t);
946
- let a = t.standardHeaders ?? !1;
947
- a === !0 && (a = "draft-6");
948
- let o = {
943
+ }, ze = (e) => {
944
+ let t = Ae(e), n = e.logger ?? Se, r = Fe(t?.validate ?? !0, n);
945
+ r.validationsConfig(), r.knownOptions(e), r.draftPolliHeaders(t.draft_polli_ratelimit_headers), r.onLimitReached(t.onLimitReached), t.ipv6Subnet !== void 0 && typeof t.ipv6Subnet != "function" && r.ipv6Subnet(t.ipv6Subnet), r.keyGeneratorIpFallback(t.keyGenerator), r.ipv6SubnetOrKeyGenerator(t);
946
+ let i = t.standardHeaders ?? !1;
947
+ i === !0 && (i = "draft-6");
948
+ let a = {
949
949
  windowMs: 60 * 1e3,
950
950
  limit: e.max ?? 5,
951
951
  message: "Too many requests, please try again later.",
952
952
  statusCode: 429,
953
953
  legacyHeaders: e.headers ?? !0,
954
954
  identifier(e, t) {
955
- let n = "", { limit: r } = e[o.requestPropertyName], i = o.windowMs / 1e3, a = o.windowMs / (1e3 * 60), s = o.windowMs / (1e3 * 60 * 60), c = o.windowMs / (1e3 * 60 * 60 * 24);
956
- return n = i < 60 ? `${i}sec` : a < 60 ? `${a}min` : s < 24 ? `${s}hr${s > 1 ? "s" : ""}` : `${c}day${c > 1 ? "s" : ""}`, `${r}-in-${n}`;
955
+ let n = "", { limit: r } = e[a.requestPropertyName], i = a.windowMs / 1e3, o = a.windowMs / (1e3 * 60), s = a.windowMs / (1e3 * 60 * 60), c = a.windowMs / (1e3 * 60 * 60 * 24);
956
+ return n = i < 60 ? `${i}sec` : o < 60 ? `${o}min` : s < 24 ? `${s}hr${s > 1 ? "s" : ""}` : `${c}day${c > 1 ? "s" : ""}`, `${r}-in-${n}`;
957
957
  },
958
958
  requestPropertyName: "rateLimit",
959
959
  skipFailedRequests: !1,
@@ -961,40 +961,40 @@ var Me = (e, t) => {
961
961
  requestWasSuccessful: (e, t) => t.statusCode < 400,
962
962
  skip: (e, t) => !1,
963
963
  async keyGenerator(e, t) {
964
- i.ip(e.ip), i.trustProxy(e), i.xForwardedForHeader(e), i.forwardedHeader(e);
965
- let n = e.ip, a = 56;
966
- return r(n) && (a = typeof o.ipv6Subnet == "function" ? await o.ipv6Subnet(e, t) : o.ipv6Subnet, typeof o.ipv6Subnet == "function" && i.ipv6Subnet(a)), _e(n, a);
964
+ r.ip(e.ip), r.trustProxy(e), r.xForwardedForHeader(e), r.forwardedHeader(e);
965
+ let n = e.ip, i = 56;
966
+ return d(n) && (i = typeof a.ipv6Subnet == "function" ? await a.ipv6Subnet(e, t) : a.ipv6Subnet, typeof a.ipv6Subnet == "function" && r.ipv6Subnet(i)), be(n, i);
967
967
  },
968
968
  ipv6Subnet: 56,
969
969
  async handler(e, t, n, r) {
970
- t.status(o.statusCode);
971
- let i = typeof o.message == "function" ? await o.message(e, t) : o.message;
970
+ t.status(a.statusCode);
971
+ let i = typeof a.message == "function" ? await a.message(e, t) : a.message;
972
972
  t.writableEnded || t.send(i);
973
973
  },
974
974
  passOnStoreError: !1,
975
975
  ...t,
976
- standardHeaders: a,
977
- store: Pe(t.store ?? new ve(i)),
978
- validations: i,
976
+ standardHeaders: i,
977
+ store: Le(t.store ?? new xe(r)),
978
+ validations: r,
979
979
  logger: n
980
980
  };
981
- if (typeof o.store.increment != "function" || typeof o.store.decrement != "function" || typeof o.store.resetKey != "function" || o.store.resetAll !== void 0 && typeof o.store.resetAll != "function" || o.store.init !== void 0 && typeof o.store.init != "function") throw TypeError("An invalid store was passed. Please ensure that the store is a class that implements the `Store` interface.");
982
- return o;
983
- }, Le = (e) => async (t, n, r) => {
981
+ if (typeof a.store.increment != "function" || typeof a.store.decrement != "function" || typeof a.store.resetKey != "function" || a.store.resetAll !== void 0 && typeof a.store.resetAll != "function" || a.store.init !== void 0 && typeof a.store.init != "function") throw TypeError("An invalid store was passed. Please ensure that the store is a class that implements the `Store` interface.");
982
+ return a;
983
+ }, Be = (e) => async (t, n, r) => {
984
984
  try {
985
985
  await Promise.resolve(e(t, n, r)).catch(r);
986
986
  } catch (e) {
987
987
  r(e);
988
988
  }
989
- }, Re = (e) => {
990
- let t = Ie(e ?? {}), n = Fe(t);
989
+ }, Ve = (e) => {
990
+ let t = ze(e ?? {}), n = Re(t);
991
991
  if (t.validations.creationStack(t.store), t.validations.unsharedStore(t.store), typeof t.store.init == "function") try {
992
992
  let e = t.store.init(n);
993
993
  e instanceof Promise && e.catch((e) => t.logger.error(e, "express-rate-limit: async error during store initialization."));
994
994
  } catch (e) {
995
995
  t.logger.error(e, "express-rate-limit: error during store initialization.");
996
996
  }
997
- let r = Le(async (e, r, i) => {
997
+ let r = Be(async (e, r, i) => {
998
998
  let a = t.skipFailedRequests && new Promise((e) => r.once("close", e)), o = (t.skipFailedRequests || t.skipSuccessfulRequests) && new Promise((e) => r.once("finish", e)), s = t.skipFailedRequests && new Promise((e) => r.once("error", e));
999
999
  if (await t.skip(e, r)) {
1000
1000
  i();
@@ -1025,16 +1025,16 @@ var Me = (e, t) => {
1025
1025
  configurable: !1,
1026
1026
  enumerable: !1,
1027
1027
  value: u
1028
- }), c[t.requestPropertyName] = p, t.legacyHeaders && !r.headersSent && Se(r, p), t.standardHeaders && !r.headersSent) switch (t.standardHeaders) {
1028
+ }), c[t.requestPropertyName] = p, t.legacyHeaders && !r.headersSent && Te(r, p), t.standardHeaders && !r.headersSent) switch (t.standardHeaders) {
1029
1029
  case "draft-6":
1030
- Ce(r, p, t.windowMs);
1030
+ Ee(r, p, t.windowMs);
1031
1031
  break;
1032
1032
  case "draft-7":
1033
- t.validations.headersResetTime(p.resetTime), we(r, p, t.windowMs);
1033
+ t.validations.headersResetTime(p.resetTime), De(r, p, t.windowMs);
1034
1034
  break;
1035
1035
  case "draft-8": {
1036
1036
  let n = await (typeof t.identifier == "function" ? t.identifier(e, r) : t.identifier);
1037
- t.validations.headersResetTime(p.resetTime), Te(r, p, t.windowMs, n, l);
1037
+ t.validations.headersResetTime(p.resetTime), Oe(r, p, t.windowMs, n, l);
1038
1038
  break;
1039
1039
  }
1040
1040
  default:
@@ -1056,7 +1056,7 @@ var Me = (e, t) => {
1056
1056
  });
1057
1057
  }
1058
1058
  if (t.validations.disable(), u > f) {
1059
- (t.legacyHeaders || t.standardHeaders) && Ee(r, p, t.windowMs), t.handler(e, r, i, n);
1059
+ (t.legacyHeaders || t.standardHeaders) && ke(r, p, t.windowMs), t.handler(e, r, i, n);
1060
1060
  return;
1061
1061
  }
1062
1062
  i();
@@ -1064,7 +1064,7 @@ var Me = (e, t) => {
1064
1064
  return r.resetKey = t.store.resetKey.bind(t.store), r.getKey = typeof t.store.get == "function" ? t.store.get.bind(t.store) : () => {
1065
1065
  throw Error("The current store does not support the get/getKey method");
1066
1066
  }, r;
1067
- }, ze = new Set([
1067
+ }, He = new Set([
1068
1068
  "token",
1069
1069
  "accesstoken",
1070
1070
  "refreshtoken",
@@ -1077,11 +1077,11 @@ var Me = (e, t) => {
1077
1077
  "password",
1078
1078
  "secret"
1079
1079
  ]);
1080
- function Be(e) {
1080
+ function Ue(e) {
1081
1081
  return e.toLowerCase().replace(/[^a-z0-9]/g, "");
1082
1082
  }
1083
- function L(e, t) {
1084
- for (let e of Object.keys(t)) if (ze.has(Be(e))) throw Error(`OAuth audit event must not carry forbidden field: ${e}`);
1083
+ function F(e, t) {
1084
+ for (let e of Object.keys(t)) if (He.has(Ue(e))) throw Error(`OAuth audit event must not carry forbidden field: ${e}`);
1085
1085
  let { now: n, ...r } = t;
1086
1086
  return {
1087
1087
  kind: e,
@@ -1089,7 +1089,7 @@ function L(e, t) {
1089
1089
  ...r
1090
1090
  };
1091
1091
  }
1092
- function Ve(e) {
1092
+ function We(e) {
1093
1093
  let t = !1;
1094
1094
  return (n) => {
1095
1095
  try {
@@ -1099,7 +1099,7 @@ function Ve(e) {
1099
1099
  }
1100
1100
  };
1101
1101
  }
1102
- function He(e = process.stderr) {
1102
+ function Ge(e = process.stderr) {
1103
1103
  return (t) => {
1104
1104
  e.write(`${JSON.stringify({
1105
1105
  source: "codemem-mcp-oauth-audit",
@@ -1107,28 +1107,28 @@ function He(e = process.stderr) {
1107
1107
  })}\n`);
1108
1108
  };
1109
1109
  }
1110
- function Ue() {
1110
+ function Ke() {
1111
1111
  return () => {};
1112
1112
  }
1113
- function We(e = process.env.CODEMEM_MCP_AUDIT) {
1113
+ function qe(e = process.env.CODEMEM_MCP_AUDIT) {
1114
1114
  let t = e?.trim().toLowerCase();
1115
- return t === "0" || t === "false" || t === "no" ? Ue() : He();
1115
+ return t === "0" || t === "false" || t === "no" ? Ke() : Ge();
1116
1116
  }
1117
- var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github.com/kunickiaj/codemem#readme", Ke = "https://claude.ai/api/mcp/auth_callback", qe = "https://chatgpt.com/connector_platform_oauth_redirect", Je = new Set([
1117
+ var Je = "codemem MCP", I = ["memory:read", "memory:write"], L = "https://github.com/kunickiaj/codemem#readme", Ye = "https://claude.ai/api/mcp/auth_callback", Xe = "https://chatgpt.com/connector_platform_oauth_redirect", Ze = new Set([
1118
1118
  "localhost",
1119
1119
  "127.0.0.1",
1120
1120
  "::1"
1121
- ]), Ye = new Set(["authorization_code", "refresh_token"]), Xe = new Set(["code"]), B = 3600, V = 720 * 60 * 60, Ze = 100, Qe = 100, $e = 100, et = 32, tt = 43, nt = /^[A-Za-z0-9_-]{43}$/, rt = /^[A-Za-z0-9_-]{43}$/, it = /^[A-Za-z0-9_-]{1,128}$/, at = class {
1121
+ ]), Qe = new Set(["authorization_code", "refresh_token"]), $e = new Set(["code"]), R = 3600, z = 720 * 60 * 60, et = 100, tt = 100, nt = 100, rt = 32, it = 43, at = /^[A-Za-z0-9_-]{43}$/, ot = /^[A-Za-z0-9_-]{43}$/, st = /^[A-Za-z0-9_-]{1,128}$/, ct = class {
1122
1122
  #e = /* @__PURE__ */ new Map();
1123
1123
  getClient(e) {
1124
1124
  return this.#e.get(e);
1125
1125
  }
1126
1126
  registerClient(e) {
1127
- let t = xt(e.redirect_uris);
1128
- if (t) throw new O(t);
1129
- if (e.client_secret || e.token_endpoint_auth_method !== "none") throw new O("Only public clients with token_endpoint_auth_method=none are supported");
1130
- if (e.grant_types && !H(e.grant_types, Ye)) throw new O("Only authorization_code and refresh_token grant_types are supported");
1131
- if (e.response_types && !H(e.response_types, Xe)) throw new O("Only code response_type is supported");
1127
+ let t = wt(e.redirect_uris);
1128
+ if (t) throw new D(t);
1129
+ if (e.client_secret || e.token_endpoint_auth_method !== "none") throw new D("Only public clients with token_endpoint_auth_method=none are supported");
1130
+ if (e.grant_types && !B(e.grant_types, Qe)) throw new D("Only authorization_code and refresh_token grant_types are supported");
1131
+ if (e.response_types && !B(e.response_types, $e)) throw new D("Only code response_type is supported");
1132
1132
  if (this.#e.size >= 100) {
1133
1133
  let e = this.#e.keys().next().value;
1134
1134
  e && this.#e.delete(e);
@@ -1138,16 +1138,16 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1138
1138
  token_endpoint_auth_method: "none",
1139
1139
  grant_types: e.grant_types ?? ["authorization_code", "refresh_token"],
1140
1140
  response_types: e.response_types ?? ["code"],
1141
- client_id: v(),
1141
+ client_id: o(),
1142
1142
  client_id_issued_at: Math.floor(Date.now() / 1e3)
1143
1143
  };
1144
1144
  return this.#e.set(n.client_id, n), n;
1145
1145
  }
1146
- }, ot = class {
1146
+ }, lt = class {
1147
1147
  #e = /* @__PURE__ */ new Map();
1148
1148
  issueCode(e, t = Date.now()) {
1149
- if (this.#t(t), this.#e.size >= Ze) return;
1150
- let n = v();
1149
+ if (this.#t(t), this.#e.size >= et) return;
1150
+ let n = o();
1151
1151
  return this.#e.set(n, {
1152
1152
  ...e,
1153
1153
  used: !1
@@ -1164,35 +1164,35 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1164
1164
  #t(e) {
1165
1165
  for (let [t, n] of this.#e) n.expiresAt <= e && this.#e.delete(t);
1166
1166
  }
1167
- }, st = class {
1167
+ }, ut = class {
1168
1168
  #e = /* @__PURE__ */ new Map();
1169
- #t = _(32);
1169
+ #t = a(32);
1170
1170
  issueToken(e, t = Date.now(), n, r, i = []) {
1171
- if (this.#n(t), this.#e.size >= Qe) return;
1172
- let a = _(et), o = kt(a, this.#t);
1173
- return this.#e.set(o, {
1171
+ if (this.#n(t), this.#e.size >= tt) return;
1172
+ let o = a(rt), s = K(o, this.#t);
1173
+ return this.#e.set(s, {
1174
1174
  clientId: e,
1175
1175
  grantId: r,
1176
1176
  scopes: [...i],
1177
1177
  resource: n,
1178
- tokenHash: o,
1178
+ tokenHash: s,
1179
1179
  issuedAt: t,
1180
- expiresAt: t + B * 1e3,
1180
+ expiresAt: t + R * 1e3,
1181
1181
  lastUsedAt: null,
1182
1182
  revokedAt: null
1183
1183
  }), {
1184
- token: a.toString("base64url"),
1185
- expiresIn: B
1184
+ token: o.toString("base64url"),
1185
+ expiresIn: R
1186
1186
  };
1187
1187
  }
1188
1188
  verifyToken(e, t = Date.now()) {
1189
- let n = W(e);
1189
+ let n = H(e);
1190
1190
  if (!n) return {
1191
1191
  ok: !1,
1192
1192
  reason: "unknown_token"
1193
1193
  };
1194
- let r = kt(n, this.#t), i = this.#e.get(r);
1195
- return !i || !J(i.tokenHash, r) ? {
1194
+ let r = K(n, this.#t), i = this.#e.get(r);
1195
+ return !i || !q(i.tokenHash, r) ? {
1196
1196
  ok: !1,
1197
1197
  reason: "unknown_token"
1198
1198
  } : i.revokedAt === null ? i.expiresAt <= t ? {
@@ -1207,10 +1207,10 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1207
1207
  };
1208
1208
  }
1209
1209
  revokeToken(e, t = Date.now()) {
1210
- let n = W(e);
1210
+ let n = H(e);
1211
1211
  if (!n) return !1;
1212
- let r = kt(n, this.#t), i = this.#e.get(r);
1213
- return !i || !J(i.tokenHash, r) ? !1 : (i.revokedAt === null && (i.revokedAt = t), !0);
1212
+ let r = K(n, this.#t), i = this.#e.get(r);
1213
+ return !i || !q(i.tokenHash, r) ? !1 : (i.revokedAt === null && (i.revokedAt = t), !0);
1214
1214
  }
1215
1215
  revokeTokensForGrant(e, t = Date.now()) {
1216
1216
  let n = 0;
@@ -1220,24 +1220,24 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1220
1220
  #n(e) {
1221
1221
  for (let [t, n] of this.#e) (n.expiresAt <= e || n.revokedAt !== null) && this.#e.delete(t);
1222
1222
  }
1223
- }, ct = class {
1223
+ }, dt = class {
1224
1224
  #e = /* @__PURE__ */ new Map();
1225
1225
  #t = /* @__PURE__ */ new Map();
1226
1226
  #n = /* @__PURE__ */ new Map();
1227
- #r = _(32);
1227
+ #r = a(32);
1228
1228
  issueGrant(e, t = Date.now()) {
1229
- if (this.#i(t), this.#e.size >= $e) return;
1230
- let n = G(), r = K(n, this.#r);
1229
+ if (this.#i(t), this.#e.size >= nt) return;
1230
+ let n = U(), r = W(n, this.#r);
1231
1231
  if (!r) return;
1232
1232
  let i = {
1233
- grantId: v(),
1233
+ grantId: o(),
1234
1234
  clientId: e.clientId,
1235
1235
  scopes: [...e.scopes ?? []],
1236
1236
  resource: e.resource,
1237
1237
  currentRefreshTokenHash: r,
1238
1238
  previousRefreshTokenHash: null,
1239
1239
  issuedAt: t,
1240
- expiresAt: t + V * 1e3,
1240
+ expiresAt: t + z * 1e3,
1241
1241
  rotatedAt: null,
1242
1242
  revokedAt: null
1243
1243
  };
@@ -1247,11 +1247,11 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1247
1247
  scopes: [...i.scopes]
1248
1248
  },
1249
1249
  refreshToken: n,
1250
- expiresIn: V
1250
+ expiresIn: z
1251
1251
  };
1252
1252
  }
1253
1253
  rotateRefreshToken(e, t, n = {}, r = Date.now()) {
1254
- let i = K(t, this.#r);
1254
+ let i = W(t, this.#r);
1255
1255
  if (!i) return {
1256
1256
  ok: !1,
1257
1257
  reason: "unknown_refresh_token"
@@ -1281,7 +1281,7 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1281
1281
  reason: "client_mismatch",
1282
1282
  grantId: a
1283
1283
  };
1284
- if (!jt(n.scopes ?? o.scopes, o.scopes)) return {
1284
+ if (!Nt(n.scopes ?? o.scopes, o.scopes)) return {
1285
1285
  ok: !1,
1286
1286
  reason: "scope_mismatch",
1287
1287
  grantId: a
@@ -1291,13 +1291,13 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1291
1291
  reason: "resource_mismatch",
1292
1292
  grantId: a
1293
1293
  };
1294
- let s = J(o.currentRefreshTokenHash, i), c = o.previousRefreshTokenHash !== null && J(o.previousRefreshTokenHash, i);
1294
+ let s = q(o.currentRefreshTokenHash, i), c = o.previousRefreshTokenHash !== null && q(o.previousRefreshTokenHash, i);
1295
1295
  if (!s && !c) return this.revokeGrant(a, r), {
1296
1296
  ok: !1,
1297
1297
  reason: "refresh_token_replay",
1298
1298
  grantId: a
1299
1299
  };
1300
- let l = G(), u = K(l, this.#r);
1300
+ let l = U(), u = W(l, this.#r);
1301
1301
  return u ? (o.scopes = [...n.scopes ?? o.scopes], o.previousRefreshTokenHash = s ? o.currentRefreshTokenHash : null, o.currentRefreshTokenHash = u, o.rotatedAt = r, this.#t.set(u, a), this.#n.get(a)?.add(u), {
1302
1302
  ok: !0,
1303
1303
  grant: {
@@ -1312,7 +1312,7 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1312
1312
  };
1313
1313
  }
1314
1314
  revokeRefreshToken(e, t = Date.now()) {
1315
- let n = K(e, this.#r);
1315
+ let n = W(e, this.#r);
1316
1316
  if (!n) return;
1317
1317
  let r = this.#t.get(n);
1318
1318
  if (r) return this.revokeGrant(r, t), r;
@@ -1333,7 +1333,7 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1333
1333
  }
1334
1334
  this.#t.delete(e.currentRefreshTokenHash), e.previousRefreshTokenHash && this.#t.delete(e.previousRefreshTokenHash);
1335
1335
  }
1336
- }, lt = class {
1336
+ }, ft = class {
1337
1337
  #e;
1338
1338
  #t = /* @__PURE__ */ new Map();
1339
1339
  #n = /* @__PURE__ */ new Map();
@@ -1341,18 +1341,18 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1341
1341
  #i = /* @__PURE__ */ new Map();
1342
1342
  #a = /* @__PURE__ */ new Map();
1343
1343
  #o = /* @__PURE__ */ new Map();
1344
- constructor(e = ht()) {
1344
+ constructor(e = vt()) {
1345
1345
  this.#e = e, this.#s();
1346
1346
  }
1347
1347
  getClient(e) {
1348
1348
  return this.#n.get(e);
1349
1349
  }
1350
1350
  registerClient(e) {
1351
- let t = xt(e.redirect_uris);
1352
- if (t) throw new O(t);
1353
- if (e.client_secret || e.token_endpoint_auth_method !== "none") throw new O("Only public clients with token_endpoint_auth_method=none are supported");
1354
- if (e.grant_types && !H(e.grant_types, Ye)) throw new O("Only authorization_code and refresh_token grant_types are supported");
1355
- if (e.response_types && !H(e.response_types, Xe)) throw new O("Only code response_type is supported");
1351
+ let t = wt(e.redirect_uris);
1352
+ if (t) throw new D(t);
1353
+ if (e.client_secret || e.token_endpoint_auth_method !== "none") throw new D("Only public clients with token_endpoint_auth_method=none are supported");
1354
+ if (e.grant_types && !B(e.grant_types, Qe)) throw new D("Only authorization_code and refresh_token grant_types are supported");
1355
+ if (e.response_types && !B(e.response_types, $e)) throw new D("Only code response_type is supported");
1356
1356
  if (this.#u(Date.now()), this.#n.size >= 100) {
1357
1357
  let e = this.#n.keys().next().value;
1358
1358
  e && this.#n.delete(e);
@@ -1362,14 +1362,14 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1362
1362
  token_endpoint_auth_method: "none",
1363
1363
  grant_types: e.grant_types ?? ["authorization_code", "refresh_token"],
1364
1364
  response_types: e.response_types ?? ["code"],
1365
- client_id: v(),
1365
+ client_id: o(),
1366
1366
  client_id_issued_at: Math.floor(Date.now() / 1e3)
1367
1367
  };
1368
1368
  return this.#n.set(n.client_id, n), this.#c(), n;
1369
1369
  }
1370
1370
  issueCode(e, t = Date.now()) {
1371
- if (this.#l(t), this.#t.size >= Ze) return;
1372
- let n = v();
1371
+ if (this.#l(t), this.#t.size >= et) return;
1372
+ let n = o();
1373
1373
  return this.#t.set(n, {
1374
1374
  ...e,
1375
1375
  used: !1
@@ -1384,8 +1384,8 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1384
1384
  if (!(!t || t.used)) return t.used = !0, t;
1385
1385
  }
1386
1386
  issueToken(e, t = Date.now(), n, r, i = []) {
1387
- if (this.#u(t), this.#r.size >= Qe) return;
1388
- let a = G(), o = q(a);
1387
+ if (this.#u(t), this.#r.size >= tt) return;
1388
+ let a = U(), o = G(a);
1389
1389
  if (o) return this.#r.set(o, {
1390
1390
  clientId: e,
1391
1391
  grantId: r,
@@ -1393,22 +1393,22 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1393
1393
  resource: n,
1394
1394
  tokenHash: o,
1395
1395
  issuedAt: t,
1396
- expiresAt: t + B * 1e3,
1396
+ expiresAt: t + R * 1e3,
1397
1397
  lastUsedAt: null,
1398
1398
  revokedAt: null
1399
1399
  }), this.#c(), {
1400
1400
  token: a,
1401
- expiresIn: B
1401
+ expiresIn: R
1402
1402
  };
1403
1403
  }
1404
1404
  verifyToken(e, t = Date.now()) {
1405
- let n = q(e);
1405
+ let n = G(e);
1406
1406
  if (!n) return {
1407
1407
  ok: !1,
1408
1408
  reason: "unknown_token"
1409
1409
  };
1410
1410
  let r = this.#r.get(n);
1411
- return !r || !J(r.tokenHash, n) ? {
1411
+ return !r || !q(r.tokenHash, n) ? {
1412
1412
  ok: !1,
1413
1413
  reason: "unknown_token"
1414
1414
  } : r.revokedAt === null ? r.expiresAt <= t ? {
@@ -1426,10 +1426,10 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1426
1426
  };
1427
1427
  }
1428
1428
  revokeToken(e, t = Date.now()) {
1429
- let n = q(e);
1429
+ let n = G(e);
1430
1430
  if (!n) return !1;
1431
1431
  let r = this.#r.get(n);
1432
- return !r || !J(r.tokenHash, n) ? !1 : r.revokedAt === null ? (r.revokedAt = t, this.#c(), !0) : !0;
1432
+ return !r || !q(r.tokenHash, n) ? !1 : r.revokedAt === null ? (r.revokedAt = t, this.#c(), !0) : !0;
1433
1433
  }
1434
1434
  revokeTokensForGrant(e, t = Date.now()) {
1435
1435
  let n = 0;
@@ -1437,18 +1437,18 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1437
1437
  return n > 0 && this.#c(), n;
1438
1438
  }
1439
1439
  issueGrant(e, t = Date.now()) {
1440
- if (this.#u(t), this.#i.size >= $e) return;
1441
- let n = G(), r = q(n);
1440
+ if (this.#u(t), this.#i.size >= nt) return;
1441
+ let n = U(), r = G(n);
1442
1442
  if (!r) return;
1443
1443
  let i = {
1444
- grantId: v(),
1444
+ grantId: o(),
1445
1445
  clientId: e.clientId,
1446
1446
  scopes: [...e.scopes ?? []],
1447
1447
  resource: e.resource,
1448
1448
  currentRefreshTokenHash: r,
1449
1449
  previousRefreshTokenHash: null,
1450
1450
  issuedAt: t,
1451
- expiresAt: t + V * 1e3,
1451
+ expiresAt: t + z * 1e3,
1452
1452
  rotatedAt: null,
1453
1453
  revokedAt: null
1454
1454
  };
@@ -1458,11 +1458,11 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1458
1458
  scopes: [...i.scopes]
1459
1459
  },
1460
1460
  refreshToken: n,
1461
- expiresIn: V
1461
+ expiresIn: z
1462
1462
  };
1463
1463
  }
1464
1464
  rotateRefreshToken(e, t, n = {}, r = Date.now()) {
1465
- let i = q(t);
1465
+ let i = G(t);
1466
1466
  if (!i) return {
1467
1467
  ok: !1,
1468
1468
  reason: "unknown_refresh_token"
@@ -1492,7 +1492,7 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1492
1492
  reason: "client_mismatch",
1493
1493
  grantId: a
1494
1494
  };
1495
- if (!jt(n.scopes ?? o.scopes, o.scopes)) return {
1495
+ if (!Nt(n.scopes ?? o.scopes, o.scopes)) return {
1496
1496
  ok: !1,
1497
1497
  reason: "scope_mismatch",
1498
1498
  grantId: a
@@ -1502,13 +1502,13 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1502
1502
  reason: "resource_mismatch",
1503
1503
  grantId: a
1504
1504
  };
1505
- let s = J(o.currentRefreshTokenHash, i), c = o.previousRefreshTokenHash !== null && J(o.previousRefreshTokenHash, i);
1505
+ let s = q(o.currentRefreshTokenHash, i), c = o.previousRefreshTokenHash !== null && q(o.previousRefreshTokenHash, i);
1506
1506
  if (!s && !c) return this.revokeGrant(a, r), {
1507
1507
  ok: !1,
1508
1508
  reason: "refresh_token_replay",
1509
1509
  grantId: a
1510
1510
  };
1511
- let l = G(), u = q(l);
1511
+ let l = U(), u = G(l);
1512
1512
  return u ? (o.scopes = [...n.scopes ?? o.scopes], o.previousRefreshTokenHash = s ? o.currentRefreshTokenHash : null, o.currentRefreshTokenHash = u, o.rotatedAt = r, this.#a.set(u, a), this.#o.get(a)?.add(u), this.#c(), {
1513
1513
  ok: !0,
1514
1514
  grant: {
@@ -1523,7 +1523,7 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1523
1523
  };
1524
1524
  }
1525
1525
  revokeRefreshToken(e, t = Date.now()) {
1526
- let n = q(e);
1526
+ let n = G(e);
1527
1527
  if (!n) return;
1528
1528
  let r = this.#a.get(n);
1529
1529
  if (r) return this.revokeGrant(r, t), r;
@@ -1533,10 +1533,10 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1533
1533
  return n ? n.revokedAt === null ? (n.revokedAt = t, this.#d(n), this.#c(), !0) : !0 : !1;
1534
1534
  }
1535
1535
  #s() {
1536
- if (!x(this.#e)) return;
1536
+ if (!v(this.#e)) return;
1537
1537
  let e;
1538
1538
  try {
1539
- e = JSON.parse(C(this.#e, "utf8"));
1539
+ e = JSON.parse(ie(this.#e, "utf8"));
1540
1540
  } catch {
1541
1541
  return;
1542
1542
  }
@@ -1551,7 +1551,7 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1551
1551
  }
1552
1552
  }
1553
1553
  #c() {
1554
- S(D(this.#e), {
1554
+ y(w(this.#e), {
1555
1555
  recursive: !0,
1556
1556
  mode: 448
1557
1557
  });
@@ -1562,7 +1562,7 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1562
1562
  refreshGrants: [...this.#i.values()],
1563
1563
  refreshHashesByGrantId: Object.fromEntries([...this.#o.entries()].map(([e, t]) => [e, [...t]]))
1564
1564
  }, t = `${this.#e}.${process.pid}.${Date.now()}.tmp`;
1565
- w(t, `${JSON.stringify(e, null, 2)}\n`, { mode: 384 }), ee(t, this.#e), T(this.#e, 384).catch(() => void 0);
1565
+ x(t, `${JSON.stringify(e, null, 2)}\n`, { mode: 384 }), b(t, this.#e), S(this.#e, 384).catch(() => void 0);
1566
1566
  }
1567
1567
  #l(e) {
1568
1568
  for (let [t, n] of this.#t) n.expiresAt <= e && this.#t.delete(t);
@@ -1583,58 +1583,58 @@ var Ge = "codemem MCP", R = ["memory:read", "memory:write"], z = "https://github
1583
1583
  this.#a.delete(e.currentRefreshTokenHash), e.previousRefreshTokenHash && this.#a.delete(e.previousRefreshTokenHash);
1584
1584
  }
1585
1585
  };
1586
- function ut() {
1587
- return new at();
1588
- }
1589
- function dt() {
1590
- return new ot();
1591
- }
1592
- function ft() {
1593
- return new st();
1594
- }
1595
1586
  function pt() {
1596
1587
  return new ct();
1597
1588
  }
1598
- function mt(e) {
1599
- return new lt(e);
1589
+ function mt() {
1590
+ return new lt();
1600
1591
  }
1601
1592
  function ht() {
1602
- return te(process.env.HOME?.trim() || E(), ".codemem", "mcp-oauth-state.json");
1593
+ return new ut();
1594
+ }
1595
+ function gt() {
1596
+ return new dt();
1597
+ }
1598
+ function _t(e) {
1599
+ return new ft(e);
1603
1600
  }
1604
- function gt(e) {
1605
- let t = bt(yt(e.mcpUrl));
1601
+ function vt() {
1602
+ return T(process.env.HOME?.trim() || C(), ".codemem", "mcp-oauth-state.json");
1603
+ }
1604
+ function yt(e) {
1605
+ let t = Ct(St(e.mcpUrl));
1606
1606
  return {
1607
- ...c({
1608
- provider: Mt(e.clientsStore),
1607
+ ...g({
1608
+ provider: Pt(e.clientsStore),
1609
1609
  issuerUrl: t,
1610
1610
  baseUrl: t
1611
1611
  }),
1612
1612
  grant_types_supported: ["authorization_code", "refresh_token"],
1613
1613
  token_endpoint_auth_methods_supported: ["none"],
1614
- scopes_supported: R,
1615
- service_documentation: z,
1614
+ scopes_supported: I,
1615
+ service_documentation: L,
1616
1616
  revocation_endpoint: new URL("/revoke", t).href,
1617
1617
  revocation_endpoint_auth_methods_supported: ["none"],
1618
1618
  client_id_metadata_document_supported: !1
1619
1619
  };
1620
1620
  }
1621
- function _t(e) {
1622
- let t = yt(e), n = {
1621
+ function bt(e) {
1622
+ let t = St(e), n = {
1623
1623
  resource: t.href,
1624
- authorization_servers: [bt(t).href],
1625
- scopes_supported: R,
1624
+ authorization_servers: [Ct(t).href],
1625
+ scopes_supported: I,
1626
1626
  bearer_methods_supported: ["header"],
1627
- resource_name: Ge,
1628
- resource_documentation: z
1627
+ resource_name: Je,
1628
+ resource_documentation: L
1629
1629
  };
1630
- return ce.parse(n);
1631
- }
1632
- function vt(e, t) {
1633
- let n = e.get("client_id") ?? "", r = e.get("redirect_uri") ?? "", i = e.get("response_type") ?? "", a = e.get("code_challenge") ?? "", o = e.get("code_challenge_method") ?? "", s = e.get("resource"), c = Dt(e.get("scope")), l = e.get("state");
1634
- if (i !== "code") return U("unsupported_response_type");
1635
- if (o !== "S256") return U("invalid_request", "PKCE code_challenge_method=S256 is required");
1636
- if (!rt.test(a)) return U("invalid_request", "Valid PKCE S256 code_challenge is required");
1637
- let u = Ot(t, n);
1630
+ return ue.parse(n);
1631
+ }
1632
+ function xt(e, t) {
1633
+ let n = e.get("client_id") ?? "", r = e.get("redirect_uri") ?? "", i = e.get("response_type") ?? "", a = e.get("code_challenge") ?? "", o = e.get("code_challenge_method") ?? "", s = e.get("resource"), c = At(e.get("scope")), l = e.get("state");
1634
+ if (i !== "code") return V("unsupported_response_type");
1635
+ if (o !== "S256") return V("invalid_request", "PKCE code_challenge_method=S256 is required");
1636
+ if (!ot.test(a)) return V("invalid_request", "Valid PKCE S256 code_challenge is required");
1637
+ let u = jt(t, n);
1638
1638
  return u ? u.redirect_uris.includes(r) ? {
1639
1639
  clientId: n,
1640
1640
  redirectUri: r,
@@ -1642,55 +1642,55 @@ function vt(e, t) {
1642
1642
  scopes: c,
1643
1643
  resource: s,
1644
1644
  state: l
1645
- } : U("invalid_request", "redirect_uri is not registered for this client") : U("invalid_client", "Unknown OAuth client_id");
1645
+ } : V("invalid_request", "redirect_uri is not registered for this client") : V("invalid_client", "Unknown OAuth client_id");
1646
1646
  }
1647
- function yt(e) {
1647
+ function St(e) {
1648
1648
  let t;
1649
1649
  try {
1650
1650
  t = new URL(e);
1651
1651
  } catch {
1652
1652
  throw Error("Invalid MCP HTTP public URL; expected an HTTPS /mcp URL");
1653
1653
  }
1654
- if (t.protocol !== "https:" && !Tt(t)) throw Error("Invalid MCP HTTP public URL; use HTTPS for non-loopback URLs");
1654
+ if (t.protocol !== "https:" && !Ot(t)) throw Error("Invalid MCP HTTP public URL; use HTTPS for non-loopback URLs");
1655
1655
  if (t.username || t.password || t.search || t.hash) throw Error("Invalid MCP HTTP public URL; credentials, query strings, and fragments are not allowed");
1656
1656
  if (t.pathname === "/" && (t.pathname = "/mcp"), t.pathname !== "/mcp") throw Error("Invalid MCP HTTP public URL; expected /mcp path");
1657
1657
  return t;
1658
1658
  }
1659
- function bt(e) {
1659
+ function Ct(e) {
1660
1660
  return new URL(e.origin);
1661
1661
  }
1662
- function xt(e) {
1662
+ function wt(e) {
1663
1663
  for (let t of e) {
1664
1664
  let e = new URL(t);
1665
1665
  if (e.username || e.password || e.hash) return "Invalid redirect URI";
1666
- if (!St(e) && !wt(e)) return "Unsupported redirect URI";
1666
+ if (!Tt(e) && !Dt(e)) return "Unsupported redirect URI";
1667
1667
  }
1668
1668
  return null;
1669
1669
  }
1670
- function St(e) {
1671
- return e.search === "" ? e.href === Ke || e.href === qe ? !0 : e.protocol === "https:" && e.hostname === "chatgpt.com" && Ct(e) : !1;
1670
+ function Tt(e) {
1671
+ return e.search === "" ? e.href === Ye || e.href === Xe ? !0 : e.protocol === "https:" && e.hostname === "chatgpt.com" && Et(e) : !1;
1672
1672
  }
1673
- function Ct(e) {
1673
+ function Et(e) {
1674
1674
  let t = e.pathname.split("/").filter(Boolean);
1675
- return t.length === 3 && t[0] === "connector" && t[1] === "oauth" && it.test(t[2] ?? "");
1675
+ return t.length === 3 && t[0] === "connector" && t[1] === "oauth" && st.test(t[2] ?? "");
1676
1676
  }
1677
- function H(e, t) {
1677
+ function B(e, t) {
1678
1678
  return e.length > 0 && e.every((e) => t.has(e));
1679
1679
  }
1680
- function wt(e) {
1681
- return e.protocol === "http:" && Je.has(Et(e.hostname)) && (e.pathname === "/callback" || e.pathname === "/oauth/callback") && e.search === "";
1680
+ function Dt(e) {
1681
+ return e.protocol === "http:" && Ze.has(kt(e.hostname)) && (e.pathname === "/callback" || e.pathname === "/oauth/callback") && e.search === "";
1682
1682
  }
1683
- function Tt(e) {
1684
- let t = Et(e.hostname);
1685
- return e.protocol === "http:" && Je.has(t);
1683
+ function Ot(e) {
1684
+ let t = kt(e.hostname);
1685
+ return e.protocol === "http:" && Ze.has(t);
1686
1686
  }
1687
- function Et(e) {
1687
+ function kt(e) {
1688
1688
  return e.replace(/^\[(.*)]$/, "$1").toLowerCase();
1689
1689
  }
1690
- function Dt(e) {
1690
+ function At(e) {
1691
1691
  return e?.split(/\s+/).map((e) => e.trim()).filter(Boolean) ?? [];
1692
1692
  }
1693
- function U(e, t) {
1693
+ function V(e, t) {
1694
1694
  return {
1695
1695
  status: 400,
1696
1696
  body: t ? {
@@ -1699,42 +1699,42 @@ function U(e, t) {
1699
1699
  } : { error: e }
1700
1700
  };
1701
1701
  }
1702
- function Ot(e, t) {
1702
+ function jt(e, t) {
1703
1703
  let n = e.getClient(t);
1704
1704
  if (n instanceof Promise) throw Error("Asynchronous OAuth client stores are not supported by this HTTP bootstrap yet");
1705
1705
  return n;
1706
1706
  }
1707
- function W(e) {
1708
- if (typeof e != "string" || e.length !== tt || !nt.test(e)) return null;
1707
+ function H(e) {
1708
+ if (typeof e != "string" || e.length !== it || !at.test(e)) return null;
1709
1709
  let t = Buffer.from(e, "base64url");
1710
- return t.length === et ? t : null;
1710
+ return t.length === rt ? t : null;
1711
1711
  }
1712
- function G() {
1713
- return _(et).toString("base64url");
1712
+ function U() {
1713
+ return a(rt).toString("base64url");
1714
1714
  }
1715
- function K(e, t) {
1716
- let n = W(e);
1717
- return n ? At(n, t) : null;
1715
+ function W(e, t) {
1716
+ let n = H(e);
1717
+ return n ? Mt(n, t) : null;
1718
1718
  }
1719
- function q(e) {
1720
- let t = W(e);
1721
- return t ? m("sha256").update(t).digest("base64url") : null;
1719
+ function G(e) {
1720
+ let t = H(e);
1721
+ return t ? n("sha256").update(t).digest("base64url") : null;
1722
1722
  }
1723
- function kt(e, t) {
1724
- return At(e, t);
1723
+ function K(e, t) {
1724
+ return Mt(e, t);
1725
1725
  }
1726
- function At(e, t) {
1727
- return h("sha256", t).update(e).digest("base64url");
1726
+ function Mt(e, t) {
1727
+ return r("sha256", t).update(e).digest("base64url");
1728
1728
  }
1729
- function J(e, t) {
1729
+ function q(e, t) {
1730
1730
  let n = Buffer.from(e), r = Buffer.from(t);
1731
- return n.length === r.length && y(n, r);
1731
+ return n.length === r.length && s(n, r);
1732
1732
  }
1733
- function jt(e, t) {
1733
+ function Nt(e, t) {
1734
1734
  let n = new Set(t);
1735
1735
  return e.every((e) => n.has(e));
1736
1736
  }
1737
- function Mt(e) {
1737
+ function Pt(e) {
1738
1738
  return {
1739
1739
  clientsStore: e,
1740
1740
  async authorize() {
@@ -1756,14 +1756,14 @@ function Mt(e) {
1756
1756
  }
1757
1757
  //#endregion
1758
1758
  //#region src/oidc.ts
1759
- var Nt = "CODEMEM_MCP_OIDC_ISSUER_URL", Pt = "CODEMEM_MCP_OIDC_CLIENT_ID", Ft = "CODEMEM_MCP_OIDC_CLIENT_SECRET", It = "CODEMEM_MCP_OAUTH_ALLOWED_SUBJECT", Lt = "CODEMEM_MCP_OAUTH_ALLOWED_EMAIL", Rt = 300 * 1e3, zt = 100, Bt = 300 * 1e3, Vt = class {
1759
+ var Ft = "CODEMEM_MCP_OIDC_ISSUER_URL", It = "CODEMEM_MCP_OIDC_CLIENT_ID", Lt = "CODEMEM_MCP_OIDC_CLIENT_SECRET", Rt = "CODEMEM_MCP_OAUTH_ALLOWED_SUBJECT", zt = "CODEMEM_MCP_OAUTH_ALLOWED_EMAIL", Bt = 300 * 1e3, Vt = 100, Ht = 300 * 1e3, Ut = class {
1760
1760
  #e = /* @__PURE__ */ new Map();
1761
1761
  issue(e, t = Date.now()) {
1762
- if (this.#t(t), this.#e.size >= zt) return;
1763
- let n = v();
1762
+ if (this.#t(t), this.#e.size >= Vt) return;
1763
+ let n = o();
1764
1764
  return this.#e.set(n, {
1765
1765
  ...e,
1766
- expiresAt: t + Rt
1766
+ expiresAt: t + Bt
1767
1767
  }), n;
1768
1768
  }
1769
1769
  consume(e) {
@@ -1774,14 +1774,14 @@ var Nt = "CODEMEM_MCP_OIDC_ISSUER_URL", Pt = "CODEMEM_MCP_OIDC_CLIENT_ID", Ft =
1774
1774
  for (let [t, n] of this.#e) n.expiresAt <= e && this.#e.delete(t);
1775
1775
  }
1776
1776
  };
1777
- function Ht() {
1778
- return new Vt();
1777
+ function Wt() {
1778
+ return new Ut();
1779
1779
  }
1780
- function Ut(e = process.env) {
1781
- let t = e[Nt]?.trim(), n = e[Pt]?.trim(), r = e[Ft]?.trim(), i = e[It]?.trim(), a = e[Lt]?.trim().toLowerCase();
1780
+ function Gt(e = process.env) {
1781
+ let t = e[Ft]?.trim(), n = e[It]?.trim(), r = e[Lt]?.trim(), i = e[Rt]?.trim(), a = e[zt]?.trim().toLowerCase();
1782
1782
  if (!(!t && !n && !r && !i && !a)) {
1783
1783
  if (!t || !n || !r) throw Error("Incomplete MCP OIDC configuration");
1784
- if (Y(t, "issuer", { allowLoopbackHttp: !0 }), !i && !a) throw Error("MCP OIDC requires CODEMEM_MCP_OAUTH_ALLOWED_SUBJECT or CODEMEM_MCP_OAUTH_ALLOWED_EMAIL");
1784
+ if (J(t, "issuer", { allowLoopbackHttp: !0 }), !i && !a) throw Error("MCP OIDC requires CODEMEM_MCP_OAUTH_ALLOWED_SUBJECT or CODEMEM_MCP_OAUTH_ALLOWED_EMAIL");
1785
1785
  return {
1786
1786
  issuerUrl: t,
1787
1787
  clientId: n,
@@ -1791,39 +1791,39 @@ function Ut(e = process.env) {
1791
1791
  };
1792
1792
  }
1793
1793
  }
1794
- async function Wt(e, t, n, r, i, a = Date.now()) {
1795
- if (!r) return X("temporarily_unavailable", "OIDC is not configured");
1796
- let o = vt(e, t);
1797
- if ("status" in o) return o;
1798
- let s = await qt(r.issuerUrl), c = v(), l = n.issue({
1794
+ async function Kt(e, t, n, r, i, a = Date.now()) {
1795
+ if (!r) return Y("temporarily_unavailable", "OIDC is not configured");
1796
+ let s = xt(e, t);
1797
+ if ("status" in s) return s;
1798
+ let c = await Yt(r.issuerUrl), l = o(), u = n.issue({
1799
1799
  oauthParams: e.toString(),
1800
- nonce: c
1800
+ nonce: l
1801
1801
  }, a);
1802
- if (!l) return X("temporarily_unavailable", "Too many pending OIDC authorizations");
1803
- let u = Kt(i), d = new URL(s.authorization_endpoint);
1804
- return d.searchParams.set("response_type", "code"), d.searchParams.set("client_id", r.clientId), d.searchParams.set("redirect_uri", u), d.searchParams.set("scope", "openid email"), d.searchParams.set("state", l), d.searchParams.set("nonce", c), {
1802
+ if (!u) return Y("temporarily_unavailable", "Too many pending OIDC authorizations");
1803
+ let d = Jt(i), f = new URL(c.authorization_endpoint);
1804
+ return f.searchParams.set("response_type", "code"), f.searchParams.set("client_id", r.clientId), f.searchParams.set("redirect_uri", d), f.searchParams.set("scope", "openid email"), f.searchParams.set("state", u), f.searchParams.set("nonce", l), {
1805
1805
  status: 302,
1806
- location: d.href
1806
+ location: f.href
1807
1807
  };
1808
1808
  }
1809
- async function Gt(e, t, n, r, i = Date.now()) {
1809
+ async function qt(e, t, n, r, i = Date.now()) {
1810
1810
  try {
1811
1811
  let a = e.get("code") ?? "", o = e.get("state") ?? "";
1812
- if (!o) return X("invalid_request", "Missing OIDC state");
1812
+ if (!o) return Y("invalid_request", "Missing OIDC state");
1813
1813
  let s = t.consume(o);
1814
- if (!s || s.expiresAt <= i) return X("invalid_request", "Expired or unknown OIDC state");
1815
- if (!a) return X("invalid_request", "Missing OIDC code");
1816
- let c = await qt(n.issuerUrl), l = await Jt(c.token_endpoint, n, Kt(r), a);
1817
- return l.id_token ? $t(await Yt(l.id_token, c, n.clientId, s.nonce, i), n) ? { oauthParams: new URLSearchParams(s.oauthParams) } : X("access_denied", "OIDC identity is not allowed") : X("invalid_request", "OIDC token exchange failed");
1814
+ if (!s || s.expiresAt <= i) return Y("invalid_request", "Expired or unknown OIDC state");
1815
+ if (!a) return Y("invalid_request", "Missing OIDC code");
1816
+ let c = await Yt(n.issuerUrl), l = await Xt(c.token_endpoint, n, Jt(r), a);
1817
+ return l.id_token ? tn(await Zt(l.id_token, c, n.clientId, s.nonce, i), n) ? { oauthParams: new URLSearchParams(s.oauthParams) } : Y("access_denied", "OIDC identity is not allowed") : Y("invalid_request", "OIDC token exchange failed");
1818
1818
  } catch {
1819
- return X("access_denied", "OIDC identity verification failed");
1819
+ return Y("access_denied", "OIDC identity verification failed");
1820
1820
  }
1821
1821
  }
1822
- function Kt(e) {
1822
+ function Jt(e) {
1823
1823
  let t = new URL(e);
1824
1824
  return new URL("/oauth/callback", t.origin).href;
1825
1825
  }
1826
- async function qt(e) {
1826
+ async function Yt(e) {
1827
1827
  let t = new URL(e);
1828
1828
  if (t.search || t.hash) throw Error("OIDC issuer must not include query or fragment");
1829
1829
  if (t.username || t.password) throw Error("OIDC issuer must not include credentials");
@@ -1832,10 +1832,10 @@ async function qt(e) {
1832
1832
  let i = await r.json();
1833
1833
  if (i.issuer !== t.href && i.issuer !== t.href.replace(/\/$/, "")) throw Error("OIDC discovery issuer mismatch");
1834
1834
  if (!i.authorization_endpoint || !i.token_endpoint || !i.jwks_uri) throw Error("OIDC discovery metadata is incomplete");
1835
- let a = t.protocol === "http:" && en(t.hostname);
1836
- return Y(i.authorization_endpoint, "authorization endpoint", { allowLoopbackHttp: a }), Y(i.token_endpoint, "token endpoint", { allowLoopbackHttp: a }), Y(i.jwks_uri, "JWKS URI", { allowLoopbackHttp: a }), i;
1835
+ let a = t.protocol === "http:" && nn(t.hostname);
1836
+ return J(i.authorization_endpoint, "authorization endpoint", { allowLoopbackHttp: a }), J(i.token_endpoint, "token endpoint", { allowLoopbackHttp: a }), J(i.jwks_uri, "JWKS URI", { allowLoopbackHttp: a }), i;
1837
1837
  }
1838
- async function Jt(e, t, n, r) {
1838
+ async function Xt(e, t, n, r) {
1839
1839
  let i = new URLSearchParams({
1840
1840
  grant_type: "authorization_code",
1841
1841
  code: r,
@@ -1850,52 +1850,52 @@ async function Jt(e, t, n, r) {
1850
1850
  if (!a.ok) throw Error("OIDC token request failed");
1851
1851
  return await a.json();
1852
1852
  }
1853
- async function Yt(e, t, n, r, i) {
1854
- let [a, o, s] = e.split(".");
1855
- if (!a || !o || !s) throw Error("Invalid OIDC id_token");
1856
- let c = Xt(a), l = Xt(o);
1857
- if (c.alg !== "RS256" || !c.kid) throw Error("Unsupported OIDC id_token signature");
1858
- if (l.iss !== t.issuer) throw Error("OIDC id_token issuer mismatch");
1859
- if (!Zt(l.aud, n)) throw Error("OIDC id_token audience mismatch");
1860
- if (!Qt(l.aud, l.azp, n)) throw Error("OIDC id_token authorized party mismatch");
1861
- if (typeof l.exp != "number" || !Number.isFinite(l.exp) || l.exp * 1e3 <= i) throw Error("OIDC id_token is expired");
1862
- if (typeof l.iat != "number" || !Number.isFinite(l.iat)) throw Error("OIDC id_token issued-at time is missing");
1863
- if (l.iat * 1e3 > i + Bt) throw Error("OIDC id_token issued-at time is in the future");
1864
- if (l.nonce !== r) throw Error("OIDC id_token nonce mismatch");
1865
- if (!l.sub) throw Error("OIDC id_token subject is missing");
1866
- let u = await fetch(t.jwks_uri);
1867
- if (!u.ok) throw Error("OIDC JWKS request failed");
1868
- let d = (await u.json()).keys?.find((e) => e.kid === c.kid && e.kty === "RSA");
1869
- if (!d) throw Error("OIDC signing key not found");
1870
- let f = g({
1871
- key: d,
1853
+ async function Zt(e, t, n, r, a) {
1854
+ let [o, s, l] = e.split(".");
1855
+ if (!o || !s || !l) throw Error("Invalid OIDC id_token");
1856
+ let u = Qt(o), d = Qt(s);
1857
+ if (u.alg !== "RS256" || !u.kid) throw Error("Unsupported OIDC id_token signature");
1858
+ if (d.iss !== t.issuer) throw Error("OIDC id_token issuer mismatch");
1859
+ if (!$t(d.aud, n)) throw Error("OIDC id_token audience mismatch");
1860
+ if (!en(d.aud, d.azp, n)) throw Error("OIDC id_token authorized party mismatch");
1861
+ if (typeof d.exp != "number" || !Number.isFinite(d.exp) || d.exp * 1e3 <= a) throw Error("OIDC id_token is expired");
1862
+ if (typeof d.iat != "number" || !Number.isFinite(d.iat)) throw Error("OIDC id_token issued-at time is missing");
1863
+ if (d.iat * 1e3 > a + Ht) throw Error("OIDC id_token issued-at time is in the future");
1864
+ if (d.nonce !== r) throw Error("OIDC id_token nonce mismatch");
1865
+ if (!d.sub) throw Error("OIDC id_token subject is missing");
1866
+ let f = await fetch(t.jwks_uri);
1867
+ if (!f.ok) throw Error("OIDC JWKS request failed");
1868
+ let p = (await f.json()).keys?.find((e) => e.kid === u.kid && e.kty === "RSA");
1869
+ if (!p) throw Error("OIDC signing key not found");
1870
+ let m = i({
1871
+ key: p,
1872
1872
  format: "jwk"
1873
- }), p = `${a}.${o}`;
1874
- if (!b("RSA-SHA256", Buffer.from(p), f, Buffer.from(s, "base64url"))) throw Error("OIDC id_token signature verification failed");
1875
- return l;
1873
+ }), h = `${o}.${s}`;
1874
+ if (!c("RSA-SHA256", Buffer.from(h), m, Buffer.from(l, "base64url"))) throw Error("OIDC id_token signature verification failed");
1875
+ return d;
1876
1876
  }
1877
- function Xt(e) {
1877
+ function Qt(e) {
1878
1878
  return JSON.parse(Buffer.from(e, "base64url").toString("utf8"));
1879
1879
  }
1880
- function Zt(e, t) {
1880
+ function $t(e, t) {
1881
1881
  return Array.isArray(e) ? e.includes(t) : e === t;
1882
1882
  }
1883
- function Qt(e, t, n) {
1883
+ function en(e, t, n) {
1884
1884
  return t && t !== n ? !1 : !Array.isArray(e) || e.length <= 1 || t === n;
1885
1885
  }
1886
- function $t(e, t) {
1886
+ function tn(e, t) {
1887
1887
  return t.allowedSubject && e.sub === t.allowedSubject ? !0 : t.allowedEmail ? e.email_verified === !0 && e.email?.toLowerCase() === t.allowedEmail : !1;
1888
1888
  }
1889
- function Y(e, t, n = {}) {
1889
+ function J(e, t, n = {}) {
1890
1890
  let r = new URL(e);
1891
1891
  if (r.username || r.password) throw Error(`OIDC ${t} must not include credentials`);
1892
- if (r.protocol !== "https:" && !(n.allowLoopbackHttp && r.protocol === "http:" && en(r.hostname))) throw Error(`OIDC ${t} must use HTTPS`);
1892
+ if (r.protocol !== "https:" && !(n.allowLoopbackHttp && r.protocol === "http:" && nn(r.hostname))) throw Error(`OIDC ${t} must use HTTPS`);
1893
1893
  }
1894
- function en(e) {
1894
+ function nn(e) {
1895
1895
  let t = e.replace(/^\[(.*)]$/, "$1").toLowerCase();
1896
1896
  return t === "localhost" || t === "127.0.0.1" || t === "::1";
1897
1897
  }
1898
- function X(e, t) {
1898
+ function Y(e, t) {
1899
1899
  return {
1900
1900
  status: 400,
1901
1901
  body: t ? {
@@ -1906,7 +1906,7 @@ function X(e, t) {
1906
1906
  }
1907
1907
  //#endregion
1908
1908
  //#region src/provider.ts
1909
- var tn = class {
1909
+ var rn = class {
1910
1910
  #e;
1911
1911
  #t;
1912
1912
  #n;
@@ -1916,44 +1916,44 @@ var tn = class {
1916
1916
  #o;
1917
1917
  #s;
1918
1918
  constructor(e) {
1919
- this.#e = e.clientsStore, this.#t = e.codeStore, this.#n = e.tokenStore, this.#r = e.refreshTokenStore ?? pt(), this.#i = e.publicMcpUrl, this.#a = new URL(e.publicMcpUrl).href, this.#o = e.oidc, this.#s = e.now ?? Date.now;
1919
+ this.#e = e.clientsStore, this.#t = e.codeStore, this.#n = e.tokenStore, this.#r = e.refreshTokenStore ?? gt(), this.#i = e.publicMcpUrl, this.#a = new URL(e.publicMcpUrl).href, this.#o = e.oidc, this.#s = e.now ?? Date.now;
1920
1920
  }
1921
1921
  get clientsStore() {
1922
1922
  return this.#e;
1923
1923
  }
1924
1924
  async authorize(e, t, n) {
1925
- if (!this.#o) throw new A("OIDC is not configured");
1926
- let r = await Wt(nn(e, t), this.#e, this.#o.pendingStore, this.#o.config, this.#i, this.#s());
1925
+ if (!this.#o) throw new k("OIDC is not configured");
1926
+ let r = await Kt(an(e, t), this.#e, this.#o.pendingStore, this.#o.config, this.#i, this.#s());
1927
1927
  if (r.status === 302) {
1928
1928
  n.redirect(302, r.location);
1929
1929
  return;
1930
1930
  }
1931
- throw rn(r.body);
1931
+ throw on(r.body);
1932
1932
  }
1933
1933
  async challengeForAuthorizationCode(e, t) {
1934
1934
  let n = this.#t.peekCode(t);
1935
- if (!n) throw new k("Invalid or already used code");
1936
- if (n.clientId !== e.client_id) throw new k("Code does not match client");
1937
- if (n.expiresAt <= this.#s()) throw this.#t.consumeCode(t), new k("Expired code");
1935
+ if (!n) throw new O("Invalid or already used code");
1936
+ if (n.clientId !== e.client_id) throw new O("Code does not match client");
1937
+ if (n.expiresAt <= this.#s()) throw this.#t.consumeCode(t), new O("Expired code");
1938
1938
  return n.codeChallenge;
1939
1939
  }
1940
1940
  async exchangeAuthorizationCode(e, t, n, r, i) {
1941
1941
  let a = this.#s(), o = this.#t.peekCode(t);
1942
- if (!o) throw new k("Invalid or already used code");
1943
- if (o.expiresAt <= a) throw this.#t.consumeCode(t), new k("Expired code");
1944
- if (o.clientId !== e.client_id) throw this.#t.consumeCode(t), new k("Code does not match client");
1945
- if (r === void 0 || o.redirectUri !== r) throw this.#t.consumeCode(t), new k("Code does not match redirect_uri");
1946
- if ((o.resource ?? null) !== (i?.href ?? null)) throw this.#t.consumeCode(t), new k("Code does not match resource");
1947
- let s = on(o.scopes) ?? [], c = this.#r.issueGrant({
1942
+ if (!o) throw new O("Invalid or already used code");
1943
+ if (o.expiresAt <= a) throw this.#t.consumeCode(t), new O("Expired code");
1944
+ if (o.clientId !== e.client_id) throw this.#t.consumeCode(t), new O("Code does not match client");
1945
+ if (r === void 0 || o.redirectUri !== r) throw this.#t.consumeCode(t), new O("Code does not match redirect_uri");
1946
+ if ((o.resource ?? null) !== (i?.href ?? null)) throw this.#t.consumeCode(t), new O("Code does not match resource");
1947
+ let s = cn(o.scopes) ?? [], c = this.#r.issueGrant({
1948
1948
  clientId: e.client_id,
1949
1949
  scopes: s,
1950
1950
  resource: o.resource
1951
1951
  }, a);
1952
- if (!c) throw new A("Too many active refresh grants");
1952
+ if (!c) throw new k("Too many active refresh grants");
1953
1953
  let l = this.#n.issueToken(e.client_id, a, o.resource, c.grant.grantId, s);
1954
- if (!l) throw this.#r.revokeGrant(c.grant.grantId, a), new A("Too many active access tokens");
1955
- if (!this.#t.consumeCode(t)) throw this.#n.revokeToken(l.token, a), this.#r.revokeGrant(c.grant.grantId, a), new k("Authorization code already used");
1956
- return le.parse({
1954
+ if (!l) throw this.#r.revokeGrant(c.grant.grantId, a), new k("Too many active access tokens");
1955
+ if (!this.#t.consumeCode(t)) throw this.#n.revokeToken(l.token, a), this.#r.revokeGrant(c.grant.grantId, a), new O("Authorization code already used");
1956
+ return de.parse({
1957
1957
  access_token: l.token,
1958
1958
  token_type: "Bearer",
1959
1959
  expires_in: l.expiresIn,
@@ -1962,13 +1962,13 @@ var tn = class {
1962
1962
  }
1963
1963
  async exchangeRefreshToken(e, t, n, r) {
1964
1964
  let i = this.#s(), a = this.#r.rotateRefreshToken(e.client_id, t, {
1965
- scopes: on(n),
1965
+ scopes: cn(n),
1966
1966
  ...r ? { resource: r.href } : {}
1967
1967
  }, i);
1968
- if (!a.ok) throw a.reason === "refresh_token_replay" && a.grantId && this.#n.revokeTokensForGrant?.(a.grantId, i), new k(an(a.reason));
1968
+ if (!a.ok) throw a.reason === "refresh_token_replay" && a.grantId && this.#n.revokeTokensForGrant?.(a.grantId, i), new O(sn(a.reason));
1969
1969
  let o = this.#n.issueToken(e.client_id, i, a.grant.resource, a.grant.grantId, a.grant.scopes);
1970
- if (!o) throw new A("Too many active access tokens");
1971
- return le.parse({
1970
+ if (!o) throw new k("Too many active access tokens");
1971
+ return de.parse({
1972
1972
  access_token: o.token,
1973
1973
  token_type: "Bearer",
1974
1974
  expires_in: o.expiresIn,
@@ -1977,7 +1977,7 @@ var tn = class {
1977
1977
  }
1978
1978
  async verifyAccessToken(e) {
1979
1979
  let t = this.#n.verifyToken(e, this.#s());
1980
- if (!t.ok) throw new ae(t.reason === "expired_token" ? "Token has expired" : t.reason === "revoked_token" ? "Token has been revoked" : "Token is invalid");
1980
+ if (!t.ok) throw new se(t.reason === "expired_token" ? "Token has expired" : t.reason === "revoked_token" ? "Token has been revoked" : "Token is invalid");
1981
1981
  let n = {
1982
1982
  token: e,
1983
1983
  clientId: t.record.clientId,
@@ -1985,7 +1985,7 @@ var tn = class {
1985
1985
  expiresAt: Math.floor(t.record.expiresAt / 1e3)
1986
1986
  };
1987
1987
  if (t.record.resource) {
1988
- if (new URL(t.record.resource).href !== this.#a) throw new ae("Token audience does not match this resource server");
1988
+ if (new URL(t.record.resource).href !== this.#a) throw new se("Token audience does not match this resource server");
1989
1989
  n.resource = new URL(t.record.resource);
1990
1990
  }
1991
1991
  return n;
@@ -1997,22 +1997,22 @@ var tn = class {
1997
1997
  r && this.#n.revokeTokensForGrant?.(r, n);
1998
1998
  }
1999
1999
  };
2000
- function nn(e, t) {
2000
+ function an(e, t) {
2001
2001
  let n = new URLSearchParams();
2002
2002
  return n.set("client_id", e.client_id), n.set("redirect_uri", t.redirectUri), n.set("response_type", "code"), n.set("code_challenge", t.codeChallenge), n.set("code_challenge_method", "S256"), t.state && n.set("state", t.state), t.scopes?.length && n.set("scope", t.scopes.join(" ")), t.resource && n.set("resource", t.resource.href), n;
2003
2003
  }
2004
- function rn(e) {
2004
+ function on(e) {
2005
2005
  let t = e.error_description ?? e.error;
2006
2006
  switch (e.error) {
2007
- case "temporarily_unavailable": return new A(t);
2008
- case "invalid_request": return new ie(t);
2009
- case "invalid_client": return new re(t);
2010
- case "access_denied": return new ne(t);
2011
- case "unsupported_response_type": return new se(t);
2012
- default: return new oe(t);
2007
+ case "temporarily_unavailable": return new k(t);
2008
+ case "invalid_request": return new oe(t);
2009
+ case "invalid_client": return new ae(t);
2010
+ case "access_denied": return new E(t);
2011
+ case "unsupported_response_type": return new le(t);
2012
+ default: return new ce(t);
2013
2013
  }
2014
2014
  }
2015
- function an(e) {
2015
+ function sn(e) {
2016
2016
  switch (e) {
2017
2017
  case "expired_refresh_token": return "Refresh token has expired";
2018
2018
  case "revoked_refresh_token": return "Refresh token has been revoked";
@@ -2023,34 +2023,42 @@ function an(e) {
2023
2023
  default: return "Invalid refresh token";
2024
2024
  }
2025
2025
  }
2026
- function on(e) {
2026
+ function cn(e) {
2027
2027
  let t = e?.map((e) => e.trim()).filter(Boolean).map((e) => e === "memory:read_access" ? "memory:read" : e === "memory:write_access" ? "memory:write" : e);
2028
2028
  return t && t.length > 0 ? t : void 0;
2029
2029
  }
2030
2030
  //#endregion
2031
2031
  //#region src/http.ts
2032
- var sn = "127.0.0.1", cn = 38889, ln = 80, un = new Set(["https://chatgpt.com", "https://claude.ai"]), dn = "authorization,content-type,mcp-session-id", fn = "600", pn = 256, mn = 900 * 1e3, hn = 600, gn = /^[a-zA-Z0-9.-]+$/, _n = new Set([
2032
+ var ln = "127.0.0.1", X = 38889, un = 80, dn = new Set(["https://chatgpt.com", "https://claude.ai"]), fn = "authorization,content-type,mcp-session-id", pn = "600", mn = 256, hn = 900 * 1e3, gn = 600, _n = 4 * 1024 * 1024, vn = 300 * 1e3, yn = 2e3, bn = /^[a-zA-Z0-9.-]+$/, xn = new Set([
2033
2033
  "127.0.0.1",
2034
2034
  "::1",
2035
2035
  "localhost"
2036
2036
  ]);
2037
- function vn(e, t = !1) {
2038
- let r = e?.trim() || "127.0.0.1";
2039
- if (r.includes("://") || r.includes("/") || r.includes("\\") || !(n(r) || r === "localhost" || gn.test(r))) throw Error(`Invalid MCP HTTP host: ${e}`);
2040
- if (!t && !Z(r)) throw Error(`Refusing unsafe MCP HTTP host ${r}; set CODEMEM_MCP_HTTP_UNSAFE_PUBLIC=1 to allow non-loopback binding`);
2041
- return r;
2037
+ function Sn(t) {
2038
+ let n = t?.extra?.sub;
2039
+ if (typeof n == "string" && n.trim().length > 0) {
2040
+ let r = n.trim(), i = t?.clientId?.trim();
2041
+ return i ? `subject-client:${e([r, i])}` : `subject:${r}`;
2042
+ }
2043
+ return t?.token ? `token:${t.token}` : void 0;
2044
+ }
2045
+ function Cn(e, t = !1) {
2046
+ let n = e?.trim() || "127.0.0.1";
2047
+ if (n.includes("://") || n.includes("/") || n.includes("\\") || !(u(n) || n === "localhost" || bn.test(n))) throw Error(`Invalid MCP HTTP host: ${e}`);
2048
+ if (!t && !Z(n)) throw Error(`Refusing unsafe MCP HTTP host ${n}; set CODEMEM_MCP_HTTP_UNSAFE_PUBLIC=1 to allow non-loopback binding`);
2049
+ return n;
2042
2050
  }
2043
2051
  function Z(e) {
2044
- return _n.has(Q(e));
2052
+ return xn.has(Q(e));
2045
2053
  }
2046
- function yn(e = process.env.CODEMEM_MCP_HTTP_UNSAFE_PUBLIC) {
2054
+ function wn(e = process.env.CODEMEM_MCP_HTTP_UNSAFE_PUBLIC) {
2047
2055
  return e === "1" || e?.toLowerCase() === "true" || e?.toLowerCase() === "yes";
2048
2056
  }
2049
- function bn(e, t) {
2050
- let n = Cn(e);
2051
- return !n || !Z(n.host) ? !1 : n.port === null ? t === ln : n.port === t;
2057
+ function Tn(e, t) {
2058
+ let n = On(e);
2059
+ return !n || !Z(n.host) ? !1 : n.port === null ? t === un : n.port === t;
2052
2060
  }
2053
- function xn(e, t) {
2061
+ function En(e, t) {
2054
2062
  if (!e) return !0;
2055
2063
  try {
2056
2064
  let n = new URL(e), r = n.port ? Number(n.port) : n.protocol === "https:" ? 443 : 80;
@@ -2059,13 +2067,13 @@ function xn(e, t) {
2059
2067
  return !1;
2060
2068
  }
2061
2069
  }
2062
- function Sn(e) {
2070
+ function Dn(e) {
2063
2071
  return e ? Z(e.replace(/^::ffff:/, "")) : !1;
2064
2072
  }
2065
2073
  function Q(e) {
2066
2074
  return e.replace(/^\[(.*)]$/, "$1").toLowerCase();
2067
2075
  }
2068
- function Cn(e) {
2076
+ function On(e) {
2069
2077
  if (!e) return null;
2070
2078
  if (e.startsWith("[")) {
2071
2079
  let t = /^\[([^\]]+)]:(\d+)$/.exec(e);
@@ -2090,70 +2098,70 @@ function Cn(e) {
2090
2098
  port: r
2091
2099
  } : null;
2092
2100
  }
2093
- function wn(e) {
2094
- if (e === void 0 || e === "") return cn;
2101
+ function kn(e) {
2102
+ if (e === void 0 || e === "") return X;
2095
2103
  let t = typeof e == "number" ? e : Number(e);
2096
2104
  if (!Number.isInteger(t) || t < 0 || t > 65535) throw Error(`Invalid MCP HTTP port: ${e}`);
2097
2105
  return t;
2098
2106
  }
2099
- async function Tn(n = {}) {
2100
- let r = vn(n.host ?? process.env.CODEMEM_MCP_HTTP_HOST, n.allowUnsafePublic ?? yn()), i = wn(n.port ?? process.env.CODEMEM_MCP_HTTP_PORT), c = n.publicUrl ?? process.env.CODEMEM_MCP_HTTP_PUBLIC_URL, p = c ? yt(c) : void 0, m = new a(n.dbPath ?? o()), h = n.oauthAccessTokenStore ? void 0 : mt(n.oauthStatePath), g = h ?? ut(), _ = h ?? dt(), v = n.oauthAccessTokenStore ?? h ?? ft(), y = Ut(), b = Ht(), x = p !== void 0 || y !== void 0, S = Ve(n.auditEmitter ?? We()), C = /* @__PURE__ */ new Set(), ee = null, w = f();
2101
- w.disable("x-powered-by"), w.set("trust proxy", "loopback");
2102
- let T = t(w);
2107
+ async function An(e = {}) {
2108
+ let n = Cn(e.host ?? process.env.CODEMEM_MCP_HTTP_HOST, e.allowUnsafePublic ?? wn()), r = kn(e.port ?? process.env.CODEMEM_MCP_HTTP_PORT), i = e.publicUrl ?? process.env.CODEMEM_MCP_HTTP_PUBLIC_URL, a = i ? St(i) : void 0, o = new p(e.dbPath ?? m()), s = e.oauthAccessTokenStore ? void 0 : _t(e.oauthStatePath), c = s ?? pt(), u = s ?? mt(), d = e.oauthAccessTokenStore ?? s ?? ht(), f = Gt(), g = Wt(), _ = a !== void 0 || f !== void 0, v = We(e.auditEmitter ?? qe()), y = /* @__PURE__ */ new Set(), ie = Hn(), b = null, x = re();
2109
+ x.disable("x-powered-by"), x.set("trust proxy", "loopback");
2110
+ let S = l(x);
2103
2111
  await new Promise((e, t) => {
2104
- T.once("error", t), T.listen({
2105
- host: r,
2106
- port: i
2112
+ S.once("error", t), S.listen({
2113
+ host: n,
2114
+ port: r
2107
2115
  }, () => {
2108
- T.off("error", t), e();
2116
+ S.off("error", t), e();
2109
2117
  });
2110
2118
  });
2111
- let E = p?.href ?? In(T, r), D = new URL(E), te = Ln(D, $(T)), ne = new tn({
2112
- clientsStore: g,
2113
- codeStore: _,
2114
- tokenStore: v,
2115
- publicMcpUrl: E,
2116
- ...h ? { refreshTokenStore: h } : {},
2117
- ...y ? { oidc: {
2118
- config: y,
2119
- pendingStore: b
2119
+ let C = a?.href ?? Vn(S, n), w = new URL(C), T = Kn(w, $(S)), E = new rn({
2120
+ clientsStore: c,
2121
+ codeStore: u,
2122
+ tokenStore: d,
2123
+ publicMcpUrl: C,
2124
+ ...s ? { refreshTokenStore: s } : {},
2125
+ ...f ? { oidc: {
2126
+ config: f,
2127
+ pendingStore: g
2120
2128
  } } : {}
2121
- }), re = l(D);
2122
- w.use(Re({
2123
- windowMs: mn,
2124
- limit: hn,
2129
+ }), ae = ee(w);
2130
+ x.use(Ve({
2131
+ windowMs: hn,
2132
+ limit: gn,
2125
2133
  standardHeaders: "draft-8",
2126
2134
  legacyHeaders: !1,
2127
2135
  ipv6Subnet: !1
2128
- })), w.use((e, t, n) => {
2129
- let r = $(T), i = zn(e.path);
2136
+ })), x.use((e, t, n) => {
2137
+ let r = $(S), i = Jn(e.path);
2130
2138
  if (i === "/mcp") {
2131
- if (En(e, r, p)) {
2132
- if (An(e, t, p), e.method === "OPTIONS") {
2139
+ if (jn(e, r, a)) {
2140
+ if (Fn(e, t, a), e.method === "OPTIONS") {
2133
2141
  t.status(204).send("");
2134
2142
  return;
2135
2143
  }
2136
2144
  return n();
2137
2145
  }
2138
- Mn(e, i, p), t.status(403).type("text/plain").send("Forbidden");
2146
+ Ln(e, i, a), t.status(403).type("text/plain").send("Forbidden");
2139
2147
  return;
2140
2148
  }
2141
- if (Rn(i)) {
2142
- if (On(e, r, p)) {
2143
- if (An(e, t, p), e.method === "OPTIONS") {
2149
+ if (qn(i)) {
2150
+ if (Nn(e, r, a)) {
2151
+ if (Fn(e, t, a), e.method === "OPTIONS") {
2144
2152
  t.status(204).send("");
2145
2153
  return;
2146
2154
  }
2147
2155
  return n();
2148
2156
  }
2149
- Mn(e, i, p), t.status(403).type("text/plain").send("Forbidden");
2157
+ Ln(e, i, a), t.status(403).type("text/plain").send("Forbidden");
2150
2158
  return;
2151
2159
  }
2152
2160
  n();
2153
- }), w.use(Bn(S)), w.get("/oauth/callback", async (e, t) => {
2161
+ }), x.use(Yn(v)), x.get("/oauth/callback", async (e, t) => {
2154
2162
  let n = e.socket.remoteAddress ?? void 0;
2155
- if (!y) {
2156
- S(L("oidc_callback", {
2163
+ if (!f) {
2164
+ v(F("oidc_callback", {
2157
2165
  outcome: "denied",
2158
2166
  reason: "oidc_not_configured",
2159
2167
  remoteAddress: n
@@ -2163,25 +2171,25 @@ async function Tn(n = {}) {
2163
2171
  });
2164
2172
  return;
2165
2173
  }
2166
- let r = await Gt(new URLSearchParams(e.query), b, y, E);
2174
+ let r = await qt(new URLSearchParams(e.query), g, f, C);
2167
2175
  if ("status" in r) {
2168
- S(L("oidc_callback", {
2176
+ v(F("oidc_callback", {
2169
2177
  outcome: "denied",
2170
2178
  reason: r.body.error,
2171
2179
  remoteAddress: n
2172
2180
  })), t.status(r.status).json(r.body);
2173
2181
  return;
2174
2182
  }
2175
- let i = r.oauthParams.get("client_id") ?? void 0, a = _.issueCode({
2183
+ let i = r.oauthParams.get("client_id") ?? void 0, a = u.issueCode({
2176
2184
  clientId: r.oauthParams.get("client_id") ?? "",
2177
2185
  redirectUri: r.oauthParams.get("redirect_uri") ?? "",
2178
2186
  codeChallenge: r.oauthParams.get("code_challenge") ?? "",
2179
- scopes: Yn(r.oauthParams.get("scope")),
2187
+ scopes: ir(r.oauthParams.get("scope")),
2180
2188
  ...r.oauthParams.get("resource") ? { resource: r.oauthParams.get("resource") ?? void 0 } : {},
2181
2189
  expiresAt: Date.now() + 300 * 1e3
2182
2190
  });
2183
2191
  if (!a) {
2184
- S(L("oidc_callback", {
2192
+ v(F("oidc_callback", {
2185
2193
  outcome: "denied",
2186
2194
  reason: "temporarily_unavailable",
2187
2195
  clientId: i,
@@ -2195,99 +2203,107 @@ async function Tn(n = {}) {
2195
2203
  let o = new URL(r.oauthParams.get("redirect_uri") ?? "");
2196
2204
  o.searchParams.set("code", a);
2197
2205
  let s = r.oauthParams.get("state");
2198
- s && o.searchParams.set("state", s), S(L("oidc_callback", {
2206
+ s && o.searchParams.set("state", s), v(F("oidc_callback", {
2199
2207
  outcome: "success",
2200
2208
  reason: "code_issued",
2201
2209
  clientId: i,
2202
2210
  remoteAddress: n
2203
2211
  })), t.redirect(302, o.href);
2204
- }), w.get("/.well-known/oauth-authorization-server", (e, t) => {
2205
- t.status(200).json(gt({
2206
- mcpUrl: E,
2207
- clientsStore: g
2212
+ }), x.get("/.well-known/oauth-authorization-server", (e, t) => {
2213
+ t.status(200).json(yt({
2214
+ mcpUrl: C,
2215
+ clientsStore: c
2208
2216
  }));
2209
- }), w.get("/.well-known/oauth-protected-resource/mcp", (e, t) => {
2210
- t.status(200).json(_t(E));
2211
- }), w.use(u({
2212
- provider: ne,
2213
- issuerUrl: te,
2214
- baseUrl: te,
2215
- resourceServerUrl: D,
2216
- resourceName: Ge,
2217
- scopesSupported: R,
2218
- serviceDocumentationUrl: new URL(z),
2217
+ }), x.get("/.well-known/oauth-protected-resource/mcp", (e, t) => {
2218
+ t.status(200).json(bt(C));
2219
+ }), x.use(te({
2220
+ provider: E,
2221
+ issuerUrl: T,
2222
+ baseUrl: T,
2223
+ resourceServerUrl: w,
2224
+ resourceName: Je,
2225
+ scopesSupported: I,
2226
+ serviceDocumentationUrl: new URL(L),
2219
2227
  clientRegistrationOptions: { clientSecretExpirySeconds: 0 }
2220
2228
  }));
2221
- let O = x ? s({
2222
- verifier: ne,
2223
- resourceMetadataUrl: re
2224
- }) : (e, t, n) => n(), k = x ? qn(S, v) : (e, t, n) => n();
2225
- return w.post("/mcp", k, O, async (t, n) => {
2226
- t.auth && S(L("bearer", {
2229
+ let D = _ ? h({
2230
+ verifier: E,
2231
+ resourceMetadataUrl: ae
2232
+ }) : (e, t, n) => n(), O = _ ? nr(v, d) : (e, t, n) => n();
2233
+ return x.post("/mcp", O, D, re.json({ limit: _n }), async (n, r) => {
2234
+ n.auth && v(F("bearer", {
2227
2235
  outcome: "success",
2228
- clientId: t.auth.clientId,
2229
- remoteAddress: t.socket.remoteAddress ?? void 0
2236
+ clientId: n.auth.clientId,
2237
+ remoteAddress: n.socket.remoteAddress ?? void 0
2230
2238
  }));
2231
- let r = e(m), i = new d({ sessionIdGenerator: void 0 }), a = { mcpServer: r };
2232
- C.add(a);
2239
+ let i = t(o, {
2240
+ retrievalLedgerScopeId: ie({
2241
+ endpoint: w,
2242
+ principal: Sn(n.auth),
2243
+ requestBody: n.body,
2244
+ now: e.retrievalLedgerNow?.() ?? Date.now()
2245
+ }),
2246
+ retrievalLedgerIdentityMode: "stateless"
2247
+ }), a = new ne({ sessionIdGenerator: void 0 }), s = { mcpServer: i };
2248
+ y.add(s);
2233
2249
  try {
2234
- await r.connect(i), await i.handleRequest(t, n);
2250
+ await i.connect(a), await a.handleRequest(n, r, n.body);
2235
2251
  } finally {
2236
- C.delete(a), await r.close();
2252
+ y.delete(s), await i.close();
2237
2253
  }
2238
- }), w.all("/mcp", (e, t) => {
2254
+ }, Wn), x.all("/mcp", (e, t) => {
2239
2255
  t.setHeader("Allow", "POST"), t.status(405).type("text/plain").send("Method not allowed");
2240
- }), w.use((e, t) => {
2256
+ }), x.use((e, t) => {
2241
2257
  t.status(404).type("text/plain").send("Not found");
2242
2258
  }), {
2243
- server: T,
2244
- store: m,
2245
- url: `http://${Fn(r)}:${$(T)}/mcp`,
2246
- close: () => (ee ??= (async () => {
2247
- await Promise.allSettled([...C].map(({ mcpServer: e }) => e.close())), await new Promise((e, t) => {
2248
- T.close((n) => {
2259
+ server: S,
2260
+ store: o,
2261
+ url: `http://${Bn(n)}:${$(S)}/mcp`,
2262
+ close: () => (b ??= (async () => {
2263
+ await Promise.allSettled([...y].map(({ mcpServer: e }) => e.close())), await new Promise((e, t) => {
2264
+ S.close((n) => {
2249
2265
  if (!n || n.code === "ERR_SERVER_NOT_RUNNING") {
2250
2266
  e();
2251
2267
  return;
2252
2268
  }
2253
2269
  t(n);
2254
- }), T.closeAllConnections();
2255
- }), m.close();
2256
- })(), ee)
2270
+ }), S.closeAllConnections();
2271
+ }), o.close();
2272
+ })(), b)
2257
2273
  };
2258
2274
  }
2259
- function En(e, t, n) {
2260
- return Dn(e, t) ? !0 : n ? Pn(e.headers.host, n) && kn(e.headers.origin, n) : !1;
2275
+ function jn(e, t, n) {
2276
+ return Mn(e, t) ? !0 : n ? zn(e.headers.host, n) && Pn(e.headers.origin, n) : !1;
2261
2277
  }
2262
- function Dn(e, t) {
2263
- return Sn(e.socket.remoteAddress) && bn(e.headers.host, t) && xn(e.headers.origin, t);
2278
+ function Mn(e, t) {
2279
+ return Dn(e.socket.remoteAddress) && Tn(e.headers.host, t) && En(e.headers.origin, t);
2264
2280
  }
2265
- function On(e, t, n) {
2266
- return Dn(e, t) ? !0 : n ? Pn(e.headers.host, n) && kn(e.headers.origin, n) : !1;
2281
+ function Nn(e, t, n) {
2282
+ return Mn(e, t) ? !0 : n ? zn(e.headers.host, n) && Pn(e.headers.origin, n) : !1;
2267
2283
  }
2268
- function kn(e, t) {
2284
+ function Pn(e, t) {
2269
2285
  if (!e) return !0;
2270
2286
  try {
2271
2287
  let n = new URL(e);
2272
- return n.origin === t.origin || un.has(n.origin);
2288
+ return n.origin === t.origin || dn.has(n.origin);
2273
2289
  } catch {
2274
2290
  return !1;
2275
2291
  }
2276
2292
  }
2277
- function An(e, t, n) {
2293
+ function Fn(e, t, n) {
2278
2294
  if (!n) return;
2279
- let r = jn(e.headers.origin, n);
2280
- r && (t.setHeader("Access-Control-Allow-Origin", r), t.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS"), t.setHeader("Access-Control-Allow-Headers", e.headers["access-control-request-headers"] ?? dn), t.setHeader("Access-Control-Max-Age", fn), t.setHeader("Vary", "Origin"));
2295
+ let r = In(e.headers.origin, n);
2296
+ r && (t.setHeader("Access-Control-Allow-Origin", r), t.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS"), t.setHeader("Access-Control-Allow-Headers", e.headers["access-control-request-headers"] ?? fn), t.setHeader("Access-Control-Max-Age", pn), t.setHeader("Vary", "Origin"));
2281
2297
  }
2282
- function jn(e, t) {
2298
+ function In(e, t) {
2283
2299
  if (e) try {
2284
2300
  let n = new URL(e).origin;
2285
- if (n === t.origin || un.has(n)) return n;
2301
+ if (n === t.origin || dn.has(n)) return n;
2286
2302
  } catch {
2287
2303
  return;
2288
2304
  }
2289
2305
  }
2290
- function Mn(e, t, n) {
2306
+ function Ln(e, t, n) {
2291
2307
  console.warn(JSON.stringify({
2292
2308
  source: "codemem-mcp-http-guard",
2293
2309
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -2295,51 +2311,97 @@ function Mn(e, t, n) {
2295
2311
  reason: "host_or_origin_mismatch",
2296
2312
  method: e.method,
2297
2313
  path: t,
2298
- host: Nn(e.headers.host),
2299
- origin: Nn(e.headers.origin),
2314
+ host: Rn(e.headers.host),
2315
+ origin: Rn(e.headers.origin),
2300
2316
  expectedOrigin: n?.origin,
2301
2317
  remoteAddress: e.socket.remoteAddress ?? void 0
2302
2318
  }));
2303
2319
  }
2304
- function Nn(e) {
2305
- return !e || e.length <= pn ? e : `${e.slice(0, pn)}…`;
2320
+ function Rn(e) {
2321
+ return !e || e.length <= mn ? e : `${e.slice(0, mn)}…`;
2306
2322
  }
2307
- function Pn(e, t) {
2308
- let n = Cn(e);
2323
+ function zn(e, t) {
2324
+ let n = On(e);
2309
2325
  if (!n) return !1;
2310
2326
  let r = t.port ? Number(t.port) : t.protocol === "https:" ? 443 : 80, i = t.protocol === "https:" ? 443 : 80, a = n.port ?? i;
2311
2327
  return Q(n.host) === Q(t.hostname) && a === r;
2312
2328
  }
2313
2329
  function $(e) {
2314
2330
  let t = e.address();
2315
- return !t || typeof t == "string" ? cn : t.port;
2331
+ return !t || typeof t == "string" ? X : t.port;
2316
2332
  }
2317
- function Fn(e) {
2318
- return n(e) === 6 ? `[${e}]` : e;
2333
+ function Bn(e) {
2334
+ return u(e) === 6 ? `[${e}]` : e;
2335
+ }
2336
+ function Vn(e, t) {
2337
+ return `http://${Bn(t)}:${$(e)}/mcp`;
2338
+ }
2339
+ function Hn() {
2340
+ let t = /* @__PURE__ */ new Map();
2341
+ return (r) => {
2342
+ if (!r.principal) return Un(o());
2343
+ for (let [e, n] of t) n.expiresAt <= r.now && t.delete(e);
2344
+ let i = n("sha256").update(JSON.stringify([
2345
+ r.endpoint.href,
2346
+ r.principal,
2347
+ e(r.requestBody)
2348
+ ])).digest("hex"), a = t.get(i);
2349
+ if (a) return a.scopeId;
2350
+ let s = Un(JSON.stringify([i, r.now]));
2351
+ for (t.set(i, {
2352
+ scopeId: s,
2353
+ expiresAt: r.now + vn
2354
+ }); t.size > yn;) {
2355
+ let e = t.keys().next().value;
2356
+ if (e === void 0) break;
2357
+ t.delete(e);
2358
+ }
2359
+ return s;
2360
+ };
2319
2361
  }
2320
- function In(e, t) {
2321
- return `http://${Fn(t)}:${$(e)}/mcp`;
2362
+ function Un(e) {
2363
+ return `mcp-http:${n("sha256").update(e).digest("hex")}`;
2322
2364
  }
2323
- function Ln(e, t) {
2365
+ function Wn(e, t, n, r) {
2366
+ let i = Gn(e);
2367
+ if (i === null) {
2368
+ r(e);
2369
+ return;
2370
+ }
2371
+ n.status(i).json({
2372
+ jsonrpc: "2.0",
2373
+ error: {
2374
+ code: i === 413 ? -32e3 : -32700,
2375
+ message: i === 413 ? "Request body too large" : "Parse error"
2376
+ },
2377
+ id: null
2378
+ });
2379
+ }
2380
+ function Gn(e) {
2381
+ if (typeof e != "object" || !e) return null;
2382
+ let t = e;
2383
+ return t.type === "entity.too.large" ? 413 : t.type === "entity.parse.failed" ? 400 : null;
2384
+ }
2385
+ function Kn(e, t) {
2324
2386
  return e.protocol === "https:" || Z(e.hostname) && Q(e.hostname) !== "::1" ? new URL(e.origin) : new URL(`http://localhost:${t}/`);
2325
2387
  }
2326
- function Rn(e) {
2388
+ function qn(e) {
2327
2389
  return e === "/register" || e === "/authorize" || e === "/token" || e === "/revoke" || e === "/oauth/callback" || e === "/.well-known/oauth-authorization-server" || e === "/.well-known/oauth-protected-resource/mcp";
2328
2390
  }
2329
- function zn(e) {
2391
+ function Jn(e) {
2330
2392
  return e.length > 1 ? e.replace(/\/+$/, "") : e;
2331
2393
  }
2332
- function Bn(e) {
2394
+ function Yn(e) {
2333
2395
  return (t, n, r) => {
2334
2396
  let i = t.path;
2335
- if (!Vn(i)) return r();
2397
+ if (!Xn(i)) return r();
2336
2398
  let a, o = n.json.bind(n);
2337
2399
  n.json = ((e) => (a = e, o(e))), n.on("finish", () => {
2338
2400
  if (i === "/oauth/callback") return;
2339
- let r = Hn(i, t);
2401
+ let r = Zn(i, t);
2340
2402
  if (!r) return;
2341
- let o = Wn(n, a), s = Kn(t, a);
2342
- e(L(r, {
2403
+ let o = $n(n, a), s = tr(t, a);
2404
+ e(F(r, {
2343
2405
  outcome: o ? "denied" : "success",
2344
2406
  ...o ? { reason: o } : {},
2345
2407
  ...s ? { clientId: s } : {},
@@ -2348,17 +2410,17 @@ function Bn(e) {
2348
2410
  }), r();
2349
2411
  };
2350
2412
  }
2351
- function Vn(e) {
2352
- return Un(e) !== null;
2413
+ function Xn(e) {
2414
+ return Qn(e) !== null;
2353
2415
  }
2354
- function Hn(e, t) {
2355
- return e === "/token" && t.body?.grant_type === "refresh_token" ? "refresh" : Un(e);
2416
+ function Zn(e, t) {
2417
+ return e === "/token" && t.body?.grant_type === "refresh_token" ? "refresh" : Qn(e);
2356
2418
  }
2357
- function Un(e) {
2419
+ function Qn(e) {
2358
2420
  return e === "/register" ? "registration" : e === "/authorize" ? "authorize" : e === "/token" ? "token" : e === "/revoke" ? "revocation" : null;
2359
2421
  }
2360
- function Wn(e, t) {
2361
- let n = Gn(t);
2422
+ function $n(e, t) {
2423
+ let n = er(t);
2362
2424
  if (n) return n;
2363
2425
  let r = e.getHeader("location");
2364
2426
  if (typeof r == "string") try {
@@ -2367,38 +2429,38 @@ function Wn(e, t) {
2367
2429
  return;
2368
2430
  }
2369
2431
  }
2370
- function Gn(e) {
2432
+ function er(e) {
2371
2433
  if (typeof e == "object" && e && "error" in e && typeof e.error == "string") return e.error;
2372
2434
  }
2373
- function Kn(e, t) {
2435
+ function tr(e, t) {
2374
2436
  return typeof t == "object" && t && "client_id" in t && typeof t.client_id == "string" ? t.client_id : (typeof e.body?.client_id == "string" ? e.body.client_id : void 0) || (typeof e.query.client_id == "string" ? e.query.client_id : void 0);
2375
2437
  }
2376
- function qn(e, t) {
2438
+ function nr(e, t) {
2377
2439
  return (n, r, i) => {
2378
- let a = Jn(n.headers.authorization, t);
2379
- a && e(L("bearer", {
2440
+ let a = rr(n.headers.authorization, t);
2441
+ a && e(F("bearer", {
2380
2442
  outcome: "denied",
2381
2443
  reason: a,
2382
2444
  remoteAddress: n.socket.remoteAddress ?? void 0
2383
2445
  })), i();
2384
2446
  };
2385
2447
  }
2386
- function Jn(e, t) {
2448
+ function rr(e, t) {
2387
2449
  if (!e) return "missing_authorization_header";
2388
2450
  let [n, r, i] = e.trim().split(/\s+/);
2389
2451
  if (!n || !r || i || n.toLowerCase() !== "bearer") return "malformed_authorization_header";
2390
2452
  let a = t.verifyToken(r);
2391
2453
  return a.ok ? null : a.reason;
2392
2454
  }
2393
- function Yn(e) {
2455
+ function ir(e) {
2394
2456
  return e?.split(/\s+/).map((e) => e.trim()).filter(Boolean) ?? [];
2395
2457
  }
2396
- function Xn() {
2458
+ function ar() {
2397
2459
  let e = process.argv[1];
2398
- return e ? import.meta.url === i(e).href : !1;
2460
+ return e ? import.meta.url === f(e).href : !1;
2399
2461
  }
2400
- async function Zn() {
2401
- let e = await Tn();
2462
+ async function or() {
2463
+ let e = await An();
2402
2464
  console.error(`codemem MCP HTTP server listening at ${e.url}`);
2403
2465
  let t = async () => {
2404
2466
  try {
@@ -2408,10 +2470,10 @@ async function Zn() {
2408
2470
  };
2409
2471
  process.on("SIGINT", t), process.on("SIGTERM", t);
2410
2472
  }
2411
- Xn() && Zn().catch((e) => {
2473
+ ar() && or().catch((e) => {
2412
2474
  console.error("codemem MCP HTTP server failed to start:", e), process.exit(1);
2413
2475
  });
2414
2476
  //#endregion
2415
- export { sn as DEFAULT_MCP_HTTP_HOST, cn as DEFAULT_MCP_HTTP_PORT, bn as isAllowedMcpHttpRequestHost, xn as isAllowedMcpHttpRequestOrigin, Sn as isAllowedMcpHttpRequestRemoteAddress, Z as isLoopbackHost, yn as isUnsafePublicBindAllowed, wn as parseMcpHttpPort, Tn as startCodememMcpHttpServer, vn as validateMcpHttpHost };
2477
+ export { ln as DEFAULT_MCP_HTTP_HOST, X as DEFAULT_MCP_HTTP_PORT, _n as MCP_HTTP_MAX_JSON_BODY_BYTES, vn as MCP_HTTP_RETRIEVAL_RETRY_WINDOW_MS, Sn as authenticatedRetrievalPrincipal, Tn as isAllowedMcpHttpRequestHost, En as isAllowedMcpHttpRequestOrigin, Dn as isAllowedMcpHttpRequestRemoteAddress, Z as isLoopbackHost, wn as isUnsafePublicBindAllowed, kn as parseMcpHttpPort, An as startCodememMcpHttpServer, Cn as validateMcpHttpHost };
2416
2478
 
2417
2479
  //# sourceMappingURL=http.js.map