Qilan2 commited on
Commit
4ff14e1
·
verified ·
1 Parent(s): 56df944

Upload 2 files

Browse files
Files changed (2) hide show
  1. config.default.js +6 -0
  2. ip-whitelist.js +33 -0
config.default.js ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ // 内部API的IP白名单配置
2
+ export const internalApiWhitelist = [
3
+ '127.0.0.1', // localhost
4
+ // '::1', // localhost IPv6
5
+ // '192.168.1.0/24' // 本地网络示例
6
+ ];
ip-whitelist.js ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { internalApiWhitelist } from '../config.default.js';
2
+
3
+ /**
4
+ * 检查IP是否在白名单中的中间件
5
+ * @param {import('express').Request} req
6
+ * @param {import('express').Response} res
7
+ * @param {import('express').NextFunction} next
8
+ */
9
+ export function ipWhitelistMiddleware(req, res, next) {
10
+ const clientIp = req.ip || req.connection.remoteAddress;
11
+
12
+ // 检查IP是否在白名单中
13
+ const isWhitelisted = internalApiWhitelist.some(whitelistedIp => {
14
+ if (whitelistedIp.includes('/')) {
15
+ // 简单的CIDR检查 (仅支持 /24 格式)
16
+ const [network] = whitelistedIp.split('/');
17
+ const networkPrefix = network.split('.').slice(0, 3).join('.');
18
+ const clientPrefix = clientIp.split('.').slice(0, 3).join('.');
19
+ return networkPrefix === clientPrefix;
20
+ }
21
+ // 精确IP匹配
22
+ return clientIp === whitelistedIp;
23
+ });
24
+
25
+ if (!isWhitelisted) {
26
+ console.warn(`未经授权的访问 IP: ${clientIp}`);
27
+ return res.status(403).json({
28
+ error: 'Access denied: Your IP is not whitelisted'
29
+ });
30
+ }
31
+
32
+ next();
33
+ }