fix: 修复 Docker 默认弱密钥、健康检查端口与版本检测

- docker-compose.yml 移除硬编码 NEXTAUTH_SECRET,留空时由入口脚本生成强随机密钥,并补充日志轮转
- HEALTHCHECK 按 PORT 环境变量探测,健康时显式退出,避免探活超时
- docker-entrypoint.sh 优先读取构建注入的 APP_VERSION,为空时回退 package.json
Refs: https://github.com/margrop/wrong-notebook/issues/161
This commit is contained in:
margrop
2026-12-04 01:29:21 +08:00
parent ac8dd8809c
commit 016ecf4db3
6 changed files with 142 additions and 9 deletions

View File

@@ -113,7 +113,7 @@ LABEL org.opencontainers.image.source="https://github.com/margrop/wrong-notebook
EXPOSE 3000
HEALTHCHECK --interval=15s --timeout=5s --start-period=45s --retries=4 \
CMD node -e "fetch('http://127.0.0.1:3000/api/health').then(async r=>{if(!r.ok||(await r.json()).status!=='ok')process.exit(1)}).catch(()=>process.exit(1))"
CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||3000)+'/api/health').then(async r=>{if(!r.ok||(await r.json()).status!=='ok')process.exit(1);process.exit(0)}).catch(()=>process.exit(1))"
# Use entrypoint script to handle DB initialization
ENTRYPOINT ["./docker-entrypoint.sh"]

View File

@@ -269,7 +269,7 @@ Every release publishes an image to GitHub Container Registry, `ghcr.io/margrop/
ghcr.io/margrop/wrong-notebook:latest
```
Or download [`docker-compose.yml`](docker-compose.yml) into the current directory, set `NEXTAUTH_SECRET` (and `NEXTAUTH_URL`), then run `docker compose up -d`.
Or download [`docker-compose.yml`](docker-compose.yml) into the current directory, set `NEXTAUTH_URL` (leave `NEXTAUTH_SECRET` empty to auto-generate), then run `docker compose up -d`.
When `NEXTAUTH_SECRET` is not set, the container generates a secret on first start and keeps it in `.nextauth_secret` under the data directory.

View File

