From 61e10edc5febbfe360e1def39115d9846409f800 Mon Sep 17 00:00:00 2001 From: margrop <1731827+margrop@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:53:21 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E5=92=8C=E4=BC=9A=E8=AF=9D=E5=AF=86=E9=92=A5=E8=AF=BB=E5=86=99?= =?UTF-8?q?=E6=B6=88=E9=99=A4=E5=85=88=E5=88=A4=E6=96=AD=E5=90=8E=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E7=9A=84=E7=AB=9E=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 配置文件直接读取并处理不存在的情况,写入改为临时文件加改名,避免读到写了一半的配置 - 启动器生成会话密钥时以独占方式创建,不覆盖同时启动的进程刚生成的密钥 Co-Authored-By: Claude Opus 5.5 --- packaging/runtime/launcher.js | 28 ++++++-- src/__tests__/unit/config.test.ts | 72 +++++++++++++-------- src/__tests__/unit/package-launcher.test.ts | 21 +++++- src/lib/config.ts | 31 +++++++-- 4 files changed, 113 insertions(+), 39 deletions(-) diff --git a/packaging/runtime/launcher.js b/packaging/runtime/launcher.js index ac98cf89..67bda7b8 100644 --- a/packaging/runtime/launcher.js +++ b/packaging/runtime/launcher.js @@ -49,15 +49,31 @@ function appVersion() { /** NextAuth 会话密钥:首次运行随机生成并保存,之后保持不变,避免重启后登录失效 */ function ensureSecret(dataDir) { const file = path.join(dataDir, '.nextauth_secret'); - if (fs.existsSync(file)) { - const saved = fs.readFileSync(file, 'utf8').trim(); - if (saved) return saved; - } + const saved = readTextIfExists(file).trim(); + if (saved) return saved; const secret = crypto.randomBytes(32).toString('base64'); - fs.writeFileSync(file, secret, { mode: 0o600 }); + try { + // wx:文件已存在时失败,不覆盖同时启动的另一个进程刚生成的密钥 + fs.writeFileSync(file, secret, { mode: 0o600, flag: 'wx' }); + } catch (error) { + if (error.code !== 'EEXIST') throw error; + const other = readTextIfExists(file).trim(); + if (other) return other; + // 已有的是空文件,直接覆盖 + fs.writeFileSync(file, secret, { mode: 0o600 }); + } return secret; } +function readTextIfExists(file) { + try { + return fs.readFileSync(file, 'utf8'); + } catch (error) { + if (error.code === 'ENOENT') return ''; + throw error; + } +} + /** Prisma 的 SQLite 地址统一使用正斜杠,Windows 盘符路径也可用 */ function sqliteUrl(file) { return `file:${file.split(path.sep).join('/')}`; @@ -181,7 +197,7 @@ function start(options = {}) { require(path.join(APP_DIR, 'server.js')); } -module.exports = { prepare, start, parseArgs, defaultDataDir, sqliteUrl }; +module.exports = { prepare, start, parseArgs, defaultDataDir, sqliteUrl, ensureSecret }; if (require.main === module) { try { diff --git a/src/__tests__/unit/config.test.ts b/src/__tests__/unit/config.test.ts index 13fa7f4f..23831aea 100644 --- a/src/__tests__/unit/config.test.ts +++ b/src/__tests__/unit/config.test.ts @@ -8,16 +8,17 @@ import fs from 'fs'; import path from 'path'; // Mock fs module -vi.mock('fs', () => ({ - default: { - existsSync: vi.fn(), - readFileSync: vi.fn(), - writeFileSync: vi.fn(), - }, - existsSync: vi.fn(), - readFileSync: vi.fn(), - writeFileSync: vi.fn(), -})); +vi.mock('fs', () => { + const mocked = { readFileSync: vi.fn(), writeFileSync: vi.fn(), renameSync: vi.fn() }; + return { default: mocked, ...mocked }; +}); + +/** 模拟配置文件不存在 */ +function mockNoConfigFile() { + vi.mocked(fs.readFileSync).mockImplementation(() => { + throw Object.assign(new Error('ENOENT: no such file'), { code: 'ENOENT' }); + }); +} // Store original env const originalEnv = { ...process.env }; @@ -37,7 +38,7 @@ describe('config module', () => { describe('getAppConfig', () => { it('应该返回默认配置(文件不存在时)', async () => { - vi.mocked(fs.existsSync).mockReturnValue(false); + mockNoConfigFile(); const { getAppConfig } = await import('@/lib/config'); const config = getAppConfig(); @@ -48,7 +49,6 @@ describe('config module', () => { }); it.each([undefined, null, 'invalid/zone'])('旧配置或无效时区 %s 回退为北京时间', async (timeZone) => { - vi.mocked(fs.existsSync).mockReturnValue(true); vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify({ aiProvider: 'gemini', timeZone })); const { getAppConfig, getAppTimeZone } = await import('@/lib/config'); expect(getAppConfig().timeZone).toBe('Asia/Shanghai'); @@ -56,24 +56,23 @@ describe('config module', () => { }); it('可保存并重新读取管理员配置的时区', async () => { - vi.mocked(fs.existsSync).mockReturnValue(false); + mockNoConfigFile(); const { updateAppConfig, getAppTimeZone } = await import('@/lib/config'); const config = updateAppConfig({ timeZone: 'America/New_York' }); - vi.mocked(fs.existsSync).mockReturnValue(true); vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(config)); expect(getAppTimeZone()).toBe('America/New_York'); expect(fs.writeFileSync).toHaveBeenCalledWith(expect.any(String), expect.stringContaining('"timeZone": "America/New_York"')); }); it('直接写配置也拒绝无效时区', async () => { - vi.mocked(fs.existsSync).mockReturnValue(false); + mockNoConfigFile(); const { updateAppConfig } = await import('@/lib/config'); expect(() => updateAppConfig({ timeZone: 'invalid/zone' })).toThrow('INVALID_TIME_ZONE'); expect(fs.writeFileSync).not.toHaveBeenCalled(); }); it('应该从环境变量读取 AI Provider', async () => { - vi.mocked(fs.existsSync).mockReturnValue(false); + mockNoConfigFile(); process.env.AI_PROVIDER = 'openai'; const { getAppConfig } = await import('@/lib/config'); @@ -83,7 +82,7 @@ describe('config module', () => { }); it('应该从环境变量读取 API Keys', async () => { - vi.mocked(fs.existsSync).mockReturnValue(false); + mockNoConfigFile(); process.env.OPENAI_API_KEY = 'sk-env-key'; process.env.GOOGLE_API_KEY = 'AIza-env-key'; @@ -110,7 +109,6 @@ describe('config module', () => { activeInstanceId: 'test-instance', }, }; - vi.mocked(fs.existsSync).mockReturnValue(true); vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(fileConfig)); const { getAppConfig } = await import('@/lib/config'); @@ -124,7 +122,6 @@ describe('config module', () => { }); it('应该在配置文件解析失败时返回默认值', async () => { - vi.mocked(fs.existsSync).mockReturnValue(true); vi.mocked(fs.readFileSync).mockReturnValue('invalid json{'); const { getAppConfig } = await import('@/lib/config'); @@ -135,7 +132,7 @@ describe('config module', () => { }); it('应该使用环境变量的模型名称', async () => { - vi.mocked(fs.existsSync).mockReturnValue(false); + mockNoConfigFile(); process.env.OPENAI_API_KEY = 'sk-test'; process.env.OPENAI_MODEL = 'gpt-4-turbo'; process.env.GEMINI_MODEL = 'gemini-3.0'; @@ -148,7 +145,7 @@ describe('config module', () => { }); it('应该使用默认模型名称(无环境变量时)', async () => { - vi.mocked(fs.existsSync).mockReturnValue(false); + mockNoConfigFile(); process.env.OPENAI_API_KEY = 'sk-test'; delete process.env.OPENAI_MODEL; delete process.env.GEMINI_MODEL; @@ -161,7 +158,7 @@ describe('config module', () => { }); it('国产大模型渠道读取 _API_KEY / _BASE_URL / _MODEL 环境变量', async () => { - vi.mocked(fs.existsSync).mockReturnValue(false); + mockNoConfigFile(); const { VENDOR_PROVIDER_IDS, VENDOR_PRESETS } = await import('@/lib/ai/vendor-presets'); for (const id of VENDOR_PROVIDER_IDS) { const prefix = VENDOR_PRESETS[id].envPrefix; @@ -181,7 +178,6 @@ describe('config module', () => { const { VENDOR_PROVIDER_IDS, VENDOR_PRESETS } = await import('@/lib/ai/vendor-presets'); const id = VENDOR_PROVIDER_IDS[0]; process.env[`${VENDOR_PRESETS[id].envPrefix}_API_KEY`] = 'env-key'; - vi.mocked(fs.existsSync).mockReturnValue(true); vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify({ aiProvider: id, [id]: { model: 'file-model' } })); const { getAppConfig } = await import('@/lib/config'); @@ -194,7 +190,7 @@ describe('config module', () => { describe('updateAppConfig', () => { it('应该成功写入配置文件', async () => { - vi.mocked(fs.existsSync).mockReturnValue(false); + mockNoConfigFile(); vi.mocked(fs.writeFileSync).mockImplementation(() => { }); const { updateAppConfig } = await import('@/lib/config'); @@ -204,8 +200,28 @@ describe('config module', () => { expect(result.aiProvider).toBe('openai'); }); + it('先写临时文件再改名替换,避免读到写了一半的配置', async () => { + mockNoConfigFile(); + + const { updateAppConfig } = await import('@/lib/config'); + updateAppConfig({ aiProvider: 'openai' }); + + const tmp = vi.mocked(fs.writeFileSync).mock.calls[0][0] as string; + expect(tmp).toMatch(/app-config\.json\.\d+\.tmp$/); + expect(fs.renameSync).toHaveBeenCalledWith(tmp, expect.stringMatching(/app-config\.json$/)); + }); + + it('配置文件无法读取(非不存在)时记录错误并返回默认配置', async () => { + vi.mocked(fs.readFileSync).mockImplementation(() => { + throw Object.assign(new Error('EACCES'), { code: 'EACCES' }); + }); + + const { getAppConfig } = await import('@/lib/config'); + expect(getAppConfig().aiProvider).toBeDefined(); + }); + it('应该合并嵌套配置', async () => { - vi.mocked(fs.existsSync).mockReturnValue(false); + mockNoConfigFile(); vi.mocked(fs.writeFileSync).mockImplementation(() => { }); const { updateAppConfig } = await import('@/lib/config'); @@ -228,7 +244,7 @@ describe('config module', () => { }); it('应该在写入失败时抛出错误', async () => { - vi.mocked(fs.existsSync).mockReturnValue(false); + mockNoConfigFile(); vi.mocked(fs.writeFileSync).mockImplementation(() => { throw new Error('Permission denied'); }); @@ -239,7 +255,7 @@ describe('config module', () => { }); it('应该更新提示词配置', async () => { - vi.mocked(fs.existsSync).mockReturnValue(false); + mockNoConfigFile(); vi.mocked(fs.writeFileSync).mockImplementation(() => { }); const { updateAppConfig } = await import('@/lib/config'); @@ -251,7 +267,7 @@ describe('config module', () => { }); it('应该更新注册开关', async () => { - vi.mocked(fs.existsSync).mockReturnValue(false); + mockNoConfigFile(); vi.mocked(fs.writeFileSync).mockImplementation(() => { }); const { updateAppConfig } = await import('@/lib/config'); diff --git a/src/__tests__/unit/package-launcher.test.ts b/src/__tests__/unit/package-launcher.test.ts index b851f52b..6b95d86a 100644 --- a/src/__tests__/unit/package-launcher.test.ts +++ b/src/__tests__/unit/package-launcher.test.ts @@ -1,7 +1,9 @@ /** * 安装包启动器单元测试 - * 覆盖命令行参数解析和 SQLite 地址转换 + * 覆盖命令行参数解析、SQLite 地址转换和会话密钥生成 */ +import fs from 'fs'; +import os from 'os'; import path from 'path'; import { createRequire } from 'module'; import { describe, expect, it } from 'vitest'; @@ -10,6 +12,7 @@ const require = createRequire(import.meta.url); const launcher = require('../../../packaging/runtime/launcher.js') as { parseArgs: (argv: string[]) => { port?: string; host?: string; dataDir?: string }; sqliteUrl: (file: string) => string; + ensureSecret: (dataDir: string) => string; }; describe('package launcher', () => { @@ -30,4 +33,20 @@ describe('package launcher', () => { const file = ['data', 'wrong-notebook.db'].join(path.sep); expect(launcher.sqliteUrl(file)).toBe('file:data/wrong-notebook.db'); }); + + it('会话密钥首次生成后保持不变,空文件会被重新生成', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'launcher-secret-')); + try { + const first = launcher.ensureSecret(dir); + expect(first).toMatch(/^[A-Za-z0-9+/]{43}=$/); + expect(launcher.ensureSecret(dir)).toBe(first); + + fs.writeFileSync(path.join(dir, '.nextauth_secret'), ''); + const regenerated = launcher.ensureSecret(dir); + expect(regenerated).not.toBe(''); + expect(fs.readFileSync(path.join(dir, '.nextauth_secret'), 'utf8')).toBe(regenerated); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); }); diff --git a/src/lib/config.ts b/src/lib/config.ts index f2b91b65..36ed3dea 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -154,10 +154,33 @@ function mergeVendorConfigs(base: Partial, override: Partial [id, { ...base[id], ...override[id] }])); } +/** 读取配置文件;文件不存在时返回 null(直接读取并处理 ENOENT,避免先判断再读取之间文件被改动) */ +function readConfigFile(): string | null { + try { + return fs.readFileSync(CONFIG_FILE_PATH, 'utf-8'); + } catch (error) { + if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') return null; + throw error; + } +} + +/** 先写临时文件再改名替换,避免其他请求读到写了一半的配置 */ +function writeConfigFile(config: unknown): void { + const tmp = `${CONFIG_FILE_PATH}.${process.pid}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(config, null, 2)); + fs.renameSync(tmp, CONFIG_FILE_PATH); +} + export function getAppConfig(): AppConfig { - if (fs.existsSync(CONFIG_FILE_PATH)) { + let fileContent: string | null; + try { + fileContent = readConfigFile(); + } catch (error) { + logger.error({ error }, 'Failed to read config file'); + return DEFAULT_CONFIG; + } + if (fileContent !== null) { try { - const fileContent = fs.readFileSync(CONFIG_FILE_PATH, 'utf-8'); const userConfig = JSON.parse(fileContent); // 检测并迁移旧版 OpenAI 配置 @@ -170,7 +193,7 @@ export function getAppConfig(): AppConfig { ...userConfig, openai: openaiConfig, }; - fs.writeFileSync(CONFIG_FILE_PATH, JSON.stringify(migratedConfig, null, 2)); + writeConfigFile(migratedConfig); logger.info('Legacy OpenAI config migrated successfully'); } @@ -220,7 +243,7 @@ export function updateAppConfig(newConfig: Partial) { }; try { - fs.writeFileSync(CONFIG_FILE_PATH, JSON.stringify(updatedConfig, null, 2)); + writeConfigFile(updatedConfig); return updatedConfig; } catch (error) { logger.error({ error }, 'Failed to write config file');