@less-is-more/less-js 1.5.0 → 1.5.1-1
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/package.json +1 -1
- package/src/router.js +54 -0
package/package.json
CHANGED
package/src/router.js
CHANGED
|
@@ -71,6 +71,7 @@ module.exports = class Router {
|
|
|
71
71
|
// 兼容非阿里云
|
|
72
72
|
await this._handleParams(req);
|
|
73
73
|
console.log(
|
|
74
|
+
req.sourceIp,
|
|
74
75
|
"p:",
|
|
75
76
|
req.method,
|
|
76
77
|
req.path,
|
|
@@ -184,6 +185,11 @@ module.exports = class Router {
|
|
|
184
185
|
delete req.params[0];
|
|
185
186
|
}
|
|
186
187
|
|
|
188
|
+
// 处理IP
|
|
189
|
+
if (Param.isBlank(req.sourceIp)) {
|
|
190
|
+
req.sourceIp = this._getRealIP(req);
|
|
191
|
+
}
|
|
192
|
+
|
|
187
193
|
if (!Param.isBlank(req.queries)) {
|
|
188
194
|
Object.keys(req.queries).forEach((n) => (req.params[n] = req.queries[n]));
|
|
189
195
|
}
|
|
@@ -274,4 +280,52 @@ module.exports = class Router {
|
|
|
274
280
|
static useDefaultFormat(isUse) {
|
|
275
281
|
this.#defaultFormat = isUse;
|
|
276
282
|
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* 获取真实IP地址
|
|
286
|
+
* @param {object} req 请求对象
|
|
287
|
+
* @returns {string} IP地址
|
|
288
|
+
*/
|
|
289
|
+
static _getRealIP(req) {
|
|
290
|
+
// 检查常用的HTTP头字段来获取原始IP地址
|
|
291
|
+
const forwardedIP =
|
|
292
|
+
req.headers["x-forwarded-for"] ||
|
|
293
|
+
req.headers["x-real-ip"] ||
|
|
294
|
+
req.headers["x-client-ip"] ||
|
|
295
|
+
req.headers["x-cluster-client-ip"];
|
|
296
|
+
|
|
297
|
+
if (forwardedIP) {
|
|
298
|
+
// x-forwarded-for 可能包含多个IP地址,第一个通常是真实的客户端IP
|
|
299
|
+
const ipList = forwardedIP.split(",");
|
|
300
|
+
const clientIP = ipList[0].trim();
|
|
301
|
+
if (clientIP && this.isValidIP(clientIP)) {
|
|
302
|
+
return clientIP;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// fallback到连接级别的IP
|
|
307
|
+
return req.connection
|
|
308
|
+
? req.connection.remoteAddress
|
|
309
|
+
: req.socket
|
|
310
|
+
? req.socket.remoteAddress
|
|
311
|
+
: "";
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* 验证IP地址格式是否有效
|
|
316
|
+
* @param {string} ip IP地址字符串
|
|
317
|
+
* @returns {boolean} 是否为有效的IP地址
|
|
318
|
+
*/
|
|
319
|
+
static isValidIP(ip) {
|
|
320
|
+
// 简单验证IP格式,支持IPv4和基本的IPv6格式
|
|
321
|
+
if (!ip || typeof ip !== "string") return false;
|
|
322
|
+
|
|
323
|
+
// IPv4 正则表达式
|
|
324
|
+
const ipv4Regex =
|
|
325
|
+
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
|
|
326
|
+
// IPv6 正则表达式(简化版)
|
|
327
|
+
const ipv6Regex = /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/;
|
|
328
|
+
|
|
329
|
+
return ipv4Regex.test(ip.trim()) || ipv6Regex.test(ip.trim());
|
|
330
|
+
}
|
|
277
331
|
};
|