From 8144dd9c27e10feb263d0ffc52e442207d33aa7c Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 17 Jun 2026 23:57:12 +0800 Subject: [PATCH 01/33] feat(onebot): implement get_group_shut_list via member shutUpTime Derive the muted-member list from the TTL-cached group member list (shutUpTime = absolute expiry epoch seconds), replacing the placeholder that always returned []. NapCat-shaped output {user_id,nickname,shut_up_time}. --- packages/onebot/src/actions/extended.ts | 19 +++++++---- .../onebot/tests/extended-actions.test.ts | 32 +++++++++++++++---- 2 files changed, 38 insertions(+), 13 deletions(-) diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index cdb33bde..f332423c 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -705,15 +705,20 @@ export const actions = [ }, }), - // get_group_shut_list 依赖尚未封装的 oidb。 - // 这里遵循 NapCat 约定返回空列表,避免调用方出错。 - defineAction({ + // get_group_shut_list — SnowLuma 无独立"禁言列表"cmd,按成员列表的 + // shutUpTime 字段(绝对到期时间戳,秒)派生:保留仍在禁言中的成员。 + // 走带 TTL 缓存的 fetchGroupMemberList(风控友好),与 NapCat 返回形状对齐。 + groupAction({ name: 'get_group_shut_list', - summary: '获取群禁言列表(占位)', + summary: '获取群禁言列表', readOnly: true, - params: {}, - run: async () => { - return okResponse([]); + run: async (p, ctx) => { + const members = await ctx.bridge.apis.contacts.fetchGroupMemberList(p.group_id); + const nowSec = Math.floor(Date.now() / 1000); + const list = members + .filter((m) => (m.shutUpTime ?? 0) > nowSec) + .map((m) => ({ user_id: m.uin, nickname: m.nickname, shut_up_time: m.shutUpTime })); + return okResponse(list); }, }), diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index 1ab9886b..150d6e4b 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -350,12 +350,6 @@ describe('extended-actions / get_group_ignore_add_request', () => { }); }); -describe('extended-actions / get_group_shut_list', () => { - it('returns empty list (oidb not yet wrapped)', async () => { - const res = await makeHandler(fakeCtx(fakeBridge())).handle('get_group_shut_list', {}); - expect(res).toEqual({ status: 'ok', retcode: 0, data: [] }); - }); -}); // ─── Tier 1: delete_group_folder alias ─── @@ -620,3 +614,29 @@ describe('extended-actions / set_group_portrait', () => { expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'highway 500' }); }); }); + +// ─── Wave 1: get_group_shut_list ─── + +describe('extended-actions / get_group_shut_list', () => { + it('returns only currently-muted members in NapCat shape', async () => { + const nowSec = Math.floor(Date.now() / 1000); + const fetchGroupMemberList = vi.fn(async () => [ + { uin: 111, uid: 'u1', nickname: 'muted', card: '', role: 'member', level: 1, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: nowSec + 3600 }, + { uin: 222, uid: 'u2', nickname: 'free', card: '', role: 'member', level: 1, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: 0 }, + { uin: 333, uid: 'u3', nickname: 'expired', card: '', role: 'member', level: 1, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: nowSec - 3600 }, + ]); + const bridge = fakeBridge({ fetchGroupMemberList: fetchGroupMemberList as any }); + const res = await makeHandler(fakeCtx(bridge)).handle('get_group_shut_list', { group_id: 12345 }); + expect(res.status).toBe('ok'); + expect(fetchGroupMemberList).toHaveBeenCalledWith(12345); + expect(res.data).toEqual([ + { user_id: 111, nickname: 'muted', shut_up_time: nowSec + 3600 }, + ]); + }); + + it('rejects missing group_id', async () => { + const bridge = fakeBridge({ fetchGroupMemberList: vi.fn() as any }); + const res = await makeHandler(fakeCtx(bridge)).handle('get_group_shut_list', {}); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + }); +}); From 84e5254c3a136d9b55be7f98ea1c30c1f9a08ec2 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 17 Jun 2026 23:58:00 +0800 Subject: [PATCH 02/33] feat(onebot): implement get_file via media cache resolution Resolve file_id against the image cache, then the record cache (both already mint a fresh url + carry file_size/file_name), replacing the not-yet-implemented stub. Document-type files have no id-resolvable cache yet, so they are intentionally left uncovered rather than faked. --- packages/onebot/src/actions/extended.ts | 15 +++++--- .../onebot/tests/extended-actions.test.ts | 34 +++++++++++++++++++ 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index f332423c..4b286d40 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1032,18 +1032,25 @@ export const actions = [ }, }), + // get_file — 统一文件信息入口。SnowLuma 按 file_id 解析媒体缓存: + // 先图片、后语音(两者已带 url 重签与 file_size/file_name)。文档类文件 + // 当前无可按 id 解析的缓存,故不在此伪造,仅覆盖图片/语音的主流用例。 defineAction({ name: 'get_file', - summary: '获取文件(未实现)', + summary: '获取文件信息(图片/语音缓存)', readOnly: true, params: { file_id: f.string().default(''), file: f.string().default(''), }, - run: async (p) => { - const fileId = p.file_id || p.file; + run: async (p, ctx) => { + const fileId = p.file || p.file_id; if (!fileId) return failedResponse(RETCODE.BAD_REQUEST, 'file_id is required'); - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + const image = await ctx.getImageInfo(fileId); + if (image) return okResponse(image); + const record = await ctx.getRecordInfo(fileId); + if (record) return okResponse(record); + return failedResponse(RETCODE.ACTION_FAILED, 'file not found in cache'); }, }), diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index 150d6e4b..43f2d66c 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -640,3 +640,37 @@ describe('extended-actions / get_group_shut_list', () => { expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); }); }); + +// ─── Wave 1: get_file (compose image→record cache) ─── + +describe('extended-actions / get_file', () => { + const imageInfo = { file: 'a.jpg', url: 'http://x/a.jpg', file_size: '12', file_name: 'a.jpg' }; + const recordInfo = { file: 'b.amr', url: 'http://x/b.amr', file_size: '34', file_name: 'b.amr' }; + + it('resolves an image file_id via the image cache', async () => { + const getImageInfo = vi.fn(async () => imageInfo); + const getRecordInfo = vi.fn(async () => null); + const res = await makeHandler(fakeCtx(fakeBridge(), { getImageInfo, getRecordInfo })).handle('get_file', { file_id: 'a.jpg' }); + expect(res).toMatchObject({ status: 'ok', data: imageInfo }); + expect(getRecordInfo).not.toHaveBeenCalled(); + }); + + it('falls back to the record cache when not an image', async () => { + const getImageInfo = vi.fn(async () => null); + const getRecordInfo = vi.fn(async () => recordInfo); + const res = await makeHandler(fakeCtx(fakeBridge(), { getImageInfo, getRecordInfo })).handle('get_file', { file: 'b.amr' }); + expect(res).toMatchObject({ status: 'ok', data: recordInfo }); + }); + + it('fails when the id resolves to nothing cached', async () => { + const getImageInfo = vi.fn(async () => null); + const getRecordInfo = vi.fn(async () => null); + const res = await makeHandler(fakeCtx(fakeBridge(), { getImageInfo, getRecordInfo })).handle('get_file', { file_id: 'nope' }); + expect(res).toMatchObject({ status: 'failed', retcode: 100 }); + }); + + it('rejects when neither file nor file_id is given', async () => { + const res = await makeHandler(fakeCtx(fakeBridge())).handle('get_file', {}); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + }); +}); From dbb5160be7199f9a62cd6d8e4fe994c23e54f78f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 00:05:20 +0800 Subject: [PATCH 03/33] fix(onebot): clarify get_file limitation + honest _mark_all_as_read summary Adversarial review of Wave 1: get_file's 'file not found in cache' was misleading for group-file file_ids (unsupported here, not uncached). Distinguish the two in the error message, surface the limitation in the summary, and lock the contract with a negative test. Also annotate get_group_shut_list's ~60s cache-delay tradeoff and mark _mark_all_as_read as an explicit no-op pending an RE'd one-shot read cmd. --- packages/onebot/src/actions/extended.ts | 27 ++++++++++++++----- .../onebot/tests/extended-actions.test.ts | 11 ++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 4b286d40..a97bf5ec 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -563,9 +563,12 @@ export const actions = [ }, }), + // _mark_all_as_read — no-op。NapCat 靠单次内核 IPC markAllMsgAsRead() 实现, + // SnowLuma 无等价单包 SSO cmd;遍历所有会话逐个发已读报告是风控高危群发, + // 故暂不真正执行(留待 RE 出"一键全读"cmd)。返回 ok 以兼容启动时盲调的客户端。 defineAction({ name: '_mark_all_as_read', - summary: '标记全部已读', + summary: '标记全部已读(no-op,待 RE 全读 cmd)', params: {}, run: async () => { return okResponse(); @@ -707,7 +710,10 @@ export const actions = [ // get_group_shut_list — SnowLuma 无独立"禁言列表"cmd,按成员列表的 // shutUpTime 字段(绝对到期时间戳,秒)派生:保留仍在禁言中的成员。 - // 走带 TTL 缓存的 fetchGroupMemberList(风控友好),与 NapCat 返回形状对齐。 + // 走带 TTL 缓存的 fetchGroupMemberList(风控友好,0xfe7 高频会触发腾讯封号), + // 与 NapCat 文档返回形状 {user_id,nickname,shut_up_time} 对齐。 + // 取舍:NapCat 此接口实时,本实现复用成员缓存,故结果最长有 ~60s 延迟—— + // 刚下/解的禁言可能在该窗口内未反映,属可接受的低频运维查询取舍。 groupAction({ name: 'get_group_shut_list', summary: '获取群禁言列表', @@ -1033,11 +1039,14 @@ export const actions = [ }), // get_file — 统一文件信息入口。SnowLuma 按 file_id 解析媒体缓存: - // 先图片、后语音(两者已带 url 重签与 file_size/file_name)。文档类文件 - // 当前无可按 id 解析的缓存,故不在此伪造,仅覆盖图片/语音的主流用例。 + // 先图片、后语音(两者已带 url 重签与 file_size/file_name)。 + // 局限:群文件/普通文件的 file_id 无法在此解析——OneBot `get_file` 单参 + // 签名不含 group_id,而 SnowLuma 群文件下载需要 group 上下文(用 + // get_group_file_url / get_private_file_url)。故此处仅覆盖图片/语音, + // 不为群文件伪造结果,且对群文件 file_id 给出可区分的错误信息。 defineAction({ name: 'get_file', - summary: '获取文件信息(图片/语音缓存)', + summary: '获取文件信息(仅图片/语音缓存;群文件请用 get_group_file_url)', readOnly: true, params: { file_id: f.string().default(''), @@ -1050,7 +1059,13 @@ export const actions = [ if (image) return okResponse(image); const record = await ctx.getRecordInfo(fileId); if (record) return okResponse(record); - return failedResponse(RETCODE.ACTION_FAILED, 'file not found in cache'); + // 与 NapCat 不同,本接口不解析群文件/普通文件 file_id(需 group 上下文)。 + // 区分"不支持此类 file_id"与"图片/语音确实未缓存",避免调用方误判。 + return failedResponse( + RETCODE.ACTION_FAILED, + 'get_file resolves only image/voice file_id from the media cache; ' + + 'group/normal file_id is unsupported here — use get_group_file_url or get_private_file_url', + ); }, }), diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index 43f2d66c..cbcb7b0b 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -669,6 +669,17 @@ describe('extended-actions / get_file', () => { expect(res).toMatchObject({ status: 'failed', retcode: 100 }); }); + it('gives an unsupported-file_id message (not a misleading "not cached") for a group-file id', async () => { + // A group-file file_id cannot be resolved here (no group context); the + // error must say so rather than imply the file is merely uncached. + const getImageInfo = vi.fn(async () => null); + const getRecordInfo = vi.fn(async () => null); + const res = await makeHandler(fakeCtx(fakeBridge(), { getImageInfo, getRecordInfo })) + .handle('get_file', { file_id: '/abcdef-group-file-id' }); + expect(res.status).toBe('failed'); + expect((res as { wording?: string }).wording).toMatch(/unsupported|get_group_file_url/); + }); + it('rejects when neither file nor file_id is given', async () => { const res = await makeHandler(fakeCtx(fakeBridge())).handle('get_file', {}); expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); From 0ba5eba31c2ce56b45849214df6d7890fae8aa9a Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 00:08:44 +0800 Subject: [PATCH 04/33] fix(onebot): neutral get_file cache-miss message, drop fake test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second adversarial pass: the previous 'unsupported' wording over-corrected — it mislabeled a genuinely-uncached image file_id as 'unsupported', mirroring the original defect. A double cache miss is runtime-indistinguishable between a group-file id and an evicted image/voice, so the message now states the cache miss neutrally and offers get_group_file_url as guidance only. The prior 'group-file id' test took the same code path as the cache-miss test (a fake test); consolidated into one honest assertion. --- packages/onebot/src/actions/extended.ts | 12 +++++----- .../onebot/tests/extended-actions.test.ts | 22 +++++++++---------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index a97bf5ec..1ca5760a 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1043,7 +1043,11 @@ export const actions = [ // 局限:群文件/普通文件的 file_id 无法在此解析——OneBot `get_file` 单参 // 签名不含 group_id,而 SnowLuma 群文件下载需要 group 上下文(用 // get_group_file_url / get_private_file_url)。故此处仅覆盖图片/语音, - // 不为群文件伪造结果,且对群文件 file_id 给出可区分的错误信息。 + // 不为群文件伪造结果。 + // 注意:缓存双 miss 时无法在此区分"传入的是群文件 file_id"与"图片/语音 + // 确实未缓存(如进程重启丢失)"——run() 不解析 id 形态。故错误信息保持 + // 中性:先陈述"未命中缓存"的事实,再把群文件改用别的接口作为指引, + // 而非武断断言"不支持"。(summary 仅进离线文档,调用方运行时只看到 wording。) defineAction({ name: 'get_file', summary: '获取文件信息(仅图片/语音缓存;群文件请用 get_group_file_url)', @@ -1059,12 +1063,10 @@ export const actions = [ if (image) return okResponse(image); const record = await ctx.getRecordInfo(fileId); if (record) return okResponse(record); - // 与 NapCat 不同,本接口不解析群文件/普通文件 file_id(需 group 上下文)。 - // 区分"不支持此类 file_id"与"图片/语音确实未缓存",避免调用方误判。 return failedResponse( RETCODE.ACTION_FAILED, - 'get_file resolves only image/voice file_id from the media cache; ' - + 'group/normal file_id is unsupported here — use get_group_file_url or get_private_file_url', + 'file_id not found in the image/voice cache. get_file only resolves cached ' + + 'image/voice ids; for group/normal files use get_group_file_url or get_private_file_url', ); }, }), diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index cbcb7b0b..c2e17982 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -662,22 +662,20 @@ describe('extended-actions / get_file', () => { expect(res).toMatchObject({ status: 'ok', data: recordInfo }); }); - it('fails when the id resolves to nothing cached', async () => { + it('fails with a neutral cache-miss message that points to the group-file path', async () => { + // A double cache miss is runtime-indistinguishable between "a group-file + // file_id was passed (unsupported here)" and "the image/voice really isn't + // cached" — run() does not parse the id's shape. So the error must stay + // neutral: state the cache miss, then offer the group-file path as + // guidance, without asserting "unsupported". const getImageInfo = vi.fn(async () => null); const getRecordInfo = vi.fn(async () => null); const res = await makeHandler(fakeCtx(fakeBridge(), { getImageInfo, getRecordInfo })).handle('get_file', { file_id: 'nope' }); expect(res).toMatchObject({ status: 'failed', retcode: 100 }); - }); - - it('gives an unsupported-file_id message (not a misleading "not cached") for a group-file id', async () => { - // A group-file file_id cannot be resolved here (no group context); the - // error must say so rather than imply the file is merely uncached. - const getImageInfo = vi.fn(async () => null); - const getRecordInfo = vi.fn(async () => null); - const res = await makeHandler(fakeCtx(fakeBridge(), { getImageInfo, getRecordInfo })) - .handle('get_file', { file_id: '/abcdef-group-file-id' }); - expect(res.status).toBe('failed'); - expect((res as { wording?: string }).wording).toMatch(/unsupported|get_group_file_url/); + const wording = (res as { wording?: string }).wording ?? ''; + expect(wording).toMatch(/not found in the image\/voice cache/); + expect(wording).toMatch(/get_group_file_url/); + expect(wording).not.toMatch(/unsupported/); }); it('rejects when neither file nor file_id is given', async () => { From 07988629f12a0eba411858721e9ff4c317ed2eb8 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 00:19:00 +0800 Subject: [PATCH 05/33] feat(onebot): implement rename_group_file (OIDB 0x6D6_4) Add the file-rename slot to the group-file OIDB envelope (req/resp field 5), a RenameGroupFile service mirroring MoveGroupFile, a groupFile.rename() api method, and the rename_group_file action (params group_id/file_id/ current_parent_directory/new_name, NapCat-aligned), replacing the stub. Wire fields (busId=102, parentFolder=current dir, newFileName) verified against NapCat's Oidb.0x6D6 transformer; subCommand 4 cross-checked against the move op (sub 5 on both sides). Serialize + envelope round-trip test locks the pb tags. --- packages/core/src/bridge/apis/group-file.ts | 5 ++ packages/onebot/src/actions/extended.ts | 9 --- packages/onebot/src/actions/group-file.ts | 16 +++++ .../onebot/tests/extended-actions.test.ts | 31 +++++++++ .../proto-defs/src/oidb-actions/group-file.ts | 9 +++ packages/protocol/package.json | 4 ++ .../group-file/rename-group-file.ts | 49 ++++++++++++++ .../group-file/rename-group-file.test.ts | 64 +++++++++++++++++++ 8 files changed, 178 insertions(+), 9 deletions(-) create mode 100644 packages/protocol/src/oidb-services/group-file/rename-group-file.ts create mode 100644 packages/protocol/tests/oidb-services/group-file/rename-group-file.test.ts diff --git a/packages/core/src/bridge/apis/group-file.ts b/packages/core/src/bridge/apis/group-file.ts index 86920988..bbdddb49 100644 --- a/packages/core/src/bridge/apis/group-file.ts +++ b/packages/core/src/bridge/apis/group-file.ts @@ -21,6 +21,7 @@ import { GetPrivateVideoUrl } from '@snowluma/protocol/oidb-services/group-file/ import { ListGroupFilesPage } from '@snowluma/protocol/oidb-services/group-file/list-group-files-page'; import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-group-file'; import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file'; +import { RenameGroupFile } from '@snowluma/protocol/oidb-services/group-file/rename-group-file'; import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder'; import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request'; import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request'; @@ -604,6 +605,10 @@ export class GroupFileApi { return MoveGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, targetDirectory }); } + rename(groupId: number, fileId: string, parentDirectory: string, newFileName: string): Promise { + return RenameGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, newFileName }); + } + // ─────────────── folders ─────────────── createFolder(groupId: number, name: string, parentId = '/'): Promise { diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 1ca5760a..4d904311 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1029,15 +1029,6 @@ export const actions = [ }, }), - defineAction({ - name: 'rename_group_file', - summary: '重命名群文件(未实现)', - params: {}, - run: async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }, - }), - // get_file — 统一文件信息入口。SnowLuma 按 file_id 解析媒体缓存: // 先图片、后语音(两者已带 url 重签与 file_size/file_name)。 // 局限:群文件/普通文件的 file_id 无法在此解析——OneBot `get_file` 单参 diff --git a/packages/onebot/src/actions/group-file.ts b/packages/onebot/src/actions/group-file.ts index 16fbd98c..177c1405 100644 --- a/packages/onebot/src/actions/group-file.ts +++ b/packages/onebot/src/actions/group-file.ts @@ -100,6 +100,22 @@ export const actions = [ }, }), + // rename_group_file — 0x6D6_4。NapCat 入参:file_id + current_parent_directory + // (文件当前所在目录)+ new_name。SnowLuma 的 file_id 即原始 fileId,无需 UUID 解码。 + groupAction({ + name: 'rename_group_file', + summary: '重命名群文件', + params: { + file_id: f.string({ allowEmpty: false }), + current_parent_directory: f.string().default('/'), + new_name: f.string({ allowEmpty: false }), + }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupFile.rename(p.group_id, p.file_id, p.current_parent_directory || '/', p.new_name); + return okResponse({ ok: true }); + }, + }), + groupAction({ name: 'create_group_file_folder', summary: '创建群文件夹', diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index c2e17982..d49af176 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -683,3 +683,34 @@ describe('extended-actions / get_file', () => { expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); }); }); + +// ─── Wave 2: rename_group_file (0x6D6_4) ─── + +describe('extended-actions / rename_group_file', () => { + it('renames a group file via apis.groupFile.rename', async () => { + const rename = vi.fn(async () => undefined); + const bridge = fakeBridge({ apis: { groupFile: { rename } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('rename_group_file', { + group_id: 12345, file_id: '/abc', current_parent_directory: '/', new_name: 'new.txt', + }); + expect(res.status).toBe('ok'); + expect(rename).toHaveBeenCalledWith(12345, '/abc', '/', 'new.txt'); + }); + + it('rejects missing required params', async () => { + const rename = vi.fn(); + const bridge = fakeBridge({ apis: { groupFile: { rename } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('rename_group_file', { group_id: 12345, file_id: '/abc' }); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(rename).not.toHaveBeenCalled(); + }); + + it('surfaces oidb errors (handler maps a thrown error to INTERNAL_ERROR, as its sibling file ops do)', async () => { + const rename = vi.fn(async () => { throw new Error('rename rejected'); }); + const bridge = fakeBridge({ apis: { groupFile: { rename } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('rename_group_file', { + group_id: 1, file_id: '/a', current_parent_directory: '/', new_name: 'x', + }); + expect(res).toMatchObject({ status: 'failed', retcode: 1200, wording: 'rename rejected' }); + }); +}); diff --git a/packages/proto-defs/src/oidb-actions/group-file.ts b/packages/proto-defs/src/oidb-actions/group-file.ts index 40ed92d4..007bb455 100644 --- a/packages/proto-defs/src/oidb-actions/group-file.ts +++ b/packages/proto-defs/src/oidb-actions/group-file.ts @@ -84,10 +84,18 @@ export interface OidbGroupFileMoveReq { parentDirectory?: pb<5, string>; targetDirectory?: pb<6, string>; } +export interface OidbGroupFileRenameReq { + groupUin?: pb<1, uint_32>; + busId?: pb<3, uint_32>; + fileId?: pb<4, string>; + parentFolder?: pb<5, string>; + newFileName?: pb<6, string>; +} export interface OidbGroupFileReq { file?: pb<1, OidbGroupFileUploadReq>; download?: pb<3, OidbGroupFileDownloadReq>; delete?: pb<4, OidbGroupFileDeleteReq>; + rename?: pb<5, OidbGroupFileRenameReq>; move?: pb<6, OidbGroupFileMoveReq>; } export interface OidbGroupFileUploadResp { @@ -121,6 +129,7 @@ export interface OidbGroupFileResp { upload?: pb<1, OidbGroupFileUploadResp>; download?: pb<3, OidbGroupFileDownloadResp>; delete?: pb<4, OidbGroupFileRetResp>; + rename?: pb<5, OidbGroupFileRetResp>; move?: pb<6, OidbGroupFileRetResp>; } export interface OidbGroupSendFileInfo { diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 402d8f9e..3d0e99d1 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -263,6 +263,10 @@ "types": "./src/oidb-services/group-file/move-group-file.ts", "default": "./src/oidb-services/group-file/move-group-file.ts" }, + "./oidb-services/group-file/rename-group-file": { + "types": "./src/oidb-services/group-file/rename-group-file.ts", + "default": "./src/oidb-services/group-file/rename-group-file.ts" + }, "./oidb-services/group-file/create-group-folder": { "types": "./src/oidb-services/group-file/create-group-folder.ts", "default": "./src/oidb-services/group-file/create-group-folder.ts" diff --git a/packages/protocol/src/oidb-services/group-file/rename-group-file.ts b/packages/protocol/src/oidb-services/group-file/rename-group-file.ts new file mode 100644 index 00000000..6b2ca5af --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/rename-group-file.ts @@ -0,0 +1,49 @@ +// 0x6D6_4 — rename a group file (not a folder; that is 0x6D7_2). The +// rename slot lives on the shared `OidbGroupFileReq` envelope at field 5. +// Wire fields verified against NapCat's Oidb.0x6D6 transformer +// (busId=102, parentFolder = the file's CURRENT parent directory). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupFileReq, OidbGroupFileResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { ensureRetCodeZero } from '../shared'; + +export namespace RenameGroupFile { + export const command = 0x6D6; + export const subCommand = 4; + export const uinForm = true; + + export interface Params { + groupId: number; fileId: string; + parentDirectory: string; newFileName: string; + } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupFileReq => ({ + rename: { + groupUin: p.groupId, + busId: 102, + fileId: p.fileId, + parentFolder: p.parentDirectory, + newFileName: p.newFileName, + }, + }); + + export const deserialize = (_ctx: Deps, body: OidbGroupFileResp): void => { + const result = body.rename; + if (!result) throw new Error('group file rename response missing'); + ensureRetCodeZero('group file rename', result.retCode, result.retMsg, result.clientWording); + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, RenameGroupFile, params); +} diff --git a/packages/protocol/tests/oidb-services/group-file/rename-group-file.test.ts b/packages/protocol/tests/oidb-services/group-file/rename-group-file.test.ts new file mode 100644 index 00000000..8b178ba2 --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/rename-group-file.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbGroupFileReq, OidbGroupFileResp } from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { RenameGroupFile } from '../../../src/oidb-services/group-file/rename-group-file'; + +// A success response the real server would send: command/sub echoed, rename +// ret slot with retCode 0. Lets `invoke`'s deserialize pass so we can assert +// the request wire (cmd name + body) without it throwing on an empty body. +function okRenameResponse(): Buffer { + const env: OidbBase = { + command: 0x6D6, subCommand: 4, body: { rename: { retCode: 0 } }, + }; + return Buffer.from(protobuf_encode>(env)); +} + +function makeSender() { + const defaultResp: SendPacketResult = { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', + responseData: okRenameResponse(), + }; + return { sendRawPacket: vi.fn(async () => defaultResp) }; +} + +describe('RenameGroupFile namespace', () => { + it('declares command 0x6D6 sub 4 (rename slot), uin form', () => { + expect(RenameGroupFile.command).toBe(0x6D6); + expect(RenameGroupFile.subCommand).toBe(4); + expect(RenameGroupFile.uinForm).toBe(true); + }); + + it('serializes into the rename slot with busId 102 and the current parent folder', () => { + const out = RenameGroupFile.serialize({} as any, { + groupId: 12345, fileId: '/abc', parentDirectory: '/sub', newFileName: 'new.txt', + }); + expect(out).toEqual({ + rename: { + groupUin: 12345, busId: 102, fileId: '/abc', parentFolder: '/sub', newFileName: 'new.txt', + }, + }); + }); + + it('round-trips the rename body through the OIDB envelope (locks the pb field tags)', async () => { + const sender = makeSender(); + await RenameGroupFile.invoke(sender, { + groupId: 12345, fileId: '/abc', parentDirectory: '/', newFileName: 'new.txt', + }); + expect(sender.sendRawPacket).toHaveBeenCalledOnce(); + const [cmd, bytes] = sender.sendRawPacket.mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0x6d6_4'); + const env = protobuf_decode>(bytes); + expect(env.command).toBe(0x6D6); + expect(env.subCommand).toBe(4); + expect(env.body.rename).toMatchObject({ + groupUin: 12345, busId: 102, fileId: '/abc', parentFolder: '/', newFileName: 'new.txt', + }); + }); + + it('deserialize throws when the rename slot is missing from the response', () => { + expect(() => RenameGroupFile.deserialize({} as any, {})).toThrow(/rename response missing/); + }); +}); From 7625c1876846f2723ec78ab31c263b82642df0ef Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 00:21:35 +0800 Subject: [PATCH 06/33] feat(onebot): add get_rkey_server (NapCat server-shape rkey) Reshape the download-rkey list (type 10=private, 20=group, same 0x9067 source) into NapCat's GetRkeyServer shape {private_rkey, group_rkey, expired_time, name}, expired_time = now + min present ttl. get_rkey / nc_get_rkey already existed (raw list) and are left unchanged. --- packages/onebot/src/actions/extended.ts | 27 ++++++++++++++++ .../onebot/tests/extended-actions.test.ts | 31 +++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 4d904311..2ebc02b0 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1215,6 +1215,33 @@ export const actions = [ : failedResponse(RETCODE.ACTION_FAILED, 'not implemented'), }), + // get_rkey_server — 把下载 rkey 列表(type 10=私聊 / 20=群聊,同 0x9067 来源) + // 收敛成 NapCat 的 server 形状。expired_time = now + 在场 rkey ttl 的最小值。 + defineAction({ + name: 'get_rkey_server', + summary: '获取 rkey 服务器信息', + readOnly: true, + params: {}, + run: async (_p, ctx) => { + if (!ctx.getDownloadRKeys) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + const rkeys = await ctx.getDownloadRKeys(); + const pick = (type: number) => + rkeys.find((r) => (r as { type?: number }).type === type) as + { rkey?: string; ttl?: number } | undefined; + const priv = pick(10); + const group = pick(20); + const ttls = [priv?.ttl, group?.ttl].filter((t): t is number => typeof t === 'number' && t > 0); + const minTtl = ttls.length ? Math.min(...ttls) : 0; + const data: JsonObject = { + expired_time: Math.floor(Date.now() / 1000) + minTtl, + name: 'SnowLuma', + }; + if (priv?.rkey) data.private_rkey = priv.rkey; + if (group?.rkey) data.group_rkey = group.rkey; + return okResponse(data); + }, + }), + defineAction({ name: ['ocr_image', '.ocr_image'], summary: 'OCR 图片(未实现)', diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index d49af176..69089577 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -714,3 +714,34 @@ describe('extended-actions / rename_group_file', () => { expect(res).toMatchObject({ status: 'failed', retcode: 1200, wording: 'rename rejected' }); }); }); + +// ─── Wave 2: get_rkey_server ─── + +describe('extended-actions / get_rkey_server', () => { + it('reshapes download rkeys into the NapCat server shape (private=10, group=20)', async () => { + const nowSec = Math.floor(Date.now() / 1000); + const getDownloadRKeys = vi.fn(async () => [ + { rkey: '&rkey=PRIV', type: 10, ttl: 3600, create_time: 100 }, + { rkey: '&rkey=GRP', type: 20, ttl: 7200, create_time: 200 }, + ]); + const res = await makeHandler(fakeCtx(fakeBridge(), { getDownloadRKeys })).handle('get_rkey_server', {}); + expect(res.status).toBe('ok'); + const d = res.data as { private_rkey?: string; group_rkey?: string; expired_time: number; name: string }; + expect(d.private_rkey).toBe('&rkey=PRIV'); + expect(d.group_rkey).toBe('&rkey=GRP'); + expect(d.name).toBe('SnowLuma'); + // expiry = now + min(ttl) = now + 3600 (allow a 1s clock tick) + expect(d.expired_time).toBeGreaterThanOrEqual(nowSec + 3600); + expect(d.expired_time).toBeLessThanOrEqual(nowSec + 3601); + }); + + it('leaves a missing scope undefined', async () => { + const getDownloadRKeys = vi.fn(async () => [ + { rkey: '&rkey=PRIV', type: 10, ttl: 3600, create_time: 100 }, + ]); + const res = await makeHandler(fakeCtx(fakeBridge(), { getDownloadRKeys })).handle('get_rkey_server', {}); + const d = res.data as { private_rkey?: string; group_rkey?: string }; + expect(d.private_rkey).toBe('&rkey=PRIV'); + expect(d.group_rkey).toBeUndefined(); + }); +}); From f936515a59033ce40d04a01bfc7173646386de93 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 00:26:34 +0800 Subject: [PATCH 07/33] fix(onebot): get_rkey_server fails on empty rkey set; document rename return Adversarial Wave 2 pass (no blockers): get_rkey_server now returns ACTION_FAILED instead of an 'expired_time=now, no keys' shell when no download rkey is available, so a caching caller can't misread 'unavailable' as 'valid-but-expired'. Added an empty-list test. Annotated rename_group_file's {ok:true} body as a deliberate NapCat-parity deviation from sibling file ops. --- packages/onebot/src/actions/extended.ts | 6 ++++++ packages/onebot/src/actions/group-file.ts | 2 ++ packages/onebot/tests/extended-actions.test.ts | 6 ++++++ 3 files changed, 14 insertions(+) diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 2ebc02b0..d8d04338 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1230,6 +1230,12 @@ export const actions = [ { rkey?: string; ttl?: number } | undefined; const priv = pick(10); const group = pick(20); + // No rkey at all → fail rather than hand back an "expired_time = now, + // no keys" shell that a caching caller would misread as a valid-but-empty + // (already-expired) result. + if (!priv?.rkey && !group?.rkey) { + return failedResponse(RETCODE.ACTION_FAILED, 'no download rkey available'); + } const ttls = [priv?.ttl, group?.ttl].filter((t): t is number => typeof t === 'number' && t > 0); const minTtl = ttls.length ? Math.min(...ttls) : 0; const data: JsonObject = { diff --git a/packages/onebot/src/actions/group-file.ts b/packages/onebot/src/actions/group-file.ts index 177c1405..e785fb40 100644 --- a/packages/onebot/src/actions/group-file.ts +++ b/packages/onebot/src/actions/group-file.ts @@ -112,6 +112,8 @@ export const actions = [ }, run: async (p, ctx) => { await ctx.bridge.apis.groupFile.rename(p.group_id, p.file_id, p.current_parent_directory || '/', p.new_name); + // {ok:true} 刻意对齐 NapCat RenameGroupFile 的返回体,偏离 SnowLuma 同类 + // 文件写操作(move/delete 返回空 data)——为 NapCat 客户端 drop-in 兼容。 return okResponse({ ok: true }); }, }), diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index 69089577..e7432c69 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -744,4 +744,10 @@ describe('extended-actions / get_rkey_server', () => { expect(d.private_rkey).toBe('&rkey=PRIV'); expect(d.group_rkey).toBeUndefined(); }); + + it('fails (not an expired empty shell) when no rkey is available', async () => { + const getDownloadRKeys = vi.fn(async () => []); + const res = await makeHandler(fakeCtx(fakeBridge(), { getDownloadRKeys })).handle('get_rkey_server', {}); + expect(res).toMatchObject({ status: 'failed', retcode: 100 }); + }); }); From e07090376a8c925a12d467ec1a7bd9cf8e52e831 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 00:36:07 +0800 Subject: [PATCH 08/33] feat(onebot): implement ocr_image via OIDB 0xE07_0 Server-side image OCR ported from Lagrange.Core ([Service] "OidbSvcTrpcTcp.0xe07_0") cross-checked with NapCat's Oidb.0xE07 proto (NapCat's transformer cmd 0xEB7 is a typo; the proto name + Lagrange + the wire name all say 0xE07_0). New ImageOcr service + proto types, misc.ocrImage api, and the ocr_image/.ocr_image action. The cmd takes an image URL, so the action accepts an http(s) url or a cached image file_id (resolved via getImageInfo); base64/local input is unsupported (NapCat's path is a Windows-only kernel OCR, not portable). Wire round-trip + response-parse tests lock the pb tags. --- packages/core/src/bridge/apis/misc.ts | 5 ++ packages/onebot/src/actions/extended.ts | 28 ++++++- .../onebot/tests/extended-actions.test.ts | 45 ++++++++++++ packages/proto-defs/package.json | 4 + packages/proto-defs/src/oidb-actions/ocr.ts | 50 +++++++++++++ packages/protocol/package.json | 4 + .../src/oidb-services/misc/image-ocr.ts | 65 +++++++++++++++++ .../oidb-services/misc/image-ocr.test.ts | 73 +++++++++++++++++++ 8 files changed, 271 insertions(+), 3 deletions(-) create mode 100644 packages/proto-defs/src/oidb-actions/ocr.ts create mode 100644 packages/protocol/src/oidb-services/misc/image-ocr.ts create mode 100644 packages/protocol/tests/oidb-services/misc/image-ocr.test.ts diff --git a/packages/core/src/bridge/apis/misc.ts b/packages/core/src/bridge/apis/misc.ts index bb549d61..ce126781 100644 --- a/packages/core/src/bridge/apis/misc.ts +++ b/packages/core/src/bridge/apis/misc.ts @@ -10,6 +10,7 @@ import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign'; import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh'; import { RequestDbKey } from '@snowluma/protocol/oidb-services/misc/request-decrypt-key'; +import { ImageOcr, type OcrResult } from '@snowluma/protocol/oidb-services/misc/image-ocr'; export class MiscApi { constructor(private readonly ctx: BridgeContext) { } @@ -18,6 +19,10 @@ export class MiscApi { return TranslateEnToZh.invoke(this.ctx, { words }); } + ocrImage(imageUrl: string): Promise { + return ImageOcr.invoke(this.ctx, { imageUrl }); + } + async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise { let appid = '1109937557'; // default: bilibili let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg'; diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index d8d04338..c47ee7a4 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1248,12 +1248,34 @@ export const actions = [ }, }), + // ocr_image — 服务端 OCR via OIDB 0xE07_0(port 自 Lagrange/NapCat proto)。 + // 该 cmd 接收图片 URL(服务端拉取),故 image 支持:http(s) URL 直用,或 + // 已缓存图片的 file_id(经 getImageInfo 解析出 URL)。base64/本地文件需先 + // 上传换 URL,本实现不覆盖(NapCat 走的是 Windows-only 内核 OCR,不可移植)。 defineAction({ name: ['ocr_image', '.ocr_image'], - summary: 'OCR 图片(未实现)', + summary: 'OCR 图片(服务端,需图片 URL 或已缓存的图片 file_id)', readOnly: true, - params: {}, - run: () => failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'), + params: { image: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + let url = /^https?:\/\//i.test(p.image) ? p.image : ''; + if (!url) { + const info = await ctx.getImageInfo(p.image); + const resolved = info && typeof info.url === 'string' ? info.url : ''; + if (resolved) url = resolved; + } + if (!url) { + return failedResponse( + RETCODE.ACTION_FAILED, + 'ocr_image needs an http(s) image url or a cached image file_id; ' + + 'base64/local-file input is not supported', + ); + } + const result = await ctx.bridge.apis.misc.ocrImage(url); + // OcrResult is plain JSON data; the interface just lacks an index + // signature, so coerce for the JsonValue-typed response. + return okResponse(result as unknown as JsonObject); + }, }), groupAction({ diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index e7432c69..5e4c84c0 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -751,3 +751,48 @@ describe('extended-actions / get_rkey_server', () => { expect(res).toMatchObject({ status: 'failed', retcode: 100 }); }); }); + +// ─── Wave 3: ocr_image / .ocr_image (OIDB 0xE07_0) ─── + +describe('extended-actions / ocr_image', () => { + const ocrResult = { texts: [{ text: 'hello', confidence: 99, coordinates: [{ x: 1, y: 2 }] }], language: 'en' }; + + it('OCRs an http(s) image URL directly', async () => { + const ocrImage = vi.fn(async () => ocrResult); + const bridge = fakeBridge({ apis: { misc: { ocrImage } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('ocr_image', { image: 'https://x/a.jpg' }); + expect(res).toMatchObject({ status: 'ok', data: ocrResult }); + expect(ocrImage).toHaveBeenCalledWith('https://x/a.jpg'); + }); + + it('resolves a cached image file_id to a url via getImageInfo', async () => { + const ocrImage = vi.fn(async () => ocrResult); + const getImageInfo = vi.fn(async () => ({ url: 'https://cdn/resolved.jpg' })); + const bridge = fakeBridge({ apis: { misc: { ocrImage } } }); + const res = await makeHandler(fakeCtx(bridge, { getImageInfo })).handle('ocr_image', { image: 'abc.jpg' }); + expect(res.status).toBe('ok'); + expect(ocrImage).toHaveBeenCalledWith('https://cdn/resolved.jpg'); + }); + + it('.ocr_image shares the same handler', async () => { + const ocrImage = vi.fn(async () => ocrResult); + const bridge = fakeBridge({ apis: { misc: { ocrImage } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('.ocr_image', { image: 'http://x/a.jpg' }); + expect(res.status).toBe('ok'); + }); + + it('fails when the id cannot be resolved to a url', async () => { + const ocrImage = vi.fn(); + const getImageInfo = vi.fn(async () => null); + const bridge = fakeBridge({ apis: { misc: { ocrImage } } }); + const res = await makeHandler(fakeCtx(bridge, { getImageInfo })).handle('ocr_image', { image: 'unknown' }); + expect(res.status).toBe('failed'); + expect(ocrImage).not.toHaveBeenCalled(); + }); + + it('rejects missing image', async () => { + const bridge = fakeBridge({ apis: { misc: { ocrImage: vi.fn() } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('ocr_image', {}); + expect(res).toMatchObject({ status: 'failed', retcode: 1400 }); + }); +}); diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index f06035af..f0ce87e8 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -70,6 +70,10 @@ "./oidb-actions/media": { "types": "./src/oidb-actions/media.ts", "default": "./src/oidb-actions/media.ts" + }, + "./oidb-actions/ocr": { + "types": "./src/oidb-actions/ocr.ts", + "default": "./src/oidb-actions/ocr.ts" } }, "scripts": { diff --git a/packages/proto-defs/src/oidb-actions/ocr.ts b/packages/proto-defs/src/oidb-actions/ocr.ts new file mode 100644 index 00000000..e1a8016d --- /dev/null +++ b/packages/proto-defs/src/oidb-actions/ocr.ts @@ -0,0 +1,50 @@ +// OIDB 0xE07_0 — server-side image OCR. Field tags verified against +// NapCat's Oidb.0xE07 proto AND Lagrange.Core's OidbSvcTrpcTcp.0xE07_0 +// (the two agree; NapCat's transformer builds with cmd 0xEB7, which is a +// typo — the proto name + Lagrange + the `OidbSvcTrpcTcp.0xe07_0` wire +// name are authoritative). Request takes an image URL (server fetches it). + +import type { pb, pb_repeated, int_32, uint_32, bool } from '@snowluma/proton'; + +export interface OcrReqBody { + imageUrl?: pb<1, string>; + languageType?: pb<2, uint_32>; + scene?: pb<3, uint_32>; + originMd5?: pb<10, string>; + afterCompressMd5?: pb<11, string>; + afterCompressFileSize?: pb<12, string>; + afterCompressWeight?: pb<13, string>; + afterCompressHeight?: pb<14, string>; + isCut?: pb<15, bool>; +} +export interface ImageOcrReq { + version?: pb<1, uint_32>; + client?: pb<2, uint_32>; + entrance?: pb<3, uint_32>; + ocrReqBody?: pb<10, OcrReqBody>; +} + +export interface OcrCoordinate { + x?: pb<1, int_32>; + y?: pb<2, int_32>; +} +export interface OcrPolygon { + coordinates?: pb_repeated<1, OcrCoordinate>; +} +export interface OcrTextDetection { + detectedText?: pb<1, string>; + confidence?: pb<2, uint_32>; + polygon?: pb<3, OcrPolygon>; + advancedInfo?: pb<4, string>; +} +export interface OcrRspBody { + textDetections?: pb_repeated<1, OcrTextDetection>; + language?: pb<2, string>; + requestId?: pb<3, string>; +} +export interface ImageOcrResp { + retCode?: pb<1, int_32>; + errMsg?: pb<2, string>; + wording?: pb<3, string>; + ocrRspBody?: pb<10, OcrRspBody>; +} diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 3d0e99d1..ed73f635 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -99,6 +99,10 @@ "types": "./src/oidb-services/misc/translate-en-to-zh.ts", "default": "./src/oidb-services/misc/translate-en-to-zh.ts" }, + "./oidb-services/misc/image-ocr": { + "types": "./src/oidb-services/misc/image-ocr.ts", + "default": "./src/oidb-services/misc/image-ocr.ts" + }, "./oidb-services/misc/click-inline-keyboard-button": { "types": "./src/oidb-services/misc/click-inline-keyboard-button.ts", "default": "./src/oidb-services/misc/click-inline-keyboard-button.ts" diff --git a/packages/protocol/src/oidb-services/misc/image-ocr.ts b/packages/protocol/src/oidb-services/misc/image-ocr.ts new file mode 100644 index 00000000..43d69fce --- /dev/null +++ b/packages/protocol/src/oidb-services/misc/image-ocr.ts @@ -0,0 +1,65 @@ +// 0xE07_0 — server-side image OCR. Sends an image URL; the server fetches +// it and returns detected text + bounding-box polygons. Cmd/sub verified +// against Lagrange.Core ([Service("OidbSvcTrpcTcp.0xe07_0")]) and NapCat's +// Oidb.0xE07 proto (NapCat's transformer cmd 0xEB7 is a typo). uinForm is +// false (NapCat build(..., false, false); Lagrange sends no uid). + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { ImageOcrReq, ImageOcrResp } from '@snowluma/proto-defs/oidb-actions/ocr'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { ensureRetCodeZero } from '../shared'; + +/** One detected text run with its bounding-box vertices. */ +export interface OcrText { + text: string; + confidence: number; + coordinates: Array<{ x: number; y: number }>; +} +export interface OcrResult { + texts: OcrText[]; + language: string; +} + +export namespace ImageOcr { + export const command = 0xE07; + export const subCommand = 0; + + export interface Params { imageUrl: string; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): ImageOcrReq => ({ + version: 1, + client: 0, + entrance: 1, + ocrReqBody: { + imageUrl: p.imageUrl, + originMd5: '', + afterCompressMd5: '', + afterCompressFileSize: '', + afterCompressWeight: '', + afterCompressHeight: '', + isCut: false, + }, + }); + + export const deserialize = (_ctx: Deps, body: ImageOcrResp): OcrResult => { + ensureRetCodeZero('image ocr', body.retCode, body.errMsg, body.wording); + const rsp = body.ocrRspBody; + const texts: OcrText[] = (rsp?.textDetections ?? []).map((d) => ({ + text: d.detectedText ?? '', + confidence: d.confidence ?? 0, + coordinates: (d.polygon?.coordinates ?? []).map((c) => ({ x: c.x ?? 0, y: c.y ?? 0 })), + })); + return { texts, language: rsp?.language ?? '' }; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, ImageOcr, params); +} diff --git a/packages/protocol/tests/oidb-services/misc/image-ocr.test.ts b/packages/protocol/tests/oidb-services/misc/image-ocr.test.ts new file mode 100644 index 00000000..27dc0747 --- /dev/null +++ b/packages/protocol/tests/oidb-services/misc/image-ocr.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it, vi } from 'vitest'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { ImageOcrReq, ImageOcrResp } from '@snowluma/proto-defs/oidb-actions/ocr'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { ImageOcr } from '../../../src/oidb-services/misc/image-ocr'; + +// A server OCR response: retCode 0, one text detection with a 2-vertex box. +function ocrResponse(): Buffer { + const env: OidbBase = { + command: 0xE07, subCommand: 0, + body: { + retCode: 0, + ocrRspBody: { + language: 'zh', + textDetections: [ + { detectedText: '你好', confidence: 95, polygon: { coordinates: [{ x: 1, y: 2 }, { x: 3, y: 4 }] } }, + ], + }, + }, + }; + return Buffer.from(protobuf_encode>(env)); +} + +function makeSender(resp = ocrResponse()) { + const r: SendPacketResult = { + success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: resp, + }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('ImageOcr namespace', () => { + it('declares command 0xE07 sub 0 (no uin form)', () => { + expect(ImageOcr.command).toBe(0xE07); + expect(ImageOcr.subCommand).toBe(0); + expect(ImageOcr.uinForm).toBeUndefined(); // defaults to false in invokeOidb + }); + + it('serializes the image url into ocrReqBody with the fixed version/client/entrance header', () => { + const out = ImageOcr.serialize({} as any, { imageUrl: 'https://x/a.jpg' }); + expect(out).toMatchObject({ version: 1, client: 0, entrance: 1 }); + expect(out.ocrReqBody).toMatchObject({ imageUrl: 'https://x/a.jpg', isCut: false }); + }); + + it('routes to OidbSvcTrpcTcp.0xe07_0 and round-trips the request body (locks pb tags)', async () => { + const sender = makeSender(); + await ImageOcr.invoke(sender, { imageUrl: 'https://x/a.jpg' }); + const [cmd, bytes] = sender.sendRawPacket.mock.calls[0]!; + expect(cmd).toBe('OidbSvcTrpcTcp.0xe07_0'); + const env = protobuf_decode>(bytes); + expect(env.command).toBe(0xE07); + // subCommand 0 is a protobuf default → omitted on the wire (decodes to + // null); the '0xe07_0' cmd string above already pins it. version/entrance + // are non-zero so survive; client=0 is likewise omitted (serialize test + // covers the pre-encode shape). + expect(env.body).toMatchObject({ version: 1, entrance: 1 }); + expect(env.body.ocrReqBody?.imageUrl).toBe('https://x/a.jpg'); + }); + + it('deserializes text detections + coordinates + language', async () => { + const result = await ImageOcr.invoke(makeSender(), { imageUrl: 'https://x/a.jpg' }); + expect(result.language).toBe('zh'); + expect(result.texts).toEqual([ + { text: '你好', confidence: 95, coordinates: [{ x: 1, y: 2 }, { x: 3, y: 4 }] }, + ]); + }); + + it('throws on a non-zero retCode', () => { + expect(() => ImageOcr.deserialize({} as any, { retCode: 5, errMsg: 'bad', wording: 'nope' })) + .toThrow(); + }); +}); From 90d3f7c0d6fc829e1e38c8460b1f583b683c82a2 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 00:40:26 +0800 Subject: [PATCH 09/33] test(protocol): real byte-oracle for ocr_image request wire MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adversarial Wave 3 pass: the prior 'round-trip locks pb tags' test was a fake lock — symmetric encode/decode via the same proto would not catch a tag swap. Replace with a fixed hex byte-oracle (hand-decoded in the comment) that goes red on any tag change, plus an empty-ocr-body deserialize test. Note in the action that a passed-in URL is used verbatim (not rkey re-signed). --- packages/onebot/src/actions/extended.ts | 3 +++ .../oidb-services/misc/image-ocr.test.ts | 20 +++++++++++++------ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index c47ee7a4..0214e2cc 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1258,6 +1258,9 @@ export const actions = [ readOnly: true, params: { image: f.string({ allowEmpty: false }) }, run: async (p, ctx) => { + // A passed-in http(s) URL is used verbatim (NOT re-signed) — if it is a + // stale CDN URL with an expired rkey the server fetch fails and surfaces + // the server's retCode. The file_id path below re-signs via getImageInfo. let url = /^https?:\/\//i.test(p.image) ? p.image : ''; if (!url) { const info = await ctx.getImageInfo(p.image); diff --git a/packages/protocol/tests/oidb-services/misc/image-ocr.test.ts b/packages/protocol/tests/oidb-services/misc/image-ocr.test.ts index 27dc0747..acdf61e4 100644 --- a/packages/protocol/tests/oidb-services/misc/image-ocr.test.ts +++ b/packages/protocol/tests/oidb-services/misc/image-ocr.test.ts @@ -43,21 +43,29 @@ describe('ImageOcr namespace', () => { expect(out.ocrReqBody).toMatchObject({ imageUrl: 'https://x/a.jpg', isCut: false }); }); - it('routes to OidbSvcTrpcTcp.0xe07_0 and round-trips the request body (locks pb tags)', async () => { + it('routes to OidbSvcTrpcTcp.0xe07_0 and encodes the exact wire bytes (fixed byte-oracle locks pb tags)', async () => { const sender = makeSender(); await ImageOcr.invoke(sender, { imageUrl: 'https://x/a.jpg' }); const [cmd, bytes] = sender.sendRawPacket.mock.calls[0]!; expect(cmd).toBe('OidbSvcTrpcTcp.0xe07_0'); + // Independent byte-oracle: a fixed hex constant, NOT re-derived from the + // proto, so a tag change actually goes red (a symmetric encode→decode + // round-trip would not). Hand-decoded: 08 871c = field1 command varint + // 0xE07; 22 17 = field4 body (23B); body: 08 01 version=1, 18 01 + // entrance=1 (client=0 omitted), 52 11 = field10 ocrReqBody (17B): + // 0a 0f = field1 imageUrl + "https://x/a.jpg". + expect(Buffer.from(bytes).toString('hex')) + .toBe('08871c22170801180152110a0f68747470733a2f2f782f612e6a7067'); + // And the structure decodes back as expected. const env = protobuf_decode>(bytes); expect(env.command).toBe(0xE07); - // subCommand 0 is a protobuf default → omitted on the wire (decodes to - // null); the '0xe07_0' cmd string above already pins it. version/entrance - // are non-zero so survive; client=0 is likewise omitted (serialize test - // covers the pre-encode shape). - expect(env.body).toMatchObject({ version: 1, entrance: 1 }); expect(env.body.ocrReqBody?.imageUrl).toBe('https://x/a.jpg'); }); + it('deserializes an empty ocr body to {texts:[], language:""}', () => { + expect(ImageOcr.deserialize({} as any, { retCode: 0 })).toEqual({ texts: [], language: '' }); + }); + it('deserializes text detections + coordinates + language', async () => { const result = await ImageOcr.invoke(makeSender(), { imageUrl: 'https://x/a.jpg' }); expect(result.language).toBe('zh'); From 77b16faebb2a4e0a33b7a9180a330ca978a95cb8 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 14:19:45 +0800 Subject: [PATCH 10/33] feat(common): extend RuntimeConfig for WebUI listener settings Add webuiHost / webuiTls.enabled / trustProxy to RuntimeConfig as the shared system-settings model for WebUI Wave A1 (HTTPS + self-config panel). Refactor load into pure, tested normalizeRuntimeConfig + resolveRuntimeEnvOverrides (env wins, in-memory only; SNOWLUMA_WEBUI_HOST added alongside the existing PORT/TRUST_PROXY overrides). loadRuntimeConfig backfills older runtime.json with the new defaults. Adds vitest to @snowluma/common (was typecheck-only). --- packages/common/package.json | 6 +- packages/common/src/runtime.ts | 137 ++++++++++++++++---------- packages/common/tests/runtime.test.ts | 76 ++++++++++++++ packages/common/vitest.config.ts | 10 ++ pnpm-lock.yaml | 44 +-------- 5 files changed, 182 insertions(+), 91 deletions(-) create mode 100644 packages/common/tests/runtime.test.ts create mode 100644 packages/common/vitest.config.ts diff --git a/packages/common/package.json b/packages/common/package.json index 23563203..4186c200 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -45,10 +45,12 @@ } }, "scripts": { - "typecheck": "tsc --noEmit" + "typecheck": "tsc --noEmit", + "test": "vitest run" }, "devDependencies": { "@types/node": "^24.12.2", - "typescript": "catalog:" + "typescript": "catalog:", + "vitest": "^4.1.4" } } diff --git a/packages/common/src/runtime.ts b/packages/common/src/runtime.ts index d1f5e610..ecde226e 100644 --- a/packages/common/src/runtime.ts +++ b/packages/common/src/runtime.ts @@ -7,71 +7,81 @@ export interface RuntimeConfig { * the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD. * Defaults to false; the Docker image flips it on in supervisord.conf. */ hookAutoLoad?: boolean; + /** WebUI listener bind address. '0.0.0.0' = all interfaces (default), + * '127.0.0.1' = localhost-only. Listener-level: change needs a restart. */ + webuiHost?: string; + /** WebUI TLS. Cert/key live in config/cert.pem + config/key.pem; this + * only flips serving on/off. Listener-level: change needs a restart. */ + webuiTls?: { enabled?: boolean }; + /** Raw trust-proxy directive (same domain as SNOWLUMA_WEBUI_TRUST_PROXY), + * consumed by the WebUI's client-ip resolver. '' = trust nobody. */ + trustProxy?: string; } const CONFIG_DIR = 'config'; const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json'); -const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = { - webuiPort: 5099, - hookAutoLoad: false, -}; +const DEFAULT_WEBUI_PORT = 5099; +const DEFAULT_WEBUI_HOST = '0.0.0.0'; + +/** + * Pure on-disk-object → typed config normalization (defaults + validation, + * no fs / no env). Exported for testing; `loadRuntimeConfig` wraps it. + */ +export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig { + const obj = isObject(parsed) ? parsed : {}; + return { + webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT), + hookAutoLoad: normalizeBool(obj.hookAutoLoad, false), + webuiHost: normalizeHost(obj.webuiHost), + webuiTls: { enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false }, + trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '', + }; +} + +/** + * Pure SNOWLUMA_* env → override patch (no fs). Env wins over runtime.json + * (a trusted launcher like SnowLumaDesktop pins these per-launch without + * rewriting the file). Absent vars produce no key. + */ +export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial { + const out: Partial = {}; + + const port = parsePortString(env.SNOWLUMA_WEBUI_PORT); + if (port !== undefined) out.webuiPort = port; + + const host = env.SNOWLUMA_WEBUI_HOST; + if (typeof host === 'string' && host.trim()) out.webuiHost = host.trim(); + + // Present-but-"0"/"off" is a deliberate override (trust nobody), distinct + // from "absent" — so gate on key presence, not truthiness. + const tp = env.SNOWLUMA_WEBUI_TRUST_PROXY; + if (typeof tp === 'string') out.trustProxy = tp; + + return out; +} export function loadRuntimeConfig(): RuntimeConfig { fs.mkdirSync(CONFIG_DIR, { recursive: true }); - const loaded = tryLoadRuntimeConfig(); - let normalized: RuntimeConfig; - if (!loaded) { - saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG); - normalized = { ...DEFAULT_RUNTIME_CONFIG }; - } else { - normalized = { - webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099), - hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false), - }; - if ( - normalized.webuiPort !== loaded.webuiPort - || normalized.hookAutoLoad !== loaded.hookAutoLoad - ) { - saveRuntimeConfig(normalized); - } + const parsed = tryLoadRuntimeConfig(); + const normalized = normalizeRuntimeConfig(parsed ?? {}); + + // Persist when the file is absent or when normalization changed/backfilled + // anything (e.g. an older runtime.json lacking webuiHost/webuiTls). + if (parsed === null || !sameRuntimeConfig(parsed, normalized)) { + saveRuntimeConfig(normalized); } - // SNOWLUMA_WEBUI_PORT overrides the on-disk value at runtime without - // rewriting runtime.json. Lets a trusted launcher (e.g. SnowLumaDesktop) - // pick a free port per-launch while CLI/Docker users continue to drive - // it from runtime.json. - const envPort = envPortOverride(); - if (envPort !== undefined) { - normalized = { ...normalized, webuiPort: envPort }; - } - - return normalized; + // Env overrides apply in-memory only — never written back to disk. + return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) }; } -function envPortOverride(): number | undefined { - const raw = process.env.SNOWLUMA_WEBUI_PORT; - if (!raw || typeof raw !== 'string') return undefined; - const n = Number(raw.trim()); - if (!Number.isFinite(n)) return undefined; - const port = Math.trunc(n); - if (port <= 0 || port > 65535) return undefined; - return port; -} - -function tryLoadRuntimeConfig(): RuntimeConfig | null { +function tryLoadRuntimeConfig(): Record | null { if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null; - try { - const raw = fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8'); - const parsed = JSON.parse(raw) as unknown; - if (!isObject(parsed)) return null; - - return { - webuiPort: normalizePort(parsed.webuiPort ?? 5099, 5099), - hookAutoLoad: normalizeBool(parsed.hookAutoLoad, false), - }; + const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown; + return isObject(parsed) ? parsed : null; } catch { return null; } @@ -81,6 +91,33 @@ function saveRuntimeConfig(config: RuntimeConfig): void { fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8'); } +/** True when the raw on-disk object already matches the normalized config + * on every known field (so we can skip a needless rewrite). */ +function sameRuntimeConfig(parsed: Record, n: RuntimeConfig): boolean { + const parsedTls = isObject(parsed.webuiTls) ? parsed.webuiTls.enabled : undefined; + return ( + parsed.webuiPort === n.webuiPort + && parsed.hookAutoLoad === n.hookAutoLoad + && parsed.webuiHost === n.webuiHost + && parsedTls === n.webuiTls?.enabled + && parsed.trustProxy === n.trustProxy + ); +} + +function parsePortString(raw: unknown): number | undefined { + if (typeof raw !== 'string' || !raw.trim()) return undefined; + const n = Number(raw.trim()); + if (!Number.isFinite(n)) return undefined; + const port = Math.trunc(n); + if (port <= 0 || port > 65535) return undefined; + return port; +} + +function normalizeHost(value: unknown): string { + if (typeof value === 'string' && value.trim()) return value.trim(); + return DEFAULT_WEBUI_HOST; +} + function normalizePort(value: unknown, fallback: number): number { if (typeof value === 'number' && Number.isFinite(value)) { const n = Math.trunc(value); diff --git a/packages/common/tests/runtime.test.ts b/packages/common/tests/runtime.test.ts new file mode 100644 index 00000000..32221cc1 --- /dev/null +++ b/packages/common/tests/runtime.test.ts @@ -0,0 +1,76 @@ +import { describe, it, expect } from 'vitest'; +import { normalizeRuntimeConfig, resolveRuntimeEnvOverrides } from '../src/runtime'; + +describe('normalizeRuntimeConfig', () => { + it('applies all defaults for an empty object', () => { + expect(normalizeRuntimeConfig({})).toEqual({ + webuiPort: 5099, + hookAutoLoad: false, + webuiHost: '0.0.0.0', + webuiTls: { enabled: false }, + trustProxy: '', + }); + }); + + it('passes through valid values', () => { + expect(normalizeRuntimeConfig({ + webuiPort: 8080, + hookAutoLoad: true, + webuiHost: '127.0.0.1', + webuiTls: { enabled: true }, + trustProxy: '1', + })).toEqual({ + webuiPort: 8080, + hookAutoLoad: true, + webuiHost: '127.0.0.1', + webuiTls: { enabled: true }, + trustProxy: '1', + }); + }); + + it('falls back on invalid types', () => { + const out = normalizeRuntimeConfig({ + webuiPort: 0, // out of range → default + webuiHost: 123, // non-string → default + webuiTls: 'yes', // non-object → default + trustProxy: 5, // non-string → default + }); + expect(out.webuiPort).toBe(5099); + expect(out.webuiHost).toBe('0.0.0.0'); + expect(out.webuiTls).toEqual({ enabled: false }); + expect(out.trustProxy).toBe(''); + }); + + it('coerces webuiTls.enabled loosely and trims a blank host to default', () => { + expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true }); + expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('0.0.0.0'); + }); + + it('rejects a non-object input back to full defaults', () => { + expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099); + expect(normalizeRuntimeConfig('nope').webuiHost).toBe('0.0.0.0'); + }); +}); + +describe('resolveRuntimeEnvOverrides', () => { + it('returns empty when no SNOWLUMA_* vars are set', () => { + expect(resolveRuntimeEnvOverrides({})).toEqual({}); + }); + + it('parses port / host / trustProxy from env', () => { + expect(resolveRuntimeEnvOverrides({ + SNOWLUMA_WEBUI_PORT: '6700', + SNOWLUMA_WEBUI_HOST: '127.0.0.1', + SNOWLUMA_WEBUI_TRUST_PROXY: '1', + })).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' }); + }); + + it('ignores an out-of-range / non-numeric port env', () => { + expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({}); + expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({}); + }); + + it('treats trustProxy="0"/"off" as a real override (not absent)', () => { + expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({ trustProxy: '0' }); + }); +}); diff --git a/packages/common/vitest.config.ts b/packages/common/vitest.config.ts new file mode 100644 index 00000000..d807e895 --- /dev/null +++ b/packages/common/vitest.config.ts @@ -0,0 +1,10 @@ +// Vitest config for @snowluma/common. Pure-TS package (no proton), so a +// plain node-environment runner over tests/ is enough. +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['tests/**/*.test.ts'], + environment: 'node', + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3dbee74c..c68c8d21 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -81,6 +81,9 @@ importers: typescript: specifier: 'catalog:' version: 6.0.2 + vitest: + specifier: ^4.1.4 + version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) packages/core: dependencies: @@ -4437,7 +4440,7 @@ snapshots: magicast: 0.5.3 obug: 2.1.1 tinyrainbow: 3.1.0 - vitest: 4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) transitivePeerDependencies: - supports-color @@ -4453,7 +4456,7 @@ snapshots: obug: 2.1.1 std-env: 4.1.0 tinyrainbow: 3.1.0 - vitest: 4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) '@vitest/expect@4.1.4': dependencies: @@ -4472,14 +4475,6 @@ snapshots: optionalDependencies: vite: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) - '@vitest/mocker@4.1.4(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))': - dependencies: - '@vitest/spy': 4.1.4 - estree-walker: 3.0.3 - magic-string: 0.30.21 - optionalDependencies: - vite: 8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) - '@vitest/pretty-format@4.1.4': dependencies: tinyrainbow: 3.1.0 @@ -5777,35 +5772,6 @@ snapshots: transitivePeerDependencies: - msw - vitest@4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)): - dependencies: - '@vitest/expect': 4.1.4 - '@vitest/mocker': 4.1.4(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) - '@vitest/pretty-format': 4.1.4 - '@vitest/runner': 4.1.4 - '@vitest/snapshot': 4.1.4 - '@vitest/spy': 4.1.4 - '@vitest/utils': 4.1.4 - es-module-lexer: 2.0.0 - expect-type: 1.3.0 - magic-string: 0.30.21 - obug: 2.1.1 - pathe: 2.0.3 - picomatch: 4.0.4 - std-env: 4.1.0 - tinybench: 2.9.0 - tinyexec: 1.1.1 - tinyglobby: 0.2.16 - tinyrainbow: 3.1.0 - vite: 8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) - why-is-node-running: 2.3.0 - optionalDependencies: - '@types/node': 25.6.0 - '@vitest/coverage-istanbul': 4.1.4(vitest@4.1.4) - '@vitest/coverage-v8': 4.1.4(vitest@4.1.4) - transitivePeerDependencies: - - msw - vp-runtime-helper@1.0.10: dependencies: '@types/fs-extra': 11.0.4 From 64c10e2856c27d05fdf6f23062a8e28487a8478c Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 14:24:51 +0800 Subject: [PATCH 11/33] feat(webui): HTTPS serving + configurable bind host initWebUI now takes { host, tlsEnabled }. When TLS is enabled, load+validate config/cert.pem + key.pem (tls.ts: validateTlsPair / resolveTlsContext, both unit-tested) and serve via @hono/node-server's https createServer; a missing or invalid cert falls back to HTTP with a loud warning (never bricks the WebUI). Bind host is now configurable (default 0.0.0.0). Wired from runtime.json (webuiHost / webuiTls.enabled) in core/index.ts. --- packages/core/src/index.ts | 5 +- packages/core/src/webui/server.ts | 23 +++++- packages/core/src/webui/tls.ts | 57 ++++++++++++++ packages/core/tests/webui-tls.test.ts | 102 ++++++++++++++++++++++++++ 4 files changed, 184 insertions(+), 3 deletions(-) create mode 100644 packages/core/src/webui/tls.ts create mode 100644 packages/core/tests/webui-tls.test.ts diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 728681e3..d7188d3b 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -48,7 +48,10 @@ async function main() { ) { try { const { initWebUI } = await import('./webui/server'); - await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager); + await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, { + host: runtimeConfig.webuiHost, + tlsEnabled: runtimeConfig.webuiTls?.enabled, + }); } catch (err) { log.error('Failed to start WebUI: ', err); } diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 4d48510f..14b1f764 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -7,11 +7,13 @@ import type { OneBotManager } from '@snowluma/onebot/manager'; import type { OneBotConfig } from '@snowluma/onebot/types'; import { randomBytes } from 'crypto'; import { existsSync, readFileSync } from 'fs'; +import { createServer as createHttpsServer } from 'https'; import { Hono, type Context } from 'hono'; import os from 'os'; import path from 'path'; import { fileURLToPath } from 'url'; import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth'; +import { resolveTlsContext } from './tls'; import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; import { findAvailablePort } from './port'; import { @@ -105,6 +107,7 @@ export async function initWebUI( oneBotManager: OneBotManager, hookManager?: HookManager, notificationManager?: NotificationManager, + listener: { host?: string; tlsEnabled?: boolean } = {}, ): Promise<{ port: number }> { const auth = WebuiAuth.load(); const initialPassword = auth.takeInitialPassword(); @@ -709,9 +712,25 @@ export async function initWebUI( log.warn('port %d is in use, using %d instead', desiredPort, finalPort); } + const host = listener.host || '0.0.0.0'; + + // TLS: only when explicitly enabled AND the on-disk cert/key load. A bad + // or missing cert must never brick the WebUI — fall back to HTTP + warn. + let tlsServe: { createServer: typeof createHttpsServer; serverOptions: { cert: Buffer; key: Buffer } } | undefined; + let scheme = 'http'; + if (listener.tlsEnabled) { + const tls = resolveTlsContext('config'); + if (tls.ok && tls.cert && tls.key) { + tlsServe = { createServer: createHttpsServer, serverOptions: { cert: tls.cert, key: tls.key } }; + scheme = 'https'; + } else { + log.warn('TLS enabled but cert/key unusable (%s) — serving over HTTP instead', tls.reason); + } + } + await new Promise((resolve) => { - serve({ fetch: app.fetch, port: finalPort }, (info) => { - log.info(`listening http://localhost:${info.port}`); + serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => { + log.info(`listening ${scheme}://${host}:${info.port}`); resolve(); }); }); diff --git a/packages/core/src/webui/tls.ts b/packages/core/src/webui/tls.ts new file mode 100644 index 00000000..144e0b1e --- /dev/null +++ b/packages/core/src/webui/tls.ts @@ -0,0 +1,57 @@ +// WebUI TLS helpers. Cert/key live as config/cert.pem + config/key.pem +// (NapCat-aligned, self-contained, travels in A2 backups). Two pure-ish +// helpers: validate a pasted pair (save path) and resolve the on-disk pair +// (boot path). Validation is `tls.createSecureContext` — it parses the PEM +// and checks the key matches the cert; expiry is NOT checked here. + +import fs from 'fs'; +import path from 'path'; +import tls from 'tls'; + +export interface TlsValidation { + ok: boolean; + reason?: string; +} + +export interface TlsResolution { + ok: boolean; + cert?: Buffer; + key?: Buffer; + reason?: string; +} + +function errMsg(e: unknown): string { + return e instanceof Error ? e.message : String(e); +} + +/** Parse-validate a cert/key pair (used by the save endpoint before writing). */ +export function validateTlsPair(cert: string | Buffer, key: string | Buffer): TlsValidation { + if (!cert || !cert.toString().trim()) return { ok: false, reason: 'certificate is empty' }; + if (!key || !key.toString().trim()) return { ok: false, reason: 'private key is empty' }; + try { + tls.createSecureContext({ cert, key }); + return { ok: true }; + } catch (e) { + return { ok: false, reason: `invalid cert/key: ${errMsg(e)}` }; + } +} + +/** Load + validate config/cert.pem + config/key.pem from `configDir`. */ +export function resolveTlsContext(configDir: string): TlsResolution { + const certPath = path.join(configDir, 'cert.pem'); + const keyPath = path.join(configDir, 'key.pem'); + if (!fs.existsSync(certPath) || !fs.existsSync(keyPath)) { + return { ok: false, reason: 'cert.pem or key.pem missing in config dir' }; + } + let cert: Buffer; + let key: Buffer; + try { + cert = fs.readFileSync(certPath); + key = fs.readFileSync(keyPath); + } catch (e) { + return { ok: false, reason: `failed to read cert/key: ${errMsg(e)}` }; + } + const valid = validateTlsPair(cert, key); + if (!valid.ok) return { ok: false, reason: valid.reason }; + return { ok: true, cert, key }; +} diff --git a/packages/core/tests/webui-tls.test.ts b/packages/core/tests/webui-tls.test.ts new file mode 100644 index 00000000..115ada7d --- /dev/null +++ b/packages/core/tests/webui-tls.test.ts @@ -0,0 +1,102 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { validateTlsPair, resolveTlsContext } from '../src/webui/tls'; + +// A throwaway self-signed pair (openssl, CN=snowluma-test). createSecureContext +// only parses — expiry is irrelevant — so this stays valid for the test forever. +const CERT = `-----BEGIN CERTIFICATE----- +MIIDETCCAfmgAwIBAgIUNiu66PmcO6Do6cUaB92UKD8j3qYwDQYJKoZIhvcNAQEL +BQAwGDEWMBQGA1UEAwwNc25vd2x1bWEtdGVzdDAeFw0yNjA2MTgwNjIwMTZaFw0z +NjA2MTUwNjIwMTZaMBgxFjAUBgNVBAMMDXNub3dsdW1hLXRlc3QwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCm0sVJhqlG75gOFJVsUJOfR+oqvb9eSq4t +k5QItuwXr85E2mrzuKFnSzVVbi3VqqyN8t4otL11mGll2ANSjusmWN4hzpaOBBdX +bP4UNX/YA7oHId+QKbVicxJgxDE18aPTwaWullyw23LsMsij8T4nLk4eHiOkeRfi +uLinG1COe3gUGkCK4uyyMT4Vz+y+5Oj9dvoXYL/A/KmcNtq7JrX7F7qYnYsJKLZZ +aZeFyIGSE8ihb0k53iyJ3agWY+rMUD+p5J7pgIZzBd5dcZuI+KwixVKZgapG5n5R +ghrnN2ZAQFz13yTRXYmDYy42m4Ue73hMmmt1xVXyf+WVhvrD6pphAgMBAAGjUzBR +MB0GA1UdDgQWBBRW/HP12nj9fYMYNxa3jyqmnUigvTAfBgNVHSMEGDAWgBRW/HP1 +2nj9fYMYNxa3jyqmnUigvTAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUA +A4IBAQCijzVQ/jHNoqu6stvkkigUv2lTKrd1EHcTZLfzwQkmNv/hfY2EMobO/Qxs +FhmITreKFALJ/dUwTt0UTO00LV9whEgr2of4x8wwjZ9wRstY6uyRYBP85QC8+8mZ +zWlcf611HugrmpOWjWfEVmmxdI1m26YWTn52nZFPnJqDWg2+RlLJWl55lVotbXEZ +Fvas4Vcf2KOk0QwBQKvpt0BISeTIQhbT4GnducxSxyoXGeBQOjQNYb/vTpMn4F9U +IAxSsfs9WVoHKXOabK8GV89BCxWoRk4UaSahTq/2Vnbgt86tWibt3lA4y49+XhA2 +6z7n9HgJAUKqhsDrYvZmM7/VZ2d5 +-----END CERTIFICATE----- +`; +const KEY = `-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCm0sVJhqlG75gO +FJVsUJOfR+oqvb9eSq4tk5QItuwXr85E2mrzuKFnSzVVbi3VqqyN8t4otL11mGll +2ANSjusmWN4hzpaOBBdXbP4UNX/YA7oHId+QKbVicxJgxDE18aPTwaWullyw23Ls +Msij8T4nLk4eHiOkeRfiuLinG1COe3gUGkCK4uyyMT4Vz+y+5Oj9dvoXYL/A/Kmc +Ntq7JrX7F7qYnYsJKLZZaZeFyIGSE8ihb0k53iyJ3agWY+rMUD+p5J7pgIZzBd5d +cZuI+KwixVKZgapG5n5RghrnN2ZAQFz13yTRXYmDYy42m4Ue73hMmmt1xVXyf+WV +hvrD6pphAgMBAAECggEAJ13+u4qhIMHCnrQBzPU42PImEt8DLXOvJcc5PFM6ZJ6S +rRHkAk60HAWV+OqOu2jS3o6NGYsJWJpWaPewVQev+zUmelDfm3TgsztfvBIh8K50 +dGFsef81tB1WnWo++K1kzUBZ4ljOV9f5hz62tWVlFubo/Vd8bsA6wEB6Jskd2fls +ZOO0hJCb/M6IIwe3cWw4sb/YFTTLMUnVHM0aJfnQ/QH+uraRwecJMv118d0YBYVG +DsNmYqrv9TYNBh4P9mKv6/0x8zaKsJZVLAMwHztILHItOXBfxCbSDivGWVUGiDq2 +NxEuBOgxzOelxEYzUzf7B6sjHoEeIL5wIKQbwUbmfwKBgQDZRLhucrMZPw7ous1t +igkO32p1ku7FRxm0/JAskc66oX61KLIYbZFM9N7nTXAEs8ZGhzUkdSgxNcdHWIdK +RI+6pd2FhhcKU1feEohlOHvZTXXEMhm61phWnN391GZXfwMKSpscqsu9kIix2jtw +4YrzKLx82EDDHcLfBh9AtArKywKBgQDEj+7UJp5wuqz9hj+gogXeq4Buv9be1u4u +HCJZMZzLCwVjvoqYw0n1afXP3057v8hQPGsBaxzQpOg7i1lYGGfuZ9T6T8fFrtqw +m/LJLHhMQxeyCEQi1/EoNewvVGSwBJkLOuOs8T2WmMXmOgdHbEYdzkKtT71jst6y +TeJ15hVuAwKBgBMK4t9LTkc4L6ZWOQsQvhp/mmUTq7m+sZIbUMeXP/c7kE9wcauS +btm/3ImJT/gZiZdE4nN/kTY+8GhgafsoZzCEuRWq2vocs+bS2QGGIdS55Uh826R0 +ioWM2igVJaMljq6oO1AX6COFN3XfGraaDgOh3mNS0NpJEXtangKdxRRhAoGAP9SF +t/r6hJz6RDHuQ5mZ0l9bC5vciOy+19ZnCRPlWMIxc9ySYV05jSplmqVndSQoRnX4 +QbOo3dBPYda0orj6Nx8cuFRkCTvo5GUgCFgakJlQ/o1UowQA2g/4rL35HHfBwzXS +bXzBhUADM+owJu9wLYmneWRlmhSh4MEOAz8+QkUCgYAw0fA1Im2/ftrA2Z2IENTi +U4cLXqeUeGJfXjIBklUmXhc4qrd/9V9eEHjackI/JI7Qhp/QfPWMXLudlSrppnNJ ++s3dVevEKosiZbf4qtTtlmR/IifuTKjK5O94KlBT+evxNsL4Hv0b0oTsVNnEfOOl +OUsvSYNSnfvl87tyLIxYLA== +-----END PRIVATE KEY----- +`; + +describe('validateTlsPair', () => { + it('accepts a matching cert/key pair', () => { + expect(validateTlsPair(CERT, KEY)).toEqual({ ok: true }); + }); + + it('rejects garbage PEM with a reason', () => { + const r = validateTlsPair('not a cert', 'not a key'); + expect(r.ok).toBe(false); + expect(r.reason).toBeTruthy(); + }); + + it('rejects an empty cert', () => { + expect(validateTlsPair('', KEY).ok).toBe(false); + }); +}); + +describe('resolveTlsContext', () => { + let dir: string; + beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-tls-')); }); + afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); }); + + it('loads cert.pem + key.pem when both present and valid', () => { + fs.writeFileSync(path.join(dir, 'cert.pem'), CERT); + fs.writeFileSync(path.join(dir, 'key.pem'), KEY); + const r = resolveTlsContext(dir); + expect(r.ok).toBe(true); + expect(r.cert?.toString()).toContain('BEGIN CERTIFICATE'); + expect(r.key?.toString()).toContain('PRIVATE KEY'); + }); + + it('fails (with reason) when files are missing', () => { + const r = resolveTlsContext(dir); + expect(r.ok).toBe(false); + expect(r.reason).toMatch(/missing/i); + }); + + it('fails when the on-disk PEM is invalid', () => { + fs.writeFileSync(path.join(dir, 'cert.pem'), 'garbage'); + fs.writeFileSync(path.join(dir, 'key.pem'), 'garbage'); + const r = resolveTlsContext(dir); + expect(r.ok).toBe(false); + expect(r.reason).toBeTruthy(); + }); +}); From ad21e19dc86da339e850f1f2132e57974adcac3f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 14:26:32 +0800 Subject: [PATCH 12/33] feat(webui): source trustProxy from runtime config (env still overrides) Move the trust-proxy/client-ip resolver from a module-level direct read of SNOWLUMA_WEBUI_TRUST_PROXY into initWebUI, fed by runtime.json's trustProxy (loadRuntimeConfig already merges the env override on top). Default '' parses identically to the old undefined (trust socket peer only), so behavior is unchanged when unset. --- packages/core/src/index.ts | 1 + packages/core/src/webui/server.ts | 17 ++++++++--------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d7188d3b..4668352e 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -51,6 +51,7 @@ async function main() { await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, { host: runtimeConfig.webuiHost, tlsEnabled: runtimeConfig.webuiTls?.enabled, + trustProxy: runtimeConfig.trustProxy, }); } catch (err) { log.error('Failed to start WebUI: ', err); diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 14b1f764..7b8b29c5 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -80,14 +80,6 @@ function purgeExpiredTokens() { } } -/** - * Resolve the client IP for per-IP rate limiting. Default is the TCP - * socket peer (cannot be spoofed by the client). Operators behind a - * reverse proxy must opt in via the `SNOWLUMA_WEBUI_TRUST_PROXY` env - * var; see `./client-ip.ts` for the accepted values. - */ -const trustProxyMode = parseTrustProxy(process.env.SNOWLUMA_WEBUI_TRUST_PROXY); -const getClientIp = makeClientIpResolver(trustProxyMode); async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> { const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, { @@ -107,8 +99,15 @@ export async function initWebUI( oneBotManager: OneBotManager, hookManager?: HookManager, notificationManager?: NotificationManager, - listener: { host?: string; tlsEnabled?: boolean } = {}, + listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string } = {}, ): Promise<{ port: number }> { + // Resolve the client IP for per-IP rate limiting from the configured + // trust-proxy directive (runtime.json `trustProxy`, env-overridable via + // SNOWLUMA_WEBUI_TRUST_PROXY which loadRuntimeConfig already merged in). + // Default ('') = trust the TCP socket peer only (cannot be spoofed). + const trustProxyMode = parseTrustProxy(listener.trustProxy); + const getClientIp = makeClientIpResolver(trustProxyMode); + const auth = WebuiAuth.load(); const initialPassword = auth.takeInitialPassword(); if (auth.isDevMode()) { From 9a455b30c60c3383a6c0c15fdfd56522d468d313 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 14:28:31 +0800 Subject: [PATCH 13/33] feat(common): updateRuntimeConfig(patch) for the WebUI settings panel Persist a partial RuntimeConfig update, merging onto the on-disk config (not the env-merged view) so an env override is never baked into runtime.json. Tested: patch merge + the env-not-persisted invariant (chdir to a temp cwd). --- packages/common/src/runtime.ts | 13 ++++++++ packages/common/tests/runtime.test.ts | 43 ++++++++++++++++++++++++++- 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/packages/common/src/runtime.ts b/packages/common/src/runtime.ts index ecde226e..18cbd1b5 100644 --- a/packages/common/src/runtime.ts +++ b/packages/common/src/runtime.ts @@ -77,6 +77,19 @@ export function loadRuntimeConfig(): RuntimeConfig { return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) }; } +/** + * Persist a partial update. Merges onto the ON-DISK config (not the env-merged + * runtime view) so an env override (e.g. SNOWLUMA_WEBUI_PORT) is never baked + * into runtime.json. Returns the new persisted config (without env overrides). + */ +export function updateRuntimeConfig(patch: Partial): RuntimeConfig { + fs.mkdirSync(CONFIG_DIR, { recursive: true }); + const onDisk = normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {}); + const next = normalizeRuntimeConfig({ ...onDisk, ...patch }); + saveRuntimeConfig(next); + return next; +} + function tryLoadRuntimeConfig(): Record | null { if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null; try { diff --git a/packages/common/tests/runtime.test.ts b/packages/common/tests/runtime.test.ts index 32221cc1..8814c34f 100644 --- a/packages/common/tests/runtime.test.ts +++ b/packages/common/tests/runtime.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { normalizeRuntimeConfig, resolveRuntimeEnvOverrides } from '../src/runtime'; describe('normalizeRuntimeConfig', () => { @@ -74,3 +74,44 @@ describe('resolveRuntimeEnvOverrides', () => { expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({ trustProxy: '0' }); }); }); + +describe('updateRuntimeConfig (fs)', () => { + let prevCwd: string; + let dir: string; + let prevPortEnv: string | undefined; + beforeEach(async () => { + const fs = await import('fs'); const os = await import('os'); const path = await import('path'); + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-rt-')); + prevCwd = process.cwd(); + process.chdir(dir); + prevPortEnv = process.env.SNOWLUMA_WEBUI_PORT; + delete process.env.SNOWLUMA_WEBUI_PORT; + }); + afterEach(async () => { + const fs = await import('fs'); + process.chdir(prevCwd); + if (prevPortEnv === undefined) delete process.env.SNOWLUMA_WEBUI_PORT; + else process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv; + fs.rmSync(dir, { recursive: true, force: true }); + }); + + it('merges a patch over on-disk values and persists normalized', async () => { + const { updateRuntimeConfig } = await import('../src/runtime'); + const fs = await import('fs'); const path = await import('path'); + const out = updateRuntimeConfig({ webuiHost: '127.0.0.1', webuiTls: { enabled: true } }); + expect(out.webuiHost).toBe('127.0.0.1'); + expect(out.webuiTls).toEqual({ enabled: true }); + const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8')); + expect(onDisk.webuiHost).toBe('127.0.0.1'); + expect(onDisk.webuiTls).toEqual({ enabled: true }); + }); + + it('does NOT bake an env-overridden port into the persisted file', async () => { + const { updateRuntimeConfig } = await import('../src/runtime'); + const fs = await import('fs'); const path = await import('path'); + process.env.SNOWLUMA_WEBUI_PORT = '9999'; + updateRuntimeConfig({ webuiHost: '127.0.0.1' }); + const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8')); + expect(onDisk.webuiPort).toBe(5099); // default on-disk, NOT the env 9999 + }); +}); From 7faef1b7c043bb00891dceab086a9a2eb9231050 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 14:32:24 +0800 Subject: [PATCH 14/33] feat(webui): system settings + TLS cert API (Wave A1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET/POST /api/system/settings (port/host/tlsEnabled/trustProxy) persisted via updateRuntimeConfig — listener-level, restart-to-apply; response carries restartRequiredToApply + the env-overridden field names so the panel can flag edits that won't take effect. Enabling TLS is blocked unless a usable cert is present. POST/DELETE /api/system/tls/cert validates a pasted PEM pair (validateTlsPair) before writing config/cert.pem + key.pem. Adds read-only readRuntimeConfig() and a tested pure coerceSettingsPatch validator. All routes sit behind the existing /api/* auth middleware. --- packages/common/src/runtime.ts | 8 ++ packages/core/src/webui/server.ts | 99 ++++++++++++++++++- packages/core/src/webui/system-settings.ts | 52 ++++++++++ .../core/tests/webui-system-settings.test.ts | 39 ++++++++ 4 files changed, 196 insertions(+), 2 deletions(-) create mode 100644 packages/core/src/webui/system-settings.ts create mode 100644 packages/core/tests/webui-system-settings.test.ts diff --git a/packages/common/src/runtime.ts b/packages/common/src/runtime.ts index 18cbd1b5..e6eca30b 100644 --- a/packages/common/src/runtime.ts +++ b/packages/common/src/runtime.ts @@ -77,6 +77,14 @@ export function loadRuntimeConfig(): RuntimeConfig { return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) }; } +/** + * Read the persisted config (normalized, no env overrides, no write). For the + * settings panel's GET — shows what's actually saved/editable on disk. + */ +export function readRuntimeConfig(): RuntimeConfig { + return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {}); +} + /** * Persist a partial update. Merges onto the ON-DISK config (not the env-merged * runtime view) so an env override (e.g. SNOWLUMA_WEBUI_PORT) is never baked diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 7b8b29c5..5034e344 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -5,15 +5,17 @@ import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subs import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config'; import type { OneBotManager } from '@snowluma/onebot/manager'; import type { OneBotConfig } from '@snowluma/onebot/types'; +import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime'; import { randomBytes } from 'crypto'; -import { existsSync, readFileSync } from 'fs'; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'; import { createServer as createHttpsServer } from 'https'; import { Hono, type Context } from 'hono'; import os from 'os'; import path from 'path'; import { fileURLToPath } from 'url'; import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth'; -import { resolveTlsContext } from './tls'; +import { resolveTlsContext, validateTlsPair } from './tls'; +import { coerceSettingsPatch } from './system-settings'; import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; import { findAvailablePort } from './port'; import { @@ -108,6 +110,10 @@ export async function initWebUI( const trustProxyMode = parseTrustProxy(listener.trustProxy); const getClientIp = makeClientIpResolver(trustProxyMode); + // Actual bound port (set just before serve; findAvailablePort may bump it). + // Read by GET /api/system/settings so the panel shows what's really live. + let boundPort = desiredPort; + const auth = WebuiAuth.load(); const initialPassword = auth.takeInitialPassword(); if (auth.isDevMode()) { @@ -397,6 +403,94 @@ export async function initWebUI( }); }); + // ── System settings (WebUI listener) — Wave A1 ── + // Listener-level changes (port/host/TLS) are persisted but apply only on the + // next restart (no supervisor → no self-restart). The panel surfaces which + // fields are currently overridden by env so edits that won't take effect are + // visible. + const SYSTEM_CERT_PATH = path.join('config', 'cert.pem'); + const SYSTEM_KEY_PATH = path.join('config', 'key.pem'); + const hasCert = (): boolean => existsSync(SYSTEM_CERT_PATH) && existsSync(SYSTEM_KEY_PATH); + + app.get('/api/system/settings', (c) => { + const disk = readRuntimeConfig(); + const envOverrides = Object.keys(resolveRuntimeEnvOverrides(process.env)); + return c.json({ + settings: { + webuiPort: disk.webuiPort, + webuiHost: disk.webuiHost, + tlsEnabled: disk.webuiTls?.enabled ?? false, + trustProxy: disk.trustProxy ?? '', + }, + hasCert: hasCert(), + envOverrides, // field names currently pinned by SNOWLUMA_* env vars + listeningPort: boundPort, + restartRequiredToApply: true, + }); + }); + + app.post('/api/system/settings', async (c) => { + let body: unknown; + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + const coerced = coerceSettingsPatch(body); + if (!coerced.ok) return c.json({ success: false, message: coerced.error }, 400); + // Enabling TLS without a usable cert would brick HTTPS on restart — block it. + if (coerced.patch.webuiTls?.enabled && !resolveTlsContext('config').ok) { + return c.json({ success: false, message: '启用 TLS 前请先上传有效的证书与私钥' }, 400); + } + const saved = updateRuntimeConfig(coerced.patch); + return c.json({ + success: true, + settings: { + webuiPort: saved.webuiPort, + webuiHost: saved.webuiHost, + tlsEnabled: saved.webuiTls?.enabled ?? false, + trustProxy: saved.trustProxy ?? '', + }, + restartRequiredToApply: true, + }); + }); + + app.post('/api/system/tls/cert', async (c) => { + let body: unknown; + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + const cert = (body as { cert?: unknown }).cert; + const key = (body as { key?: unknown }).key; + if (typeof cert !== 'string' || typeof key !== 'string') { + return c.json({ success: false, message: 'cert 和 key 必须为 PEM 字符串' }, 400); + } + const valid = validateTlsPair(cert, key); + if (!valid.ok) return c.json({ success: false, message: valid.reason }, 400); + try { + mkdirSync('config', { recursive: true }); + writeFileSync(SYSTEM_CERT_PATH, cert.endsWith('\n') ? cert : cert + '\n', 'utf8'); + writeFileSync(SYSTEM_KEY_PATH, key.endsWith('\n') ? key : key + '\n', 'utf8'); + } catch (err) { + log.warn('write cert/key failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '写入证书失败,请检查服务器日志' }, 500); + } + return c.json({ success: true, restartRequiredToApply: true }); + }); + + app.delete('/api/system/tls/cert', (c) => { + try { + rmSync(SYSTEM_CERT_PATH, { force: true }); + rmSync(SYSTEM_KEY_PATH, { force: true }); + } catch (err) { + log.warn('remove cert/key failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '删除证书失败' }, 500); + } + return c.json({ success: true }); + }); + app.get('/api/qq-list', (c) => { const instances = oneBotManager.getInstances(); const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.nickname })); @@ -710,6 +804,7 @@ export async function initWebUI( if (finalPort !== desiredPort) { log.warn('port %d is in use, using %d instead', desiredPort, finalPort); } + boundPort = finalPort; const host = listener.host || '0.0.0.0'; diff --git a/packages/core/src/webui/system-settings.ts b/packages/core/src/webui/system-settings.ts new file mode 100644 index 00000000..fcecf80e --- /dev/null +++ b/packages/core/src/webui/system-settings.ts @@ -0,0 +1,52 @@ +// Pure validator for the POST /api/system/settings body. Rejects clearly-bad +// input with a message (→ 400) rather than silently normalizing it, then hands +// a clean patch to updateRuntimeConfig. Wire field `tlsEnabled` maps to the +// nested `webuiTls.enabled`. + +import type { RuntimeConfig } from '@snowluma/common/runtime'; + +export type SettingsPatch = Partial>; + +export type CoerceResult = + | { ok: true; patch: SettingsPatch } + | { ok: false; error: string }; + +function isObject(v: unknown): v is Record { + return typeof v === 'object' && v !== null && !Array.isArray(v); +} + +export function coerceSettingsPatch(body: unknown): CoerceResult { + if (!isObject(body)) return { ok: false, error: 'body must be an object' }; + const patch: SettingsPatch = {}; + + if ('webuiPort' in body) { + const p = body.webuiPort; + if (typeof p !== 'number' || !Number.isInteger(p) || p <= 0 || p > 65535) { + return { ok: false, error: 'webuiPort must be an integer in 1..65535' }; + } + patch.webuiPort = p; + } + + if ('webuiHost' in body) { + if (typeof body.webuiHost !== 'string' || !body.webuiHost.trim()) { + return { ok: false, error: 'webuiHost must be a non-empty string' }; + } + patch.webuiHost = body.webuiHost.trim(); + } + + if ('tlsEnabled' in body) { + if (typeof body.tlsEnabled !== 'boolean') { + return { ok: false, error: 'tlsEnabled must be a boolean' }; + } + patch.webuiTls = { enabled: body.tlsEnabled }; + } + + if ('trustProxy' in body) { + if (typeof body.trustProxy !== 'string') { + return { ok: false, error: 'trustProxy must be a string' }; + } + patch.trustProxy = body.trustProxy; + } + + return { ok: true, patch }; +} diff --git a/packages/core/tests/webui-system-settings.test.ts b/packages/core/tests/webui-system-settings.test.ts new file mode 100644 index 00000000..d79b6607 --- /dev/null +++ b/packages/core/tests/webui-system-settings.test.ts @@ -0,0 +1,39 @@ +import { describe, it, expect } from 'vitest'; +import { coerceSettingsPatch } from '../src/webui/system-settings'; + +describe('coerceSettingsPatch', () => { + it('accepts a full valid body and maps tlsEnabled → webuiTls.enabled', () => { + const r = coerceSettingsPatch({ webuiPort: 8080, webuiHost: '127.0.0.1', tlsEnabled: true, trustProxy: '1' }); + expect(r).toEqual({ ok: true, patch: { webuiPort: 8080, webuiHost: '127.0.0.1', webuiTls: { enabled: true }, trustProxy: '1' } }); + }); + + it('only includes provided keys (partial patch)', () => { + const r = coerceSettingsPatch({ webuiHost: '0.0.0.0' }); + expect(r).toEqual({ ok: true, patch: { webuiHost: '0.0.0.0' } }); + }); + + it('rejects a non-object body', () => { + expect(coerceSettingsPatch(null).ok).toBe(false); + expect(coerceSettingsPatch('x').ok).toBe(false); + }); + + it('rejects an out-of-range or non-integer port', () => { + expect(coerceSettingsPatch({ webuiPort: 0 }).ok).toBe(false); + expect(coerceSettingsPatch({ webuiPort: 70000 }).ok).toBe(false); + expect(coerceSettingsPatch({ webuiPort: 12.5 }).ok).toBe(false); + }); + + it('rejects an empty/blank host', () => { + expect(coerceSettingsPatch({ webuiHost: ' ' }).ok).toBe(false); + expect(coerceSettingsPatch({ webuiHost: 123 }).ok).toBe(false); + }); + + it('rejects a non-boolean tlsEnabled and non-string trustProxy', () => { + expect(coerceSettingsPatch({ tlsEnabled: 'yes' }).ok).toBe(false); + expect(coerceSettingsPatch({ trustProxy: 1 }).ok).toBe(false); + }); + + it('accepts an empty-string trustProxy (trust nobody)', () => { + expect(coerceSettingsPatch({ trustProxy: '' })).toEqual({ ok: true, patch: { trustProxy: '' } }); + }); +}); From 82d5f782a3cebc40e64fa073dd61b01b1dd90df9 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 14:39:35 +0800 Subject: [PATCH 15/33] feat(webui): system settings panel (port/host/TLS/trust-proxy) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New Settings → 服务 tab (SystemPanel) over the /api/system/settings + TLS cert API: edit port / bind host / trust-proxy, paste cert+key PEM to enable HTTPS, delete cert. Flags env-overridden fields ('被环境变量覆盖') and shows a restart-to-apply banner (no self-restart). Typed systemSettings API client domain. View layer — verified by tsc + vite build (webui has no component-test infra). --- .../src/components/pages/settings-page.tsx | 5 +- .../src/components/settings/system-panel.tsx | 205 ++++++++++++++++++ packages/webui/src/lib/api/client.ts | 18 +- packages/webui/src/lib/api/types.ts | 12 + packages/webui/src/router/index.tsx | 2 +- packages/webui/src/types.ts | 17 ++ 6 files changed, 256 insertions(+), 3 deletions(-) create mode 100644 packages/webui/src/components/settings/system-panel.tsx diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index 2ee74e48..79ea4c72 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -2,7 +2,7 @@ import { createContext, useContext, useId, useRef, useState, type ReactNode } fr import { motion } from 'motion/react'; import { Accessibility, AlertTriangle, Bell, Bug, Check, Clock, Code2, Download, ExternalLink, Github, Image as ImageIcon, - Info, KeyRound, Loader2, Monitor, Moon, Palette, PanelTop, Plus, RefreshCw, RotateCcw, ShieldCheck, + Info, KeyRound, Loader2, Monitor, Moon, Palette, PanelTop, Plus, RefreshCw, RotateCcw, Server, ShieldCheck, Sparkles, Star, Sun, Tag, Upload, Trash2, } from 'lucide-react'; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; @@ -41,12 +41,14 @@ import { useAppState } from '@/contexts/AppStateContext'; import { cn } from '@/lib/utils'; import { settingsRoute, type SettingsTab } from '@/router'; import { NotificationsPanel } from '@/components/settings/notifications-panel'; +import { SystemPanel } from '@/components/settings/system-panel'; const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [ { key: 'appearance', label: '外观', icon: Palette }, { key: 'data', label: '数据与格式', icon: RefreshCw }, { key: 'advanced', label: '高级', icon: Code2 }, { key: 'account', label: '账号安全', icon: ShieldCheck }, + { key: 'system', label: '服务', icon: Server }, { key: 'notifications', label: '通知', icon: Bell }, { key: 'about', label: '关于', icon: Info }, ]; @@ -78,6 +80,7 @@ export function SettingsPage() { {tab === 'data' && } {tab === 'advanced' && } {tab === 'account' && } + {tab === 'system' && } {tab === 'notifications' && } {tab === 'about' && } diff --git a/packages/webui/src/components/settings/system-panel.tsx b/packages/webui/src/components/settings/system-panel.tsx new file mode 100644 index 00000000..399fd484 --- /dev/null +++ b/packages/webui/src/components/settings/system-panel.tsx @@ -0,0 +1,205 @@ +// Settings → 服务 tab (Wave A1). Edits the WebUI listener's own config +// (port / bind host / trust-proxy / HTTPS). Listener-level changes are +// persisted but apply only after a restart — there is no supervisor to +// self-restart, so we never offer a "restart now" button, only a banner. +// Fields currently pinned by SNOWLUMA_* env vars are flagged (edits to them +// won't take effect until the env var is removed). +import { useEffect, useState } from 'react'; +import { motion } from 'motion/react'; +import { AlertTriangle, Loader2, Lock, Save, ShieldCheck, Trash2 } from 'lucide-react'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Badge } from '@/components/ui/badge'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { ToggleSwitch } from '@/components/ui/toggle-switch'; +import { useApi } from '@/lib/api'; +import { cn } from '@/lib/utils'; +import type { SystemSettingsResponse } from '@/types'; + +const TEXTAREA_CLS = + 'w-full min-h-28 rounded-lg border border-border bg-background px-3 py-2 font-mono text-xs ' + + 'outline-none focus-visible:ring-2 focus-visible:ring-ring'; + +export function SystemPanel() { + const api = useApi(); + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); + const [saving, setSaving] = useState(false); + const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null); + + // editable form state + const [port, setPort] = useState(''); + const [host, setHost] = useState('0.0.0.0'); + const [trustProxy, setTrustProxy] = useState(''); + const [tlsEnabled, setTlsEnabled] = useState(false); + const [certPem, setCertPem] = useState(''); + const [keyPem, setKeyPem] = useState(''); + + const load = async () => { + try { + const res = await api.systemSettings.get(); + setData(res); + setPort(String(res.settings.webuiPort)); + setHost(res.settings.webuiHost); + setTrustProxy(res.settings.trustProxy); + setTlsEnabled(res.settings.tlsEnabled); + } catch { + setMsg({ kind: 'err', text: '加载系统设置失败' }); + } finally { + setLoading(false); + } + }; + + useEffect(() => { void load(); }, []); // eslint-disable-line react-hooks/exhaustive-deps + + const overridden = (field: string) => data?.envOverrides.includes(field) ?? false; + const flash = (kind: 'ok' | 'err', text: string) => { + setMsg({ kind, text }); + window.setTimeout(() => setMsg(null), 4000); + }; + + const saveSettings = async () => { + const portNum = Number(port); + if (!Number.isInteger(portNum) || portNum <= 0 || portNum > 65535) { + flash('err', '端口必须是 1–65535 的整数'); + return; + } + setSaving(true); + try { + await api.systemSettings.save({ webuiPort: portNum, webuiHost: host.trim(), trustProxy, tlsEnabled }); + await load(); + flash('ok', '已保存,重启 SnowLuma 后生效'); + } catch (e) { + flash('err', e instanceof Error ? e.message : '保存失败'); + } finally { + setSaving(false); + } + }; + + const uploadCert = async () => { + if (!certPem.trim() || !keyPem.trim()) { flash('err', '请同时填入证书与私钥'); return; } + setSaving(true); + try { + await api.systemSettings.uploadCert(certPem, keyPem); + setCertPem(''); setKeyPem(''); + await load(); + flash('ok', '证书已保存,重启后生效'); + } catch (e) { + flash('err', e instanceof Error ? e.message : '证书保存失败'); + } finally { + setSaving(false); + } + }; + + const deleteCert = async () => { + setSaving(true); + try { + await api.systemSettings.deleteCert(); + await load(); + flash('ok', '证书已删除'); + } catch (e) { + flash('err', e instanceof Error ? e.message : '删除失败'); + } finally { + setSaving(false); + } + }; + + if (loading) { + return
加载中…
; + } + + const EnvBadge = ({ field }: { field: string }) => + overridden(field) + ? 被环境变量覆盖 + : null; + + return ( + + {/* restart-to-apply notice */} +
+ + 监听相关设置(端口 / 绑定地址 / HTTPS)属服务级配置,保存后需重启 SnowLuma 才生效;本机无自动重启。 +
+ + {msg && ( +
{msg.text}
+ )} + + + + 服务监听 + WebUI 当前监听端口:{data?.listeningPort} + + +
+ + setPort(e.target.value)} inputMode="numeric" placeholder="5099" /> +
+
+ + +
+
+ + setTrustProxy(e.target.value)} placeholder="留空=只信任 socket 对端;1=信任反代头" /> +

仅在 WebUI 位于受信任反向代理之后时才设为 1 / loopback / IP 列表。

+
+
+ +
+
+
+ + + + + HTTPS / TLS + + + {data?.hasCert ? '已安装证书。' : '尚未安装证书。'} 启用 TLS 需先安装有效的证书与私钥(PEM)。 + + + +
+ + +
+ +
+ +