diff --git a/doc/HTTPS_SETUP.md b/doc/HTTPS_SETUP.md index 1fa6f17e..171568f7 100644 --- a/doc/HTTPS_SETUP.md +++ b/doc/HTTPS_SETUP.md @@ -64,7 +64,7 @@ services: wrong-notebook: ports: - - "443:443" # HTTPS 端口 + - "443:8443" # HTTPS 端口(容器内非特权端口) environment: - HTTPS_ENABLED=true - CERT_DOMAIN=YOUR_IP_OR_DOMAIN # 替换为你的 IP 或域名 @@ -101,7 +101,7 @@ docker logs wrong-notebook | grep -i cert | `CERT_DOMAIN` | 否 | `localhost` | 证书的 CN(你的 IP 或域名) | | `NEXTAUTH_URL` | 是 | - | 完整访问地址 | | `AUTH_TRUST_HOST` | 是 | - | 设为 `true` | -| `HTTPS_PORT` | 否 | `443` | HTTPS 监听端口 | +| `HTTPS_PORT` | 否 | `8443` | 容器内 HTTPS 监听端口;宿主 443 映射到该端口 | ### 使用自定义证书 diff --git a/doc/wiki/Deployment.md b/doc/wiki/Deployment.md index 96a604a2..2d23d17a 100644 --- a/doc/wiki/Deployment.md +++ b/doc/wiki/Deployment.md @@ -193,7 +193,7 @@ DSM 7.2 及以上使用 Container Manager;旧版 DSM 的 Docker 套件操作 应用也提供内置 HTTPS,参考仓库中的 [`docker-compose.https.yml`](https://github.com/margrop/wrong-notebook/blob/main/docker-compose.https.yml): - 设置 `HTTPS_ENABLED=true`、`CERT_DOMAIN` 和正确的 `NEXTAUTH_URL`。 -- 映射容器 `443` 端口,将证书目录挂载到 `/app/certs`。 +- 将宿主 `443` 映射到容器内非特权端口 `8443`,并将证书目录挂载到 `/app/certs`。 - 自定义证书文件名为 `cert.pem` 和 `key.pem`;缺失时启动脚本会尝试生成自签名证书。 自签名证书需要客户端正确配置并信任。HTTPS 是屏幕截图的必要条件之一,移动浏览器仍可能不支持 `getDisplayMedia()`。更多说明见 [HTTPS 配置文档](https://github.com/margrop/wrong-notebook/blob/main/doc/HTTPS_SETUP.md)。 diff --git a/doc/wiki/en/Deployment-en.md b/doc/wiki/en/Deployment-en.md index 39921f62..c09d1b02 100644 --- a/doc/wiki/en/Deployment-en.md +++ b/doc/wiki/en/Deployment-en.md @@ -193,7 +193,7 @@ The reverse proxy should forward `X-Real-IP` or `X-Forwarded-For`, because faile The app also provides built-in HTTPS; see [`docker-compose.https.yml`](https://github.com/margrop/wrong-notebook/blob/main/docker-compose.https.yml) in the repository: - Set `HTTPS_ENABLED=true`, `CERT_DOMAIN` and the correct `NEXTAUTH_URL`. -- Map container port `443` and mount the certificate directory at `/app/certs`. +- Map host port `443` to the container's unprivileged port `8443`, and mount the certificate directory at `/app/certs`. - Custom certificates must be named `cert.pem` and `key.pem`; if they are missing, the startup script tries to generate a self-signed certificate. Clients must be set up to trust a self-signed certificate. HTTPS is one of the requirements for screenshots, and mobile browsers may still not support `getDisplayMedia()`. See the [HTTPS setup guide](https://github.com/margrop/wrong-notebook/blob/main/doc/HTTPS_SETUP.md) for details. diff --git a/docker-compose.https.yml b/docker-compose.https.yml index c48f64f2..8096c5b2 100644 --- a/docker-compose.https.yml +++ b/docker-compose.https.yml @@ -25,7 +25,7 @@ services: restart: always ports: - "80:3000" # HTTP(可选) - - "443:443" # HTTPS + - "443:8443" # HTTPS(容器内非特权端口) environment: # === 必须配置(请修改) === # 替换为你的实际访问地址 diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index fd196594..4661f143 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -115,6 +115,9 @@ node "$SEED_CHINESE_TAGS_SCRIPT" node "$SEED_UNIVERSITY_GRADES_SCRIPT" # HTTPS Setup +# 非 root 运行时默认 8443,compose 将宿主 443 映射到该端口 +HTTPS_PORT="${HTTPS_PORT:-8443}" +export HTTPS_PORT CERT_DIR="/app/certs" CERT_FILE="$CERT_DIR/cert.pem" KEY_FILE="$CERT_DIR/key.pem" @@ -154,7 +157,7 @@ if [ "$HTTPS_ENABLED" = "true" ]; then # 启动 HTTPS 代理 if [ -f "$CERT_FILE" ] && [ -f "$KEY_FILE" ]; then - echo "[Entrypoint] 启动 HTTPS 代理 (端口 443)..." + echo "[Entrypoint] 启动 HTTPS 代理 (端口 $HTTPS_PORT)..." $RUN_AS node /app/https-server.js & fi fi diff --git a/https-server.js b/https-server.js index a4e7845b..91945abe 100644 --- a/https-server.js +++ b/https-server.js @@ -32,8 +32,10 @@ const options = { }; const port = parseInt(process.env.PORT || '3000', 10); +// 非 root 运行时无法绑定 443 特权端口,默认使用 8443,由 compose 映射到宿主 443 +const httpsPort = parseInt(process.env.HTTPS_PORT || '8443', 10); -console.log(`[HTTPS] 启动 HTTPS 代理,端口 443 -> HTTP ${port}`); +console.log(`[HTTPS] 启动 HTTPS 代理,端口 ${httpsPort} -> HTTP ${port}`); console.log(`[HTTPS] 代理超时设置: ${PROXY_TIMEOUT / 1000} 秒`); const httpsServer = https.createServer(options, (req, res) => { @@ -46,6 +48,11 @@ const httpsServer = https.createServer(options, (req, res) => { ...req.headers, // 确保 Host 头正确 host: req.headers.host || `127.0.0.1:${port}`, + // 下游按 HTTPS 处理 Secure Cookie、回调地址与来源 IP + 'x-forwarded-proto': 'https', + 'x-forwarded-for': req.headers['x-forwarded-for'] + ? `${req.headers['x-forwarded-for']}, ${req.socket.remoteAddress}` + : req.socket.remoteAddress, }, // 设置代理请求超时 timeout: PROXY_TIMEOUT, @@ -80,9 +87,10 @@ const httpsServer = https.createServer(options, (req, res) => { } }); - // 客户端断开连接时,终止代理请求 - req.on('close', () => { - proxyReq.destroy(); + // 客户端断开连接时终止代理请求;Node 16+ 在请求体读完后也会触发 req close, + // 因此监听 res close 并只在响应尚未写完时销毁,避免正常请求被误判为 502 + res.on('close', () => { + if (!res.writableEnded) proxyReq.destroy(); }); // 将请求体转发到代理 @@ -94,8 +102,6 @@ httpsServer.timeout = PROXY_TIMEOUT; httpsServer.keepAliveTimeout = 65000; // 65 秒 Keep-Alive httpsServer.headersTimeout = 66000; // 略大于 keepAliveTimeout -const httpsPort = parseInt(process.env.HTTPS_PORT || '443', 10); - httpsServer.listen(httpsPort, '0.0.0.0', () => { console.log(`[HTTPS] HTTPS 服务器已启动,监听端口 ${httpsPort}`); }); diff --git a/src/__tests__/unit/https-server.test.ts b/src/__tests__/unit/https-server.test.ts new file mode 100644 index 00000000..0a42e277 --- /dev/null +++ b/src/__tests__/unit/https-server.test.ts @@ -0,0 +1,167 @@ +/** + * 内置 HTTPS 代理集成测试: + * 覆盖 GET/POST 正常转发、Node 请求体读完后的 close 不误杀代理、 + * X-Forwarded-* 头与默认非特权监听端口。 + */ +import fs from 'fs'; +import http from 'http'; +import https from 'https'; +import net from 'net'; +import os from 'os'; +import path from 'path'; +import { spawn, spawnSync, type ChildProcess } from 'child_process'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +const script = path.join(__dirname, '../../../https-server.js'); + +const children: ChildProcess[] = []; +const servers: (http.Server | net.Server)[] = []; +const tempDirs: string[] = []; +let certDir: string; +let receivedHeaders: http.IncomingHttpHeaders[] = []; + +function stopChild(child: ChildProcess): Promise { + const { promise, resolve } = Promise.withResolvers(); + if (child.exitCode !== null) { + resolve(); + return promise; + } + child.once('exit', () => resolve()); + child.kill('SIGKILL'); + return promise; +} + +afterEach(async () => { + await Promise.all(children.map((child) => stopChild(child))); + children.length = 0; + for (const server of servers) { + if (server instanceof http.Server) server.closeAllConnections(); + server.close(); + } + servers.length = 0; + for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true }); + tempDirs.length = 0; +}); + +beforeEach(() => { + certDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wn-https-cert-')); + tempDirs.push(certDir); + const result = spawnSync('openssl', [ + 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', + '-keyout', path.join(certDir, 'key.pem'), + '-out', path.join(certDir, 'cert.pem'), + '-days', '1', '-subj', '/CN=localhost', + ], { encoding: 'utf8' }); + expect(result.status, result.stderr).toBe(0); + receivedHeaders = []; +}); + +function listenHttp(handler: http.RequestListener): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const server = http.createServer(handler); + servers.push(server); + server.unref(); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + if (!address || typeof address === 'string') reject(new Error('未取得 HTTP 端口')); + else resolve(address.port); + }); + return promise; +} + +function startProxy(env: NodeJS.ProcessEnv): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const child = spawn(process.execPath, [script], { + env: { ...process.env, CERT_DIR: certDir, ...env }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + children.push(child); + let output = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => { + output += chunk.toString(); + const match = /HTTPS 服务器已启动,监听端口 (\d+)/.exec(output); + if (match) resolve(Number(match[1])); + }); + child.stderr.on('data', (chunk) => { + stderr += chunk.toString(); + }); + child.once('exit', (code) => reject(new Error(`HTTPS 代理提前退出:${code} ${stderr}`))); + return promise; +} + +function requestHttps(port: number, request: { path: string; method?: string; body?: string }): Promise<{ status: number; body: string; headers: http.IncomingHttpHeaders }> { + const { promise, resolve, reject } = Promise.withResolvers<{ status: number; body: string; headers: http.IncomingHttpHeaders }>(); + const req = https.request({ + host: '127.0.0.1', + port, + path: request.path, + method: request.method ?? 'GET', + rejectUnauthorized: false, + headers: request.body ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(request.body) } : {}, + }, (res) => { + let body = ''; + res.setEncoding('utf8'); + res.on('data', (chunk) => { + body += chunk; + }); + res.on('end', () => resolve({ status: res.statusCode ?? 0, body, headers: res.headers })); + }); + req.once('error', reject); + if (request.body) req.write(request.body); + req.end(); + return promise; +} + +describe('https-server.js', () => { + it('正常转发 GET 并补上 X-Forwarded-Proto/For', async () => { + const httpPort = await listenHttp((req, res) => { + receivedHeaders.push(req.headers); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ status: 'ok', url: req.url })); + }); + const httpsPort = await startProxy({ PORT: String(httpPort), HTTPS_PORT: '8443' }); + + const response = await requestHttps(httpsPort, { path: '/api/health' }); + expect(response.status).toBe(200); + expect(JSON.parse(response.body)).toEqual({ status: 'ok', url: '/api/health' }); + expect(receivedHeaders).toHaveLength(1); + expect(receivedHeaders[0]['x-forwarded-proto']).toBe('https'); + expect(receivedHeaders[0]['x-forwarded-for']).toContain('127.0.0.1'); + }); + + it('POST 请求体读完后仍等待后端响应,不返回 502', async () => { + const httpPort = await listenHttp((req, res) => { + receivedHeaders.push(req.headers); + let body = ''; + req.setEncoding('utf8'); + req.on('data', (chunk) => { + body += chunk; + }); + req.on('end', () => { + // 真实延时用于复现 Node 在请求体读完触发 close 的竞态:后端必须晚于 close 才响应 + setTimeout(() => { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ echo: body })); + }, 200); + }); + }); + const httpsPort = await startProxy({ PORT: String(httpPort), HTTPS_PORT: '8443' }); + + const payload = JSON.stringify({ question: '2+3=?' }); + const response = await requestHttps(httpsPort, { path: '/grade', method: 'POST', body: payload }); + expect(response.status).toBe(200); + expect(JSON.parse(response.body)).toEqual({ echo: payload }); + }); + + it('默认监听非特权端口 8443,非 root 启动不再 EACCES', async () => { + const httpPort = await listenHttp((req, res) => { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ status: 'ok' })); + }); + const httpsPort = await startProxy({ PORT: String(httpPort) }); + expect(httpsPort).toBe(8443); + expect((await requestHttps(httpsPort, { path: '/api/health' })).status).toBe(200); + }); +});