@vitemcp/server 1.9.13 → 1.9.15

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();
@@ -1461,7 +1462,15 @@ var MemoryTokenStorage = (_class3 = class {
1461
1462
  var withoutTrailingSlash = (url) => url.replace(/\/+$/, "");
1462
1463
 
1463
1464
  // src/auth/OAuthProxy.ts
1465
+ var DEFAULT_REDIRECT_PATH = "/oauth/callback";
1466
+ var GENERATED_ID = /^[\w-]{43}$/;
1464
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
+ });
1465
1474
  var RESERVED_AUTHORIZATION_PARAMS = /* @__PURE__ */ new Set([
1466
1475
  "client_id",
1467
1476
  "code_challenge",
@@ -1484,11 +1493,10 @@ var OAuthProxy = (_class4 = class {
1484
1493
 
1485
1494
 
1486
1495
  /**
1487
- * The fallback storage this proxy created for itself, if any. It runs a
1488
- * cleanup timer that keeps the event loop alive, so `destroy()` has to stop
1489
- * it — and once the storage is wrapped for encryption it is reachable
1490
- * through nothing else. A caller-supplied storage is deliberately not
1491
- * 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.
1492
1500
  */
1493
1501
  __init7() {this.ownedTokenStorage = null}
1494
1502
  /**
@@ -1506,7 +1514,7 @@ var OAuthProxy = (_class4 = class {
1506
1514
  consentRequired: true,
1507
1515
  enableTokenSwap: true,
1508
1516
  // Enabled by default for security
1509
- redirectPath: "/oauth/callback",
1517
+ redirectPath: DEFAULT_REDIRECT_PATH,
1510
1518
  transactionTtl: DEFAULT_TRANSACTION_TTL,
1511
1519
  upstreamRequestTimeoutMs: DEFAULT_UPSTREAM_REQUEST_TIMEOUT_MS,
1512
1520
  upstreamTokenEndpointAuthMethod: "client_secret_basic",
@@ -1622,7 +1630,7 @@ var OAuthProxy = (_class4 = class {
1622
1630
  clearInterval(this.cleanupInterval);
1623
1631
  this.cleanupInterval = null;
1624
1632
  }
1625
- _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()]);
1626
1634
  this.registeredClientsByClientId.clear();
1627
1635
  }
1628
1636
  /**
@@ -1761,19 +1769,29 @@ var OAuthProxy = (_class4 = class {
1761
1769
  tokenEndpointAuthMethodsSupported: [...TOKEN_ENDPOINT_AUTH_METHODS]
1762
1770
  };
1763
1771
  }
1772
+ /**
1773
+ * The path the upstream provider redirects back to: `redirectPath`, or
1774
+ * `/oauth/callback` when none is set. The router serves the callback here
1775
+ * and the proxy sends `{baseUrl}{path}` upstream as the `redirect_uri`, so
1776
+ * both read it from this one place and cannot disagree.
1777
+ */
1778
+ getRedirectPath() {
1779
+ return _nullishCoalesce(this.config.redirectPath, () => ( DEFAULT_REDIRECT_PATH));
1780
+ }
1764
1781
  /**
1765
1782
  * Handle OAuth callback from upstream provider
1766
1783
  */
1767
1784
  async handleCallback(request2) {
1768
1785
  const url = new URL(request2.url);
1769
- const code = url.searchParams.get("code");
1786
+ const code = _nullishCoalesce(url.searchParams.get("code"), () => ( ""));
1770
1787
  const state = url.searchParams.get("state");
1771
1788
  const error = url.searchParams.get("error");
1789
+ const description = url.searchParams.get("error_description") || void 0;
1772
1790
  if (error) {
1773
- const errorDescription = url.searchParams.get("error_description");
1774
- throw new OAuthProxyError(error, errorDescription || void 0);
1775
- }
1776
- 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) {
1777
1795
  throw new OAuthProxyError(
1778
1796
  "invalid_request",
1779
1797
  "Missing code or state parameter"
@@ -1796,21 +1814,18 @@ var OAuthProxy = (_class4 = class {
1796
1814
  "Authorization response issuer does not match the request issuer"
1797
1815
  );
1798
1816
  }
1817
+ if (error) {
1818
+ return this.redirectToClient(
1819
+ transaction,
1820
+ relayableError(error, description)
1821
+ );
1822
+ }
1799
1823
  const upstreamTokens = await this.exchangeUpstreamCode(code, transaction);
1800
1824
  const clientCode = await this.generateAuthorizationCode(
1801
1825
  transaction,
1802
1826
  upstreamTokens
1803
1827
  );
1804
- const redirectUrl = new URL(transaction.clientCallbackUrl);
1805
- redirectUrl.searchParams.set("code", clientCode);
1806
- redirectUrl.searchParams.set("state", transaction.state);
1807
- redirectUrl.searchParams.set("iss", this.config.baseUrl);
1808
- return new Response(null, {
1809
- headers: {
1810
- Location: redirectUrl.toString()
1811
- },
1812
- status: 302
1813
- });
1828
+ return this.redirectToClient(transaction, { code: clientCode });
1814
1829
  }
1815
1830
  /**
1816
1831
  * Handle consent form submission
@@ -1843,19 +1858,9 @@ var OAuthProxy = (_class4 = class {
1843
1858
  "Transaction callback URL is not registered"
1844
1859
  );
1845
1860
  }
1846
- const redirectUrl = new URL(transaction.clientCallbackUrl);
1847
- redirectUrl.searchParams.set("error", "access_denied");
1848
- redirectUrl.searchParams.set(
1849
- "error_description",
1850
- "User denied authorization"
1851
- );
1852
- redirectUrl.searchParams.set("state", transaction.state);
1853
- redirectUrl.searchParams.set("iss", this.config.baseUrl);
1854
- return new Response(null, {
1855
- headers: {
1856
- Location: redirectUrl.toString()
1857
- },
1858
- status: 302
1861
+ return this.redirectToClient(transaction, {
1862
+ error: "access_denied",
1863
+ error_description: "User denied authorization"
1859
1864
  });
1860
1865
  }
1861
1866
  const approvedTransaction = {
@@ -1873,7 +1878,7 @@ var OAuthProxy = (_class4 = class {
1873
1878
  return null;
1874
1879
  }
1875
1880
  const result = await this.jwtIssuer.verify(vitemcpToken);
1876
- 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])) {
1877
1882
  return null;
1878
1883
  }
1879
1884
  if (result.claims.token_use !== "access") {
@@ -2073,7 +2078,7 @@ var OAuthProxy = (_class4 = class {
2073
2078
  code,
2074
2079
  code_verifier: transaction.proxyCodeVerifier,
2075
2080
  grant_type: "authorization_code",
2076
- redirect_uri: `${this.config.baseUrl}${this.config.redirectPath}`
2081
+ redirect_uri: `${this.config.baseUrl}${this.getRedirectPath()}`
2077
2082
  };
2078
2083
  if (!useBasicAuth) {
2079
2084
  bodyParams.client_id = this.config.upstreamClientId;
@@ -2121,7 +2126,7 @@ var OAuthProxy = (_class4 = class {
2121
2126
  throw new Error("JWT issuer not initialized");
2122
2127
  }
2123
2128
  const result = await this.jwtIssuer.verify(token);
2124
- 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])) {
2125
2130
  throw new Error("Failed to extract JTI from token");
2126
2131
  }
2127
2132
  return result.claims.jti;
@@ -2680,6 +2685,28 @@ var OAuthProxy = (_class4 = class {
2680
2685
  const digest = _crypto.createHash.call(void 0, "sha256").update(refreshToken).digest("base64url");
2681
2686
  return `passthrough-refresh:${this.issuerNs}:${digest}`;
2682
2687
  }
2688
+ /**
2689
+ * Send the user's browser back to the client's registered callback with how
2690
+ * its request came out: a code, or an error (RFC 6749 §4.1.2). The `state`
2691
+ * the client sent goes with either, and so does the issuer, so that the
2692
+ * client can detect an AS mix-up (RFC 9207 §2).
2693
+ */
2694
+ redirectToClient(transaction, params) {
2695
+ const redirectUrl = new URL(transaction.clientCallbackUrl);
2696
+ for (const [name, value] of Object.entries(params)) {
2697
+ if (value !== void 0) {
2698
+ redirectUrl.searchParams.set(name, value);
2699
+ }
2700
+ }
2701
+ redirectUrl.searchParams.set("state", transaction.state);
2702
+ redirectUrl.searchParams.set("iss", this.config.baseUrl);
2703
+ return new Response(null, {
2704
+ headers: {
2705
+ Location: redirectUrl.toString()
2706
+ },
2707
+ status: 302
2708
+ });
2709
+ }
2683
2710
  /**
2684
2711
  * Redirect to upstream OAuth provider
2685
2712
  */
@@ -2697,7 +2724,7 @@ var OAuthProxy = (_class4 = class {
2697
2724
  authUrl.searchParams.set("client_id", this.config.upstreamClientId);
2698
2725
  authUrl.searchParams.set(
2699
2726
  "redirect_uri",
2700
- `${this.config.baseUrl}${this.config.redirectPath}`
2727
+ `${this.config.baseUrl}${this.getRedirectPath()}`
2701
2728
  );
2702
2729
  authUrl.searchParams.set("response_type", "code");
2703
2730
  authUrl.searchParams.set("state", transaction.id);
@@ -2873,12 +2900,18 @@ var OAuthProxy = (_class4 = class {
2873
2900
  );
2874
2901
  }
2875
2902
  /**
2876
- * Start periodic cleanup of expired transactions and codes
2903
+ * Start periodic cleanup of expired transactions and codes.
2904
+ *
2905
+ * The timer is `unref`ed: a sweep is housekeeping, and a process with nothing
2906
+ * else left to do must be free to exit rather than wait on it. `stop()`
2907
+ * leaves the proxy running, since it may be shared or serve again, so a timer
2908
+ * that held the process open would do so until `destroy()`.
2877
2909
  */
2878
2910
  startCleanup() {
2879
2911
  this.cleanupInterval = setInterval(() => {
2880
2912
  this.cleanup();
2881
2913
  }, 6e4);
2914
+ _optionalChain([this, 'access', _24 => _24.cleanupInterval, 'access', _25 => _25.unref, 'optionalCall', _26 => _26()]);
2882
2915
  }
2883
2916
  /**
2884
2917
  * PKCE challenge methods this proxy accepts, advertised in the authorization
@@ -3092,10 +3125,10 @@ var AuthProvider = (_class5 = class {
3092
3125
  * Release the resources held by the proxy this provider built for itself.
3093
3126
  *
3094
3127
  * That proxy runs two cleanup timers — its own sweep and its token
3095
- * storage's — and both keep the Node event loop alive, so a process that has
3096
- * stopped serving does not exit until this runs. `getProxy().destroy()`
3097
- * reaches the same teardown; this exists so a caller holding only the
3098
- * provider does not have to know that.
3128
+ * storage's. Neither keeps the Node event loop alive, so a process that has
3129
+ * stopped serving exits without this, but the timers run on until it does.
3130
+ * `getProxy().destroy()` reaches the same teardown; this exists so a caller
3131
+ * holding only the provider does not have to know that.
3099
3132
  *
3100
3133
  * Terminal: the provider will not serve again afterwards, and any later use
3101
3134
  * throws rather than quietly building a replacement. Call it when the process
@@ -3107,7 +3140,7 @@ var AuthProvider = (_class5 = class {
3107
3140
  */
3108
3141
  destroy() {
3109
3142
  this._destroyed = true;
3110
- _optionalChain([this, 'access', _14 => _14._proxy, 'optionalAccess', _15 => _15.destroy, 'call', _16 => _16()]);
3143
+ _optionalChain([this, 'access', _27 => _27._proxy, 'optionalAccess', _28 => _28.destroy, 'call', _29 => _29()]);
3111
3144
  this._proxy = void 0;
3112
3145
  }
3113
3146
  /**
@@ -3322,6 +3355,7 @@ var DiskStore = (_class6 = class {
3322
3355
  this.cleanupInterval = setInterval(() => {
3323
3356
  void this.cleanup();
3324
3357
  }, cleanupIntervalMs);
3358
+ _optionalChain([this, 'access', _30 => _30.cleanupInterval, 'access', _31 => _31.unref, 'optionalCall', _32 => _32()]);
3325
3359
  }
3326
3360
  /**
3327
3361
  * Clean up expired entries.
@@ -3685,4 +3719,4 @@ Original error: ${error.message}`
3685
3719
 
3686
3720
 
3687
3721
  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;
3688
- //# sourceMappingURL=chunk-SKQK3QGJ.cjs.map
3722
+ //# sourceMappingURL=chunk-7XWK66ZT.cjs.map