aicodeswitch 4.0.1 → 4.0.2

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.
@@ -10,14 +10,20 @@ exports.verifyToken = verifyToken;
10
10
  exports.authMiddleware = authMiddleware;
11
11
  const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
12
12
  const crypto_1 = __importDefault(require("crypto"));
13
- const AUTH_CODE = process.env.AUTH || '';
14
- const JWT_SECRET = process.env.JWT_SECRET || (AUTH_CODE ? crypto_1.default.createHash('sha256').update(AUTH_CODE).digest('hex') : '');
13
+ // 延迟读取 process.env.AUTH,避免模块加载时 dotenv 尚未执行导致值始终为空
14
+ function getAuthCode() {
15
+ return process.env.AUTH || '';
16
+ }
17
+ function getJwtSecret() {
18
+ const authCode = getAuthCode();
19
+ return process.env.JWT_SECRET || (authCode ? crypto_1.default.createHash('sha256').update(authCode).digest('hex') : '');
20
+ }
15
21
  const TOKEN_EXPIRY = '7d'; // 7天有效期
16
22
  /**
17
23
  * 检查是否启用鉴权
18
24
  */
19
25
  function isAuthEnabled() {
20
- return AUTH_CODE.trim().length > 0;
26
+ return getAuthCode().trim().length > 0;
21
27
  }
22
28
  /**
23
29
  * 验证鉴权码
@@ -26,7 +32,7 @@ function verifyAuthCode(authCode) {
26
32
  if (!isAuthEnabled()) {
27
33
  return true; // 未启用鉴权,直接通过
28
34
  }
29
- return authCode === AUTH_CODE;
35
+ return authCode === getAuthCode();
30
36
  }
31
37
  /**
32
38
  * 生成 JWT Token
@@ -35,14 +41,14 @@ function generateToken() {
35
41
  const payload = {
36
42
  authenticated: true,
37
43
  };
38
- return jsonwebtoken_1.default.sign(payload, JWT_SECRET, { expiresIn: TOKEN_EXPIRY });
44
+ return jsonwebtoken_1.default.sign(payload, getJwtSecret(), { expiresIn: TOKEN_EXPIRY });
39
45
  }
40
46
  /**
41
47
  * 验证 JWT Token
42
48
  */
43
49
  function verifyToken(token) {
44
50
  try {
45
- jsonwebtoken_1.default.verify(token, JWT_SECRET);
51
+ jsonwebtoken_1.default.verify(token, getJwtSecret());
46
52
  return true;
47
53
  }
48
54
  catch (error) {