From d0ce3b92d56455682f32a723bb80362a8c2a5aa7 Mon Sep 17 00:00:00 2001 From: huangxd- <649924757@qq.com> Date: Sun, 2 Aug 2026 08:54:55 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=E5=8F=8D=E5=90=91?= =?UTF-8?q?=E4=BB=A3=E7=90=86HTTPS=E5=8D=8F=E8=AE=AE=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=EF=BC=8C=E7=94=9F=E6=88=90=E6=AD=A3=E7=A1=AE=E7=9A=84=E5=AF=B9?= =?UTF-8?q?=E5=A4=96=E9=93=BE=E6=8E=A5=20(#416)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增环境变量 `DANMU_API_PUBLIC_PROTO` 用于指定对外协议 - 请求处理时优先读取 `X-Forwarded-Proto` 头,无则回退至配置变量 - 修复反向代理环境下弹幕链接协议错误的问题 --- README.md | 1 + config/.env.example | 4 ++++ danmu_api/server.js | 20 ++++++++++++++++++-- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 84b541b..da2743a 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,7 @@ LogVar 弹幕 API 服务器 ``` 服务器将在 `http://{ip}:9321` 运行,默认token是`87654321`。 如需修改端口,可设置环境变量 `DANMU_API_PORT`(例如 `DANMU_API_PORT=8080 npm start`)。 + HTTPS 反向代理应传递 `X-Forwarded-Proto`;无法传递时可设置 `DANMU_API_PUBLIC_PROTO=https`,用于生成正确的对外弹幕链接。 **热更新支持**:修改 `config/.env`,应用会自动检测并重新加载配置(无需重启应用)。 diff --git a/config/.env.example b/config/.env.example index 0f45fda..0ff6b4f 100644 --- a/config/.env.example +++ b/config/.env.example @@ -22,6 +22,10 @@ TOKEN=87654321 # 说明:本地 Node 服务会优先读取 DANMU_API_PORT;未设置时回退到 9321 # DANMU_API_PORT=9321 +# API 对外访问协议(反向代理未传递 X-Forwarded-Proto 时使用) +# 可选值:http、https;默认值:http +# DANMU_API_PUBLIC_PROTO=https + # 系统管理访问令牌(用于系统管理功能) # 如果未配置此值,则无法访问系统管理功能,需要先配置后在URL中填入此token才能打开系统管理 # 默认值:空(不启用系统管理访问控制) diff --git a/danmu_api/server.js b/danmu_api/server.js index 96bac06..8c21641 100644 --- a/danmu_api/server.js +++ b/danmu_api/server.js @@ -49,6 +49,21 @@ function detectNodeDeployPlatform() { return "node"; } +function resolvePublicRequestProtocol(req) { + const forwardedProto = String(req.headers['x-forwarded-proto'] || '') + .split(',')[0] + .trim() + .toLowerCase(); + if (forwardedProto === 'http' || forwardedProto === 'https') { + return forwardedProto; + } + + const configuredProto = String(process.env.DANMU_API_PUBLIC_PROTO || 'http') + .trim() + .toLowerCase(); + return configuredProto === 'https' ? 'https' : 'http'; +} + /** * 检查并自动复制配置文件 * 在Node环境下,如果config目录下没有.env,则自动从.env.example拷贝一份生成.env @@ -270,8 +285,9 @@ process.on('SIGINT', cleanupWatcher); function createServer() { return http.createServer(async (req, res) => { try { - // 构造完整的请求 URL - const fullUrl = `http://${req.headers.host}${req.url}`; + // 构造完整的请求 URL,反向代理场景优先使用客户端原始协议 + const scheme = resolvePublicRequestProtocol(req); + const fullUrl = `${scheme}://${req.headers.host}${req.url}`; // 获取请求客户端的ip,兼容反向代理场景 let clientIp = 'unknown';