@vitemcp/server 1.9.14 → 1.9.16

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.
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7;// src/auth/helpers.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7;// src/auth/helpers.ts
2
2
  function getAuthSession(session) {
3
3
  if (!session) {
4
4
  throw new Error("Session is not authenticated");
@@ -1393,6 +1393,7 @@ var MemoryTokenStorage = (_class3 = class {
1393
1393
  () => void this.cleanup(),
1394
1394
  cleanupIntervalMs
1395
1395
  );
1396
+ _optionalChain([this, 'access', _7 => _7.cleanupInterval, 'access', _8 => _8.unref, 'optionalCall', _9 => _9()]);
1396
1397
  }
1397
1398
  async cleanup() {
1398
1399
  const now = Date.now();
@@ -1462,7 +1463,14 @@ var withoutTrailingSlash = (url) => url.replace(/\/+$/, "");
1462
1463
 
1463
1464
  // src/auth/OAuthProxy.ts
1464
1465
  var DEFAULT_REDIRECT_PATH = "/oauth/callback";
1466
+ var GENERATED_ID = /^[\w-]{43}$/;
1465
1467
  var GITHUB_TOKEN_ENDPOINT = "https://github.com/login/oauth/access_token";
1468
+ var MAX_RELAYED_ERROR_LENGTH = 512;
1469
+ var OAUTH_ERROR_TEXT = /^[\x20-\x21\x23-\x5b\x5d-\x7e]+$/;
1470
+ var relayableError = (error, description) => ({
1471
+ error: OAUTH_ERROR_TEXT.test(error) && error.length <= MAX_RELAYED_ERROR_LENGTH ? error : "server_error",
1472
+ error_description: _optionalChain([description, 'optionalAccess', _10 => _10.replace, 'call', _11 => _11(/[^\x21\x23-\x5b\x5d-\x7e]+/g, " "), 'access', _12 => _12.slice, 'call', _13 => _13(0, MAX_RELAYED_ERROR_LENGTH), 'access', _14 => _14.trim, 'call', _15 => _15()]) || void 0
1473
+ });
1466
1474
  var RESERVED_AUTHORIZATION_PARAMS = /* @__PURE__ */ new Set([
1467
1475
  "client_id",
1468
1476
  "code_challenge",
@@ -1485,11 +1493,10 @@ var OAuthProxy = (_class4 = class {
1485
1493
 
1486
1494
 
1487
1495
  /**
1488
- * The fallback storage this proxy created for itself, if any. It runs a
1489
- * cleanup timer that keeps the event loop alive, so `destroy()` has to stop
1490
- * it — and once the storage is wrapped for encryption it is reachable
1491
- * through nothing else. A caller-supplied storage is deliberately not
1492
- * recorded here: its lifetime belongs to the caller.
1496
+ * The fallback storage this proxy created for itself, if any. Kept so that
1497
+ * `destroy()` can stop its cleanup timer: once the storage is wrapped for
1498
+ * encryption it is reachable through nothing else. A caller-supplied storage
1499
+ * is deliberately not recorded here: its lifetime belongs to the caller.
1493
1500
  */
1494
1501
  __init7() {this.ownedTokenStorage = null}
1495
1502
  /**
@@ -1623,7 +1630,7 @@ var OAuthProxy = (_class4 = class {
1623
1630
  clearInterval(this.cleanupInterval);
1624
1631
  this.cleanupInterval = null;
1625
1632
  }
1626
- _optionalChain([this, 'access', _7 => _7.ownedTokenStorage, 'optionalAccess', _8 => _8.destroy, 'call', _9 => _9()]);
1633
+ _optionalChain([this, 'access', _16 => _16.ownedTokenStorage, 'optionalAccess', _17 => _17.destroy, 'call', _18 => _18()]);
1627
1634
  this.registeredClientsByClientId.clear();
1628
1635
  }
1629
1636
  /**
@@ -1776,14 +1783,15 @@ var OAuthProxy = (_class4 = class {
1776
1783
  */
1777
1784
  async handleCallback(request2) {
1778
1785
  const url = new URL(request2.url);
1779
- const code = url.searchParams.get("code");
1786
+ const code = _nullishCoalesce(url.searchParams.get("code"), () => ( ""));
1780
1787
  const state = url.searchParams.get("state");
1781
1788
  const error = url.searchParams.get("error");
1789
+ const description = url.searchParams.get("error_description") || void 0;
1782
1790
  if (error) {
1783
- const errorDescription = url.searchParams.get("error_description");
1784
- throw new OAuthProxyError(error, errorDescription || void 0);
1785
- }
1786
- if (!code || !state) {
1791
+ if (!state || url.searchParams.getAll("state").length !== 1 || !GENERATED_ID.test(state) || await _asyncOptionalChain([(await this.stateStore.getTransaction(state)), 'optionalAccess', async _19 => _19.id]) !== state) {
1792
+ throw new OAuthProxyError(error, description);
1793
+ }
1794
+ } else if (!code || !state) {
1787
1795
  throw new OAuthProxyError(
1788
1796
  "invalid_request",
1789
1797
  "Missing code or state parameter"
@@ -1806,21 +1814,18 @@ var OAuthProxy = (_class4 = class {
1806
1814
  "Authorization response issuer does not match the request issuer"
1807
1815
  );
1808
1816
  }
1817
+ if (error) {
1818
+ return this.redirectToClient(
1819
+ transaction,
1820
+ relayableError(error, description)
1821
+ );
1822
+ }
1809
1823
  const upstreamTokens = await this.exchangeUpstreamCode(code, transaction);
1810
1824
  const clientCode = await this.generateAuthorizationCode(
1811
1825
  transaction,
1812
1826
  upstreamTokens
1813
1827
  );
1814
- const redirectUrl = new URL(transaction.clientCallbackUrl);
1815
- redirectUrl.searchParams.set("code", clientCode);
1816
- redirectUrl.searchParams.set("state", transaction.state);
1817
- redirectUrl.searchParams.set("iss", this.config.baseUrl);
1818
- return new Response(null, {
1819
- headers: {
1820
- Location: redirectUrl.toString()
1821
- },
1822
- status: 302
1823
- });
1828
+ return this.redirectToClient(transaction, { code: clientCode });
1824
1829
  }
1825
1830
  /**
1826
1831
  * Handle consent form submission
@@ -1853,19 +1858,9 @@ var OAuthProxy = (_class4 = class {
1853
1858
  "Transaction callback URL is not registered"
1854
1859
  );
1855
1860
  }
1856
- const redirectUrl = new URL(transaction.clientCallbackUrl);
1857
- redirectUrl.searchParams.set("error", "access_denied");
1858
- redirectUrl.searchParams.set(
1859
- "error_description",
1860
- "User denied authorization"
1861
- );
1862
- redirectUrl.searchParams.set("state", transaction.state);
1863
- redirectUrl.searchParams.set("iss", this.config.baseUrl);
1864
- return new Response(null, {
1865
- headers: {
1866
- Location: redirectUrl.toString()
1867
- },
1868
- status: 302
1861
+ return this.redirectToClient(transaction, {
1862
+ error: "access_denied",
1863
+ error_description: "User denied authorization"
1869
1864
  });
1870
1865
  }
1871
1866
  const approvedTransaction = {
@@ -1883,7 +1878,7 @@ var OAuthProxy = (_class4 = class {
1883
1878
  return null;
1884
1879
  }
1885
1880
  const result = await this.jwtIssuer.verify(vitemcpToken);
1886
- if (!result.valid || !_optionalChain([result, 'access', _10 => _10.claims, 'optionalAccess', _11 => _11.jti])) {
1881
+ if (!result.valid || !_optionalChain([result, 'access', _20 => _20.claims, 'optionalAccess', _21 => _21.jti])) {
1887
1882
  return null;
1888
1883
  }
1889
1884
  if (result.claims.token_use !== "access") {
@@ -2100,7 +2095,7 @@ var OAuthProxy = (_class4 = class {
2100
2095
  let errorCode = "server_error";
2101
2096
  let errorDescription;
2102
2097
  try {
2103
- const error = await tokenResponse.json();
2098
+ const error = await this.readUpstreamError(tokenResponse);
2104
2099
  errorCode = error.error || "server_error";
2105
2100
  errorDescription = error.error_description;
2106
2101
  } catch (e7) {
@@ -2131,7 +2126,7 @@ var OAuthProxy = (_class4 = class {
2131
2126
  throw new Error("JWT issuer not initialized");
2132
2127
  }
2133
2128
  const result = await this.jwtIssuer.verify(token);
2134
- if (!result.valid || !_optionalChain([result, 'access', _12 => _12.claims, 'optionalAccess', _13 => _13.jti])) {
2129
+ if (!result.valid || !_optionalChain([result, 'access', _22 => _22.claims, 'optionalAccess', _23 => _23.jti])) {
2135
2130
  throw new Error("Failed to extract JTI from token");
2136
2131
  }
2137
2132
  return result.claims.jti;
@@ -2304,7 +2299,7 @@ var OAuthProxy = (_class4 = class {
2304
2299
  let errorCode = "invalid_grant";
2305
2300
  let errorDescription;
2306
2301
  try {
2307
- const error = await tokenResponse.json();
2302
+ const error = await this.readUpstreamError(tokenResponse);
2308
2303
  errorCode = error.error || "invalid_grant";
2309
2304
  errorDescription = error.error_description;
2310
2305
  } catch (e8) {
@@ -2690,6 +2685,62 @@ var OAuthProxy = (_class4 = class {
2690
2685
  const digest = _crypto.createHash.call(void 0, "sha256").update(refreshToken).digest("base64url");
2691
2686
  return `passthrough-refresh:${this.issuerNs}:${digest}`;
2692
2687
  }
2688
+ /**
2689
+ * What a refusal from the token endpoint says: the `error` and
2690
+ * `error_description` RFC 6749 §5.2 gives it.
2691
+ *
2692
+ * §5.2 sends them as JSON, but a provider that answers a successful request
2693
+ * with a form — GitHub, by default — may refuse with one too, and read as
2694
+ * JSON that lost the provider's own code and description to a bare HTTP
2695
+ * status.
2696
+ *
2697
+ * What parses as JSON is read as JSON, whatever the response declares, as
2698
+ * every refusal was before. A form is read only when the response declares
2699
+ * one, by its media type alone: a 502 page can name that type in a parameter
2700
+ * and carry `error=` in a link, and is no provider's refusal. Rejects when
2701
+ * the body is neither, and the caller falls back to the HTTP status.
2702
+ */
2703
+ async readUpstreamError(response) {
2704
+ const text = await response.text();
2705
+ try {
2706
+ return JSON.parse(text);
2707
+ } catch (cause) {
2708
+ const mediaType = _optionalChain([response, 'access', _24 => _24.headers, 'access', _25 => _25.get, 'call', _26 => _26("content-type"), 'optionalAccess', _27 => _27.split, 'call', _28 => _28(";", 1), 'access', _29 => _29[0], 'optionalAccess', _30 => _30.trim, 'call', _31 => _31(), 'access', _32 => _32.toLowerCase, 'call', _33 => _33()]);
2709
+ if (mediaType === "application/x-www-form-urlencoded") {
2710
+ const params = new URLSearchParams(text);
2711
+ const error = params.get("error");
2712
+ if (error) {
2713
+ return {
2714
+ error,
2715
+ error_description: _nullishCoalesce(params.get("error_description"), () => ( void 0))
2716
+ };
2717
+ }
2718
+ }
2719
+ throw cause;
2720
+ }
2721
+ }
2722
+ /**
2723
+ * Send the user's browser back to the client's registered callback with how
2724
+ * its request came out: a code, or an error (RFC 6749 §4.1.2). The `state`
2725
+ * the client sent goes with either, and so does the issuer, so that the
2726
+ * client can detect an AS mix-up (RFC 9207 §2).
2727
+ */
2728
+ redirectToClient(transaction, params) {
2729
+ const redirectUrl = new URL(transaction.clientCallbackUrl);
2730
+ for (const [name, value] of Object.entries(params)) {
2731
+ if (value !== void 0) {
2732
+ redirectUrl.searchParams.set(name, value);
2733
+ }
2734
+ }
2735
+ redirectUrl.searchParams.set("state", transaction.state);
2736
+ redirectUrl.searchParams.set("iss", this.config.baseUrl);
2737
+ return new Response(null, {
2738
+ headers: {
2739
+ Location: redirectUrl.toString()
2740
+ },
2741
+ status: 302
2742
+ });
2743
+ }
2693
2744
  /**
2694
2745
  * Redirect to upstream OAuth provider
2695
2746
  */
@@ -2753,7 +2804,7 @@ var OAuthProxy = (_class4 = class {
2753
2804
  let errorCode = "invalid_grant";
2754
2805
  let errorDescription = "Upstream refresh failed";
2755
2806
  try {
2756
- const error = await tokenResponse.json();
2807
+ const error = await this.readUpstreamError(tokenResponse);
2757
2808
  errorCode = error.error || "invalid_grant";
2758
2809
  errorDescription = error.error_description || "Upstream refresh failed";
2759
2810
  } catch (e10) {
@@ -2883,12 +2934,18 @@ var OAuthProxy = (_class4 = class {
2883
2934
  );
2884
2935
  }
2885
2936
  /**
2886
- * Start periodic cleanup of expired transactions and codes
2937
+ * Start periodic cleanup of expired transactions and codes.
2938
+ *
2939
+ * The timer is `unref`ed: a sweep is housekeeping, and a process with nothing
2940
+ * else left to do must be free to exit rather than wait on it. `stop()`
2941
+ * leaves the proxy running, since it may be shared or serve again, so a timer
2942
+ * that held the process open would do so until `destroy()`.
2887
2943
  */
2888
2944
  startCleanup() {
2889
2945
  this.cleanupInterval = setInterval(() => {
2890
2946
  this.cleanup();
2891
2947
  }, 6e4);
2948
+ _optionalChain([this, 'access', _34 => _34.cleanupInterval, 'access', _35 => _35.unref, 'optionalCall', _36 => _36()]);
2892
2949
  }
2893
2950
  /**
2894
2951
  * PKCE challenge methods this proxy accepts, advertised in the authorization
@@ -3087,11 +3144,12 @@ var AuthProvider = (_class5 = class {
3087
3144
  if (!request2) {
3088
3145
  return void 0;
3089
3146
  }
3090
- const authHeader = request2.headers.get("authorization");
3091
- if (!authHeader || !authHeader.startsWith("Bearer ")) {
3147
+ const token = _optionalChain([/^bearer +(\S.*)$/i, 'access', _37 => _37.exec, 'call', _38 => _38(
3148
+ _nullishCoalesce(request2.headers.get("authorization"), () => ( ""))
3149
+ ), 'optionalAccess', _39 => _39[1]]);
3150
+ if (!token) {
3092
3151
  return void 0;
3093
3152
  }
3094
- const token = authHeader.slice(7);
3095
3153
  const upstreamTokens = await this.proxy.loadUpstreamTokens(token);
3096
3154
  if (!upstreamTokens) {
3097
3155
  return void 0;
@@ -3102,10 +3160,10 @@ var AuthProvider = (_class5 = class {
3102
3160
  * Release the resources held by the proxy this provider built for itself.
3103
3161
  *
3104
3162
  * That proxy runs two cleanup timers — its own sweep and its token
3105
- * storage's — and both keep the Node event loop alive, so a process that has
3106
- * stopped serving does not exit until this runs. `getProxy().destroy()`
3107
- * reaches the same teardown; this exists so a caller holding only the
3108
- * provider does not have to know that.
3163
+ * storage's. Neither keeps the Node event loop alive, so a process that has
3164
+ * stopped serving exits without this, but the timers run on until it does.
3165
+ * `getProxy().destroy()` reaches the same teardown; this exists so a caller
3166
+ * holding only the provider does not have to know that.
3109
3167
  *
3110
3168
  * Terminal: the provider will not serve again afterwards, and any later use
3111
3169
  * throws rather than quietly building a replacement. Call it when the process
@@ -3117,7 +3175,7 @@ var AuthProvider = (_class5 = class {
3117
3175
  */
3118
3176
  destroy() {
3119
3177
  this._destroyed = true;
3120
- _optionalChain([this, 'access', _14 => _14._proxy, 'optionalAccess', _15 => _15.destroy, 'call', _16 => _16()]);
3178
+ _optionalChain([this, 'access', _40 => _40._proxy, 'optionalAccess', _41 => _41.destroy, 'call', _42 => _42()]);
3121
3179
  this._proxy = void 0;
3122
3180
  }
3123
3181
  /**
@@ -3332,6 +3390,7 @@ var DiskStore = (_class6 = class {
3332
3390
  this.cleanupInterval = setInterval(() => {
3333
3391
  void this.cleanup();
3334
3392
  }, cleanupIntervalMs);
3393
+ _optionalChain([this, 'access', _43 => _43.cleanupInterval, 'access', _44 => _44.unref, 'optionalCall', _45 => _45()]);
3335
3394
  }
3336
3395
  /**
3337
3396
  * Clean up expired entries.
@@ -3695,4 +3754,4 @@ Original error: ${error.message}`
3695
3754
 
3696
3755
 
3697
3756
  exports.withoutTrailingSlash = withoutTrailingSlash; exports.getAuthSession = getAuthSession; exports.requireAll = requireAll; exports.requireAny = requireAny; exports.requireAuth = requireAuth; exports.requireRole = requireRole; exports.requireScopes = requireScopes; exports.DEFAULT_ACCESS_TOKEN_TTL = DEFAULT_ACCESS_TOKEN_TTL; exports.DEFAULT_ACCESS_TOKEN_TTL_NO_REFRESH = DEFAULT_ACCESS_TOKEN_TTL_NO_REFRESH; exports.DEFAULT_REFRESH_TOKEN_TTL = DEFAULT_REFRESH_TOKEN_TTL; exports.DEFAULT_AUTHORIZATION_CODE_TTL = DEFAULT_AUTHORIZATION_CODE_TTL; exports.DEFAULT_TRANSACTION_TTL = DEFAULT_TRANSACTION_TTL; exports.ConsentManager = ConsentManager; exports.JWTIssuer = JWTIssuer; exports.PKCEUtils = PKCEUtils; exports.EncryptedTokenStorage = EncryptedTokenStorage; exports.MemoryTokenStorage = MemoryTokenStorage; exports.OAuthProxy = OAuthProxy; exports.OAuthProxyError = OAuthProxyError; exports.AuthProvider = AuthProvider; exports.AzureProvider = AzureProvider; exports.GitHubProvider = GitHubProvider; exports.GoogleProvider = GoogleProvider; exports.OAuthProvider = OAuthProvider; exports.DiskStore = DiskStore; exports.JWKSVerifier = JWKSVerifier;
3698
- //# sourceMappingURL=chunk-T7EJGNI3.cjs.map
3757
+ //# sourceMappingURL=chunk-TWYBLPRQ.cjs.map