@@ -267,7 +267,7 @@ wrong-notebook --port 3000
ghcr.io/margrop/wrong-notebook:latest
```
或下载仓库中的 [`docker-compose.yml`](docker-compose.yml) 放到当前目录,修改 `NEXTAUTH_SECRET`(及 `NEXTAUTH_URL`)后执行 `docker compose up -d`。
或下载仓库中的 [`docker-compose.yml`](docker-compose.yml) 放到当前目录,按需设置 `NEXTAUTH_URL`(`NEXTAUTH_SECRET` 可留空,容器自动生成)后执行 `docker compose up -d`。
未设置 `NEXTAUTH_SECRET` 时,容器首次启动会生成密钥并保存到数据目录的 `.nextauth_secret`,之后保持不变。

View File

@@ -1,5 +1,3 @@
version: '3'
services:
wrong-notebook:
image: ghcr.io/margrop/wrong-notebook:latest
@@ -8,9 +6,14 @@ services:
ports:
- "3000:3000"
environment:
# NEXTAUTH_URL 根据实际情况设置你的信息
# NEXTAUTH_URL 根据实际情况设置;NEXTAUTH_SECRET 留空时容器首次启动自动生成并保存到数据卷
#- NEXTAUTH_URL=http://your_domain_name:3000
- NEXTAUTH_SECRET=your_secret_key
#- NEXTAUTH_SECRET=可选,留空自动生成
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
volumes:
# Persist the SQLite database
- ./data:/app/data

View File

@@ -13,8 +13,8 @@ REBUILD_TAGS_SCRIPT="/app/dist-scripts/scripts/rebuild-system-tags.js"
SEED_CHINESE_TAGS_SCRIPT="/app/dist-scripts/scripts/seed-chinese-primary.js"
SEED_UNIVERSITY_GRADES_SCRIPT="/app/dist-scripts/scripts/seed-university-grades.js"
# Get current app version from package.json
CURRENT_VERSION=$(node -p "require('./package.json').version" 2>/dev/null || echo "unknown")
# 版本优先取构建时按 Git 标签注入的 APP_VERSION,为空时回退到 package.json
CURRENT_VERSION="${APP_VERSION:-$(node -p "require('./package.json').version" 2>/dev/null || echo "unknown")}"
# 配置目录默认 /app/config,可用 CONFIG_DIR 放到数据卷内
CONFIG_PATH="${CONFIG_DIR:-/app/config}"

View File

@@ -0,0 +1,130 @@
/**
* Docker 默认配置测试:
* compose 不再硬编码弱密钥并带日志轮转,HEALTHCHECK 跟随 PORT,
* 入口脚本优先采用镜像构建时的 APP_VERSION。
*/
import fs from 'fs';
import http from 'http';
import os from 'os';
import path from 'path';
import { spawn, spawnSync } from 'child_process';
import { afterEach, describe, expect, it } from 'vitest';
const root = path.join(__dirname, '../../../../');
const read = (file: string) => fs.readFileSync(path.join(root, file), 'utf8');
const servers: http.Server[] = [];
const tempDirs: string[] = [];
afterEach(() => {
for (const server of servers) {
server.closeAllConnections();
server.close();
}
servers.length = 0;
for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true });
tempDirs.length = 0;
});
function listen(handler: http.RequestListener): Promise<number> {
const { promise, resolve, reject } = Promise.withResolvers<number>();
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('未取得监听端口'));
else resolve(address.port);
});
return promise;
}
function runShell(command: string, env: NodeJS.ProcessEnv, timeoutMs: number): Promise<{ status: number | null; stderr: string }> {
const { promise, resolve } = Promise.withResolvers<{ status: number | null; stderr: string }>();
const child = spawn('sh', ['-c', command], { env, stdio: ['ignore', 'ignore', 'pipe'] });
let stderr = '';
child.stderr.on('data', (chunk) => {
stderr += chunk.toString();
});
const timer = setTimeout(() => child.kill(), timeoutMs);
timer.unref();
child.once('exit', (status) => {
clearTimeout(timer);
resolve({ status, stderr });
});
return promise;
}
describe('docker compose 默认配置', () => {
it('不再硬编码默认弱密钥', () => {
const compose = read('docker-compose.yml');
expect(compose).not.toContain('your_secret_key');
expect(compose).toMatch(/NEXTAUTH_SECRET.*留空自动生成/);
});
it('配置日志轮转,避免长期运行写满磁盘', () => {
const compose = read('docker-compose.yml');
expect(compose).toContain('logging:');
expect(compose).toContain('max-size: "10m"');
expect(compose).toContain('max-file: "3"');
});
});
describe('Dockerfile HEALTHCHECK', () => {
const healthCommand = (): string => {
const line = read('Dockerfile').split('\n').find((value) => value.includes('CMD node -e "fetch'));
if (!line) throw new Error('未找到 HEALTHCHECK 命令');
return line.trim().slice('CMD '.length);
};
it('按 PORT 环境变量探测健康接口', async () => {
const port = await listen((req, res) => {
if (req.url === '/api/health') {
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ status: 'ok' }));
return;
}
res.writeHead(404);
res.end();
});
const result = await runShell(healthCommand(), { ...process.env, PORT: String(port) }, 5000);
expect(result.status, result.stderr).toBe(0);
});
it('接口不可达时以非零退出', async () => {
const result = await runShell(healthCommand(), { ...process.env, PORT: '1' }, 5000);
expect(result.status).toBe(1);
});
});
describe('docker-entrypoint 版本检测', () => {
const versionLine = (): string => {
const line = read('docker-entrypoint.sh').split('\n').find((value) => value.startsWith('CURRENT_VERSION='));
if (!line) throw new Error('未找到版本检测语句');
return line;
};
function currentVersion(env: Record<string, string>): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wn-version-'));
tempDirs.push(dir);
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ version: '0.0.0' }));
const result = spawnSync('sh', ['-c', `${versionLine()}\nprintf '%s\\n' "$CURRENT_VERSION"`], {
cwd: dir,
encoding: 'utf8',
env: { ...process.env, ...env },
});
expect(result.status).toBe(0);
return result.stdout.trim();
}
it('优先使用构建时注入的 APP_VERSION', () => {
expect(currentVersion({ APP_VERSION: 'v2026.12.4-1' })).toBe('v2026.12.4-1');
});
it('APP_VERSION 为空时回退 package.json 版本', () => {
const env = { ...process.env };
delete env.APP_VERSION;
expect(currentVersion(env)).toBe('0.0.0');
});
});