diff --git a/package.json b/package.json index 239b686b..36b271a8 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "snowluma-monorepo", - "version": "1.14.7", + "version": "1.14.8", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index eef3e57a..47bb61b5 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/bridge", - "version": "1.14.7", + "version": "1.14.8", "private": true, "type": "module", "description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).", diff --git a/packages/bridge/tests/injector.test.ts b/packages/bridge/tests/injector.test.ts new file mode 100644 index 00000000..8ae58215 --- /dev/null +++ b/packages/bridge/tests/injector.test.ts @@ -0,0 +1,402 @@ +import path from 'path'; +import { fileURLToPath } from 'url'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const { existsSyncMock, listPidsMock } = vi.hoisted(() => ({ + existsSyncMock: vi.fn<(target: string) => boolean>(() => false), + listPidsMock: vi.fn(() => new Set()), +})); + +vi.mock('fs', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + existsSync: (target: Parameters[0]) => + existsSyncMock(String(target)), + }; +}); + +vi.mock('../src/qq-hook-client', () => ({ + listSnowlumaPipePidsSync: listPidsMock, +})); + +const INJECTOR_DIR = path.dirname(fileURLToPath(new URL('../src/injector.ts', import.meta.url))); +const ORIGINAL_PLATFORM = process.platform; +const ORIGINAL_ARCH = process.arch; + +const HANDLE = { + base: 0x7fff0000n, + entry: 0x7fff1234n, + exceptionTable: 0x7fff5678n, + size: 8192, +}; + +function setPlatform(platform: NodeJS.Platform, arch: string): void { + Object.defineProperty(process, 'platform', { value: platform, configurable: true }); + Object.defineProperty(process, 'arch', { value: arch, configurable: true }); +} + +function restorePlatform(): void { + Object.defineProperty(process, 'platform', { value: ORIGINAL_PLATFORM, configurable: true }); + Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true }); +} + +function nativeSearchDirs(cwd = process.cwd()): string[] { + return [ + path.resolve(INJECTOR_DIR, 'native'), + path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'), + path.resolve(cwd, 'dist', 'native'), + path.resolve(cwd, 'packages', 'runtime', 'native'), + ]; +} + +function nativeCandidate(fileName: string, dirIndex: number, cwd = process.cwd()): string { + return path.join(nativeSearchDirs(cwd)[dirIndex]!, fileName); +} + +function allowExisting(paths: readonly string[]): void { + const allowed = new Set(paths); + existsSyncMock.mockImplementation((target) => allowed.has(target)); +} + +function fakeAddon(overrides: { + getAllMainProcess?: number[]; + loadModuleManual?: (pid: number, dylibPath: string) => unknown; + unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void; +} = {}) { + return { + getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []), + loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)), + unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)), + }; +} + +function installDlopen(addon: object) { + return vi.spyOn(process, 'dlopen').mockImplementation((mod) => { + (mod as { exports: object }).exports = addon; + }); +} + +async function loadInjector() { + return import('../src/injector'); +} + +beforeEach(() => { + existsSyncMock.mockReset(); + existsSyncMock.mockReturnValue(false); + listPidsMock.mockReset(); + listPidsMock.mockReturnValue(new Set()); + vi.resetModules(); +}); + +afterEach(() => { + restorePlatform(); + vi.restoreAllMocks(); +}); + +describe('resolveHookNativePath', () => { + it('returns null after probing every search directory', async () => { + setPlatform('linux', 'x64'); + const probed: string[] = []; + existsSyncMock.mockImplementation((target) => { + probed.push(target); + return false; + }); + + const { resolveHookNativePath } = await loadInjector(); + expect(resolveHookNativePath('node')).toBeNull(); + expect(probed).toEqual([ + nativeCandidate('snowluma-linux-x64.node', 0), + nativeCandidate('snowluma-linux-x64.node', 1), + nativeCandidate('snowluma-linux-x64.node', 2), + nativeCandidate('snowluma-linux-x64.node', 3), + ]); + }); + + it('returns the first existing candidate and stops scanning', async () => { + setPlatform('linux', 'x64'); + const winner = nativeCandidate('snowluma-linux-x64.node', 0); + const later = nativeCandidate('snowluma-linux-x64.node', 1); + const probed: string[] = []; + existsSyncMock.mockImplementation((target) => { + probed.push(target); + return target === winner || target === later; + }); + + const { resolveHookNativePath } = await loadInjector(); + expect(resolveHookNativePath('node')).toBe(winner); + expect(probed).toEqual([winner]); + }); + + it('skips missing earlier directories for the injectable .so', async () => { + setPlatform('linux', 'arm64'); + const winner = nativeCandidate('snowluma-linux-arm64.so', 2); + allowExisting([winner]); + + const { resolveHookNativePath } = await loadInjector(); + expect(resolveHookNativePath('so')).toBe(winner); + }); + + it('resolves snowluma-win32-x64.dll on win32 x64', async () => { + setPlatform('win32', 'x64'); + const winner = nativeCandidate('snowluma-win32-x64.dll', 3); + allowExisting([winner]); + + const { resolveHookNativePath } = await loadInjector(); + expect(resolveHookNativePath('dll')).toBe(winner); + }); + + it('uses the generic platform-arch name on win32 arm64', async () => { + setPlatform('win32', 'arm64'); + const winner = nativeCandidate('snowluma-win32-arm64.node', 1); + allowExisting([winner]); + + const { resolveHookNativePath } = await loadInjector(); + expect(resolveHookNativePath('node')).toBe(winner); + }); + + it('re-reads process.cwd() for the dist/native fallback', async () => { + setPlatform('darwin', 'arm64'); + vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd'); + const winner = path.join('/tmp/sl-injector-cwd', 'dist', 'native', 'snowluma-darwin-arm64.node'); + allowExisting([winner]); + + const { resolveHookNativePath } = await loadInjector(); + expect(resolveHookNativePath('node')).toBe(winner); + }); +}); + +describe('getNativeHookAddon / getNativeHookLoadError', () => { + it('starts with a null load error before any probe', async () => { + const { getNativeHookLoadError } = await loadInjector(); + expect(getNativeHookLoadError()).toBeNull(); + }); + + it('returns null and records a missing-binary error', async () => { + setPlatform('linux', 'x64'); + const dlopen = vi.spyOn(process, 'dlopen'); + const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); + + expect(getNativeHookAddon()).toBeNull(); + expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64'); + expect(dlopen).not.toHaveBeenCalled(); + }); + + it('dlopens the resolved .node once and caches the addon', async () => { + setPlatform('linux', 'x64'); + const nodePath = nativeCandidate('snowluma-linux-x64.node', 0); + allowExisting([nodePath]); + const addon = fakeAddon(); + const dlopen = installDlopen(addon); + + const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); + const first = getNativeHookAddon(); + const second = getNativeHookAddon(); + + expect(first).toBe(addon); + expect(second).toBe(addon); + expect(getNativeHookLoadError()).toBeNull(); + expect(dlopen).toHaveBeenCalledTimes(1); + expect(dlopen.mock.calls[0]![1]).toBe(nodePath); + }); + + it('stores Error.message when process.dlopen throws', async () => { + setPlatform('darwin', 'arm64'); + allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]); + vi.spyOn(process, 'dlopen').mockImplementation(() => { + throw new Error('not a valid Node addon'); + }); + + const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); + expect(getNativeHookAddon()).toBeNull(); + expect(getNativeHookLoadError()).toBe('not a valid Node addon'); + }); + + it('stringifies a non-Error dlopen failure', async () => { + setPlatform('linux', 'x64'); + allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]); + vi.spyOn(process, 'dlopen').mockImplementation(() => { + throw 42; + }); + + const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); + expect(getNativeHookAddon()).toBeNull(); + expect(getNativeHookLoadError()).toBe('42'); + }); + + it('retries after a failed load when a binary later appears', async () => { + setPlatform('linux', 'x64'); + const nodePath = nativeCandidate('snowluma-linux-x64.node', 1); + const addon = fakeAddon(); + installDlopen(addon); + + const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector(); + expect(getNativeHookAddon()).toBeNull(); + expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64'); + + allowExisting([nodePath]); + expect(getNativeHookAddon()).toBe(addon); + expect(getNativeHookLoadError()).toBeNull(); + }); +}); + +describe('listHookProcesses', () => { + it('on darwin maps sorted pipe pids without opening the native addon', async () => { + setPlatform('darwin', 'arm64'); + listPidsMock.mockReturnValue(new Set([42, 7, 15])); + allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]); + const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] })); + + const { listHookProcesses } = await loadInjector(); + expect(listHookProcesses()).toEqual([ + { pid: 7, name: 'qq', path: '' }, + { pid: 15, name: 'qq', path: '' }, + { pid: 42, name: 'qq', path: '' }, + ]); + expect(listPidsMock).toHaveBeenCalledTimes(1); + expect(dlopen).not.toHaveBeenCalled(); + }); + + it('on darwin returns an empty list when no control sockets exist', async () => { + setPlatform('darwin', 'arm64'); + listPidsMock.mockReturnValue(new Set()); + + const { listHookProcesses } = await loadInjector(); + expect(listHookProcesses()).toEqual([]); + }); + + it('on non-darwin returns [] when the addon cannot be loaded', async () => { + setPlatform('linux', 'x64'); + + const { listHookProcesses } = await loadInjector(); + expect(listHookProcesses()).toEqual([]); + }); + + it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => { + setPlatform('linux', 'x64'); + const nodePath = nativeCandidate('snowluma-linux-x64.node', 0); + allowExisting([nodePath]); + installDlopen(fakeAddon({ + getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2], + })); + + const { listHookProcesses } = await loadInjector(); + expect(listHookProcesses()).toEqual([ + { pid: 2, name: 'qq', path: '' }, + { pid: 8, name: 'qq', path: '' }, + ]); + }); + + it('on win32 names processes QQ.exe', async () => { + setPlatform('win32', 'x64'); + allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]); + installDlopen(fakeAddon({ getAllMainProcess: [9] })); + + const { listHookProcesses } = await loadInjector(); + expect(listHookProcesses()).toEqual([ + { pid: 9, name: 'QQ.exe', path: '' }, + ]); + }); +}); + +describe('injectHookProcess', () => { + it('throws the missing-addon load error', async () => { + setPlatform('linux', 'x64'); + const { injectHookProcess } = await loadInjector(); + await expect(injectHookProcess(4242)).rejects.toThrow('No hook native addon found for linux-x64'); + }); + + it('throws when the addon exists but the injectable is missing', async () => { + setPlatform('linux', 'x64'); + allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]); + installDlopen(fakeAddon()); + + const { injectHookProcess } = await loadInjector(); + await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64'); + }); + + it('awaits a thenable loadModuleManual handle', async () => { + setPlatform('linux', 'x64'); + const nodePath = nativeCandidate('snowluma-linux-x64.node', 0); + const soPath = nativeCandidate('snowluma-linux-x64.so', 0); + allowExisting([nodePath, soPath]); + const addon = fakeAddon({ + loadModuleManual: () => Promise.resolve(HANDLE), + }); + installDlopen(addon); + + const { injectHookProcess } = await loadInjector(); + await expect(injectHookProcess(4242)).resolves.toEqual({ + method: 'loadModuleManual', + handle: HANDLE, + }); + expect(addon.loadModuleManual).toHaveBeenCalledTimes(1); + expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath); + }); + + it('accepts a synchronous loadModuleManual return value', async () => { + setPlatform('darwin', 'arm64'); + const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2); + const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3); + allowExisting([nodePath, soPath]); + const addon = fakeAddon({ loadModuleManual: () => HANDLE }); + installDlopen(addon); + + const { injectHookProcess } = await loadInjector(); + await expect(injectHookProcess(77)).resolves.toEqual({ + method: 'loadModuleManual', + handle: HANDLE, + }); + expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath); + }); + + it('injects snowluma-win32-x64.dll on win32 x64', async () => { + setPlatform('win32', 'x64'); + const nodePath = nativeCandidate('snowluma-win32-x64.node', 0); + const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0); + allowExisting([nodePath, dllPath]); + const addon = fakeAddon({ loadModuleManual: () => HANDLE }); + installDlopen(addon); + + const { injectHookProcess } = await loadInjector(); + await expect(injectHookProcess(5150)).resolves.toEqual({ + method: 'loadModuleManual', + handle: HANDLE, + }); + expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath); + }); + + it('propagates a rejected loadModuleManual', async () => { + setPlatform('linux', 'x64'); + allowExisting([ + nativeCandidate('snowluma-linux-x64.node', 0), + nativeCandidate('snowluma-linux-x64.so', 0), + ]); + installDlopen(fakeAddon({ + loadModuleManual: () => Promise.reject(new Error('map failed')), + })); + + const { injectHookProcess } = await loadInjector(); + await expect(injectHookProcess(7)).rejects.toThrow('map failed'); + }); +}); + +describe('unloadHookProcess', () => { + it('throws the missing-addon load error', async () => { + setPlatform('linux', 'x64'); + const { unloadHookProcess } = await loadInjector(); + expect(() => unloadHookProcess(4242, HANDLE)).toThrow('No hook native addon found for linux-x64'); + }); + + it('forwards pid and handle to unloadModuleManual', async () => { + setPlatform('linux', 'x64'); + allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]); + const addon = fakeAddon(); + installDlopen(addon); + + const { unloadHookProcess } = await loadInjector(); + expect(unloadHookProcess(4242, HANDLE)).toBeUndefined(); + expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1); + expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE); + }); +}); diff --git a/packages/bridge/tests/qq-port-probe-more.test.ts b/packages/bridge/tests/qq-port-probe-more.test.ts new file mode 100644 index 00000000..c96a9cd2 --- /dev/null +++ b/packages/bridge/tests/qq-port-probe-more.test.ts @@ -0,0 +1,695 @@ +import { EventEmitter } from 'events'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { getLogLevel, setLogLevel, subscribeLogs } from '@snowluma/common/logger'; + +const execMock = vi.hoisted(() => vi.fn()); +const httpGetMock = vi.hoisted(() => vi.fn()); +const httpsGetMock = vi.hoisted(() => vi.fn()); + +vi.mock('child_process', () => ({ exec: execMock })); +vi.mock('http', () => ({ + default: { get: httpGetMock }, + get: httpGetMock, +})); +vi.mock('https', () => ({ + default: { get: httpsGetMock }, + get: httpsGetMock, +})); + +import { probeQqLoginInfo } from '../src/qq-port-probe'; + +const originalPlatform = process.platform; +const EXEC_OPTIONS = { timeout: 1500, killSignal: 'SIGKILL' }; +const PTLOGIN_HEADERS = { + Host: 'localhost.ptlogin2.qq.com', + Referer: 'https://xui.ptlogin2.qq.com/', + Cookie: 'pt_local_token=0', +}; + +type ExecCallback = (error: Error | null, result?: { stdout: string; stderr: string }) => void; +type RequestLike = EventEmitter & { destroy: ReturnType }; + +function setPlatform(platform: string): void { + Object.defineProperty(process, 'platform', { value: platform, configurable: true }); +} + +function mockExec(replies: Record): void { + execMock.mockImplementation((command: string, _options: unknown, callback: ExecCallback) => { + const reply = replies[command]; + if (reply === undefined) { + callback(new Error(`unexpected command ${command}`)); + return; + } + if (reply instanceof Error) { + callback(reply); + return; + } + callback(null, { stdout: reply, stderr: '' }); + }); +} + +function execCommands(): string[] { + return execMock.mock.calls.map((call) => String(call[0])); +} + +function ssLine(port: number, pid: number, owner: 'comma' | 'paren' = 'comma'): string { + const tag = owner === 'comma' ? `pid=${pid},fd=9` : `pid=${pid}`; + return `LISTEN 0 128 127.0.0.1:${port} 0.0.0.0:* users:(("qq",${tag}))`; +} + +function netstatLine(localAddr: string, pid: number): string { + return ` TCP ${localAddr} 0.0.0.0:0 LISTENING ${pid}`; +} + +function jsonp(accounts: unknown[]): string { + return `ptui_getuins_CB(${JSON.stringify(accounts)});`; +} + +function requestStub(): RequestLike { + const req = new EventEmitter() as RequestLike; + req.destroy = vi.fn(); + return req; +} + +function replyBody(body: string | ReadonlyArray) { + return (_url: string, _options: unknown, onResponse: (res: EventEmitter) => void): RequestLike => { + const req = requestStub(); + const res = new EventEmitter(); + onResponse(res); + const chunks = typeof body === 'string' ? [body] : body; + for (const chunk of chunks) res.emit('data', chunk); + res.emit('end'); + return req; + }; +} + +function replyError(error: Error) { + return (): RequestLike => { + const req = requestStub(); + queueMicrotask(() => req.emit('error', error)); + return req; + }; +} + +beforeEach(() => { + execMock.mockReset(); + httpGetMock.mockReset(); + httpsGetMock.mockReset(); + setPlatform('linux'); +}); + +afterEach(() => { + setPlatform(originalPlatform); + vi.useRealTimers(); +}); + +describe('probeQqLoginInfo — unix listing', () => { + it('returns null when ss cannot list sockets', async () => { + mockExec({ 'ss -tlnp': new Error('ss: not found') }); + + await expect(probeQqLoginInfo(3310)).resolves.toBeNull(); + expect(execCommands()).toEqual(['ss -tlnp']); + expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(httpsGetMock).not.toHaveBeenCalled(); + }); + + it('reports a logged-out identity when the PID has no sockets and pgrep is below 6', async () => { + mockExec({ + 'ss -tlnp': 'State Recv-Q Send-Q Local Address:Port Peer Address:Port\n', + 'pgrep -c qq': '5\n', + }); + + await expect(probeQqLoginInfo(3311)).resolves.toEqual({ + port: 0, + uin: '', + identityKnown: false, + }); + expect(execCommands()).toEqual(['ss -tlnp', 'pgrep -c qq']); + expect(execMock.mock.calls[1]?.[1]).toEqual(EXEC_OPTIONS); + }); + + it('treats a pgrep count of 0 as logged out', async () => { + mockExec({ + 'ss -tlnp': '', + 'pgrep -c qq': '0\n', + }); + + await expect(probeQqLoginInfo(3312)).resolves.toEqual({ + port: 0, + uin: '', + identityKnown: false, + }); + }); + + it('treats a non-numeric pgrep count as 0 and therefore logged out', async () => { + mockExec({ + 'ss -tlnp': '', + 'pgrep -c qq': 'qq: no process found\n', + }); + + await expect(probeQqLoginInfo(3313)).resolves.toEqual({ + port: 0, + uin: '', + identityKnown: false, + }); + }); + + it('returns null when there are no sockets and pgrep is 6 or higher', async () => { + mockExec({ + 'ss -tlnp': '', + 'pgrep -c qq': '6\n', + }); + await expect(probeQqLoginInfo(3314)).resolves.toBeNull(); + + mockExec({ + 'ss -tlnp': '', + 'pgrep -c qq': '9\n', + }); + await expect(probeQqLoginInfo(3315)).resolves.toBeNull(); + }); + + it('does not treat a failed pgrep as logged out', async () => { + mockExec({ + 'ss -tlnp': '', + 'pgrep -c qq': new Error('pgrep: exit 1'), + }); + + await expect(probeQqLoginInfo(3316)).resolves.toBeNull(); + }); + + it('uses the first listening port as a logged-out hint when no Ptlogin port is present', async () => { + mockExec({ + 'ss -tlnp': [ + ssLine(9218, 4410), + ssLine(18000, 4410), + ].join('\n'), + 'pgrep -c qq': ' 4 \n', + }); + + await expect(probeQqLoginInfo(4410)).resolves.toEqual({ + port: 9218, + uin: '', + identityKnown: false, + }); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(httpsGetMock).not.toHaveBeenCalled(); + }); + + it('returns null for non-Ptlogin ports when the QQ process count is ambiguous', async () => { + mockExec({ + 'ss -tlnp': ssLine(9218, 4411), + 'pgrep -c qq': '7\n', + }); + + await expect(probeQqLoginInfo(4411)).resolves.toBeNull(); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(httpsGetMock).not.toHaveBeenCalled(); + }); + + it('collects unique ports from ss lines that name the PID with either pid=N, or pid=N)', async () => { + mockExec({ + 'ss -tlnp': [ + 'LISTEN 0 128 127.0.0.1:4301users:(("qq",pid=4412,fd=1))', + ssLine(4301, 4412, 'comma'), + ssLine(4301, 4412, 'comma'), + ssLine(4305, 4412, 'paren'), + ssLine(4305, 9999, 'comma'), + 'ESTAB 0 0 127.0.0.1:4307 127.0.0.1:443 users:(("qq",pid=4412,fd=4))', + ].join('\n'), + }); + httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '10001', nickname: 'Ada' }]))); + + await expect(probeQqLoginInfo(4412)).resolves.toEqual({ + port: 4301, + uin: '10001', + nickName: 'Ada', + identityKnown: true, + }); + expect(httpsGetMock).toHaveBeenCalledTimes(2); + expect(httpsGetMock.mock.calls[0]?.[0]).toBe( + 'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + ); + }); +}); + +describe('probeQqLoginInfo — Ptlogin identity', () => { + it('reads a single account from an odd Ptlogin port over https', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5501) }); + httpsGetMock.mockImplementation(replyBody(jsonp([{ + uin: 319427101, + account: 1, + nickname: 'Snow', + extra: 'ignored', + }]))); + + await expect(probeQqLoginInfo(5501)).resolves.toEqual({ + port: 4301, + uin: '319427101', + nickName: 'Snow', + identityKnown: true, + }); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(httpsGetMock).toHaveBeenCalledTimes(2); + expect(httpsGetMock.mock.calls[0]?.[1]).toEqual({ + headers: PTLOGIN_HEADERS, + timeout: 500, + rejectUnauthorized: false, + }); + }); + + it('reads a single account from an even Ptlogin port over http', async () => { + mockExec({ 'ss -tlnp': ssLine(4302, 5502) }); + httpGetMock.mockImplementation(replyBody(jsonp([{ + account: '2880036470', + }]))); + + await expect(probeQqLoginInfo(5502)).resolves.toEqual({ + port: 4302, + uin: '2880036470', + nickName: '', + identityKnown: true, + }); + expect(httpsGetMock).not.toHaveBeenCalled(); + expect(httpGetMock).toHaveBeenCalledTimes(2); + expect(httpGetMock.mock.calls[0]?.[0]).toBe( + 'http://127.0.0.1:4302/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + ); + expect(httpGetMock.mock.calls[0]?.[1]).toEqual({ + headers: PTLOGIN_HEADERS, + timeout: 500, + }); + }); + + it('probes every documented odd Ptlogin port over https', async () => { + for (const port of [4301, 4303, 4305, 4307, 4309]) { + execMock.mockReset(); + httpsGetMock.mockReset(); + httpGetMock.mockReset(); + mockExec({ 'ss -tlnp': ssLine(port, 5510) }); + httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '70001', nickname: 'Odd' }]))); + + await expect(probeQqLoginInfo(5510)).resolves.toEqual({ + port, + uin: '70001', + nickName: 'Odd', + identityKnown: true, + }); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(String(httpsGetMock.mock.calls[0]?.[0])).toBe( + `https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`, + ); + } + }); + + it('probes every documented even Ptlogin port over http when no odd port is listening', async () => { + for (const port of [4302, 4304, 4306, 4308, 4310]) { + execMock.mockReset(); + httpsGetMock.mockReset(); + httpGetMock.mockReset(); + mockExec({ 'ss -tlnp': ssLine(port, 5511) }); + httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '70002', nickname: 'Even' }]))); + + await expect(probeQqLoginInfo(5511)).resolves.toEqual({ + port, + uin: '70002', + nickName: 'Even', + identityKnown: true, + }); + expect(httpsGetMock).not.toHaveBeenCalled(); + expect(String(httpGetMock.mock.calls[0]?.[0])).toBe( + `http://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`, + ); + } + }); + + it('prefers odd Ptlogin ports and never falls through to even ones', async () => { + mockExec({ + 'ss -tlnp': [ssLine(4302, 5520), ssLine(4301, 5520)].join('\n'), + }); + httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED'))); + + await expect(probeQqLoginInfo(5520)).resolves.toBeNull(); + expect(httpsGetMock).toHaveBeenCalled(); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(execCommands()).toEqual(['ss -tlnp']); + }); + + it('tries the next odd Ptlogin port after the first one fails', async () => { + mockExec({ + 'ss -tlnp': [ssLine(4301, 5521), ssLine(4305, 5521)].join('\n'), + }); + httpsGetMock + .mockImplementationOnce(replyBody('nope')) + .mockImplementationOnce(replyBody('nope')) + .mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }]))) + .mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }]))); + + await expect(probeQqLoginInfo(5521)).resolves.toEqual({ + port: 4305, + uin: '188888', + nickName: 'Next', + identityKnown: true, + }); + expect(httpsGetMock.mock.calls.map((call) => call[0])).toEqual([ + 'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + 'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + 'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + 'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + ]); + }); + + it('stops after the first Ptlogin port that yields a single account', async () => { + mockExec({ + 'ss -tlnp': [ssLine(4303, 5522), ssLine(4309, 5522)].join('\n'), + }); + httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '42', nickname: 'First' }]))); + + await expect(probeQqLoginInfo(5522)).resolves.toEqual({ + port: 4303, + uin: '42', + nickName: 'First', + identityKnown: true, + }); + expect(httpsGetMock).toHaveBeenCalledTimes(2); + }); + + it('uses account when uin is missing or empty, including a numeric 0 uin', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5530) }); + httpsGetMock + .mockImplementationOnce(replyBody(jsonp([{ uin: 0, account: 314159, nickname: 'Zero' }]))) + .mockImplementationOnce(replyBody(jsonp([{ uin: '', account: '314159', nickname: 'Zero' }]))); + + await expect(probeQqLoginInfo(5530)).resolves.toEqual({ + port: 4301, + uin: '314159', + nickName: 'Zero', + identityKnown: true, + }); + }); + + it('returns an empty uin when the single account has neither uin nor account', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5531) }); + httpsGetMock.mockImplementation(replyBody('[{"nickname":"Anon"}]')); + + await expect(probeQqLoginInfo(5531)).resolves.toEqual({ + port: 4301, + uin: '', + nickName: 'Anon', + identityKnown: true, + }); + }); + + it('keeps the shorter of the two pt_get_uins snapshots', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5540) }); + httpsGetMock + .mockImplementationOnce(replyBody(jsonp([ + { uin: '11', nickname: 'A' }, + { uin: '22', nickname: 'B' }, + ]))) + .mockImplementationOnce(replyBody(jsonp([{ uin: '33', nickname: 'Cora' }]))); + + await expect(probeQqLoginInfo(5540)).resolves.toEqual({ + port: 4301, + uin: '33', + nickName: 'Cora', + identityKnown: true, + }); + }); + + it('keeps the first snapshot when both pt_get_uins calls have one account', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5541) }); + httpsGetMock + .mockImplementationOnce(replyBody(jsonp([{ uin: '100', nickname: 'Left' }]))) + .mockImplementationOnce(replyBody(jsonp([{ uin: '200', nickname: 'Right' }]))); + + await expect(probeQqLoginInfo(5541)).resolves.toEqual({ + port: 4301, + uin: '100', + nickName: 'Left', + identityKnown: true, + }); + }); + + it('accepts a single account from the second fetch when the first fetch is unusable', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5542) }); + httpsGetMock + .mockImplementationOnce(replyError(new Error('ECONNRESET'))) + .mockImplementationOnce(replyBody(jsonp([{ uin: '9090', nickname: 'Retry' }]))); + + await expect(probeQqLoginInfo(5542)).resolves.toEqual({ + port: 4301, + uin: '9090', + nickName: 'Retry', + identityKnown: true, + }); + }); + + it('returns null for an empty pt_get_uins array and does not consult pgrep', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5550) }); + httpsGetMock.mockImplementation(replyBody('ptui_getuins_CB([]);')); + + await expect(probeQqLoginInfo(5550)).resolves.toBeNull(); + expect(execCommands()).toEqual(['ss -tlnp']); + }); + + it('returns null when both snapshots have more than one account', async () => { + mockExec({ 'ss -tlnp': ssLine(4304, 5551) }); + httpGetMock.mockImplementation(replyBody(jsonp([ + { uin: '1' }, + { uin: '2' }, + ]))); + + await expect(probeQqLoginInfo(5551)).resolves.toBeNull(); + }); + + it('returns null when both fetches fail to parse a pt_get_uins body', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5552) }); + httpsGetMock.mockImplementation(replyBody('not-jsonp')); + + await expect(probeQqLoginInfo(5552)).resolves.toBeNull(); + }); + + it('returns null when both fetches error', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5553) }); + httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED'))); + + await expect(probeQqLoginInfo(5553)).resolves.toBeNull(); + }); + + it('destroys the request and returns null when both fetches time out', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5554) }); + const seen: RequestLike[] = []; + httpsGetMock.mockImplementation(() => { + const req = requestStub(); + seen.push(req); + queueMicrotask(() => req.emit('timeout')); + return req; + }); + + await expect(probeQqLoginInfo(5554)).resolves.toBeNull(); + expect(seen).toHaveLength(2); + expect(seen[0]?.destroy).toHaveBeenCalledTimes(1); + expect(seen[1]?.destroy).toHaveBeenCalledTimes(1); + }); + + it('joins chunked pt_get_uins bodies including Buffer pieces', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5560) }); + httpsGetMock.mockImplementation(replyBody([ + 'ptui_getuins_CB([', + Buffer.from('{"uin":"10001","nickname":"Ada"}'), + ']);', + ])); + + await expect(probeQqLoginInfo(5560)).resolves.toEqual({ + port: 4301, + uin: '10001', + nickName: 'Ada', + identityKnown: true, + }); + }); + + it('treats a nickname that closes the JSONP array early as unusable', async () => { + mockExec({ 'ss -tlnp': ssLine(4301, 5561) }); + httpsGetMock.mockImplementation(replyBody('ptui_getuins_CB([{"nickname":"a]b","uin":"1"}]);')); + + await expect(probeQqLoginInfo(5561)).resolves.toBeNull(); + }); +}); + +describe('probeQqLoginInfo — win32 listing', () => { + beforeEach(() => { + setPlatform('win32'); + }); + + it('returns null when netstat cannot list sockets', async () => { + mockExec({ 'netstat -ano': new Error('netstat: access denied') }); + + await expect(probeQqLoginInfo(6610)).resolves.toBeNull(); + expect(execCommands()).toEqual(['netstat -ano']); + expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS); + }); + + it('counts QQ.exe rows from tasklist when netstat lists no sockets for the PID', async () => { + mockExec({ + 'netstat -ano': [ + 'Active Connections', + '', + ' Proto Local Address Foreign Address State PID', + netstatLine('127.0.0.1:4301', 1), + ].join('\n'), + 'tasklist /fi "imagename eq QQ.exe" /nh': [ + 'QQ.exe 100 Console 1 10,000 K', + 'QQ.exe 101 Console 1 11,000 K', + 'explorer.exe 200 Console 1 9,000 K', + ].join('\n'), + }); + + await expect(probeQqLoginInfo(6611)).resolves.toEqual({ + port: 0, + uin: '', + identityKnown: false, + }); + expect(execCommands()).toEqual([ + 'netstat -ano', + 'tasklist /fi "imagename eq QQ.exe" /nh', + ]); + }); + + it('returns null when tasklist reports 6 or more QQ.exe rows and the PID has no sockets', async () => { + mockExec({ + 'netstat -ano': '', + 'tasklist /fi "imagename eq QQ.exe" /nh': [ + 'QQ.exe 1', + 'QQ.exe 2', + 'QQ.exe 3', + 'qq.exe 4', + 'QQ.EXE 5', + 'QQ.exe 6', + ].join('\n'), + }); + + await expect(probeQqLoginInfo(6612)).resolves.toBeNull(); + }); + + it('does not treat a failed tasklist as logged out', async () => { + mockExec({ + 'netstat -ano': '', + 'tasklist /fi "imagename eq QQ.exe" /nh': new Error('tasklist: exit 1'), + }); + + await expect(probeQqLoginInfo(6613)).resolves.toBeNull(); + }); + + it('parses netstat rows for the owning PID and skips short or portless lines', async () => { + mockExec({ + 'netstat -ano': [ + 'Active Connections', + ' TCP 127.0.0.1:4301 LISTENING', + ' TCP 127.0.0.1 0.0.0.0:0 LISTENING 6620', + netstatLine('10.0.0.8:18000', 1), + netstatLine('127.0.0.1:4303', 6620), + netstatLine('[::1]:4303', 6620), + netstatLine('127.0.0.1:9218', 6620), + ].join('\n'), + }); + httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '20002', nickname: 'Win' }]))); + + await expect(probeQqLoginInfo(6620)).resolves.toEqual({ + port: 4303, + uin: '20002', + nickName: 'Win', + identityKnown: true, + }); + expect(httpsGetMock).toHaveBeenCalledTimes(2); + expect(httpsGetMock.mock.calls[0]?.[0]).toBe( + 'https://127.0.0.1:4303/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0', + ); + }); + + it('uses the first netstat port as a logged-out hint when no Ptlogin port is present', async () => { + mockExec({ + 'netstat -ano': [ + netstatLine('127.0.0.1:18000', 6630), + netstatLine('127.0.0.1:18001', 6630), + ].join('\n'), + 'tasklist /fi "imagename eq QQ.exe" /nh': 'QQ.exe 100\n', + }); + + await expect(probeQqLoginInfo(6630)).resolves.toEqual({ + port: 18000, + uin: '', + identityKnown: false, + }); + expect(httpGetMock).not.toHaveBeenCalled(); + expect(httpsGetMock).not.toHaveBeenCalled(); + }); +}); + +describe('probeQqLoginInfo — overall deadline', () => { + it('returns null and warns after 5000ms if listing never finishes', async () => { + vi.useFakeTimers(); + execMock.mockImplementation(() => undefined); + const previousLevel = getLogLevel(); + setLogLevel('info'); + const warnings: string[] = []; + const unsubscribe = subscribeLogs((entry) => { + if (entry.scope === 'LoginProbe' && entry.level === 'warn') { + warnings.push(entry.message); + } + }); + + try { + const pending = probeQqLoginInfo(9001); + let settled: unknown = 'pending'; + void pending.then((value) => { + settled = value; + }); + + await vi.advanceTimersByTimeAsync(4999); + expect(settled).toBe('pending'); + + await vi.advanceTimersByTimeAsync(1); + await expect(pending).resolves.toBeNull(); + expect(warnings).toEqual(['login check timed out: PID=9001']); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + }); + + it('does not warn when the probe finishes before the deadline', async () => { + mockExec({ + 'ss -tlnp': '', + 'pgrep -c qq': '2\n', + }); + const previousLevel = getLogLevel(); + setLogLevel('info'); + const warnings: string[] = []; + const unsubscribe = subscribeLogs((entry) => { + if (entry.scope === 'LoginProbe') warnings.push(entry.message); + }); + + try { + await expect(probeQqLoginInfo(9002)).resolves.toEqual({ + port: 0, + uin: '', + identityKnown: false, + }); + expect(warnings).toEqual([]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + }); + + it('abandons a hung Ptlogin fetch at the overall deadline', async () => { + vi.useFakeTimers(); + mockExec({ 'ss -tlnp': ssLine(4301, 9003) }); + httpsGetMock.mockImplementation(() => requestStub()); + + const pending = probeQqLoginInfo(9003); + await vi.advanceTimersByTimeAsync(5000); + await expect(pending).resolves.toBeNull(); + }); +}); diff --git a/packages/common/package.json b/packages/common/package.json index aca06e4e..0433fe8e 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/common", - "version": "1.14.7", + "version": "1.14.8", "private": true, "type": "module", "description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).", diff --git a/packages/common/tests/log-file-transport.test.ts b/packages/common/tests/log-file-transport.test.ts new file mode 100644 index 00000000..4ea2bd14 --- /dev/null +++ b/packages/common/tests/log-file-transport.test.ts @@ -0,0 +1,1049 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { + FileTransport, + _resetFileTransportForTesting, + clearManagedLogs, + configureFileTransport, + getFileTransport, + getLogStorageStatus, + type LogStoragePolicy, +} from '../src/log-file-transport'; + +const ENV_KEYS = [ + 'SNOWLUMA_LOG_FILE', + 'SNOWLUMA_LOG_DIR', + 'SNOWLUMA_LOG_MAX_MB', + 'SNOWLUMA_LOG_MAX_TOTAL_MB', + 'SNOWLUMA_LOG_RETAIN_DAYS', + 'SNOWLUMA_LOG_PER_UIN', +] as const; + +const savedEnv: Record = {}; +const opened: FileTransport[] = []; + +let tmpDir: string; + +function setEnv(env: Partial>): void { + for (const [key, value] of Object.entries(env)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } +} + +function createTransport(policy?: LogStoragePolicy): FileTransport { + const transport = new FileTransport(policy); + opened.push(transport); + return transport; +} + +function listLogFiles(dir: string): string[] { + return fs.readdirSync(dir).filter((name) => name.endsWith('.log')).sort(); +} + +async function waitForLogFiles(dir: string, expected: string[]): Promise { + await vi.waitFor(() => { + expect(listLogFiles(dir)).toEqual(expected); + }); +} + +function silenceStderr(): ReturnType { + return vi.spyOn(process.stderr, 'write').mockImplementation(() => true); +} + +beforeEach(() => { + for (const key of ENV_KEYS) savedEnv[key] = process.env[key]; + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-common-log-')); + setEnv({ + SNOWLUMA_LOG_DIR: tmpDir, + SNOWLUMA_LOG_FILE: '1', + SNOWLUMA_LOG_MAX_MB: '1', + SNOWLUMA_LOG_MAX_TOTAL_MB: '2', + SNOWLUMA_LOG_RETAIN_DAYS: '7', + SNOWLUMA_LOG_PER_UIN: '0', + }); +}); + +afterEach(async () => { + await Promise.all(opened.splice(0).map((transport) => transport.close())); + await _resetFileTransportForTesting(); + for (const key of ENV_KEYS) { + if (savedEnv[key] === undefined) delete process.env[key]; + else process.env[key] = savedEnv[key]; + } + vi.useRealTimers(); + vi.restoreAllMocks(); + fs.rmSync(tmpDir, { recursive: true, force: true }); +}); + +describe('FileTransport environment and policy', () => { + it('uses the constructor policy for total size, retention, and per-UIN instead of env', () => { + setEnv({ + SNOWLUMA_LOG_MAX_TOTAL_MB: '8', + SNOWLUMA_LOG_RETAIN_DAYS: '14', + SNOWLUMA_LOG_PER_UIN: '0', + SNOWLUMA_LOG_FILE: '0', + }); + + expect(createTransport({ + maxTotalMb: 3, + retainDays: 0, + perUinEnabled: true, + }).getStorageStatus()).toEqual({ + state: 'disabled', + directory: tmpDir, + totalBytes: 0, + maxTotalBytes: 3_145_728, + retainDays: 0, + perUinEnabled: true, + fileCount: 0, + activeFileCount: 0, + droppedLines: 0, + }); + }); + + it('falls back to defaults when optional log env vars are blank', () => { + setEnv({ + SNOWLUMA_LOG_FILE: '0', + SNOWLUMA_LOG_MAX_MB: ' ', + SNOWLUMA_LOG_MAX_TOTAL_MB: '', + SNOWLUMA_LOG_RETAIN_DAYS: ' ', + SNOWLUMA_LOG_PER_UIN: '', + }); + + expect(createTransport().getStorageStatus()).toMatchObject({ + state: 'disabled', + maxTotalBytes: 1_073_741_824, + retainDays: 7, + perUinEnabled: false, + }); + }); + + it('resolves an unset SNOWLUMA_LOG_DIR to the process-relative logs folder', () => { + setEnv({ SNOWLUMA_LOG_DIR: undefined, SNOWLUMA_LOG_FILE: '0' }); + + expect(createTransport().getStorageStatus().directory).toBe(path.resolve('logs')); + }); + + it('treats only the exact string 0 as a file-output disable switch', () => { + setEnv({ SNOWLUMA_LOG_FILE: 'false' }); + expect(createTransport().isDisabled).toBe(false); + + setEnv({ SNOWLUMA_LOG_FILE: '0' }); + expect(createTransport().isDisabled).toBe(true); + }); + + it.each([ + ['1', true], + ['TRUE', true], + [' yes ', true], + ['On', true], + ['0', false], + ['FALSE', false], + [' no ', false], + ['Off', false], + ] as const)('parses SNOWLUMA_LOG_PER_UIN=%j as %s', (value, expected) => { + setEnv({ SNOWLUMA_LOG_PER_UIN: value, SNOWLUMA_LOG_FILE: '0' }); + expect(createTransport().getStorageStatus().perUinEnabled).toBe(expected); + }); + + it.each([ + ['0', 'SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591'], + ['1.5', 'SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591'], + ['abc', 'SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591'], + ] as const)('rejects SNOWLUMA_LOG_MAX_MB=%j', (value, message) => { + setEnv({ SNOWLUMA_LOG_MAX_MB: value }); + expect(() => new FileTransport()).toThrow(new RangeError(message)); + }); + + it('rejects invalid total-size, retain-day, and per-UIN environment values', () => { + setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '0' }); + expect(() => new FileTransport()).toThrow( + new RangeError('SNOWLUMA_LOG_MAX_TOTAL_MB must be an integer in 1..8589934591'), + ); + + setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '2', SNOWLUMA_LOG_RETAIN_DAYS: '-1' }); + expect(() => new FileTransport()).toThrow( + new RangeError('SNOWLUMA_LOG_RETAIN_DAYS must be an integer in 0..104249991'), + ); + + setEnv({ SNOWLUMA_LOG_RETAIN_DAYS: '7', SNOWLUMA_LOG_PER_UIN: 'maybe' }); + expect(() => new FileTransport()).toThrow( + new TypeError('SNOWLUMA_LOG_PER_UIN must be a boolean'), + ); + }); + + it('still validates SNOWLUMA_LOG_MAX_MB when a storage policy is supplied', () => { + setEnv({ SNOWLUMA_LOG_MAX_MB: '0' }); + expect(() => new FileTransport({ + maxTotalMb: 2, + retainDays: 7, + perUinEnabled: false, + })).toThrow(new RangeError('SNOWLUMA_LOG_MAX_MB must be an integer in 1..8589934591')); + }); + + it('rejects constructor policies before touching the log directory', () => { + expect(() => new FileTransport({ + maxTotalMb: 0, + retainDays: 7, + perUinEnabled: false, + })).toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591')); + expect(() => new FileTransport({ + maxTotalMb: 2, + retainDays: -1, + perUinEnabled: false, + })).toThrow(new RangeError('retainDays must be an integer in 0..104249991')); + expect(() => new FileTransport({ + maxTotalMb: 2, + retainDays: 7, + perUinEnabled: 'yes' as unknown as boolean, + })).toThrow(new TypeError('perUinEnabled must be a boolean')); + expect(fs.readdirSync(tmpDir)).toEqual([]); + }); +}); + +describe('FileTransport write, rotation, and paths', () => { + it('creates today\'s shared file, appends a newline, and reports an exact healthy snapshot', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 15, 4, 5)); + const transport = createTransport(); + + expect(transport.isDisabled).toBe(false); + expect(transport.currentPath).toBeNull(); + expect(transport.perUinPath(12345)).toBeNull(); + + transport.write('hello'); + + const activePath = path.join(tmpDir, 'snowluma-2026-07-24.log'); + expect(transport.currentPath).toBe(activePath); + expect(transport.getStorageStatus()).toEqual({ + state: 'healthy', + directory: tmpDir, + totalBytes: 6, + maxTotalBytes: 2_097_152, + retainDays: 7, + perUinEnabled: false, + fileCount: 1, + activeFileCount: 1, + droppedLines: 0, + }); + + await transport.close(); + expect(transport.isDisabled).toBe(true); + expect(transport.currentPath).toBeNull(); + expect(transport.getStorageStatus()).toMatchObject({ + state: 'healthy', + fileCount: 1, + activeFileCount: 0, + }); + expect(fs.readFileSync(activePath, 'utf8')).toBe('hello\n'); + }); + + it('sanitizes control sequences and counts UTF-8 bytes including the trailing newline', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + const transport = createTransport(); + transport.write('\x1b[31m你好\x1b[0m'); + await transport.close(); + + const filePath = path.join(tmpDir, 'snowluma-2026-07-24.log'); + expect(fs.readFileSync(filePath, 'utf8')).toBe('你好\n'); + expect(fs.statSync(filePath).size).toBe(7); + }); + + it('does not write when file output is disabled', async () => { + setEnv({ SNOWLUMA_LOG_FILE: '0' }); + const transport = createTransport(); + transport.write('should not persist'); + await transport.close(); + + expect(transport.isDisabled).toBe(true); + expect(listLogFiles(tmpDir)).toEqual([]); + }); + + it('appends to the existing today file and tracks the on-disk size after a restart', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), '0123456789'); + + const first = createTransport(); + first.write('hello'); + expect(first.getStorageStatus().totalBytes).toBe(16); + await first.close(); + + const second = createTransport(); + second.write('z'); + await second.close(); + + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')) + .toBe('0123456789hello\nz\n'); + }); + + it('resumes the highest existing split index for the current day', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'base\n'); + fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'one\n'); + + const transport = createTransport(); + transport.write('two'); + await transport.close(); + + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe('base\n'); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'utf8')).toBe('one\ntwo\n'); + }); + + it('skips an already-present next split when rotating by size', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + // Leave the base file just under the 1 MiB cap so the first write opens + // split 0. ensureForToday resumes at the highest existing split, so + // planting `.1` before that open would append there instead of rotating. + fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), Buffer.alloc(1_048_570)); + + const transport = createTransport(); + transport.write('open'); + await waitForLogFiles(tmpDir, ['snowluma-2026-07-24.log']); + expect(transport.currentPath).toBe(path.join(tmpDir, 'snowluma-2026-07-24.log')); + + fs.writeFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'taken\n'); + transport.write('overflow'); + await transport.close(); + + expect(listLogFiles(tmpDir)).toEqual([ + 'snowluma-2026-07-24.1.log', + 'snowluma-2026-07-24.2.log', + 'snowluma-2026-07-24.log', + ]); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.2.log'), 'utf8')) + .toBe('overflow\n'); + }); + + it('lets a first line exceed the per-file cap and only rotates on the next write', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + const transport = createTransport(); + const oversized = 'a'.repeat(1_048_580); + transport.write(oversized); + await waitForLogFiles(tmpDir, ['snowluma-2026-07-24.log']); + + transport.write('b'); + await transport.close(); + + expect(listLogFiles(tmpDir)).toEqual([ + 'snowluma-2026-07-24.1.log', + 'snowluma-2026-07-24.log', + ]); + expect(fs.statSync(path.join(tmpDir, 'snowluma-2026-07-24.log')).size).toBe(1_048_581); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.1.log'), 'utf8')).toBe('b\n'); + }); + + it('opens a new dated file when the calendar day changes', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 4, 18, 23, 59, 0)); + const transport = createTransport(); + transport.write('day-one'); + vi.setSystemTime(new Date(2026, 4, 19, 0, 0, 1)); + transport.write('day-two'); + await transport.close(); + + expect(listLogFiles(tmpDir)).toEqual([ + 'snowluma-2026-05-18.log', + 'snowluma-2026-05-19.log', + ]); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-18.log'), 'utf8')).toBe('day-one\n'); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-19.log'), 'utf8')).toBe('day-two\n'); + }); +}); + +describe('FileTransport retention, listing, and quota', () => { + it('deletes expired managed files in the root and numeric account directories only', async () => { + fs.writeFileSync(path.join(tmpDir, 'keep.txt'), 'keep\n'); + fs.writeFileSync(path.join(tmpDir, 'snowluma-nope.log'), 'unmanaged\n'); + fs.mkdirSync(path.join(tmpDir, 'not-an-account')); + fs.writeFileSync( + path.join(tmpDir, 'not-an-account', 'snowluma-2020-01-01.log'), + 'ignored\n', + ); + fs.mkdirSync(path.join(tmpDir, '10001')); + fs.writeFileSync(path.join(tmpDir, 'snowluma-2020-01-01.log'), 'stale-root\n'); + fs.writeFileSync(path.join(tmpDir, '10001', 'snowluma-2020-01-01.2.log'), 'stale-account\n'); + + const transport = createTransport(); + await transport.close(); + + expect(fs.existsSync(path.join(tmpDir, 'snowluma-2020-01-01.log'))).toBe(false); + expect(fs.existsSync(path.join(tmpDir, '10001', 'snowluma-2020-01-01.2.log'))).toBe(false); + expect(fs.readFileSync(path.join(tmpDir, 'keep.txt'), 'utf8')).toBe('keep\n'); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-nope.log'), 'utf8')).toBe('unmanaged\n'); + expect(fs.readFileSync( + path.join(tmpDir, 'not-an-account', 'snowluma-2020-01-01.log'), + 'utf8', + )).toBe('ignored\n'); + }); + + it('keeps files inside the retention window and skips date cleanup when retainDays is 0', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + const recentPath = path.join(tmpDir, 'snowluma-2026-07-22.log'); + const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log'); + fs.writeFileSync(recentPath, 'recent\n'); + fs.writeFileSync(stalePath, 'stale\n'); + + const kept = createTransport(); + await kept.close(); + expect(fs.existsSync(recentPath)).toBe(true); + expect(fs.existsSync(stalePath)).toBe(false); + + fs.writeFileSync(stalePath, 'stale-again\n'); + setEnv({ SNOWLUMA_LOG_RETAIN_DAYS: '0' }); + const noDateCleanup = createTransport(); + await noDateCleanup.close(); + expect(fs.existsSync(stalePath)).toBe(true); + expect(noDateCleanup.getStorageStatus().retainDays).toBe(0); + }); + + it('runs retention again after the active writer closes', async () => { + const transport = createTransport(); + transport.write('keep the writer open'); + const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log'); + fs.writeFileSync(stalePath, 'stale\n'); + expect(fs.existsSync(stalePath)).toBe(true); + + await transport.close(); + expect(fs.existsSync(stalePath)).toBe(false); + }); + + it('never deletes the active file when a later retention policy makes its date stale', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date(2026, 0, 1, 12, 0, 0)); + const activePath = path.join(tmpDir, 'snowluma-2026-01-01.log'); + const transport = createTransport(); + transport.write('still-active'); + await vi.waitFor(() => { + expect(fs.existsSync(activePath)).toBe(true); + }); + + vi.setSystemTime(new Date(2026, 0, 3, 12, 0, 0)); + await transport.updatePolicy({ + maxTotalMb: 2, + retainDays: 1, + perUinEnabled: false, + }); + + expect(fs.existsSync(activePath)).toBe(true); + expect(transport.getStorageStatus().activeFileCount).toBe(1); + }); + + it('reclaims the oldest closed files first when applying a lower aggregate limit', async () => { + setEnv({ + SNOWLUMA_LOG_MAX_TOTAL_MB: '4', + SNOWLUMA_LOG_RETAIN_DAYS: '0', + }); + const older = path.join(tmpDir, 'snowluma-2026-07-24.log'); + const accountDir = path.join(tmpDir, '12345'); + const newer = path.join(accountDir, 'snowluma-2026-07-24.log'); + fs.mkdirSync(accountDir); + fs.writeFileSync(older, Buffer.alloc(700 * 1024)); + fs.writeFileSync(newer, Buffer.alloc(700 * 1024)); + fs.utimesSync(older, new Date('2026-07-24T01:00:00Z'), new Date('2026-07-24T01:00:00Z')); + fs.utimesSync(newer, new Date('2026-07-24T02:00:00Z'), new Date('2026-07-24T02:00:00Z')); + + const transport = createTransport(); + expect(await transport.updatePolicy({ + maxTotalMb: 1, + retainDays: 0, + perUinEnabled: false, + })).toMatchObject({ + state: 'healthy', + maxTotalBytes: 1_048_576, + totalBytes: 716_800, + fileCount: 1, + }); + expect(fs.existsSync(older)).toBe(false); + expect(fs.existsSync(newer)).toBe(true); + }); + + it('enters one degraded quota state and counts later lines as dropped', async () => { + setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '1' }); + const stderr = silenceStderr(); + const transport = createTransport(); + const kib = 'x'.repeat(1023); + for (let i = 0; i < 1024; i += 1) transport.write(kib); + for (let i = 0; i < 10; i += 1) transport.write('dropped'); + + expect(transport.getStorageStatus()).toMatchObject({ + state: 'degraded', + maxTotalBytes: 1_048_576, + droppedLines: 10, + }); + expect( + stderr.mock.calls + .map(([message]) => String(message)) + .filter((message) => message.includes('no closed log can be reclaimed')), + ).toHaveLength(1); + expect(stderr.mock.calls[0]![0]).toMatch(/^\[logger\.storage] /); + }); + + it('does not fan out a dropped shared line to a per-UIN writer', async () => { + setEnv({ + SNOWLUMA_LOG_MAX_TOTAL_MB: '1', + SNOWLUMA_LOG_PER_UIN: '1', + }); + silenceStderr(); + const transport = createTransport(); + const kib = 'x'.repeat(1023); + for (let i = 0; i < 1024; i += 1) transport.write(kib); + transport.write('overflow', 12345); + + expect(transport.perUinPath(12345)).toBeNull(); + expect(fs.existsSync(path.join(tmpDir, '12345'))).toBe(false); + expect(transport.getStorageStatus().droppedLines).toBe(1); + }); + + it('reports a warning when retention cannot unlink an expired closed file', async () => { + const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log'); + fs.writeFileSync(stalePath, 'stale\n'); + const realUnlink = fs.unlinkSync.bind(fs); + vi.spyOn(fs, 'unlinkSync').mockImplementation((filePath) => { + if (path.resolve(String(filePath)) === stalePath) { + throw new Error('permission denied'); + } + realUnlink(filePath); + }); + silenceStderr(); + + const transport = createTransport(); + expect(transport.getStorageStatus()).toMatchObject({ + state: 'warning', + lastError: `retention cleanup failed for ${stalePath}: permission denied`, + fileCount: 1, + }); + expect(fs.existsSync(stalePath)).toBe(true); + }); +}); + +describe('FileTransport per-UIN writers', () => { + it('duplicates a UIN-scoped line into logs// and leaves unscoped lines in the shared file only', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); + const transport = createTransport(); + transport.write('shared-only'); + transport.write('both', 12345); + await transport.close(); + + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')) + .toBe('shared-only\nboth\n'); + expect(fs.readFileSync(path.join(tmpDir, '12345', 'snowluma-2026-07-24.log'), 'utf8')) + .toBe('both\n'); + }); + + it('does not create an account directory when the account path is already a file', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); + fs.writeFileSync(path.join(tmpDir, '12345'), 'occupied'); + silenceStderr(); + const transport = createTransport(); + transport.write('shared-ok', 12345); + await transport.close(); + + expect(transport.perUinPath(12345)).toBeNull(); + expect(fs.statSync(path.join(tmpDir, '12345')).isFile()).toBe(true); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')).toBe('shared-ok\n'); + }); + + it('rolls per-UIN files on day change and stops creating them after the policy turns off', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 23, 59, 0)); + setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); + const transport = createTransport(); + transport.write('day-one', 99); + expect(transport.perUinPath(99)).toBe(path.join(tmpDir, '99', 'snowluma-2026-07-24.log')); + + const updating = transport.updatePolicy({ + maxTotalMb: 2, + retainDays: 7, + perUinEnabled: false, + }); + transport.write('during-disable', 99); + expect(transport.perUinPath(99)).toBeNull(); + await updating; + + vi.setSystemTime(new Date(2026, 6, 25, 0, 0, 1)); + transport.write('day-two', 99); + await transport.close(); + + expect(fs.existsSync(path.join(tmpDir, '99', 'snowluma-2026-07-25.log'))).toBe(false); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-25.log'), 'utf8')) + .toBe('day-two\n'); + expect(transport.getStorageStatus().perUinEnabled).toBe(false); + }); + + it('creates account writers only after a policy enables per-UIN output', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + const transport = createTransport(); + transport.write('before', 55); + expect(fs.existsSync(path.join(tmpDir, '55'))).toBe(false); + + await transport.updatePolicy({ + maxTotalMb: 2, + retainDays: 7, + perUinEnabled: true, + }); + transport.write('after', 55); + await transport.close(); + + expect(fs.readFileSync(path.join(tmpDir, '55', 'snowluma-2026-07-24.log'), 'utf8')) + .toBe('after\n'); + }); + + it('replaces a disabled per-UIN writer on the next line for that account', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); + const realCreate = fs.createWriteStream.bind(fs); + const accountStreams: fs.WriteStream[] = []; + vi.spyOn(fs, 'createWriteStream').mockImplementation((file, options) => { + const stream = realCreate(file, options); + if (String(file).startsWith(path.join(tmpDir, '77') + path.sep)) { + accountStreams.push(stream); + } + return stream; + }); + silenceStderr(); + + const transport = createTransport(); + transport.write('one', 77); + const accountFile = path.join(tmpDir, '77', 'snowluma-2026-07-24.log'); + await vi.waitFor(() => { + expect(fs.readFileSync(accountFile, 'utf8')).toBe('one\n'); + }); + accountStreams[0]!.emit('error', Object.assign(new Error('account eio'), { code: 'EIO' })); + vi.setSystemTime(Date.now() + 5_000); + transport.write('two', 77); + await transport.close(); + + expect(fs.readFileSync(accountFile, 'utf8')).toBe('one\ntwo\n'); + }); +}); + +describe('FileTransport initialization, recovery, and policy updates', () => { + it('surfaces a failed log-root mkdir as a disabled status with lastError', async () => { + const blocked = path.join(tmpDir, 'blocked-root'); + fs.writeFileSync(blocked, 'occupied'); + setEnv({ SNOWLUMA_LOG_DIR: blocked }); + const stderr = silenceStderr(); + + const transport = createTransport(); + expect(transport.isDisabled).toBe(true); + expect(transport.getStorageStatus()).toMatchObject({ + state: 'disabled', + directory: blocked, + totalBytes: 0, + fileCount: 0, + droppedLines: 0, + }); + expect(transport.getStorageStatus().lastError) + .toMatch(/^failed to initialize log storage /); + expect(String(stderr.mock.calls[0]![0])).toContain('[logger.storage]'); + await transport.close(); + }); + + it('treats a non-ENOENT readdir of an account directory as an initialization failure', async () => { + fs.mkdirSync(path.join(tmpDir, '12345')); + const realReaddir = fs.readdirSync.bind(fs); + vi.spyOn(fs, 'readdirSync').mockImplementation((dir, options) => { + if (path.resolve(String(dir)) === path.join(tmpDir, '12345')) { + throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' }); + } + return realReaddir(dir, options as Parameters[1]); + }); + silenceStderr(); + + const transport = createTransport(); + expect(transport.getStorageStatus()).toMatchObject({ + state: 'disabled', + lastError: expect.stringContaining('failed to read managed log directory'), + }); + }); + + it('retries a failed shared-writer open after the 5s backoff', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + silenceStderr(); + vi.spyOn(fs, 'createWriteStream').mockImplementationOnce(() => { + throw Object.assign(new Error('open failed'), { code: 'EIO' }); + }); + + const transport = createTransport(); + transport.write('dropped-while-opening'); + expect(transport.getStorageStatus().state).toBe('degraded'); + expect(listLogFiles(tmpDir)).toEqual([]); + + vi.advanceTimersByTime(4_999); + transport.write('still-waiting'); + expect(listLogFiles(tmpDir)).toEqual([]); + + vi.advanceTimersByTime(1); + transport.write('recovered'); + await transport.close(); + + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8')) + .toBe('recovered\n'); + }); + + it('does not persist lines during the quota retry window after a stream error', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + silenceStderr(); + const realCreate = fs.createWriteStream.bind(fs); + const streams: fs.WriteStream[] = []; + vi.spyOn(fs, 'createWriteStream').mockImplementation((file, options) => { + const stream = realCreate(file, options); + streams.push(stream); + return stream; + }); + + const transport = createTransport(); + transport.write('before-error'); + streams[0]!.emit('error', Object.assign(new Error('EIO write'), { code: 'EIO' })); + expect(transport.getStorageStatus().state).toBe('degraded'); + + transport.write('during-backoff'); + expect(transport.getStorageStatus().droppedLines).toBe(1); + + vi.advanceTimersByTime(5_000); + transport.write('after-backoff'); + await transport.close(); + + const body = fs.readFileSync(path.join(tmpDir, 'snowluma-2026-07-24.log'), 'utf8'); + expect(body).toContain('after-backoff\n'); + expect(body).not.toContain('during-backoff'); + }); + + it('recovers a previously unwritable root when updatePolicy forces a reopen', async () => { + const blocked = path.join(tmpDir, 'blocked-root'); + fs.writeFileSync(blocked, 'occupied'); + setEnv({ SNOWLUMA_LOG_DIR: blocked }); + silenceStderr(); + const transport = createTransport(); + expect(transport.getStorageStatus().state).toBe('disabled'); + + fs.unlinkSync(blocked); + fs.mkdirSync(blocked); + const status = await transport.updatePolicy({ + maxTotalMb: 2, + retainDays: 3, + perUinEnabled: false, + }); + + expect(status).toMatchObject({ + state: 'healthy', + directory: blocked, + maxTotalBytes: 2_097_152, + retainDays: 3, + }); + transport.write('via-policy'); + await transport.close(); + expect(listLogFiles(blocked)).toHaveLength(1); + }); + + it('updates stored policy fields even when applying the quota policy throws', async () => { + const transport = createTransport(); + vi.spyOn(fs, 'readdirSync').mockImplementation(() => { + throw Object.assign(new Error('EIO readdir'), { code: 'EIO' }); + }); + silenceStderr(); + + await expect(transport.updatePolicy({ + maxTotalMb: 4, + retainDays: 1, + perUinEnabled: true, + })).rejects.toThrow(/failed to read managed log directory/); + + expect(transport.getStorageStatus()).toMatchObject({ + state: 'degraded', + maxTotalBytes: 4_194_304, + retainDays: 1, + perUinEnabled: true, + lastError: expect.stringContaining('failed to apply log storage policy'), + }); + }); + + it('applies a policy to a disabled transport without creating files', async () => { + setEnv({ SNOWLUMA_LOG_FILE: '0' }); + const transport = createTransport(); + const status = await transport.updatePolicy({ + maxTotalMb: 5, + retainDays: 2, + perUinEnabled: true, + }); + + expect(status).toEqual({ + state: 'disabled', + directory: tmpDir, + totalBytes: 0, + maxTotalBytes: 5_242_880, + retainDays: 2, + perUinEnabled: true, + fileCount: 0, + activeFileCount: 0, + droppedLines: 0, + }); + expect(listLogFiles(tmpDir)).toEqual([]); + }); + + it('rejects an unsafe updatePolicy without changing the live limits', async () => { + const transport = createTransport(); + await expect(transport.updatePolicy({ + maxTotalMb: 9_007_199_254_740_991, + retainDays: 7, + perUinEnabled: false, + })).rejects.toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591')); + await expect(transport.updatePolicy({ + maxTotalMb: 2, + retainDays: 9_007_199_254_740_991, + perUinEnabled: false, + })).rejects.toThrow(new RangeError('retainDays must be an integer in 0..104249991')); + expect(transport.getStorageStatus()).toMatchObject({ + maxTotalBytes: 2_097_152, + retainDays: 7, + }); + }); +}); + +describe('FileTransport.clearManagedLogs', () => { + it('deletes closed shared and account files and reopens empty writers', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 6, 24, 12, 0, 0)); + setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); + const transport = createTransport(); + transport.write('shared and account', 12345); + + const result = await transport.clearManagedLogs(); + + expect(result.deletedFiles).toBe(2); + expect(result.freedBytes).toBeGreaterThan(0); + expect(result.failures).toEqual([]); + expect(fs.statSync(transport.currentPath!).size).toBe(0); + expect(fs.statSync(transport.perUinPath(12345)!).size).toBe(0); + expect(result.status.activeFileCount).toBe(2); + }); + + it('clears managed files while file output is disabled and leaves unrelated files', async () => { + fs.writeFileSync(path.join(tmpDir, 'snowluma-2020-01-01.log'), 'managed\n'); + fs.writeFileSync(path.join(tmpDir, 'keep.txt'), 'unrelated\n'); + setEnv({ SNOWLUMA_LOG_FILE: '0' }); + const transport = createTransport(); + + expect(await transport.clearManagedLogs()).toEqual({ + deletedFiles: 1, + freedBytes: 8, + failures: [], + status: { + state: 'disabled', + directory: tmpDir, + totalBytes: 0, + maxTotalBytes: 2_097_152, + retainDays: 7, + perUinEnabled: false, + fileCount: 0, + activeFileCount: 0, + droppedLines: 0, + }, + }); + expect(fs.existsSync(path.join(tmpDir, 'snowluma-2020-01-01.log'))).toBe(false); + expect(fs.readFileSync(path.join(tmpDir, 'keep.txt'), 'utf8')).toBe('unrelated\n'); + }); + + it('reports a disabled clear failure when the log root cannot be read', async () => { + const blocked = path.join(tmpDir, 'not-a-dir'); + fs.writeFileSync(blocked, 'occupied'); + setEnv({ SNOWLUMA_LOG_DIR: blocked, SNOWLUMA_LOG_FILE: '0' }); + silenceStderr(); + const transport = createTransport(); + + const result = await transport.clearManagedLogs(); + expect(result.deletedFiles).toBe(0); + expect(result.freedBytes).toBe(0); + expect(result.failures).toEqual([{ + file: '.', + message: expect.stringContaining(`failed to clear disabled log storage ${blocked}`), + }]); + expect(result.status).toMatchObject({ + state: 'disabled', + directory: blocked, + lastError: result.failures[0]!.message, + }); + }); + + it('can clear and reopen writers before the failed-open retry delay expires', async () => { + silenceStderr(); + vi.spyOn(fs, 'createWriteStream').mockImplementationOnce(() => { + throw Object.assign(new Error('open failed'), { code: 'EIO' }); + }); + const transport = createTransport(); + transport.write('dropped-while-opening'); + fs.writeFileSync(path.join(tmpDir, 'snowluma-2020-01-01.log'), 'stale\n'); + + const result = await transport.clearManagedLogs(); + + expect(result.failures).toEqual([]); + expect(fs.existsSync(path.join(tmpDir, 'snowluma-2020-01-01.log'))).toBe(false); + expect(transport.currentPath).not.toBeNull(); + }); + + it('records a shared reopen failure after a successful cleanup', async () => { + const transport = createTransport(); + transport.write('to-clear'); + vi.spyOn(fs, 'createWriteStream').mockImplementation(() => { + throw Object.assign(new Error('reopen failed'), { code: 'EIO' }); + }); + silenceStderr(); + + const result = await transport.clearManagedLogs(); + expect(result.deletedFiles).toBe(1); + expect(result.failures).toEqual([{ + file: '.', + message: expect.stringMatching(/^failed to initialize log storage /), + }]); + expect(transport.currentPath).toBeNull(); + }); + + it('records an account reopen failure without losing the shared writer', async () => { + setEnv({ SNOWLUMA_LOG_PER_UIN: '1' }); + const transport = createTransport(); + transport.write('both', 12345); + const realCreate = fs.createWriteStream.bind(fs); + const accountPrefix = path.join(tmpDir, '12345') + path.sep; + vi.spyOn(fs, 'createWriteStream').mockImplementation((file, options) => { + if (String(file).startsWith(accountPrefix)) { + throw new Error('account reopen failed'); + } + return realCreate(file, options); + }); + silenceStderr(); + + const result = await transport.clearManagedLogs(); + expect(result.failures).toEqual([{ + file: '12345', + message: `failed to reopen account log writer: failed to prepare log writer in ${path.join(tmpDir, '12345')}`, + }]); + expect(transport.currentPath).not.toBeNull(); + expect(transport.perUinPath(12345)).toBeNull(); + }); + + it('returns the initialization error when a disabled root still cannot build a quota', async () => { + const blocked = path.join(tmpDir, 'blocked-root'); + fs.writeFileSync(blocked, 'occupied'); + setEnv({ SNOWLUMA_LOG_DIR: blocked }); + silenceStderr(); + const transport = createTransport(); + + const result = await transport.clearManagedLogs(); + expect(result).toMatchObject({ + deletedFiles: 0, + freedBytes: 0, + failures: [{ + file: '.', + message: expect.stringMatching(/^failed to initialize log storage /), + }], + status: { state: 'disabled', directory: blocked }, + }); + }); +}); + +describe('file-transport singleton', () => { + it('reuses one FileTransport until _resetFileTransportForTesting closes it', async () => { + const first = getFileTransport(); + expect(getFileTransport()).toBe(first); + first.write('singleton-line'); + + await _resetFileTransportForTesting(); + const second = getFileTransport(); + expect(second).not.toBe(first); + expect(first.isDisabled).toBe(true); + expect(second.isDisabled).toBe(false); + }); + + it('configureFileTransport creates the singleton with a copied policy', async () => { + const policy: LogStoragePolicy = { + maxTotalMb: 3, + retainDays: 1, + perUinEnabled: true, + }; + const status = await configureFileTransport(policy); + policy.retainDays = 9; + policy.perUinEnabled = false; + + expect(status).toMatchObject({ + maxTotalBytes: 3_145_728, + retainDays: 1, + perUinEnabled: true, + }); + expect(getFileTransport().getStorageStatus()).toMatchObject({ + retainDays: 1, + perUinEnabled: true, + }); + expect(getLogStorageStatus()).toEqual(getFileTransport().getStorageStatus()); + }); + + it('configureFileTransport updates the existing singleton and rejects invalid policies first', async () => { + const created = getFileTransport(); + const updated = await configureFileTransport({ + maxTotalMb: 5, + retainDays: 2, + perUinEnabled: true, + }); + expect(getFileTransport()).toBe(created); + expect(updated).toMatchObject({ + maxTotalBytes: 5_242_880, + retainDays: 2, + perUinEnabled: true, + }); + + await expect(configureFileTransport({ + maxTotalMb: 0, + retainDays: 2, + perUinEnabled: true, + })).rejects.toThrow(new RangeError('maxTotalMb must be an integer in 1..8589934591')); + expect(getLogStorageStatus().maxTotalBytes).toBe(5_242_880); + }); + + it('forgets a configured policy after reset so the next singleton reads env', async () => { + await configureFileTransport({ + maxTotalMb: 3, + retainDays: 1, + perUinEnabled: true, + }); + expect(getLogStorageStatus().retainDays).toBe(1); + + await _resetFileTransportForTesting(); + expect(getLogStorageStatus()).toMatchObject({ + maxTotalBytes: 2_097_152, + retainDays: 7, + perUinEnabled: false, + }); + }); + + it('clearManagedLogs delegates to the singleton', async () => { + setEnv({ SNOWLUMA_LOG_RETAIN_DAYS: '0' }); + fs.writeFileSync(path.join(tmpDir, 'snowluma-2020-01-01.log'), 'stale\n'); + getFileTransport(); + + const result = await clearManagedLogs(); + expect(result.deletedFiles).toBe(1); + expect(fs.existsSync(path.join(tmpDir, 'snowluma-2020-01-01.log'))).toBe(false); + expect(result.status.directory).toBe(tmpDir); + }); + + it('is a no-op reset when no singleton was created', async () => { + await expect(_resetFileTransportForTesting()).resolves.toBeUndefined(); + await expect(_resetFileTransportForTesting()).resolves.toBeUndefined(); + }); +}); diff --git a/packages/core/package.json b/packages/core/package.json index 5ee59686..44e42cfc 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/core", - "version": "1.14.7", + "version": "1.14.8", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/core/src/bridge/apis/flash-transfer.ts b/packages/core/src/bridge/apis/flash-transfer.ts index cf9da0a0..c60fec64 100644 --- a/packages/core/src/bridge/apis/flash-transfer.ts +++ b/packages/core/src/bridge/apis/flash-transfer.ts @@ -60,6 +60,21 @@ interface StagedFlashItem { cleanup(): Promise; } +/** One create_flash_task source: a path/URL, or a path plus a display name. */ +export type FlashTaskFileInput = string | { file: string; name?: string }; + +function flashFileDisplayName(override: string | undefined, fallback: string): string { + const cleaned = (override ?? '').replace(/[/\\]/g, '_').trim(); + return cleaned || fallback; +} + +function normalizeFlashTaskInputs( + files: FlashTaskFileInput | FlashTaskFileInput[], +): { file: string; name?: string }[] { + const list = Array.isArray(files) ? files : [files]; + return list.map((item) => (typeof item === 'string' ? { file: item } : item)); +} + /** 闪传文件信息(业务层,从 FlashFileEntry 转换)。 */ export interface FlashFileInfo { filesetUuid: string; @@ -413,15 +428,21 @@ export class FlashTransferApi { * 多文件:0x93d0 的 f4 是 repeated,一个 commit 请求同时携带 fileset 内所有文件 * 条目,每条 f6=文件序号(1,2,3...)。commit 在上传前只发一次,之后 complete → * 逐个 prepare/apply/sliceupload。prepare/apply 的 filesetWrap.f4 必须与 commit - * 的 f6 一致,否则文件不计入 fileset。多文件时 ApplyFileset 的 fileName 用 - * 「<首文件名>等N个文件」、fileSize 用总和——服务端据此判定 fileset 为多文件。 + * 的 f6 一致,否则文件不计入 fileset。ApplyFileset 的 fileName 是 fileset 显示名 + * (卡片标题):有 name 用 name,否则单文件用首文件名、多文件用「<首文件名>等N个文件」。 + * fileSize 用总和——服务端据此判定 fileset 为多文件。各文件在 commit 里用 + * 条目上的 name(若有),否则用路径 basename。 * * 源文件经 stageSourceToDisk 落到本地路径后流式哈希 / 分片读取,不再经 * loadBinarySource 整文件进内存。本地与 HTTP 上限与群文件相同(4 GiB); * 内联 base64 仍按 1 GiB 封顶,因为 stage 解码时会占用等量 RAM。 */ - async createFlashTask(files: string | string[], _name?: string, _thumbPath?: string): Promise<{ filesetId: string }> { - const fileList = Array.isArray(files) ? files : [files]; + async createFlashTask( + files: FlashTaskFileInput | FlashTaskFileInput[], + name?: string, + _thumbPath?: string, + ): Promise<{ filesetId: string }> { + const fileList = normalizeFlashTaskInputs(files); if (fileList.length === 0) throw new Error('create_flash_task: files is empty'); const uploader = { uin: this.ctx.identity.uin, @@ -433,9 +454,10 @@ export class FlashTransferApi { const items: StagedFlashItem[] = []; try { for (let i = 0; i < fileList.length; i++) { - const source = fileList[i]; + const source = fileList[i]!.file; + if (!source) throw new Error('create_flash_task: files is empty'); const staged = await stageSourceToDisk(source, flashStageMaxBytes(source)); - const fileName = staged.fileName; + const fileName = flashFileDisplayName(fileList[i]!.name, staged.fileName); const { formatCode } = FlashTransferApi.fileTypeCode(fileName); items.push({ filePath: staged.filePath, @@ -449,12 +471,14 @@ export class FlashTransferApi { }); if (staged.fileSize === 0) throw new Error('create_flash_task: file is empty'); } - // 申请 fileset。多文件时 fileName 用「<首文件名>等N个文件」、fileSize 用总和, + // 申请 fileset。fileName 是卡片/面板上的 fileset 标题;各文件真实名走 commit。 + // 未指定 name 时,多文件用「<首文件名>等N个文件」、fileSize 用总和, // 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。 const first = items[0]; const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName); const isMulti = items.length > 1; - const filesetName = isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName; + const filesetName = name?.trim() + || (isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName); const totalSize = items.reduce((s, it) => s + it.fileSize, 0); const apply = await ApplyFileset.invoke(this.ctx, { fileName: filesetName, origName: filesetName, diff --git a/packages/core/tests/flash-transfer-create.test.ts b/packages/core/tests/flash-transfer-create.test.ts index 9b9e838a..00bf1074 100644 --- a/packages/core/tests/flash-transfer-create.test.ts +++ b/packages/core/tests/flash-transfer-create.test.ts @@ -252,6 +252,93 @@ describe('FlashTransferApi.createFlashTask — disk streaming (#359)', () => { expect(Buffer.from(uploaded[1]!.payload!.chunk!).equals(Buffer.from(b))).toBe(true); }); + it('uses the optional name as the fileset title and keeps real file names on commit (#363)', async () => { + const file = writeSrc('clip.mp4', synth(40, 3)); + installSliceuploadOk(); + + await api().createFlashTask(file, '自定义名称'); + + expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + fileName: '自定义名称', + origName: '自定义名称', + fileSize: 40, + })); + expect(CommitFile.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + entries: [expect.objectContaining({ fileName: 'clip.mp4', fileSize: 40 })], + })); + }); + + it('uses the optional name as the multi-file fileset title (#363)', async () => { + const fileA = writeSrc('a.mp4', synth(50, 1)); + const fileB = writeSrc('b.zip', synth(70, 2)); + installSliceuploadOk(); + + await api().createFlashTask([fileA, fileB], '相册'); + + expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + fileName: '相册', + origName: '相册', + fileSize: 120, + })); + const commit = vi.mocked(CommitFile.invoke).mock.calls[0]![1]; + expect(commit.entries[0]).toEqual(expect.objectContaining({ fileName: 'a.mp4' })); + expect(commit.entries[1]).toEqual(expect.objectContaining({ fileName: 'b.zip' })); + }); + + it('uses a per-file name on commit and keeps the fileset title separate (#361)', async () => { + const file = writeSrc('uuid__clip.mp4', synth(40, 3)); + installSliceuploadOk(); + + await api().createFlashTask({ file, name: 'clip.mp4' }, '自定义名称'); + + expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + fileName: '自定义名称', + origName: '自定义名称', + })); + expect(CommitFile.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + entries: [expect.objectContaining({ fileName: 'clip.mp4', origName: 'clip.mp4', fileSize: 40 })], + })); + }); + + it('uses per-file names in a mixed files list (#361)', async () => { + const fileA = writeSrc('a-id__a.mp4', synth(50, 1)); + const fileB = writeSrc('b.zip', synth(70, 2)); + installSliceuploadOk(); + + await api().createFlashTask([{ file: fileA, name: 'a.mp4' }, fileB]); + + expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + fileName: 'a.mp4等2个文件', + fileSize: 120, + })); + const commit = vi.mocked(CommitFile.invoke).mock.calls[0]![1]; + expect(commit.entries[0]).toEqual(expect.objectContaining({ fileName: 'a.mp4' })); + expect(commit.entries[1]).toEqual(expect.objectContaining({ fileName: 'b.zip' })); + }); + + it('falls back to the path basename when the per-file name is blank (#361)', async () => { + const file = writeSrc('clip.mp4', synth(32, 9)); + installSliceuploadOk(); + + await api().createFlashTask({ file, name: ' ' }); + + expect(CommitFile.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + entries: [expect.objectContaining({ fileName: 'clip.mp4' })], + })); + }); + + it('falls back to the filename title when name is blank (#363)', async () => { + const file = writeSrc('clip.mp4', synth(32, 9)); + installSliceuploadOk(); + + await api().createFlashTask(file, ' '); + + expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + fileName: 'clip.mp4', + origName: 'clip.mp4', + })); + }); + it('rejects a source that mutates between hashing and upload', async () => { const file = writeSrc('mut.mp4', synth(90, 5)); const actualHash = hashMod.hashFlashFileStreaming; diff --git a/packages/core/tests/webui-auth.test.ts b/packages/core/tests/webui-auth.test.ts new file mode 100644 index 00000000..41e42fc1 --- /dev/null +++ b/packages/core/tests/webui-auth.test.ts @@ -0,0 +1,519 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { + evaluatePasswordRules, + isDevAuthMode, + isStrongPassword, + PASSWORD_RULES, + prepareWebuiAuthStateForRestore, + WebuiAuth, +} from '../src/webui/auth'; +import { confirmTotpEnrollment, unwrapTotpSecret, type TotpPersistedState } from '../src/webui/totp'; + +const TS = '2026-06-18T00:00:00.000Z'; +const HASH = 'ab'.repeat(64); +const SALT = 'cd'.repeat(16); +const STRONG = 'Correct-Horse-1!'; +const STRONG_NEXT = 'Correct-Horse-2!'; +const RFC_SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'; +const T59_MS = 59_000; +const T59_CODE = '287082'; + +const VALID_TOTP: TotpPersistedState = { + wrapSalt: '11'.repeat(16), + iv: '22'.repeat(12), + ciphertext: '33'.repeat(10), + authTag: '44'.repeat(16), + recoveryCodeHashes: ['55'.repeat(32), '66'.repeat(32)], + lastUsedStep: 7, + label: 'SnowLuma (testhost)', +}; + +const AUTH_ENV = ['SNOWLUMA_DEV_MODE', 'SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD'] as const; +const savedEnv: Record = {}; + +beforeEach(() => { + for (const key of AUTH_ENV) { + savedEnv[key] = process.env[key]; + delete process.env[key]; + } +}); + +afterEach(() => { + for (const key of AUTH_ENV) { + if (savedEnv[key] === undefined) delete process.env[key]; + else process.env[key] = savedEnv[key]; + } +}); + +describe('PASSWORD_RULES / evaluatePasswordRules / isStrongPassword', () => { + it('exposes the five published rule ids and labels in order', () => { + expect(PASSWORD_RULES.map((rule) => ({ id: rule.id, label: rule.label }))).toEqual([ + { id: 'length', label: '长度不少于 10 位' }, + { id: 'lower', label: '包含小写字母' }, + { id: 'upper', label: '包含大写字母' }, + { id: 'special', label: '包含特殊符号 (!@#$%…)' }, + { id: 'no-space', label: '不包含空格' }, + ]); + }); + + it('marks every rule ok for a 10-character mixed password with a symbol', () => { + expect(evaluatePasswordRules('Abcdefghi!')).toEqual([ + { id: 'length', label: '长度不少于 10 位', ok: true }, + { id: 'lower', label: '包含小写字母', ok: true }, + { id: 'upper', label: '包含大写字母', ok: true }, + { id: 'special', label: '包含特殊符号 (!@#$%…)', ok: true }, + { id: 'no-space', label: '不包含空格', ok: true }, + ]); + expect(isStrongPassword('Abcdefghi!')).toBe(true); + }); + + it('fails only length when the password is 9 characters', () => { + expect(evaluatePasswordRules('Abcdefgh!')).toEqual([ + { id: 'length', label: '长度不少于 10 位', ok: false }, + { id: 'lower', label: '包含小写字母', ok: true }, + { id: 'upper', label: '包含大写字母', ok: true }, + { id: 'special', label: '包含特殊符号 (!@#$%…)', ok: true }, + { id: 'no-space', label: '不包含空格', ok: true }, + ]); + expect(isStrongPassword('Abcdefgh!')).toBe(false); + }); + + it('fails only lower when every letter is uppercase', () => { + expect(evaluatePasswordRules('ABCDEFGHI!')).toEqual([ + { id: 'length', label: '长度不少于 10 位', ok: true }, + { id: 'lower', label: '包含小写字母', ok: false }, + { id: 'upper', label: '包含大写字母', ok: true }, + { id: 'special', label: '包含特殊符号 (!@#$%…)', ok: true }, + { id: 'no-space', label: '不包含空格', ok: true }, + ]); + expect(isStrongPassword('ABCDEFGHI!')).toBe(false); + }); + + it('fails only upper when every letter is lowercase', () => { + expect(evaluatePasswordRules('abcdefghi!')).toEqual([ + { id: 'length', label: '长度不少于 10 位', ok: true }, + { id: 'lower', label: '包含小写字母', ok: true }, + { id: 'upper', label: '包含大写字母', ok: false }, + { id: 'special', label: '包含特殊符号 (!@#$%…)', ok: true }, + { id: 'no-space', label: '不包含空格', ok: true }, + ]); + expect(isStrongPassword('abcdefghi!')).toBe(false); + }); + + it('fails only special when the password is letters and digits', () => { + expect(evaluatePasswordRules('Abcdefgh12')).toEqual([ + { id: 'length', label: '长度不少于 10 位', ok: true }, + { id: 'lower', label: '包含小写字母', ok: true }, + { id: 'upper', label: '包含大写字母', ok: true }, + { id: 'special', label: '包含特殊符号 (!@#$%…)', ok: false }, + { id: 'no-space', label: '不包含空格', ok: true }, + ]); + expect(isStrongPassword('Abcdefgh12')).toBe(false); + }); + + it('fails special and no-space when the only extra character is a space', () => { + expect(evaluatePasswordRules('Abcdefgh i')).toEqual([ + { id: 'length', label: '长度不少于 10 位', ok: true }, + { id: 'lower', label: '包含小写字母', ok: true }, + { id: 'upper', label: '包含大写字母', ok: true }, + { id: 'special', label: '包含特殊符号 (!@#$%…)', ok: false }, + { id: 'no-space', label: '不包含空格', ok: false }, + ]); + expect(isStrongPassword('Abcdefgh i')).toBe(false); + }); + + it('fails every rule for an empty string, including no-space', () => { + expect(evaluatePasswordRules('')).toEqual([ + { id: 'length', label: '长度不少于 10 位', ok: false }, + { id: 'lower', label: '包含小写字母', ok: false }, + { id: 'upper', label: '包含大写字母', ok: false }, + { id: 'special', label: '包含特殊符号 (!@#$%…)', ok: false }, + { id: 'no-space', label: '不包含空格', ok: false }, + ]); + expect(isStrongPassword('')).toBe(false); + }); +}); + +describe('isDevAuthMode', () => { + it('is true only when SNOWLUMA_DEV_MODE is the string 1', () => { + expect(isDevAuthMode()).toBe(false); + + process.env.SNOWLUMA_DEV_MODE = ''; + expect(isDevAuthMode()).toBe(false); + + process.env.SNOWLUMA_DEV_MODE = '0'; + expect(isDevAuthMode()).toBe(false); + + process.env.SNOWLUMA_DEV_MODE = 'true'; + expect(isDevAuthMode()).toBe(false); + + process.env.SNOWLUMA_DEV_MODE = '1'; + expect(isDevAuthMode()).toBe(true); + }); +}); + +describe('prepareWebuiAuthStateForRestore', () => { + const base = { + passwordHash: HASH, + passwordSalt: SALT, + mustChangePassword: false, + generatedAt: TS, + updatedAt: TS, + }; + + it('accepts a complete credential object and omits totp when it is absent or undefined', () => { + expect(prepareWebuiAuthStateForRestore(base)).toEqual({ + passwordHash: HASH, + passwordSalt: SALT, + mustChangePassword: false, + generatedAt: TS, + updatedAt: TS, + }); + expect(prepareWebuiAuthStateForRestore({ ...base, totp: undefined })).toEqual({ + passwordHash: HASH, + passwordSalt: SALT, + mustChangePassword: false, + generatedAt: TS, + updatedAt: TS, + }); + }); + + it('keeps mixed-case hash and salt hex and attaches a valid totp object', () => { + const mixedHash = 'AB'.repeat(64); + const mixedSalt = 'CD'.repeat(16); + expect(prepareWebuiAuthStateForRestore({ + passwordHash: mixedHash, + passwordSalt: mixedSalt, + mustChangePassword: true, + generatedAt: TS, + updatedAt: '2026-06-19T12:34:56.000Z', + totp: VALID_TOTP, + })).toEqual({ + passwordHash: mixedHash, + passwordSalt: mixedSalt, + mustChangePassword: true, + generatedAt: TS, + updatedAt: '2026-06-19T12:34:56.000Z', + totp: { + wrapSalt: '11'.repeat(16), + iv: '22'.repeat(12), + ciphertext: '33'.repeat(10), + authTag: '44'.repeat(16), + recoveryCodeHashes: ['55'.repeat(32), '66'.repeat(32)], + lastUsedStep: 7, + label: 'SnowLuma (testhost)', + }, + }); + }); + + it('rejects a non-object credential state', () => { + expect(() => prepareWebuiAuthStateForRestore(null)).toThrow('credential state must be an object'); + expect(() => prepareWebuiAuthStateForRestore(undefined)).toThrow('credential state must be an object'); + expect(() => prepareWebuiAuthStateForRestore([])).toThrow('credential state must be an object'); + expect(() => prepareWebuiAuthStateForRestore('x')).toThrow('credential state must be an object'); + }); + + it('rejects a passwordHash that is not exactly 128 hexadecimal characters', () => { + expect(() => prepareWebuiAuthStateForRestore({ ...base, passwordHash: 'ab'.repeat(63) })) + .toThrow('passwordHash must be exactly 128 hexadecimal characters'); + expect(() => prepareWebuiAuthStateForRestore({ ...base, passwordHash: `${HASH}0` })) + .toThrow('passwordHash must be exactly 128 hexadecimal characters'); + expect(() => prepareWebuiAuthStateForRestore({ ...base, passwordHash: 'gg'.repeat(64) })) + .toThrow('passwordHash must be exactly 128 hexadecimal characters'); + expect(() => prepareWebuiAuthStateForRestore({ ...base, passwordHash: 1 })) + .toThrow('passwordHash must be exactly 128 hexadecimal characters'); + }); + + it('rejects a passwordSalt that is not exactly 32 hexadecimal characters', () => { + expect(() => prepareWebuiAuthStateForRestore({ ...base, passwordSalt: 'cd'.repeat(15) })) + .toThrow('passwordSalt must be exactly 32 hexadecimal characters'); + expect(() => prepareWebuiAuthStateForRestore({ ...base, passwordSalt: 'zz'.repeat(16) })) + .toThrow('passwordSalt must be exactly 32 hexadecimal characters'); + }); + + it('rejects a non-boolean mustChangePassword', () => { + expect(() => prepareWebuiAuthStateForRestore({ ...base, mustChangePassword: 'false' })) + .toThrow('mustChangePassword must be a boolean'); + }); + + it('rejects generatedAt or updatedAt that are not parseable timestamps', () => { + expect(() => prepareWebuiAuthStateForRestore({ ...base, generatedAt: 'not-a-timestamp' })) + .toThrow('generatedAt must be a valid timestamp'); + expect(() => prepareWebuiAuthStateForRestore({ ...base, generatedAt: 0 })) + .toThrow('generatedAt must be a valid timestamp'); + expect(() => prepareWebuiAuthStateForRestore({ ...base, updatedAt: '' })) + .toThrow('updatedAt must be a valid timestamp'); + expect(() => prepareWebuiAuthStateForRestore({ ...base, updatedAt: 'Invalid Date' })) + .toThrow('updatedAt must be a valid timestamp'); + }); + + it('rejects an unknown top-level field', () => { + expect(() => prepareWebuiAuthStateForRestore({ ...base, note: 'x' })).toThrow('unknown field $.note'); + }); + + it('rejects a malformed totp object and a null totp value', () => { + expect(() => prepareWebuiAuthStateForRestore({ ...base, totp: { wrapSalt: 'zz' } })) + .toThrow('totp wrapped secret fields are invalid'); + expect(() => prepareWebuiAuthStateForRestore({ ...base, totp: null })) + .toThrow('totp state must be an object'); + }); +}); + +describe('WebuiAuth', () => { + const configPath = path.join('config', 'webui.json'); + let tmp: string; + let prevCwd: string; + + beforeEach(() => { + prevCwd = process.cwd(); + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-webui-auth-')); + process.chdir(tmp); + }); + + afterEach(() => { + process.chdir(prevCwd); + fs.rmSync(tmp, { recursive: true, force: true }); + }); + + function readAuthFile(): Record { + return JSON.parse(fs.readFileSync(configPath, 'utf8')) as Record; + } + + function writeAuthFile(value: string | Record): void { + fs.mkdirSync('config', { recursive: true }); + fs.writeFileSync(configPath, typeof value === 'string' ? value : JSON.stringify(value, null, 2)); + } + + function backupNames(): string[] { + if (!fs.existsSync('config')) return []; + return fs.readdirSync('config').filter((name) => name.startsWith('webui.json.bak.')).sort(); + } + + it('publishes the fixed dev password', () => { + expect(WebuiAuth.devPassword).toBe('snowluma-dev'); + }); + + it('creates config/webui.json with a one-shot hex bootstrap password', () => { + const auth = WebuiAuth.load(); + const initial = auth.takeInitialPassword(); + expect(initial).toMatch(/^[0-9a-f]{16}$/); + expect(auth.takeInitialPassword()).toBeNull(); + expect(auth.mustChangePassword()).toBe(true); + expect(auth.isDevMode()).toBe(false); + expect(auth.verify(initial!)).toBe(true); + expect(auth.verify('wrong-password')).toBe(false); + expect(auth.verify('')).toBe(false); + expect(auth.verify(undefined as unknown as string)).toBe(false); + expect(auth.totpEnabled()).toBe(false); + expect(auth.totpStatus()).toEqual({ enabled: false }); + expect(auth.totpState()).toBeUndefined(); + + const disk = readAuthFile(); + expect(disk.mustChangePassword).toBe(true); + expect(disk.totp).toBeUndefined(); + expect(disk.passwordHash).toMatch(/^[0-9a-f]{128}$/); + expect(disk.passwordSalt).toMatch(/^[0-9a-f]{32}$/); + expect(disk.generatedAt).toBe(disk.updatedAt); + expect(Number.isFinite(Date.parse(disk.generatedAt as string))).toBe(true); + if (process.platform !== 'win32') { + expect(fs.statSync(configPath).mode & 0o777).toBe(0o600); + } + }); + + it('rotates a leftover must-change bootstrap password on the next load', () => { + const first = WebuiAuth.load(); + const oldPassword = first.takeInitialPassword(); + expect(oldPassword).toMatch(/^[0-9a-f]{16}$/); + + const second = WebuiAuth.load(); + const rotated = second.takeInitialPassword(); + expect(rotated).toMatch(/^[0-9a-f]{16}$/); + expect(rotated).not.toBe(oldPassword); + expect(second.mustChangePassword()).toBe(true); + expect(second.verify(oldPassword!)).toBe(false); + expect(second.verify(rotated!)).toBe(true); + }); + + it('seeds credentials from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD when it is at least 8 characters', () => { + process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = '12345678'; + const auth = WebuiAuth.load(); + expect(auth.takeInitialPassword()).toBeNull(); + expect(auth.mustChangePassword()).toBe(false); + expect(auth.verify('12345678')).toBe(true); + expect(readAuthFile().mustChangePassword).toBe(false); + }); + + it('ignores a bootstrap env value shorter than 8 characters', () => { + process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = '1234567'; + const auth = WebuiAuth.load(); + expect(auth.mustChangePassword()).toBe(true); + expect(auth.verify('1234567')).toBe(false); + expect(auth.takeInitialPassword()).toMatch(/^[0-9a-f]{16}$/); + }); + + it('reloads an already-rotated file without regenerating', () => { + process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = 'seed-pass'; + WebuiAuth.load(); + delete process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD; + + const again = WebuiAuth.load(); + expect(again.takeInitialPassword()).toBeNull(); + expect(again.mustChangePassword()).toBe(false); + expect(again.verify('seed-pass')).toBe(true); + expect(backupNames()).toEqual([]); + }); + + it('backs up invalid JSON and regenerates credentials', () => { + writeAuthFile('{not-json'); + const auth = WebuiAuth.load(); + const names = backupNames(); + expect(names).toEqual([expect.stringMatching(/^webui\.json\.bak\.\d+$/)]); + expect(fs.readFileSync(path.join('config', names[0]!), 'utf8')).toBe('{not-json'); + expect(auth.takeInitialPassword()).toMatch(/^[0-9a-f]{16}$/); + expect(auth.mustChangePassword()).toBe(true); + }); + + it('backs up a schema-invalid object and can reseed from the bootstrap env', () => { + writeAuthFile({ passwordHash: 'zz', passwordSalt: '00', mustChangePassword: false }); + process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = 'env-password'; + const auth = WebuiAuth.load(); + expect(backupNames()).toHaveLength(1); + expect(auth.takeInitialPassword()).toBeNull(); + expect(auth.mustChangePassword()).toBe(false); + expect(auth.verify('env-password')).toBe(true); + }); + + it('keeps password credentials when the live totp field is invalid', () => { + process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = STRONG; + WebuiAuth.load(); + delete process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD; + + const disk = readAuthFile(); + writeAuthFile({ ...disk, totp: { wrapSalt: 'zz' } }); + + const auth = WebuiAuth.load(); + expect(auth.verify(STRONG)).toBe(true); + expect(auth.mustChangePassword()).toBe(false); + expect(auth.totpEnabled()).toBe(false); + expect(auth.totpStatus()).toEqual({ enabled: false }); + expect(auth.totpState()).toBeUndefined(); + expect(backupNames()).toEqual([]); + }); + + it('loads a persisted totp object from disk', () => { + process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = STRONG; + const first = WebuiAuth.load(); + delete process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD; + first.persistTotp(VALID_TOTP); + + const auth = WebuiAuth.load(); + expect(auth.totpEnabled()).toBe(true); + expect(auth.totpStatus()).toEqual({ + enabled: true, + remainingRecoveryCodes: 2, + label: 'SnowLuma (testhost)', + }); + expect(auth.totpState()).toEqual({ + wrapSalt: '11'.repeat(16), + iv: '22'.repeat(12), + ciphertext: '33'.repeat(10), + authTag: '44'.repeat(16), + recoveryCodeHashes: ['55'.repeat(32), '66'.repeat(32)], + lastUsedStep: 7, + label: 'SnowLuma (testhost)', + }); + }); + + it('setPassword writes a new hash, clears must-change, and keeps generatedAt', () => { + const auth = WebuiAuth.load(); + const initial = auth.takeInitialPassword()!; + const generatedAt = readAuthFile().generatedAt; + + expect(() => auth.setPassword('too-weak')).toThrow('密码不符合强度要求'); + auth.setPassword(STRONG); + expect(auth.mustChangePassword()).toBe(false); + expect(auth.verify(initial)).toBe(false); + expect(auth.verify(STRONG)).toBe(true); + + const disk = readAuthFile(); + expect(disk.mustChangePassword).toBe(false); + expect(disk.generatedAt).toBe(generatedAt); + expect(disk.updatedAt).not.toBe(generatedAt); + expect(disk.totp).toBeUndefined(); + }); + + it('setPassword rewraps totp with the current password', () => { + process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = STRONG; + const auth = WebuiAuth.load(); + delete process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD; + + const enabled = confirmTotpEnrollment({ + password: STRONG, + secret: RFC_SECRET, + code: T59_CODE, + label: 'SnowLuma (testhost)', + atMs: T59_MS, + }); + auth.persistTotp(enabled.state); + + expect(() => auth.setPassword(STRONG_NEXT)).toThrow('修改密码需要当前密码以重新保护 2FA 密钥'); + expect(() => auth.setPassword(STRONG_NEXT, '')).toThrow('修改密码需要当前密码以重新保护 2FA 密钥'); + expect(() => auth.setPassword(STRONG_NEXT, 'Wrong-Password-3!')).toThrow('无法使用当前密码解开 2FA 密钥'); + + auth.setPassword(STRONG_NEXT, STRONG); + expect(auth.verify(STRONG)).toBe(false); + expect(auth.verify(STRONG_NEXT)).toBe(true); + expect(auth.totpEnabled()).toBe(true); + expect(unwrapTotpSecret(STRONG_NEXT, auth.totpState()!)).toBe(RFC_SECRET); + expect(unwrapTotpSecret(STRONG, auth.totpState()!)).toBeNull(); + }); + + it('persistTotp writes, reports, and then removes 2FA state', () => { + process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD = STRONG; + const auth = WebuiAuth.load(); + delete process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD; + + auth.persistTotp(VALID_TOTP); + expect(auth.totpEnabled()).toBe(true); + expect(auth.totpStatus()).toEqual({ + enabled: true, + remainingRecoveryCodes: 2, + label: 'SnowLuma (testhost)', + }); + expect(auth.totpState()).toEqual(VALID_TOTP); + expect(readAuthFile().totp).toEqual(VALID_TOTP); + + auth.persistTotp(undefined); + expect(auth.totpEnabled()).toBe(false); + expect(auth.totpStatus()).toEqual({ enabled: false }); + expect(auth.totpState()).toBeUndefined(); + expect(Object.prototype.hasOwnProperty.call(readAuthFile(), 'totp')).toBe(false); + }); + + it('uses the in-memory dev password and never reads or writes webui.json', () => { + writeAuthFile('should-not-be-read'); + process.env.SNOWLUMA_DEV_MODE = '1'; + const auth = WebuiAuth.load(); + delete process.env.SNOWLUMA_DEV_MODE; + + expect(isDevAuthMode()).toBe(false); + expect(auth.isDevMode()).toBe(true); + expect(auth.mustChangePassword()).toBe(false); + expect(auth.takeInitialPassword()).toBeNull(); + expect(auth.verify('snowluma-dev')).toBe(true); + expect(auth.verify(STRONG)).toBe(false); + expect(auth.totpEnabled()).toBe(false); + expect(() => auth.setPassword(STRONG)).toThrow('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改'); + expect(() => auth.persistTotp(VALID_TOTP)).toThrow('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用 2FA'); + expect(fs.readFileSync(configPath, 'utf8')).toBe('should-not-be-read'); + }); + + it('does not create config/webui.json when loading in dev mode on a fresh directory', () => { + process.env.SNOWLUMA_DEV_MODE = '1'; + WebuiAuth.load(); + expect(fs.existsSync('config')).toBe(false); + }); +}); diff --git a/packages/core/tests/webui-port.test.ts b/packages/core/tests/webui-port.test.ts new file mode 100644 index 00000000..4387d902 --- /dev/null +++ b/packages/core/tests/webui-port.test.ts @@ -0,0 +1,180 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import net from 'node:net'; +import { findAvailablePort } from '../src/webui/port'; + +const HOST = '127.0.0.1'; +const OTHER_HOST = '127.0.0.2'; + +const held: net.Server[] = []; + +afterEach(async () => { + await Promise.all(held.splice(0).map(closeServer)); +}); + +function closeServer(server: net.Server): Promise { + return new Promise((resolve) => { + server.close(() => resolve()); + }); +} + +function portOf(server: net.Server): number { + const addr = server.address(); + if (!addr || typeof addr === 'string') throw new Error('expected TCP AddressInfo'); + return addr.port; +} + +function hold(port: number, host = HOST): Promise { + return new Promise((resolve, reject) => { + const server = net.createServer(); + server.once('error', reject); + server.listen({ port, host, exclusive: true }, () => { + held.push(server); + resolve(server); + }); + }); +} + +async function release(server: net.Server): Promise { + const i = held.indexOf(server); + if (i >= 0) held.splice(i, 1); + await closeServer(server); +} + +/** Bind an ephemeral port that still has a free successor on the same host. */ +async function holdWithFreeNext(host = HOST): Promise { + for (let n = 0; n < 8; n++) { + const server = await hold(0, host); + const start = portOf(server); + if (start >= 65535) { + await release(server); + continue; + } + try { + await release(await hold(start + 1, host)); + return start; + } catch { + await release(server); + } + } + throw new Error('no occupied port with a free successor'); +} + +describe('findAvailablePort', () => { + it('returns start when that TCP port is free', async () => { + const server = await hold(0); + const start = portOf(server); + await release(server); + + expect(await findAvailablePort(start)).toBe(start); + }); + + it('truncates a fractional start toward zero before probing', async () => { + const server = await hold(0); + const start = portOf(server); + await release(server); + + expect(await findAvailablePort(start + 0.9, { maxTries: 1 })).toBe(start); + expect(await findAvailablePort(start + 0.1, { maxTries: 1 })).toBe(start); + }); + + it('clamps a start above 65535 down to 65535', async () => { + const probe = await hold(65535); + expect(portOf(probe)).toBe(65535); + await release(probe); + + expect(await findAvailablePort(65536, { maxTries: 1 })).toBe(65535); + expect(await findAvailablePort(70000, { maxTries: 1 })).toBe(65535); + expect(await findAvailablePort(65535.8, { maxTries: 1 })).toBe(65535); + expect(await findAvailablePort(Number.POSITIVE_INFINITY, { maxTries: 1 })).toBe(65535); + }); + + it('returns the next port when start is already bound', async () => { + const start = await holdWithFreeNext(); + expect(await findAvailablePort(start)).toBe(start + 1); + }); + + it('walks forward one port at a time after consecutive collisions', async () => { + const start = await holdWithFreeNext(); + await hold(start + 1); + const third = await hold(start + 2); + await release(third); + + expect(await findAvailablePort(start, { maxTries: 3 })).toBe(start + 2); + }); + + it('throws when maxTries is exhausted on an occupied port', async () => { + const start = await holdWithFreeNext(); + await expect(findAvailablePort(start, { maxTries: 1 })).rejects.toThrow( + `No available TCP port found near ${start}`, + ); + }); + + it('throws without probing when maxTries is 0 and keeps the caller start in the message', async () => { + await expect(findAvailablePort(4123, { maxTries: 0 })).rejects.toThrow( + 'No available TCP port found near 4123', + ); + await expect(findAvailablePort(0, { maxTries: 0 })).rejects.toThrow( + 'No available TCP port found near 0', + ); + await expect(findAvailablePort(-20, { maxTries: 0 })).rejects.toThrow( + 'No available TCP port found near -20', + ); + await expect(findAvailablePort(70000, { maxTries: 0 })).rejects.toThrow( + 'No available TCP port found near 70000', + ); + }); + + it('stops at 65535 instead of wrapping after the last TCP port is taken', async () => { + await hold(65535); + + await expect(findAvailablePort(65535, { maxTries: 10 })).rejects.toThrow( + 'No available TCP port found near 65535', + ); + await expect(findAvailablePort(80000, { maxTries: 10 })).rejects.toThrow( + 'No available TCP port found near 80000', + ); + }); + + it('defaults host to 127.0.0.1', async () => { + const start = await holdWithFreeNext(); + await expect(findAvailablePort(start, { maxTries: 1 })).rejects.toThrow( + `No available TCP port found near ${start}`, + ); + }); + + it('probes only the requested host', async (ctx) => { + const start = await holdWithFreeNext(); + try { + await release(await hold(start, OTHER_HOST)); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'EADDRNOTAVAIL') { + ctx.skip(`${OTHER_HOST} is not assigned on this machine`); + } + throw error; + } + + expect(await findAvailablePort(start, { host: OTHER_HOST, maxTries: 1 })).toBe(start); + await expect(findAvailablePort(start, { host: HOST, maxTries: 1 })).rejects.toThrow( + `No available TCP port found near ${start}`, + ); + }); + + it('treats a listen failure as unavailable', async () => { + await expect( + findAvailablePort(43123, { host: '256.256.256.256', maxTries: 1 }), + ).rejects.toThrow('No available TCP port found near 43123'); + await expect(findAvailablePort(Number.NaN, { maxTries: 1 })).rejects.toThrow( + 'No available TCP port found near NaN', + ); + }); + + it('returns a port that can actually be bound', async () => { + const server = await hold(0); + const start = portOf(server); + await release(server); + + const found = await findAvailablePort(start, { maxTries: 5 }); + const bound = await hold(found); + expect(portOf(bound)).toBe(found); + }); +}); diff --git a/packages/core/tests/webui-update-check.test.ts b/packages/core/tests/webui-update-check.test.ts new file mode 100644 index 00000000..dd692e82 --- /dev/null +++ b/packages/core/tests/webui-update-check.test.ts @@ -0,0 +1,339 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { compareVersions, currentVersion, getUpdateInfo } from '../src/webui/update-check'; + +const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest'; +const NOTES_MAX = 4_000; +const originalFetch = globalThis.fetch; +const savedUpdateCheck = process.env.SNOWLUMA_UPDATE_CHECK; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((res) => { + resolve = res; + }); + return { promise, resolve }; +} + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +function mockFetch(impl: (...args: Parameters) => ReturnType) { + const fetchMock = vi.fn<(...args: Parameters) => ReturnType>(impl); + globalThis.fetch = fetchMock as typeof fetch; + return fetchMock; +} + +beforeEach(() => { + delete process.env.SNOWLUMA_UPDATE_CHECK; + globalThis.fetch = vi.fn(async () => { + throw new Error('unexpected fetch'); + }) as typeof fetch; +}); + +afterEach(() => { + globalThis.fetch = originalFetch; + if (savedUpdateCheck === undefined) delete process.env.SNOWLUMA_UPDATE_CHECK; + else process.env.SNOWLUMA_UPDATE_CHECK = savedUpdateCheck; +}); + +describe('currentVersion', () => { + it('falls back to 0.0.0 when the build-time version is unset', () => { + expect(currentVersion()).toBe('0.0.0'); + }); +}); + +describe('compareVersions', () => { + it.each([ + ['1.2.3', '1.2.3', 0], + ['v1.2.3', '1.2.3', 0], + ['1.2', '1.2.0', 0], + ['1.2.3.9', '1.2.3.1', 0], + ['1.2.x', '1.2.0', 0], + ['', '0.0.0', 0], + // Only a leading lowercase `v` is stripped; `V1.2.3` parses as 0.2.3. + ['V1.2.3', '0.0.0', 2], + ['V1.2.3', '0.2.3', 0], + ['1.2.4', '1.2.3', 1], + ['1.2.3', '1.2.4', -1], + ['1.10.0', '1.9.0', 1], + ['2.0.0', '1.9.9', 1], + ['3.0.0', '1.0.0', 2], + ['1.0.0', '3.0.0', -2], + ['1.2.3', '1.2.3-rc.1', 1], + ['1.2.3-rc.1', '1.2.3', -1], + ['1.2.3-rc.1', '1.2.3-rc.1', 0], + ['1.2.3-rc.1', '1.2.3-rc.2', -1], + ['1.2.3-rc.2', '1.2.3-rc.1', 1], + ['1.2.3-rc.10', '1.2.3-rc.2', -1], + ['2.0.0-rc.1', '1.9.9', 1], + ] as const)('compareVersions(%j, %j) === %s', (a, b, expected) => { + expect(compareVersions(a, b)).toBe(expected); + }); +}); + +describe('getUpdateInfo', () => { + it.each(['0', 'false', 'off', 'no', 'FALSE', ' Off ', 'No'] as const)( + 'skips the GitHub request when SNOWLUMA_UPDATE_CHECK=%j', + async (value) => { + process.env.SNOWLUMA_UPDATE_CHECK = value; + const fetchMock = mockFetch(async () => jsonResponse({ tag_name: 'v9.9.9' })); + const t0 = Date.now(); + const result = await getUpdateInfo(true); + + expect(fetchMock).not.toHaveBeenCalled(); + expect(result).toMatchObject({ + current: '0.0.0', + latest: null, + hasUpdate: false, + htmlUrl: null, + notes: null, + publishedAt: null, + error: 'disabled', + }); + expect(result.checkedAt).toBeGreaterThanOrEqual(t0); + expect(result.checkedAt).toBeLessThanOrEqual(Date.now()); + }, + ); + + // Must run before any successful check: errors are not cached, but a prior + // success stays in the module-level TTL cache and would hide this retry. + it('retries after a failed check instead of caching the error', async () => { + const fetchMock = mockFetch(async () => { + throw new Error('ECONNRESET'); + }); + + const failed = await getUpdateInfo(); + expect(failed).toMatchObject({ + current: '0.0.0', + latest: null, + hasUpdate: false, + htmlUrl: null, + notes: null, + publishedAt: null, + error: 'ECONNRESET', + }); + + fetchMock.mockImplementation(async () => jsonResponse({ tag_name: 'v1.0.0' })); + const ok = await getUpdateInfo(); + expect(ok.latest).toBe('1.0.0'); + expect(ok.hasUpdate).toBe(true); + expect(ok.error).toBeUndefined(); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it.each(['', '1', 'true', 'yes', 'on', ' '] as const)( + 'is enabled when SNOWLUMA_UPDATE_CHECK=%j', + async (value) => { + process.env.SNOWLUMA_UPDATE_CHECK = value; + mockFetch(async () => jsonResponse({ tag_name: 'v1.0.0' })); + const result = await getUpdateInfo(true); + expect(result.error).toBeUndefined(); + expect(result.latest).toBe('1.0.0'); + }, + ); + + it('GETs the latest stable release with the GitHub API headers', async () => { + const fetchMock = mockFetch(async () => jsonResponse({ tag_name: 'v1.2.3' })); + await getUpdateInfo(true); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0]?.[0]).toBe(LATEST_RELEASE_URL); + expect(fetchMock.mock.calls[0]?.[1]).toEqual({ + headers: { + Accept: 'application/vnd.github+json', + 'User-Agent': 'SnowLuma/0.0.0', + 'X-GitHub-Api-Version': '2022-11-28', + }, + signal: expect.any(AbortSignal), + }); + }); + + it('maps a newer release onto hasUpdate=true and strips the v prefix', async () => { + const t0 = Date.now(); + mockFetch(async () => + jsonResponse({ + tag_name: ' v1.14.7 ', + html_url: 'https://github.com/SnowLuma/SnowLuma/releases/tag/v1.14.7', + body: 'hello', + published_at: '2026-06-01T12:00:00Z', + }), + ); + + const result = await getUpdateInfo(true); + expect(result).toMatchObject({ + current: '0.0.0', + latest: '1.14.7', + hasUpdate: true, + htmlUrl: 'https://github.com/SnowLuma/SnowLuma/releases/tag/v1.14.7', + notes: 'hello', + publishedAt: '2026-06-01T12:00:00Z', + }); + expect(result.error).toBeUndefined(); + expect(result.checkedAt).toBeGreaterThanOrEqual(t0); + expect(result.checkedAt).toBeLessThanOrEqual(Date.now()); + }); + + it('sets hasUpdate=false when latest is not strictly newer than current', async () => { + mockFetch(async () => jsonResponse({ tag_name: '0.0.0' })); + const same = await getUpdateInfo(true); + expect(same.latest).toBe('0.0.0'); + expect(same.hasUpdate).toBe(false); + + mockFetch(async () => jsonResponse({ tag_name: 'v0.0.0-rc.1' })); + const older = await getUpdateInfo(true); + expect(older.latest).toBe('0.0.0-rc.1'); + expect(older.hasUpdate).toBe(false); + }); + + it('treats a missing body / html_url / published_at as null', async () => { + mockFetch(async () => jsonResponse({ tag_name: 'v5.0.0', body: '' })); + const result = await getUpdateInfo(true); + expect(result).toMatchObject({ + latest: '5.0.0', + hasUpdate: true, + htmlUrl: null, + notes: null, + publishedAt: null, + }); + }); + + it('truncates release notes to 4000 characters', async () => { + mockFetch(async () => jsonResponse({ tag_name: 'v6.0.0', body: 'n'.repeat(NOTES_MAX + 1) })); + const result = await getUpdateInfo(true); + expect(result.notes).toBe('n'.repeat(NOTES_MAX)); + }); + + it('returns github when the API is not ok', async () => { + mockFetch(async () => jsonResponse({ message: 'rate limited' }, 403)); + const result = await getUpdateInfo(true); + expect(result).toMatchObject({ + current: '0.0.0', + latest: null, + hasUpdate: false, + htmlUrl: null, + notes: null, + publishedAt: null, + error: 'github 403', + }); + }); + + it.each([{}, { tag_name: ' ' }, { tag_name: '' }] as const)( + 'returns no tag when tag_name is missing or blank: %j', + async (body) => { + mockFetch(async () => jsonResponse(body)); + const result = await getUpdateInfo(true); + expect(result.error).toBe('no tag'); + expect(result.hasUpdate).toBe(false); + expect(result.latest).toBeNull(); + }, + ); + + it('uses the Error message when fetch throws an Error', async () => { + mockFetch(async () => { + throw new Error('getaddrinfo ENOTFOUND'); + }); + const result = await getUpdateInfo(true); + expect(result.error).toBe('getaddrinfo ENOTFOUND'); + expect(result.hasUpdate).toBe(false); + }); + + it('uses network error when fetch throws a non-Error', async () => { + mockFetch(async () => { + throw 'timeout'; + }); + const result = await getUpdateInfo(true); + expect(result.error).toBe('network error'); + expect(result.hasUpdate).toBe(false); + }); + + it('degrades when the response body is not JSON', async () => { + mockFetch(async () => new Response('not-json', { status: 200 })); + const result = await getUpdateInfo(true); + expect(result.hasUpdate).toBe(false); + expect(result.latest).toBeNull(); + expect(result.error).toEqual(expect.any(String)); + expect(result.error).toBeTruthy(); + }); + + it('never throws', async () => { + mockFetch(async () => { + throw new Error('boom'); + }); + await expect(getUpdateInfo(true)).resolves.toMatchObject({ error: 'boom', hasUpdate: false }); + }); + + it('reuses a successful result until force=true', async () => { + const fetchMock = mockFetch(async () => + jsonResponse({ + tag_name: 'v3.1.0', + html_url: 'https://github.com/SnowLuma/SnowLuma/releases/tag/v3.1.0', + body: 'cached', + published_at: '2026-07-01T00:00:00Z', + }), + ); + + const first = await getUpdateInfo(true); + const second = await getUpdateInfo(); + const third = await getUpdateInfo(false); + expect(second).toBe(first); + expect(third).toBe(first); + expect(fetchMock).toHaveBeenCalledTimes(1); + + const forced = await getUpdateInfo(true); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(forced).toMatchObject({ + latest: '3.1.0', + hasUpdate: true, + notes: 'cached', + }); + expect(forced).not.toBe(first); + }); + + it('keeps a cached success after a forced failed check', async () => { + const fetchMock = mockFetch(async () => jsonResponse({ tag_name: 'v4.0.0' })); + const good = await getUpdateInfo(true); + expect(good.latest).toBe('4.0.0'); + + fetchMock.mockImplementation(async () => { + throw new Error('boom'); + }); + const bad = await getUpdateInfo(true); + expect(bad.error).toBe('boom'); + + const cached = await getUpdateInfo(); + expect(cached).toBe(good); + expect(cached.error).toBeUndefined(); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it('collapses concurrent checks onto one fetch', async () => { + const pending = deferred(); + const fetchMock = mockFetch(() => pending.promise); + const p1 = getUpdateInfo(true); + const p2 = getUpdateInfo(true); + expect(fetchMock).toHaveBeenCalledTimes(1); + + pending.resolve( + jsonResponse({ + tag_name: 'v2.0.0', + html_url: 'https://github.com/SnowLuma/SnowLuma/releases/tag/v2.0.0', + body: 'two', + published_at: '2026-07-01T00:00:00Z', + }), + ); + const [a, b] = await Promise.all([p1, p2]); + expect(a).toEqual(b); + expect(a).toMatchObject({ + latest: '2.0.0', + hasUpdate: true, + htmlUrl: 'https://github.com/SnowLuma/SnowLuma/releases/tag/v2.0.0', + notes: 'two', + publishedAt: '2026-07-01T00:00:00Z', + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 349170fc..08de5994 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/mcp", - "version": "1.14.7", + "version": "1.14.8", "description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.", "repository": { "type": "git", diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index be46612f..f8f9a392 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -924,7 +924,8 @@ "name": "files", "type": "raw", "required": false, - "schema": {} + "schema": {}, + "desc": "路径、{ file, name },或它们的数组" }, { "name": "name", @@ -947,7 +948,9 @@ "inputSchema": { "type": "object", "properties": { - "files": {}, + "files": { + "description": "路径、{ file, name },或它们的数组" + }, "name": { "type": "string" }, @@ -11578,7 +11581,7 @@ "name": "upload_file_stream", "aliases": [], "summary": "以流式分块方式上传文件到机器人本地(返回可用于发送的本地路径)", - "returns": "流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_size/sha256)", + "returns": "流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_name/file_size/sha256)", "readOnly": false, "params": [ { diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 62e9ca0b..717a159c 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -927,7 +927,8 @@ export const ACTIONS: CatalogAction[] = [ "name": "files", "type": "raw", "required": false, - "schema": {} + "schema": {}, + "desc": "路径、{ file, name },或它们的数组" }, { "name": "name", @@ -950,7 +951,9 @@ export const ACTIONS: CatalogAction[] = [ "inputSchema": { "type": "object", "properties": { - "files": {}, + "files": { + "description": "路径、{ file, name },或它们的数组" + }, "name": { "type": "string" }, @@ -11581,7 +11584,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "upload_file_stream", "aliases": [], "summary": "以流式分块方式上传文件到机器人本地(返回可用于发送的本地路径)", - "returns": "流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_size/sha256)", + "returns": "流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_name/file_size/sha256)", "readOnly": false, "params": [ { diff --git a/packages/onebot/package.json b/packages/onebot/package.json index d864336f..f9f60175 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/onebot", - "version": "1.14.7", + "version": "1.14.8", "private": true, "type": "module", "description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis..method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/'` collapses to `import { … } from '@snowluma/onebot/'`.", diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 048a568e..e195d219 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -302,6 +302,31 @@ async function groupTodoRun( return okResponse(); } +function parseFlashTaskFiles( + raw: unknown, +): { files: Array<{ file: string; name?: string }> } | { error: string } { + const items = Array.isArray(raw) ? raw : raw == null ? [] : [raw]; + if (items.length === 0) return { error: 'files must not be empty' }; + const files: Array<{ file: string; name?: string }> = []; + for (const item of items) { + if (typeof item === 'string') { + if (item === '') return { error: 'files must not be empty' }; + files.push({ file: item }); + continue; + } + if (item && typeof item === 'object' && !Array.isArray(item)) { + const file = (item as { file?: unknown }).file; + const name = (item as { name?: unknown }).name; + if (typeof file !== 'string' || file === '') return { error: 'files must not be empty' }; + if (name !== undefined && typeof name !== 'string') return { error: 'files[].name must be a string' }; + files.push({ file, name }); + continue; + } + return { error: 'files must be a path string, { file, name }, or an array of those' }; + } + return { files }; +} + /** FlashTransferApi 返回的 FlashFileInfo → OneBot JSON 响应(plain object,JsonObject 兼容)。 * 字段名对齐 NapCat(get_flash_file_list 用 size,非 file_size),便于客户端 drop-in 迁移。 */ function flashFileInfoToJson(f: { @@ -2584,25 +2609,15 @@ export const actions = [ name: 'create_flash_task', summary: '创建闪传任务', params: { - // files 支持单个路径(string)或多个路径(string[]),多文件共用一个 fileset - files: f.raw(), + // 路径、{ file, name },或它们的数组;name 是该文件在闪传里的显示名 + files: f.raw().describe('路径、{ file, name },或它们的数组'), name: f.string().optional(), thumb_path: f.string().optional(), }, run: async (p, ctx) => { - // f.raw() 不做校验,这里归一化为 string[] 并校验 - const rawFiles = p.files; - let fileList: string[]; - if (typeof rawFiles === 'string') { - if (rawFiles === '') return failedResponse(RETCODE.BAD_REQUEST, 'files must not be empty'); - fileList = [rawFiles]; - } else if (Array.isArray(rawFiles) && rawFiles.every((x) => typeof x === 'string' && x !== '')) { - if (rawFiles.length === 0) return failedResponse(RETCODE.BAD_REQUEST, 'files must not be empty'); - fileList = rawFiles as string[]; - } else { - return failedResponse(RETCODE.BAD_REQUEST, 'files must be a string or string array'); - } - const result = await ctx.bridge.apis.flashTransfer.createFlashTask(fileList, p.name, p.thumb_path); + const parsed = parseFlashTaskFiles(p.files); + if ('error' in parsed) return failedResponse(RETCODE.BAD_REQUEST, parsed.error); + const result = await ctx.bridge.apis.flashTransfer.createFlashTask(parsed.files, p.name, p.thumb_path); return okResponse({ fileset_id: result.filesetId, task_id: result.filesetId }); }, }), diff --git a/packages/onebot/src/actions/stream-file.ts b/packages/onebot/src/actions/stream-file.ts index bff3487d..87a4fa5e 100644 --- a/packages/onebot/src/actions/stream-file.ts +++ b/packages/onebot/src/actions/stream-file.ts @@ -251,6 +251,7 @@ async function completeUpload(state: UploadState): Promise { received_chunks: received, total_chunks: total, file_path: finalPath, + file_name: state.filename, file_size: fileSize, sha256, }); @@ -346,7 +347,7 @@ type UploadParams = { const uploadFileStream = defineStreamAction({ name: 'upload_file_stream', summary: '以流式分块方式上传文件到机器人本地(返回可用于发送的本地路径)', - returns: '流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_size/sha256)', + returns: '流式帧:分块确认 type=stream、完成 type=response(含 file_path/file_name/file_size/sha256)', params: uploadParams, run: (p, ctx) => handleUpload(p, accountKey(ctx)), }); diff --git a/packages/onebot/src/event-converter/element-codecs.ts b/packages/onebot/src/event-converter/element-codecs.ts index 97163182..5b72728d 100644 --- a/packages/onebot/src/event-converter/element-codecs.ts +++ b/packages/onebot/src/event-converter/element-codecs.ts @@ -478,6 +478,7 @@ export const ELEMENT_CODECS = { title: element.fileName ?? '', file_set_id: element.filesetId ?? '', scene_type: element.sceneType ?? 0, + thumb: element.thumbUrl ?? '', }, }; }, diff --git a/packages/onebot/tests/actions-group-admin.test.ts b/packages/onebot/tests/actions-group-admin.test.ts new file mode 100644 index 00000000..9e5d618c --- /dev/null +++ b/packages/onebot/tests/actions-group-admin.test.ts @@ -0,0 +1,1153 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { ApiActionContext } from '../src/api-handler'; +import { actions } from '../src/actions/group-admin'; + +function requireAction(name: string) { + const action = actions.find((entry) => entry.names[0] === name); + if (!action) throw new Error(`${name} action missing`); + return action; +} + +function adminCtx(groupAdmin: Record>): { + ctx: ApiActionContext; + groupAdmin: typeof groupAdmin; +} { + return { + groupAdmin, + ctx: { bridge: { apis: { groupAdmin } } } as unknown as ApiActionContext, + }; +} + +function portraitCtx(setGroupAvatar = vi.fn(async () => {})): { + ctx: ApiActionContext; + setGroupAvatar: ReturnType; +} { + return { + setGroupAvatar, + ctx: { + bridge: { apis: { profile: { setGroupAvatar } } }, + } as unknown as ApiActionContext, + }; +} + +const setGroupKick = requireAction('set_group_kick'); +const setGroupKickMembers = requireAction('set_group_kick_members'); +const setGroupBan = requireAction('set_group_ban'); +const setGroupWholeBan = requireAction('set_group_whole_ban'); +const setGroupAddOption = requireAction('set_group_add_option'); +const setGroupSearch = requireAction('set_group_search'); +const setGroupMemberInvitePolicy = requireAction('set_group_member_invite_policy'); +const setGroupNewMemberHistoryVisibility = requireAction('set_group_new_member_history_visibility'); +const setGroupMemberPermissions = requireAction('set_group_member_permissions'); +const setGroupAdmin = requireAction('set_group_admin'); +const setGroupCard = requireAction('set_group_card'); +const setGroupName = requireAction('set_group_name'); +const setGroupLeave = requireAction('set_group_leave'); +const setGroupSpecialTitle = requireAction('set_group_special_title'); +const setGroupAnonymous = requireAction('set_group_anonymous'); +const setGroupAnonymousBan = requireAction('set_group_anonymous_ban'); +const setGroupPortrait = requireAction('set_group_portrait'); + +describe('group admin actions catalog', () => { + it('exports the public group-admin actions in source order', () => { + expect(actions.map((action) => [...action.names])).toEqual([ + ['set_group_kick'], + ['set_group_kick_members'], + ['set_group_ban'], + ['set_group_whole_ban'], + ['set_group_add_option'], + ['set_group_search'], + ['set_group_member_invite_policy'], + ['set_group_new_member_history_visibility'], + ['set_group_member_permissions'], + ['set_group_admin'], + ['set_group_card'], + ['set_group_name'], + ['set_group_leave'], + ['set_group_special_title'], + ['set_group_anonymous'], + ['set_group_anonymous_ban'], + ['set_group_portrait'], + ]); + expect(actions.map((action) => action.kind)).toEqual([ + 'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal', + 'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal', + 'normal', 'normal', 'normal', + ]); + }); +}); + +describe('set_group_kick parse', () => { + it('requires group_id and user_id and defaults reject_add_request to false', () => { + expect(setGroupKick.parse({ group_id: 314159, user_id: 271828 })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, reject_add_request: false }, + }); + }); + + it('coerces numeric-string ids and an explicit reject flag', () => { + expect(setGroupKick.parse({ + group_id: '80001', + user_id: '24680', + reject_add_request: 'yes', + })).toEqual({ + ok: true, + value: { group_id: 80001, user_id: 24680, reject_add_request: true }, + }); + }); + + it('rejects a missing group_id', () => { + expect(setGroupKick.parse({ user_id: 271828 })).toEqual({ + ok: false, + field: 'group_id', + reason: 'is required', + }); + }); + + it('rejects group_id 0 and user_id 0', () => { + expect(setGroupKick.parse({ group_id: 0, user_id: 271828 })).toEqual({ + ok: false, + field: 'group_id', + reason: 'must be >= 1', + }); + expect(setGroupKick.parse({ group_id: 314159, user_id: 0 })).toEqual({ + ok: false, + field: 'user_id', + reason: 'must be >= 1', + }); + }); + + it('rejects an unrecognised reject_add_request synonym', () => { + expect(setGroupKick.parse({ + group_id: 314159, + user_id: 271828, + reject_add_request: 'maybe', + })).toEqual({ + ok: false, + field: 'reject_add_request', + reason: 'expected a boolean', + }); + }); +}); + +describe('set_group_kick toHandler', () => { + it('forwards the default reject flag and returns an empty ok payload', async () => { + const kickMember = vi.fn(async () => {}); + const { ctx } = adminCtx({ kickMember }); + + await expect(setGroupKick.toHandler(ctx)({ group_id: 314159, user_id: 271828 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(kickMember.mock.calls).toEqual([[314159, 271828, false]]); + }); + + it('forwards an explicit reject_add_request', async () => { + const kickMember = vi.fn(async () => {}); + const { ctx } = adminCtx({ kickMember }); + + await expect(setGroupKick.toHandler(ctx)({ + group_id: 80002, + user_id: 30003, + reject_add_request: 1, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(kickMember.mock.calls).toEqual([[80002, 30003, true]]); + }); + + it('returns BAD_REQUEST for a missing user_id without kicking', async () => { + const kickMember = vi.fn(async () => {}); + const { ctx } = adminCtx({ kickMember }); + + await expect(setGroupKick.toHandler(ctx)({ group_id: 314159 })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'user_id: is required', + }); + expect(kickMember).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_kick_members parse', () => { + it('requires a non-empty member-id array and defaults reject_add_request', () => { + expect(setGroupKickMembers.parse({ + group_id: 888001, + user_id: [271828, '13579'], + })).toEqual({ + ok: true, + value: { group_id: 888001, user_id: [271828, 13579], reject_add_request: false }, + }); + }); + + it('keeps an explicit reject_add_request of false', () => { + expect(setGroupKickMembers.parse({ + group_id: 888001, + user_id: [24680], + reject_add_request: false, + })).toEqual({ + ok: true, + value: { group_id: 888001, user_id: [24680], reject_add_request: false }, + }); + }); + + it('rejects a missing or non-array user_id', () => { + expect(setGroupKickMembers.parse({ group_id: 888001 })).toEqual({ + ok: false, + field: 'user_id', + reason: 'is required', + }); + expect(setGroupKickMembers.parse({ group_id: 888001, user_id: 271828 })).toEqual({ + ok: false, + field: 'user_id', + reason: 'expected an array', + }); + }); + + it('rejects an empty member list and names a bad element index', () => { + expect(setGroupKickMembers.parse({ group_id: 888001, user_id: [] })).toEqual({ + ok: false, + field: 'user_id', + reason: 'must not be empty', + }); + expect(setGroupKickMembers.parse({ group_id: 888001, user_id: [271828, 0] })).toEqual({ + ok: false, + field: 'user_id[1]', + reason: 'must be >= 1', + }); + }); +}); + +describe('set_group_kick_members toHandler', () => { + it('forwards the member list and default reject flag', async () => { + const kickMembers = vi.fn(async () => {}); + const { ctx } = adminCtx({ kickMembers }); + + await expect(setGroupKickMembers.toHandler(ctx)({ + group_id: 888001, + user_id: [271828, 13579], + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(kickMembers.mock.calls).toEqual([[888001, [271828, 13579], false]]); + }); + + it('forwards reject_add_request when kicking several members', async () => { + const kickMembers = vi.fn(async () => {}); + const { ctx } = adminCtx({ kickMembers }); + + await expect(setGroupKickMembers.toHandler(ctx)({ + group_id: '70001', + user_id: ['24681'], + reject_add_request: 'on', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(kickMembers.mock.calls).toEqual([[70001, [24681], true]]); + }); + + it('returns BAD_REQUEST for an empty member list without kicking', async () => { + const kickMembers = vi.fn(async () => {}); + const { ctx } = adminCtx({ kickMembers }); + + await expect(setGroupKickMembers.toHandler(ctx)({ + group_id: 888001, + user_id: [], + })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'user_id: must not be empty', + }); + expect(kickMembers).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_ban parse', () => { + it('defaults duration to 1800 and keeps a present 0 as unmute', () => { + expect(setGroupBan.parse({ group_id: 314159, user_id: 271828 })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, duration: 1800 }, + }); + expect(setGroupBan.parse({ group_id: 314159, user_id: 271828, duration: 0 })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, duration: 0 }, + }); + }); + + it('truncates a numeric-string duration', () => { + expect(setGroupBan.parse({ + group_id: 314159, + user_id: 271828, + duration: '600.9', + })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, duration: 600 }, + }); + }); + + it('rejects a negative duration', () => { + expect(setGroupBan.parse({ + group_id: 314159, + user_id: 271828, + duration: -1, + })).toEqual({ + ok: false, + field: 'duration', + reason: 'must be >= 0', + }); + }); +}); + +describe('set_group_ban toHandler', () => { + it('mutes with the default duration', async () => { + const muteMember = vi.fn(async () => {}); + const { ctx } = adminCtx({ muteMember }); + + await expect(setGroupBan.toHandler(ctx)({ group_id: 314159, user_id: 271828 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(muteMember.mock.calls).toEqual([[314159, 271828, 1800]]); + }); + + it('forwards duration 0 as unmute', async () => { + const muteMember = vi.fn(async () => {}); + const { ctx } = adminCtx({ muteMember }); + + await expect(setGroupBan.toHandler(ctx)({ + group_id: 80003, + user_id: 30004, + duration: 0, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(muteMember.mock.calls).toEqual([[80003, 30004, 0]]); + }); + + it('returns BAD_REQUEST for a negative duration without muting', async () => { + const muteMember = vi.fn(async () => {}); + const { ctx } = adminCtx({ muteMember }); + + await expect(setGroupBan.toHandler(ctx)({ + group_id: 314159, + user_id: 271828, + duration: -3, + })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'duration: must be >= 0', + }); + expect(muteMember).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_ban describe', () => { + it('documents the group-user preset and the unmute-capable duration', () => { + const doc = setGroupBan.describe(); + + expect(doc.name).toBe('set_group_ban'); + expect(doc.aliases).toEqual([]); + expect(doc.summary).toBe('禁言群成员(duration=0 解除)'); + expect(doc.readOnly).toBe(false); + expect(doc.returns).toBeUndefined(); + expect(doc.returnsSchema).toBeUndefined(); + expect(doc.stream).toBeUndefined(); + expect(doc.invariants).toEqual([]); + expect(doc.params).toEqual([ + { + name: 'group_id', + type: 'uint', + required: true, + desc: '群号', + role: 'group_id', + schema: { type: 'integer', minimum: 1 }, + }, + { + name: 'user_id', + type: 'uint', + required: true, + desc: 'QQ 号', + role: 'member_id', + schema: { type: 'integer', minimum: 1 }, + }, + { + name: 'duration', + type: 'int', + required: false, + default: 1800, + role: 'duration', + schema: { type: 'integer', minimum: 0 }, + }, + ]); + expect(doc.inputSchema).toEqual({ + type: 'object', + additionalProperties: true, + required: ['group_id', 'user_id'], + properties: { + group_id: { + type: 'integer', + minimum: 1, + description: '群号', + 'x-role': 'group_id', + }, + user_id: { + type: 'integer', + minimum: 1, + description: 'QQ 号', + 'x-role': 'member_id', + }, + duration: { + type: 'integer', + minimum: 0, + default: 1800, + 'x-role': 'duration', + }, + }, + }); + }); +}); + +describe('set_group_whole_ban parse', () => { + it('defaults enable to true', () => { + expect(setGroupWholeBan.parse({ group_id: 941657197 })).toEqual({ + ok: true, + value: { group_id: 941657197, enable: true }, + }); + }); + + it('coerces enable false synonyms', () => { + expect(setGroupWholeBan.parse({ group_id: 941657197, enable: 0 })).toEqual({ + ok: true, + value: { group_id: 941657197, enable: false }, + }); + expect(setGroupWholeBan.parse({ group_id: 941657197, enable: 'OFF' })).toEqual({ + ok: true, + value: { group_id: 941657197, enable: false }, + }); + }); +}); + +describe('set_group_whole_ban toHandler', () => { + it('enables whole-group mute by default', async () => { + const muteAll = vi.fn(async () => {}); + const { ctx } = adminCtx({ muteAll }); + + await expect(setGroupWholeBan.toHandler(ctx)({ group_id: 941657197 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(muteAll.mock.calls).toEqual([[941657197, true]]); + }); + + it('forwards an explicit disable', async () => { + const muteAll = vi.fn(async () => {}); + const { ctx } = adminCtx({ muteAll }); + + await expect(setGroupWholeBan.toHandler(ctx)({ + group_id: 12345, + enable: false, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(muteAll.mock.calls).toEqual([[12345, false]]); + }); +}); + +describe('set_group_add_option parse', () => { + it('defaults add_type to 0 and keeps a present 0', () => { + expect(setGroupAddOption.parse({ group_id: 12345 })).toEqual({ + ok: true, + value: { group_id: 12345, add_type: 0 }, + }); + expect(setGroupAddOption.parse({ group_id: 12345, add_type: 0 })).toEqual({ + ok: true, + value: { group_id: 12345, add_type: 0 }, + }); + }); + + it('accepts a positive add_type and rejects a negative one', () => { + expect(setGroupAddOption.parse({ group_id: 12345, add_type: '2' })).toEqual({ + ok: true, + value: { group_id: 12345, add_type: 2 }, + }); + expect(setGroupAddOption.parse({ group_id: 12345, add_type: -1 })).toEqual({ + ok: false, + field: 'add_type', + reason: 'must be >= 0', + }); + }); +}); + +describe('set_group_add_option toHandler', () => { + it('forwards the default add_type of 0', async () => { + const setAddOption = vi.fn(async () => {}); + const { ctx } = adminCtx({ setAddOption }); + + await expect(setGroupAddOption.toHandler(ctx)({ group_id: 12345 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setAddOption.mock.calls).toEqual([[12345, 0]]); + }); + + it('forwards an explicit add_type', async () => { + const setAddOption = vi.fn(async () => {}); + const { ctx } = adminCtx({ setAddOption }); + + await expect(setGroupAddOption.toHandler(ctx)({ + group_id: 941657197, + add_type: 3, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setAddOption.mock.calls).toEqual([[941657197, 3]]); + }); +}); + +describe('set_group_search parse', () => { + it('leaves both search switches undefined when omitted', () => { + expect(setGroupSearch.parse({ group_id: 70001 })).toEqual({ + ok: true, + value: { + group_id: 70001, + no_finger_open: undefined, + no_code_finger_open: undefined, + }, + }); + }); + + it('keeps a present 0 instead of treating it as missing', () => { + expect(setGroupSearch.parse({ + group_id: 70001, + no_finger_open: 0, + no_code_finger_open: '1', + })).toEqual({ + ok: true, + value: { + group_id: 70001, + no_finger_open: 0, + no_code_finger_open: 1, + }, + }); + }); + + it('rejects a negative search switch', () => { + expect(setGroupSearch.parse({ group_id: 70001, no_finger_open: -1 })).toEqual({ + ok: false, + field: 'no_finger_open', + reason: 'must be >= 0', + }); + expect(setGroupSearch.parse({ group_id: 70001, no_code_finger_open: -2 })).toEqual({ + ok: false, + field: 'no_code_finger_open', + reason: 'must be >= 0', + }); + }); +}); + +describe('set_group_search toHandler', () => { + it('forwards omitted switches as undefined', async () => { + const setSearch = vi.fn(async () => {}); + const { ctx } = adminCtx({ setSearch }); + + await expect(setGroupSearch.toHandler(ctx)({ group_id: 70001 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setSearch.mock.calls).toEqual([[70001, undefined, undefined]]); + }); + + it('forwards both supplied switches', async () => { + const setSearch = vi.fn(async () => {}); + const { ctx } = adminCtx({ setSearch }); + + await expect(setGroupSearch.toHandler(ctx)({ + group_id: 70002, + no_finger_open: 1, + no_code_finger_open: 0, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setSearch.mock.calls).toEqual([[70002, 1, 0]]); + }); +}); + +describe('set_group_member_invite_policy parse', () => { + it.each([ + 'disabled', + 'require_approval', + 'no_approval', + 'no_approval_under_100', + ] as const)('accepts policy %s', (policy) => { + expect(setGroupMemberInvitePolicy.parse({ group_id: 12345, policy })).toEqual({ + ok: true, + value: { group_id: 12345, policy }, + }); + }); + + it('requires policy and rejects an unknown value', () => { + expect(setGroupMemberInvitePolicy.parse({ group_id: 12345 })).toEqual({ + ok: false, + field: 'policy', + reason: 'is required', + }); + expect(setGroupMemberInvitePolicy.parse({ + group_id: 12345, + policy: 'anything', + })).toEqual({ + ok: false, + field: 'policy', + reason: 'expected one of: disabled, require_approval, no_approval, no_approval_under_100', + }); + }); +}); + +describe('set_group_member_invite_policy toHandler', () => { + it('forwards the validated policy', async () => { + const setMemberInvitePolicy = vi.fn(async () => {}); + const { ctx } = adminCtx({ setMemberInvitePolicy }); + + await expect(setGroupMemberInvitePolicy.toHandler(ctx)({ + group_id: '12345', + policy: 'no_approval_under_100', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setMemberInvitePolicy.mock.calls).toEqual([[12345, 'no_approval_under_100']]); + }); + + it('returns BAD_REQUEST for an unknown policy without calling the API', async () => { + const setMemberInvitePolicy = vi.fn(async () => {}); + const { ctx } = adminCtx({ setMemberInvitePolicy }); + + await expect(setGroupMemberInvitePolicy.toHandler(ctx)({ + group_id: 12345, + policy: 'open', + })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'policy: expected one of: disabled, require_approval, no_approval, no_approval_under_100', + }); + expect(setMemberInvitePolicy).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_new_member_history_visibility parse', () => { + it('requires visible and coerces boolean synonyms', () => { + expect(setGroupNewMemberHistoryVisibility.parse({ + group_id: 12345, + visible: 'false', + })).toEqual({ + ok: true, + value: { group_id: 12345, visible: false }, + }); + expect(setGroupNewMemberHistoryVisibility.parse({ group_id: 12345 })).toEqual({ + ok: false, + field: 'visible', + reason: 'is required', + }); + }); +}); + +describe('set_group_new_member_history_visibility toHandler', () => { + it('forwards the normalized group id and visibility', async () => { + const setNewMemberHistoryVisibility = vi.fn(async () => {}); + const { ctx } = adminCtx({ setNewMemberHistoryVisibility }); + + await expect(setGroupNewMemberHistoryVisibility.toHandler(ctx)({ + group_id: '12345', + visible: false, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setNewMemberHistoryVisibility.mock.calls).toEqual([[12345, false]]); + }); + + it('returns BAD_REQUEST when visible is missing', async () => { + const setNewMemberHistoryVisibility = vi.fn(async () => {}); + const { ctx } = adminCtx({ setNewMemberHistoryVisibility }); + + await expect(setGroupNewMemberHistoryVisibility.toHandler(ctx)({ group_id: 12345 })) + .resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'visible: is required', + }); + expect(setNewMemberHistoryVisibility).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_member_permissions parse', () => { + it('accepts a single capability switch and leaves the others undefined', () => { + expect(setGroupMemberPermissions.parse({ + group_id: 12345, + allow_member_upload_album: false, + })).toEqual({ + ok: true, + value: { + group_id: 12345, + allow_member_upload_album: false, + allow_member_temporary_session: undefined, + allow_member_create_group: undefined, + }, + }); + }); + + it('coerces every supplied capability switch', () => { + expect(setGroupMemberPermissions.parse({ + group_id: '12345', + allow_member_upload_album: 'true', + allow_member_temporary_session: false, + allow_member_create_group: 1, + })).toEqual({ + ok: true, + value: { + group_id: 12345, + allow_member_upload_album: true, + allow_member_temporary_session: false, + allow_member_create_group: true, + }, + }); + }); + + it('rejects an empty update after optional fields resolve to undefined', () => { + expect(setGroupMemberPermissions.parse({ group_id: 12345 })).toEqual({ + ok: false, + field: '', + reason: 'at least one of: allow_member_upload_album, allow_member_temporary_session, allow_member_create_group', + }); + }); +}); + +describe('set_group_member_permissions toHandler', () => { + it('remaps all supplied switches into the group-admin payload', async () => { + const setMemberPermissions = vi.fn(async () => {}); + const { ctx } = adminCtx({ setMemberPermissions }); + + await expect(setGroupMemberPermissions.toHandler(ctx)({ + group_id: '12345', + allow_member_upload_album: 'true', + allow_member_temporary_session: false, + allow_member_create_group: 1, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setMemberPermissions.mock.calls).toEqual([[12345, { + allowMemberUploadAlbum: true, + allowMemberTemporarySession: false, + allowMemberCreateGroup: true, + }]]); + }); + + it('forwards a single supplied switch with the others undefined', async () => { + const setMemberPermissions = vi.fn(async () => {}); + const { ctx } = adminCtx({ setMemberPermissions }); + + await expect(setGroupMemberPermissions.toHandler(ctx)({ + group_id: 12345, + allow_member_temporary_session: true, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setMemberPermissions.mock.calls).toEqual([[12345, { + allowMemberUploadAlbum: undefined, + allowMemberTemporarySession: true, + allowMemberCreateGroup: undefined, + }]]); + }); + + it('returns BAD_REQUEST for an empty update without calling the API', async () => { + const setMemberPermissions = vi.fn(async () => {}); + const { ctx } = adminCtx({ setMemberPermissions }); + + await expect(setGroupMemberPermissions.toHandler(ctx)({ group_id: 12345 })) + .resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'at least one of: allow_member_upload_album, allow_member_temporary_session, allow_member_create_group', + }); + expect(setMemberPermissions).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_member_permissions describe', () => { + it('documents the at-least-one capability invariant', () => { + const doc = setGroupMemberPermissions.describe(); + + expect(doc.name).toBe('set_group_member_permissions'); + expect(doc.summary).toBe('设置群成员权限'); + expect(doc.invariants).toEqual([ + 'at least one of: allow_member_upload_album, allow_member_temporary_session, allow_member_create_group', + ]); + expect(doc.inputSchema).toEqual({ + type: 'object', + additionalProperties: true, + required: ['group_id'], + properties: { + group_id: { + type: 'integer', + minimum: 1, + description: '群号', + 'x-role': 'group_id', + }, + allow_member_upload_album: { type: 'boolean' }, + allow_member_temporary_session: { type: 'boolean' }, + allow_member_create_group: { type: 'boolean' }, + }, + }); + }); +}); + +describe('set_group_admin parse', () => { + it('defaults enable to true', () => { + expect(setGroupAdmin.parse({ group_id: 314159, user_id: 271828 })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, enable: true }, + }); + }); + + it('accepts an explicit disable', () => { + expect(setGroupAdmin.parse({ + group_id: 314159, + user_id: 271828, + enable: 'no', + })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, enable: false }, + }); + }); +}); + +describe('set_group_admin toHandler', () => { + it('promotes a member with the default enable flag', async () => { + const setAdmin = vi.fn(async () => {}); + const { ctx } = adminCtx({ setAdmin }); + + await expect(setGroupAdmin.toHandler(ctx)({ group_id: 314159, user_id: 271828 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setAdmin.mock.calls).toEqual([[314159, 271828, true]]); + }); + + it('forwards an explicit demotion', async () => { + const setAdmin = vi.fn(async () => {}); + const { ctx } = adminCtx({ setAdmin }); + + await expect(setGroupAdmin.toHandler(ctx)({ + group_id: 80004, + user_id: 30005, + enable: false, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setAdmin.mock.calls).toEqual([[80004, 30005, false]]); + }); +}); + +describe('set_group_card parse', () => { + it('defaults card to an empty string and keeps an explicit empty clear', () => { + expect(setGroupCard.parse({ group_id: 314159, user_id: 271828 })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, card: '' }, + }); + expect(setGroupCard.parse({ + group_id: 314159, + user_id: 271828, + card: '', + })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, card: '' }, + }); + }); + + it('stringifies a numeric card and rejects a non-stringifiable value', () => { + expect(setGroupCard.parse({ + group_id: 314159, + user_id: 271828, + card: 404, + })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, card: '404' }, + }); + expect(setGroupCard.parse({ + group_id: 314159, + user_id: 271828, + card: { text: 'nick' }, + })).toEqual({ + ok: false, + field: 'card', + reason: 'expected a string', + }); + }); +}); + +describe('set_group_card toHandler', () => { + it('forwards the default empty card as a clear', async () => { + const setCard = vi.fn(async () => {}); + const { ctx } = adminCtx({ setCard }); + + await expect(setGroupCard.toHandler(ctx)({ group_id: 314159, user_id: 271828 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setCard.mock.calls).toEqual([[314159, 271828, '']]); + }); + + it('forwards an explicit card string', async () => { + const setCard = vi.fn(async () => {}); + const { ctx } = adminCtx({ setCard }); + + await expect(setGroupCard.toHandler(ctx)({ + group_id: 80005, + user_id: 30006, + card: '值班号', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setCard.mock.calls).toEqual([[80005, 30006, '值班号']]); + }); +}); + +describe('set_group_name parse', () => { + it('defaults group_name to an empty string', () => { + expect(setGroupName.parse({ group_id: 314159 })).toEqual({ + ok: true, + value: { group_id: 314159, group_name: '' }, + }); + }); + + it('stringifies a boolean group_name', () => { + expect(setGroupName.parse({ group_id: 314159, group_name: true })).toEqual({ + ok: true, + value: { group_id: 314159, group_name: 'true' }, + }); + }); +}); + +describe('set_group_name toHandler', () => { + it('forwards the default empty name', async () => { + const setName = vi.fn(async () => {}); + const { ctx } = adminCtx({ setName }); + + await expect(setGroupName.toHandler(ctx)({ group_id: 314159 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setName.mock.calls).toEqual([[314159, '']]); + }); + + it('forwards an explicit group name', async () => { + const setName = vi.fn(async () => {}); + const { ctx } = adminCtx({ setName }); + + await expect(setGroupName.toHandler(ctx)({ + group_id: 941657197, + group_name: 'Muted Group', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setName.mock.calls).toEqual([[941657197, 'Muted Group']]); + }); +}); + +describe('set_group_leave parse', () => { + it('requires only group_id and drops undeclared keys', () => { + expect(setGroupLeave.parse({ group_id: 314159, extra: true })).toEqual({ + ok: true, + value: { group_id: 314159 }, + }); + }); + + it('rejects a missing group_id', () => { + expect(setGroupLeave.parse({})).toEqual({ + ok: false, + field: 'group_id', + reason: 'is required', + }); + }); +}); + +describe('set_group_leave toHandler', () => { + it('forwards the group id to leave', async () => { + const leave = vi.fn(async () => {}); + const { ctx } = adminCtx({ leave }); + + await expect(setGroupLeave.toHandler(ctx)({ group_id: 314159 })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(leave.mock.calls).toEqual([[314159]]); + }); + + it('returns BAD_REQUEST for group_id 0 without leaving', async () => { + const leave = vi.fn(async () => {}); + const { ctx } = adminCtx({ leave }); + + await expect(setGroupLeave.toHandler(ctx)({ group_id: 0 })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'group_id: must be >= 1', + }); + expect(leave).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_special_title parse', () => { + it('defaults special_title to an empty string', () => { + expect(setGroupSpecialTitle.parse({ group_id: 314159, user_id: 271828 })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, special_title: '' }, + }); + }); + + it('keeps an explicit empty title', () => { + expect(setGroupSpecialTitle.parse({ + group_id: 314159, + user_id: 271828, + special_title: '', + })).toEqual({ + ok: true, + value: { group_id: 314159, user_id: 271828, special_title: '' }, + }); + }); +}); + +describe('set_group_special_title toHandler', () => { + it('forwards the default empty title', async () => { + const setSpecialTitle = vi.fn(async () => {}); + const { ctx } = adminCtx({ setSpecialTitle }); + + await expect(setGroupSpecialTitle.toHandler(ctx)({ + group_id: 314159, + user_id: 271828, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setSpecialTitle.mock.calls).toEqual([[314159, 271828, '']]); + }); + + it('forwards an explicit title', async () => { + const setSpecialTitle = vi.fn(async () => {}); + const { ctx } = adminCtx({ setSpecialTitle }); + + await expect(setGroupSpecialTitle.toHandler(ctx)({ + group_id: 80006, + user_id: 30007, + special_title: '龙王', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setSpecialTitle.mock.calls).toEqual([[80006, 30007, '龙王']]); + }); +}); + +describe('set_group_anonymous parse', () => { + it('accepts any params and returns an empty object', () => { + expect(setGroupAnonymous.parse({})).toEqual({ ok: true, value: {} }); + expect(setGroupAnonymous.parse({ group_id: 314159, enable: true })).toEqual({ + ok: true, + value: {}, + }); + }); +}); + +describe('set_group_anonymous toHandler', () => { + it('returns ok without touching the bridge', async () => { + await expect(setGroupAnonymous.toHandler({} as ApiActionContext)({ + group_id: 314159, + enable: false, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + }); +}); + +describe('set_group_anonymous describe', () => { + it('documents the unimplemented anonymous switch', () => { + const doc = setGroupAnonymous.describe(); + + expect(doc.name).toBe('set_group_anonymous'); + expect(doc.summary).toBe('匿名开关(未实现,返回 ok)'); + expect(doc.readOnly).toBe(false); + expect(doc.params).toEqual([]); + expect(doc.invariants).toEqual([]); + expect(doc.inputSchema).toEqual({ + type: 'object', + properties: {}, + additionalProperties: true, + }); + }); +}); + +describe('set_group_anonymous_ban parse', () => { + it('accepts any params and returns an empty object', () => { + expect(setGroupAnonymousBan.parse({ + group_id: 314159, + anonymous_flag: 'x', + duration: 60, + })).toEqual({ ok: true, value: {} }); + }); +}); + +describe('set_group_anonymous_ban toHandler', () => { + it('returns ok without touching the bridge', async () => { + await expect(setGroupAnonymousBan.toHandler({} as ApiActionContext)({ + flag: 'anon', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + }); +}); + +describe('set_group_anonymous_ban describe', () => { + it('documents the unimplemented anonymous mute', () => { + expect(setGroupAnonymousBan.describe().summary).toBe('匿名禁言(未实现,返回 ok)'); + }); +}); + +describe('set_group_portrait parse', () => { + it('requires a non-empty image source and stringifies primitives', () => { + expect(setGroupPortrait.parse({ + group_id: 314159, + file: 'https://example.invalid/avatar.png', + })).toEqual({ + ok: true, + value: { group_id: 314159, file: 'https://example.invalid/avatar.png' }, + }); + expect(setGroupPortrait.parse({ group_id: 314159, file: 10001 })).toEqual({ + ok: true, + value: { group_id: 314159, file: '10001' }, + }); + }); + + it('rejects a missing or empty file', () => { + expect(setGroupPortrait.parse({ group_id: 314159 })).toEqual({ + ok: false, + field: 'file', + reason: 'is required', + }); + expect(setGroupPortrait.parse({ group_id: 314159, file: '' })).toEqual({ + ok: false, + field: 'file', + reason: 'must not be empty', + }); + }); + + it('rejects a non-stringifiable file', () => { + expect(setGroupPortrait.parse({ + group_id: 314159, + file: { url: 'https://example.invalid/avatar.png' }, + })).toEqual({ + ok: false, + field: 'file', + reason: 'expected a string', + }); + }); +}); + +describe('set_group_portrait toHandler', () => { + it('forwards the image source to profile.setGroupAvatar', async () => { + const { ctx, setGroupAvatar } = portraitCtx(); + + await expect(setGroupPortrait.toHandler(ctx)({ + group_id: 314159, + file: 'base64://abc', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(setGroupAvatar.mock.calls).toEqual([[314159, 'base64://abc']]); + }); + + it('returns BAD_REQUEST for an empty file without setting the avatar', async () => { + const { ctx, setGroupAvatar } = portraitCtx(); + + await expect(setGroupPortrait.toHandler(ctx)({ + group_id: 314159, + file: '', + })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'file: must not be empty', + }); + expect(setGroupAvatar).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/onebot/tests/actions-message.test.ts b/packages/onebot/tests/actions-message.test.ts new file mode 100644 index 00000000..35d55765 --- /dev/null +++ b/packages/onebot/tests/actions-message.test.ts @@ -0,0 +1,570 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { ApiActionContext } from '../src/api-handler'; +import { actions } from '../src/actions/message'; +import type { JsonObject, MessageMeta } from '../src/types'; + +function requireAction(name: string) { + const action = actions.find((entry) => entry.names[0] === name); + if (!action) throw new Error(`${name} action missing`); + return action; +} + +function asCtx(partial: Partial): ApiActionContext { + return partial as ApiActionContext; +} + +const sendMsg = requireAction('send_msg'); +const sendPrivateMsg = requireAction('send_private_msg'); +const sendGroupMsg = requireAction('send_group_msg'); +const getMsg = requireAction('get_msg'); +const deleteMsg = requireAction('delete_msg'); + +describe('message actions catalog', () => { + it('exports the five public message actions in source order', () => { + expect(actions.map((entry) => entry.names[0])).toEqual([ + 'send_msg', + 'send_private_msg', + 'send_group_msg', + 'get_msg', + 'delete_msg', + ]); + }); + + it('marks only get_msg as read-only', () => { + expect(sendMsg.describe().readOnly).toBe(false); + expect(sendPrivateMsg.describe().readOnly).toBe(false); + expect(sendGroupMsg.describe().readOnly).toBe(false); + expect(getMsg.describe().readOnly).toBe(true); + expect(deleteMsg.describe().readOnly).toBe(false); + }); +}); + +describe('send_msg parse', () => { + it('defaults auto_escape to false and leaves optional ids unset', () => { + expect(sendMsg.parse({ message: 'hello route' })).toEqual({ + ok: true, + value: { + message: 'hello route', + message_type: undefined, + group_id: undefined, + user_id: undefined, + auto_escape: false, + }, + }); + }); + + it('parses a JSON-array message string and numeric ids', () => { + expect(sendMsg.parse({ + message: '[{"type":"text","data":{"text":"hi"}}]', + message_type: 'group', + group_id: '314159', + user_id: '271828', + auto_escape: 'on', + })).toEqual({ + ok: true, + value: { + message: [{ type: 'text', data: { text: 'hi' } }], + message_type: 'group', + group_id: 314159, + user_id: 271828, + auto_escape: true, + }, + }); + }); + + it('requires message and rejects group_id 0', () => { + expect(sendMsg.parse({})).toEqual({ + ok: false, + field: 'message', + reason: 'is required', + }); + expect(sendMsg.parse({ message: 'x', group_id: 0 })).toEqual({ + ok: false, + field: 'group_id', + reason: 'must be >= 1', + }); + }); +}); + +describe('send_msg run', () => { + it('sends a group message when message_type is group', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 9001 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 0 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + message_type: 'group', + group_id: 314159, + message: 'group hello', + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9001 } }); + expect(sendGroupMessage.mock.calls).toEqual([[314159, 'group hello', false]]); + expect(sendPrivateMessage).not.toHaveBeenCalled(); + }); + + it('sends a group message when only group_id is present', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 9002 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 0 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + group_id: 80001, + user_id: 271828, + message: [{ type: 'text', data: { text: 'by group_id' } }], + auto_escape: true, + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9002 } }); + expect(sendGroupMessage.mock.calls).toEqual([[ + 80001, + [{ type: 'text', data: { text: 'by group_id' } }], + true, + ]]); + expect(sendPrivateMessage).not.toHaveBeenCalled(); + }); + + it('sends a private message when only user_id is present', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 0 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 9003 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + user_id: 271828, + message: 'private hello', + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9003 } }); + expect(sendPrivateMessage.mock.calls).toEqual([[271828, 'private hello', false, undefined]]); + expect(sendGroupMessage).not.toHaveBeenCalled(); + }); + + it('routes private + both ids into a temp-session reply', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 0 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 9004 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + message_type: 'private', + user_id: 13579, + group_id: 70001, + message: 'temp hi', + auto_escape: false, + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9004 } }); + expect(sendPrivateMessage.mock.calls).toEqual([[13579, 'temp hi', false, 70001]]); + expect(sendGroupMessage).not.toHaveBeenCalled(); + }); + + it('still sends a group message when message_type is group and user_id is also set', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 9005 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 0 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + message_type: 'group', + group_id: 80002, + user_id: 30003, + message: 'not temp', + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9005 } }); + expect(sendGroupMessage.mock.calls).toEqual([[80002, 'not temp', false]]); + expect(sendPrivateMessage).not.toHaveBeenCalled(); + }); + + it('returns BAD_REQUEST when message_type is group without group_id', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 0 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 0 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + message_type: 'group', + message: 'missing group', + }); + + expect(response).toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'group_id is required', + }); + expect(sendGroupMessage).not.toHaveBeenCalled(); + expect(sendPrivateMessage).not.toHaveBeenCalled(); + }); + + it('returns BAD_REQUEST when neither a group route nor user_id is present', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 0 })); + const sendPrivateMessage = vi.fn(async () => ({ messageId: 0 })); + const response = await sendMsg.toHandler(asCtx({ sendGroupMessage, sendPrivateMessage }))({ + message_type: 'private', + message: 'missing user', + }); + + expect(response).toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'user_id is required', + }); + expect(sendGroupMessage).not.toHaveBeenCalled(); + expect(sendPrivateMessage).not.toHaveBeenCalled(); + }); + + it('shapes a parse failure as BAD_REQUEST wording', async () => { + const response = await sendMsg.toHandler(asCtx({}))({}); + + expect(response).toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'message: is required', + }); + }); +}); + +describe('send_private_msg', () => { + it('parses group_id 0 and defaults auto_escape', () => { + expect(sendPrivateMsg.parse({ + user_id: 24680, + message: 'plain private', + group_id: 0, + })).toEqual({ + ok: true, + value: { + user_id: 24680, + message: 'plain private', + group_id: 0, + auto_escape: false, + }, + }); + }); + + it('rejects a negative group_id before sending', () => { + expect(sendPrivateMsg.parse({ + user_id: 24680, + message: 'x', + group_id: -1, + })).toEqual({ + ok: false, + field: 'group_id', + reason: 'must be >= 0', + }); + }); + + it('sends a friend private message when group_id is absent', async () => { + const sendPrivateMessage = vi.fn(async () => ({ messageId: 9101 })); + const response = await sendPrivateMsg.toHandler(asCtx({ sendPrivateMessage }))({ + user_id: 24680, + message: 'friend hi', + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9101 } }); + expect(sendPrivateMessage.mock.calls).toEqual([[24680, 'friend hi', false, undefined]]); + }); + + it('treats group_id 0 as no temp session', async () => { + const sendPrivateMessage = vi.fn(async () => ({ messageId: 9102 })); + const response = await sendPrivateMsg.toHandler(asCtx({ sendPrivateMessage }))({ + user_id: 24682, + group_id: 0, + message: 'zero group', + auto_escape: true, + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9102 } }); + expect(sendPrivateMessage.mock.calls).toEqual([[24682, 'zero group', true, undefined]]); + }); + + it('forwards a positive group_id as the temp-session source', async () => { + const sendPrivateMessage = vi.fn(async () => ({ messageId: 9103 })); + const response = await sendPrivateMsg.toHandler(asCtx({ sendPrivateMessage }))({ + user_id: 24681, + group_id: 70002, + message: 'temp from group', + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9103 } }); + expect(sendPrivateMessage.mock.calls).toEqual([[24681, 'temp from group', false, 70002]]); + }); +}); + +describe('send_group_msg', () => { + it('requires group_id from the groupAction preset', () => { + expect(sendGroupMsg.parse({ message: 'need group' })).toEqual({ + ok: false, + field: 'group_id', + reason: 'is required', + }); + expect(sendGroupMsg.parse({ group_id: 888001, message: 'ok' })).toEqual({ + ok: true, + value: { + group_id: 888001, + message: 'ok', + auto_escape: false, + }, + }); + }); + + it('sends the group message and returns the receipt id', async () => { + const sendGroupMessage = vi.fn(async () => ({ messageId: 9201 })); + const response = await sendGroupMsg.toHandler(asCtx({ sendGroupMessage }))({ + group_id: 888001, + message: 'group body', + auto_escape: true, + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: { message_id: 9201 } }); + expect(sendGroupMessage.mock.calls).toEqual([[888001, 'group body', true]]); + }); +}); + +describe('get_msg', () => { + it('accepts a negative message_id and rejects 0', () => { + expect(getMsg.parse({ message_id: -2147483648 })).toEqual({ + ok: true, + value: { message_id: -2147483648 }, + }); + expect(getMsg.parse({ message_id: 0 })).toEqual({ + ok: false, + field: 'message_id', + reason: 'must not be 0', + }); + }); + + it('returns ACTION_FAILED when the store has no event', async () => { + const getMessage = vi.fn(() => null); + const response = await getMsg.toHandler(asCtx({ getMessage }))({ message_id: 424243 }); + + expect(response).toEqual({ + status: 'failed', + retcode: 100, + data: null, + wording: 'message not found', + }); + expect(getMessage.mock.calls).toEqual([[424243]]); + }); + + it('strips post_type/self_id and sets real_id from the stored message_id', async () => { + const stored: JsonObject = { + post_type: 'message', + self_id: 10001, + message_id: 424242, + message_type: 'group', + group_id: 314159, + user_id: 271828, + message: 'plain stored text', + time: 1700000000, + }; + const getMessage = vi.fn(() => stored); + const getImageInfo = vi.fn(async () => ({ url: 'https://unused.example/img' })); + const response = await getMsg.toHandler(asCtx({ getMessage, getImageInfo }))({ + message_id: 424242, + }); + + expect(response).toEqual({ + status: 'ok', + retcode: 0, + data: { + message_id: 424242, + message_type: 'group', + group_id: 314159, + user_id: 271828, + message: 'plain stored text', + time: 1700000000, + real_id: 424242, + }, + }); + expect(stored).toEqual({ + post_type: 'message', + self_id: 10001, + message_id: 424242, + message_type: 'group', + group_id: 314159, + user_id: 271828, + message: 'plain stored text', + time: 1700000000, + }); + expect(getImageInfo).not.toHaveBeenCalled(); + }); + + it('falls back to the request message_id when the stored event has none', async () => { + const getMessage = vi.fn(() => ({ + message_type: 'private', + user_id: 13579, + message: 'no stored id', + })); + const response = await getMsg.toHandler(asCtx({ getMessage }))({ message_id: 555001 }); + + expect(response).toEqual({ + status: 'ok', + retcode: 0, + data: { + message_type: 'private', + user_id: 13579, + message: 'no stored id', + real_id: 555001, + }, + }); + }); + + it('refreshes image URLs from file, then file_id, and skips unusable segments', async () => { + const fileImage: JsonObject = { + file: 'ABC.jpg', + file_id: 'SHOULD_NOT_WIN.jpg', + url: 'https://old.example/ABC.jpg', + }; + const fileIdImage: JsonObject = { + file_id: 'BY_FILE_ID.jpg', + url: 'https://old.example/file-id.jpg', + }; + const emptyFileImage: JsonObject = { + file: '', + file_id: 'SHOULD_NOT_USE.jpg', + url: 'https://old.example/empty-file.jpg', + }; + const keepEmptyUrl: JsonObject = { + file: 'KEEP_EMPTY.jpg', + url: 'https://old.example/keep-empty.jpg', + }; + const keepNull: JsonObject = { + file: 'KEEP_NULL.jpg', + url: 'https://old.example/keep-null.jpg', + }; + const keepNonString: JsonObject = { + file: 'KEEP_NONSTRING.jpg', + url: 'https://old.example/keep-nonstring.jpg', + }; + const noHandle: JsonObject = { + url: 'https://old.example/no-file.jpg', + }; + const stored: JsonObject = { + message_id: 777001, + message: [ + null, + 'skip-me', + 12, + { type: 'text', data: { text: 'plain' } }, + { type: 'image', data: 'not-object' }, + { type: 'image' }, + { type: 'image', data: emptyFileImage }, + { type: 'image', data: noHandle }, + { type: 'image', data: fileIdImage }, + { type: 'image', data: keepEmptyUrl }, + { type: 'image', data: keepNull }, + { type: 'image', data: keepNonString }, + { type: 'image', data: fileImage }, + ], + }; + const getImageInfo = vi.fn(async (file: string) => { + if (file === 'ABC.jpg') return { url: 'https://new.example/ABC.jpg?rkey=FRESH' }; + if (file === 'BY_FILE_ID.jpg') return { url: 'https://new.example/file-id.jpg?rkey=FRESH' }; + if (file === 'KEEP_EMPTY.jpg') return { url: '' }; + if (file === 'KEEP_NULL.jpg') return null; + if (file === 'KEEP_NONSTRING.jpg') return { url: 1 }; + return { url: 'https://should-not-apply.example/' }; + }); + + const response = await getMsg.toHandler(asCtx({ + getMessage: () => stored, + getImageInfo, + }))({ message_id: 777001 }); + + expect(getImageInfo.mock.calls).toEqual([ + ['BY_FILE_ID.jpg'], + ['KEEP_EMPTY.jpg'], + ['KEEP_NULL.jpg'], + ['KEEP_NONSTRING.jpg'], + ['ABC.jpg'], + ]); + expect(response).toEqual({ + status: 'ok', + retcode: 0, + data: { + message_id: 777001, + real_id: 777001, + message: [ + null, + 'skip-me', + 12, + { type: 'text', data: { text: 'plain' } }, + { type: 'image', data: 'not-object' }, + { type: 'image' }, + { type: 'image', data: emptyFileImage }, + { type: 'image', data: noHandle }, + { type: 'image', data: fileIdImage }, + { type: 'image', data: keepEmptyUrl }, + { type: 'image', data: keepNull }, + { type: 'image', data: keepNonString }, + { type: 'image', data: fileImage }, + ], + }, + }); + expect(fileImage.url).toBe('https://new.example/ABC.jpg?rkey=FRESH'); + expect(fileIdImage.url).toBe('https://new.example/file-id.jpg?rkey=FRESH'); + expect(emptyFileImage.url).toBe('https://old.example/empty-file.jpg'); + expect(keepEmptyUrl.url).toBe('https://old.example/keep-empty.jpg'); + expect(keepNull.url).toBe('https://old.example/keep-null.jpg'); + expect(keepNonString.url).toBe('https://old.example/keep-nonstring.jpg'); + expect(noHandle.url).toBe('https://old.example/no-file.jpg'); + }); + + it('keeps the stored image URL when getImageInfo throws', async () => { + const imageData: JsonObject = { + file: 'THROW.jpg', + url: 'https://old.example/throw.jpg', + }; + const getImageInfo = vi.fn(async () => { + throw new Error('rkey fetch failed'); + }); + const response = await getMsg.toHandler(asCtx({ + getMessage: () => ({ + message_id: 777002, + message: [{ type: 'image', data: imageData }], + }), + getImageInfo, + }))({ message_id: 777002 }); + + expect(getImageInfo.mock.calls).toEqual([['THROW.jpg']]); + expect(response).toEqual({ + status: 'ok', + retcode: 0, + data: { + message_id: 777002, + real_id: 777002, + message: [{ type: 'image', data: imageData }], + }, + }); + expect(imageData.url).toBe('https://old.example/throw.jpg'); + }); +}); + +describe('delete_msg', () => { + it('returns ACTION_FAILED when no retractable meta exists', async () => { + const getMessageMeta = vi.fn(() => null); + const deleteMessage = vi.fn(async () => {}); + const response = await deleteMsg.toHandler(asCtx({ getMessageMeta, deleteMessage }))({ + message_id: 424245, + }); + + expect(response).toEqual({ + status: 'failed', + retcode: 100, + data: null, + wording: 'message not found or not retractable', + }); + expect(getMessageMeta.mock.calls).toEqual([[424245]]); + expect(deleteMessage).not.toHaveBeenCalled(); + }); + + it('deletes with the stored meta and returns an empty ok payload', async () => { + const meta: MessageMeta = { + isGroup: true, + targetId: 314159, + sequence: 77, + sequenceAuthoritative: true, + eventName: 'group_message', + clientSequence: 0, + random: 123, + timestamp: 1700000000, + }; + const getMessageMeta = vi.fn(() => meta); + const deleteMessage = vi.fn(async () => {}); + const response = await deleteMsg.toHandler(asCtx({ getMessageMeta, deleteMessage }))({ + message_id: -424244, + }); + + expect(response).toEqual({ status: 'ok', retcode: 0, data: null }); + expect(getMessageMeta.mock.calls).toEqual([[-424244]]); + expect(deleteMessage.mock.calls).toEqual([[-424244, meta]]); + }); +}); diff --git a/packages/onebot/tests/actions-request.test.ts b/packages/onebot/tests/actions-request.test.ts new file mode 100644 index 00000000..d91b0533 --- /dev/null +++ b/packages/onebot/tests/actions-request.test.ts @@ -0,0 +1,547 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { ApiActionContext } from '../src/api-handler'; +import { ACTION_GROUPS } from '../src/actions'; + +// Load through the registry so `request.ts` → `api-handler` → `actions/index` +// finishes compiling before we read the request specs. Importing `./request` +// first leaves `group.actions` undefined in that cycle. +const requestGroup = ACTION_GROUPS.find((group) => group.category === '请求'); +if (!requestGroup) throw new Error('request action group missing'); +const actions = requestGroup.actions; + +const setFriendAddRequest = actions.find((action) => action.names[0] === 'set_friend_add_request'); +const setGroupAddRequest = actions.find((action) => action.names[0] === 'set_group_add_request'); +if (!setFriendAddRequest) throw new Error('set_friend_add_request action missing'); +if (!setGroupAddRequest) throw new Error('set_group_add_request action missing'); + +function friendCtx(handleRequest = vi.fn(async () => {})): { + ctx: ApiActionContext; + handleRequest: ReturnType; +} { + return { + handleRequest, + ctx: { + bridge: { apis: { friend: { handleRequest } } }, + } as unknown as ApiActionContext, + }; +} + +function groupCtx(handleGroupRequest = vi.fn(async () => {})): { + ctx: ApiActionContext; + handleGroupRequest: ReturnType; +} { + return { + handleGroupRequest, + ctx: { handleGroupRequest } as unknown as ApiActionContext, + }; +} + +describe('onebot/actions/request', () => { + it('exports the two request actions in authored order', () => { + expect(actions.map((action) => [...action.names])).toEqual([ + ['set_friend_add_request'], + ['set_group_add_request'], + ]); + expect(actions.map((action) => action.kind)).toEqual(['normal', 'normal']); + }); +}); + +describe('set_friend_add_request parse', () => { + it('requires a non-empty flag and defaults approve to true', () => { + expect(setFriendAddRequest.parse({ flag: 'flag-friend-7' })).toEqual({ + ok: true, + value: { flag: 'flag-friend-7', approve: true }, + }); + }); + + it('stringifies a numeric flag and keeps an explicit approve', () => { + expect(setFriendAddRequest.parse({ flag: 261237407, approve: false })).toEqual({ + ok: true, + value: { flag: '261237407', approve: false }, + }); + }); + + it('stringifies a boolean flag', () => { + expect(setFriendAddRequest.parse({ flag: true, approve: true })).toEqual({ + ok: true, + value: { flag: 'true', approve: true }, + }); + }); + + it('drops undeclared keys such as remark', () => { + expect(setFriendAddRequest.parse({ + flag: 'flag-friend-7', + approve: true, + remark: 'buddy', + })).toEqual({ + ok: true, + value: { flag: 'flag-friend-7', approve: true }, + }); + }); + + it.each([ + [true, true], + [false, false], + [1, true], + [0, false], + [-3, true], + ['true', true], + ['FALSE', false], + [' 1 ', true], + ['0', false], + ['yes', true], + ['NO', false], + ['on', true], + ['off', false], + ] as const)('coerces approve %j to %s', (approve, expected) => { + expect(setFriendAddRequest.parse({ flag: 'flag-friend-7', approve })).toEqual({ + ok: true, + value: { flag: 'flag-friend-7', approve: expected }, + }); + }); + + it('rejects a missing flag', () => { + expect(setFriendAddRequest.parse({})).toEqual({ + ok: false, + field: 'flag', + reason: 'is required', + }); + }); + + it('rejects an empty flag', () => { + expect(setFriendAddRequest.parse({ flag: '' })).toEqual({ + ok: false, + field: 'flag', + reason: 'must not be empty', + }); + }); + + it('rejects a non-stringifiable flag', () => { + expect(setFriendAddRequest.parse({ flag: { id: 1 } })).toEqual({ + ok: false, + field: 'flag', + reason: 'expected a string', + }); + }); + + it('rejects a null flag', () => { + expect(setFriendAddRequest.parse({ flag: null })).toEqual({ + ok: false, + field: 'flag', + reason: 'expected a string', + }); + }); + + it('rejects an unrecognised approve synonym', () => { + expect(setFriendAddRequest.parse({ flag: 'flag-friend-7', approve: 'maybe' })).toEqual({ + ok: false, + field: 'approve', + reason: 'expected a boolean', + }); + }); +}); + +describe('set_friend_add_request toHandler', () => { + it('forwards the flag and default approve, returning an empty ok payload', async () => { + const { ctx, handleRequest } = friendCtx(); + + await expect(setFriendAddRequest.toHandler(ctx)({ flag: 'flag-friend-7' })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(handleRequest.mock.calls).toEqual([['flag-friend-7', true]]); + }); + + it('forwards an explicit rejection and ignores remark', async () => { + const { ctx, handleRequest } = friendCtx(); + + await expect(setFriendAddRequest.toHandler(ctx)({ + flag: 'u_abc', + approve: false, + remark: 'buddy', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(handleRequest.mock.calls).toEqual([['u_abc', false]]); + }); + + it('stringifies a numeric flag before calling the friend API', async () => { + const { ctx, handleRequest } = friendCtx(); + + await expect(setFriendAddRequest.toHandler(ctx)({ flag: 10001, approve: 'yes' })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(handleRequest.mock.calls).toEqual([['10001', true]]); + }); + + it('returns BAD_REQUEST for an empty flag without calling the friend API', async () => { + const { ctx, handleRequest } = friendCtx(); + + await expect(setFriendAddRequest.toHandler(ctx)({ flag: '' })) + .resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'flag: must not be empty', + }); + + expect(handleRequest).not.toHaveBeenCalled(); + }); + + it('returns BAD_REQUEST naming a missing flag', async () => { + const { ctx, handleRequest } = friendCtx(); + + await expect(setFriendAddRequest.toHandler(ctx)({})) + .resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'flag: is required', + }); + + expect(handleRequest).not.toHaveBeenCalled(); + }); +}); + +describe('set_friend_add_request describe', () => { + it('documents the friend-request params and input schema', () => { + const doc = setFriendAddRequest.describe(); + + expect(doc.name).toBe('set_friend_add_request'); + expect(doc.aliases).toEqual([]); + expect(doc.summary).toBe('处理好友添加请求'); + expect(doc.readOnly).toBe(false); + expect(doc.returns).toBeUndefined(); + expect(doc.returnsSchema).toBeUndefined(); + expect(doc.stream).toBeUndefined(); + expect(doc.invariants).toEqual([]); + expect(doc.params).toEqual([ + { + name: 'flag', + type: 'string', + required: true, + schema: { type: 'string', minLength: 1 }, + }, + { + name: 'approve', + type: 'bool', + required: false, + default: true, + schema: { type: 'boolean' }, + }, + ]); + expect(doc.inputSchema).toEqual({ + type: 'object', + properties: { + flag: { type: 'string', minLength: 1 }, + approve: { type: 'boolean', default: true }, + }, + required: ['flag'], + additionalProperties: true, + }); + }); +}); + +describe('set_group_add_request parse', () => { + it('requires flag and defaults approve, reason, and the raw type fields', () => { + expect(setGroupAddRequest.parse({ flag: 'slreq:1:123456:999:22:1' })).toEqual({ + ok: true, + value: { + flag: 'slreq:1:123456:999:22:1', + sub_type: undefined, + type: undefined, + approve: true, + reason: '', + }, + }); + }); + + it('keeps raw sub_type and type values without coercing them', () => { + expect(setGroupAddRequest.parse({ + flag: 'flag-group-9', + sub_type: { kind: 'invite' }, + type: [1, 2], + approve: 0, + reason: 404, + })).toEqual({ + ok: true, + value: { + flag: 'flag-group-9', + sub_type: { kind: 'invite' }, + type: [1, 2], + approve: false, + reason: '404', + }, + }); + }); + + it('stringifies a numeric flag and a boolean reason', () => { + expect(setGroupAddRequest.parse({ + flag: 261237407, + sub_type: 'add', + type: 'invite', + approve: 'off', + reason: true, + })).toEqual({ + ok: true, + value: { + flag: '261237407', + sub_type: 'add', + type: 'invite', + approve: false, + reason: 'true', + }, + }); + }); + + it('accepts an explicit empty reason', () => { + expect(setGroupAddRequest.parse({ + flag: 'invite:999:u_i', + reason: '', + })).toEqual({ + ok: true, + value: { + flag: 'invite:999:u_i', + sub_type: undefined, + type: undefined, + approve: true, + reason: '', + }, + }); + }); + + it('rejects a missing flag', () => { + expect(setGroupAddRequest.parse({ sub_type: 'add' })).toEqual({ + ok: false, + field: 'flag', + reason: 'is required', + }); + }); + + it('rejects an empty flag', () => { + expect(setGroupAddRequest.parse({ flag: '' })).toEqual({ + ok: false, + field: 'flag', + reason: 'must not be empty', + }); + }); + + it('rejects a non-string reason', () => { + expect(setGroupAddRequest.parse({ flag: 'flag-group-9', reason: { text: 'no' } })).toEqual({ + ok: false, + field: 'reason', + reason: 'expected a string', + }); + }); + + it('rejects a null reason', () => { + expect(setGroupAddRequest.parse({ flag: 'flag-group-9', reason: null })).toEqual({ + ok: false, + field: 'reason', + reason: 'expected a string', + }); + }); +}); + +describe('set_group_add_request toHandler', () => { + it('defaults sub_type to add, approve to true, and reason to empty', async () => { + const { ctx, handleGroupRequest } = groupCtx(); + + await expect(setGroupAddRequest.toHandler(ctx)({ flag: 'slreq:1:123456:999:22:1' })) + .resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(handleGroupRequest.mock.calls).toEqual([ + ['slreq:1:123456:999:22:1', 'add', true, ''], + ]); + }); + + it('prefers a present sub_type over type', async () => { + const { ctx, handleGroupRequest } = groupCtx(); + + await expect(setGroupAddRequest.toHandler(ctx)({ + flag: 'flag-group-9', + sub_type: 'invite', + type: 'add', + approve: false, + reason: 'no', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(handleGroupRequest.mock.calls).toEqual([ + ['flag-group-9', 'invite', false, 'no'], + ]); + }); + + it('falls back from a missing sub_type to type', async () => { + const { ctx, handleGroupRequest } = groupCtx(); + + await expect(setGroupAddRequest.toHandler(ctx)({ + flag: 'add:999:u_t', + type: 'add', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(handleGroupRequest.mock.calls).toEqual([ + ['add:999:u_t', 'add', true, ''], + ]); + }); + + it('keeps an empty-string sub_type instead of falling back to type', async () => { + const { ctx, handleGroupRequest } = groupCtx(); + + await expect(setGroupAddRequest.toHandler(ctx)({ + flag: 'flag-group-9', + sub_type: '', + type: 'invite', + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(handleGroupRequest.mock.calls).toEqual([ + ['flag-group-9', '', true, ''], + ]); + }); + + it.each([ + [{ sub_type: 2, type: 'add' }, '2'], + [{ sub_type: 0 }, '0'], + [{ sub_type: true, type: 'add' }, 'true'], + [{ sub_type: false }, 'false'], + [{ type: 8 }, '8'], + [{ type: false }, 'false'], + [{ type: '' }, ''], + ] as const)('stringifies a primitive locator %j as %s', async (params, subType) => { + const { ctx, handleGroupRequest } = groupCtx(); + + await expect(setGroupAddRequest.toHandler(ctx)({ + flag: 'flag-group-9', + ...params, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(handleGroupRequest.mock.calls).toEqual([ + ['flag-group-9', subType, true, ''], + ]); + }); + + it.each([ + [{ sub_type: { kind: 'invite' }, type: 'invite' }, 'invite'], + [{ sub_type: ['invite'], type: 'add' }, 'add'], + [{ sub_type: null, type: 'invite' }, 'invite'], + [{ sub_type: null, type: null }, 'add'], + [{ type: { kind: 'add' } }, 'add'], + [{ type: null }, 'add'], + ])('falls through a non-primitive locator %j to %s', async (params, subType) => { + const { ctx, handleGroupRequest } = groupCtx(); + + await expect(setGroupAddRequest.toHandler(ctx)({ + flag: 'flag-group-9', + ...params, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(handleGroupRequest.mock.calls).toEqual([ + ['flag-group-9', subType, true, ''], + ]); + }); + + it('stringifies a numeric flag and reason', async () => { + const { ctx, handleGroupRequest } = groupCtx(); + + await expect(setGroupAddRequest.toHandler(ctx)({ + flag: 55, + sub_type: 'add', + approve: 'no', + reason: 0, + })).resolves.toEqual({ status: 'ok', retcode: 0, data: null }); + + expect(handleGroupRequest.mock.calls).toEqual([ + ['55', 'add', false, '0'], + ]); + }); + + it('returns BAD_REQUEST for an empty flag without handling the group request', async () => { + const { ctx, handleGroupRequest } = groupCtx(); + + await expect(setGroupAddRequest.toHandler(ctx)({ flag: '', sub_type: 'add' })) + .resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'flag: must not be empty', + }); + + expect(handleGroupRequest).not.toHaveBeenCalled(); + }); + + it('returns BAD_REQUEST for a non-string reason without handling the group request', async () => { + const { ctx, handleGroupRequest } = groupCtx(); + + await expect(setGroupAddRequest.toHandler(ctx)({ + flag: 'flag-group-9', + reason: ['no'], + })).resolves.toEqual({ + status: 'failed', + retcode: 1400, + data: null, + wording: 'reason: expected a string', + }); + + expect(handleGroupRequest).not.toHaveBeenCalled(); + }); +}); + +describe('set_group_add_request describe', () => { + it('documents the group-request params including raw type fields', () => { + const doc = setGroupAddRequest.describe(); + + expect(doc.name).toBe('set_group_add_request'); + expect(doc.aliases).toEqual([]); + expect(doc.summary).toBe('处理加群请求'); + expect(doc.readOnly).toBe(false); + expect(doc.returns).toBeUndefined(); + expect(doc.returnsSchema).toBeUndefined(); + expect(doc.stream).toBeUndefined(); + expect(doc.invariants).toEqual([]); + expect(doc.params).toEqual([ + { + name: 'flag', + type: 'string', + required: true, + schema: { type: 'string', minLength: 1 }, + }, + { + name: 'sub_type', + type: 'raw', + required: false, + default: undefined, + schema: {}, + }, + { + name: 'type', + type: 'raw', + required: false, + default: undefined, + schema: {}, + }, + { + name: 'approve', + type: 'bool', + required: false, + default: true, + schema: { type: 'boolean' }, + }, + { + name: 'reason', + type: 'string', + required: false, + default: '', + schema: { type: 'string' }, + }, + ]); + expect(doc.inputSchema).toEqual({ + type: 'object', + properties: { + flag: { type: 'string', minLength: 1 }, + sub_type: {}, + type: {}, + approve: { type: 'boolean', default: true }, + reason: { type: 'string', default: '' }, + }, + required: ['flag'], + additionalProperties: true, + }); + }); +}); diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index d7b31e07..a26820f4 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -2209,3 +2209,46 @@ describe('extended-actions / get_fileset_id', () => { expect(res).toMatchObject({ status: 'failed', retcode: 100 }); }); }); + +describe('extended-actions / create_flash_task (#361)', () => { + it('accepts a path string', async () => { + const createFlashTask = vi.fn(async () => ({ filesetId: 'fs-1' })); + const bridge = fakeBridge({ apis: { flashTransfer: { createFlashTask } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('create_flash_task', { files: '/tmp/a.pdf' }); + expect(res).toMatchObject({ status: 'ok', data: { fileset_id: 'fs-1', task_id: 'fs-1' } }); + expect(createFlashTask).toHaveBeenCalledWith([{ file: '/tmp/a.pdf' }], undefined, undefined); + }); + + it('accepts { file, name } and forwards the per-file name', async () => { + const createFlashTask = vi.fn(async () => ({ filesetId: 'fs-2' })); + const bridge = fakeBridge({ apis: { flashTransfer: { createFlashTask } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('create_flash_task', { + files: { file: '/tmp/uuid__a.pdf', name: 'a.pdf' }, + name: '卡片', + }); + expect(res.status).toBe('ok'); + expect(createFlashTask).toHaveBeenCalledWith( + [{ file: '/tmp/uuid__a.pdf', name: 'a.pdf' }], + '卡片', + undefined, + ); + }); + + it('rejects an empty files value', async () => { + const createFlashTask = vi.fn(async () => ({ filesetId: 'fs' })); + const bridge = fakeBridge({ apis: { flashTransfer: { createFlashTask } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('create_flash_task', { files: [] }); + expect(res).toMatchObject({ status: 'failed', retcode: 1400, wording: 'files must not be empty' }); + expect(createFlashTask).not.toHaveBeenCalled(); + }); + + it('rejects a non-string per-file name', async () => { + const createFlashTask = vi.fn(async () => ({ filesetId: 'fs' })); + const bridge = fakeBridge({ apis: { flashTransfer: { createFlashTask } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('create_flash_task', { + files: { file: '/tmp/a.pdf', name: 1 }, + }); + expect(res).toMatchObject({ status: 'failed', retcode: 1400, wording: 'files[].name must be a string' }); + expect(createFlashTask).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/onebot/tests/flash-file-segment.test.ts b/packages/onebot/tests/flash-file-segment.test.ts index 91a8278f..c136932f 100644 --- a/packages/onebot/tests/flash-file-segment.test.ts +++ b/packages/onebot/tests/flash-file-segment.test.ts @@ -5,15 +5,21 @@ import type { MessageElement } from '@snowluma/protocol/events'; // The receive-side flash_file codec (#199/#200). Sending is a separate action // (send_flash_msg), so there is no fromSegment. describe('flash_file element → OneBot segment (#199/#200)', () => { - it('maps filesetId/fileName/sceneType → file_set_id/title/scene_type', async () => { - const el: MessageElement = { type: 'flash_file', filesetId: 'fs-1', fileName: 'a.pdf', sceneType: 2 }; + it('maps filesetId/fileName/sceneType/thumbUrl → file_set_id/title/scene_type/thumb', async () => { + const el: MessageElement = { + type: 'flash_file', filesetId: 'fs-1', fileName: 'a.pdf', sceneType: 2, + thumbUrl: 'https://example.test/cover.jpg', + }; const seg = await ELEMENT_CODECS.flash_file!.toSegment!(el, {} as never); - expect(seg).toEqual({ type: 'flash_file', data: { title: 'a.pdf', file_set_id: 'fs-1', scene_type: 2 } }); + expect(seg).toEqual({ + type: 'flash_file', + data: { title: 'a.pdf', file_set_id: 'fs-1', scene_type: 2, thumb: 'https://example.test/cover.jpg' }, + }); }); it('defaults missing fields to empty / 0', async () => { const seg = await ELEMENT_CODECS.flash_file!.toSegment!({ type: 'flash_file' } as MessageElement, {} as never); - expect(seg).toEqual({ type: 'flash_file', data: { title: '', file_set_id: '', scene_type: 0 } }); + expect(seg).toEqual({ type: 'flash_file', data: { title: '', file_set_id: '', scene_type: 0, thumb: '' } }); }); it('is receive-only (no fromSegment)', () => { diff --git a/packages/onebot/tests/instance-context.test.ts b/packages/onebot/tests/instance-context.test.ts new file mode 100644 index 00000000..f8d1e2ea --- /dev/null +++ b/packages/onebot/tests/instance-context.test.ts @@ -0,0 +1,1227 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { GroupMemberInfo, GroupRequestInfo, QQGroupInfo } from '@snowluma/protocol/qq-info'; +import { buildApiContext, type OneBotInstanceContext } from '../src/instance-context'; +import { + GROUP_MESSAGE_EVENT, + PRIVATE_NT_MESSAGE_EVENT, + hashMessageIdInt32, +} from '../src/message-id'; +import { TempSessionStore } from '../src/temp-session-store'; +import type { JsonObject, MessageMeta, OneBotConfig } from '../src/types'; + +const SELF_UIN = '10001'; +const SELF_ID = 10001; +const PEER_ID = 20002; +const GROUP_ID = 710001; +const RECEIPT = { + messageId: 900001, + sequence: 77, + clientSequence: 14, + random: 424242, + timestamp: 1_725_000_000, +}; + +function groupMeta(overrides: Partial = {}): MessageMeta { + return { + isGroup: true, + targetId: GROUP_ID, + sequence: 42, + sequenceAuthoritative: true, + eventName: GROUP_MESSAGE_EVENT, + clientSequence: 0, + random: 7, + timestamp: 1_725_000_000, + ...overrides, + }; +} + +function privateMeta(overrides: Partial = {}): MessageMeta { + return { + isGroup: false, + targetId: PEER_ID, + sequence: 42, + sequenceAuthoritative: true, + eventName: PRIVATE_NT_MESSAGE_EVENT, + clientSequence: 9, + random: 7, + timestamp: 1_725_000_000, + ...overrides, + }; +} + +function makeGroup(groupId: number, groupName: string, extras: Partial = {}): QQGroupInfo { + return { + groupId, + groupName, + remark: '', + memberCount: 3, + memberMax: 200, + members: new Map(), + ...extras, + }; +} + +function makeMember(uin: number, nickname: string, extras: Partial = {}): GroupMemberInfo { + return { + uin, + uid: `u_${uin}`, + nickname, + card: '', + isRobot: false, + role: 'member', + level: 4, + title: '', + joinTime: 1_700_000_100, + lastSentTime: 1_700_000_200, + shutUpTime: 0, + ...extras, + }; +} + +function makeRequest(overrides: Partial = {}): GroupRequestInfo { + return { + groupId: 710010, + groupName: 'sys-group', + targetUid: 'u_20002', + targetUin: PEER_ID, + targetName: 'applicant', + invitorUid: 'u_inviter', + invitorUin: 30003, + invitorName: 'inviter', + operatorUid: 'u_operator', + operatorUin: 40004, + operatorName: 'operator', + sequence: 888, + state: 1, + notifyType: 7, + eventType: 22, + comment: 'please add', + filtered: false, + ...overrides, + }; +} + +function makeRef(overrides: { + uin?: string; + selfId?: number; + identity?: Record; + apis?: Record>; + messageStore?: Record; + mediaStore?: Record; + reactionStore?: Record; + converterCtx?: Record; + extraBridge?: Record; +} = {}): { + ref: OneBotInstanceContext; + api: ReturnType; + dispatchEvent: ReturnType; + cacheMessageMeta: ReturnType; + events: Map; + metas: Map; +} { + const events = new Map(); + const metas = new Map(); + const dispatchEvent = vi.fn(); + const cacheMessageMeta = vi.fn((messageId: number, meta: MessageMeta) => { + metas.set(messageId, meta); + }); + + const messageStore = { + findEvent: (messageId: number) => events.get(messageId) ?? null, + findMeta: (messageId: number) => metas.get(messageId) ?? null, + storeMetas: (entries: ReadonlyArray<{ messageId: number; meta: MessageMeta }>) => { + for (const entry of entries) metas.set(entry.messageId, entry.meta); + }, + storeEvent: ( + messageId: number, + _isGroup: boolean, + _sessionId: number, + _sequence: number, + _eventName: string, + event: JsonObject, + ) => { + events.set(messageId, event); + }, + listReadSessions: vi.fn(() => ({ groupIds: [GROUP_ID], privateUserIds: [PEER_ID] })), + resolveReplySequence: () => null, + findLatestAuthoritativeSequence: () => null, + listSessionEvents: vi.fn(() => []), + ...overrides.messageStore, + }; + + const bridge = { + identity: { + uin: SELF_UIN, + nickname: 'SnowLuma', + groups: [] as QQGroupInfo[], + friends: [] as Array<{ uin: number; nickname: string; remark: string }>, + findGroup: () => null, + findGroupMember: () => null, + findUserProfile: () => null, + findFriend: () => null, + findUinByUid: () => undefined, + ...overrides.identity, + }, + apis: { + message: { + sendPrivate: vi.fn(async () => RECEIPT), + sendGroup: vi.fn(async () => RECEIPT), + sendGroupTempMessage: vi.fn(async () => RECEIPT), + recallGroup: vi.fn(async () => undefined), + recallPrivate: vi.fn(async () => undefined), + getGroupHistory: vi.fn(async () => []), + getC2cHistory: vi.fn(async () => []), + getC2cLatestHistory: vi.fn(async () => []), + ...overrides.apis?.message, + }, + contacts: { + fetchFriendList: vi.fn(async () => []), + fetchGroupList: vi.fn(async () => []), + fetchGroupDetail: vi.fn(async () => null), + fetchGroupMemberList: vi.fn(async () => []), + fetchUserProfile: vi.fn(async () => { + throw new Error('no profile'); + }), + fetchGroupRequests: vi.fn(async () => []), + fetchDownloadRKeys: vi.fn(async () => []), + findGroupInviteCardGroupBySequence: vi.fn(() => undefined), + getGroupInviteCardSequence: vi.fn(() => undefined), + ...overrides.apis?.contacts, + }, + groupFile: { + list: vi.fn(async () => ({ files: [], folders: [] })), + getPttUrl: vi.fn(async () => ''), + getPrivatePttUrl: vi.fn(async () => ''), + ...overrides.apis?.groupFile, + }, + groupAdmin: { + setAddRequest: vi.fn(async () => undefined), + ...overrides.apis?.groupAdmin, + }, + interaction: { + setReaction: vi.fn(async () => undefined), + fetchReactionSummary: vi.fn(async () => []), + setEssence: vi.fn(async () => undefined), + ...overrides.apis?.interaction, + }, + forward: { + upload: vi.fn(async () => 'forward-res-id'), + fetch: vi.fn(async () => []), + ...overrides.apis?.forward, + }, + extras: { + translatePttToText: vi.fn(async () => ''), + ...overrides.apis?.extras, + }, + }, + resolveUserUid: vi.fn(async () => 'u_peer'), + ...overrides.extraBridge, + }; + + const ref = { + uin: overrides.uin ?? SELF_UIN, + selfId: overrides.selfId ?? SELF_ID, + bridge, + messageStore, + mediaStore: { + findImage: () => null, + findRecord: () => null, + updateRecordUrl: vi.fn(), + ...overrides.mediaStore, + }, + reactionStore: { + listUsers: vi.fn(() => []), + countUsers: vi.fn(() => 0), + ...overrides.reactionStore, + }, + tempSessions: new TempSessionStore(), + converterCtx: { + selfId: overrides.selfId ?? SELF_ID, + imageUrlResolver: null, + mediaUrlResolver: null, + messageIdResolver: null, + mediaSegmentSink: null, + ...overrides.converterCtx, + }, + config: { + networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] }, + } as OneBotConfig, + cacheMessageMeta, + dispatchEvent, + } as unknown as OneBotInstanceContext; + + return { + ref, + api: buildApiContext(ref), + dispatchEvent, + cacheMessageMeta, + events, + metas, + }; +} + +describe('buildApiContext capabilities', () => { + it('reports the account as online and able to send image or record', () => { + const { api } = makeRef(); + expect(api.isOnline()).toBe(true); + expect(api.canSendImage()).toBe(true); + expect(api.canSendRecord()).toBe(true); + }); +}); + +describe('buildApiContext getLoginInfo', () => { + it('parses uin and uses the identity nickname', () => { + const { api } = makeRef({ + uin: '188001', + identity: { nickname: 'login-nick' }, + }); + expect(api.getLoginInfo()).toEqual({ userId: 188001, nickname: 'login-nick' }); + }); + + it('falls back to the uin string when the nickname is empty', () => { + const { api } = makeRef({ + uin: '188002', + identity: { nickname: '' }, + }); + expect(api.getLoginInfo()).toEqual({ userId: 188002, nickname: '188002' }); + }); + + it('uses userId 0 when uin is not a number', () => { + const { api } = makeRef({ + uin: 'not-a-uin', + identity: { nickname: 'fallback-nick' }, + }); + expect(api.getLoginInfo()).toEqual({ userId: 0, nickname: 'fallback-nick' }); + }); +}); + +describe('buildApiContext message-store passthroughs', () => { + it('reads events and metas through the message store', () => { + const storedEvent = { + post_type: 'message', + message_type: 'group', + message_id: -55, + raw_message: 'stored', + }; + const storedMeta = groupMeta({ sequence: 91 }); + const { api, events, metas } = makeRef(); + events.set(-55, storedEvent); + metas.set(-55, storedMeta); + + expect(api.getMessage(-55)).toEqual({ + post_type: 'message', + message_type: 'group', + message_id: -55, + raw_message: 'stored', + }); + expect(api.getMessage(1)).toBeNull(); + expect(api.getMessageMeta(-55)).toEqual({ + isGroup: true, + targetId: GROUP_ID, + sequence: 91, + sequenceAuthoritative: true, + eventName: GROUP_MESSAGE_EVENT, + clientSequence: 0, + random: 7, + timestamp: 1_725_000_000, + }); + }); + + it('stores meta batches on the message store', () => { + const storeMetas = vi.fn(); + const { api } = makeRef({ messageStore: { storeMetas } }); + const entries = [{ messageId: -12, meta: privateMeta({ sequence: 8 }) }]; + + api.cacheMessageMetas(entries); + + expect(storeMetas).toHaveBeenCalledOnce(); + expect(storeMetas).toHaveBeenCalledWith(entries); + }); + + it('lists read sessions from the current identity group ids', () => { + const listReadSessions = vi.fn(() => ({ + groupIds: [710101, 710102], + privateUserIds: [50001], + })); + const { api } = makeRef({ + identity: { + groups: [makeGroup(710101, 'A'), makeGroup(710102, 'B')], + }, + messageStore: { listReadSessions }, + }); + + expect(api.listReadSessions()).toEqual({ + groupIds: [710101, 710102], + privateUserIds: [50001], + }); + expect(listReadSessions).toHaveBeenCalledWith([710101, 710102]); + }); +}); + +describe('buildApiContext setMsgEmojiLike', () => { + it('throws when the message is missing', async () => { + const { api } = makeRef(); + await expect(api.setMsgEmojiLike(-1, '76', true)).rejects.toThrow('message not found'); + }); + + it('throws when the message is private', async () => { + const { api, metas } = makeRef(); + metas.set(-2, privateMeta()); + await expect(api.setMsgEmojiLike(-2, '76', true)) + .rejects.toThrow('emoji reactions are not supported on private messages'); + }); + + it('throws when the stored sequence is not authoritative', async () => { + const { api, metas } = makeRef(); + metas.set(-3, groupMeta({ sequenceAuthoritative: false, sequence: 42 })); + await expect(api.setMsgEmojiLike(-3, '76', true)) + .rejects.toThrow('message has no authoritative QQ sequence'); + }); + + it('throws when the stored sequence is not a positive integer', async () => { + const { api, metas } = makeRef(); + metas.set(-4, groupMeta({ sequence: 0 })); + await expect(api.setMsgEmojiLike(-4, '76', true)) + .rejects.toThrow('message has no authoritative QQ sequence'); + }); + + it('sets the reaction on the group message', async () => { + const setReaction = vi.fn(async () => undefined); + const { api, metas, ref } = makeRef({ + apis: { interaction: { setReaction, fetchReactionSummary: vi.fn(async () => []) } }, + }); + metas.set(-5, groupMeta({ targetId: 710201, sequence: 4242 })); + + await api.setMsgEmojiLike(-5, '76', true); + + expect(setReaction).toHaveBeenCalledWith(710201, 4242, '76', true); + expect(ref.bridge.apis.interaction.setReaction).toHaveBeenCalledOnce(); + }); + + it('clears the reaction when set is false', async () => { + const setReaction = vi.fn(async () => undefined); + const { api, metas } = makeRef({ + apis: { interaction: { setReaction, fetchReactionSummary: vi.fn(async () => []) } }, + }); + metas.set(-6, groupMeta({ targetId: 710202, sequence: 88 })); + + await api.setMsgEmojiLike(-6, '144', false); + + expect(setReaction).toHaveBeenCalledWith(710202, 88, '144', false); + }); +}); + +describe('buildApiContext fetchEmojiLikeUsers', () => { + it('throws when the message is missing', async () => { + const { api } = makeRef(); + await expect(api.fetchEmojiLikeUsers(-1, '76', 20)).rejects.toThrow('message not found'); + }); + + it('throws when the message is private', async () => { + const { api, metas } = makeRef(); + metas.set(-2, privateMeta()); + await expect(api.fetchEmojiLikeUsers(-2, '76', 20)) + .rejects.toThrow('emoji reactions are not supported on private messages'); + }); + + it('throws when the stored sequence is not authoritative', async () => { + const { api, metas } = makeRef(); + metas.set(-3, groupMeta({ sequence: 1.5 })); + await expect(api.fetchEmojiLikeUsers(-3, '76', 20)) + .rejects.toThrow('message has no authoritative QQ sequence'); + }); + + it('maps cached users and defaults the offset to 0', async () => { + const listUsers = vi.fn(() => [ + { operatorUin: 20002, operatorUid: 'u_20002', setAt: 1_700_000_001 }, + ]); + const countUsers = vi.fn(() => 1); + const fetchReactionSummary = vi.fn(async () => [{ emojiId: '76', count: 1 }]); + const { api, metas } = makeRef({ + reactionStore: { listUsers, countUsers }, + apis: { interaction: { setReaction: vi.fn(), fetchReactionSummary } }, + }); + metas.set(-7, groupMeta({ targetId: 710301, sequence: 55 })); + + await expect(api.fetchEmojiLikeUsers(-7, '76', 20)).resolves.toEqual({ + users: [{ uin: 20002, uid: 'u_20002', setAt: 1_700_000_001 }], + cachedCount: 1, + serverCount: 1, + complete: true, + }); + expect(listUsers).toHaveBeenCalledWith(710301, 55, '76', 20, 0); + expect(countUsers).toHaveBeenCalledWith(710301, 55, '76'); + }); + + it('forwards a custom offset to the reaction store', async () => { + const listUsers = vi.fn(() => []); + const countUsers = vi.fn(() => 0); + const { api, metas } = makeRef({ + reactionStore: { listUsers, countUsers }, + }); + metas.set(-8, groupMeta({ targetId: 710302, sequence: 9 })); + + await api.fetchEmojiLikeUsers(-8, '144', 5, 3); + + expect(listUsers).toHaveBeenCalledWith(710302, 9, '144', 5, 3); + }); + + it('uses the matching server summary count and reports incomplete when cache is short', async () => { + const { api, metas } = makeRef({ + reactionStore: { + listUsers: () => [{ operatorUin: 1, operatorUid: 'u_1', setAt: 10 }], + countUsers: () => 2, + }, + apis: { + interaction: { + setReaction: vi.fn(), + fetchReactionSummary: vi.fn(async () => [ + { emojiId: '99', count: 4 }, + { emojiId: '76', count: 8 }, + ]), + }, + }, + }); + metas.set(-9, groupMeta({ targetId: 710303, sequence: 12 })); + + await expect(api.fetchEmojiLikeUsers(-9, '76', 10)).resolves.toEqual({ + users: [{ uin: 1, uid: 'u_1', setAt: 10 }], + cachedCount: 2, + serverCount: 8, + complete: false, + }); + }); + + it('keeps the cached count when the summary has no matching emoji', async () => { + const { api, metas } = makeRef({ + reactionStore: { + listUsers: () => [], + countUsers: () => 3, + }, + apis: { + interaction: { + setReaction: vi.fn(), + fetchReactionSummary: vi.fn(async () => [{ emojiId: '99', count: 9 }]), + }, + }, + }); + metas.set(-10, groupMeta({ targetId: 710304, sequence: 13 })); + + await expect(api.fetchEmojiLikeUsers(-10, '76', 10)).resolves.toEqual({ + users: [], + cachedCount: 3, + serverCount: 3, + complete: true, + }); + }); + + it('reports complete when the cache already exceeds the server count', async () => { + const { api, metas } = makeRef({ + reactionStore: { + listUsers: () => [], + countUsers: () => 6, + }, + apis: { + interaction: { + fetchReactionSummary: vi.fn(async () => [{ emojiId: '76', count: 5 }]), + }, + }, + }); + metas.set(-12, groupMeta({ targetId: 710306, sequence: 15 })); + + await expect(api.fetchEmojiLikeUsers(-12, '76', 10)).resolves.toEqual({ + users: [], + cachedCount: 6, + serverCount: 5, + complete: true, + }); + }); + + it('keeps the cached count when the summary fetch fails', async () => { + const { api, metas } = makeRef({ + reactionStore: { + listUsers: () => [], + countUsers: () => 4, + }, + apis: { + interaction: { + setReaction: vi.fn(), + fetchReactionSummary: vi.fn(async () => { + throw new Error('summary down'); + }), + }, + }, + }); + metas.set(-11, groupMeta({ targetId: 710305, sequence: 14 })); + + await expect(api.fetchEmojiLikeUsers(-11, '76', 10)).resolves.toEqual({ + users: [], + cachedCount: 4, + serverCount: 4, + complete: true, + }); + }); +}); + +describe('buildApiContext recall and essence', () => { + it('recalls a group message by target and sequence', async () => { + const recallGroup = vi.fn(async () => undefined); + const { api, ref } = makeRef({ + apis: { message: { recallGroup } }, + }); + + await api.deleteMessage(-20, groupMeta({ targetId: 710401, sequence: 33 })); + + expect(recallGroup).toHaveBeenCalledWith(710401, 33); + expect(ref.bridge.apis.message.recallPrivate).not.toHaveBeenCalled(); + }); + + it('recalls a private message with client sequence, random and timestamp', async () => { + const { api, ref } = makeRef(); + const meta = privateMeta({ + targetId: 20099, + clientSequence: 18, + sequence: 66, + random: 1234, + timestamp: 1_725_111_000, + }); + + await api.deleteMessage(-21, meta); + + expect(ref.bridge.apis.message.recallPrivate).toHaveBeenCalledWith( + 20099, + 18, + 66, + 1234, + 1_725_111_000, + ); + expect(ref.bridge.apis.message.recallGroup).not.toHaveBeenCalled(); + }); + + it('enables and disables essence through the same interaction API', async () => { + const setEssence = vi.fn(async () => undefined); + const { api, metas, ref } = makeRef({ + apis: { interaction: { setReaction: vi.fn(), fetchReactionSummary: vi.fn(), setEssence } }, + }); + metas.set(-22, groupMeta({ targetId: 710402, sequence: 50, random: 9 })); + + await api.setEssenceMsg(-22); + await api.deleteEssenceMsg(-22); + + expect(setEssence).toHaveBeenNthCalledWith(1, 710402, 50, 9, true); + expect(setEssence).toHaveBeenNthCalledWith(2, 710402, 50, 9, false); + expect(ref.bridge.apis.interaction.setEssence).toHaveBeenCalledTimes(2); + }); +}); + +describe('buildApiContext handleGroupRequest', () => { + it('approves a canonical flag and ignores the unused sub_type argument', async () => { + const setAddRequest = vi.fn(async () => undefined); + const fetchGroupRequests = vi.fn(async () => []); + const { api, ref } = makeRef({ + apis: { + groupAdmin: { setAddRequest }, + contacts: { fetchGroupRequests }, + }, + }); + + await api.handleGroupRequest('slreq:1:123456:710410:22:1', 'add', true, 'welcome'); + + expect(setAddRequest).toHaveBeenCalledWith(710410, 123456, 22, true, 'welcome', true); + expect(fetchGroupRequests).not.toHaveBeenCalled(); + expect(ref.bridge.apis.groupAdmin.setAddRequest).toHaveBeenCalledOnce(); + }); +}); + +describe('buildApiContext contact reads', () => { + it('maps the friend list into OneBot fields', async () => { + const { api } = makeRef({ + apis: { + contacts: { + fetchFriendList: vi.fn(async () => [ + { uin: 22222, uid: 'u_22222', nickname: 'alice', remark: 'best-friend' }, + ]), + }, + }, + }); + + await expect(api.getFriendList()).resolves.toEqual([ + { user_id: 22222, nickname: 'alice', remark: 'best-friend' }, + ]); + }); + + it('maps the cached group list and forces a refresh when noCache is true', async () => { + const groups = [makeGroup(710501, 'Group A', { + remark: 'work', + createTime: 100, + level: 2, + memo: 'rules', + allMuted: true, + })]; + const fetchGroupList = vi.fn(async () => groups); + const { api } = makeRef({ + identity: { groups }, + apis: { contacts: { fetchGroupList } }, + }); + + await expect(api.getGroupList()).resolves.toEqual([{ + group_id: 710501, + group_name: 'Group A', + group_remark: 'work', + member_count: 3, + max_member_count: 200, + group_create_time: 100, + group_level: 2, + group_memo: 'rules', + group_all_shut: -1, + }]); + expect(fetchGroupList).not.toHaveBeenCalled(); + + await api.getGroupList(true); + expect(fetchGroupList).toHaveBeenCalledOnce(); + }); + + it('returns joined-group info including the detail level', async () => { + const cached = makeGroup(710502, 'Group E', { remark: '常用群', allMuted: false }); + const { api } = makeRef({ + identity: { findGroup: (groupId: number) => groupId === 710502 ? cached : null }, + apis: { + contacts: { + fetchGroupDetail: vi.fn(async () => ({ ...cached, level: 6 })), + }, + }, + }); + + await expect(api.getGroupInfo(710502)).resolves.toEqual({ + group_id: 710502, + group_name: 'Group E', + group_remark: '常用群', + member_count: 3, + max_member_count: 200, + group_create_time: 0, + group_level: 6, + group_memo: '', + group_all_shut: 0, + }); + }); + + it('maps group members and a single member lookup', async () => { + const member = makeMember(20002, 'bob', { card: 'card-bob', isRobot: true, role: 'admin', title: 't' }); + const fetchGroupMemberList = vi.fn(async () => [member]); + const { api } = makeRef({ + identity: { + findGroupMember: (groupId: number, userId: number) => + groupId === 710503 && userId === 20002 ? member : null, + }, + apis: { contacts: { fetchGroupMemberList } }, + }); + + await expect(api.getGroupMemberList(710503)).resolves.toEqual([{ + group_id: 710503, + user_id: 20002, + nickname: 'bob', + card: 'card-bob', + is_robot: true, + sex: 'unknown', + age: 0, + join_time: 1_700_000_100, + last_sent_time: 1_700_000_200, + shut_up_timestamp: 0, + level: '4', + role: 'admin', + title: 't', + area: '', + unfriendly: false, + title_expire_time: 0, + card_changeable: true, + }]); + await expect(api.getGroupMemberInfo(710503, 20002)).resolves.toMatchObject({ + group_id: 710503, + user_id: 20002, + nickname: 'bob', + is_robot: true, + }); + }); + + it('maps a stranger profile from the contacts API', async () => { + const { api } = makeRef({ + apis: { + contacts: { + fetchUserProfile: vi.fn(async () => ({ + uin: 20002, + uid: 'u_20002', + nickname: 'stranger', + remark: 'r', + sex: 'female', + age: 21, + sign: 'hello sign', + level: 17, + })), + }, + }, + }); + + await expect(api.getStrangerInfo(20002)).resolves.toEqual({ + user_id: 20002, + nickname: 'stranger', + remark: 'r', + sex: 'female', + age: 21, + long_nick: 'hello sign', + qq_level: 17, + level: 17, + }); + }); + + it('lists group files and defaults a missing folder id to /', async () => { + const list = vi.fn(async () => ({ + files: [{ + fileId: 'f1', + fileName: 'a.txt', + busId: 102, + fileSize: 12, + uploadTime: 10, + deadTime: 0, + modifyTime: 11, + downloadTimes: 2, + uploader: 20002, + uploaderName: 'alice', + }], + folders: [{ + folderId: 'd1', + folderName: 'dir', + createTime: 100, + creator: 123, + creatorName: 'creator', + totalFileCount: 2, + lastUploadTime: 200, + lastUploader: 5_000_000_001, + lastUploaderName: 'uploader', + }], + })); + const { api } = makeRef({ + apis: { groupFile: { list, getPttUrl: vi.fn(), getPrivatePttUrl: vi.fn() } }, + }); + + await expect(api.getGroupFiles(710504)).resolves.toEqual({ + files: [{ + group_id: 710504, + file_id: 'f1', + file_name: 'a.txt', + busid: 102, + file_size: 12, + upload_time: 10, + dead_time: 0, + modify_time: 11, + download_times: 2, + uploader: 20002, + uploader_name: 'alice', + }], + folders: [{ + group_id: 710504, + folder_id: 'd1', + folder_name: 'dir', + create_time: 100, + creator: 123, + create_name: 'creator', + total_file_count: 2, + last_upload_time: 200, + last_uploader: 5_000_000_001, + last_uploader_name: 'uploader', + }], + }); + expect(list).toHaveBeenCalledWith(710504, '/'); + }); + + it('maps download rkeys and returns an empty list when the fetch fails', async () => { + const ok = makeRef({ + apis: { + contacts: { + fetchDownloadRKeys: vi.fn(async () => [ + { rkey: 'rk', type: 20, ttlSeconds: 3600, createTime: 100 }, + ]), + }, + }, + }); + await expect(ok.api.getDownloadRKeys()).resolves.toEqual([ + { rkey: 'rk', type: 20, ttl: 3600, create_time: 100 }, + ]); + + const failed = makeRef({ + apis: { + contacts: { + fetchDownloadRKeys: vi.fn(async () => { + throw new Error('rkey down'); + }), + }, + }, + }); + await expect(failed.api.getDownloadRKeys()).resolves.toEqual([]); + }); + + it('maps pending group system messages for the supplied query', async () => { + const { api } = makeRef({ + apis: { + contacts: { + fetchGroupRequests: vi.fn(async (filtered: boolean) => + filtered ? [] : [makeRequest()]), + }, + }, + }); + + await expect(api.handleGetGroupSystemMsg({ + groupId: 710010, + onlyPending: true, + count: 10, + })).resolves.toEqual([{ + group_id: 710010, + group_name: 'sys-group', + request_id: 888, + requester_uin: 20002, + requester_nick: 'applicant', + message: 'please add', + checked: false, + flag: 'slreq:1:888:710010:22:0', + }]); + }); +}); + +describe('buildApiContext media', () => { + it('resolves image info with the converter imageUrlResolver', async () => { + const resolver = vi.fn(async () => 'https://cdn.example/fresh'); + const { api } = makeRef({ + mediaStore: { + findImage: (file: string) => file === 'pic.jpg' + ? { + file: 'pic.jpg', + url: 'https://cdn.example/stale', + fileSize: 64, + fileName: 'pic.jpg', + subType: 0, + summary: '', + isGroup: true, + sessionId: GROUP_ID, + imageUrl: 'https://cdn.example/raw', + } + : null, + }, + converterCtx: { imageUrlResolver: resolver }, + }); + + await expect(api.getImageInfo('pic.jpg')).resolves.toEqual({ + file: 'https://cdn.example/fresh', + url: 'https://cdn.example/fresh', + file_size: '64', + file_name: 'pic.jpg', + }); + expect(resolver).toHaveBeenCalledWith( + { type: 'image', imageUrl: 'https://cdn.example/raw', subType: 0 }, + true, + ); + await expect(api.getImageInfo('missing.jpg')).resolves.toBeNull(); + }); + + it('returns cached record info and refetches a missing group ptt url', async () => { + const getPttUrl = vi.fn(async () => 'https://ptt.example/group'); + const updateRecordUrl = vi.fn(); + const mediaNode = { fileUuid: 'uuid-1' }; + const { api } = makeRef({ + mediaStore: { + findRecord: (file: string) => file === 'voice.amr' + ? { + file: 'voice.amr', + fileId: 'rec-1', + url: '', + fileSize: 32, + fileName: 'voice.amr', + duration: 3, + fileHash: 'hash', + mediaNode, + isGroup: true, + sessionId: GROUP_ID, + } + : null, + updateRecordUrl, + }, + apis: { groupFile: { list: vi.fn(), getPttUrl, getPrivatePttUrl: vi.fn() } }, + }); + + await expect(api.getRecordInfo('voice.amr')).resolves.toEqual({ + file: 'https://ptt.example/group', + url: 'https://ptt.example/group', + file_size: '32', + file_name: 'voice.amr', + }); + expect(getPttUrl).toHaveBeenCalledWith(GROUP_ID, mediaNode); + expect(updateRecordUrl).toHaveBeenCalledWith('voice.amr', 'https://ptt.example/group'); + await expect(api.getRecordInfo('missing.amr')).resolves.toBeNull(); + }); + + it('transcribes a private ptt using the instance selfId as peer', async () => { + const translatePttToText = vi.fn(async () => 'hello text'); + const { api, events } = makeRef({ + selfId: 188003, + mediaStore: { + findRecord: () => ({ + file: 'voice.silk', + fileId: 'ptt-uuid', + url: 'https://ptt.example/c2c', + fileSize: 16, + fileName: 'voice.silk', + duration: 2, + fileHash: 'hash', + isGroup: false, + sessionId: PEER_ID, + md5Hex: 'aa', + voiceFormat: 1, + }), + }, + apis: { extras: { translatePttToText } }, + }); + events.set(-30, { + message_type: 'private', + user_id: PEER_ID, + message: [{ type: 'record', data: { file: 'voice.silk' } }], + }); + + await expect(api.fetchPttText(-30)).resolves.toEqual({ text: 'hello text' }); + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: false, + msgId: -30, + senderUin: PEER_ID, + peerUin: 188003, + uuid: 'ptt-uuid', + md5Hex: 'aa', + duration: 2, + size: 16, + format: 1, + }); + }); + + it('rejects ptt transcription when the stored event is missing', async () => { + const { api } = makeRef(); + await expect(api.fetchPttText(-31)).rejects.toThrow('消息不存在或已被撤回'); + }); +}); + +describe('buildApiContext send and forward dispatch', () => { + it('dispatches a friend private send as a message_sent event', async () => { + const { api, dispatchEvent, ref } = makeRef(); + + const result = await api.sendPrivateMessage(PEER_ID, [ + { type: 'text', data: { text: 'hello' } }, + ], false); + + expect(result.messageId).toBe(hashMessageIdInt32(77, PEER_ID, PRIVATE_NT_MESSAGE_EVENT)); + expect(ref.bridge.apis.message.sendPrivate).toHaveBeenCalledOnce(); + expect(dispatchEvent).toHaveBeenCalledOnce(); + expect(dispatchEvent).toHaveBeenCalledWith({ + time: 1_725_000_000, + self_id: SELF_ID, + post_type: 'message_sent', + message_type: 'private', + sub_type: 'friend', + message_id: hashMessageIdInt32(77, PEER_ID, PRIVATE_NT_MESSAGE_EVENT), + message_seq: 14, + user_id: SELF_ID, + message: [{ type: 'text', data: { text: 'hello' } }], + raw_message: 'hello', + font: 0, + sender: { user_id: SELF_ID, nickname: 'SnowLuma', sex: 'unknown', age: 0 }, + target_id: PEER_ID, + }, 'send'); + }); + + it('does not dispatch a temp-session private send', async () => { + const { api, dispatchEvent, ref } = makeRef(); + ref.tempSessions.record(PEER_ID, GROUP_ID); + + const result = await api.sendPrivateMessage( + PEER_ID, + [{ type: 'text', data: { text: 'temp hi' } }], + false, + GROUP_ID, + ); + + expect(result.messageId).toBe(hashMessageIdInt32(77, PEER_ID, PRIVATE_NT_MESSAGE_EVENT)); + expect(ref.bridge.apis.message.sendGroupTempMessage).toHaveBeenCalledWith( + PEER_ID, + GROUP_ID, + [{ type: 'text', text: 'temp hi' }], + ); + expect(ref.bridge.apis.message.sendPrivate).not.toHaveBeenCalled(); + expect(dispatchEvent).not.toHaveBeenCalled(); + }); + + it('sends a group message without a self-sent dispatch callback', async () => { + const { api, dispatchEvent, ref } = makeRef(); + + const result = await api.sendGroupMessage(GROUP_ID, [ + { type: 'text', data: { text: 'group hi' } }, + ], false); + + expect(result.messageId).toBe(hashMessageIdInt32(77, GROUP_ID, GROUP_MESSAGE_EVENT)); + expect(ref.bridge.apis.message.sendGroup).toHaveBeenCalledWith( + GROUP_ID, + [{ type: 'text', text: 'group hi' }], + ); + expect(dispatchEvent).not.toHaveBeenCalled(); + }); + + it('dispatches a private forward send', async () => { + const { api, dispatchEvent, ref } = makeRef(); + + const result = await api.sendPrivateForwardMsg(PEER_ID, [{ + type: 'node', + data: { + user_id: SELF_ID, + nickname: 'SnowLuma', + content: [{ type: 'text', data: { text: 'forwarded' } }], + }, + }]); + + expect(result).toEqual({ + messageId: hashMessageIdInt32(77, PEER_ID, PRIVATE_NT_MESSAGE_EVENT), + forwardId: 'forward-res-id', + }); + expect(ref.bridge.apis.forward.upload).toHaveBeenCalledOnce(); + expect(dispatchEvent).toHaveBeenCalledOnce(); + expect(dispatchEvent.mock.calls[0][1]).toBe('send'); + expect(dispatchEvent.mock.calls[0][0]).toMatchObject({ + post_type: 'message_sent', + message_type: 'private', + self_id: SELF_ID, + user_id: SELF_ID, + target_id: PEER_ID, + message_seq: 14, + }); + }); + + it('dispatches a single-message forward to a friend and not to a group', async () => { + const friend = makeRef(); + friend.events.set(-40, { + message_id: -40, + message_type: 'private', + user_id: PEER_ID, + message: [{ type: 'text', data: { text: 'forward me' } }], + }); + + await expect(friend.api.forwardSingleMsg(-40, { userId: PEER_ID })).resolves.toEqual({ + messageId: hashMessageIdInt32(77, PEER_ID, PRIVATE_NT_MESSAGE_EVENT), + }); + expect(friend.dispatchEvent).toHaveBeenCalledOnce(); + expect(friend.dispatchEvent).toHaveBeenCalledWith(expect.objectContaining({ + post_type: 'message_sent', + message_type: 'private', + target_id: PEER_ID, + message: [{ type: 'text', data: { text: 'forward me' } }], + }), 'send'); + + const group = makeRef(); + group.events.set(-41, { + message_id: -41, + message_type: 'group', + group_id: GROUP_ID, + user_id: PEER_ID, + message: [{ type: 'text', data: { text: 'to group' } }], + }); + + await expect(group.api.forwardSingleMsg(-41, { groupId: GROUP_ID })).resolves.toEqual({ + messageId: hashMessageIdInt32(77, GROUP_ID, GROUP_MESSAGE_EVENT), + }); + expect(group.ref.bridge.apis.message.sendGroup).toHaveBeenCalledOnce(); + expect(group.dispatchEvent).not.toHaveBeenCalled(); + }); + + it('uploads a forward pack and sends a group forward card', async () => { + const { api, ref, dispatchEvent } = makeRef(); + const nodes = [{ + type: 'node', + data: { + user_id: SELF_ID, + nickname: 'SnowLuma', + content: [{ type: 'text', data: { text: 'pack' } }], + }, + }]; + + await expect(api.sendForwardMsg(nodes, GROUP_ID)).resolves.toEqual({ + forwardId: 'forward-res-id', + }); + expect(ref.bridge.apis.forward.upload).toHaveBeenCalledOnce(); + + await expect(api.sendGroupForwardMsg(GROUP_ID, nodes)).resolves.toEqual({ + messageId: hashMessageIdInt32(77, GROUP_ID, GROUP_MESSAGE_EVENT), + forwardId: 'forward-res-id', + }); + expect(ref.bridge.apis.message.sendGroup).toHaveBeenCalledOnce(); + expect(dispatchEvent).not.toHaveBeenCalled(); + }); + + it('loads a stored forward by res_id', async () => { + const fetch = vi.fn(async () => [{ + messageType: 'private', + userUin: PEER_ID, + nickname: 'peer', + time: 1_725_000_100, + msgId: 11, + msgSeq: 12, + elements: [{ type: 'text', text: 'from-forward' }], + }]); + const { api } = makeRef({ + apis: { forward: { upload: vi.fn(), fetch } }, + }); + + await expect(api.getForwardMsg('res-abc')).resolves.toEqual([{ + self_id: SELF_ID, + user_id: PEER_ID, + time: 1_725_000_100, + message_id: 11, + message_seq: 12, + real_id: 11, + message_type: 'private', + sender: { user_id: PEER_ID, nickname: 'peer' }, + raw_message: '', + font: 14, + sub_type: 'friend', + message: [{ type: 'text', data: { text: 'from-forward' } }], + message_format: 'array', + post_type: 'message', + }]); + expect(fetch).toHaveBeenCalledWith('res-abc'); + }); +}); + +describe('buildApiContext history', () => { + it('returns an empty list for non-positive session ids', async () => { + const { api } = makeRef(); + await expect(api.getGroupMsgHistory(0)).resolves.toEqual([]); + await expect(api.getFriendMsgHistory(-5)).resolves.toEqual([]); + }); + + it('falls back to the local group store when there is no server anchor', async () => { + const stored = { + post_type: 'message', + self_id: SELF_ID, + message_type: 'group', + group_id: GROUP_ID, + message_id: -50, + raw_message: 'old', + }; + const listSessionEvents = vi.fn(() => [stored]); + const { api } = makeRef({ + messageStore: { + findLatestAuthoritativeSequence: () => null, + listSessionEvents, + }, + }); + + await expect(api.getGroupMsgHistory(GROUP_ID, undefined, 5, false)).resolves.toEqual([{ + message_type: 'group', + group_id: GROUP_ID, + message_id: -50, + raw_message: 'old', + real_id: -50, + }]); + expect(listSessionEvents).toHaveBeenCalledWith(true, GROUP_ID, 5, undefined, false); + }); +}); diff --git a/packages/onebot/tests/media-actions-more.test.ts b/packages/onebot/tests/media-actions-more.test.ts new file mode 100644 index 00000000..30f428d7 --- /dev/null +++ b/packages/onebot/tests/media-actions-more.test.ts @@ -0,0 +1,851 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import { + fetchPttText, + getImageInfo, + getRecordInfo, +} from '../src/modules/media-actions'; +import { + deliverPttTransText, + failPttTransWaiter, + pttTransKey, +} from '../src/modules/ptt-trans-waiter'; +import type { CachedImage, CachedRecord, MediaStore } from '../src/media-store'; +import type { MessageStore } from '../src/message-store'; +import type { JsonObject } from '../src/types'; + +const SELF_ID = 7654321; +const PEER_UIN = 20002; +const GROUP_ID = 710010; +const RAW_IMAGE = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=DEF'; + +const usedPttKeys = new Set(); + +afterEach(() => { + vi.useRealTimers(); + for (const key of usedPttKeys) { + failPttTransWaiter(key, new Error('test cleanup')); + } + usedPttKeys.clear(); +}); + +function trackPttKey(selfId: number, messageId: number): string { + const key = pttTransKey(selfId, messageId); + usedPttKeys.add(key); + return key; +} + +function fakeMessageStore(event: JsonObject | null): MessageStore { + return { findEvent: () => event } as unknown as MessageStore; +} + +function fakeImageStore(image: CachedImage | null): MediaStore { + return { findImage: () => image } as unknown as MediaStore; +} + +function fakeRecordStore( + record: CachedRecord | null, + extras: { updateRecordUrl?: ReturnType } = {}, +): MediaStore { + return { + findRecord: () => record, + updateRecordUrl: extras.updateRecordUrl ?? vi.fn(), + } as unknown as MediaStore; +} + +function cachedImage(overrides: Partial = {}): CachedImage { + return { + file: 'DEF.jpg', + url: `${RAW_IMAGE}&rkey=STALE`, + fileSize: 2048, + fileName: 'DEF.jpg', + subType: 1, + summary: '', + isGroup: false, + sessionId: PEER_UIN, + imageUrl: RAW_IMAGE, + ...overrides, + }; +} + +function cachedRecord(overrides: Partial = {}): CachedRecord { + return { + file: 'voice.silk', + fileId: 'ptt-uuid-1', + url: 'https://ptt.example/c2c.silk', + fileSize: 4096, + fileName: 'voice.silk', + duration: 7, + fileHash: 'deadbeef', + isGroup: false, + sessionId: PEER_UIN, + md5Hex: 'aabbccddeeff00112233445566778899', + voiceFormat: 1, + ...overrides, + }; +} + +function recordEvent(overrides: JsonObject = {}): JsonObject { + return { + message_type: 'private', + user_id: PEER_UIN, + message: [{ type: 'record', data: { file: 'voice.silk' } }], + ...overrides, + }; +} + +function fakeBridge(overrides: { + translatePttToText?: ReturnType; + getPttUrl?: ReturnType; + getPrivatePttUrl?: ReturnType; +} = {}): BridgeInterface { + return { + apis: { + extras: { + translatePttToText: overrides.translatePttToText ?? vi.fn(async () => ''), + }, + groupFile: { + getPttUrl: overrides.getPttUrl ?? vi.fn(async () => ''), + getPrivatePttUrl: overrides.getPrivatePttUrl ?? vi.fn(async () => ''), + }, + }, + } as unknown as BridgeInterface; +} + +describe('fetchPttText', () => { + it('throws when the message event is missing', async () => { + await expect(fetchPttText( + fakeMessageStore(null), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40001, + )).rejects.toThrow('消息不存在或已被撤回'); + }); + + it('throws when event.message is not an array', async () => { + await expect(fetchPttText( + fakeMessageStore({ + message_type: 'private', + user_id: PEER_UIN, + message: '[CQ:record,file=voice.silk]', + }), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40002, + )).rejects.toThrow('消息中不包含语音'); + }); + + it('throws when the message has no record segment', async () => { + await expect(fetchPttText( + fakeMessageStore({ + message_type: 'private', + user_id: PEER_UIN, + message: [{ type: 'text', data: { text: 'hi' } }], + }), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40003, + )).rejects.toThrow('消息中不包含语音'); + }); + + it('skips non-object segments and non-record types before finding a record', async () => { + const translatePttToText = vi.fn(async () => '跳过垃圾段落后转写'); + const store = { + findRecord: vi.fn((file: string) => file === 'keep.silk' ? cachedRecord({ file: 'keep.silk' }) : null), + } as unknown as MediaStore; + const event = { + message_type: 'private', + user_id: PEER_UIN, + message: [ + null, + 'x', + 12, + ['record'], + { type: 'image', data: { file: 'pic.jpg' } }, + { type: 'record', data: { file: 'keep.silk' } }, + ], + }; + + trackPttKey(SELF_ID, 40004); + await expect(fetchPttText( + fakeMessageStore(event), + store, + fakeBridge({ translatePttToText }), + SELF_ID, + 40004, + )).resolves.toEqual({ text: '跳过垃圾段落后转写' }); + expect(store.findRecord).toHaveBeenCalledWith('keep.silk'); + }); + + it('throws when the record segment has no file and no url', async () => { + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [{ type: 'record', data: {} }], + })), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40005, + )).rejects.toThrow('消息中不包含语音'); + }); + + it('throws when record data is not a plain object', async () => { + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [{ type: 'record', data: 'voice.silk' }], + })), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40006, + )).rejects.toThrow('消息中不包含语音'); + }); + + it('throws when record data is an array', async () => { + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [{ type: 'record', data: [{ file: 'voice.silk' }] }], + })), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40007, + )).rejects.toThrow('消息中不包含语音'); + }); + + it('does not fall back to url when file is an empty string', async () => { + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [{ type: 'record', data: { file: '', url: 'https://ptt.example/ignored.silk' } }], + })), + fakeRecordStore(cachedRecord()), + fakeBridge(), + SELF_ID, + 40008, + )).rejects.toThrow('消息中不包含语音'); + }); + + it('looks the record up by data.url when data.file is absent', async () => { + const translatePttToText = vi.fn(async () => 'url 字段转写'); + const store = { + findRecord: vi.fn((file: string) => ( + file === 'https://ptt.example/by-url.silk' + ? cachedRecord({ file: 'https://ptt.example/by-url.silk' }) + : null + )), + } as unknown as MediaStore; + + trackPttKey(SELF_ID, 40009); + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [{ type: 'record', data: { url: 'https://ptt.example/by-url.silk' } }], + })), + store, + fakeBridge({ translatePttToText }), + SELF_ID, + 40009, + )).resolves.toEqual({ text: 'url 字段转写' }); + expect(store.findRecord).toHaveBeenCalledWith('https://ptt.example/by-url.silk'); + }); + + it('uses the first record segment even when a later one exists', async () => { + const translatePttToText = vi.fn(async () => '第一段'); + const store = { + findRecord: vi.fn((file: string) => ( + file === 'first.silk' ? cachedRecord({ file: 'first.silk' }) : null + )), + } as unknown as MediaStore; + + trackPttKey(SELF_ID, 40010); + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [ + { type: 'record', data: { file: 'first.silk' } }, + { type: 'record', data: { file: 'second.silk' } }, + ], + })), + store, + fakeBridge({ translatePttToText }), + SELF_ID, + 40010, + )).resolves.toEqual({ text: '第一段' }); + expect(store.findRecord).toHaveBeenCalledWith('first.silk'); + expect(store.findRecord).not.toHaveBeenCalledWith('second.silk'); + }); + + it('stringifies a numeric file id before cache lookup', async () => { + const translatePttToText = vi.fn(async () => '数字 file'); + const store = { + findRecord: vi.fn((file: string) => file === '9001' ? cachedRecord({ file: '9001' }) : null), + } as unknown as MediaStore; + + trackPttKey(SELF_ID, 40011); + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message: [{ type: 'record', data: { file: 9001 } }], + })), + store, + fakeBridge({ translatePttToText }), + SELF_ID, + 40011, + )).resolves.toEqual({ text: '数字 file' }); + expect(store.findRecord).toHaveBeenCalledWith('9001'); + }); + + it('throws when the record is not in the media cache', async () => { + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(null), + fakeBridge(), + SELF_ID, + 40012, + )).rejects.toThrow('语音不在缓存中,无法转写'); + }); + + it('transcribes a private ptt with selfId as peerUin and inline text', async () => { + const translatePttToText = vi.fn(async () => '今天天气不错'); + trackPttKey(SELF_ID, 40013); + + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40013, + )).resolves.toEqual({ text: '今天天气不错' }); + + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: false, + msgId: 40013, + senderUin: 20002, + peerUin: 7654321, + uuid: 'ptt-uuid-1', + md5Hex: 'aabbccddeeff00112233445566778899', + duration: 7, + size: 4096, + format: 1, + }); + }); + + it('treats message_type group as a group ptt and uses group_id as peerUin', async () => { + const translatePttToText = vi.fn(async () => '群语音'); + trackPttKey(SELF_ID, 40014); + + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message_type: 'group', + group_id: GROUP_ID, + user_id: PEER_UIN, + })), + fakeRecordStore(cachedRecord({ isGroup: false, sessionId: 1 })), + fakeBridge({ translatePttToText }), + SELF_ID, + 40014, + )).resolves.toEqual({ text: '群语音' }); + + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: true, + msgId: 40014, + senderUin: 20002, + peerUin: 710010, + uuid: 'ptt-uuid-1', + md5Hex: 'aabbccddeeff00112233445566778899', + duration: 7, + size: 4096, + format: 1, + }); + }); + + it('uses cached.sessionId when group_id is missing or zero', async () => { + const translatePttToText = vi.fn(async () => 'session 回退'); + trackPttKey(SELF_ID, 40015); + + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message_type: 'group', + group_id: 0, + user_id: PEER_UIN, + })), + fakeRecordStore(cachedRecord({ isGroup: true, sessionId: 888001 })), + fakeBridge({ translatePttToText }), + SELF_ID, + 40015, + )).resolves.toEqual({ text: 'session 回退' }); + + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: true, + msgId: 40015, + senderUin: 20002, + peerUin: 888001, + uuid: 'ptt-uuid-1', + md5Hex: 'aabbccddeeff00112233445566778899', + duration: 7, + size: 4096, + format: 1, + }); + }); + + it('treats a private event as group when the cached record is a group ptt', async () => { + const translatePttToText = vi.fn(async () => '缓存标记群'); + trackPttKey(SELF_ID, 40016); + + await expect(fetchPttText( + fakeMessageStore(recordEvent({ + message_type: 'private', + group_id: 555000, + })), + fakeRecordStore(cachedRecord({ isGroup: true, sessionId: 555000 })), + fakeBridge({ translatePttToText }), + SELF_ID, + 40016, + )).resolves.toEqual({ text: '缓存标记群' }); + + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: true, + msgId: 40016, + senderUin: 20002, + peerUin: 555000, + uuid: 'ptt-uuid-1', + md5Hex: 'aabbccddeeff00112233445566778899', + duration: 7, + size: 4096, + format: 1, + }); + }); + + it('defaults senderUin and fingerprint fields when they are missing', async () => { + const translatePttToText = vi.fn(async () => '缺省指纹'); + trackPttKey(SELF_ID, 40017); + + await expect(fetchPttText( + fakeMessageStore({ + message_type: 'private', + message: [{ type: 'record', data: { file: 'voice.silk' } }], + }), + fakeRecordStore(cachedRecord({ + fileId: '', + md5Hex: undefined, + duration: undefined as unknown as number, + fileSize: undefined as unknown as number, + voiceFormat: undefined, + })), + fakeBridge({ translatePttToText }), + SELF_ID, + 40017, + )).resolves.toEqual({ text: '缺省指纹' }); + + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: false, + msgId: 40017, + senderUin: 0, + peerUin: 7654321, + uuid: '', + md5Hex: '', + duration: 0, + size: 0, + format: 0, + }); + }); + + it('coerces a string user_id to senderUin', async () => { + const translatePttToText = vi.fn(async () => '字符串 uin'); + trackPttKey(SELF_ID, 40018); + + await expect(fetchPttText( + fakeMessageStore(recordEvent({ user_id: '20002' })), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40018, + )).resolves.toEqual({ text: '字符串 uin' }); + + expect(translatePttToText).toHaveBeenCalledWith({ + isGroup: false, + msgId: 40018, + senderUin: 20002, + peerUin: 7654321, + uuid: 'ptt-uuid-1', + md5Hex: 'aabbccddeeff00112233445566778899', + duration: 7, + size: 4096, + format: 1, + }); + }); + + it('registers the waiter before triggering so an inline push cannot race', async () => { + const key = trackPttKey(SELF_ID, 40019); + const translatePttToText = vi.fn(async () => { + deliverPttTransText(key, '推送先到'); + return ''; + }); + + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40019, + )).resolves.toEqual({ text: '推送先到' }); + }); + + it('keeps the push text when the trigger later also returns inline text', async () => { + const key = trackPttKey(SELF_ID, 40020); + const translatePttToText = vi.fn(async () => { + deliverPttTransText(key, '推送文本'); + return '同步文本'; + }); + + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40020, + )).resolves.toEqual({ text: '推送文本' }); + }); + + it('waits for an async push when the trigger returns an empty string', async () => { + const key = trackPttKey(SELF_ID, 40021); + const translatePttToText = vi.fn(async () => { + queueMicrotask(() => deliverPttTransText(key, '异步推送转写')); + return ''; + }); + + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40021, + )).resolves.toEqual({ text: '异步推送转写' }); + }); + + it('rejects with the trigger Error', async () => { + trackPttKey(SELF_ID, 40022); + const err = new Error('桥接失败'); + const translatePttToText = vi.fn(async () => { + throw err; + }); + + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40022, + )).rejects.toBe(err); + }); + + it('wraps a non-Error trigger rejection', async () => { + trackPttKey(SELF_ID, 40023); + const translatePttToText = vi.fn(async () => { + throw 'boom'; + }); + + await expect(fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40023, + )).rejects.toThrow('boom'); + }); + + it('times out after 20000ms when neither inline text nor a push arrives', async () => { + vi.useFakeTimers(); + trackPttKey(SELF_ID, 40024); + const translatePttToText = vi.fn(async () => ''); + + const pending = fetchPttText( + fakeMessageStore(recordEvent()), + fakeRecordStore(cachedRecord()), + fakeBridge({ translatePttToText }), + SELF_ID, + 40024, + ); + const rejected = expect(pending).rejects.toThrow('语音转文字超时(未收到结果推送)'); + await vi.advanceTimersByTimeAsync(19_999); + await vi.advanceTimersByTimeAsync(1); + await rejected; + }); +}); + +describe('getImageInfo', () => { + it('returns the full info object after a successful re-sign', async () => { + const resolver = vi.fn(async () => `${RAW_IMAGE}&rkey=FRESH`); + + await expect(getImageInfo(fakeImageStore(cachedImage()), 'DEF.jpg', resolver)).resolves.toEqual({ + file: `${RAW_IMAGE}&rkey=FRESH`, + url: `${RAW_IMAGE}&rkey=FRESH`, + file_size: '2048', + file_name: 'DEF.jpg', + }); + expect(resolver).toHaveBeenCalledWith( + { type: 'image', imageUrl: RAW_IMAGE, subType: 1 }, + false, + ); + }); + + it('keeps the stored URL when the resolver returns an empty string', async () => { + const resolver = vi.fn(async () => ''); + await expect(getImageInfo(fakeImageStore(cachedImage()), 'DEF.jpg', resolver)).resolves.toEqual({ + file: `${RAW_IMAGE}&rkey=STALE`, + url: `${RAW_IMAGE}&rkey=STALE`, + file_size: '2048', + file_name: 'DEF.jpg', + }); + }); + + it('does not call a null resolver', async () => { + await expect(getImageInfo(fakeImageStore(cachedImage()), 'DEF.jpg', null)).resolves.toEqual({ + file: `${RAW_IMAGE}&rkey=STALE`, + url: `${RAW_IMAGE}&rkey=STALE`, + file_size: '2048', + file_name: 'DEF.jpg', + }); + }); + + it('falls file back to the cache key when both url fields are empty', async () => { + await expect(getImageInfo(fakeImageStore(cachedImage({ + file: 'orphan.jpg', + url: '', + imageUrl: '', + fileName: 'named.jpg', + fileSize: 12, + })), 'orphan.jpg')).resolves.toEqual({ + file: 'orphan.jpg', + url: '', + file_size: '12', + file_name: 'named.jpg', + }); + }); + + it('uses imageUrl as the unsigned url when the stored signed url is empty', async () => { + await expect(getImageInfo(fakeImageStore(cachedImage({ + url: '', + imageUrl: RAW_IMAGE, + })), 'DEF.jpg')).resolves.toEqual({ + file: RAW_IMAGE, + url: RAW_IMAGE, + file_size: '2048', + file_name: 'DEF.jpg', + }); + }); + + it('stringifies a missing fileSize as 0 and falls file_name back to file', async () => { + await expect(getImageInfo(fakeImageStore(cachedImage({ + file: 'fallback-name.jpg', + fileName: '', + fileSize: undefined as unknown as number, + })), 'fallback-name.jpg')).resolves.toEqual({ + file: `${RAW_IMAGE}&rkey=STALE`, + url: `${RAW_IMAGE}&rkey=STALE`, + file_size: '0', + file_name: 'fallback-name.jpg', + }); + }); + + it('passes isGroup true through to the resolver', async () => { + const resolver = vi.fn(async () => 'https://cdn.example/group-fresh'); + await expect(getImageInfo( + fakeImageStore(cachedImage({ isGroup: true, sessionId: GROUP_ID })), + 'DEF.jpg', + resolver, + )).resolves.toEqual({ + file: 'https://cdn.example/group-fresh', + url: 'https://cdn.example/group-fresh', + file_size: '2048', + file_name: 'DEF.jpg', + }); + expect(resolver).toHaveBeenCalledWith( + { type: 'image', imageUrl: RAW_IMAGE, subType: 1 }, + true, + ); + }); +}); + +describe('getRecordInfo', () => { + it('returns null when the record is not cached', async () => { + await expect(getRecordInfo(fakeBridge(), fakeRecordStore(null), 'missing.silk')).resolves.toBeNull(); + }); + + it('returns the stored url without refetching', async () => { + const getPttUrl = vi.fn(async () => 'https://ptt.example/should-not-run'); + const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/should-not-run'); + const updateRecordUrl = vi.fn(); + + await expect(getRecordInfo( + fakeBridge({ getPttUrl, getPrivatePttUrl }), + fakeRecordStore(cachedRecord({ + url: 'https://ptt.example/cached.silk', + mediaNode: { fileUuid: 'uuid-1' }, + }), { updateRecordUrl }), + 'voice.silk', + )).resolves.toEqual({ + file: 'https://ptt.example/cached.silk', + url: 'https://ptt.example/cached.silk', + file_size: '4096', + file_name: 'voice.silk', + }); + expect(getPttUrl).not.toHaveBeenCalled(); + expect(getPrivatePttUrl).not.toHaveBeenCalled(); + expect(updateRecordUrl).not.toHaveBeenCalled(); + }); + + it('does not refetch when the url is empty and there is no mediaNode', async () => { + const getPttUrl = vi.fn(async () => 'https://ptt.example/group'); + const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private'); + + await expect(getRecordInfo( + fakeBridge({ getPttUrl, getPrivatePttUrl }), + fakeRecordStore(cachedRecord({ url: '', mediaNode: undefined })), + 'voice.silk', + )).resolves.toEqual({ + file: 'voice.silk', + url: '', + file_size: '4096', + file_name: 'voice.silk', + }); + expect(getPttUrl).not.toHaveBeenCalled(); + expect(getPrivatePttUrl).not.toHaveBeenCalled(); + }); + + it('refetches a group ptt url and writes it back under the lookup key', async () => { + const mediaNode = { fileUuid: 'group-uuid', storeId: 1 }; + const getPttUrl = vi.fn(async () => 'https://ptt.example/group-fresh'); + const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private'); + const updateRecordUrl = vi.fn(); + + await expect(getRecordInfo( + fakeBridge({ getPttUrl, getPrivatePttUrl }), + fakeRecordStore(cachedRecord({ + file: 'primary.silk', + url: '', + isGroup: true, + sessionId: GROUP_ID, + mediaNode, + }), { updateRecordUrl }), + 'alias.silk', + )).resolves.toEqual({ + file: 'https://ptt.example/group-fresh', + url: 'https://ptt.example/group-fresh', + file_size: '4096', + file_name: 'voice.silk', + }); + expect(getPttUrl).toHaveBeenCalledWith(710010, mediaNode); + expect(getPrivatePttUrl).not.toHaveBeenCalled(); + expect(updateRecordUrl).toHaveBeenCalledWith('alias.silk', 'https://ptt.example/group-fresh'); + }); + + it('refetches a private ptt url from the media node only', async () => { + const mediaNode = { fileUuid: 'c2c-uuid' }; + const getPttUrl = vi.fn(async () => 'https://ptt.example/group'); + const getPrivatePttUrl = vi.fn(async () => 'https://ptt.example/private-fresh'); + const updateRecordUrl = vi.fn(); + + await expect(getRecordInfo( + fakeBridge({ getPttUrl, getPrivatePttUrl }), + fakeRecordStore(cachedRecord({ + url: '', + isGroup: false, + mediaNode, + }), { updateRecordUrl }), + 'voice.silk', + )).resolves.toEqual({ + file: 'https://ptt.example/private-fresh', + url: 'https://ptt.example/private-fresh', + file_size: '4096', + file_name: 'voice.silk', + }); + expect(getPrivatePttUrl).toHaveBeenCalledWith(mediaNode); + expect(getPttUrl).not.toHaveBeenCalled(); + expect(updateRecordUrl).toHaveBeenCalledWith('voice.silk', 'https://ptt.example/private-fresh'); + }); + + it('does not write back an empty refetch result', async () => { + const updateRecordUrl = vi.fn(); + const getPrivatePttUrl = vi.fn(async () => ''); + + await expect(getRecordInfo( + fakeBridge({ getPrivatePttUrl }), + fakeRecordStore(cachedRecord({ + url: '', + mediaNode: { fileUuid: 'empty-uuid' }, + }), { updateRecordUrl }), + 'voice.silk', + )).resolves.toEqual({ + file: 'voice.silk', + url: '', + file_size: '4096', + file_name: 'voice.silk', + }); + expect(updateRecordUrl).not.toHaveBeenCalled(); + }); + + it('returns the cached file after a refetch Error', async () => { + const updateRecordUrl = vi.fn(); + const getPttUrl = vi.fn(async () => { + throw new Error('cdn timeout'); + }); + + await expect(getRecordInfo( + fakeBridge({ getPttUrl }), + fakeRecordStore(cachedRecord({ + file: 'keep.silk', + url: '', + isGroup: true, + sessionId: GROUP_ID, + mediaNode: { fileUuid: 'fail-uuid' }, + }), { updateRecordUrl }), + 'keep.silk', + )).resolves.toEqual({ + file: 'keep.silk', + url: '', + file_size: '4096', + file_name: 'voice.silk', + }); + expect(updateRecordUrl).not.toHaveBeenCalled(); + }); + + it('returns the cached file after a non-Error refetch rejection', async () => { + const getPrivatePttUrl = vi.fn(async () => { + throw 'offline'; + }); + + await expect(getRecordInfo( + fakeBridge({ getPrivatePttUrl }), + fakeRecordStore(cachedRecord({ + url: '', + isGroup: false, + mediaNode: { fileUuid: 'offline-uuid' }, + })), + 'voice.silk', + )).resolves.toEqual({ + file: 'voice.silk', + url: '', + file_size: '4096', + file_name: 'voice.silk', + }); + }); + + it('stringifies a missing fileSize as 0 and falls file_name back to file', async () => { + await expect(getRecordInfo( + fakeBridge(), + fakeRecordStore(cachedRecord({ + file: 'fallback.silk', + fileName: '', + fileSize: undefined as unknown as number, + url: 'https://ptt.example/named.silk', + })), + 'fallback.silk', + )).resolves.toEqual({ + file: 'https://ptt.example/named.silk', + url: 'https://ptt.example/named.silk', + file_size: '0', + file_name: 'fallback.silk', + }); + }); +}); diff --git a/packages/onebot/tests/message-store-migration-worker.test.ts b/packages/onebot/tests/message-store-migration-worker.test.ts new file mode 100644 index 00000000..071262ef --- /dev/null +++ b/packages/onebot/tests/message-store-migration-worker.test.ts @@ -0,0 +1,383 @@ +import { EventEmitter } from 'node:events'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import type { MessagePort } from 'node:worker_threads'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + inspectMessageStoreMigration, + MessageStoreMigrator, + prepareMessageStoreDatabase, +} from '../src/message-store-migration'; +import { + isMessageStoreMigrationWorkerData, + MESSAGE_STORE_WORKER_KIND, + runMessageStoreMigrationWorker, + type MessageStoreMigrationWorkerData, + type MessageStoreMigrationWorkerMessage, +} from '../src/message-store-migration-worker'; + +function workerPayload(dbPath: string): MessageStoreMigrationWorkerData { + return { kind: 'snowluma-message-store-migration', dbPath }; +} + +function createControlPort(): { + port: MessagePort; + messages: MessageStoreMigrationWorkerMessage[]; + send(message: unknown): void; + listenerCount(): number; +} { + const messages: MessageStoreMigrationWorkerMessage[] = []; + const events = new EventEmitter(); + return { + port: { + on: events.on.bind(events), + off: events.off.bind(events), + postMessage(message: MessageStoreMigrationWorkerMessage) { + messages.push(message); + }, + } as unknown as MessagePort, + messages, + send(message: unknown) { + events.emit('message', message); + }, + listenerCount() { + return events.listenerCount('message'); + }, + }; +} + +function seedUnclassified(dbPath: string, count: number): void { + prepareMessageStoreDatabase(dbPath); + const db = new DatabaseSync(dbPath); + const insert = db.prepare(` + INSERT INTO messages ( + message_hash, is_group, session_id, sequence, event_name, classification_version + ) VALUES (?, 1, 70001, ?, 'message.group', 0) + `); + db.exec('BEGIN'); + for (let hash = 1; hash <= count; hash += 1) { + insert.run(hash, hash); + } + db.exec('COMMIT'); + db.close(); +} + +describe('isMessageStoreMigrationWorkerData', () => { + it('exports the worker kind used by the type guard', () => { + expect(MESSAGE_STORE_WORKER_KIND).toBe('snowluma-message-store-migration'); + }); + + it('accepts only the worker kind with a string dbPath', () => { + expect(isMessageStoreMigrationWorkerData({ + kind: 'snowluma-message-store-migration', + dbPath: '/data/10001/messages.db', + })).toBe(true); + expect(isMessageStoreMigrationWorkerData({ + kind: 'snowluma-message-store-migration', + dbPath: '', + })).toBe(true); + + expect(isMessageStoreMigrationWorkerData(null)).toBe(false); + expect(isMessageStoreMigrationWorkerData(undefined)).toBe(false); + expect(isMessageStoreMigrationWorkerData(1)).toBe(false); + expect(isMessageStoreMigrationWorkerData('snowluma-message-store-migration')).toBe(false); + expect(isMessageStoreMigrationWorkerData({ + kind: 'other-worker', + dbPath: '/data/10001/messages.db', + })).toBe(false); + expect(isMessageStoreMigrationWorkerData({ + kind: 'snowluma-message-store-migration', + })).toBe(false); + expect(isMessageStoreMigrationWorkerData({ + kind: 'snowluma-message-store-migration', + dbPath: 1, + })).toBe(false); + }); + + it('defaults to workerData when no argument is passed', () => { + expect(isMessageStoreMigrationWorkerData()).toBe(false); + }); +}); + +describe('runMessageStoreMigrationWorker', () => { + let tmpDir: string; + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-ms-migration-worker-')); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + it('rejects when the worker port is unavailable', async () => { + await expect(runMessageStoreMigrationWorker( + workerPayload(path.join(tmpDir, 'messages.db')), + null, + )).rejects.toThrow('database migration worker port is unavailable'); + }); + + it('posts ready then a complete progress for an empty store', async () => { + const dbPath = path.join(tmpDir, 'messages.db'); + const control = createControlPort(); + const close = vi.spyOn(MessageStoreMigrator.prototype, 'close'); + + const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port); + expect(control.messages).toEqual([{ kind: 'ready' }]); + expect(control.listenerCount()).toBe(1); + + control.send('start'); + await running; + + expect(control.messages).toEqual([ + { kind: 'ready' }, + { + kind: 'progress', + status: { phase: 'complete', processed: 0, total: 0 }, + elapsedMs: 0, + }, + ]); + expect(control.listenerCount()).toBe(0); + expect(close).toHaveBeenCalledOnce(); + expect(inspectMessageStoreMigration(dbPath)).toEqual({ + phase: 'complete', + processed: 0, + total: 0, + }); + }); + + it('does not start on an unrecognized control message', async () => { + const dbPath = path.join(tmpDir, 'messages.db'); + const control = createControlPort(); + const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port); + + control.send('go'); + control.send({ kind: 'start' }); + await Promise.resolve(); + expect(control.messages).toEqual([{ kind: 'ready' }]); + + control.send('start'); + await running; + expect(control.messages).toEqual([ + { kind: 'ready' }, + { + kind: 'progress', + status: { phase: 'complete', processed: 0, total: 0 }, + elapsedMs: 0, + }, + ]); + }); + + it('returns after cancel without posting progress', async () => { + const dbPath = path.join(tmpDir, 'messages.db'); + seedUnclassified(dbPath, 1); + const control = createControlPort(); + const runBatch = vi.spyOn(MessageStoreMigrator.prototype, 'runBatch'); + const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port); + + control.send('cancel'); + await running; + + expect(control.messages).toEqual([{ kind: 'ready' }]); + expect(runBatch).not.toHaveBeenCalled(); + expect(control.listenerCount()).toBe(0); + expect(inspectMessageStoreMigration(dbPath)).toEqual({ + phase: 'migrating', + processed: 0, + total: 1, + }); + }); + + it('treats start then cancel in the same turn as a cancel', async () => { + const dbPath = path.join(tmpDir, 'messages.db'); + seedUnclassified(dbPath, 1); + const control = createControlPort(); + const runBatch = vi.spyOn(MessageStoreMigrator.prototype, 'runBatch'); + const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port); + + control.send('start'); + control.send('cancel'); + await running; + + expect(control.messages).toEqual([{ kind: 'ready' }]); + expect(runBatch).not.toHaveBeenCalled(); + }); + + it('migrates pending rows in one batch and posts complete progress', async () => { + const dbPath = path.join(tmpDir, 'messages.db'); + seedUnclassified(dbPath, 1); + const control = createControlPort(); + const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port); + + control.send('start'); + await running; + + expect(control.messages).toEqual([ + { kind: 'ready' }, + { + kind: 'progress', + status: { phase: 'complete', processed: 1, total: 1 }, + elapsedMs: 0, + }, + ]); + expect(inspectMessageStoreMigration(dbPath)).toEqual({ + phase: 'complete', + processed: 1, + total: 1, + }); + }); + + it('posts a second progress after the batch pause when more than 200 rows remain', async () => { + const dbPath = path.join(tmpDir, 'messages.db'); + seedUnclassified(dbPath, 201); + const control = createControlPort(); + const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port); + + control.send('start'); + await running; + + expect(control.messages).toHaveLength(3); + expect(control.messages[0]).toEqual({ kind: 'ready' }); + expect(control.messages[1]).toEqual({ + kind: 'progress', + status: { phase: 'migrating', processed: 200, total: 201 }, + elapsedMs: 0, + }); + expect(control.messages[2]).toMatchObject({ + kind: 'progress', + status: { phase: 'complete', processed: 201, total: 201 }, + }); + const last = control.messages[2]; + expect(last?.kind).toBe('progress'); + if (last?.kind === 'progress') { + expect(last.elapsedMs).toBeGreaterThanOrEqual(0); + } + expect(inspectMessageStoreMigration(dbPath)).toEqual({ + phase: 'complete', + processed: 201, + total: 201, + }); + }); + + it('stops after cancel between batches', async () => { + vi.useFakeTimers(); + const dbPath = path.join(tmpDir, 'messages.db'); + seedUnclassified(dbPath, 201); + const control = createControlPort(); + const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port); + + control.send('start'); + await Promise.resolve(); + expect(control.messages).toEqual([ + { kind: 'ready' }, + { + kind: 'progress', + status: { phase: 'migrating', processed: 200, total: 201 }, + elapsedMs: 0, + }, + ]); + + control.send('cancel'); + await vi.advanceTimersByTimeAsync(25); + await running; + + expect(control.messages).toEqual([ + { kind: 'ready' }, + { + kind: 'progress', + status: { phase: 'migrating', processed: 200, total: 201 }, + elapsedMs: 0, + }, + ]); + expect(inspectMessageStoreMigration(dbPath)).toEqual({ + phase: 'migrating', + processed: 200, + total: 201, + }); + }); + + it('posts failed when the database parent path is not a directory', async () => { + const parent = path.join(tmpDir, 'not-a-directory'); + fs.writeFileSync(parent, 'blocked'); + const dbPath = path.join(parent, 'messages.db'); + let expected = ''; + try { + fs.mkdirSync(path.dirname(dbPath), { recursive: true }); + } catch (error) { + expected = error instanceof Error ? error.message : String(error); + } + const control = createControlPort(); + + await runMessageStoreMigrationWorker(workerPayload(dbPath), control.port); + + expect(expected).not.toBe(''); + expect(control.messages).toEqual([{ kind: 'failed', message: expected }]); + expect(control.listenerCount()).toBe(0); + }); + + it('posts failed when the messages table is missing after ready', async () => { + const dbPath = path.join(tmpDir, 'messages.db'); + const control = createControlPort(); + const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port); + expect(control.messages).toEqual([{ kind: 'ready' }]); + + const db = new DatabaseSync(dbPath); + db.exec('DROP TABLE messages'); + db.close(); + + control.send('start'); + await running; + + expect(control.messages).toEqual([ + { kind: 'ready' }, + { kind: 'failed', message: 'no such table: messages' }, + ]); + }); + + it('posts failed when a batch update is aborted', async () => { + const dbPath = path.join(tmpDir, 'messages.db'); + seedUnclassified(dbPath, 1); + const db = new DatabaseSync(dbPath); + db.exec(` + CREATE TRIGGER fail_classify BEFORE UPDATE ON messages + BEGIN + SELECT RAISE(ABORT, 'classified row rejected'); + END; + `); + db.close(); + + const control = createControlPort(); + const close = vi.spyOn(MessageStoreMigrator.prototype, 'close'); + const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port); + + control.send('start'); + await running; + + expect(control.messages).toEqual([ + { kind: 'ready' }, + { kind: 'failed', message: 'classified row rejected' }, + ]); + expect(close).toHaveBeenCalledOnce(); + }); + + it('stringifies a non-Error thrown from a batch', async () => { + const dbPath = path.join(tmpDir, 'messages.db'); + vi.spyOn(MessageStoreMigrator.prototype, 'runBatch').mockImplementation(() => { + throw 'raw-failure'; + }); + const control = createControlPort(); + const running = runMessageStoreMigrationWorker(workerPayload(dbPath), control.port); + + control.send('start'); + await running; + + expect(control.messages).toEqual([ + { kind: 'ready' }, + { kind: 'failed', message: 'raw-failure' }, + ]); + }); +}); diff --git a/packages/onebot/tests/ptt-trans-waiter.test.ts b/packages/onebot/tests/ptt-trans-waiter.test.ts new file mode 100644 index 00000000..0f3bcab1 --- /dev/null +++ b/packages/onebot/tests/ptt-trans-waiter.test.ts @@ -0,0 +1,152 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + deliverPttTransText, + failPttTransWaiter, + pttTransKey, + waitPttTransText, +} from '../src/modules/ptt-trans-waiter'; + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('pttTransKey', () => { + it('joins selfUin and msgId with a colon', () => { + expect(pttTransKey(1787882683, 4001)).toBe('1787882683:4001'); + expect(pttTransKey(10001, 42)).toBe('10001:42'); + expect(pttTransKey(0, 0)).toBe('0:0'); + }); +}); + +describe('waitPttTransText / deliverPttTransText', () => { + it('resolves with the delivered text', async () => { + const waiter = waitPttTransText('1787882683:4001', 20_000); + deliverPttTransText('1787882683:4001', '今天天气不错'); + await expect(waiter).resolves.toBe('今天天气不错'); + }); + + it('resolves empty text the same way as any other string', async () => { + const waiter = waitPttTransText('10001:1', 20_000); + deliverPttTransText('10001:1', ''); + await expect(waiter).resolves.toBe(''); + }); + + it('is a no-op when no waiter is registered', () => { + expect(() => deliverPttTransText('10001:missing', '不会被消费')).not.toThrow(); + }); + + it('is a no-op after the waiter has already settled', async () => { + const waiter = waitPttTransText('10001:2', 20_000); + deliverPttTransText('10001:2', '第一次'); + await expect(waiter).resolves.toBe('第一次'); + expect(() => deliverPttTransText('10001:2', '第二次')).not.toThrow(); + }); + + it('does not resolve a different key', async () => { + const a = waitPttTransText('10001:10', 20_000); + const b = waitPttTransText('10001:11', 20_000); + deliverPttTransText('10001:10', '甲'); + await expect(a).resolves.toBe('甲'); + failPttTransWaiter('10001:11', new Error('桥接失败')); + await expect(b).rejects.toThrow('桥接失败'); + }); + + it('allows a new waiter on the same key after settle', async () => { + const first = waitPttTransText('10001:3', 20_000); + deliverPttTransText('10001:3', '一次'); + await expect(first).resolves.toBe('一次'); + + const second = waitPttTransText('10001:3', 20_000); + deliverPttTransText('10001:3', '二次'); + await expect(second).resolves.toBe('二次'); + }); +}); + +describe('failPttTransWaiter', () => { + it('rejects the waiter with the provided error', async () => { + const err = new Error('触发失败'); + const waiter = waitPttTransText('10001:20', 20_000); + failPttTransWaiter('10001:20', err); + await expect(waiter).rejects.toBe(err); + }); + + it('is a no-op when no waiter is registered', () => { + expect(() => failPttTransWaiter('10001:gone', new Error('无人等待'))).not.toThrow(); + }); + + it('is a no-op after the waiter has already settled', async () => { + const waiter = waitPttTransText('10001:21', 20_000); + failPttTransWaiter('10001:21', new Error('第一次失败')); + await expect(waiter).rejects.toThrow('第一次失败'); + expect(() => failPttTransWaiter('10001:21', new Error('第二次失败'))).not.toThrow(); + }); +}); + +describe('waitPttTransText supersede', () => { + it('rejects the previous waiter when the same key is waited again', async () => { + const first = waitPttTransText('10001:30', 20_000); + const firstRejected = expect(first).rejects.toThrow('语音转文字请求被新的请求取代'); + const second = waitPttTransText('10001:30', 20_000); + await firstRejected; + deliverPttTransText('10001:30', '新请求结果'); + await expect(second).resolves.toBe('新请求结果'); + }); + + it('lets failPttTransWaiter settle only the replacement waiter', async () => { + const first = waitPttTransText('10001:31', 20_000); + const firstRejected = expect(first).rejects.toThrow('语音转文字请求被新的请求取代'); + const second = waitPttTransText('10001:31', 20_000); + await firstRejected; + const err = new Error('trigger failed'); + failPttTransWaiter('10001:31', err); + await expect(second).rejects.toBe(err); + }); + + it('does not time out the replacement when the superseded timeout would have fired', async () => { + vi.useFakeTimers(); + const first = waitPttTransText('10001:32', 1_000); + const firstRejected = expect(first).rejects.toThrow('语音转文字请求被新的请求取代'); + const second = waitPttTransText('10001:32', 20_000); + await firstRejected; + await vi.advanceTimersByTimeAsync(1_000); + deliverPttTransText('10001:32', '未被旧超时打断'); + await expect(second).resolves.toBe('未被旧超时打断'); + }); +}); + +describe('waitPttTransText timeout', () => { + it('rejects after timeoutMs when no result is delivered', async () => { + vi.useFakeTimers(); + const waiter = waitPttTransText('10001:40', 20_000); + const rejected = expect(waiter).rejects.toThrow('语音转文字超时(未收到结果推送)'); + await vi.advanceTimersByTimeAsync(19_999); + await vi.advanceTimersByTimeAsync(1); + await rejected; + }); + + it('does not reject after deliver even if the original timeout later elapses', async () => { + vi.useFakeTimers(); + const waiter = waitPttTransText('10001:41', 20_000); + deliverPttTransText('10001:41', '同步转写'); + await expect(waiter).resolves.toBe('同步转写'); + await vi.advanceTimersByTimeAsync(20_000); + }); + + it('does not reject again after fail even if the original timeout later elapses', async () => { + vi.useFakeTimers(); + const waiter = waitPttTransText('10001:42', 20_000); + failPttTransWaiter('10001:42', new Error('请求失败')); + await expect(waiter).rejects.toThrow('请求失败'); + await vi.advanceTimersByTimeAsync(20_000); + }); + + it('ignores deliver and fail after the timeout has already settled the waiter', async () => { + vi.useFakeTimers(); + const waiter = waitPttTransText('10001:43', 20_000); + const rejected = expect(waiter).rejects.toThrow('语音转文字超时(未收到结果推送)'); + await vi.advanceTimersByTimeAsync(20_000); + await rejected; + expect(() => deliverPttTransText('10001:43', '来晚了')).not.toThrow(); + expect(() => failPttTransWaiter('10001:43', new Error('也来晚了'))).not.toThrow(); + }); +}); diff --git a/packages/onebot/tests/quick-operation.test.ts b/packages/onebot/tests/quick-operation.test.ts new file mode 100644 index 00000000..606225f7 --- /dev/null +++ b/packages/onebot/tests/quick-operation.test.ts @@ -0,0 +1,560 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { ApiHandler } from '../src/api-handler'; +import { executeQuickOperation } from '../src/network/quick-operation'; +import type { JsonObject } from '../src/types'; + +function mockApi(): { api: ApiHandler; handle: ReturnType } { + const handle = vi.fn(); + return { api: { handle } as unknown as ApiHandler, handle }; +} + +const GROUP_MESSAGE: JsonObject = { + post_type: 'message', + message_type: 'group', + group_id: 314159, + user_id: 271828, + message_id: 424242, +}; + +const PRIVATE_MESSAGE: JsonObject = { + post_type: 'message', + message_type: 'private', + user_id: 13579, + message_id: 24680, +}; + +describe('executeQuickOperation', () => { + describe('message reply', () => { + it('prepends an at segment to a group string reply and forces auto_escape off', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: 'hello group', + auto_escape: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: [ + { type: 'at', data: { qq: '271828' } }, + { type: 'text', data: { text: 'hello group' } }, + ], + auto_escape: false, + }], + ]); + }); + + it('sends a raw group string reply when at_sender is false', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: 'no at', + at_sender: false, + auto_escape: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: 'no at', + auto_escape: true, + }], + ]); + }); + + it('defaults auto_escape to false for a group string reply without at', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: 'plain', + at_sender: false, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: 'plain', + auto_escape: false, + }], + ]); + }); + + it('prepends an at segment to a group array reply without forcing auto_escape', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: [ + { type: 'text', data: { text: 'hi' } }, + { type: 'face', data: { id: '14' } }, + ], + auto_escape: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: [ + { type: 'at', data: { qq: '271828' } }, + { type: 'text', data: { text: 'hi' } }, + { type: 'face', data: { id: '14' } }, + ], + auto_escape: true, + }], + ]); + }); + + it('leaves a non-string non-array group reply unwrapped when at_sender is on', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: { type: 'image', data: { file: 'pic.jpg' } }, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: { type: 'image', data: { file: 'pic.jpg' } }, + auto_escape: false, + }], + ]); + }); + + it('does not at-wrap a group reply when the event has no user_id', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'message', + message_type: 'group', + group_id: 314159, + message_id: 424242, + }, { + reply: 'nobody', + auto_escape: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: 'nobody', + auto_escape: true, + }], + ]); + }); + + it('does not at-wrap a group reply when user_id is 0', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'message', + message_type: 'group', + group_id: 314159, + user_id: 0, + message_id: 424242, + }, { reply: 'zero-user' }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: 'zero-user', + auto_escape: false, + }], + ]); + }); + + it('at-wraps a group string reply when at_sender is explicitly true', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: 'explicit', + at_sender: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: [ + { type: 'at', data: { qq: '271828' } }, + { type: 'text', data: { text: 'explicit' } }, + ], + auto_escape: false, + }], + ]); + }); + + it('sends a private reply without at-wrapping', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(PRIVATE_MESSAGE, { + reply: 'hello pm', + auto_escape: true, + at_sender: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_private_msg', { + user_id: 13579, + message: 'hello pm', + auto_escape: true, + }], + ]); + }); + + it('coerces a truthy auto_escape on a private reply', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(PRIVATE_MESSAGE, { + reply: [{ type: 'text', data: { text: 'seg' } }], + auto_escape: 1, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_private_msg', { + user_id: 13579, + message: [{ type: 'text', data: { text: 'seg' } }], + auto_escape: true, + }], + ]); + }); + + it('does not send a reply for an unknown message_type', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'message', + message_type: 'guild', + user_id: 9, + message_id: 8, + }, { reply: 'ignored' }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + + it.each([ + ['undefined', { reply: undefined }], + ['null', { reply: null }], + ['empty string', { reply: '' }], + ] as const)('does not send a reply when reply is %s', async (_label, operation) => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { ...operation }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + }); + + describe('message delete', () => { + it('deletes the event message_id', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { delete: true }, api); + + expect(handle.mock.calls).toEqual([ + ['delete_msg', { message_id: 424242 }], + ]); + }); + + it('does not delete when delete is falsy', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { delete: 0 }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + }); + + describe('message ban', () => { + it('bans a group sender for an explicit duration', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + ban: true, + ban_duration: 60, + }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_ban', { + group_id: 314159, + user_id: 271828, + duration: 60, + }], + ]); + }); + + it('bans for 0 seconds when ban_duration is 0', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + ban: true, + ban_duration: 0, + }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_ban', { + group_id: 314159, + user_id: 271828, + duration: 0, + }], + ]); + }); + + it.each([ + ['omitted', {}], + ['a string', { ban_duration: '90' }], + ['null', { ban_duration: null }], + ])('bans for 1800s when ban_duration is %s', async (_label, extra) => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { ban: true, ...extra }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_ban', { + group_id: 314159, + user_id: 271828, + duration: 1800, + }], + ]); + }); + + it('does not ban on a private message', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(PRIVATE_MESSAGE, { + ban: true, + ban_duration: 30, + }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + }); + + describe('message kick', () => { + it('kicks a group sender and rejects later requests when asked', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + kick: true, + reject_add_request: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_kick', { + group_id: 314159, + user_id: 271828, + reject_add_request: true, + }], + ]); + }); + + it('kicks without reject_add_request when the flag is omitted', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { kick: true }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_kick', { + group_id: 314159, + user_id: 271828, + reject_add_request: false, + }], + ]); + }); + + it('coerces a truthy reject_add_request', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + kick: 1, + reject_add_request: 'yes', + }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_kick', { + group_id: 314159, + user_id: 271828, + reject_add_request: true, + }], + ]); + }); + + it('does not kick on a private message', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(PRIVATE_MESSAGE, { kick: true }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + }); + + describe('request approve', () => { + it('approves a friend request with a remark', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'request', + request_type: 'friend', + flag: 'flag-friend-7', + }, { + approve: true, + remark: 'buddy', + }, api); + + expect(handle.mock.calls).toEqual([ + ['set_friend_add_request', { + flag: 'flag-friend-7', + approve: true, + remark: 'buddy', + }], + ]); + }); + + it('rejects a friend request with an empty default remark', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'request', + request_type: 'friend', + flag: 'flag-friend-7', + }, { approve: false }, api); + + expect(handle.mock.calls).toEqual([ + ['set_friend_add_request', { + flag: 'flag-friend-7', + approve: false, + remark: '', + }], + ]); + }); + + it('approves a group request with a reason', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'request', + request_type: 'group', + sub_type: 'add', + flag: 'flag-group-9', + }, { + approve: true, + reason: 'ok', + }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_add_request', { + flag: 'flag-group-9', + sub_type: 'add', + approve: true, + reason: 'ok', + }], + ]); + }); + + it('rejects a group request with an empty default reason', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'request', + request_type: 'group', + sub_type: 'invite', + flag: 'flag-group-9', + }, { approve: false }, api); + + expect(handle.mock.calls).toEqual([ + ['set_group_add_request', { + flag: 'flag-group-9', + sub_type: 'invite', + approve: false, + reason: '', + }], + ]); + }); + + it('does not handle a request when approve is omitted', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'request', + request_type: 'friend', + flag: 'flag-friend-7', + }, { remark: 'unused' }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + + it('does not handle an unknown request_type', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'request', + request_type: 'business', + flag: 'flag-x', + }, { approve: true }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + }); + + describe('combined and ignored operations', () => { + it('runs reply, delete, ban, then kick in that order', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation(GROUP_MESSAGE, { + reply: 'bye', + at_sender: false, + delete: true, + ban: true, + ban_duration: 120, + kick: true, + reject_add_request: true, + }, api); + + expect(handle.mock.calls).toEqual([ + ['send_group_msg', { + group_id: 314159, + message: 'bye', + auto_escape: false, + }], + ['delete_msg', { message_id: 424242 }], + ['set_group_ban', { + group_id: 314159, + user_id: 271828, + duration: 120, + }], + ['set_group_kick', { + group_id: 314159, + user_id: 271828, + reject_add_request: true, + }], + ]); + }); + + it('does nothing for a non-message non-request event', async () => { + const { api, handle } = mockApi(); + + await executeQuickOperation({ + post_type: 'notice', + notice_type: 'group_increase', + group_id: 314159, + user_id: 271828, + }, { + reply: 'x', + delete: true, + ban: true, + kick: true, + approve: true, + }, api); + + expect(handle).not.toHaveBeenCalled(); + }); + + it('propagates a rejected api.handle call', async () => { + const { api, handle } = mockApi(); + handle.mockRejectedValueOnce(new Error('send failed')); + + await expect(executeQuickOperation(GROUP_MESSAGE, { + reply: 'fail', + at_sender: false, + }, api)).rejects.toThrow('send failed'); + }); + }); +}); diff --git a/packages/onebot/tests/stream-file.test.ts b/packages/onebot/tests/stream-file.test.ts index ea99ab48..9943f130 100644 --- a/packages/onebot/tests/stream-file.test.ts +++ b/packages/onebot/tests/stream-file.test.ts @@ -42,7 +42,10 @@ describe('upload_file_stream', () => { r = await handleUpload(mk({ stream_id: id, total_chunks: 3, is_complete: true, expected_sha256: sha })); const data = r.data as Record; - expect(data).toMatchObject({ type: 'response', status: 'file_complete', total_chunks: 3, file_size: full.length, sha256: sha }); + expect(data).toMatchObject({ + type: 'response', status: 'file_complete', total_chunks: 3, + file_size: full.length, sha256: sha, file_name: `upload_${id}`, + }); expect(fs.readFileSync(String(data.file_path), 'utf8')).toBe(full); // state dropped after completion, chunk dir gone expect(uploads.has(id)).toBe(false); @@ -97,6 +100,17 @@ describe('upload_file_stream', () => { await expect(handleUpload(mk({ stream_id: 'nope', verify_only: true }))).rejects.toThrow(/not found/i); }); + it('returns the original filename alongside the prefixed file_path (#361)', async () => { + const id = 'up-named'; + await handleUpload(mk({ + stream_id: id, total_chunks: 1, chunk_index: 0, chunk_data: b64('x'), filename: 'report.pdf', + })); + const r = await handleUpload(mk({ stream_id: id, total_chunks: 1, is_complete: true })); + const data = r.data as Record; + expect(data.file_name).toBe('report.pdf'); + expect(String(data.file_path)).toBe(path.join(STREAM_UPLOAD_DIR, `${id}__report.pdf`)); + }); + it('strips path separators from filename (no temp-dir escape)', async () => { const id = 'up-escape'; await handleUpload(mk({ stream_id: id, total_chunks: 1, chunk_index: 0, chunk_data: b64('x'), filename: '../../evil.sh' })); diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index d3087790..ee8e89b3 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proto-defs", - "version": "1.14.7", + "version": "1.14.8", "private": true, "type": "module", "description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).", diff --git a/packages/proto-defs/src/action.ts b/packages/proto-defs/src/action.ts index 9e58823c..424a9368 100644 --- a/packages/proto-defs/src/action.ts +++ b/packages/proto-defs/src/action.ts @@ -96,11 +96,24 @@ export interface MentionExtraSend { // Markdown commonElem (svc=45). Official DecodeMarkdownElement reads // content / process_msg / summary / extType / mdExtInfo. // extType=1 dispatches to DecodeMdExtInfoFileTransfer. +/** extInfo.thumbnail — cover download info, not raw image bytes. */ +export interface MarkdownFlashTransferThumbUrl { + field1?: pb<1, uint_32>; + downloadUrl?: pb<2, string>; +} + +export interface MarkdownFlashTransferThumb { + fileId?: pb<1, string>; + download?: pb<2, MarkdownFlashTransferThumbUrl>; + sha1?: pb<3, string>; + field4?: pb<4, uint_32>; +} + export interface MarkdownFlashTransferExt { filesetId?: pb<1, string>; name?: pb<2, string>; fileSize?: pb<3, uint_32>; - thumbnail?: pb<4, bytes>; + thumbnail?: pb<4, MarkdownFlashTransferThumb>; expireTime?: pb<6, uint_32>; } diff --git a/packages/protocol/package.json b/packages/protocol/package.json index b8b9a117..1a79c9dc 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/protocol", - "version": "1.14.7", + "version": "1.14.8", "private": true, "type": "module", "description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/'` collapses to `import { … } from '@snowluma/protocol/'`.", diff --git a/packages/protocol/src/element-manifest.ts b/packages/protocol/src/element-manifest.ts index 0cdef7af..ee5bd219 100644 --- a/packages/protocol/src/element-manifest.ts +++ b/packages/protocol/src/element-manifest.ts @@ -213,7 +213,7 @@ export const ELEMENT_MANIFEST = { }, flash_file: { directions: { D: 'yes', S: 'yes', P: 'by-design-no', W: 'by-design-no' }, - fields: fieldsFor<'flash_file'>()(['filesetId', 'sceneType', 'fileName']), + fields: fieldsFor<'flash_file'>()(['filesetId', 'sceneType', 'fileName', 'thumbUrl']), requiredFields: ['filesetId'], note: '闪传文件:收侧解码 markdown commonElem(旧卡 JSON data.fileSetId,现网 extType=1/extInfo + open_fileset scheme,#199/#200/#358);发送走 send_flash_msg,故 P/W 按设计不支持', }, diff --git a/packages/protocol/src/events.ts b/packages/protocol/src/events.ts index c77d1bc0..d17adc8d 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -191,6 +191,8 @@ export interface FlashFileElement { filesetId: string; sceneType?: number; fileName?: string; + /** Cover URL from the incoming card, when present. */ + thumbUrl?: string; } type MessageElementVariant = diff --git a/packages/protocol/src/msg-push/rich-body-decoder.ts b/packages/protocol/src/msg-push/rich-body-decoder.ts index ed6cb695..a4d061e2 100644 --- a/packages/protocol/src/msg-push/rich-body-decoder.ts +++ b/packages/protocol/src/msg-push/rich-body-decoder.ts @@ -1070,11 +1070,13 @@ function decodeFlashTransfer(md: MarkdownData): MessageElement | null { fileName = md.summary.replace(/^\[QQ闪传\]\s*/, '').trim(); } + const thumbUrl = (ext?.thumbnail?.download?.downloadUrl ?? '').trim(); return { type: 'flash_file', filesetId, fileName, sceneType: card?.sceneType ?? 0, + ...(thumbUrl ? { thumbUrl } : {}), }; } diff --git a/packages/protocol/tests/format.test.ts b/packages/protocol/tests/format.test.ts new file mode 100644 index 00000000..48a47daf --- /dev/null +++ b/packages/protocol/tests/format.test.ts @@ -0,0 +1,671 @@ +import { describe, expect, it } from 'vitest'; +import type { JsonObject, JsonValue } from '@snowluma/common/json'; +import type { QQEventVariant } from '@snowluma/protocol/events'; +import { + formatEvent, + formatGroup, + formatMessageSegments, + formatReply, + formatUser, + type ReplyEventLookup, +} from '@snowluma/protocol/format'; +import type { IdentityService } from '@snowluma/protocol/identity-service'; + +function stubIdentity(opts: { + groups?: Record; + members?: Record; + friends?: Record; +} = {}): IdentityService { + return { + findGroup: (groupId: number) => opts.groups?.[groupId] ?? null, + findGroupMember: (groupId: number, uin: number) => + opts.members?.[`${groupId}:${uin}`] ?? null, + findFriend: (uin: number) => opts.friends?.[uin] ?? null, + } as IdentityService; +} + +function throwingIdentity(): IdentityService { + return { + findGroup: () => { + throw new Error('identity unavailable'); + }, + findGroupMember: () => { + throw new Error('identity unavailable'); + }, + findFriend: () => { + throw new Error('identity unavailable'); + }, + } as IdentityService; +} + +function stubStore(events: Record): ReplyEventLookup { + return { + findEvent: (messageId: number) => events[messageId] ?? null, + }; +} + +describe('formatGroup', () => { + it('renders [name(id)] from a cached groupName', () => { + const identity = stubIdentity({ groups: { 778899: { groupName: '雪夜茶话' } } }); + expect(formatGroup(identity, 778899)).toBe('[雪夜茶话(778899)]'); + }); + + it('trims groupName before wrapping', () => { + const identity = stubIdentity({ groups: { 778899: { groupName: ' 雪夜茶话 ' } } }); + expect(formatGroup(identity, 778899)).toBe('[雪夜茶话(778899)]'); + }); + + it('falls back to the bare id when groupName is blank after trim', () => { + const identity = stubIdentity({ groups: { 778899: { groupName: ' ' } } }); + expect(formatGroup(identity, 778899)).toBe('778899'); + }); + + it('falls back to the bare id on cache miss', () => { + expect(formatGroup(stubIdentity(), 778899)).toBe('778899'); + }); + + it('maps 0 and other non-positive ids without a roster lookup', () => { + const identity = stubIdentity({ groups: { 0: { groupName: 'ghost' } } }); + expect(formatGroup(identity, 0)).toBe('0'); + expect(formatGroup(identity, -12)).toBe('-12'); + expect(formatGroup(identity, Number.NaN)).toBe('0'); + }); + + it('falls back to the bare id when findGroup throws', () => { + expect(formatGroup(throwingIdentity(), 778899)).toBe('778899'); + }); +}); + +describe('formatUser', () => { + it('prefers a group-member card over nickname', () => { + const identity = stubIdentity({ + members: { '778899:20001': { card: '冬至', nickname: '小满' } }, + }); + expect(formatUser(identity, 778899, 20001)).toBe('[冬至(20001)]'); + }); + + it('uses the member nickname when card is empty after trim', () => { + const identity = stubIdentity({ + members: { '778899:20001': { card: ' ', nickname: '小满' } }, + }); + expect(formatUser(identity, 778899, 20001)).toBe('[小满(20001)]'); + }); + + it('skips the member roster when groupId is missing or non-positive', () => { + const identity = stubIdentity({ + members: { '778899:20001': { card: '冬至' } }, + friends: { 20001: { remark: '谷雨', nickname: '小满' } }, + }); + expect(formatUser(identity, undefined, 20001)).toBe('[谷雨(20001)]'); + expect(formatUser(identity, 0, 20001)).toBe('[谷雨(20001)]'); + expect(formatUser(identity, -3, 20001)).toBe('[谷雨(20001)]'); + }); + + it('falls through to the friend nickname when remark is blank', () => { + const identity = stubIdentity({ + friends: { 30001: { remark: ' ', nickname: '惊蛰' } }, + }); + expect(formatUser(identity, undefined, 30001)).toBe('[惊蛰(30001)]'); + }); + + it('uses a friend after a group-member miss', () => { + const identity = stubIdentity({ + friends: { 20002: { remark: '白露' } }, + }); + expect(formatUser(identity, 778899, 20002)).toBe('[白露(20002)]'); + }); + + it('returns the bare uin when nothing is cached', () => { + expect(formatUser(stubIdentity(), 778899, 20001)).toBe('20001'); + }); + + it('returns the uid when uin is missing or non-positive', () => { + expect(formatUser(stubIdentity(), 778899, 0, 'u_winter')).toBe('u_winter'); + expect(formatUser(stubIdentity(), 778899, -8, 'u_neg')).toBe('u_neg'); + }); + + it('returns 0 when both uin and uid are missing', () => { + expect(formatUser(stubIdentity(), undefined, 0)).toBe('0'); + expect(formatUser(stubIdentity(), undefined, -8)).toBe('0'); + }); + + it('returns the bare uin when identity lookups throw', () => { + expect(formatUser(throwingIdentity(), 778899, 20001)).toBe('20001'); + expect(formatUser(throwingIdentity(), undefined, 20001)).toBe('20001'); + }); +}); + +describe('formatMessageSegments', () => { + it('renders a raw string and truncates past 50 characters', () => { + expect(formatMessageSegments('清明')).toBe('清明'); + expect(formatMessageSegments('雨'.repeat(51))).toBe(`${'雨'.repeat(50)}...`); + }); + + it('returns [空消息] for an empty string or a non-array payload', () => { + expect(formatMessageSegments('')).toBe('[空消息]'); + expect(formatMessageSegments([])).toBe('[空消息]'); + expect(formatMessageSegments(null)).toBe('[空消息]'); + expect(formatMessageSegments(42)).toBe('[空消息]'); + expect(formatMessageSegments({ type: 'text' })).toBe('[空消息]'); + }); + + it('skips non-object segments and still joins the rest', () => { + expect(formatMessageSegments([ + null, + 7, + 'skip', + ['nested'], + { type: 'text', data: { text: '立夏' } }, + { type: 'text', data: { text: '小暑' } }, + ])).toBe('立夏 小暑'); + }); + + it('treats a missing or non-object data field as empty segment data', () => { + expect(formatMessageSegments([{ type: 'text' }])).toBe('[空消息]'); + expect(formatMessageSegments([{ type: 'at', data: null }])).toBe('@'); + expect(formatMessageSegments([{ type: 'at', data: ['all'] }])).toBe('@'); + expect(formatMessageSegments([{ type: 'image', data: 'pic' }])).toBe('[图片]'); + }); + + it('renders each known segment type with its preview token', () => { + expect(formatMessageSegments([ + { type: 'text', data: { text: 'hi' } }, + { type: 'image', data: {} }, + { type: 'image', data: { emoji_id: 'e1', summary: '捂脸' } }, + { type: 'image', data: { emoji_id: 'e2' } }, + { type: 'face', data: { id: 1 } }, + { type: 'mface', data: { text: '旺柴' } }, + { type: 'mface', data: {} }, + { type: 'at', data: { qq: 20001 } }, + { type: 'at', data: { qq: 'all' } }, + { type: 'at', data: {} }, + { type: 'reply', data: { id: 4100 } }, + { type: 'reply', data: {} }, + { type: 'record', data: {} }, + { type: 'video', data: {} }, + { type: 'file', data: { name: 'notes.txt' } }, + { type: 'file', data: { file: 'old.bin' } }, + { type: 'file', data: {} }, + { type: 'xml', data: {} }, + { type: 'markdown', data: {} }, + { type: 'inline_keyboard', data: {} }, + { type: 'forward', data: {} }, + { type: 'poke', data: {} }, + { type: 'flash_file', data: { title: '图纸.dwg' } }, + { type: 'flash_file', data: {} }, + { type: 'mystery', data: {} }, + {}, + ])).toBe([ + 'hi', + '[图片]', + '[捂脸]', + '[表情]', + '[表情]', + '[旺柴]', + '[表情]', + '@20001', + '@全体成员', + '@', + '[回复:4100]', + '[回复:]', + '[语音]', + '[视频]', + '[文件:notes.txt]', + '[文件:old.bin]', + '[文件]', + '[XML]', + '[Markdown]', + '[交互按钮]', + '[聊天记录]', + '[窗口抖动]', + '[闪传文件:图纸.dwg]', + '[闪传文件]', + '[mystery]', + '[]', + ].join(' ')); + }); + + it('truncates file names and flash-file titles to 20 characters', () => { + const longName = 'abcdefghijABCDEFGHIJxyz'; + expect(formatMessageSegments([{ type: 'file', data: { name: longName } }])) + .toBe('[文件:abcdefghijABCDEFGHIJ...]'); + expect(formatMessageSegments([{ type: 'flash_file', data: { title: longName } }])) + .toBe('[闪传文件:abcdefghijABCDEFGHIJ...]'); + }); + + it('treats an empty file name as absent even if file is also empty', () => { + expect(formatMessageSegments([{ type: 'file', data: { name: '' } }])).toBe('[文件]'); + }); + + it('extracts json card titles from the documented ARK locations in order', () => { + const ranked = JSON.stringify({ + meta: { + detail_1: { title: '小程序名' }, + detail: { title: '详情名' }, + news: { title: '新闻名' }, + }, + prompt: '提示文案', + }); + expect(formatMessageSegments([{ type: 'json', data: { data: ranked } }])) + .toBe('[卡片:小程序名]'); + + expect(formatMessageSegments([{ + type: 'json', + data: { data: JSON.stringify({ meta: { detail: { title: '图文分享' } } }) }, + }])).toBe('[卡片:图文分享]'); + + expect(formatMessageSegments([{ + type: 'json', + data: { data: JSON.stringify({ meta: { news: { title: '头条' } } }) }, + }])).toBe('[卡片:头条]'); + + expect(formatMessageSegments([{ + type: 'json', + data: { data: JSON.stringify({ meta: { mannonce: { title: '群公告' } } }) }, + }])).toBe('[卡片:群公告]'); + + expect(formatMessageSegments([{ + type: 'json', + data: { data: JSON.stringify({ meta: { music: { title: '夜曲' } } }) }, + }])).toBe('[卡片:夜曲]'); + + expect(formatMessageSegments([{ + type: 'json', + data: { data: JSON.stringify({ meta: { video: { title: '短片' } } }) }, + }])).toBe('[卡片:短片]'); + }); + + it('uses the single remaining meta section title when the key is unknown', () => { + expect(formatMessageSegments([{ + type: 'json', + data: { data: JSON.stringify({ meta: { share_card: { title: '自定义卡片' } } }) }, + }])).toBe('[卡片:自定义卡片]'); + }); + + it('falls back to prompt, then desc, when meta has no usable title', () => { + expect(formatMessageSegments([{ + type: 'json', + data: { data: JSON.stringify({ + meta: { left: { title: '' }, right: { title: ' ' } }, + prompt: ' 请升级客户端 ', + }) }, + }])).toBe('[卡片:请升级客户端]'); + + expect(formatMessageSegments([{ + type: 'json', + data: { data: JSON.stringify({ desc: ' 简介文案 ' }) }, + }])).toBe('[卡片:简介文案]'); + }); + + it('truncates card titles to 30 characters', () => { + const prompt = '卡'.repeat(31); + expect(formatMessageSegments([{ + type: 'json', + data: { data: JSON.stringify({ prompt }) }, + }])).toBe(`[卡片:${'卡'.repeat(30)}...]`); + }); + + it('falls back to [JSON] when the payload has no extractable title', () => { + expect(formatMessageSegments([{ type: 'json', data: {} }])).toBe('[JSON]'); + expect(formatMessageSegments([{ type: 'json', data: { data: 1 } }])).toBe('[JSON]'); + expect(formatMessageSegments([{ type: 'json', data: { data: '' } }])).toBe('[JSON]'); + expect(formatMessageSegments([{ type: 'json', data: { data: '{broken' } }])).toBe('[JSON]'); + expect(formatMessageSegments([{ type: 'json', data: { data: 'null' } }])).toBe('[JSON]'); + expect(formatMessageSegments([{ type: 'json', data: { data: '12' } }])).toBe('[JSON]'); + expect(formatMessageSegments([{ type: 'json', data: { data: '[1]' } }])).toBe('[JSON]'); + expect(formatMessageSegments([{ + type: 'json', + data: { data: JSON.stringify({ meta: ['x'], prompt: '' }) }, + }])).toBe('[JSON]'); + expect(formatMessageSegments([{ + type: 'json', + data: { data: JSON.stringify({ meta: { a: { title: 9 }, b: { title: true } } }) }, + }])).toBe('[JSON]'); + expect(formatMessageSegments([{ + type: 'json', + data: { data: JSON.stringify({ meta: { only: ['not-object'] } }) }, + }])).toBe('[JSON]'); + expect(formatMessageSegments([{ + type: 'json', + data: { data: JSON.stringify({ foo: 1 }) }, + }])).toBe('[JSON]'); + }); + + it('returns [消息渲染异常] when walking the segment list throws', () => { + const broken = new Proxy([] as JsonValue[], { + get(target, prop, receiver) { + if (prop === Symbol.iterator) throw new Error('segment exploded'); + return Reflect.get(target, prop, receiver); + }, + }); + expect(formatMessageSegments(broken)).toBe('[消息渲染异常]'); + }); +}); + +describe('formatReply', () => { + const identity = stubIdentity({ + groups: { 778899: { groupName: '雪夜茶话' } }, + members: { '778899:20001': { card: '冬至' } }, + }); + + it('renders [回复:0] when the reply id is missing', () => { + expect(formatReply(stubStore({}), identity, 0)).toBe('[回复:0]'); + expect(formatReply(stubStore({}), identity, Number.NaN)).toBe('[回复:0]'); + }); + + it('renders [回复:] when the store has no matching event', () => { + expect(formatReply(stubStore({}), identity, 4100)).toBe('[回复:4100]'); + }); + + it('resolves a group reply from the identity roster', () => { + const store = stubStore({ + 4100: { + message_type: 'group', + group_id: 778899, + user_id: 20001, + message: [{ type: 'text', data: { text: '霜降好' } }], + }, + }); + expect(formatReply(store, identity, 4100)).toBe('[回复 [冬至(20001)]: 霜降好]'); + }); + + it('coerces string user_id / group_id and uses the stored sender card on cache miss', () => { + const store = stubStore({ + 4101: { + message_type: 'group', + group_id: '778899', + user_id: '20003', + sender: { card: '处暑', nickname: 'ignored' }, + message: '晚风', + }, + }); + expect(formatReply(store, stubIdentity(), 4101)).toBe('[回复 [处暑(20003)]: 晚风]'); + }); + + it('does not treat private messages as group and ignores a whitespace-only card', () => { + const store = stubStore({ + 4102: { + message_type: 'private', + group_id: 778899, + user_id: 20001, + sender: { card: ' ', nickname: '寒露' }, + message: [{ type: 'text', data: { text: '私聊一句' } }], + }, + }); + // Fallback is `(card || nickname).trim()`: a whitespace card is truthy + // before trim, so the nickname is not used. + expect(formatReply(store, stubIdentity(), 4102)).toBe('[回复 20001: 私聊一句]'); + }); + + it('uses sender.nickname when card is absent', () => { + const store = stubStore({ + 4102: { + message_type: 'private', + user_id: 20001, + sender: { nickname: '寒露' }, + message: [{ type: 'text', data: { text: '私聊一句' } }], + }, + }); + expect(formatReply(store, stubIdentity(), 4102)).toBe('[回复 [寒露(20001)]: 私聊一句]'); + }); + + it('keeps the bare uin when sender is not a usable object', () => { + const noSender = stubStore({ + 4103: { + message_type: 'private', + user_id: 20004, + sender: null, + message: 'x', + }, + }); + expect(formatReply(noSender, stubIdentity(), 4103)).toBe('[回复 20004: x]'); + + const arraySender = stubStore({ + 4104: { + message_type: 'private', + user_id: 20004, + sender: ['寒露'], + message: 'y', + }, + }); + expect(formatReply(arraySender, stubIdentity(), 4104)).toBe('[回复 20004: y]'); + }); + + it('maps non-numeric user_id to 0 and skips the sender-name fallback', () => { + const store = stubStore({ + 4105: { + message_type: 'private', + user_id: 'not-a-uin', + sender: { nickname: '不该出现' }, + message: 'z', + }, + }); + expect(formatReply(store, stubIdentity(), 4105)).toBe('[回复 0: z]'); + }); + + it('truncates the body preview to 30 characters after segment rendering', () => { + const store = stubStore({ + 4106: { + message_type: 'private', + user_id: 20004, + message: [{ type: 'text', data: { text: '正'.repeat(80) } }], + }, + }); + expect(formatReply(store, stubIdentity(), 4106)) + .toBe(`[回复 20004: ${'正'.repeat(30)}...]`); + }); + + it('renders referenced reply segments as tokens instead of recursing', () => { + const store = stubStore({ + 4107: { + message_type: 'private', + user_id: 20004, + message: [{ type: 'reply', data: { id: 1 } }, { type: 'text', data: { text: '外层' } }], + }, + }); + expect(formatReply(store, stubIdentity(), 4107)).toBe('[回复 20004: [回复:1] 外层]'); + }); + + it('returns [回复:] when findEvent throws', () => { + const store: ReplyEventLookup = { + findEvent: () => { + throw new Error('store unavailable'); + }, + }; + expect(formatReply(store, identity, 4100)).toBe('[回复:4100]'); + }); +}); + +describe('formatEvent', () => { + const identity = stubIdentity({ + groups: { 778899: { groupName: '雪夜茶话' } }, + members: { + '778899:20001': { card: '冬至' }, + '778899:20002': { card: '小满' }, + '778899:20003': { nickname: '谷雨' }, + }, + friends: { + 30001: { nickname: '惊蛰' }, + 30002: { remark: '白露' }, + }, + }); + + it('returns null for kinds that have dedicated message-log paths', () => { + expect(formatEvent(identity, { kind: 'group_message' } as QQEventVariant)).toBeNull(); + expect(formatEvent(identity, { kind: 'friend_message' } as QQEventVariant)).toBeNull(); + expect(formatEvent(identity, { kind: 'temp_message' } as QQEventVariant)).toBeNull(); + expect(formatEvent(identity, { kind: 'group_file_upload' } as QQEventVariant)).toBeNull(); + expect(formatEvent(identity, { kind: 'friend_add' } as QQEventVariant)).toBeNull(); + }); + + it('returns null for kinds with no notice-line renderer', () => { + expect(formatEvent(identity, { kind: 'bot_offline' } as QQEventVariant)).toBeNull(); + expect(formatEvent(identity, { kind: 'ptt_trans_result' } as QQEventVariant)).toBeNull(); + expect(formatEvent(identity, { kind: 'group_card_change' } as QQEventVariant)).toBeNull(); + expect(formatEvent(identity, { kind: 'friend_input_status' } as QQEventVariant)).toBeNull(); + }); + + it('renders group_recall', () => { + expect(formatEvent(identity, { + kind: 'group_recall', + groupId: 778899, + authorUin: 20001, + operatorUin: 20002, + } as QQEventVariant)).toBe('群撤回 [雪夜茶话(778899)] | [冬至(20001)] 被 [小满(20002)] 撤回'); + }); + + it('renders friend_recall', () => { + expect(formatEvent(identity, { + kind: 'friend_recall', + userUin: 30001, + } as QQEventVariant)).toBe('私聊撤回 [惊蛰(30001)] 撤回了消息'); + }); + + it('renders group_member_join including a uid-only joiner', () => { + expect(formatEvent(identity, { + kind: 'group_member_join', + groupId: 778899, + userUin: 20003, + userUid: 'u_guyu', + } as QQEventVariant)).toBe('入群 [谷雨(20003)] 加入 [雪夜茶话(778899)]'); + + expect(formatEvent(identity, { + kind: 'group_member_join', + groupId: 778899, + userUin: 0, + userUid: 'u_only', + } as QQEventVariant)).toBe('入群 u_only 加入 [雪夜茶话(778899)]'); + }); + + it('renders group_member_leave for leave, kick, and disband', () => { + expect(formatEvent(identity, { + kind: 'group_member_leave', + groupId: 778899, + userUin: 20001, + leaveType: 'leave', + } as QQEventVariant)).toBe('退群 [冬至(20001)] 退出 [雪夜茶话(778899)]'); + + expect(formatEvent(identity, { + kind: 'group_member_leave', + groupId: 778899, + userUin: 20001, + leaveType: 'kick', + } as QQEventVariant)).toBe('退群 [冬至(20001)] 被踢出 [雪夜茶话(778899)]'); + + expect(formatEvent(identity, { + kind: 'group_member_leave', + groupId: 778899, + userUin: 20001, + leaveType: 'disband', + } as QQEventVariant)).toBe('退群 [冬至(20001)] 随群解散 [雪夜茶话(778899)]'); + }); + + it('renders group_mute with the duration in seconds', () => { + expect(formatEvent(identity, { + kind: 'group_mute', + groupId: 778899, + userUin: 20001, + duration: 600, + } as QQEventVariant)).toBe('禁言 [雪夜茶话(778899)] | [冬至(20001)] 600秒'); + }); + + it('renders group_admin set and unset', () => { + expect(formatEvent(identity, { + kind: 'group_admin', + groupId: 778899, + userUin: 20002, + set: true, + } as QQEventVariant)).toBe('管理 [雪夜茶话(778899)] | [小满(20002)] +管理员'); + + expect(formatEvent(identity, { + kind: 'group_admin', + groupId: 778899, + userUin: 20002, + set: false, + } as QQEventVariant)).toBe('管理 [雪夜茶话(778899)] | [小满(20002)] -管理员'); + }); + + it('renders friend_poke and group_poke', () => { + expect(formatEvent(identity, { + kind: 'friend_poke', + peerUin: 30001, + senderUin: 30002, + targetUin: 30001, + } as QQEventVariant)).toBe('私聊戳 [惊蛰(30001)] | [白露(30002)] -> [惊蛰(30001)]'); + + expect(formatEvent(identity, { + kind: 'group_poke', + groupId: 778899, + userUin: 20001, + targetUin: 20002, + } as QQEventVariant)).toBe('群戳 [雪夜茶话(778899)] | [冬至(20001)] -> [小满(20002)]'); + }); + + it('renders friend_request and group_invite', () => { + expect(formatEvent(identity, { + kind: 'friend_request', + fromUin: 30002, + message: '加个好友', + } as QQEventVariant)).toBe('好友请求 [白露(30002)]: 加个好友'); + + expect(formatEvent(identity, { + kind: 'group_invite', + fromUin: 30001, + groupId: 778899, + } as QQEventVariant)).toBe('群邀请 [惊蛰(30001)] -> [雪夜茶话(778899)]'); + }); + + it('renders group_essence set and unset', () => { + expect(formatEvent(identity, { + kind: 'group_essence', + groupId: 778899, + set: true, + } as QQEventVariant)).toBe('精华 [雪夜茶话(778899)] | +精华'); + + expect(formatEvent(identity, { + kind: 'group_essence', + groupId: 778899, + set: false, + } as QQEventVariant)).toBe('精华 [雪夜茶话(778899)] | -精华'); + }); + + it('renders group_msg_emoji_like add and remove', () => { + expect(formatEvent(identity, { + kind: 'group_msg_emoji_like', + groupId: 778899, + operatorUin: 20001, + operatorUid: 'u_dongzhi', + emojiId: '76', + msgSeq: 8801, + isAdd: true, + } as QQEventVariant)).toBe('表情回应 [雪夜茶话(778899)] | [冬至(20001)] +[76] msgSeq=8801'); + + expect(formatEvent(identity, { + kind: 'group_msg_emoji_like', + groupId: 778899, + operatorUin: 0, + operatorUid: 'u_dongzhi', + emojiId: 'ok', + msgSeq: 8802, + isAdd: false, + } as QQEventVariant)).toBe('表情回应 [雪夜茶话(778899)] | u_dongzhi -[ok] msgSeq=8802'); + }); + + it('degrades to numeric ids when the roster is empty', () => { + expect(formatEvent(stubIdentity(), { + kind: 'group_recall', + groupId: 778899, + authorUin: 20001, + operatorUin: 20002, + } as QQEventVariant)).toBe('群撤回 778899 | 20001 被 20002 撤回'); + }); + + it('returns null when reading the event kind throws', () => { + const broken = { + get kind() { + throw new Error('event exploded'); + }, + } as unknown as QQEventVariant; + expect(formatEvent(identity, broken)).toBeNull(); + }); +}); diff --git a/packages/protocol/tests/highway/hash-file.test.ts b/packages/protocol/tests/highway/hash-file.test.ts new file mode 100644 index 00000000..501c33f2 --- /dev/null +++ b/packages/protocol/tests/highway/hash-file.test.ts @@ -0,0 +1,286 @@ +// Streaming hasher must be byte-identical to the buffered helpers over the +// same bytes: computeHashes + computeVideoSha1Blocks (+ computeMd5 of the +// head) for hashFileStreaming, and computeHashes + computeSha1StateV for +// hashFlashFileStreaming. Flash Sha1StateV is not video sha1Blocks. + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { createHash } from 'node:crypto'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { hashFileStreaming, hashFlashFileStreaming } from '@snowluma/protocol/highway/hash-file'; +import { computeHashes, computeMd5 } from '@snowluma/protocol/highway/utils'; +import { computeSha1StateV, Sha1Stream } from '@snowluma/protocol/highway/sha1-stream'; +import { computeVideoSha1Blocks } from '../../src/highway/video-upload'; + +const MB = 1024 * 1024; + +// Same generator as video-sha1-blocks.test.ts (and its golden-capture script). +function det(len: number): Uint8Array { + const b = new Uint8Array(len); + for (let i = 0; i < len; i++) b[i] = (i * 31 + 7) & 0xff; + return b; +} + +function hex(u: Uint8Array): string { + return Buffer.from(u).toString('hex'); +} + +function nodeMd5Hex(data: Uint8Array): string { + return createHash('md5').update(Buffer.from(data)).digest('hex'); +} + +function nodeSha1Hex(data: Uint8Array): string { + return createHash('sha1').update(Buffer.from(data)).digest('hex'); +} + +describe('hashFileStreaming', () => { + let dir: string; + beforeAll(async () => { + dir = await mkdtemp(join(tmpdir(), 'sl-hash-file-')); + }); + afterAll(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + async function writeBin(name: string, data: Uint8Array): Promise { + const file = join(dir, name); + await writeFile(file, data); + return file; + } + + it('empty file: well-known empty digests and a single finalized sha1 block', async () => { + const file = await writeBin('empty.bin', new Uint8Array(0)); + const streamed = await hashFileStreaming(file); + + expect(streamed.md5Hex).toBe('d41d8cd98f00b204e9800998ecf8427e'); + expect(streamed.sha1Hex).toBe('da39a3ee5e6b4b0d3255bfef95601890afd80709'); + expect(hex(streamed.md5)).toBe('d41d8cd98f00b204e9800998ecf8427e'); + expect(hex(streamed.sha1)).toBe('da39a3ee5e6b4b0d3255bfef95601890afd80709'); + expect(streamed.headMd5).toBeUndefined(); + expect(streamed.sha1Blocks.map(hex)).toEqual([ + 'da39a3ee5e6b4b0d3255bfef95601890afd80709', + ]); + }); + + it('empty file with headLimit still yields md5 of zero bytes', async () => { + const file = await writeBin('empty-head.bin', new Uint8Array(0)); + const streamed = await hashFileStreaming(file, { headLimit: 10 }); + expect(hex(streamed.headMd5!)).toBe('d41d8cd98f00b204e9800998ecf8427e'); + expect(streamed.md5Hex).toBe('d41d8cd98f00b204e9800998ecf8427e'); + }); + + it('sub-1 MiB file matches RFC hashes and has only the finalized sha1 block', async () => { + const data = Buffer.from('abc', 'utf8'); + const file = await writeBin('abc.bin', data); + const streamed = await hashFileStreaming(file); + + expect(streamed.md5Hex).toBe('900150983cd24fb0d6963f7d28e17f72'); + expect(streamed.sha1Hex).toBe('a9993e364706816aba3e25717850c26c9cd0d89d'); + expect(streamed.sha1Blocks.map(hex)).toEqual([ + 'a9993e364706816aba3e25717850c26c9cd0d89d', + ]); + expect(streamed.headMd5).toBeUndefined(); + }); + + it('det(1000) matches computeHashes + computeVideoSha1Blocks + Node crypto', async () => { + const data = det(1000); + const file = await writeBin('det-1000.bin', data); + const streamed = await hashFileStreaming(file); + const buffered = computeHashes(data); + + expect(streamed.md5Hex).toBe(nodeMd5Hex(data)); + expect(streamed.sha1Hex).toBe(nodeSha1Hex(data)); + expect(hex(streamed.md5)).toBe(hex(buffered.md5)); + expect(hex(streamed.sha1)).toBe(hex(buffered.sha1)); + expect(streamed.md5Hex).toBe(buffered.md5Hex); + expect(streamed.sha1Hex).toBe(buffered.sha1Hex); + expect(streamed.sha1Blocks.map(hex)).toEqual(computeVideoSha1Blocks(data).map(hex)); + expect(streamed.sha1Blocks).toHaveLength(1); + }); + + it('exact 1 MiB emits an un-finalized boundary state then the overall sha1', async () => { + const data = det(MB); + const file = await writeBin('exact-1m.bin', data); + const streamed = await hashFileStreaming(file); + const overall = nodeSha1Hex(data); + const prefixDigest = nodeSha1Hex(data); // whole file *is* the first slice + const manual = new Sha1Stream(); + manual.update(data); + + expect(streamed.md5Hex).toBe(nodeMd5Hex(data)); + expect(streamed.sha1Hex).toBe(overall); + expect(streamed.sha1Blocks).toHaveLength(2); + expect(hex(streamed.sha1Blocks[0]!)).toBe(hex(manual.hash(true))); + expect(hex(streamed.sha1Blocks[0]!)).not.toBe(prefixDigest); + expect(hex(streamed.sha1Blocks[1]!)).toBe(overall); + expect(streamed.sha1Blocks.map(hex)).toEqual(computeVideoSha1Blocks(data).map(hex)); + }); + + it('2 MiB + 12345 reproduces the video-sha1-blocks golden states', async () => { + const data = det(2 * MB + 12345); + const file = await writeBin('golden-2m.bin', data); + const streamed = await hashFileStreaming(file); + + expect(streamed.sha1Blocks.map(hex)).toEqual([ + 'ab9a20fd6c98fc1f8f0c985cd552ff14c6feacfd', + '2ccc5923b75f46ebd8ccb78e8c413c18025178b9', + 'dd9cfd4648ab460260afa820c98bfec1b17655d4', + ]); + expect(streamed.sha1Hex).toBe('dd9cfd4648ab460260afa820c98bfec1b17655d4'); + expect(streamed.md5Hex).toBe(nodeMd5Hex(data)); + expect(streamed.sha1Blocks.map(hex)).toEqual(computeVideoSha1Blocks(data).map(hex)); + }); + + it('omitting opts leaves headMd5 undefined', async () => { + const file = await writeBin('no-opts.bin', det(64)); + const streamed = await hashFileStreaming(file); + expect(streamed.headMd5).toBeUndefined(); + }); + + it('headLimit 0 is present and is the empty-md5', async () => { + const file = await writeBin('head-0.bin', det(200)); + const streamed = await hashFileStreaming(file, { headLimit: 0 }); + expect(hex(streamed.headMd5!)).toBe('d41d8cd98f00b204e9800998ecf8427e'); + expect(streamed.md5Hex).toBe(nodeMd5Hex(det(200))); + }); + + it('headMd5 is computeMd5 of the first N bytes inside the first 1 MiB chunk', async () => { + const data = det(8000); + const file = await writeBin('head-inside.bin', data); + const streamed = await hashFileStreaming(file, { headLimit: 10 }); + expect(hex(streamed.headMd5!)).toBe(hex(computeMd5(data.subarray(0, 10)))); + expect(hex(streamed.headMd5!)).toBe(nodeMd5Hex(data.subarray(0, 10))); + }); + + it('headMd5 across a 1 MiB boundary matches computeMd5 of the clamped prefix', async () => { + const data = det(MB + 500); + const file = await writeBin('head-span.bin', data); + const cases: Array<[number, number]> = [ + [MB - 1, MB - 1], + [MB, MB], + [MB + 1, MB + 1], + [data.length + 1, data.length], + ]; + for (const [limit, take] of cases) { + const streamed = await hashFileStreaming(file, { headLimit: limit }); + expect(hex(streamed.headMd5!)).toBe(hex(computeMd5(data.subarray(0, take)))); + expect(streamed.md5Hex).toBe(nodeMd5Hex(data)); + expect(streamed.sha1Hex).toBe(nodeSha1Hex(data)); + } + }); + + it('rejects a missing path from stat before hashing', async () => { + await expect(hashFileStreaming(join(dir, 'no-such.bin'))).rejects.toMatchObject({ + code: 'ENOENT', + }); + }); +}); + +describe('hashFlashFileStreaming', () => { + let dir: string; + beforeAll(async () => { + dir = await mkdtemp(join(tmpdir(), 'sl-flash-hash-file-')); + }); + afterAll(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + async function writeBin(name: string, data: Uint8Array): Promise { + const file = join(dir, name); + await writeFile(file, data); + return file; + } + + it('empty file: empty digests, sliceCount 0, no Sha1StateV entries', async () => { + const file = await writeBin('empty.bin', new Uint8Array(0)); + const streamed = await hashFlashFileStreaming(file); + + expect(streamed.md5Hex).toBe('d41d8cd98f00b204e9800998ecf8427e'); + expect(streamed.sha1Hex).toBe('da39a3ee5e6b4b0d3255bfef95601890afd80709'); + expect(streamed.sliceCount).toBe(0); + expect(streamed.sha1StateV).toEqual([]); + }); + + it('sub-1 MiB file is a single finalized slice', async () => { + const data = Buffer.from('abc', 'utf8'); + const file = await writeBin('abc.bin', data); + const streamed = await hashFlashFileStreaming(file); + + expect(streamed.sliceCount).toBe(1); + expect(streamed.md5Hex).toBe('900150983cd24fb0d6963f7d28e17f72'); + expect(streamed.sha1Hex).toBe('a9993e364706816aba3e25717850c26c9cd0d89d'); + expect(streamed.sha1StateV.map(hex)).toEqual([ + 'a9993e364706816aba3e25717850c26c9cd0d89d', + ]); + }); + + it('exact 1 MiB omits the extra un-finalized last-slice state video sha1Blocks keeps', async () => { + const data = det(MB); + const file = await writeBin('exact-1m.bin', data); + const flash = await hashFlashFileStreaming(file); + const video = await hashFileStreaming(file); + const overall = nodeSha1Hex(data); + const refState = computeSha1StateV(data, 1, MB); + + expect(flash.sliceCount).toBe(1); + expect(flash.sha1StateV).toHaveLength(1); + expect(hex(flash.sha1StateV[0]!)).toBe(overall); + expect(hex(flash.sha1StateV[0]!)).toBe(hex(refState[0]!)); + expect(video.sha1Blocks).toHaveLength(2); + expect(hex(flash.sha1StateV[0]!)).toBe(hex(video.sha1Blocks[1]!)); + expect(hex(flash.sha1StateV[0]!)).not.toBe(hex(video.sha1Blocks[0]!)); + expect(flash.md5Hex).toBe(nodeMd5Hex(data)); + }); + + it('1 MiB + 1: first state is the un-finalized 1 MiB snapshot', async () => { + const data = det(MB + 1); + const file = await writeBin('1m-plus.bin', data); + const flash = await hashFlashFileStreaming(file); + const manual = new Sha1Stream(); + manual.update(data.subarray(0, MB)); + const refState = computeSha1StateV(data, 2, MB); + + expect(flash.sliceCount).toBe(2); + expect(flash.sha1StateV).toHaveLength(2); + expect(hex(flash.sha1StateV[0]!)).toBe(hex(manual.hash(true))); + expect(hex(flash.sha1StateV[0]!)).not.toBe(nodeSha1Hex(data.subarray(0, MB))); + expect(hex(flash.sha1StateV[1]!)).toBe(nodeSha1Hex(data)); + expect(flash.sha1StateV.map(hex)).toEqual(refState.map(hex)); + }); + + it('exact 2 MiB: flash has 2 states, video sha1Blocks has 3', async () => { + const data = det(2 * MB); + const file = await writeBin('exact-2m.bin', data); + const flash = await hashFlashFileStreaming(file); + const video = await hashFileStreaming(file); + + expect(flash.sliceCount).toBe(2); + expect(flash.sha1StateV).toHaveLength(2); + expect(video.sha1Blocks).toHaveLength(3); + expect(hex(flash.sha1StateV[0]!)).toBe(hex(video.sha1Blocks[0]!)); + expect(hex(flash.sha1StateV[1]!)).toBe(hex(video.sha1Blocks[2]!)); + expect(hex(flash.sha1StateV[1]!)).toBe(nodeSha1Hex(data)); + expect(flash.sha1StateV.map(hex)).toEqual(computeSha1StateV(data, 2, MB).map(hex)); + expect(flash.md5Hex).toBe(computeHashes(data).md5Hex); + }); + + it('2 MiB + 12345 Sha1StateV matches computeSha1StateV and Node overall sha1', async () => { + const data = det(2 * MB + 12345); + const file = await writeBin('golden-2m.bin', data); + const flash = await hashFlashFileStreaming(file); + + expect(flash.sliceCount).toBe(3); + expect(flash.sha1Hex).toBe('dd9cfd4648ab460260afa820c98bfec1b17655d4'); + expect(hex(flash.sha1StateV[2]!)).toBe('dd9cfd4648ab460260afa820c98bfec1b17655d4'); + expect(hex(flash.sha1StateV[0]!)).toBe('ab9a20fd6c98fc1f8f0c985cd552ff14c6feacfd'); + expect(hex(flash.sha1StateV[1]!)).toBe('2ccc5923b75f46ebd8ccb78e8c413c18025178b9'); + expect(flash.sha1StateV.map(hex)).toEqual(computeSha1StateV(data, 3, MB).map(hex)); + }); + + it('rejects a missing path from stat before hashing', async () => { + await expect(hashFlashFileStreaming(join(dir, 'no-such.bin'))).rejects.toMatchObject({ + code: 'ENOENT', + }); + }); +}); diff --git a/packages/protocol/tests/highway/stage.test.ts b/packages/protocol/tests/highway/stage.test.ts new file mode 100644 index 00000000..1cb98da2 --- /dev/null +++ b/packages/protocol/tests/highway/stage.test.ts @@ -0,0 +1,468 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { randomUUID } from 'crypto'; +import fs, { promises as fsp } from 'fs'; +import os from 'os'; +import path from 'path'; +import { pathToFileURL } from 'url'; +import { STAGE_DIR, stageSourceToDisk, sweepStagedUploads } from '@snowluma/protocol/highway/stage'; + +const DOWNLOAD_UA = + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'; +const STAGE_TTL_MS = 30 * 60 * 1000; +const SNOW_BYTES = Buffer.from([0x53, 0x4e, 0x4f, 0x57]); + +const live: Array<{ cleanup(): Promise }> = []; +let scratch = ''; + +function hold }>(staged: T): T { + live.push(staged); + return staged; +} + +async function stageNames(): Promise { + try { + return await fsp.readdir(STAGE_DIR); + } catch { + return []; + } +} + +async function newPartNames(before: readonly string[]): Promise { + const prior = new Set(before); + return (await stageNames()).filter((name) => name.endsWith('.part') && !prior.has(name)); +} + +function expectStagedPath(filePath: string, ext: string): void { + expect(filePath.startsWith(`${STAGE_DIR}${path.sep}`)).toBe(true); + expect(path.basename(filePath)).toMatch( + new RegExp(`^stage-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}${ext.replaceAll('.', '\\.')}$`), + ); +} + +beforeEach(async () => { + scratch = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-proto-stage-')); +}); + +afterEach(async () => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + while (live.length > 0) { + await live.pop()!.cleanup(); + } + await fsp.rm(scratch, { recursive: true, force: true }); +}); + +describe('STAGE_DIR', () => { + it('is os.tmpdir()/media-stage', () => { + expect(STAGE_DIR).toBe(path.join(os.tmpdir(), 'media-stage')); + }); +}); + +describe('stageSourceToDisk — empty / classification', () => { + it('rejects an empty source before touching disk', async () => { + const before = await stageNames(); + await expect(stageSourceToDisk('', 64)).rejects.toThrow('stage source is empty'); + expect(await stageNames()).toEqual(before); + }); + + it('rejects a data URL that is missing the comma separator', async () => { + await expect(stageSourceToDisk('data:image/png;base64', 64)).rejects.toThrow( + 'data URL source is missing its payload separator', + ); + }); + + it('rejects a data URL that is not base64-encoded', async () => { + await expect(stageSourceToDisk('data:text/plain,hello', 64)).rejects.toThrow( + 'data URL source must use base64 encoding', + ); + }); + + it('rejects a missing local path via realpath', async () => { + const missing = path.join(scratch, 'no-such-file.bin'); + await expect(stageSourceToDisk(missing, 64)).rejects.toThrow(/ENOENT/); + }); +}); + +describe('stageSourceToDisk — base64', () => { + it('writes base64:// bytes to a .bin stage file with an empty fileName', async () => { + const staged = hold(await stageSourceToDisk('base64://U05PVw==', 64)); + expect(staged.fileSize).toBe(4); + expect(staged.fileName).toBe(''); + expectStagedPath(staged.filePath, '.bin'); + expect(await fsp.readFile(staged.filePath)).toEqual(SNOW_BYTES); + }); + + it('accepts a case-insensitive BASE64:// prefix and one-byte padding', async () => { + const staged = hold(await stageSourceToDisk('BASE64:///w==', 1)); + expect(staged.fileSize).toBe(1); + expect(staged.fileName).toBe(''); + expect(await fsp.readFile(staged.filePath)).toEqual(Buffer.from([0xff])); + }); + + it('accepts two-byte and three-byte payloads at the decoded-size ceiling', async () => { + const two = hold(await stageSourceToDisk('base64://AAA=', 2)); + const three = hold(await stageSourceToDisk('base64://AAAA', 3)); + expect(two.fileSize).toBe(2); + expect(three.fileSize).toBe(3); + expect(await fsp.readFile(two.filePath)).toEqual(Buffer.from([0x00, 0x00])); + expect(await fsp.readFile(three.filePath)).toEqual(Buffer.from([0x00, 0x00, 0x00])); + }); + + it('stages an RFC 2397 data URL and keeps fileName empty', async () => { + const staged = hold(await stageSourceToDisk('data:image/png;base64,U05PVw==', 4)); + expect(staged.fileSize).toBe(4); + expect(staged.fileName).toBe(''); + expect(await fsp.readFile(staged.filePath)).toEqual(SNOW_BYTES); + }); + + it('accepts DATA:…;BASE64, payloads (case-insensitive metadata)', async () => { + const staged = hold(await stageSourceToDisk('DATA:application/octet-stream;BASE64,AA==', 1)); + expect(staged.fileSize).toBe(1); + expect(await fsp.readFile(staged.filePath)).toEqual(Buffer.from([0x00])); + }); + + it('strips non-base64 characters before the decoded-length check', async () => { + const staged = hold(await stageSourceToDisk('base64://U05P\nVw==', 4)); + expect(staged.fileSize).toBe(4); + expect(await fsp.readFile(staged.filePath)).toEqual(SNOW_BYTES); + }); + + it('stages an empty base64:// payload as a zero-byte file', async () => { + const staged = hold(await stageSourceToDisk('base64://', 0)); + expect(staged.fileSize).toBe(0); + expect(staged.fileName).toBe(''); + expect(await fsp.readFile(staged.filePath)).toEqual(Buffer.alloc(0)); + }); + + it('rejects oversized base64 on decoded length and leaves no new .part', async () => { + const before = await stageNames(); + await expect(stageSourceToDisk('base64://aGVsbG8=', 4)).rejects.toThrow('stage source too large: 5 > 4'); + expect(await newPartNames(before)).toEqual([]); + }); + + it('rejects an oversized data URL on decoded length and leaves no new .part', async () => { + const before = await stageNames(); + await expect(stageSourceToDisk('data:audio/ogg;base64,aGVsbG8=', 4)).rejects.toThrow( + 'stage source too large: 5 > 4', + ); + expect(await newPartNames(before)).toEqual([]); + }); + + it('unlinks the .part when finalize rename fails', async () => { + const before = await stageNames(); + vi.spyOn(fsp, 'rename').mockRejectedValueOnce(new Error('rename failed')); + await expect(stageSourceToDisk('base64://U05PVw==', 64)).rejects.toThrow('rename failed'); + expect(await newPartNames(before)).toEqual([]); + }); +}); + +describe('stageSourceToDisk — http', () => { + it('streams the body to disk and uses the decoded URL basename', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(Uint8Array.from([0x10, 0x20, 0x30, 0x40]), { status: 200 })), + ); + const staged = hold(await stageSourceToDisk('https://media.example.test/packs/clip%20v2.mp4?sig=9', 64)); + expect(staged.fileName).toBe('clip v2.mp4'); + expect(staged.fileSize).toBe(4); + expectStagedPath(staged.filePath, '.bin'); + expect(await fsp.readFile(staged.filePath)).toEqual(Buffer.from([0x10, 0x20, 0x30, 0x40])); + }); + + it('keeps fileName empty when the URL has no basename', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response(Uint8Array.from([0x7f]), { status: 200 }))); + const staged = hold(await stageSourceToDisk('https://media.example.test/', 8)); + expect(staged.fileName).toBe(''); + expect(staged.fileSize).toBe(1); + expect(await fsp.readFile(staged.filePath)).toEqual(Buffer.from([0x7f])); + }); + + it('creates an empty staged file for an empty HTTP body', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response(new Uint8Array(0), { status: 200 }))); + const staged = hold(await stageSourceToDisk('HTTP://cdn.example.test/empty.bin', 8)); + expect(staged.fileName).toBe('empty.bin'); + expect(staged.fileSize).toBe(0); + expect(await fsp.readFile(staged.filePath)).toEqual(Buffer.alloc(0)); + }); + + it('rejects a declared Content-Length overflow without retrying and leaves no .part', async () => { + const fetchMock = vi.fn(async () => new Response(new Uint8Array(80), { + status: 200, + headers: { 'content-length': '80' }, + })); + vi.stubGlobal('fetch', fetchMock); + const before = await stageNames(); + await expect(stageSourceToDisk('https://cdn.example.test/huge.bin', 16)).rejects.toThrow( + 'stage too large: 80 > 16', + ); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(await newPartNames(before)).toEqual([]); + }); + + it('rejects a streamed overflow after the sink opened and discards the .part', async () => { + const stream = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(10).fill(0x11)); + controller.enqueue(new Uint8Array(10).fill(0x22)); + controller.enqueue(new Uint8Array(10).fill(0x33)); + controller.close(); + }, + }); + vi.stubGlobal('fetch', vi.fn(async () => new Response(stream, { status: 200 }))); + const before = await stageNames(); + await expect(stageSourceToDisk('https://cdn.example.test/stream.bin', 16)).rejects.toThrow( + 'stage too large: > 16', + ); + expect(await newPartNames(before)).toEqual([]); + }); + + it('retries once with Referer after a non-size failure and stages the retry body', async () => { + const url = 'https://media.example.test/packs/retry.bin'; + const fetchMock = vi.fn(async (_input: string, init?: RequestInit) => { + const headers = init?.headers as Record; + if (!headers.Referer) throw new TypeError('fetch failed'); + expect(headers.Referer).toBe(url); + expect(headers['User-Agent']).toBe(DOWNLOAD_UA); + expect(headers.Accept).toBe('*/*'); + expect(init?.redirect).toBe('follow'); + return new Response(Uint8Array.from([0xaa, 0xbb, 0xcc]), { status: 200 }); + }); + vi.stubGlobal('fetch', fetchMock); + const staged = hold(await stageSourceToDisk(url, 32)); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(staged.fileSize).toBe(3); + expect(await fsp.readFile(staged.filePath)).toEqual(Buffer.from([0xaa, 0xbb, 0xcc])); + }); + + it('surfaces the first HTTP status error when the Referer retry also fails', async () => { + const fetchMock = vi.fn(async () => new Response(null, { status: 503 })); + vi.stubGlobal('fetch', fetchMock); + await expect(stageSourceToDisk('https://cdn.example.test/down.bin', 32)).rejects.toThrow( + 'HTTP download failed: 503', + ); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it('unlinks the http .part when rename after download fails', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(Uint8Array.from([0x01, 0x02]), { status: 200 })), + ); + vi.spyOn(fsp, 'rename').mockRejectedValueOnce(new Error('http rename failed')); + const before = await stageNames(); + await expect(stageSourceToDisk('https://cdn.example.test/r.bin', 32)).rejects.toThrow( + 'http rename failed', + ); + expect(await newPartNames(before)).toEqual([]); + }); +}); + +describe('stageSourceToDisk — local files', () => { + it('hardlinks a raw path, preserves basename, and pins the inode after source unlink', async () => { + const src = path.join(scratch, 'payload.dat'); + await fsp.writeFile(src, Buffer.from([0xde, 0xad, 0xbe, 0xef])); + const srcStat = await fsp.stat(src); + const staged = hold(await stageSourceToDisk(src, 64)); + expect(staged.fileName).toBe('payload.dat'); + expect(staged.fileSize).toBe(4); + expectStagedPath(staged.filePath, '.dat'); + const stagedStat = await fsp.stat(staged.filePath); + expect(stagedStat.ino).toBe(srcStat.ino); + expect(stagedStat.nlink).toBe(2); + await fsp.unlink(src); + expect(await fsp.readFile(staged.filePath)).toEqual(Buffer.from([0xde, 0xad, 0xbe, 0xef])); + }); + + it('accepts a file:// URL and uses the pre-resolution basename', async () => { + const src = path.join(scratch, 'video.mp4'); + await fsp.writeFile(src, Buffer.from([0x00, 0x00, 0x00, 0x18])); + const staged = hold(await stageSourceToDisk(pathToFileURL(src).href, 64)); + expect(staged.fileName).toBe('video.mp4'); + expect(staged.fileSize).toBe(4); + expectStagedPath(staged.filePath, '.mp4'); + expect(await fsp.readFile(staged.filePath)).toEqual(Buffer.from([0x00, 0x00, 0x00, 0x18])); + }); + + it('resolves a symlink target but keeps the symlink basename and extension', async () => { + const target = path.join(scratch, 'blob-real.bin'); + const linkPath = path.join(scratch, 'alias.mov'); + await fsp.writeFile(target, Buffer.from([0x6d, 0x6f, 0x6f, 0x76])); + await fsp.symlink(target, linkPath); + const staged = hold(await stageSourceToDisk(linkPath, 64)); + expect(staged.fileName).toBe('alias.mov'); + expectStagedPath(staged.filePath, '.mov'); + expect(await fsp.readFile(staged.filePath)).toEqual(Buffer.from([0x6d, 0x6f, 0x6f, 0x76])); + }); + + it('uses .bin when the local path has no extension', async () => { + const src = path.join(scratch, 'noext'); + await fsp.writeFile(src, Buffer.from([0x42])); + const staged = hold(await stageSourceToDisk(src, 8)); + expect(staged.fileName).toBe('noext'); + expectStagedPath(staged.filePath, '.bin'); + }); + + it('preserves a mixed-case extension on the staged path', async () => { + const src = path.join(scratch, 'Photo.JPEG'); + await fsp.writeFile(src, Buffer.from([0xff, 0xd8])); + const staged = hold(await stageSourceToDisk(src, 8)); + expect(staged.fileName).toBe('Photo.JPEG'); + expectStagedPath(staged.filePath, '.JPEG'); + }); + + it('allows a local file whose size equals maxBytes', async () => { + const src = path.join(scratch, 'exact.bin'); + await fsp.writeFile(src, Buffer.from([1, 2, 3, 4, 5, 6, 7, 8])); + const staged = hold(await stageSourceToDisk(src, 8)); + expect(staged.fileSize).toBe(8); + }); + + it('stages an empty regular file', async () => { + const src = path.join(scratch, 'zero.dat'); + await fsp.writeFile(src, Buffer.alloc(0)); + const staged = hold(await stageSourceToDisk(src, 0)); + expect(staged.fileSize).toBe(0); + expect(staged.fileName).toBe('zero.dat'); + expect(await fsp.readFile(staged.filePath)).toEqual(Buffer.alloc(0)); + }); + + it('rejects a directory before creating a stage file', async () => { + await expect(stageSourceToDisk(scratch, 64)).rejects.toThrow( + `stage source is not a regular file: ${scratch}`, + ); + }); + + it('rejects an oversized local file before staging', async () => { + const src = path.join(scratch, 'huge.bin'); + await fsp.writeFile(src, Buffer.alloc(80, 0xab)); + await expect(stageSourceToDisk(src, 16)).rejects.toThrow('stage source too large: 80 > 16'); + }); + + it('copies when link() fails and the copy survives source deletion', async () => { + const src = path.join(scratch, 'xfs.bin'); + const payload = Buffer.from([0xc0, 0xff, 0xee, 0x11]); + await fsp.writeFile(src, payload); + const srcIno = (await fsp.stat(src)).ino; + const linkSpy = vi.spyOn(fsp, 'link').mockRejectedValueOnce( + Object.assign(new Error('EXDEV'), { code: 'EXDEV' }), + ); + const staged = hold(await stageSourceToDisk(src, 64)); + expect(linkSpy).toHaveBeenCalledOnce(); + expect(staged.fileName).toBe('xfs.bin'); + expect(staged.fileSize).toBe(4); + expect((await fsp.stat(staged.filePath)).ino).not.toBe(srcIno); + await fsp.unlink(src); + expect(await fsp.readFile(staged.filePath)).toEqual(payload); + }); + + it('cleans temps when both link() and the copy fallback fail', async () => { + const src = path.join(scratch, 'fail.bin'); + await fsp.writeFile(src, Buffer.from([0x01])); + vi.spyOn(fsp, 'link').mockRejectedValueOnce(Object.assign(new Error('EXDEV'), { code: 'EXDEV' })); + vi.spyOn(fsp, 'copyFile').mockRejectedValueOnce(new Error('ENOSPC: copy failed')); + const before = await stageNames(); + await expect(stageSourceToDisk(src, 64)).rejects.toThrow('ENOSPC: copy failed'); + expect(await newPartNames(before)).toEqual([]); + }); + + it('cleans temps when link() fails and the copy rename fails', async () => { + const src = path.join(scratch, 'rename-fail.bin'); + await fsp.writeFile(src, Buffer.from([0x02, 0x03])); + vi.spyOn(fsp, 'link').mockRejectedValueOnce(Object.assign(new Error('EPERM'), { code: 'EPERM' })); + vi.spyOn(fsp, 'rename').mockRejectedValueOnce(new Error('copy rename failed')); + const before = await stageNames(); + await expect(stageSourceToDisk(src, 64)).rejects.toThrow('copy rename failed'); + expect(await newPartNames(before)).toEqual([]); + }); +}); + +describe('stageSourceToDisk — cleanup', () => { + it('removes only the staged temp, never the caller file, and is idempotent', async () => { + const src = path.join(scratch, 'keep-me.bin'); + await fsp.writeFile(src, Buffer.from([0xde, 0xad, 0xbe, 0xef])); + const staged = hold(await stageSourceToDisk(src, 64)); + expect(fs.existsSync(staged.filePath)).toBe(true); + await staged.cleanup(); + expect(fs.existsSync(staged.filePath)).toBe(false); + expect(fs.existsSync(src)).toBe(true); + expect(await fsp.readFile(src)).toEqual(Buffer.from([0xde, 0xad, 0xbe, 0xef])); + await expect(staged.cleanup()).resolves.toBeUndefined(); + }); + + it('tolerates the staged path already being gone', async () => { + const src = path.join(scratch, 'gone.bin'); + await fsp.writeFile(src, Buffer.from([0x09])); + const staged = hold(await stageSourceToDisk(src, 64)); + await fsp.unlink(staged.filePath); + await expect(staged.cleanup()).resolves.toBeUndefined(); + }); +}); + +describe('sweepStagedUploads', () => { + it('returns 0 when the stage directory does not exist', async () => { + const parked = `${STAGE_DIR}.park-${randomUUID()}`; + let moved = false; + try { + try { + await fsp.rename(STAGE_DIR, parked); + moved = true; + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err; + } + await expect(sweepStagedUploads(2_000_000_000_000)).resolves.toBe(0); + } finally { + if (moved) { + await fsp.rm(STAGE_DIR, { recursive: true, force: true }).catch(() => undefined); + await fsp.rename(parked, STAGE_DIR); + } + } + }); + + it('reaps a temp older than 30 minutes, keeps a TTL-edge temp, and skips an active staged file', async () => { + const src = path.join(scratch, 'inflight.bin'); + await fsp.writeFile(src, Buffer.from([0x51, 0x52])); + const staged = hold(await stageSourceToDisk(src, 64)); + + await fsp.mkdir(STAGE_DIR, { recursive: true }); + const now = 2_000_000_000_000; + const aged = path.join(STAGE_DIR, `stage-${randomUUID()}.aged`); + const edge = path.join(STAGE_DIR, `stage-${randomUUID()}.edge`); + const recent = path.join(STAGE_DIR, `stage-${randomUUID()}.recent`); + await fsp.writeFile(aged, Buffer.from('aged-orphan')); + await fsp.writeFile(edge, Buffer.from('ttl-edge')); + await fsp.writeFile(recent, Buffer.from('fresh-orphan')); + // Age by whole seconds: some filesystems store mtime at 1s resolution, so a + // 1ms-past-TTL stamp can round back onto the keep side of `> 30min`. + await fsp.utimes(aged, new Date(now), new Date(now - STAGE_TTL_MS - 1000)); + await fsp.utimes(edge, new Date(now), new Date(now - STAGE_TTL_MS)); + await fsp.utimes(recent, new Date(now), new Date(now)); + await fsp.utimes(staged.filePath, new Date(now - STAGE_TTL_MS - 1000), new Date(now - STAGE_TTL_MS - 1000)); + + try { + const removed = await sweepStagedUploads(now); + expect(fs.existsSync(aged)).toBe(false); + expect(fs.existsSync(edge)).toBe(true); + expect(fs.existsSync(recent)).toBe(true); + expect(fs.existsSync(staged.filePath)).toBe(true); + expect(removed).toBeGreaterThanOrEqual(1); + } finally { + await fsp.rm(edge, { force: true }); + await fsp.rm(recent, { force: true }); + await fsp.rm(aged, { force: true }); + } + }); + + it('uses Date.now() when now is omitted', async () => { + await fsp.mkdir(STAGE_DIR, { recursive: true }); + const orphan = path.join(STAGE_DIR, `stage-${randomUUID()}.epoch`); + await fsp.writeFile(orphan, Buffer.from('epoch-orphan')); + await fsp.utimes(orphan, new Date('1990-01-01T00:00:00.000Z'), new Date('1990-01-01T00:00:00.000Z')); + try { + const removed = await sweepStagedUploads(); + expect(fs.existsSync(orphan)).toBe(false); + expect(removed).toBeGreaterThanOrEqual(1); + } finally { + await fsp.rm(orphan, { force: true }); + } + }); +}); diff --git a/packages/protocol/tests/msg-push/flash-transfer-decode.test.ts b/packages/protocol/tests/msg-push/flash-transfer-decode.test.ts index eeb94489..b3fe4e0b 100644 --- a/packages/protocol/tests/msg-push/flash-transfer-decode.test.ts +++ b/packages/protocol/tests/msg-push/flash-transfer-decode.test.ts @@ -95,6 +95,21 @@ describe('decodeRichBody / 闪传 flash_file (#358 current NT card)', () => { }]); }); + it('reads the cover URL from extInfo.thumbnail', () => { + const out = decodeRichBody(currentNtFlashBody(currentNtCardJson, { + filesetId: 'fs-nt-358', + name: 'a.zip', + thumbnail: { download: { field1: 2, downloadUrl: 'https://example.test/cover.jpg' } }, + }), true); + expect(out).toEqual([{ + type: 'flash_file', + filesetId: 'fs-nt-358', + fileName: 'a.zip', + sceneType: 1, + thumbUrl: 'https://example.test/cover.jpg', + }]); + }); + it('falls back to the open_fileset scheme when extInfo is absent', () => { const out = decodeRichBody(currentNtFlashBody(currentNtCardJson), true); expect(out).toEqual([{ @@ -155,12 +170,14 @@ describe('decodeRichBody / 闪传 flash_file (#358 current NT card)', () => { const push = protobuf_decode(Buffer.from(hex, 'hex')); const out = decodeRichBody(push.message?.body, false); // Reporter redacted the richui JSON (unterminated src), so scene_type - // cannot be recovered from the scheme. extInfo still supplies fileset + name. + // cannot be recovered from the scheme. extInfo still supplies fileset + name + // and the cover URL (placeholder). expect(out).toEqual([{ type: 'flash_file', filesetId: '[UUID]', fileName: 'cpwd截图.zip', sceneType: 0, + thumbUrl: '[FILE_URL]', }]); }); }); diff --git a/packages/proton/package.json b/packages/proton/package.json index 9c76de28..27c12bfe 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proton", - "version": "1.14.7", + "version": "1.14.8", "private": true, "type": "module", "description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.", diff --git a/packages/runtime/native/snowluma-linux-arm64.node b/packages/runtime/native/snowluma-linux-arm64.node index a542a777..b24be4f9 100644 Binary files a/packages/runtime/native/snowluma-linux-arm64.node and b/packages/runtime/native/snowluma-linux-arm64.node differ diff --git a/packages/runtime/native/snowluma-linux-arm64.so b/packages/runtime/native/snowluma-linux-arm64.so index 87273de9..f569a7af 100644 Binary files a/packages/runtime/native/snowluma-linux-arm64.so and b/packages/runtime/native/snowluma-linux-arm64.so differ diff --git a/packages/runtime/native/snowluma-linux-x64.node b/packages/runtime/native/snowluma-linux-x64.node index ea5e2ac5..aa3815dd 100644 Binary files a/packages/runtime/native/snowluma-linux-x64.node and b/packages/runtime/native/snowluma-linux-x64.node differ diff --git a/packages/runtime/native/snowluma-linux-x64.so b/packages/runtime/native/snowluma-linux-x64.so index b7edccad..f40f077e 100644 Binary files a/packages/runtime/native/snowluma-linux-x64.so and b/packages/runtime/native/snowluma-linux-x64.so differ diff --git a/packages/runtime/native/snowluma-win32-x64.dll b/packages/runtime/native/snowluma-win32-x64.dll index 6db65def..92589917 100644 Binary files a/packages/runtime/native/snowluma-win32-x64.dll and b/packages/runtime/native/snowluma-win32-x64.dll differ diff --git a/packages/runtime/native/snowluma-win32-x64.node b/packages/runtime/native/snowluma-win32-x64.node index bc2f5de6..d9294a1e 100644 Binary files a/packages/runtime/native/snowluma-win32-x64.node and b/packages/runtime/native/snowluma-win32-x64.node differ diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 96bfb199..e4b9d077 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/runtime", - "version": "1.14.7", + "version": "1.14.8", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index da9f4af7..cd1a23cc 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.14.7", + "version": "1.14.8", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/sdk/tests/api-client.test.ts b/packages/sdk/tests/api-client.test.ts new file mode 100644 index 00000000..68a843f9 --- /dev/null +++ b/packages/sdk/tests/api-client.test.ts @@ -0,0 +1,698 @@ +import { describe, expect, it } from 'vitest'; +import { SnowLumaApiClient, toJsonObject } from '../src/client/api-client'; +import { + SnowLumaApiError, + SnowLumaAuthError, + text, + type ActionParams, + type ActionResult, + type ApiResponse, + type RequestOptions, + type SnowLumaAction, +} from '../src'; + +class RecordingClient extends SnowLumaApiClient { + readonly calls: Array<{ + action: string; + params: unknown; + options: RequestOptions | undefined; + }> = []; + + response: ApiResponse = { status: 'ok', retcode: 0, data: null }; + + async request( + action: TAction, + params?: ActionParams, + options?: RequestOptions, + ): Promise>> { + this.calls.push({ action, params, options }); + return this.response as ApiResponse>; + } +} + +function okClient(data: unknown = null): RecordingClient { + const client = new RecordingClient(); + client.response = { status: 'ok', retcode: 0, data }; + return client; +} + +describe('toJsonObject', () => { + it('returns an empty object for undefined', () => { + expect(toJsonObject(undefined)).toEqual({}); + }); + + it('returns the same object when one is provided', () => { + const value = { domain: 'qun.qq.com' }; + expect(toJsonObject(value)).toBe(value); + }); +}); + +describe('SnowLumaApiClient.call', () => { + it('returns response data when status is ok and retcode is 0', async () => { + const client = okClient({ user_id: 1787882683, nickname: 'luma' }); + + await expect(client.call('get_login_info', {}, { timeoutMs: 1500 })).resolves.toEqual({ + user_id: 1787882683, + nickname: 'luma', + }); + expect(client.calls).toEqual([ + { action: 'get_login_info', params: {}, options: { timeoutMs: 1500 } }, + ]); + }); + + it('throws SnowLumaApiError when status is failed even if retcode is 0', async () => { + const client = new RecordingClient(); + const response: ApiResponse = { + status: 'failed', + retcode: 0, + data: null, + wording: 'handler rejected', + }; + client.response = response; + + await expect(client.call('clean_cache', {})).rejects.toBeInstanceOf(SnowLumaApiError); + await expect(client.call('clean_cache', {})).rejects.toMatchObject({ + name: 'SnowLumaApiError', + retcode: 0, + wording: 'handler rejected', + message: 'handler rejected', + response, + }); + }); + + it('throws SnowLumaApiError when retcode is non-zero even if status is ok', async () => { + const client = new RecordingClient(); + const response: ApiResponse = { status: 'ok', retcode: 1200, data: null }; + client.response = response; + + await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaApiError); + await expect(client.getStatus()).rejects.toMatchObject({ + name: 'SnowLumaApiError', + retcode: 1200, + message: 'SnowLuma API failed with retcode 1200', + response, + }); + }); + + it('throws SnowLumaAuthError for auth retcodes', async () => { + const client = new RecordingClient(); + + client.response = { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' }; + await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaAuthError); + + client.response = { status: 'ok', retcode: 401, data: null, wording: 'token missing' }; + await expect(client.getStatus()).rejects.toMatchObject({ + name: 'SnowLumaAuthError', + retcode: 401, + wording: 'token missing', + }); + + client.response = { status: 'failed', retcode: 403, data: null }; + await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaAuthError); + }); +}); + +describe('SnowLumaApiClient.raw', () => { + it('unwraps successful data and forwards the raw action arguments', async () => { + const client = okClient({ cookies: 'uin=o10001' }); + + await expect(client.raw('get_cookies', { domain: 'qun.qq.com' }, { echo: 'raw-1' })).resolves.toEqual({ + cookies: 'uin=o10001', + }); + expect(client.calls).toEqual([ + { action: 'get_cookies', params: { domain: 'qun.qq.com' }, options: { echo: 'raw-1' } }, + ]); + }); + + it('throws on failed envelopes instead of returning them', async () => { + const client = new RecordingClient(); + client.response = { status: 'failed', retcode: 1403, data: null, wording: 'denied' }; + + await expect(client.raw('get_csrf_token', {})).rejects.toBeInstanceOf(SnowLumaApiError); + }); +}); + +describe('SnowLumaApiClient.rawResponse', () => { + it('returns the full envelope without applying call error handling', async () => { + const client = new RecordingClient(); + const response: ApiResponse = { status: 'failed', retcode: 1403, data: null, wording: 'denied' }; + client.response = response; + + await expect(client.rawResponse('get_csrf_token', {}, { echo: 'env-1' })).resolves.toEqual(response); + expect(client.calls).toEqual([ + { action: 'get_csrf_token', params: {}, options: { echo: 'env-1' } }, + ]); + }); +}); + +describe('SnowLumaApiClient typed actions', () => { + it('maps session helpers to empty-param OneBot actions', async () => { + const client = okClient(); + const timeout = { timeoutMs: 2500 }; + + await client.getLoginInfo(); + await client.getStatus(timeout); + await client.getVersionInfo(); + await client.canSendImage(); + await client.canSendRecord(); + await client.getFriendList(); + await client.getRKey(); + await client.getCsrfToken(); + await client.cleanCache(); + await client.markAllAsRead(); + await client.checkUrlSafely(); + await client.getClientKey(); + + expect(client.calls).toEqual([ + { action: 'get_login_info', params: {}, options: undefined }, + { action: 'get_status', params: {}, options: timeout }, + { action: 'get_version_info', params: {}, options: undefined }, + { action: 'can_send_image', params: {}, options: undefined }, + { action: 'can_send_record', params: {}, options: undefined }, + { action: 'get_friend_list', params: {}, options: undefined }, + { action: 'get_rkey', params: {}, options: undefined }, + { action: 'get_csrf_token', params: {}, options: undefined }, + { action: 'clean_cache', params: {}, options: undefined }, + { action: '_mark_all_as_read', params: {}, options: undefined }, + { action: 'check_url_safely', params: {}, options: undefined }, + { action: 'get_clientkey', params: {}, options: undefined }, + ]); + }); + + it('normalizes outgoing messages for send helpers', async () => { + const client = okClient({ message_id: 88 }); + + await client.sendMsg({ + message_type: 'group', + group_id: 941657197, + message: 'plain', + auto_escape: true, + }); + await client.sendMsg({ + message_type: 'private', + user_id: 10001, + message: { type: 'text', data: { text: 'seg' } }, + }); + await client.sendPrivateMessage(10002, text('hi'), { autoEscape: true, timeoutMs: 9 }); + await client.sendGroupMessage(20002, [{ type: 'text', data: { text: 'arr' } }]); + await client.sendGroupForwardMessage(30003, text('fwd-g')); + await client.sendPrivateForwardMessage(40004, 'fwd-p'); + + expect(client.calls).toEqual([ + { + action: 'send_msg', + params: { + message_type: 'group', + group_id: 941657197, + message: 'plain', + auto_escape: true, + }, + options: undefined, + }, + { + action: 'send_msg', + params: { + message_type: 'private', + user_id: 10001, + message: [{ type: 'text', data: { text: 'seg' } }], + }, + options: undefined, + }, + { + action: 'send_private_msg', + params: { + user_id: 10002, + message: [{ type: 'text', data: { text: 'hi' } }], + auto_escape: true, + }, + options: { autoEscape: true, timeoutMs: 9 }, + }, + { + action: 'send_group_msg', + params: { + group_id: 20002, + message: [{ type: 'text', data: { text: 'arr' } }], + auto_escape: undefined, + }, + options: undefined, + }, + { + action: 'send_group_forward_msg', + params: { + group_id: 30003, + messages: [{ type: 'text', data: { text: 'fwd-g' } }], + }, + options: undefined, + }, + { + action: 'send_private_forward_msg', + params: { + user_id: 40004, + messages: 'fwd-p', + }, + options: undefined, + }, + ]); + }); + + it('maps message lookup, delete, and history helpers', async () => { + const client = okClient(); + + await client.getMessage(71); + await client.deleteMessage(72); + await client.getGroupMessageHistory({ group_id: 941657197, message_id: 73, count: 20, reverse_order: false }); + await client.getFriendMessageHistory({ user_id: 10001, count: 8 }); + await client.markGroupMessageAsRead(74); + await client.markGroupMessageAsRead(75, 941657198); + await client.markPrivateMessageAsRead(76); + await client.markPrivateMessageAsRead(77, 10002); + await client.markMessageAsRead(78); + await client.markMessageAsRead(79, 10003); + + expect(client.calls).toEqual([ + { action: 'get_msg', params: { message_id: 71 }, options: undefined }, + { action: 'delete_msg', params: { message_id: 72 }, options: undefined }, + { + action: 'get_group_msg_history', + params: { group_id: 941657197, message_id: 73, count: 20, reverse_order: false }, + options: undefined, + }, + { + action: 'get_friend_msg_history', + params: { user_id: 10001, count: 8 }, + options: undefined, + }, + { action: 'mark_group_msg_as_read', params: { message_id: 74, group_id: undefined }, options: undefined }, + { action: 'mark_group_msg_as_read', params: { message_id: 75, group_id: 941657198 }, options: undefined }, + { action: 'mark_private_msg_as_read', params: { message_id: 76, user_id: undefined }, options: undefined }, + { action: 'mark_private_msg_as_read', params: { message_id: 77, user_id: 10002 }, options: undefined }, + { action: 'mark_msg_as_read', params: { message_id: 78, target_id: undefined }, options: undefined }, + { action: 'mark_msg_as_read', params: { message_id: 79, target_id: 10003 }, options: undefined }, + ]); + }); + + it('maps friend and stranger helpers, including optional block', async () => { + const client = okClient(); + + await client.getStrangerInfo(10011); + await client.deleteFriend(10012); + await client.deleteFriend(10013, { block: true, timeoutMs: 40 }); + await client.setFriendRemark(10014, 'alias'); + await client.setFriendAddRequest('flag-a'); + await client.setFriendAddRequest('flag-b', false); + + expect(client.calls).toEqual([ + { action: 'get_stranger_info', params: { user_id: 10011 }, options: undefined }, + { action: 'delete_friend', params: { user_id: 10012, block: undefined }, options: undefined }, + { action: 'delete_friend', params: { user_id: 10013, block: true }, options: { block: true, timeoutMs: 40 } }, + { action: 'set_friend_remark', params: { user_id: 10014, remark: 'alias' }, options: undefined }, + { action: 'set_friend_add_request', params: { flag: 'flag-a', approve: true }, options: undefined }, + { action: 'set_friend_add_request', params: { flag: 'flag-b', approve: false }, options: undefined }, + ]); + }); + + it('maps group list and member lookups with noCache', async () => { + const client = okClient(); + + await client.getGroupList(); + await client.getGroupList({ noCache: true, timeoutMs: 11 }); + await client.getGroupInfo(941657197); + await client.getGroupInfo(941657198, { noCache: false }); + await client.getGroupMemberList(941657199); + await client.getGroupMemberList(941657200, { noCache: true }); + await client.getGroupMemberInfo(941657201, 10021); + await client.getGroupMemberInfo(941657202, 10022, { noCache: true }); + await client.getGroupInfoEx(941657203); + await client.getGroupInfoEx(941657204, { noCache: true }); + await client.getGroupDetailInfo(941657205); + await client.getGroupDetailInfo(941657206, { noCache: true }); + + expect(client.calls).toEqual([ + { action: 'get_group_list', params: { no_cache: undefined }, options: undefined }, + { action: 'get_group_list', params: { no_cache: true }, options: { noCache: true, timeoutMs: 11 } }, + { action: 'get_group_info', params: { group_id: 941657197, no_cache: undefined }, options: undefined }, + { action: 'get_group_info', params: { group_id: 941657198, no_cache: false }, options: { noCache: false } }, + { action: 'get_group_member_list', params: { group_id: 941657199, no_cache: undefined }, options: undefined }, + { action: 'get_group_member_list', params: { group_id: 941657200, no_cache: true }, options: { noCache: true } }, + { + action: 'get_group_member_info', + params: { group_id: 941657201, user_id: 10021, no_cache: undefined }, + options: undefined, + }, + { + action: 'get_group_member_info', + params: { group_id: 941657202, user_id: 10022, no_cache: true }, + options: { noCache: true }, + }, + { action: 'get_group_info_ex', params: { group_id: 941657203, no_cache: undefined }, options: undefined }, + { action: 'get_group_info_ex', params: { group_id: 941657204, no_cache: true }, options: { noCache: true } }, + { action: 'get_group_detail_info', params: { group_id: 941657205, no_cache: undefined }, options: undefined }, + { action: 'get_group_detail_info', params: { group_id: 941657206, no_cache: true }, options: { noCache: true } }, + ]); + }); + + it('maps honor and system-message helpers', async () => { + const client = okClient(); + + await client.getGroupHonorInfo({ group_id: 941657210, type: 'talkative' }); + await client.getGroupSystemMessages(); + await client.getGroupSystemMessages({ groupId: 941657211, onlyPending: true, count: 5 }); + + expect(client.calls).toEqual([ + { action: 'get_group_honor_info', params: { group_id: 941657210, type: 'talkative' }, options: undefined }, + { + action: 'get_group_system_msg', + params: { group_id: undefined, only_pending: undefined, count: undefined }, + options: undefined, + }, + { + action: 'get_group_system_msg', + params: { group_id: 941657211, only_pending: true, count: 5 }, + options: { groupId: 941657211, onlyPending: true, count: 5 }, + }, + ]); + }); + + it('maps group administration helpers and their defaults', async () => { + const client = okClient(); + + await client.setGroupKick(941657220, 10031); + await client.setGroupKick(941657221, 10032, { rejectAddRequest: true }); + await client.setGroupBan(941657222, 10033); + await client.setGroupBan(941657223, 10034, 600); + await client.setGroupWholeBan(941657224); + await client.setGroupWholeBan(941657225, false); + await client.setGroupAdmin(941657226, 10035); + await client.setGroupAdmin(941657227, 10036, false); + await client.setGroupCard(941657228, 10037); + await client.setGroupCard(941657229, 10038, 'card'); + await client.setGroupName(941657230, 'new-name'); + await client.setGroupLeave(941657231); + await client.setGroupSpecialTitle(941657232, 10039); + await client.setGroupSpecialTitle(941657233, 10040, 'title'); + + expect(client.calls).toEqual([ + { + action: 'set_group_kick', + params: { group_id: 941657220, user_id: 10031, reject_add_request: undefined }, + options: undefined, + }, + { + action: 'set_group_kick', + params: { group_id: 941657221, user_id: 10032, reject_add_request: true }, + options: { rejectAddRequest: true }, + }, + { action: 'set_group_ban', params: { group_id: 941657222, user_id: 10033, duration: undefined }, options: undefined }, + { action: 'set_group_ban', params: { group_id: 941657223, user_id: 10034, duration: 600 }, options: undefined }, + { action: 'set_group_whole_ban', params: { group_id: 941657224, enable: true }, options: undefined }, + { action: 'set_group_whole_ban', params: { group_id: 941657225, enable: false }, options: undefined }, + { action: 'set_group_admin', params: { group_id: 941657226, user_id: 10035, enable: true }, options: undefined }, + { action: 'set_group_admin', params: { group_id: 941657227, user_id: 10036, enable: false }, options: undefined }, + { action: 'set_group_card', params: { group_id: 941657228, user_id: 10037, card: '' }, options: undefined }, + { action: 'set_group_card', params: { group_id: 941657229, user_id: 10038, card: 'card' }, options: undefined }, + { action: 'set_group_name', params: { group_id: 941657230, group_name: 'new-name' }, options: undefined }, + { action: 'set_group_leave', params: { group_id: 941657231 }, options: undefined }, + { + action: 'set_group_special_title', + params: { group_id: 941657232, user_id: 10039, special_title: '' }, + options: undefined, + }, + { + action: 'set_group_special_title', + params: { group_id: 941657233, user_id: 10040, special_title: 'title' }, + options: undefined, + }, + ]); + }); + + it('maps group and private file helpers', async () => { + const client = okClient(); + + await client.uploadGroupFile(941657240, '/tmp/a.png'); + await client.uploadGroupFile(941657241, '/tmp/b.png', { + name: 'b.png', + folder: '/docs', + folderId: '/abc', + uploadFile: true, + }); + await client.uploadPrivateFile(10051, '/tmp/c.png'); + await client.uploadPrivateFile(10052, '/tmp/d.png', { name: 'd.png', uploadFile: false }); + await client.getGroupFileUrl(941657242, 'file-1'); + await client.getGroupFileUrl(941657243, 'file-2', { busid: 102 }); + await client.getGroupRootFiles(941657244); + await client.getGroupFilesByFolder(941657245); + await client.getGroupFilesByFolder(941657246, '/sub'); + await client.deleteGroupFile(941657247, 'file-3'); + await client.moveGroupFile(941657248, 'file-4', '/from', '/to'); + await client.createGroupFileFolder(941657249, 'photos'); + await client.createGroupFileFolder(941657250, 'docs', '/root'); + await client.deleteGroupFileFolder(941657251, '/gone'); + await client.renameGroupFileFolder(941657252, '/old', 'new-name'); + await client.getPrivateFileUrl(10053, 'file-5', 'hash-5'); + await client.getGroupFileSystemInfo(941657253); + + expect(client.calls).toEqual([ + { + action: 'upload_group_file', + params: { + group_id: 941657240, + file: '/tmp/a.png', + name: undefined, + folder: undefined, + folder_id: undefined, + upload_file: undefined, + }, + options: {}, + }, + { + action: 'upload_group_file', + params: { + group_id: 941657241, + file: '/tmp/b.png', + name: 'b.png', + folder: '/docs', + folder_id: '/abc', + upload_file: true, + }, + options: { name: 'b.png', folder: '/docs', folderId: '/abc', uploadFile: true }, + }, + { + action: 'upload_private_file', + params: { user_id: 10051, file: '/tmp/c.png', name: undefined, upload_file: undefined }, + options: {}, + }, + { + action: 'upload_private_file', + params: { user_id: 10052, file: '/tmp/d.png', name: 'd.png', upload_file: false }, + options: { name: 'd.png', uploadFile: false }, + }, + { action: 'get_group_file_url', params: { group_id: 941657242, file_id: 'file-1', busid: undefined }, options: undefined }, + { action: 'get_group_file_url', params: { group_id: 941657243, file_id: 'file-2', busid: 102 }, options: { busid: 102 } }, + { action: 'get_group_root_files', params: { group_id: 941657244 }, options: undefined }, + { action: 'get_group_files_by_folder', params: { group_id: 941657245, folder_id: '/' }, options: undefined }, + { action: 'get_group_files_by_folder', params: { group_id: 941657246, folder_id: '/sub' }, options: undefined }, + { action: 'delete_group_file', params: { group_id: 941657247, file_id: 'file-3' }, options: undefined }, + { + action: 'move_group_file', + params: { + group_id: 941657248, + file_id: 'file-4', + parent_directory: '/from', + target_directory: '/to', + }, + options: undefined, + }, + { action: 'create_group_file_folder', params: { group_id: 941657249, name: 'photos', parent_id: '/' }, options: undefined }, + { action: 'create_group_file_folder', params: { group_id: 941657250, name: 'docs', parent_id: '/root' }, options: undefined }, + { action: 'delete_group_file_folder', params: { group_id: 941657251, folder_id: '/gone' }, options: undefined }, + { + action: 'rename_group_file_folder', + params: { group_id: 941657252, folder_id: '/old', new_folder_name: 'new-name' }, + options: undefined, + }, + { action: 'get_private_file_url', params: { user_id: 10053, file_id: 'file-5', file_hash: 'hash-5' }, options: undefined }, + { action: 'get_group_file_system_info', params: { group_id: 941657253 }, options: undefined }, + ]); + }); + + it('maps group add-request, poke, like, and essence helpers', async () => { + const client = okClient(); + + await client.setGroupAddRequest('flag-c'); + await client.setGroupAddRequest('flag-d', { + subType: 'add', + type: 'group', + approve: false, + reason: 'nope', + }); + await client.sendLike(10061); + await client.sendLike(10062, 5); + await client.friendPoke(10063); + await client.friendPoke(10064, { targetId: 10065 }); + await client.groupPoke(941657260, 10066); + await client.sendPoke(10067); + await client.sendPoke(10068, { groupId: 941657261 }); + await client.setEssenceMessage(81); + await client.deleteEssenceMessage(82); + await client.getEssenceMessageList(941657262); + await client.setGroupReaction({ message_id: 83, code: '76', group_id: 941657263, is_set: true }); + + expect(client.calls).toEqual([ + { + action: 'set_group_add_request', + params: { flag: 'flag-c', sub_type: undefined, type: undefined, approve: undefined, reason: undefined }, + options: {}, + }, + { + action: 'set_group_add_request', + params: { flag: 'flag-d', sub_type: 'add', type: 'group', approve: false, reason: 'nope' }, + options: { subType: 'add', type: 'group', approve: false, reason: 'nope' }, + }, + { action: 'send_like', params: { user_id: 10061, times: 1 }, options: undefined }, + { action: 'send_like', params: { user_id: 10062, times: 5 }, options: undefined }, + { action: 'friend_poke', params: { user_id: 10063, target_id: undefined }, options: undefined }, + { action: 'friend_poke', params: { user_id: 10064, target_id: 10065 }, options: { targetId: 10065 } }, + { action: 'group_poke', params: { group_id: 941657260, user_id: 10066 }, options: undefined }, + { action: 'send_poke', params: { user_id: 10067, group_id: undefined }, options: undefined }, + { action: 'send_poke', params: { user_id: 10068, group_id: 941657261 }, options: { groupId: 941657261 } }, + { action: 'set_essence_msg', params: { message_id: 81 }, options: undefined }, + { action: 'delete_essence_msg', params: { message_id: 82 }, options: undefined }, + { action: 'get_essence_msg_list', params: { group_id: 941657262 }, options: undefined }, + { + action: 'set_group_reaction', + params: { message_id: 83, code: '76', group_id: 941657263, is_set: true }, + options: undefined, + }, + ]); + }); + + it('maps group-notice helpers to underscored OneBot actions', async () => { + const client = okClient(); + + await client.sendGroupNotice(941657270, 'welcome'); + await client.sendGroupNotice(941657271, 'pinned', { + image: 'https://example.test/n.png', + pinned: 1, + type: 20, + sendToNewMembers: true, + isShowEditCard: 0, + tipWindowType: 1, + confirmRequired: 0, + }); + await client.getGroupNotice(941657272); + + expect(client.calls).toEqual([ + { + action: '_send_group_notice', + params: { + group_id: 941657270, + content: 'welcome', + image: undefined, + pinned: undefined, + type: undefined, + send_to_new_members: undefined, + is_show_edit_card: undefined, + tip_window_type: undefined, + confirm_required: undefined, + }, + options: {}, + }, + { + action: '_send_group_notice', + params: { + group_id: 941657271, + content: 'pinned', + image: 'https://example.test/n.png', + pinned: 1, + type: 20, + send_to_new_members: true, + is_show_edit_card: 0, + tip_window_type: 1, + confirm_required: 0, + }, + options: { + image: 'https://example.test/n.png', + pinned: 1, + type: 20, + sendToNewMembers: true, + isShowEditCard: 0, + tipWindowType: 1, + confirmRequired: 0, + }, + }, + { action: '_get_group_notice', params: { group_id: 941657272 }, options: undefined }, + ]); + }); + + it('forwards forward-message and media helpers without remapping their params', async () => { + const client = okClient(); + + await client.uploadForwardMessage({ group_id: 941657280, messages: 'up' }); + await client.sendForwardMessage({ user_id: 10071, message: 'send' }); + await client.getForwardMessage({ id: 'fwd-1' }); + await client.getImage({ file: 'img-1' }); + await client.getRecord({ file_id: 'rec-1' }); + await client.downloadFile({ url: 'https://example.test/a.bin', name: 'a.bin' }); + + expect(client.calls).toEqual([ + { action: 'upload_forward_msg', params: { group_id: 941657280, messages: 'up' }, options: undefined }, + { action: 'send_forward_msg', params: { user_id: 10071, message: 'send' }, options: undefined }, + { action: 'get_forward_msg', params: { id: 'fwd-1' }, options: undefined }, + { action: 'get_image', params: { file: 'img-1' }, options: undefined }, + { action: 'get_record', params: { file_id: 'rec-1' }, options: undefined }, + { action: 'download_file', params: { url: 'https://example.test/a.bin', name: 'a.bin' }, options: undefined }, + ]); + }); + + it('maps cookie, credential, profile, and status helpers', async () => { + const client = okClient(); + + await client.getCookies(); + await client.getCookies({ domain: 'qun.qq.com' }); + await client.getCredentials(); + await client.getCredentials({ domain: 'qzone.qq.com' }); + await client.setQqProfile({ nickname: 'luma', personalNote: 'hello' }); + await client.setOnlineStatus(11); + await client.setOnlineStatus(10, { extStatus: 1000, batteryStatus: 80, timeoutMs: 30 }); + + expect(client.calls).toEqual([ + { action: 'get_cookies', params: {}, options: undefined }, + { action: 'get_cookies', params: { domain: 'qun.qq.com' }, options: undefined }, + { action: 'get_credentials', params: {}, options: undefined }, + { action: 'get_credentials', params: { domain: 'qzone.qq.com' }, options: undefined }, + { action: 'set_qq_profile', params: { nickname: 'luma', personal_note: 'hello' }, options: undefined }, + { action: 'set_online_status', params: { status: 11, ext_status: undefined, battery_status: undefined }, options: {} }, + { + action: 'set_online_status', + params: { status: 10, ext_status: 1000, battery_status: 80 }, + options: { extStatus: 1000, batteryStatus: 80, timeoutMs: 30 }, + }, + ]); + }); + + it('maps emoji and system-face helpers including refresh defaults', async () => { + const client = okClient(); + + await client.setMsgEmojiLike(91, '128076'); + await client.setMsgEmojiLike(92, '128077', false); + await client.fetchSysFaces(); + await client.fetchSysFaces(true); + await client.fetchFaceEntity(392); + await client.fetchFaceEntity(393, { refresh: true }); + await client.searchSysFaces('dragon'); + await client.fetchSuperFaceId(394); + await client.fetchSuperFaceId(395, { refresh: false }); + + expect(client.calls).toEqual([ + { action: 'set_msg_emoji_like', params: { message_id: 91, emoji_id: '128076', set: true }, options: undefined }, + { action: 'set_msg_emoji_like', params: { message_id: 92, emoji_id: '128077', set: false }, options: undefined }, + { action: 'fetch_sys_faces', params: { refresh: false }, options: undefined }, + { action: 'fetch_sys_faces', params: { refresh: true }, options: undefined }, + { action: 'fetch_face_entity', params: { face_id: 392, refresh: false }, options: {} }, + { action: 'fetch_face_entity', params: { face_id: 393, refresh: true }, options: { refresh: true } }, + { action: 'search_sys_faces', params: { query: 'dragon' }, options: undefined }, + { action: 'fetch_super_face_id', params: { face_id: 394, refresh: false }, options: {} }, + { action: 'fetch_super_face_id', params: { face_id: 395, refresh: false }, options: { refresh: false } }, + ]); + }); +}); diff --git a/packages/sdk/tests/chain.test.ts b/packages/sdk/tests/chain.test.ts new file mode 100644 index 00000000..323f89bb --- /dev/null +++ b/packages/sdk/tests/chain.test.ts @@ -0,0 +1,506 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + at, + atAll, + br, + chain, + contact, + face, + forward, + image, + json, + location, + MessageChain, + music, + node, + normalizeMessage, + poke, + raw, + record, + reply, + share, + text, + video, + xml, +} from '../src'; + +function sender() { + return { + sendGroupMessage: vi.fn().mockResolvedValue({ message_id: 61001 }), + sendPrivateMessage: vi.fn().mockResolvedValue({ message_id: 61002 }), + }; +} + +describe('MessageChain.empty and chain()', () => { + it('starts empty', () => { + const empty = MessageChain.empty(); + + expect(empty).toBeInstanceOf(MessageChain); + expect(empty.length).toBe(0); + expect(empty.isEmpty).toBe(true); + expect(empty.toSegments()).toEqual([]); + expect(chain().toSegments()).toEqual([]); + }); + + it('updates length and isEmpty after a segment is added', () => { + const next = chain().text('wave'); + + expect(next.length).toBe(1); + expect(next.isEmpty).toBe(false); + expect(chain().isEmpty).toBe(true); + }); + + it('does not mutate the previous chain when a segment is added', () => { + const base = text('keep'); + const next = base.face(39); + + expect(base.toSegments()).toEqual([{ type: 'text', data: { text: 'keep' } }]); + expect(next.toSegments()).toEqual([ + { type: 'text', data: { text: 'keep' } }, + { type: 'face', data: { id: '39' } }, + ]); + }); +}); + +describe('segment builders', () => { + it('builds a text segment and defaults to an empty string', () => { + expect(text().toSegments()).toEqual([{ type: 'text', data: { text: '' } }]); + expect(text('wave').toSegments()).toEqual([{ type: 'text', data: { text: 'wave' } }]); + expect(chain().text().toSegments()).toEqual([{ type: 'text', data: { text: '' } }]); + }); + + it('treats br as a newline text segment', () => { + expect(br().toSegments()).toEqual([{ type: 'text', data: { text: '\n' } }]); + }); + + it('stringifies face ids', () => { + expect(face(39).toSegments()).toEqual([{ type: 'face', data: { id: '39' } }]); + expect(face('178').toSegments()).toEqual([{ type: 'face', data: { id: '178' } }]); + }); + + it('stringifies at targets and only copies truthy name/uid', () => { + expect(at(31415).toSegments()).toEqual([{ type: 'at', data: { qq: '31415' } }]); + expect(at('all').toSegments()).toEqual([{ type: 'at', data: { qq: 'all' } }]); + expect(atAll().toSegments()).toEqual([{ type: 'at', data: { qq: 'all' } }]); + expect(at(31415, { name: 'Ada', uid: 'uid-ada' }).toSegments()).toEqual([ + { type: 'at', data: { qq: '31415', name: 'Ada', uid: 'uid-ada' } }, + ]); + expect(at(31415, { name: '', uid: '' }).toSegments()).toEqual([ + { type: 'at', data: { qq: '31415' } }, + ]); + }); + + it('stringifies reply ids', () => { + expect(reply(88).toSegments()).toEqual([{ type: 'reply', data: { id: '88' } }]); + expect(reply('mid-88').toSegments()).toEqual([{ type: 'reply', data: { id: 'mid-88' } }]); + }); + + it('spreads image, record, and video options after file', () => { + expect(image('file://pic.webp').toSegments()).toEqual([ + { type: 'image', data: { file: 'file://pic.webp' } }, + ]); + expect( + image('file://pic.webp', { + type: 'flash', + subType: 4, + summary: 'cover', + url: 'https://cdn.example/pic.webp', + }).toSegments(), + ).toEqual([ + { + type: 'image', + data: { + file: 'file://pic.webp', + type: 'flash', + subType: 4, + summary: 'cover', + url: 'https://cdn.example/pic.webp', + }, + }, + ]); + expect(record('file://voice.amr').toSegments()).toEqual([ + { type: 'record', data: { file: 'file://voice.amr' } }, + ]); + expect(record('file://voice.amr', { url: 'https://cdn.example/voice.amr' }).toSegments()).toEqual([ + { type: 'record', data: { file: 'file://voice.amr', url: 'https://cdn.example/voice.amr' } }, + ]); + expect(video('file://clip.mp4').toSegments()).toEqual([ + { type: 'video', data: { file: 'file://clip.mp4' } }, + ]); + expect( + video('file://clip.mp4', { + url: 'https://cdn.example/clip.mp4', + thumb: 'file://thumb.jpg', + }).toSegments(), + ).toEqual([ + { + type: 'video', + data: { + file: 'file://clip.mp4', + url: 'https://cdn.example/clip.mp4', + thumb: 'file://thumb.jpg', + }, + }, + ]); + }); + + it('keeps a json string and stringifies a json object', () => { + expect(json('{"prompt":"card"}').toSegments()).toEqual([ + { type: 'json', data: { data: '{"prompt":"card"}' } }, + ]); + expect(json({ prompt: 'card', n: 2 }).toSegments()).toEqual([ + { type: 'json', data: { data: '{"prompt":"card","n":2}' } }, + ]); + }); + + it('spreads xml options after the payload', () => { + expect(xml('').toSegments()).toEqual([{ type: 'xml', data: { data: '' } }]); + expect(xml('', { id: 'resid-3' }).toSegments()).toEqual([ + { type: 'xml', data: { data: '', id: 'resid-3' } }, + ]); + }); + + it('omits poke id only when it is undefined', () => { + expect(poke(6).toSegments()).toEqual([{ type: 'poke', data: { type: 6 } }]); + expect(poke(6, 0).toSegments()).toEqual([{ type: 'poke', data: { type: 6, id: 0 } }]); + expect(poke('6', '-1').toSegments()).toEqual([{ type: 'poke', data: { type: '6', id: '-1' } }]); + }); + + it('mirrors a forward id onto res_id and forward_id', () => { + expect(forward('fwd-22').toSegments()).toEqual([ + { type: 'forward', data: { id: 'fwd-22', res_id: 'fwd-22', forward_id: 'fwd-22' } }, + ]); + }); + + it('stores node content as given', () => { + const inner = text('nested'); + + expect(node(20002, 'bot', 'plain').toSegments()).toEqual([ + { type: 'node', data: { user_id: 20002, nickname: 'bot', content: 'plain' } }, + ]); + expect(node(20002, 'bot', { type: 'text', data: { text: 'seg' } }).toSegments()).toEqual([ + { + type: 'node', + data: { user_id: 20002, nickname: 'bot', content: { type: 'text', data: { text: 'seg' } } }, + }, + ]); + expect(node(20002, 'bot', inner).toSegments()).toEqual([ + { type: 'node', data: { user_id: 20002, nickname: 'bot', content: inner } }, + ]); + }); + + it('passes share, music, location, and contact data through', () => { + expect(share({ url: 'https://ex.test/page', title: 'Page' }).toSegments()).toEqual([ + { type: 'share', data: { url: 'https://ex.test/page', title: 'Page' } }, + ]); + expect( + share({ + url: 'https://ex.test/page', + title: 'Page', + content: 'blurb', + image: 'https://ex.test/cover.png', + }).toSegments(), + ).toEqual([ + { + type: 'share', + data: { + url: 'https://ex.test/page', + title: 'Page', + content: 'blurb', + image: 'https://ex.test/cover.png', + }, + }, + ]); + expect(music({ type: 'qq', id: '991' }).toSegments()).toEqual([ + { type: 'music', data: { type: 'qq', id: '991' } }, + ]); + expect( + location({ lat: 30.1, lon: 120.2, title: 'Hangzhou', content: 'West Lake' }).toSegments(), + ).toEqual([ + { + type: 'location', + data: { lat: 30.1, lon: 120.2, title: 'Hangzhou', content: 'West Lake' }, + }, + ]); + expect(contact('qq', 20002).toSegments()).toEqual([ + { type: 'contact', data: { type: 'qq', id: 20002 } }, + ]); + expect(contact('group', '987654').toSegments()).toEqual([ + { type: 'contact', data: { type: 'group', id: '987654' } }, + ]); + }); + + it('builds an arbitrary raw segment', () => { + expect(raw('dice', { result: 3 }).toSegments()).toEqual([ + { type: 'dice', data: { result: 3 } }, + ]); + }); + + it('chains fluent builders in order', () => { + const built = chain().text('ping').at(20002).br().image('file://b.jpg').face(39); + + expect(built.length).toBe(5); + expect(built.toSegments()).toEqual([ + { type: 'text', data: { text: 'ping' } }, + { type: 'at', data: { qq: '20002' } }, + { type: 'text', data: { text: '\n' } }, + { type: 'image', data: { file: 'file://b.jpg' } }, + { type: 'face', data: { id: '39' } }, + ]); + }); +}); + +describe('append', () => { + it('appends a string as a text segment', () => { + expect(text('pre').append('post').toSegments()).toEqual([ + { type: 'text', data: { text: 'pre' } }, + { type: 'text', data: { text: 'post' } }, + ]); + expect(text('pre').append('').toSegments()).toEqual([ + { type: 'text', data: { text: 'pre' } }, + { type: 'text', data: { text: '' } }, + ]); + }); + + it('returns the same instance when appending an empty array', () => { + const base = text('keep'); + expect(base.append([])).toBe(base); + }); + + it('appends a single segment', () => { + expect(text('pre').append({ type: 'face', data: { id: '39' } }).toSegments()).toEqual([ + { type: 'text', data: { text: 'pre' } }, + { type: 'face', data: { id: '39' } }, + ]); + }); + + it('appends a segment array', () => { + expect( + text('pre') + .append([ + { type: 'at', data: { qq: 'all' } }, + { type: 'face', data: { id: '39' } }, + ]) + .toSegments(), + ).toEqual([ + { type: 'text', data: { text: 'pre' } }, + { type: 'at', data: { qq: 'all' } }, + { type: 'face', data: { id: '39' } }, + ]); + }); + + it('appends another chain by copying its segments', () => { + const extra = at(20002).text('!'); + expect(text('pre').append(extra).toSegments()).toEqual([ + { type: 'text', data: { text: 'pre' } }, + { type: 'at', data: { qq: '20002' } }, + { type: 'text', data: { text: '!' } }, + ]); + expect(extra.toSegments()).toEqual([ + { type: 'at', data: { qq: '20002' } }, + { type: 'text', data: { text: '!' } }, + ]); + }); + + it('appends a duck-typed chain-like value via toSegments', () => { + const duck = { + length: 1, + toSegments() { + return [{ type: 'poke', data: { type: 6 } }]; + }, + toJSON() { + return this.toSegments(); + }, + }; + + expect(text('pre').append(duck).toSegments()).toEqual([ + { type: 'text', data: { text: 'pre' } }, + { type: 'poke', data: { type: 6 } }, + ]); + }); +}); + +describe('single-use reply', () => { + it('throws when reply is added twice through reply()', () => { + const once = reply(88); + expect(() => (once as unknown as { reply(id: number): unknown }).reply(89)).toThrow( + 'Message segment "reply" can only appear once in a chain', + ); + }); + + it('throws when a second reply is appended', () => { + expect(() => reply(88).append({ type: 'reply', data: { id: '89' } })).toThrow( + 'Message segment "reply" can only appear once in a chain', + ); + expect(() => + chain().append([ + { type: 'reply', data: { id: '88' } }, + { type: 'text', data: { text: 'x' } }, + { type: 'reply', data: { id: '89' } }, + ]), + ).toThrow('Message segment "reply" can only appear once in a chain'); + }); + + it('throws when raw reply is added twice', () => { + expect(() => raw('reply', { id: '88' }).raw('reply', { id: '89' })).toThrow( + 'Message segment "reply" can only appear once in a chain', + ); + }); + + it('allows two independent chains to each have their own reply', () => { + const base = text('fork'); + expect(base.reply(88).toSegments()).toEqual([ + { type: 'text', data: { text: 'fork' } }, + { type: 'reply', data: { id: '88' } }, + ]); + expect(base.reply(89).toSegments()).toEqual([ + { type: 'text', data: { text: 'fork' } }, + { type: 'reply', data: { id: '89' } }, + ]); + }); + + it('allows non-reply types, including raw, to appear more than once', () => { + expect(image('a.webp').image('b.webp').toSegments()).toEqual([ + { type: 'image', data: { file: 'a.webp' } }, + { type: 'image', data: { file: 'b.webp' } }, + ]); + expect(raw('dice', { result: 1 }).raw('dice', { result: 2 }).toSegments()).toEqual([ + { type: 'dice', data: { result: 1 } }, + { type: 'dice', data: { result: 2 } }, + ]); + }); + + it('still allows other segments after a reply', () => { + expect(reply(88).text('after').toSegments()).toEqual([ + { type: 'reply', data: { id: '88' } }, + { type: 'text', data: { text: 'after' } }, + ]); + }); +}); + +describe('serialization and iteration', () => { + it('returns a shallow copy from build, toArray, toSegments, and toJSON', () => { + const built = text('copy').at(20002); + const viaBuild = built.build(); + const viaArray = built.toArray(); + const viaSegments = built.toSegments(); + const viaJson = built.toJSON(); + const expected = [ + { type: 'text', data: { text: 'copy' } }, + { type: 'at', data: { qq: '20002' } }, + ]; + + expect(viaBuild).toEqual(expected); + expect(viaArray).toEqual(expected); + expect(viaSegments).toEqual(expected); + expect(viaJson).toEqual(expected); + expect(viaBuild).not.toBe(viaArray); + expect(viaArray).not.toBe(viaSegments); + expect(viaSegments).not.toBe(viaJson); + + viaBuild.push({ type: 'face', data: { id: '1' } }); + expect(built.toSegments()).toEqual(expected); + expect(built.length).toBe(2); + }); + + it('uses toJSON when stringified', () => { + expect(JSON.parse(JSON.stringify(text('copy').at(20002)))).toEqual([ + { type: 'text', data: { text: 'copy' } }, + { type: 'at', data: { qq: '20002' } }, + ]); + }); + + it('renders CQ text through toString', () => { + expect(chain().toString()).toBe(''); + expect(text('A&B[C]').toString()).toBe('A&B[C]'); + expect(text('wave').at(20002).face(39).toString()).toBe('wave[CQ:at,qq=20002][CQ:face,id=39]'); + expect(image('a,b').toString()).toBe('[CQ:image,file=a,b]'); + expect(raw('dice', {}).toString()).toBe('[CQ:dice]'); + expect(chain().append({ type: 'image', data: { file: 'z.webp', url: undefined } }).toString()).toBe( + '[CQ:image,file=z.webp]', + ); + }); + + it('iterates stored segments', () => { + const built = text('wave').face(39); + expect([...built]).toEqual([ + { type: 'text', data: { text: 'wave' } }, + { type: 'face', data: { id: '39' } }, + ]); + + const walked: unknown[] = []; + for (const segment of built) { + walked.push(segment); + } + expect(walked).toEqual([ + { type: 'text', data: { text: 'wave' } }, + { type: 'face', data: { id: '39' } }, + ]); + }); +}); + +describe('sendToGroup and sendToPrivate', () => { + it('forwards the chain instance and options to the client', async () => { + const client = sender(); + const groupPayload = text('group-hi'); + const privatePayload = text('priv-hi'); + const options = { autoEscape: true, timeoutMs: 2500, echo: 'echo-chain' }; + + await expect(groupPayload.sendToGroup(client, 70001, options)).resolves.toEqual({ + message_id: 61001, + }); + await expect(privatePayload.sendToPrivate(client, 80001, options)).resolves.toEqual({ + message_id: 61002, + }); + + expect(client.sendGroupMessage).toHaveBeenCalledTimes(1); + expect(client.sendGroupMessage).toHaveBeenCalledWith(70001, groupPayload, options); + expect(client.sendPrivateMessage).toHaveBeenCalledTimes(1); + expect(client.sendPrivateMessage).toHaveBeenCalledWith(80001, privatePayload, options); + }); + + it('passes undefined options when none are given', async () => { + const client = sender(); + const payload = text('plain'); + + await payload.sendToGroup(client, 70002); + await payload.sendToPrivate(client, 80002); + + expect(client.sendGroupMessage).toHaveBeenCalledWith(70002, payload, undefined); + expect(client.sendPrivateMessage).toHaveBeenCalledWith(80002, payload, undefined); + }); +}); + +describe('normalizeMessage', () => { + it('returns a string unchanged', () => { + expect(normalizeMessage('plain-text')).toBe('plain-text'); + expect(normalizeMessage('')).toBe(''); + }); + + it('returns toSegments() for a chain and for duck-typed chain-like values', () => { + expect(normalizeMessage(text('wave').at(20002))).toEqual([ + { type: 'text', data: { text: 'wave' } }, + { type: 'at', data: { qq: '20002' } }, + ]); + + const segs = [{ type: 'face', data: { id: '39' } }]; + const duck = { toSegments: () => segs }; + expect(normalizeMessage(duck)).toBe(segs); + }); + + it('returns an array input by reference', () => { + const segs = [{ type: 'text', data: { text: 'arr' } }]; + expect(normalizeMessage(segs)).toBe(segs); + }); + + it('wraps a single segment in a new array', () => { + const segment = { type: 'text', data: { text: 'solo' } }; + expect(normalizeMessage(segment)).toEqual([segment]); + expect(normalizeMessage(segment)).not.toBe(segment); + }); + + it('does not treat an object with a non-function toSegments as a chain', () => { + const value = { type: 'text', data: { text: 'solo' }, toSegments: 0 }; + expect(normalizeMessage(value as never)).toEqual([value]); + }); +}); diff --git a/packages/sdk/tests/emitter.test.ts b/packages/sdk/tests/emitter.test.ts new file mode 100644 index 00000000..cf10de88 --- /dev/null +++ b/packages/sdk/tests/emitter.test.ts @@ -0,0 +1,331 @@ +import { describe, expect, it } from 'vitest'; +import { Emitter } from '../src/emitter'; + +type TestEvents = { + open: undefined; + data: string; + count: number; + close: { code: number; reason: string }; +}; + +describe('Emitter', () => { + it('delivers a payload to a listener registered with on', () => { + const emitter = new Emitter(); + const seen: string[] = []; + + emitter.on('data', (payload) => { + seen.push(payload); + }); + emitter.emit('data', 'hello'); + + expect(seen).toEqual(['hello']); + }); + + it('invokes every listener for the same event in registration order', () => { + const emitter = new Emitter(); + const seen: string[] = []; + + emitter.on('data', (payload) => { + seen.push(`first:${payload}`); + }); + emitter.on('data', (payload) => { + seen.push(`second:${payload}`); + }); + emitter.emit('data', 'alpha'); + + expect(seen).toEqual(['first:alpha', 'second:alpha']); + }); + + it('keeps listeners for different events isolated', () => { + const emitter = new Emitter(); + const data: string[] = []; + const counts: number[] = []; + + emitter.on('data', (payload) => { + data.push(payload); + }); + emitter.on('count', (payload) => { + counts.push(payload); + }); + emitter.emit('data', 'alpha'); + emitter.emit('count', 7); + emitter.emit('data', 'beta'); + + expect(data).toEqual(['alpha', 'beta']); + expect(counts).toEqual([7]); + }); + + it('passes the payload object through by reference', () => { + const emitter = new Emitter(); + const payload = { code: 1000, reason: 'done' }; + const seen: Array<{ code: number; reason: string }> = []; + + emitter.on('close', (value) => { + seen.push(value); + }); + emitter.emit('close', payload); + + expect(seen).toEqual([{ code: 1000, reason: 'done' }]); + expect(seen[0]).toBe(payload); + }); + + it('forwards an undefined payload for events typed as undefined', () => { + const emitter = new Emitter(); + const seen: Array = []; + + emitter.on('open', (payload) => { + seen.push(payload); + }); + emitter.emit('open', undefined); + + expect(seen).toEqual([undefined]); + }); + + it('stores a listener only once when the same function is registered twice', () => { + const emitter = new Emitter(); + const seen: string[] = []; + const listener = (payload: string) => { + seen.push(payload); + }; + + emitter.on('data', listener); + emitter.on('data', listener); + emitter.emit('data', 'once-only'); + + expect(seen).toEqual(['once-only']); + }); + + it('returns an unsubscribe function from on that stops later delivery', () => { + const emitter = new Emitter(); + const seen: string[] = []; + + const off = emitter.on('data', (payload) => { + seen.push(payload); + }); + off(); + emitter.emit('data', 'nope'); + + expect(seen).toEqual([]); + }); + + it('does not throw when emit is called with no listeners for that event', () => { + const emitter = new Emitter(); + + expect(() => emitter.emit('data', 'orphan')).not.toThrow(); + }); + + it('does not deliver after every listener has been unsubscribed, even if the event key remains', () => { + const emitter = new Emitter(); + const seen: string[] = []; + + const off = emitter.on('data', (payload) => { + seen.push(payload); + }); + off(); + emitter.emit('data', 'ghost'); + + expect(seen).toEqual([]); + }); + + it('fires a once listener exactly once', () => { + const emitter = new Emitter(); + const seen: string[] = []; + + emitter.once('data', (payload) => { + seen.push(payload); + }); + emitter.emit('data', 'first'); + emitter.emit('data', 'second'); + + expect(seen).toEqual(['first']); + }); + + it('lets once and on listeners share an event without once firing again', () => { + const emitter = new Emitter(); + const seen: string[] = []; + + emitter.on('data', (payload) => { + seen.push(`on:${payload}`); + }); + emitter.once('data', (payload) => { + seen.push(`once:${payload}`); + }); + emitter.emit('data', 'a'); + emitter.emit('data', 'b'); + + expect(seen).toEqual(['on:a', 'once:a', 'on:b']); + }); + + it('does not call a once listener that was unsubscribed before emit', () => { + const emitter = new Emitter(); + const seen: string[] = []; + + const off = emitter.once('data', (payload) => { + seen.push(payload); + }); + off(); + emitter.emit('data', 'nope'); + + expect(seen).toEqual([]); + }); + + it('allows calling the once unsubscribe after it has already fired', () => { + const emitter = new Emitter(); + const seen: string[] = []; + + const off = emitter.once('data', (payload) => { + seen.push(payload); + }); + emitter.emit('data', 'first'); + off(); + emitter.emit('data', 'second'); + + expect(seen).toEqual(['first']); + }); + + it('does not re-enter a once listener that emits the same event again', () => { + const emitter = new Emitter(); + const seen: string[] = []; + + emitter.once('data', (payload) => { + seen.push(payload); + emitter.emit('data', 'again'); + }); + emitter.emit('data', 'first'); + + expect(seen).toEqual(['first']); + }); + + it('does not cancel a once subscription when off is given the original listener', () => { + const emitter = new Emitter(); + const seen: string[] = []; + const listener = (payload: string) => { + seen.push(payload); + }; + + emitter.once('data', listener); + emitter.off('data', listener); + emitter.emit('data', 'still'); + + expect(seen).toEqual(['still']); + }); + + it('removes only the given listener when off is called', () => { + const emitter = new Emitter(); + const seen: string[] = []; + const keep = (payload: string) => { + seen.push(`keep:${payload}`); + }; + const drop = (payload: string) => { + seen.push(`drop:${payload}`); + }; + + emitter.on('data', keep); + emitter.on('data', drop); + emitter.off('data', drop); + emitter.emit('data', 'x'); + + expect(seen).toEqual(['keep:x']); + }); + + it('does not throw when off is called for an event that was never registered', () => { + const emitter = new Emitter(); + + expect(() => { + emitter.off('data', () => {}); + }).not.toThrow(); + }); + + it('does not throw when off is called with a listener that was never added', () => { + const emitter = new Emitter(); + + emitter.on('data', (payload) => { + void payload; + }); + + expect(() => { + emitter.off('data', () => {}); + }).not.toThrow(); + }); + + it('still delivers to a listener removed by an earlier listener during the same emit', () => { + const emitter = new Emitter(); + const seen: string[] = []; + const second = (payload: string) => { + seen.push(`second:${payload}`); + }; + + emitter.on('data', (payload) => { + seen.push(`first:${payload}`); + emitter.off('data', second); + }); + emitter.on('data', second); + emitter.emit('data', 'keep'); + + expect(seen).toEqual(['first:keep', 'second:keep']); + }); + + it('does not deliver to a listener added during the same emit', () => { + const emitter = new Emitter(); + const seen: string[] = []; + const late = (payload: string) => { + seen.push(`late:${payload}`); + }; + + emitter.on('data', (payload) => { + seen.push(`early:${payload}`); + emitter.on('data', late); + }); + emitter.emit('data', 'now'); + emitter.emit('data', 'next'); + + expect(seen).toEqual(['early:now', 'early:next', 'late:next']); + }); + + it('stops all listeners after clear', () => { + const emitter = new Emitter(); + const seen: Array = []; + + emitter.on('data', (payload) => { + seen.push(payload); + }); + emitter.on('count', (payload) => { + seen.push(payload); + }); + emitter.clear(); + emitter.emit('data', 'x'); + emitter.emit('count', 1); + + expect(seen).toEqual([]); + }); + + it('accepts new listeners after clear', () => { + const emitter = new Emitter(); + const seen: string[] = []; + + emitter.on('data', (payload) => { + seen.push(`old:${payload}`); + }); + emitter.clear(); + emitter.on('data', (payload) => { + seen.push(`new:${payload}`); + }); + emitter.emit('data', 'after'); + + expect(seen).toEqual(['new:after']); + }); + + it('does not throw when off is called after clear', () => { + const emitter = new Emitter(); + const listener = (payload: string) => { + void payload; + }; + + emitter.on('data', listener); + emitter.clear(); + + expect(() => { + emitter.off('data', listener); + }).not.toThrow(); + }); +}); diff --git a/packages/sdk/tests/guards.test.ts b/packages/sdk/tests/guards.test.ts new file mode 100644 index 00000000..d05eb1b4 --- /dev/null +++ b/packages/sdk/tests/guards.test.ts @@ -0,0 +1,450 @@ +import { describe, expect, it } from 'vitest'; +import { + isGroupMessageEvent, + isMessageEvent, + isMetaEvent, + isNoticeEvent, + isPrivateMessageEvent, + isRequestEvent, + noticeType, + requestType, + type OneBotGroupMessageEvent, + type OneBotMetaEvent, + type OneBotNoticeEvent, + type OneBotPrivateMessageEvent, + type OneBotRequestEvent, + type SnowLumaEvent, +} from '../src'; + +const PRIVATE_MESSAGE: OneBotPrivateMessageEvent = { + time: 1_700_000_001, + self_id: 10000, + post_type: 'message', + message_type: 'private', + sub_type: 'friend', + message_id: 11, + message_seq: 12, + user_id: 20001, + message: [{ type: 'text', data: { text: 'hi' } }], + raw_message: 'hi', + font: 0, + sender: { user_id: 20001, nickname: 'alice' }, +}; + +const PRIVATE_SENT: OneBotPrivateMessageEvent = { + time: 1_700_000_002, + self_id: 10000, + post_type: 'message_sent', + message_type: 'private', + sub_type: 'friend', + message_id: 13, + user_id: 20002, + message: 'echo', + raw_message: 'echo', + font: 0, + sender: { user_id: 10000, nickname: 'bot' }, +}; + +const GROUP_MESSAGE: OneBotGroupMessageEvent = { + time: 1_700_000_003, + self_id: 10000, + post_type: 'message', + message_type: 'group', + sub_type: 'normal', + message_id: 21, + message_seq: 22, + group_id: 30001, + user_id: 20003, + message: [{ type: 'text', data: { text: 'hey' } }], + raw_message: 'hey', + font: 0, + sender: { user_id: 20003, nickname: 'bob', card: 'Bobby', role: 'member' }, +}; + +const GROUP_SENT: OneBotGroupMessageEvent = { + time: 1_700_000_004, + self_id: 10000, + post_type: 'message_sent', + message_type: 'group', + sub_type: 'normal', + message_id: 23, + group_id: 30002, + user_id: 10000, + message: 'sent', + raw_message: 'sent', + font: 0, + sender: { user_id: 10000, nickname: 'bot' }, +}; + +const NOTICE: OneBotNoticeEvent = { + time: 1_700_000_005, + self_id: 10000, + post_type: 'notice', + notice_type: 'group_increase', +}; + +const REQUEST: OneBotRequestEvent = { + time: 1_700_000_006, + self_id: 10000, + post_type: 'request', + request_type: 'friend', + flag: 'flag-friend-1', + user_id: 20004, + comment: 'please', +}; + +const META: OneBotMetaEvent = { + time: 1_700_000_007, + self_id: 10000, + post_type: 'meta_event', + meta_event_type: 'heartbeat', +}; + +const UNKNOWN: SnowLumaEvent = { + time: 1_700_000_008, + self_id: 10000, + post_type: 'unknown', +}; + +describe('isMessageEvent', () => { + it('accepts inbound private and group messages', () => { + expect(isMessageEvent(PRIVATE_MESSAGE)).toBe(true); + expect(isMessageEvent(GROUP_MESSAGE)).toBe(true); + }); + + it('accepts message_sent private and group events', () => { + expect(isMessageEvent(PRIVATE_SENT)).toBe(true); + expect(isMessageEvent(GROUP_SENT)).toBe(true); + }); + + it('rejects message post types whose message_type is not private or group', () => { + const guild: SnowLumaEvent = { + time: 9, + self_id: 10000, + post_type: 'message', + message_type: 'guild', + }; + const sentChannel: SnowLumaEvent = { + time: 10, + self_id: 10000, + post_type: 'message_sent', + message_type: 'channel', + }; + const missingType: SnowLumaEvent = { + time: 11, + self_id: 10000, + post_type: 'message', + }; + + expect(isMessageEvent(guild)).toBe(false); + expect(isMessageEvent(sentChannel)).toBe(false); + expect(isMessageEvent(missingType)).toBe(false); + }); + + it('rejects non-message events even when message_type is present', () => { + const noticeShaped: SnowLumaEvent = { + time: 12, + self_id: 10000, + post_type: 'notice', + notice_type: 'notify', + message_type: 'private', + }; + + expect(isMessageEvent(NOTICE)).toBe(false); + expect(isMessageEvent(REQUEST)).toBe(false); + expect(isMessageEvent(META)).toBe(false); + expect(isMessageEvent(UNKNOWN)).toBe(false); + expect(isMessageEvent(noticeShaped)).toBe(false); + }); +}); + +describe('isPrivateMessageEvent', () => { + it('accepts private inbound and sent messages', () => { + expect(isPrivateMessageEvent(PRIVATE_MESSAGE)).toBe(true); + expect(isPrivateMessageEvent(PRIVATE_SENT)).toBe(true); + }); + + it('rejects group messages and non-message events', () => { + expect(isPrivateMessageEvent(GROUP_MESSAGE)).toBe(false); + expect(isPrivateMessageEvent(GROUP_SENT)).toBe(false); + expect(isPrivateMessageEvent(NOTICE)).toBe(false); + expect(isPrivateMessageEvent(REQUEST)).toBe(false); + expect(isPrivateMessageEvent(META)).toBe(false); + }); + + it('rejects private message_type when post_type is not a message kind', () => { + const leftover: SnowLumaEvent = { + time: 13, + self_id: 10000, + post_type: 'notice', + notice_type: 'friend_add', + message_type: 'private', + }; + + expect(isPrivateMessageEvent(leftover)).toBe(false); + }); +}); + +describe('isGroupMessageEvent', () => { + it('accepts group inbound and sent messages', () => { + expect(isGroupMessageEvent(GROUP_MESSAGE)).toBe(true); + expect(isGroupMessageEvent(GROUP_SENT)).toBe(true); + }); + + it('rejects private messages and non-message events', () => { + expect(isGroupMessageEvent(PRIVATE_MESSAGE)).toBe(false); + expect(isGroupMessageEvent(PRIVATE_SENT)).toBe(false); + expect(isGroupMessageEvent(NOTICE)).toBe(false); + expect(isGroupMessageEvent(REQUEST)).toBe(false); + expect(isGroupMessageEvent(META)).toBe(false); + }); + + it('rejects group message_type when post_type is not a message kind', () => { + const leftover: SnowLumaEvent = { + time: 14, + self_id: 10000, + post_type: 'request', + request_type: 'group', + flag: 'flag-x', + message_type: 'group', + }; + + expect(isGroupMessageEvent(leftover)).toBe(false); + }); +}); + +describe('isNoticeEvent', () => { + it('accepts notice events with a string notice_type', () => { + expect(isNoticeEvent(NOTICE)).toBe(true); + expect(isNoticeEvent({ + time: 15, + self_id: 10000, + post_type: 'notice', + notice_type: '', + })).toBe(true); + }); + + it('rejects notice post_type when notice_type is not a string', () => { + const missing: SnowLumaEvent = { + time: 16, + self_id: 10000, + post_type: 'notice', + }; + const numeric: SnowLumaEvent = { + time: 17, + self_id: 10000, + post_type: 'notice', + notice_type: 7, + }; + const nulled: SnowLumaEvent = { + time: 18, + self_id: 10000, + post_type: 'notice', + notice_type: null, + }; + + expect(isNoticeEvent(missing)).toBe(false); + expect(isNoticeEvent(numeric)).toBe(false); + expect(isNoticeEvent(nulled)).toBe(false); + }); + + it('rejects other post types', () => { + expect(isNoticeEvent(PRIVATE_MESSAGE)).toBe(false); + expect(isNoticeEvent(REQUEST)).toBe(false); + expect(isNoticeEvent(META)).toBe(false); + expect(isNoticeEvent(UNKNOWN)).toBe(false); + }); +}); + +describe('isRequestEvent', () => { + it('accepts request events with string request_type and flag', () => { + expect(isRequestEvent(REQUEST)).toBe(true); + expect(isRequestEvent({ + time: 19, + self_id: 10000, + post_type: 'request', + request_type: 'group', + sub_type: 'add', + flag: '', + group_id: 30003, + })).toBe(true); + }); + + it('rejects request post_type when request_type or flag is not a string', () => { + const missingFlag: SnowLumaEvent = { + time: 20, + self_id: 10000, + post_type: 'request', + request_type: 'friend', + }; + const numericFlag: SnowLumaEvent = { + time: 21, + self_id: 10000, + post_type: 'request', + request_type: 'friend', + flag: 99, + }; + const missingType: SnowLumaEvent = { + time: 22, + self_id: 10000, + post_type: 'request', + flag: 'flag-2', + }; + const numericType: SnowLumaEvent = { + time: 23, + self_id: 10000, + post_type: 'request', + request_type: 1, + flag: 'flag-3', + }; + const nullFlag: SnowLumaEvent = { + time: 24, + self_id: 10000, + post_type: 'request', + request_type: 'friend', + flag: null, + }; + + expect(isRequestEvent(missingFlag)).toBe(false); + expect(isRequestEvent(numericFlag)).toBe(false); + expect(isRequestEvent(missingType)).toBe(false); + expect(isRequestEvent(numericType)).toBe(false); + expect(isRequestEvent(nullFlag)).toBe(false); + }); + + it('rejects other post types even when request fields are present', () => { + const leftover: SnowLumaEvent = { + time: 25, + self_id: 10000, + post_type: 'notice', + notice_type: 'group_ban', + request_type: 'group', + flag: 'flag-4', + }; + + expect(isRequestEvent(PRIVATE_MESSAGE)).toBe(false); + expect(isRequestEvent(NOTICE)).toBe(false); + expect(isRequestEvent(META)).toBe(false); + expect(isRequestEvent(leftover)).toBe(false); + }); +}); + +describe('isMetaEvent', () => { + it('accepts meta_event events with a string meta_event_type', () => { + expect(isMetaEvent(META)).toBe(true); + expect(isMetaEvent({ + time: 26, + self_id: 10000, + post_type: 'meta_event', + meta_event_type: 'lifecycle', + })).toBe(true); + }); + + it('rejects meta_event post_type when meta_event_type is not a string', () => { + const missing: SnowLumaEvent = { + time: 27, + self_id: 10000, + post_type: 'meta_event', + }; + const numeric: SnowLumaEvent = { + time: 28, + self_id: 10000, + post_type: 'meta_event', + meta_event_type: 0, + }; + const nulled: SnowLumaEvent = { + time: 29, + self_id: 10000, + post_type: 'meta_event', + meta_event_type: null, + }; + + expect(isMetaEvent(missing)).toBe(false); + expect(isMetaEvent(numeric)).toBe(false); + expect(isMetaEvent(nulled)).toBe(false); + }); + + it('rejects other post types', () => { + expect(isMetaEvent(PRIVATE_MESSAGE)).toBe(false); + expect(isMetaEvent(NOTICE)).toBe(false); + expect(isMetaEvent(REQUEST)).toBe(false); + expect(isMetaEvent(UNKNOWN)).toBe(false); + }); +}); + +describe('noticeType', () => { + it('matches notice events by notice_type', () => { + const isIncrease = noticeType('group_increase'); + const isDecrease = noticeType('group_decrease'); + + expect(isIncrease(NOTICE)).toBe(true); + expect(isDecrease(NOTICE)).toBe(false); + expect(isIncrease({ + time: 30, + self_id: 10000, + post_type: 'notice', + notice_type: 'group_decrease', + })).toBe(false); + }); + + it('rejects events that fail isNoticeEvent', () => { + const isIncrease = noticeType('group_increase'); + const missingType: SnowLumaEvent = { + time: 31, + self_id: 10000, + post_type: 'notice', + }; + const leftover: SnowLumaEvent = { + time: 32, + self_id: 10000, + post_type: 'message', + message_type: 'private', + notice_type: 'group_increase', + }; + + expect(isIncrease(missingType)).toBe(false); + expect(isIncrease(leftover)).toBe(false); + expect(isIncrease(REQUEST)).toBe(false); + expect(isIncrease(PRIVATE_MESSAGE)).toBe(false); + }); +}); + +describe('requestType', () => { + it('matches request events by request_type', () => { + const isFriend = requestType('friend'); + const isGroup = requestType('group'); + + expect(isFriend(REQUEST)).toBe(true); + expect(isGroup(REQUEST)).toBe(false); + expect(isFriend({ + time: 33, + self_id: 10000, + post_type: 'request', + request_type: 'group', + flag: 'flag-group-1', + })).toBe(false); + }); + + it('rejects events that fail isRequestEvent', () => { + const isFriend = requestType('friend'); + const missingFlag: SnowLumaEvent = { + time: 34, + self_id: 10000, + post_type: 'request', + request_type: 'friend', + }; + const leftover: SnowLumaEvent = { + time: 35, + self_id: 10000, + post_type: 'notice', + notice_type: 'friend_add', + request_type: 'friend', + flag: 'flag-5', + }; + + expect(isFriend(missingFlag)).toBe(false); + expect(isFriend(leftover)).toBe(false); + expect(isFriend(NOTICE)).toBe(false); + expect(isFriend(META)).toBe(false); + }); +}); diff --git a/packages/sdk/tests/segments.test.ts b/packages/sdk/tests/segments.test.ts new file mode 100644 index 00000000..f4f94aaf --- /dev/null +++ b/packages/sdk/tests/segments.test.ts @@ -0,0 +1,347 @@ +import { describe, expect, it } from 'vitest'; +import { segments } from '../src/messages/segments'; + +describe('segments.text', () => { + it('wraps a string as a text segment', () => { + expect(segments.text('hello')).toEqual({ type: 'text', data: { text: 'hello' } }); + }); + + it('keeps empty text', () => { + expect(segments.text('')).toEqual({ type: 'text', data: { text: '' } }); + }); +}); + +describe('segments.face', () => { + it('stringifies a numeric face id', () => { + expect(segments.face(14)).toEqual({ type: 'face', data: { id: '14' } }); + }); + + it('keeps a string face id', () => { + expect(segments.face('178')).toEqual({ type: 'face', data: { id: '178' } }); + }); + + it('stringifies zero', () => { + expect(segments.face(0)).toEqual({ type: 'face', data: { id: '0' } }); + }); +}); + +describe('segments.at', () => { + it('stringifies a numeric qq and omits empty options', () => { + expect(segments.at(10001)).toEqual({ type: 'at', data: { qq: '10001' } }); + }); + + it('supports at-all', () => { + expect(segments.at('all')).toEqual({ type: 'at', data: { qq: 'all' } }); + }); + + it('includes name when provided', () => { + expect(segments.at(10001, { name: 'luma' })).toEqual({ + type: 'at', + data: { qq: '10001', name: 'luma' }, + }); + }); + + it('includes uid when provided', () => { + expect(segments.at(10001, { uid: 'u_abc' })).toEqual({ + type: 'at', + data: { qq: '10001', uid: 'u_abc' }, + }); + }); + + it('includes both name and uid', () => { + expect(segments.at(10001, { name: 'luma', uid: 'u_abc' })).toEqual({ + type: 'at', + data: { qq: '10001', name: 'luma', uid: 'u_abc' }, + }); + }); + + it('omits empty name and uid', () => { + expect(segments.at(10001, { name: '', uid: '' })).toEqual({ + type: 'at', + data: { qq: '10001' }, + }); + }); +}); + +describe('segments.reply', () => { + it('stringifies a numeric message id', () => { + expect(segments.reply(7)).toEqual({ type: 'reply', data: { id: '7' } }); + }); + + it('keeps a string message id', () => { + expect(segments.reply('abc')).toEqual({ type: 'reply', data: { id: 'abc' } }); + }); +}); + +describe('segments.image', () => { + it('uses only the file when no options are given', () => { + expect(segments.image('/tmp/a.png')).toEqual({ + type: 'image', + data: { file: '/tmp/a.png' }, + }); + }); + + it('spreads image options after file', () => { + expect( + segments.image('base64://abc', { + type: 'flash', + subType: 1, + summary: 'pic', + url: 'https://example.com/a.png', + }), + ).toEqual({ + type: 'image', + data: { + file: 'base64://abc', + type: 'flash', + subType: 1, + summary: 'pic', + url: 'https://example.com/a.png', + }, + }); + }); +}); + +describe('segments.record', () => { + it('uses only the file when no options are given', () => { + expect(segments.record('/tmp/a.amr')).toEqual({ + type: 'record', + data: { file: '/tmp/a.amr' }, + }); + }); + + it('spreads record options after file', () => { + expect(segments.record('/tmp/a.amr', { url: 'https://example.com/a.amr' })).toEqual({ + type: 'record', + data: { file: '/tmp/a.amr', url: 'https://example.com/a.amr' }, + }); + }); +}); + +describe('segments.video', () => { + it('uses only the file when no options are given', () => { + expect(segments.video('/tmp/a.mp4')).toEqual({ + type: 'video', + data: { file: '/tmp/a.mp4' }, + }); + }); + + it('spreads video options after file', () => { + expect( + segments.video('/tmp/a.mp4', { + url: 'https://example.com/a.mp4', + thumb: '/tmp/thumb.jpg', + }), + ).toEqual({ + type: 'video', + data: { + file: '/tmp/a.mp4', + url: 'https://example.com/a.mp4', + thumb: '/tmp/thumb.jpg', + }, + }); + }); +}); + +describe('segments.json', () => { + it('keeps a JSON string as-is', () => { + expect(segments.json('{"app":"com.tencent.miniapp"}')).toEqual({ + type: 'json', + data: { data: '{"app":"com.tencent.miniapp"}' }, + }); + }); + + it('stringifies a JSON object', () => { + expect(segments.json({ app: 'com.tencent.miniapp', desc: 'hi' })).toEqual({ + type: 'json', + data: { data: '{"app":"com.tencent.miniapp","desc":"hi"}' }, + }); + }); +}); + +describe('segments.xml', () => { + it('uses only the xml payload when no options are given', () => { + expect(segments.xml('')).toEqual({ + type: 'xml', + data: { data: '' }, + }); + }); + + it('spreads xml options after data', () => { + expect(segments.xml('', { id: '12345' })).toEqual({ + type: 'xml', + data: { data: '', id: '12345' }, + }); + }); +}); + +describe('segments.poke', () => { + it('omits id when it is not provided', () => { + expect(segments.poke(1)).toEqual({ type: 'poke', data: { type: 1 } }); + }); + + it('includes a numeric id', () => { + expect(segments.poke(1, -1)).toEqual({ type: 'poke', data: { type: 1, id: -1 } }); + }); + + it('keeps string type and id', () => { + expect(segments.poke('1', '0')).toEqual({ type: 'poke', data: { type: '1', id: '0' } }); + }); + + it('includes an id of 0', () => { + expect(segments.poke(1, 0)).toEqual({ type: 'poke', data: { type: 1, id: 0 } }); + }); +}); + +describe('segments.forward', () => { + it('mirrors the id onto res_id and forward_id', () => { + expect(segments.forward('res-9')).toEqual({ + type: 'forward', + data: { id: 'res-9', res_id: 'res-9', forward_id: 'res-9' }, + }); + }); +}); + +describe('segments.node', () => { + it('stores user_id, nickname, and string content', () => { + expect(segments.node(10001, 'luma', 'hello')).toEqual({ + type: 'node', + data: { user_id: 10001, nickname: 'luma', content: 'hello' }, + }); + }); + + it('stores a single segment as content', () => { + expect(segments.node(10001, 'luma', { type: 'text', data: { text: 'hi' } })).toEqual({ + type: 'node', + data: { + user_id: 10001, + nickname: 'luma', + content: { type: 'text', data: { text: 'hi' } }, + }, + }); + }); + + it('stores a segment array as content', () => { + expect(segments.node(10001, 'luma', [{ type: 'text', data: { text: 'hi' } }])).toEqual({ + type: 'node', + data: { + user_id: 10001, + nickname: 'luma', + content: [{ type: 'text', data: { text: 'hi' } }], + }, + }); + }); +}); + +describe('segments.share', () => { + it('passes required share fields through', () => { + expect(segments.share({ url: 'https://example.com', title: 'Example' })).toEqual({ + type: 'share', + data: { url: 'https://example.com', title: 'Example' }, + }); + }); + + it('passes optional share fields through', () => { + expect( + segments.share({ + url: 'https://example.com', + title: 'Example', + content: 'desc', + image: 'https://example.com/a.png', + }), + ).toEqual({ + type: 'share', + data: { + url: 'https://example.com', + title: 'Example', + content: 'desc', + image: 'https://example.com/a.png', + }, + }); + }); +}); + +describe('segments.music', () => { + it('passes platform music id data through', () => { + expect(segments.music({ type: '163', id: '12345' })).toEqual({ + type: 'music', + data: { type: '163', id: '12345' }, + }); + }); + + it('passes custom music data through', () => { + expect( + segments.music({ + type: 'custom', + url: 'https://example.com/song', + audio: 'https://example.com/song.mp3', + title: 'Song', + image: 'https://example.com/cover.jpg', + content: 'Artist', + }), + ).toEqual({ + type: 'music', + data: { + type: 'custom', + url: 'https://example.com/song', + audio: 'https://example.com/song.mp3', + title: 'Song', + image: 'https://example.com/cover.jpg', + content: 'Artist', + }, + }); + }); +}); + +describe('segments.location', () => { + it('passes numeric coordinates and labels through', () => { + expect( + segments.location({ + lat: 39.9, + lon: 116.4, + title: 'Beijing', + content: 'Tiananmen', + }), + ).toEqual({ + type: 'location', + data: { + lat: 39.9, + lon: 116.4, + title: 'Beijing', + content: 'Tiananmen', + }, + }); + }); + + it('passes string coordinates through', () => { + expect(segments.location({ lat: '31.2', lon: '121.5' })).toEqual({ + type: 'location', + data: { lat: '31.2', lon: '121.5' }, + }); + }); +}); + +describe('segments.contact', () => { + it('builds a qq contact with a numeric id', () => { + expect(segments.contact('qq', 10001)).toEqual({ + type: 'contact', + data: { type: 'qq', id: 10001 }, + }); + }); + + it('builds a group contact with a string id', () => { + expect(segments.contact('group', '123456')).toEqual({ + type: 'contact', + data: { type: 'group', id: '123456' }, + }); + }); +}); + +describe('segments.raw', () => { + it('builds an arbitrary typed segment', () => { + expect(segments.raw('dice', { result: 6 })).toEqual({ + type: 'dice', + data: { result: 6 }, + }); + }); +}); diff --git a/packages/sdk/tests/websocket-utils.test.ts b/packages/sdk/tests/websocket-utils.test.ts new file mode 100644 index 00000000..42c3993d --- /dev/null +++ b/packages/sdk/tests/websocket-utils.test.ts @@ -0,0 +1,225 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + addSocketListener, + closeInfo, + normalizeReconnect, + rawToString, + unwrapEventPayload, + unwrapMessagePayload, + WEBSOCKET_CLOSED, + WEBSOCKET_OPEN, +} from '../src/client/websocket-utils'; +import type { WebSocketLike } from '../src/client/websocket-types'; + +function stubSocket(extra: Partial = {}): WebSocketLike { + return { + readyState: 0, + send() {}, + close() {}, + ...extra, + }; +} + +describe('websocket readyState constants', () => { + it('matches the standard WebSocket readyState values', () => { + expect(WEBSOCKET_OPEN).toBe(1); + expect(WEBSOCKET_CLOSED).toBe(3); + }); +}); + +describe('normalizeReconnect', () => { + it('treats a disabled or omitted value as no reconnect policy', () => { + expect(normalizeReconnect(false)).toBeNull(); + expect(normalizeReconnect(undefined)).toBeNull(); + }); + + it('turns a boolean enable flag into an empty options object', () => { + expect(normalizeReconnect(true)).toEqual({}); + }); + + it('returns the given reconnect options object unchanged', () => { + const options = { retries: 4, minDelayMs: 250, maxDelayMs: 8_000 }; + expect(normalizeReconnect(options)).toBe(options); + expect(normalizeReconnect({ retries: 0 })).toEqual({ retries: 0 }); + expect(normalizeReconnect({})).toEqual({}); + }); +}); + +describe('addSocketListener', () => { + it('binds and unbinds through addEventListener when present', () => { + const listener = vi.fn(); + const socket = stubSocket({ + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + on: vi.fn(), + }); + + const off = addSocketListener(socket, 'message', listener); + + expect(socket.addEventListener).toHaveBeenCalledTimes(1); + expect(socket.addEventListener).toHaveBeenCalledWith('message', listener); + expect(socket.on).not.toHaveBeenCalled(); + + off(); + expect(socket.removeEventListener).toHaveBeenCalledTimes(1); + expect(socket.removeEventListener).toHaveBeenCalledWith('message', listener); + }); + + it('does not throw on cleanup when removeEventListener is absent', () => { + const socket = stubSocket({ addEventListener: vi.fn() }); + const off = addSocketListener(socket, 'open', vi.fn()); + expect(off).not.toThrow(); + }); + + it('binds through on() and unbinds through off() when addEventListener is missing', () => { + const listener = vi.fn(); + const socket = stubSocket({ + on: vi.fn(), + off: vi.fn(), + removeListener: vi.fn(), + }); + + const off = addSocketListener(socket, 'close', listener); + + expect(socket.on).toHaveBeenCalledTimes(1); + expect(socket.on).toHaveBeenCalledWith('close', listener); + + off(); + expect(socket.off).toHaveBeenCalledTimes(1); + expect(socket.off).toHaveBeenCalledWith('close', listener); + expect(socket.removeListener).not.toHaveBeenCalled(); + }); + + it('falls back to removeListener when off() is absent', () => { + const listener = vi.fn(); + const socket = stubSocket({ + on: vi.fn(), + removeListener: vi.fn(), + }); + + const off = addSocketListener(socket, 'error', listener); + off(); + + expect(socket.removeListener).toHaveBeenCalledTimes(1); + expect(socket.removeListener).toHaveBeenCalledWith('error', listener); + }); + + it('cleanup is a no-op when on() has neither off nor removeListener', () => { + const socket = stubSocket({ on: vi.fn() }); + const off = addSocketListener(socket, 'message', vi.fn()); + expect(off).not.toThrow(); + }); + + it('returns a no-op cleanup when the socket has no listener APIs', () => { + const off = addSocketListener(stubSocket(), 'open', vi.fn()); + expect(off).not.toThrow(); + }); +}); + +describe('unwrapMessagePayload', () => { + it('returns the data field from a JSON object envelope', () => { + expect(unwrapMessagePayload({ data: '{"ok":true}' })).toBe('{"ok":true}'); + expect(unwrapMessagePayload({ data: { text: 'hi' } })).toEqual({ text: 'hi' }); + expect(unwrapMessagePayload({ data: 0 })).toBe(0); + expect(unwrapMessagePayload({ data: undefined })).toBeUndefined(); + }); + + it('returns the original value when it is not a data envelope', () => { + expect(unwrapMessagePayload('raw-text')).toBe('raw-text'); + expect(unwrapMessagePayload(null)).toBeNull(); + expect(unwrapMessagePayload([{ data: 1 }])).toEqual([{ data: 1 }]); + expect(unwrapMessagePayload({ type: 'message' })).toEqual({ type: 'message' }); + }); +}); + +describe('unwrapEventPayload', () => { + it('returns the error field from a JSON object envelope', () => { + expect(unwrapEventPayload({ error: 'socket failed' })).toBe('socket failed'); + expect(unwrapEventPayload({ error: { message: 'boom' } })).toEqual({ message: 'boom' }); + expect(unwrapEventPayload({ error: undefined })).toBeUndefined(); + }); + + it('returns the original value when it is not an error envelope', () => { + expect(unwrapEventPayload('plain-error')).toBe('plain-error'); + expect(unwrapEventPayload(null)).toBeNull(); + expect(unwrapEventPayload([{ error: 1 }])).toEqual([{ error: 1 }]); + expect(unwrapEventPayload({ type: 'error' })).toEqual({ type: 'error' }); + }); +}); + +describe('rawToString', () => { + it('returns strings unchanged', () => { + expect(rawToString('{"echo":1}')).toBe('{"echo":1}'); + expect(rawToString('')).toBe(''); + }); + + it('decodes ArrayBuffer and ArrayBufferView payloads as UTF-8', () => { + const bytes = Uint8Array.from([0x68, 0x69]); + expect(rawToString(bytes.buffer)).toBe('hi'); + expect(rawToString(bytes)).toBe('hi'); + expect(rawToString(Buffer.from([0x68, 0x69]))).toBe('hi'); + expect(rawToString(new DataView(bytes.buffer))).toBe('hi'); + expect(rawToString(Uint8Array.from([0x21, 0x68, 0x69, 0x21]).subarray(1, 3))).toBe('hi'); + expect(rawToString(new ArrayBuffer(0))).toBe(''); + }); + + it('rejects Blob payloads that cannot be read synchronously', () => { + expect(() => rawToString(new Blob(['hi']))).toThrow( + 'Blob WebSocket messages are not supported synchronously', + ); + }); + + it('uses toString() on objects and String() on primitives', () => { + expect(rawToString({ toString: () => 'from-toString' })).toBe('from-toString'); + expect(rawToString([1, 2])).toBe('1,2'); + expect(rawToString({ a: 1 })).toBe('[object Object]'); + expect(rawToString(42)).toBe('42'); + expect(rawToString(false)).toBe('false'); + expect(rawToString(null)).toBe('null'); + expect(rawToString(undefined)).toBe('undefined'); + }); +}); + +describe('closeInfo', () => { + it('reads code and reason from a CloseEvent-like object', () => { + expect(closeInfo([{ code: 1000, reason: 'normal', wasClean: true }])).toEqual({ + code: 1000, + reason: 'normal', + }); + expect(closeInfo([{ code: 1001 }])).toEqual({ + code: 1001, + reason: undefined, + }); + expect(closeInfo([{ reason: 'going away' }])).toEqual({ + code: undefined, + reason: 'going away', + }); + expect(closeInfo([{ code: '1000', reason: 1 }])).toEqual({ + code: undefined, + reason: undefined, + }); + }); + + it('reads positional Node-style close arguments', () => { + expect(closeInfo([1006, 'abnormal'])).toEqual({ + code: 1006, + reason: 'abnormal', + }); + expect(closeInfo([1000])).toEqual({ + code: 1000, + reason: undefined, + }); + expect(closeInfo(['1000', 1])).toEqual({ + code: undefined, + reason: undefined, + }); + expect(closeInfo([])).toEqual({ + code: undefined, + reason: undefined, + }); + expect(closeInfo([[1000, 'nested']])).toEqual({ + code: undefined, + reason: undefined, + }); + }); +}); diff --git a/packages/ui/package.json b/packages/ui/package.json index 7a3d9a76..d46ee238 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.14.7", + "version": "1.14.8", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index 93c66ae6..e5715175 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/websocket", - "version": "1.14.7", + "version": "1.14.8", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/websocket/tests/client.test.ts b/packages/websocket/tests/client.test.ts new file mode 100644 index 00000000..d74b014f --- /dev/null +++ b/packages/websocket/tests/client.test.ts @@ -0,0 +1,947 @@ +import crypto, { createHash } from 'node:crypto'; +import net from 'node:net'; +import type { AddressInfo, Socket } from 'node:net'; +import tls from 'node:tls'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { WebSocketClient } from '../src/client'; + +const ACCEPT_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; + +// Throwaway self-signed pair (openssl, CN=snowluma-test). Used only with +// rejectUnauthorized: false so expiry/SAN are irrelevant. +const TLS_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 TLS_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----- +`; + +const closers: Array<() => void | Promise> = []; + +afterEach(async () => { + vi.restoreAllMocks(); + const pending = closers.splice(0).reverse(); + for (const close of pending) await close(); +}); + +function acceptKey(key: string): string { + return createHash('sha1').update(key + ACCEPT_GUID).digest('base64'); +} + +function serverFrame(opcode: number, payload: Buffer): Buffer { + if (payload.length > 125) throw new Error('test frames must be <=125 bytes'); + return Buffer.concat([Buffer.from([0x80 | opcode, payload.length]), payload]); +} + +function tryDecodeClientFrame(buf: Buffer): { opcode: number; payload: Buffer; rest: Buffer } | null { + if (buf.length < 2) return null; + const opcode = buf[0]! & 0x0f; + const masked = (buf[1]! & 0x80) !== 0; + let length = buf[1]! & 0x7f; + let offset = 2; + if (length === 126) { + if (buf.length < 4) return null; + length = buf.readUInt16BE(2); + offset = 4; + } + const maskLen = masked ? 4 : 0; + if (buf.length < offset + maskLen + length) return null; + let mask: Buffer | undefined; + if (masked) { + mask = buf.subarray(offset, offset + 4); + offset += 4; + } + const payload = Buffer.from(buf.subarray(offset, offset + length)); + if (mask) { + for (let i = 0; i < payload.length; i++) payload[i]! ^= mask[i & 3]!; + } + return { opcode, payload, rest: buf.subarray(offset + length) }; +} + +function collectFrames(socket: Socket) { + let buf = Buffer.alloc(0); + socket.on('data', (chunk: Buffer) => { + buf = Buffer.concat([buf, chunk]); + }); + return { + async next(): Promise<{ opcode: number; payload: Buffer }> { + for (;;) { + const decoded = tryDecodeClientFrame(buf); + if (decoded) { + buf = decoded.rest; + return { opcode: decoded.opcode, payload: decoded.payload }; + } + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error('timeout waiting for frame')), 3000); + const onChunk = () => { + clearTimeout(timer); + socket.off('data', onChunk); + socket.off('error', onErr); + resolve(); + }; + const onErr = (err: Error) => { + clearTimeout(timer); + socket.off('data', onChunk); + reject(err); + }; + socket.on('data', onChunk); + socket.on('error', onErr); + if (tryDecodeClientFrame(buf)) onChunk(); + }); + } + }, + }; +} + +function handshakeResponse(key: string, extraHeaders: string[] = [], rest?: Buffer): Buffer { + const lines = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${acceptKey(key)}`, + ...extraHeaders, + '', + '', + ]; + const head = Buffer.from(lines.join('\r\n'), 'latin1'); + return rest && rest.length > 0 ? Buffer.concat([head, rest]) : head; +} + +type ParsedRequest = { + requestLine: string; + headers: Record; +}; + +function parseRequest(raw: string): ParsedRequest { + const lines = raw.split('\r\n'); + const headers: Record = Object.create(null); + for (const line of lines.slice(1)) { + const colon = line.indexOf(':'); + if (colon < 0) continue; + headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim(); + } + return { requestLine: lines[0] ?? '', headers }; +} + +function readRequest(socket: Socket): Promise { + return new Promise((resolve, reject) => { + let buf = Buffer.alloc(0); + const timer = setTimeout(() => reject(new Error('timeout waiting for handshake request')), 3000); + const onError = (err: Error) => { + clearTimeout(timer); + reject(err); + }; + const onData = (chunk: Buffer) => { + buf = Buffer.concat([buf, chunk]); + const idx = buf.indexOf('\r\n\r\n'); + if (idx < 0) return; + clearTimeout(timer); + socket.off('data', onData); + socket.off('error', onError); + resolve(parseRequest(buf.subarray(0, idx).toString('latin1'))); + }; + socket.on('data', onData); + socket.on('error', onError); + }); +} + +function track(client: WebSocketClient) { + const errors: Error[] = []; + const closes: Array<{ code: number; reason: string }> = []; + const messages: Array<{ data: Buffer; isBinary: boolean }> = []; + const pings: Buffer[] = []; + const pongs: Buffer[] = []; + let upgrade: { statusCode: number; statusMessage: string; headers: Record } | undefined; + let opened = false; + + client.on('error', (err) => errors.push(err)); + client.on('close', (code, reason) => closes.push({ code, reason })); + client.on('message', (data, isBinary) => messages.push({ data, isBinary })); + client.on('ping', (data) => pings.push(data)); + client.on('pong', (data) => pongs.push(data)); + client.on('upgrade', (parsed) => { + upgrade = parsed as { statusCode: number; statusMessage: string; headers: Record }; + }); + client.on('open', () => { + opened = true; + }); + + const wait = (label: string, ready: () => T | undefined, subscribe: (finish: (value: T) => void) => void): Promise => { + const existing = ready(); + if (existing !== undefined) return Promise.resolve(existing); + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`timeout waiting for ${label}`)), 3000); + subscribe((value) => { + clearTimeout(timer); + resolve(value); + }); + }); + }; + + return { + errors, + closes, + messages, + pings, + pongs, + get upgrade() { + return upgrade; + }, + waitOpen: () => new Promise((resolve, reject) => { + if (opened) return resolve(); + if (errors.length) return reject(errors[0]); + const timer = setTimeout(() => reject(new Error('timeout waiting for open')), 3000); + const onOpen = () => { + cleanup(); + resolve(); + }; + const onError = (err: Error) => { + cleanup(); + reject(err); + }; + const cleanup = () => { + clearTimeout(timer); + client.off('open', onOpen); + client.off('error', onError); + }; + client.once('open', onOpen); + client.once('error', onError); + }), + waitError: () => wait('error', () => errors[0], (finish) => { + client.once('error', (err) => finish(err)); + }), + waitClose: () => wait('close', () => closes[0], (finish) => { + client.once('close', (code, reason) => finish({ code, reason })); + }), + waitMessage: () => wait('message', () => messages[0], (finish) => { + client.once('message', (data, isBinary) => finish({ data, isBinary })); + }), + waitPing: () => wait('ping', () => pings[0], (finish) => { + client.once('ping', (data) => finish(data)); + }), + waitPong: () => wait('pong', () => pongs[0], (finish) => { + client.once('pong', (data) => finish(data)); + }), + }; +} + +async function listenPlain(): Promise<{ port: number; nextSocket: () => Promise }> { + const sockets = new Set(); + const queued: Socket[] = []; + const waiters: Array<(socket: Socket) => void> = []; + const server = net.createServer((socket) => { + sockets.add(socket); + const waiter = waiters.shift(); + if (waiter) waiter(socket); + else queued.push(socket); + }); + await new Promise((resolve, reject) => { + const onError = (err: Error) => reject(err); + server.once('error', onError); + server.listen(0, '127.0.0.1', () => { + server.off('error', onError); + resolve(); + }); + }); + const port = (server.address() as AddressInfo).port; + closers.push(() => { + for (const socket of sockets) socket.destroy(); + return new Promise((resolve, reject) => { + server.close((err) => (err ? reject(err) : resolve())); + }); + }); + return { + port, + nextSocket: () => { + const socket = queued.shift(); + if (socket) return Promise.resolve(socket); + return new Promise((resolve) => waiters.push(resolve)); + }, + }; +} + +async function listenTls(): Promise<{ port: number; nextSocket: () => Promise }> { + const sockets = new Set(); + const queued: tls.TLSSocket[] = []; + const waiters: Array<(socket: tls.TLSSocket) => void> = []; + const server = tls.createServer({ cert: TLS_CERT, key: TLS_KEY }, (socket) => { + sockets.add(socket); + const waiter = waiters.shift(); + if (waiter) waiter(socket); + else queued.push(socket); + }); + await new Promise((resolve, reject) => { + const onError = (err: Error) => reject(err); + server.once('error', onError); + server.listen(0, '127.0.0.1', () => { + server.off('error', onError); + resolve(); + }); + }); + const port = (server.address() as AddressInfo).port; + closers.push(() => { + for (const socket of sockets) socket.destroy(); + return new Promise((resolve, reject) => { + server.close((err) => (err ? reject(err) : resolve())); + }); + }); + return { + port, + nextSocket: () => { + const socket = queued.shift(); + if (socket) return Promise.resolve(socket); + return new Promise((resolve) => waiters.push(resolve)); + }, + }; +} + +function createClient( + address: string, + protocols?: string | string[] | ConstructorParameters[1], + options?: ConstructorParameters[2], +): WebSocketClient { + const client = new WebSocketClient(address, protocols, options); + client.on('error', () => {}); + closers.push(() => { + try { client.terminate(); } catch { /* already closed */ } + }); + return client; +} + +async function unusedPort(): Promise { + const server = net.createServer(); + await new Promise((resolve, reject) => { + const onError = (err: Error) => reject(err); + server.once('error', onError); + server.listen(0, '127.0.0.1', () => { + server.off('error', onError); + resolve(); + }); + }); + const port = (server.address() as AddressInfo).port; + await new Promise((resolve, reject) => { + server.close((err) => (err ? reject(err) : resolve())); + }); + return port; +} + +async function writeAndTick(socket: Socket, data: Buffer | string): Promise { + await new Promise((resolve, reject) => { + socket.write(data, (err) => (err ? reject(err) : resolve())); + }); + await new Promise((resolve) => setImmediate(resolve)); +} + +describe('WebSocketClient', () => { + it('exposes the standard ready-state constants', () => { + expect(WebSocketClient.CONNECTING).toBe(0); + expect(WebSocketClient.OPEN).toBe(1); + expect(WebSocketClient.CLOSING).toBe(2); + expect(WebSocketClient.CLOSED).toBe(3); + }); + + it('rejects non-ws URLs before connecting', () => { + expect(() => new WebSocketClient('http://127.0.0.1/')).toThrowError( + new Error('Only ws: and wss: URLs are supported'), + ); + expect(() => new WebSocketClient('https://127.0.0.1/')).toThrowError( + new Error('Only ws: and wss: URLs are supported'), + ); + expect(() => new WebSocketClient('foo')).toThrow(TypeError); + }); + + it('starts in CONNECTING', async () => { + const { port } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + expect(client.readyState).toBe(0); + expect(client.protocol).toBe(''); + expect(client.extensions).toBe(''); + }); + + it('sends RFC 6455 handshake fields, path, query, protocols, deflate offer, and extra headers', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient( + `ws://127.0.0.1:${port}/rooms/1?token=abc`, + ['chat', 'superchat'], + { + perMessageDeflate: true, + headers: { 'X-Token': 'secret', Authorization: 'Bearer t' }, + }, + ); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + + expect(req.requestLine).toBe('GET /rooms/1?token=abc HTTP/1.1'); + expect(req.headers.host).toBe(`127.0.0.1:${port}`); + expect(req.headers.upgrade).toBe('websocket'); + expect(req.headers.connection).toBe('Upgrade'); + expect(req.headers['sec-websocket-version']).toBe('13'); + expect(req.headers['sec-websocket-key']).toMatch(/^[A-Za-z0-9+/]{22}==$/); + expect(req.headers['sec-websocket-protocol']).toBe('chat, superchat'); + expect(req.headers['sec-websocket-extensions']).toBe( + 'permessage-deflate; client_no_context_takeover; server_no_context_takeover', + ); + expect(req.headers['x-token']).toBe('secret'); + expect(req.headers.authorization).toBe('Bearer t'); + expect(client.readyState).toBe(0); + expect(events.errors).toEqual([]); + }); + + it('treats a string protocol as a one-element list', async () => { + const { port, nextSocket } = await listenPlain(); + createClient(`ws://127.0.0.1:${port}`, 'chat'); + const req = await readRequest(await nextSocket()); + expect(req.headers['sec-websocket-protocol']).toBe('chat'); + }); + + it('omits Sec-WebSocket-Protocol when the list is empty', async () => { + const { port, nextSocket } = await listenPlain(); + createClient(`ws://127.0.0.1:${port}`, []); + const req = await readRequest(await nextSocket()); + expect(req.headers['sec-websocket-protocol']).toBeUndefined(); + }); + + it('treats a non-array object second argument as options, not protocols', async () => { + const { port, nextSocket } = await listenPlain(); + createClient(`ws://127.0.0.1:${port}`, { + headers: { 'X-From-Options': 'yes' }, + perMessageDeflate: false, + }); + const req = await readRequest(await nextSocket()); + expect(req.headers['sec-websocket-protocol']).toBeUndefined(); + expect(req.headers['sec-websocket-extensions']).toBeUndefined(); + expect(req.headers['x-from-options']).toBe('yes'); + }); + + it('offers only the requested permessage-deflate flags', async () => { + const { port, nextSocket } = await listenPlain(); + createClient(`ws://127.0.0.1:${port}`, { + perMessageDeflate: { clientNoContextTakeover: false }, + }); + const req = await readRequest(await nextSocket()); + expect(req.headers['sec-websocket-extensions']).toBe( + 'permessage-deflate; server_no_context_takeover', + ); + }); + + it('uses Host without a port when the URL port is the ws default', async () => { + const { port, nextSocket } = await listenPlain(); + createClient('ws://127.0.0.1:80/chat', { + socketOptions: { port, host: '127.0.0.1' }, + }); + const req = await readRequest(await nextSocket()); + expect(req.requestLine).toBe('GET /chat HTTP/1.1'); + expect(req.headers.host).toBe('127.0.0.1'); + }); + + it('emits upgrade+open, records protocol/extensions, and forwards leftover frames', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`, ['chat', 'superchat'], { + perMessageDeflate: true, + }); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + const rest = serverFrame(0x1, Buffer.from('hello')); + socket.write(handshakeResponse( + req.headers['sec-websocket-key']!, + [ + 'NoColonLine', + 'Sec-WebSocket-Protocol: superchat', + 'Sec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover; server_no_context_takeover', + ], + rest, + )); + + await events.waitOpen(); + const message = await events.waitMessage(); + expect(client.readyState).toBe(1); + expect(client.protocol).toBe('superchat'); + expect(client.extensions).toBe('permessage-deflate'); + expect(events.upgrade).toMatchObject({ + statusCode: 101, + statusMessage: 'Switching Protocols', + headers: { + upgrade: 'websocket', + connection: 'Upgrade', + 'sec-websocket-accept': acceptKey(req.headers['sec-websocket-key']!), + 'sec-websocket-protocol': 'superchat', + 'sec-websocket-extensions': + 'permessage-deflate; client_no_context_takeover; server_no_context_takeover', + }, + }); + expect(message.data).toEqual(Buffer.from('hello')); + expect(message.isBinary).toBe(false); + }); + + it('accepts a 101 that arrives in two TCP chunks and Upgrade/Connection variants', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + await writeAndTick(socket, 'HTTP/1.1 101\r\n'); + expect(client.readyState).toBe(0); + socket.write( + `Upgrade: WebSocket\r\nConnection: keep-alive, Upgrade\r\nSec-WebSocket-Accept: ${acceptKey(req.headers['sec-websocket-key']!)}\r\n\r\n`, + ); + await events.waitOpen(); + expect(client.readyState).toBe(1); + expect(events.upgrade?.statusMessage).toBe(''); + expect(events.upgrade?.headers.upgrade).toBe('WebSocket'); + expect(events.upgrade?.headers.connection).toBe('keep-alive, Upgrade'); + }); + + it('accepts the RFC 6455 example Sec-WebSocket-Accept', async () => { + vi.spyOn(crypto, 'randomBytes').mockImplementation(((size: number) => { + expect(size).toBe(16); + return Buffer.from('the sample nonce'); + }) as typeof crypto.randomBytes); + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + expect(req.headers['sec-websocket-key']).toBe('dGhlIHNhbXBsZSBub25jZQ=='); + socket.write([ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + 'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=', + '', + '', + ].join('\r\n')); + await events.waitOpen(); + expect(client.readyState).toBe(1); + }); + + it('keeps CONNECTING while the response is incomplete and aborts once it exceeds 16384 bytes', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const socket = await nextSocket(); + await writeAndTick(socket, Buffer.alloc(16384, 0x58)); + expect(client.readyState).toBe(0); + expect(events.errors).toEqual([]); + socket.write('Y'); + const err = await events.waitError(); + expect(err.message).toBe('WebSocket handshake failed: Handshake response too large'); + expect(await events.waitClose()).toEqual({ code: 1006, reason: '' }); + expect(client.readyState).toBe(3); + }); + + it.each([ + { + name: 'a non-HTTP status line', + respond: () => 'NOT-A-STATUS\r\n\r\n', + message: 'WebSocket handshake failed: Bad HTTP status line: NOT-A-STATUS', + }, + { + name: 'HTTP/1.0', + respond: () => 'HTTP/1.0 101 Switching Protocols\r\n\r\n', + message: 'WebSocket handshake failed: Bad HTTP status line: HTTP/1.0 101 Switching Protocols', + }, + { + name: 'an empty header block', + respond: () => '\r\n\r\n', + message: 'WebSocket handshake failed: Bad HTTP status line: ', + }, + { + name: 'a non-101 status', + respond: () => 'HTTP/1.1 400 Bad Request\r\n\r\n', + message: 'WebSocket handshake failed: Unexpected response status 400', + }, + { + name: 'a missing Upgrade header', + respond: (key: string) => + `HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptKey(key)}\r\n\r\n`, + message: 'WebSocket handshake failed: Missing/invalid Upgrade header', + }, + { + name: 'an Upgrade header that is not websocket', + respond: (key: string) => + `HTTP/1.1 101 Switching Protocols\r\nUpgrade: h2c\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptKey(key)}\r\n\r\n`, + message: 'WebSocket handshake failed: Missing/invalid Upgrade header', + }, + { + name: 'a Connection header without upgrade', + respond: (key: string) => + `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: keep-alive\r\nSec-WebSocket-Accept: ${acceptKey(key)}\r\n\r\n`, + message: 'WebSocket handshake failed: Missing Connection: Upgrade header', + }, + { + name: 'a missing Connection header', + respond: (key: string) => + `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nSec-WebSocket-Accept: ${acceptKey(key)}\r\n\r\n`, + message: 'WebSocket handshake failed: Missing Connection: Upgrade header', + }, + { + name: 'an invalid Sec-WebSocket-Accept', + respond: () => + 'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: AAAAAAAAAAAAAAAAAAAAAAAAAAA=\r\n\r\n', + message: 'WebSocket handshake failed: Invalid Sec-WebSocket-Accept', + }, + { + name: 'an unexpected extension when none were offered', + respond: (key: string) => + `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptKey(key)}\r\nSec-WebSocket-Extensions: permessage-deflate\r\n\r\n`, + message: 'WebSocket handshake failed: Unexpected Sec-WebSocket-Extensions', + }, + { + name: 'an unexpected subprotocol when none were requested', + respond: (key: string) => + `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptKey(key)}\r\nSec-WebSocket-Protocol: chat\r\n\r\n`, + message: 'WebSocket handshake failed: Unexpected Sec-WebSocket-Protocol', + }, + ])('aborts the handshake on $name', async ({ respond, message }) => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + socket.write(respond(req.headers['sec-websocket-key'] ?? '')); + const err = await events.waitError(); + expect(err.message).toBe(message); + expect(await events.waitClose()).toEqual({ code: 1006, reason: '' }); + expect(client.readyState).toBe(3); + }); + + it('aborts when the selected subprotocol is not in the offered list', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`, ['chat']); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + socket.write(handshakeResponse(req.headers['sec-websocket-key']!, [ + 'Sec-WebSocket-Protocol: other', + ])); + const err = await events.waitError(); + expect(err.message).toBe('WebSocket handshake failed: Unexpected Sec-WebSocket-Protocol'); + expect(client.readyState).toBe(3); + }); + + it('aborts when the server returns an unsupported permessage-deflate parameter', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`, { perMessageDeflate: true }); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + socket.write(handshakeResponse(req.headers['sec-websocket-key']!, [ + 'Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=10', + ])); + const err = await events.waitError(); + expect(err.message).toBe( + 'WebSocket handshake failed: Unsupported permessage-deflate parameter: server_max_window_bits', + ); + expect(client.readyState).toBe(3); + }); + + it('opens without extensions when deflate was offered but the server omitted them', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`, { perMessageDeflate: true }); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + socket.write(handshakeResponse(req.headers['sec-websocket-key']!)); + await events.waitOpen(); + expect(client.extensions).toBe(''); + expect(client.protocol).toBe(''); + }); + + it('forwards a binary leftover frame as isBinary=true', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + socket.write(handshakeResponse( + req.headers['sec-websocket-key']!, + [], + serverFrame(0x2, Buffer.from([0xde, 0xad])), + )); + await events.waitOpen(); + const message = await events.waitMessage(); + expect(message.data).toEqual(Buffer.from([0xde, 0xad])); + expect(message.isBinary).toBe(true); + }); + + it('queues send() until the socket is open, including options-as-callback', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const queued = new Promise((resolve) => { + client.send('queued', (err) => resolve(err)); + }); + client.send('bin', { binary: true }); + client.ping('too-early'); + client.pong('too-early'); + + const socket = await nextSocket(); + const req = await readRequest(socket); + const frames = collectFrames(socket); + socket.write(handshakeResponse(req.headers['sec-websocket-key']!)); + await events.waitOpen(); + expect(await queued).toBeFalsy(); + + const first = await frames.next(); + expect(first.opcode).toBe(0x1); + expect(first.payload).toEqual(Buffer.from('queued')); + const second = await frames.next(); + expect(second.opcode).toBe(0x2); + expect(second.payload).toEqual(Buffer.from('bin')); + }); + + it('delegates send/ping/pong/close after open and forwards control events', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + const frames = collectFrames(socket); + socket.write(handshakeResponse(req.headers['sec-websocket-key']!)); + await events.waitOpen(); + + const sent = new Promise((resolve) => { + client.send('after-open', (err) => resolve(err)); + }); + expect(await frames.next()).toEqual({ opcode: 0x1, payload: Buffer.from('after-open') }); + expect(await sent).toBeFalsy(); + + client.ping('hi'); + expect(await frames.next()).toEqual({ opcode: 0x9, payload: Buffer.from('hi') }); + + client.pong(Buffer.from('xy')); + expect(await frames.next()).toEqual({ opcode: 0xa, payload: Buffer.from('xy') }); + + socket.write(serverFrame(0x9, Buffer.from('srv-ping'))); + expect(await events.waitPing()).toEqual(Buffer.from('srv-ping')); + expect(await frames.next()).toEqual({ opcode: 0xa, payload: Buffer.from('srv-ping') }); + + socket.write(serverFrame(0xa, Buffer.from('srv-pong'))); + expect(await events.waitPong()).toEqual(Buffer.from('srv-pong')); + + client.close(1000, 'done'); + expect(client.readyState).toBe(2); + const close = await frames.next(); + expect(close.opcode).toBe(0x8); + expect(close.payload.readUInt16BE(0)).toBe(1000); + expect(close.payload.subarray(2).toString('utf8')).toBe('done'); + socket.destroy(); + expect(await events.waitClose()).toEqual({ code: 1006, reason: '' }); + }); + + it('forwards a peer close code and reason', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + socket.write(handshakeResponse(req.headers['sec-websocket-key']!)); + await events.waitOpen(); + + const reason = Buffer.from('bye'); + const payload = Buffer.alloc(2 + reason.length); + payload.writeUInt16BE(1001, 0); + reason.copy(payload, 2); + socket.write(serverFrame(0x8, payload)); + socket.end(); + expect(await events.waitClose()).toEqual({ code: 1001, reason: 'bye' }); + }); + + it('rejects invalid close codes before touching the socket', async () => { + const { port } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + expect(() => client.close(1005)).toThrowError(new RangeError('Invalid close code: 1005')); + expect(() => client.close(1006)).toThrowError(new RangeError('Invalid close code: 1006')); + expect(() => client.close(2500)).toThrowError(new RangeError('Invalid close code: 2500')); + expect(client.readyState).toBe(0); + }); + + it('destroys the TCP socket when close() is called before the handshake finishes', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const socket = await nextSocket(); + // The handshake request may already be sitting unread. A paused socket + // with buffered data does not emit 'close' after the peer destroy()s. + socket.resume(); + const socketClosed = new Promise((resolve) => socket.once('close', () => resolve())); + client.close(1000, 'ignored-before-open'); + await socketClosed; + expect(await events.waitClose()).toEqual({ code: 1006, reason: '' }); + expect(client.readyState).toBe(3); + }); + + it('destroys the TCP socket when terminate() is called before the handshake finishes', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const socket = await nextSocket(); + socket.resume(); + const socketClosed = new Promise((resolve) => socket.once('close', () => resolve())); + client.terminate(); + await socketClosed; + expect(await events.waitClose()).toEqual({ code: 1006, reason: '' }); + expect(client.readyState).toBe(3); + }); + + it('terminates an open connection without a close frame', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + socket.write(handshakeResponse(req.headers['sec-websocket-key']!)); + await events.waitOpen(); + client.terminate(); + expect(() => client.send('nope')).toThrowError(new Error('WebSocket is not open')); + expect(await events.waitClose()).toEqual({ code: 1006, reason: '' }); + }); + + it('forwards a socket error after the handshake', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + socket.write(handshakeResponse(req.headers['sec-websocket-key']!)); + await events.waitOpen(); + // destroy(err) emits only on this socket. RST the peer so the client + // sees a real TCP error (ECONNRESET) after the handshake listeners move. + socket.resetAndDestroy(); + const err = await events.waitError(); + expect(err).toBeInstanceOf(Error); + expect((err as NodeJS.ErrnoException).code).toBe('ECONNRESET'); + expect(await events.waitClose()).toEqual({ code: 1006, reason: '' }); + }); + + it('emits the TCP connect error and then a 1006 close', async () => { + const port = await unusedPort(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const err = await events.waitError(); + expect((err as NodeJS.ErrnoException).code).toBe('ECONNREFUSED'); + expect(await events.waitClose()).toEqual({ code: 1006, reason: '' }); + expect(client.readyState).toBe(3); + }); + + it('emits 1006 when the peer closes before the handshake', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`); + const events = track(client); + const socket = await nextSocket(); + socket.destroy(); + expect(await events.waitClose()).toEqual({ code: 1006, reason: '' }); + expect(client.readyState).toBe(3); + }); + + it('forwards maxPayload into the post-handshake socket', async () => { + const { port, nextSocket } = await listenPlain(); + const client = createClient(`ws://127.0.0.1:${port}`, { maxPayload: 4 }); + const events = track(client); + const socket = await nextSocket(); + const req = await readRequest(socket); + socket.write(handshakeResponse( + req.headers['sec-websocket-key']!, + [], + serverFrame(0x1, Buffer.from('12345')), + )); + const err = await events.waitError(); + expect(err.message).toBe('WebSocket protocol error: Payload exceeds configured max'); + expect((err as Error & { code?: number }).code).toBe(1009); + }); + + it('completes a wss handshake and auto-sets SNI from a non-IP hostname', async () => { + const { port, nextSocket } = await listenTls(); + const client = createClient('wss://sni.example.test:443/secure', { + socketOptions: { + host: '127.0.0.1', + port, + rejectUnauthorized: false, + }, + }); + const events = track(client); + const socket = await nextSocket(); + expect(socket.servername).toBe('sni.example.test'); + const req = await readRequest(socket); + expect(req.requestLine).toBe('GET /secure HTTP/1.1'); + expect(req.headers.host).toBe('sni.example.test'); + socket.write(handshakeResponse(req.headers['sec-websocket-key']!)); + await events.waitOpen(); + expect(client.readyState).toBe(1); + }); + + it('does not overwrite an explicit TLS servername', async () => { + const { port, nextSocket } = await listenTls(); + createClient('wss://sni.example.test:443/', { + socketOptions: { + host: '127.0.0.1', + port, + rejectUnauthorized: false, + servername: 'explicit.example', + }, + }); + const socket = await nextSocket(); + expect(socket.servername).toBe('explicit.example'); + }); + + it('does not invent SNI for an IPv4 wss URL and includes a non-default port in Host', async () => { + const { port, nextSocket } = await listenTls(); + const client = createClient(`wss://127.0.0.1:${port}/`, { + socketOptions: { rejectUnauthorized: false }, + }); + const events = track(client); + const socket = await nextSocket(); + expect(socket.servername || '').toBe(''); + const req = await readRequest(socket); + expect(req.headers.host).toBe(`127.0.0.1:${port}`); + socket.write(handshakeResponse(req.headers['sec-websocket-key']!)); + await events.waitOpen(); + expect(client.readyState).toBe(1); + }); +}); diff --git a/packages/websocket/tests/extensions-more.test.ts b/packages/websocket/tests/extensions-more.test.ts new file mode 100644 index 00000000..f8bc9d15 --- /dev/null +++ b/packages/websocket/tests/extensions-more.test.ts @@ -0,0 +1,378 @@ +import zlib from 'node:zlib'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { + acceptPerMessageDeflate, + chooseSubprotocol, + compressRaw, + decompressRaw, + normalizeProtocolList, + offerPerMessageDeflate, + parseAcceptedPerMessageDeflate, + parseHeader, +} from '../src/extensions'; + +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +function deflateRawFlushed(data: Buffer): Buffer { + return zlib.deflateRawSync(data, { flush: zlib.constants.Z_SYNC_FLUSH }); +} + +function inflateRawError(data: Buffer): Error & { code?: string } { + try { + zlib.inflateRawSync(Buffer.concat([data, TRAILER]), { + finishFlush: zlib.constants.Z_SYNC_FLUSH, + }); + } catch (err) { + return err as Error & { code?: string }; + } + throw new Error('expected inflateRawSync to fail'); +} + +describe('parseHeader', () => { + it('returns no offers for missing or blank headers', () => { + expect(parseHeader(undefined)).toEqual([]); + expect(parseHeader(null)).toEqual([]); + expect(parseHeader('')).toEqual([]); + expect(parseHeader(' ')).toEqual([]); + expect(parseHeader(', ,')).toEqual([]); + }); + + it('lowercases names and flag parameters, and keeps unquoted values', () => { + expect(parseHeader('PerMessage-Deflate; Client_No_Context_Takeover; Server_Max_Window_Bits=10')).toEqual([ + { + name: 'permessage-deflate', + params: { + client_no_context_takeover: true, + server_max_window_bits: '10', + }, + }, + ]); + }); + + it('strips matching double or single quotes around parameter values', () => { + expect(parseHeader(`mux; token="a b"; flag='x'`)).toEqual([ + { name: 'mux', params: { token: 'a b', flag: 'x' } }, + ]); + }); + + it('leaves unmatched quotes and empty quoted values as parsed', () => { + expect(parseHeader(`ext; a="bare; b='bare; c=""; d=''`)).toEqual([ + { + name: 'ext', + params: { + a: '"bare', + b: "'bare", + c: '', + d: '', + }, + }, + ]); + }); + + it('splits multiple offers and ignores empty tokens', () => { + expect(parseHeader(' mux , permessage-deflate; client_no_context_takeover, ')).toEqual([ + { name: 'mux', params: {} }, + { name: 'permessage-deflate', params: { client_no_context_takeover: true } }, + ]); + }); +}); + +describe('acceptPerMessageDeflate', () => { + it('returns null when deflate is disabled or the client did not offer it', () => { + expect(acceptPerMessageDeflate('permessage-deflate', undefined)).toBeNull(); + expect(acceptPerMessageDeflate('permessage-deflate', false)).toBeNull(); + expect(acceptPerMessageDeflate('permessage-deflate', null)).toBeNull(); + expect(acceptPerMessageDeflate(undefined, true)).toBeNull(); + expect(acceptPerMessageDeflate('mux', true)).toBeNull(); + }); + + it('accepts a boolean enable with both no-context-takeover parameters', () => { + expect(acceptPerMessageDeflate('permessage-deflate', true)).toEqual({ + header: 'permessage-deflate; server_no_context_takeover; client_no_context_takeover', + options: { + enabled: true, + requestNoContextTakeover: true, + responseNoContextTakeover: true, + threshold: 1024, + }, + }); + }); + + it('treats a non-object enable value like true', () => { + expect(acceptPerMessageDeflate('PerMessage-Deflate', 1)).toEqual({ + header: 'permessage-deflate; server_no_context_takeover; client_no_context_takeover', + options: { + enabled: true, + requestNoContextTakeover: true, + responseNoContextTakeover: true, + threshold: 1024, + }, + }); + }); + + it('omits takeover parameters that are disabled and not requested', () => { + expect(acceptPerMessageDeflate('permessage-deflate', { + clientNoContextTakeover: false, + serverNoContextTakeover: false, + threshold: 0, + })).toEqual({ + header: 'permessage-deflate', + options: { + enabled: true, + requestNoContextTakeover: false, + responseNoContextTakeover: false, + threshold: 0, + }, + }); + }); + + it('still echoes a takeover parameter the client offered when the config disables it', () => { + expect(acceptPerMessageDeflate( + 'mux, permessage-deflate; server_no_context_takeover; client_no_context_takeover', + { clientNoContextTakeover: false, serverNoContextTakeover: false, threshold: 8 }, + )).toEqual({ + header: 'permessage-deflate; server_no_context_takeover; client_no_context_takeover', + options: { + enabled: true, + requestNoContextTakeover: true, + responseNoContextTakeover: true, + threshold: 8, + }, + }); + }); + + it('defaults object options to both takeover flags', () => { + expect(acceptPerMessageDeflate('permessage-deflate', {})).toEqual({ + header: 'permessage-deflate; server_no_context_takeover; client_no_context_takeover', + options: { + enabled: true, + requestNoContextTakeover: true, + responseNoContextTakeover: true, + threshold: 1024, + }, + }); + }); +}); + +describe('offerPerMessageDeflate', () => { + it('returns null when deflate is disabled', () => { + expect(offerPerMessageDeflate(undefined)).toBeNull(); + expect(offerPerMessageDeflate(false)).toBeNull(); + expect(offerPerMessageDeflate(null)).toBeNull(); + }); + + it('offers both takeover flags for true or a non-object enable value', () => { + expect(offerPerMessageDeflate(true)).toBe( + 'permessage-deflate; client_no_context_takeover; server_no_context_takeover', + ); + expect(offerPerMessageDeflate('yes')).toBe( + 'permessage-deflate; client_no_context_takeover; server_no_context_takeover', + ); + }); + + it('offers only the takeover flags that are not disabled', () => { + expect(offerPerMessageDeflate({ clientNoContextTakeover: false })).toBe( + 'permessage-deflate; server_no_context_takeover', + ); + expect(offerPerMessageDeflate({ serverNoContextTakeover: false })).toBe( + 'permessage-deflate; client_no_context_takeover', + ); + expect(offerPerMessageDeflate({ + clientNoContextTakeover: false, + serverNoContextTakeover: false, + })).toBe('permessage-deflate'); + }); + + it('keeps default takeover flags when the object only sets threshold', () => { + expect(offerPerMessageDeflate({ threshold: 8 })).toBe( + 'permessage-deflate; client_no_context_takeover; server_no_context_takeover', + ); + }); +}); + +describe('parseAcceptedPerMessageDeflate', () => { + it('returns null when deflate was not requested or not accepted', () => { + expect(parseAcceptedPerMessageDeflate('permessage-deflate', undefined)).toBeNull(); + expect(parseAcceptedPerMessageDeflate('permessage-deflate', false)).toBeNull(); + expect(parseAcceptedPerMessageDeflate('permessage-deflate', null)).toBeNull(); + expect(parseAcceptedPerMessageDeflate(undefined, true)).toBeNull(); + expect(parseAcceptedPerMessageDeflate('mux', true)).toBeNull(); + }); + + it('maps server/client takeover parameters onto the opposite request/response flags', () => { + expect(parseAcceptedPerMessageDeflate( + 'permessage-deflate; server_no_context_takeover; client_no_context_takeover', + true, + )).toEqual({ + enabled: true, + requestNoContextTakeover: true, + responseNoContextTakeover: true, + threshold: 1024, + }); + }); + + it('treats missing takeover parameters as false and uses the requested threshold', () => { + expect(parseAcceptedPerMessageDeflate('mux, permessage-deflate', { threshold: 4096 })).toEqual({ + enabled: true, + requestNoContextTakeover: false, + responseNoContextTakeover: false, + threshold: 4096, + }); + }); + + it('treats an empty parameter value as absent and a non-empty string as present', () => { + expect(parseAcceptedPerMessageDeflate( + 'permessage-deflate; client_no_context_takeover=; server_no_context_takeover=0', + {}, + )).toEqual({ + enabled: true, + requestNoContextTakeover: true, + responseNoContextTakeover: false, + threshold: 1024, + }); + }); + + it('rejects unsupported permessage-deflate parameters', () => { + expect(() => parseAcceptedPerMessageDeflate( + 'permessage-deflate; server_max_window_bits=10', + true, + )).toThrowError(new Error('Unsupported permessage-deflate parameter: server_max_window_bits')); + expect(() => parseAcceptedPerMessageDeflate( + 'permessage-deflate; client_no_context_takeover; client_max_window_bits=12', + true, + )).toThrowError(new Error('Unsupported permessage-deflate parameter: client_max_window_bits')); + }); +}); + +describe('compressRaw / decompressRaw', () => { + it('strips the zlib sync-flush trailer when deflateRawSync emits one', () => { + const source = Buffer.from('hello hello hello'); + const flushed = deflateRawFlushed(source); + const compressed = compressRaw(source); + if (flushed.length >= 4 && flushed.subarray(flushed.length - 4).equals(TRAILER)) { + expect(compressed).toEqual(flushed.subarray(0, flushed.length - 4)); + } else { + expect(compressed).toEqual(flushed); + } + }); + + it('returns raw bytes when the deflate output has no sync-flush trailer', () => { + const raw = Buffer.from([0x03, 0x00]); + vi.spyOn(zlib, 'deflateRawSync').mockReturnValueOnce(raw); + expect(compressRaw(Buffer.from('x'))).toEqual(Buffer.from([0x03, 0x00])); + }); + + it('returns raw bytes when the deflate output is shorter than the trailer', () => { + vi.spyOn(zlib, 'deflateRawSync').mockReturnValueOnce(Buffer.from([0xaa])); + expect(compressRaw(Buffer.alloc(0))).toEqual(Buffer.from([0xaa])); + }); + + it('inflates independently stripped deflate bytes without a maxPayload cap', () => { + const source = Buffer.from('roundtrip payload'); + expect(decompressRaw(compressRaw(source))).toEqual(source); + }); + + it('accepts an empty inflate when maxPayload is 0', () => { + expect(decompressRaw(compressRaw(Buffer.alloc(0)), 0)).toEqual(Buffer.alloc(0)); + }); + + it('rejects a one-byte inflate when maxPayload is 0 after zlib succeeds', () => { + const source = Buffer.from([0x61]); + const stripped = compressRaw(source); + expect(zlib.inflateRawSync(Buffer.concat([stripped, TRAILER]), { + finishFlush: zlib.constants.Z_SYNC_FLUSH, + maxOutputLength: 1, + })).toEqual(source); + + let thrown: unknown; + try { + decompressRaw(stripped, 0); + } catch (error) { + thrown = error; + } + + expect(thrown).toMatchObject({ + code: 1009, + message: 'Message too large after inflate (maxPayload=0)', + }); + expect((thrown as Error).cause).toBeUndefined(); + }); + + it('rethrows a zlib failure that is not ERR_BUFFER_TOO_LARGE', () => { + const garbage = Buffer.from([0x03, 0x01, 0x02, 0xff]); + const cause = inflateRawError(garbage); + let thrown: unknown; + try { + decompressRaw(garbage, 64); + } catch (error) { + thrown = error; + } + expect(thrown).toBeInstanceOf(Error); + expect(thrown).toMatchObject({ + message: cause.message, + code: cause.code, + }); + expect(thrown).not.toMatchObject({ code: 1009 }); + }); +}); + +describe('normalizeProtocolList', () => { + it('returns an empty list for missing or empty inputs', () => { + expect(normalizeProtocolList(undefined)).toEqual([]); + expect(normalizeProtocolList(null)).toEqual([]); + expect(normalizeProtocolList('')).toEqual([]); + expect(normalizeProtocolList([])).toEqual([]); + expect(normalizeProtocolList(new Set())).toEqual([]); + }); + + it('splits a comma-separated string and drops blank tokens', () => { + expect(normalizeProtocolList(' chat , , superchat ')).toEqual(['chat', 'superchat']); + }); + + it('stringifies array entries, trims them, and drops blanks', () => { + expect(normalizeProtocolList(['chat', ' superchat ', '', ' '])).toEqual(['chat', 'superchat']); + }); + + it('stringifies Set entries, trims them, and drops blanks', () => { + expect(normalizeProtocolList(new Set(['chat', ' superchat ', '']))).toEqual([ + 'chat', + 'superchat', + ]); + }); +}); + +describe('chooseSubprotocol', () => { + it('returns the first supported protocol that the client requested', () => { + expect(chooseSubprotocol('chat, superchat', ['superchat', 'chat'])).toBe('superchat'); + expect(chooseSubprotocol('chat, superchat', 'chat, extra')).toBe('chat'); + expect(chooseSubprotocol('chat, superchat', new Set(['other', 'superchat']))).toBe('superchat'); + }); + + it('returns null when either side has no protocols or there is no overlap', () => { + expect(chooseSubprotocol(undefined, ['chat'])).toBeNull(); + expect(chooseSubprotocol(' , ', ['chat'])).toBeNull(); + expect(chooseSubprotocol('chat', undefined)).toBeNull(); + expect(chooseSubprotocol('chat', [])).toBeNull(); + expect(chooseSubprotocol('chat', ['superchat'])).toBeNull(); + }); + + it('uses a selector function only when the result is in the requested list', () => { + let seen: string[] | undefined; + expect(chooseSubprotocol(' chat , superchat ', (requested) => { + seen = requested; + return 'superchat'; + })).toBe('superchat'); + expect(seen).toEqual(['chat', 'superchat']); + + expect(chooseSubprotocol('chat', () => 'other')).toBeNull(); + expect(chooseSubprotocol('chat', () => null)).toBeNull(); + expect(chooseSubprotocol('chat', () => undefined)).toBeNull(); + expect(chooseSubprotocol('chat', () => '')).toBeNull(); + expect(chooseSubprotocol('', () => 'chat')).toBeNull(); + }); +}); diff --git a/packages/websocket/tests/native.test.ts b/packages/websocket/tests/native.test.ts new file mode 100644 index 00000000..646d7966 --- /dev/null +++ b/packages/websocket/tests/native.test.ts @@ -0,0 +1,505 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import native, { type NativeAddon, type ParserOptions } from '../src/native'; + +const { existsSyncMock } = vi.hoisted(() => ({ + existsSyncMock: vi.fn<(target: string) => boolean>(), +})); + +const fsHooks = vi.hoisted(() => ({ + realExistsSync: (_target: string): boolean => false, +})); + +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal(); + fsHooks.realExistsSync = (target) => actual.existsSync(target); + existsSyncMock.mockImplementation((target) => actual.existsSync(target)); + return { + ...actual, + existsSync: (target: Parameters[0]) => + existsSyncMock(String(target)), + }; +}); + +const ORIGINAL_DEV_NO_NATIVE = process.env.SNOWLUMA_DEV_NO_NATIVE; +const ORIGINAL_CWD = process.cwd(); +const NATIVE_SRC_DIR = path.dirname(fileURLToPath(new URL('../src/native.ts', import.meta.url))); +const BINARY_NAME = `websocket-${process.platform}-${process.arch}.node`; +const tmpDirs: string[] = []; + +const RFC_KEY = 'dGhlIHNhbXBsZSBub25jZQ=='; +const RFC_ACCEPT = 's3pPLMBiTxaQ9kYGzzhZRbK+xOo='; +const RFC_UNMASKED_HELLO = Buffer.from([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]); +const RFC_MASKED_HELLO = Buffer.from([ + 0x81, 0x85, 0x37, 0xfa, 0x21, 0x3d, 0x7f, 0x9f, 0x4d, 0x51, 0x58, +]); +const RFC_MASK = Buffer.from([0x37, 0xfa, 0x21, 0x3d]); +const HELLO = Buffer.from([0x48, 0x65, 0x6c, 0x6c, 0x6f]); + +const STUB_USE_SUFFIX = + 'Set SNOWLUMA_DEV_NO_NATIVE=0 (or unset) and provide the prebuilt binary to enable WebSocket I/O.'; + +let nativeIo = false; +try { + nativeIo = native.computeAcceptKey(RFC_KEY) === RFC_ACCEPT; +} catch (err) { + nativeIo = !String((err as Error).message).includes('native addon is stubbed'); +} + +function expectedSearchDirs(cwd = process.cwd()): string[] { + return [ + path.resolve(NATIVE_SRC_DIR, 'native'), + path.resolve(NATIVE_SRC_DIR, '..', 'native'), + path.resolve(NATIVE_SRC_DIR, '..', '..', 'runtime', 'native'), + path.resolve(cwd, 'native'), + path.resolve(cwd, 'dist', 'native'), + path.resolve(cwd, 'packages', 'runtime', 'native'), + ]; +} + +function candidatePaths(cwd = process.cwd()): string[] { + return expectedSearchDirs(cwd).map((dir) => path.join(dir, BINARY_NAME)); +} + +function notFoundMessage(cwd = process.cwd()): string { + return `[snowluma/websocket] native addon not found: ${BINARY_NAME}. Searched: ${expectedSearchDirs(cwd).join(', ')}`; +} + +function stubWarnMessage(reason: string): string { + return `[snowluma/websocket] WARNING: using stub addon (${reason}). WebSocket features are disabled.`; +} + +function stubUseMessage(reason: string): string { + return `[snowluma/websocket] native addon is stubbed (${reason}). ${STUB_USE_SUFFIX}`; +} + +function restoreExistsSync(): void { + existsSyncMock.mockReset(); + existsSyncMock.mockImplementation((target) => fsHooks.realExistsSync(target)); +} + +function restoreDevNoNative(): void { + if (ORIGINAL_DEV_NO_NATIVE === undefined) delete process.env.SNOWLUMA_DEV_NO_NATIVE; + else process.env.SNOWLUMA_DEV_NO_NATIVE = ORIGINAL_DEV_NO_NATIVE; +} + +async function loadNative(): Promise { + return (await import('../src/native')).default; +} + +function installFakeAddon(exports: NativeAddon): string[] { + const opened: string[] = []; + vi.spyOn(process, 'dlopen').mockImplementation((module, filename) => { + opened.push(filename); + module.exports = exports; + }); + return opened; +} + +function fakeAddon(acceptKey: string): NativeAddon { + return { + Parser: class { + push() { + return { frames: [] }; + } + } as unknown as NativeAddon['Parser'], + buildFrame: () => Buffer.from([0x81, 0x00]), + computeAcceptKey: () => acceptKey, + }; +} + +function makeTmpDir(): string { + const dir = mkdtempSync(path.join(os.tmpdir(), 'sl-ws-native-')); + tmpDirs.push(dir); + return dir; +} + +function cleanupLoaderTest(): void { + process.chdir(ORIGINAL_CWD); + restoreDevNoNative(); + restoreExistsSync(); + vi.restoreAllMocks(); + vi.resetModules(); + for (const dir of tmpDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +} + +describe.skipIf(!nativeIo)('computeAcceptKey', () => { + it('returns the RFC 6455 §1.3 Sec-WebSocket-Accept value', () => { + expect(native.computeAcceptKey(RFC_KEY)).toBe(RFC_ACCEPT); + }); + + it('rejects a non-string key', () => { + expect(() => native.computeAcceptKey(1 as unknown as string)).toThrow('expected string'); + }); +}); + +describe.skipIf(!nativeIo)('buildFrame', () => { + it('emits the RFC 6455 §5.7 unmasked Hello text frame', () => { + expect(native.buildFrame(0x1, true, HELLO, null, 0)).toEqual(RFC_UNMASKED_HELLO); + }); + + it('emits the RFC 6455 §5.7 masked Hello text frame', () => { + expect(native.buildFrame(0x1, true, HELLO, RFC_MASK, 0)).toEqual(RFC_MASKED_HELLO); + }); + + it('encodes a 16-bit length for a 126-byte payload', () => { + const payload = Buffer.alloc(126, 0x55); + expect(native.buildFrame(0x2, true, payload, null, 0)).toEqual( + Buffer.concat([Buffer.from([0x82, 0x7e, 0x00, 0x7e]), payload]), + ); + }); + + it('encodes a 64-bit length for a 65536-byte payload', () => { + const payload = Buffer.alloc(65536, 0x62); + expect(native.buildFrame(0x2, true, payload, null, 0)).toEqual( + Buffer.concat([ + Buffer.from([0x82, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]), + payload, + ]), + ); + }); + + it('masks a 16-bit-length payload with the 4-byte key', () => { + const payload = Buffer.alloc(126, 0x55); + const mask = Buffer.from([0x01, 0x02, 0x03, 0x04]); + const body = Buffer.from(payload); + for (let i = 0; i < body.length; i++) body[i]! ^= mask[i & 3]!; + expect(native.buildFrame(0x2, true, payload, mask, 0)).toEqual( + Buffer.concat([Buffer.from([0x82, 0xfe, 0x00, 0x7e, 0x01, 0x02, 0x03, 0x04]), body]), + ); + }); + + it('writes FIN, RSV, and opcode into the first header byte', () => { + expect(native.buildFrame(0x1, false, Buffer.from([0x48, 0x65, 0x6c]), null, 0)).toEqual( + Buffer.from([0x01, 0x03, 0x48, 0x65, 0x6c]), + ); + expect(native.buildFrame(0x1, true, Buffer.alloc(0), null, 0x40)).toEqual(Buffer.from([0xc1, 0x00])); + expect(native.buildFrame(0x11, true, Buffer.alloc(0), null, 0x41)).toEqual(Buffer.from([0xc1, 0x00])); + expect(native.buildFrame(0x8, true, Buffer.from([0x03, 0xe8]), null, 0)).toEqual( + Buffer.from([0x88, 0x02, 0x03, 0xe8]), + ); + expect(native.buildFrame(0x9, true, Buffer.alloc(0), null, 0)).toEqual(Buffer.from([0x89, 0x00])); + }); + + it('rejects a mask key that is not 4 bytes', () => { + expect(() => native.buildFrame(0x1, true, HELLO, Buffer.from([0x00, 0x01, 0x02]), 0)).toThrow( + 'mask key must be 4 bytes', + ); + }); + + it('rejects a call that is missing the required arguments', () => { + expect(() => + (native.buildFrame as unknown as (opcode: number) => Buffer)(0x1), + ).toThrow('bad args'); + }); +}); + +describe.skipIf(!nativeIo)('Parser', () => { + it('parses the RFC 6455 unmasked Hello frame as a client', () => { + const parser = new native.Parser({ isServer: false, maxPayload: 1024, allowedRsv: 0 }); + expect(parser.push(RFC_UNMASKED_HELLO)).toEqual({ + frames: [{ fin: true, rsv: 0, opcode: 0x1, payload: HELLO }], + }); + }); + + it('unmasks the RFC 6455 masked Hello frame as a server', () => { + const parser = new native.Parser({ isServer: true, maxPayload: 1024, allowedRsv: 0 }); + expect(parser.push(RFC_MASKED_HELLO)).toEqual({ + frames: [{ fin: true, rsv: 0, opcode: 0x1, payload: HELLO }], + }); + }); + + it('returns no frames until a split header and payload are complete', () => { + const parser = new native.Parser({ isServer: false, maxPayload: 1024, allowedRsv: 0 }); + expect(parser.push(Buffer.from([0x81]))).toEqual({ frames: [] }); + expect(parser.push(Buffer.from([0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]))).toEqual({ + frames: [{ fin: true, rsv: 0, opcode: 0x1, payload: HELLO }], + }); + }); + + it('parses two frames from one chunk', () => { + const parser = new native.Parser({ isServer: false, maxPayload: 1024, allowedRsv: 0 }); + expect(parser.push(Buffer.concat([ + RFC_UNMASKED_HELLO, + Buffer.from([0x89, 0x00]), + ]))).toEqual({ + frames: [ + { fin: true, rsv: 0, opcode: 0x1, payload: HELLO }, + { fin: true, rsv: 0, opcode: 0x9, payload: Buffer.alloc(0) }, + ], + }); + }); + + it('parses 16-bit and 64-bit unmasked payloads', () => { + const mid = Buffer.alloc(126, 0x41); + const large = Buffer.alloc(65536, 0x42); + const midParser = new native.Parser({ isServer: false, maxPayload: 200, allowedRsv: 0 }); + expect(midParser.push(Buffer.concat([Buffer.from([0x82, 0x7e, 0x00, 0x7e]), mid]))).toEqual({ + frames: [{ fin: true, rsv: 0, opcode: 0x2, payload: mid }], + }); + const largeParser = new native.Parser({ isServer: false, maxPayload: 70_000, allowedRsv: 0 }); + expect(largeParser.push(Buffer.concat([ + Buffer.from([0x82, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]), + large, + ]))).toEqual({ + frames: [{ fin: true, rsv: 0, opcode: 0x2, payload: large }], + }); + }); + + it('exposes allowed RSV1 and defaults to a masking server', () => { + const deflate = new native.Parser({ isServer: false, maxPayload: 1024, allowedRsv: 0x40 }); + expect(deflate.push(Buffer.from([0xc1, 0x00]))).toEqual({ + frames: [{ fin: true, rsv: 0x40, opcode: 0x1, payload: Buffer.alloc(0) }], + }); + + const defaults = new native.Parser({} as ParserOptions); + expect(defaults.push(RFC_UNMASKED_HELLO)).toEqual({ + error: true, + code: 1002, + message: 'Expected masked frame from client', + }); + }); + + it('reports protocol errors with the native close code and message', () => { + const client: ParserOptions = { isServer: false, maxPayload: 1, allowedRsv: 0 }; + expect(new native.Parser(client).push(Buffer.from([0xc1, 0x00]))).toEqual({ + error: true, + code: 1002, + message: 'Unexpected RSV bits', + }); + expect(new native.Parser(client).push(Buffer.from([0x83, 0x00]))).toEqual({ + error: true, + code: 1002, + message: 'Unknown opcode', + }); + expect(new native.Parser(client).push(Buffer.from([0x09, 0x00]))).toEqual({ + error: true, + code: 1002, + message: 'Fragmented control frame', + }); + expect(new native.Parser(client).push(Buffer.from([0x89, 0x7e, 0x00, 0x7e]))).toEqual({ + error: true, + code: 1002, + message: 'Control frame too large', + }); + expect(new native.Parser(client).push(Buffer.from([0x81, 0x80]))).toEqual({ + error: true, + code: 1002, + message: 'Server must not mask frames', + }); + expect(new native.Parser(client).push(Buffer.from([0x82, 0x7e, 0x00, 0x05]))).toEqual({ + error: true, + code: 1002, + message: 'Non-minimal 16-bit length', + }); + expect(new native.Parser(client).push(Buffer.from([ + 0x82, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, + ]))).toEqual({ + error: true, + code: 1002, + message: 'Non-minimal 64-bit length', + }); + expect(new native.Parser(client).push(Buffer.from([ + 0x82, 0x7f, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ]))).toEqual({ + error: true, + code: 1002, + message: 'Payload length top bit set', + }); + expect(new native.Parser(client).push(Buffer.from([0x82, 0x02]))).toEqual({ + error: true, + code: 1009, + message: 'Payload exceeds configured max', + }); + + expect(new native.Parser({ isServer: true, maxPayload: 1024, allowedRsv: 0 }).push( + Buffer.from([0x81, 0x00]), + )).toEqual({ + error: true, + code: 1002, + message: 'Expected masked frame from client', + }); + + expect(new native.Parser({ isServer: false, maxPayload: 1024, allowedRsv: 0x40 }).push( + Buffer.from([0xc9, 0x00]), + )).toEqual({ + error: true, + code: 1002, + message: 'Control frame RSV bits must be zero', + }); + }); + + it('treats a negative maxPayload as zero and masks allowedRsv to RSV bits', () => { + const zeroCap = new native.Parser({ isServer: false, maxPayload: -1, allowedRsv: 0 }); + expect(zeroCap.push(Buffer.from([0x81, 0x00]))).toEqual({ + frames: [{ fin: true, rsv: 0, opcode: 0x1, payload: Buffer.alloc(0) }], + }); + expect(zeroCap.push(Buffer.from([0x81, 0x01, 0x61]))).toEqual({ + error: true, + code: 1009, + message: 'Payload exceeds configured max', + }); + + const rsvMasked = new native.Parser({ isServer: false, maxPayload: 1024, allowedRsv: 0x41 }); + expect(rsvMasked.push(Buffer.from([0xc1, 0x00]))).toEqual({ + frames: [{ fin: true, rsv: 0x40, opcode: 0x1, payload: Buffer.alloc(0) }], + }); + }); + + it('rejects a non-Buffer push argument', () => { + const parser = new native.Parser({ isServer: false, maxPayload: 1024, allowedRsv: 0 }); + expect(() => parser.push('hello' as unknown as Buffer)).toThrow('expected Buffer'); + }); +}); + +describe('addon path resolution', () => { + beforeEach(() => { + delete process.env.SNOWLUMA_DEV_NO_NATIVE; + restoreExistsSync(); + vi.resetModules(); + }); + + afterEach(cleanupLoaderTest); + + it('dlopens the first existing websocket--.node candidate', async () => { + const opened = installFakeAddon(fakeAddon('from-first-hit')); + const winner = candidatePaths()[2]!; + const probed: string[] = []; + existsSyncMock.mockImplementation((target) => { + probed.push(target); + return target === winner; + }); + + const addon = await loadNative(); + expect(probed).toEqual(candidatePaths().slice(0, 3)); + expect(opened).toEqual([winner]); + expect(addon.computeAcceptKey(RFC_KEY)).toBe('from-first-hit'); + }); + + it('prefers the flattened /native layout over later candidates', async () => { + const opened = installFakeAddon(fakeAddon('flattened')); + const winner = candidatePaths()[0]!; + existsSyncMock.mockImplementation((target) => target === winner); + + await loadNative(); + expect(opened).toEqual([winner]); + expect(existsSyncMock.mock.calls.map(([target]) => target)).toEqual([winner]); + }); + + it('falls back to process.cwd()/native when module-relative binaries are absent', async () => { + process.chdir(makeTmpDir()); + // Node may report /private/var/folders/... after chdir while mkdtemp + // returned /var/folders/...; searchDirs() uses process.cwd(). + const cwd = process.cwd(); + const opened = installFakeAddon(fakeAddon('cwd-native')); + const winner = path.join(cwd, 'native', BINARY_NAME); + existsSyncMock.mockImplementation((target) => target === winner); + + const addon = await loadNative(); + expect(opened).toEqual([winner]); + expect(addon.computeAcceptKey(RFC_KEY)).toBe('cwd-native'); + }); + + it('throws the searched-path error when no candidate exists', async () => { + process.chdir(makeTmpDir()); + const cwd = process.cwd(); + const probed: string[] = []; + existsSyncMock.mockImplementation((target) => { + probed.push(target); + return false; + }); + + let thrown: unknown; + try { + await loadNative(); + } catch (err) { + thrown = err; + } + + expect(probed).toEqual(candidatePaths(cwd)); + expect(thrown).toBeInstanceOf(Error); + expect((thrown as Error).message).toBe(notFoundMessage(cwd)); + }); + + it('does not stub a successful load when SNOWLUMA_DEV_NO_NATIVE=1', async () => { + process.env.SNOWLUMA_DEV_NO_NATIVE = '1'; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + existsSyncMock.mockImplementation((target) => target === candidatePaths()[0]); + installFakeAddon(fakeAddon('still-live')); + + const addon = await loadNative(); + expect(warn).not.toHaveBeenCalled(); + expect(addon.computeAcceptKey(RFC_KEY)).toBe('still-live'); + expect(addon.buildFrame(0x1, true, Buffer.alloc(0), null, 0)).toEqual(Buffer.from([0x81, 0x00])); + }); +}); + +describe('SNOWLUMA_DEV_NO_NATIVE stub', () => { + beforeEach(() => { + delete process.env.SNOWLUMA_DEV_NO_NATIVE; + restoreExistsSync(); + vi.resetModules(); + }); + + afterEach(cleanupLoaderTest); + + it('stubs after a missing binary when the env var is exactly 1', async () => { + process.env.SNOWLUMA_DEV_NO_NATIVE = '1'; + existsSyncMock.mockReturnValue(false); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + const addon = await loadNative(); + const reason = notFoundMessage(); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith(stubWarnMessage(reason)); + + const parser = new addon.Parser({ isServer: true, maxPayload: 1, allowedRsv: 0 }); + expect(() => parser.push(Buffer.alloc(0))).toThrow(stubUseMessage(reason)); + expect(() => addon.buildFrame(0x1, true, Buffer.alloc(0), null, 0)).toThrow(stubUseMessage(reason)); + expect(() => addon.computeAcceptKey(RFC_KEY)).toThrow(stubUseMessage(reason)); + }); + + it('stubs after process.dlopen fails when the env var is exactly 1', async () => { + process.env.SNOWLUMA_DEV_NO_NATIVE = '1'; + existsSyncMock.mockReturnValue(true); + vi.spyOn(process, 'dlopen').mockImplementation(() => { + throw new Error('not a valid Node addon'); + }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + const addon = await loadNative(); + expect(warn).toHaveBeenCalledWith(stubWarnMessage('not a valid Node addon')); + expect(() => addon.computeAcceptKey(RFC_KEY)).toThrow(stubUseMessage('not a valid Node addon')); + }); + + it('rethrows a missing-binary error when the env var is not 1', async () => { + existsSyncMock.mockReturnValue(false); + for (const value of [undefined, '', '0', 'true', '2'] as const) { + vi.resetModules(); + if (value === undefined) delete process.env.SNOWLUMA_DEV_NO_NATIVE; + else process.env.SNOWLUMA_DEV_NO_NATIVE = value; + + let thrown: unknown; + try { + await loadNative(); + } catch (err) { + thrown = err; + } + expect(thrown).toBeInstanceOf(Error); + expect((thrown as Error).message).toBe(notFoundMessage()); + } + }); + + it('rethrows a dlopen failure when the env var is unset', async () => { + existsSyncMock.mockReturnValue(true); + vi.spyOn(process, 'dlopen').mockImplementation(() => { + throw new Error('not a valid Node addon'); + }); + + await expect(loadNative()).rejects.toThrow('not a valid Node addon'); + }); +}); diff --git a/packages/websocket/tests/server.test.ts b/packages/websocket/tests/server.test.ts new file mode 100644 index 00000000..785f9596 --- /dev/null +++ b/packages/websocket/tests/server.test.ts @@ -0,0 +1,1108 @@ +import { EventEmitter } from 'node:events'; +import http from 'node:http'; +import https from 'node:https'; +import type { IncomingMessage } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import type { Duplex } from 'node:stream'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { WebSocketServer } from '../src/server'; + +// RFC 6455 §1.3 example. +const RFC_KEY = 'dGhlIHNhbXBsZSBub25jZQ=='; +const RFC_SWITCHING = + 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + 'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n' + + '\r\n'; + +const METHOD_NOT_ALLOWED = + 'HTTP/1.1 405 Method Not Allowed\r\n' + + 'Connection: close\r\n' + + 'Content-Length: 18\r\n' + + 'Content-Type: text/plain\r\n' + + '\r\n' + + 'Method not allowed'; + +const BAD_UPGRADE_HEADER = + 'HTTP/1.1 400 Bad Request\r\n' + + 'Connection: close\r\n' + + 'Content-Length: 32\r\n' + + 'Content-Type: text/plain\r\n' + + '\r\n' + + 'Upgrade header must be websocket'; + +const BAD_CONNECTION_HEADER = + 'HTTP/1.1 400 Bad Request\r\n' + + 'Connection: close\r\n' + + 'Content-Length: 40\r\n' + + 'Content-Type: text/plain\r\n' + + '\r\n' + + 'Connection header must contain "upgrade"'; + +const BAD_KEY = + 'HTTP/1.1 400 Bad Request\r\n' + + 'Connection: close\r\n' + + 'Content-Length: 25\r\n' + + 'Content-Type: text/plain\r\n' + + '\r\n' + + 'Invalid Sec-WebSocket-Key'; + +const VERSION_REQUIRED = + 'HTTP/1.1 426 Upgrade Required\r\n' + + 'Sec-WebSocket-Version: 13\r\n' + + 'Connection: close\r\n' + + '\r\n'; + +const UNAUTHORIZED = + 'HTTP/1.1 401 Unauthorized\r\n' + + 'Connection: close\r\n' + + 'Content-Length: 12\r\n' + + 'Content-Type: text/plain\r\n' + + '\r\n' + + 'Unauthorized'; + +const BAD_PATH = + 'HTTP/1.1 400 Bad Request\r\n' + + 'Connection: close\r\n' + + 'Content-Length: 22\r\n' + + 'Content-Type: text/plain\r\n' + + '\r\n' + + 'Bad path for WebSocket'; + +const SHUTDOWN_CLOSE_FRAME = Buffer.from([ + 0x88, 0x16, 0x03, 0xe9, + 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, + 0x73, 0x68, 0x75, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x20, + 0x64, 0x6f, 0x77, 0x6e, +]); + +class MockSocket extends EventEmitter { + readonly writes: Buffer[] = []; + destroyed = false; + ended = false; + timeout: number | undefined; + noDelay: boolean | undefined; + encrypted: boolean | undefined; + private readonly failWrite: boolean; + private readonly failDestroy: boolean; + + constructor(opts?: { encrypted?: boolean; throwOnWrite?: boolean; throwOnDestroy?: boolean }) { + super(); + this.encrypted = opts?.encrypted; + this.failWrite = opts?.throwOnWrite === true; + this.failDestroy = opts?.throwOnDestroy === true; + } + + write(data: string | Buffer): boolean { + if (this.failWrite) throw new Error('write failed'); + this.writes.push(typeof data === 'string' ? Buffer.from(data) : Buffer.from(data)); + return true; + } + + get text(): string { + return Buffer.concat(this.writes).toString('utf8'); + } + + setTimeout(ms: number): this { + this.timeout = ms; + return this; + } + + setNoDelay(value: boolean): this { + this.noDelay = value; + return this; + } + + end(data?: string | Buffer): this { + if (data !== undefined) this.write(data); + this.ended = true; + this.emit('end'); + this.destroy(); + return this; + } + + destroy(): this { + if (this.failDestroy) throw new Error('destroy failed'); + this.destroyed = true; + this.emit('close'); + return this; + } +} + +function asSocket(socket: MockSocket): Duplex { + return socket as unknown as Duplex; +} + +function upgradeRequest(overrides: { + method?: string; + url?: string; + headers?: Record; +} = {}): IncomingMessage { + return { + method: overrides.method ?? 'GET', + url: 'url' in overrides ? overrides.url : '/', + headers: { + upgrade: 'websocket', + connection: 'Upgrade', + 'sec-websocket-version': '13', + 'sec-websocket-key': RFC_KEY, + ...overrides.headers, + }, + } as IncomingMessage; +} + +function listen(server: http.Server): Promise { + return new Promise((resolve, reject) => { + const onError = (err: Error) => { + server.off('listening', onListening); + reject(err); + }; + const onListening = () => { + server.off('error', onError); + resolve((server.address() as AddressInfo).port); + }; + server.once('error', onError); + server.listen(0, '127.0.0.1', onListening); + }); +} + +function waitListening(wss: WebSocketServer): Promise { + return new Promise((resolve, reject) => { + const onError = (err: Error) => { + wss.off('listening', onListening); + reject(err); + }; + const onListening = () => { + wss.off('error', onError); + resolve(); + }; + wss.once('listening', onListening); + wss.once('error', onError); + }); +} + +function closeWss(wss: WebSocketServer): Promise { + return new Promise((resolve) => { + wss.close(() => resolve()); + }); +} + +function closeHttp(server: http.Server): Promise { + return new Promise((resolve) => { + server.close(() => resolve()); + }); +} + +function stubListenServer(address = { address: '127.0.0.1', family: 'IPv4', port: 8443 }) { + const stub = { + listen: vi.fn((..._args: unknown[]) => stub), + on: vi.fn(), + close: (cb?: (err?: Error) => void) => { + cb?.(); + }, + address: () => address, + }; + return stub; +} + +const ownedServers: WebSocketServer[] = []; +const httpServers: http.Server[] = []; + +afterEach(async () => { + const pendingWss = ownedServers.splice(0); + const pendingHttp = httpServers.splice(0); + await Promise.all(pendingWss.map((wss) => closeWss(wss))); + await Promise.all(pendingHttp.map((server) => closeHttp(server))); + vi.restoreAllMocks(); +}); + +describe('WebSocketServer constructor', () => { + it('throws when neither port, server, nor noServer is provided', () => { + expect(() => new WebSocketServer()).toThrowError( + 'WebSocketServer requires { port } or { server } or { noServer: true }', + ); + expect(() => new WebSocketServer({})).toThrowError( + 'WebSocketServer requires { port } or { server } or { noServer: true }', + ); + }); + + it('stores options and skips listening in noServer mode', () => { + const verifyClient = () => true; + const wss = new WebSocketServer({ + noServer: true, + path: '/ws', + maxPayload: 4096, + verifyClient, + protocols: ['chat'], + perMessageDeflate: true, + backlog: 128, + host: '127.0.0.1', + port: 9, + }); + ownedServers.push(wss); + + expect(wss.options).toEqual({ + port: 9, + host: '127.0.0.1', + server: undefined, + noServer: true, + path: '/ws', + maxPayload: 4096, + verifyClient, + protocols: ['chat'], + perMessageDeflate: true, + backlog: 128, + tls: undefined, + }); + expect(wss.clients).toEqual(new Set()); + expect(wss.address()).toBeNull(); + }); + + it('does not attach to a provided server when noServer is set', () => { + const server = http.createServer(); + httpServers.push(server); + const wss = new WebSocketServer({ noServer: true, server }); + ownedServers.push(wss); + expect(server.listenerCount('upgrade')).toBe(0); + }); + + it('copies listed TLS keys into options.tls and ignores non-TLS fields', () => { + const wss = new WebSocketServer({ + noServer: true, + cert: 'CERT', + key: 'KEY', + rejectUnauthorized: false, + ca: undefined, + host: '127.0.0.1', + } as never); + ownedServers.push(wss); + expect(wss.options.tls).toEqual({ + cert: 'CERT', + key: 'KEY', + rejectUnauthorized: false, + }); + }); + + it('lets a tls object overwrite top-level TLS keys', () => { + const wss = new WebSocketServer({ + noServer: true, + cert: 'TOP', + key: 'TOPKEY', + tls: { cert: 'NESTED', passphrase: 'p' }, + }); + ownedServers.push(wss); + expect(wss.options.tls).toEqual({ + cert: 'NESTED', + key: 'TOPKEY', + passphrase: 'p', + }); + }); + + it('leaves options.tls unset when no TLS material is present', () => { + const wss = new WebSocketServer({ noServer: true, tls: {} }); + ownedServers.push(wss); + expect(wss.options.tls).toBeUndefined(); + }); + + it('attaches an upgrade listener to an existing server', () => { + const server = http.createServer(); + httpServers.push(server); + const wss = new WebSocketServer({ server, path: '/ws' }); + ownedServers.push(wss); + expect(wss.options.server).toBe(server); + expect(server.listenerCount('upgrade')).toBe(1); + expect(wss.address()).toBeNull(); + }); + + it('listens on a standalone port, emits listening, and answers plain HTTP with 426', async () => { + const wss = new WebSocketServer({ port: 0, host: '127.0.0.1' }); + ownedServers.push(wss); + await waitListening(wss); + + const addr = wss.address() as AddressInfo; + expect(addr.address).toBe('127.0.0.1'); + expect(addr.port).toBeGreaterThan(0); + + const res = await fetch(`http://127.0.0.1:${addr.port}/`); + expect(res.status).toBe(426); + expect(res.headers.get('content-type')).toBe('text/plain'); + expect(res.headers.get('content-length')).toBe('16'); + expect(await res.text()).toBe('Upgrade Required'); + }); + + it('creates an HTTPS server when tls options are present', () => { + const stub = stubListenServer(); + const spy = vi.spyOn(https, 'createServer').mockReturnValue(stub as never); + const wss = new WebSocketServer({ + port: 8443, + host: '127.0.0.1', + backlog: 511, + tls: { cert: 'CERT', key: 'KEY' }, + }); + ownedServers.push(wss); + + expect(spy).toHaveBeenCalledTimes(1); + expect(spy.mock.calls[0]![0]).toEqual({ cert: 'CERT', key: 'KEY' }); + expect(stub.listen).toHaveBeenCalledWith(8443, '127.0.0.1', 511, expect.any(Function)); + expect(wss.address()).toEqual({ address: '127.0.0.1', family: 'IPv4', port: 8443 }); + }); + + it('creates an HTTPS server from top-level cert and key', () => { + const stub = stubListenServer(); + const spy = vi.spyOn(https, 'createServer').mockReturnValue(stub as never); + const wss = new WebSocketServer({ + port: 8443, + host: '127.0.0.1', + cert: 'CERT', + key: 'KEY', + } as never); + ownedServers.push(wss); + + expect(spy.mock.calls[0]![0]).toEqual({ cert: 'CERT', key: 'KEY' }); + }); + + it('forwards a listen error from the owned HTTP server', async () => { + const blocker = http.createServer(); + httpServers.push(blocker); + const port = await listen(blocker); + const wss = new WebSocketServer({ port, host: '127.0.0.1' }); + ownedServers.push(wss); + + const err = await new Promise((resolve) => { + wss.once('error', resolve); + }); + expect((err as NodeJS.ErrnoException).code).toBe('EADDRINUSE'); + }); +}); + +describe('WebSocketServer.address', () => { + it('returns the listening address of an attached external server', async () => { + const server = http.createServer(); + httpServers.push(server); + const port = await listen(server); + const wss = new WebSocketServer({ server }); + ownedServers.push(wss); + + const addr = wss.address() as AddressInfo; + expect(addr.address).toBe('127.0.0.1'); + expect(addr.port).toBe(port); + }); + + it('returns null when an external server has no address method', () => { + const server = { + on() {}, + removeListener() {}, + }; + const wss = new WebSocketServer({ server: server as never }); + ownedServers.push(wss); + expect(wss.address()).toBeNull(); + }); +}); + +describe('WebSocketServer.handleUpgrade', () => { + it('rejects a non-GET method with 405', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + const socket = new MockSocket(); + let accepted = false; + wss.handleUpgrade(upgradeRequest({ method: 'POST' }), asSocket(socket), Buffer.alloc(0), () => { + accepted = true; + }); + expect(accepted).toBe(false); + expect(socket.text).toBe(METHOD_NOT_ALLOWED); + expect(socket.destroyed).toBe(true); + }); + + it('rejects a missing or non-websocket Upgrade header with 400', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + + const missing = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { upgrade: undefined } }), + asSocket(missing), + Buffer.alloc(0), + () => {}, + ); + expect(missing.text).toBe(BAD_UPGRADE_HEADER); + expect(missing.destroyed).toBe(true); + + const httpUpgrade = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { upgrade: 'h2c' } }), + asSocket(httpUpgrade), + Buffer.alloc(0), + () => {}, + ); + expect(httpUpgrade.text).toBe(BAD_UPGRADE_HEADER); + }); + + it('rejects a Connection header that does not contain upgrade', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { connection: 'keep-alive' } }), + asSocket(socket), + Buffer.alloc(0), + () => {}, + ); + expect(socket.text).toBe(BAD_CONNECTION_HEADER); + expect(socket.destroyed).toBe(true); + }); + + it('rejects a Sec-WebSocket-Version other than 13 with 426', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + + const old = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { 'sec-websocket-version': '8' } }), + asSocket(old), + Buffer.alloc(0), + () => {}, + ); + expect(old.text).toBe(VERSION_REQUIRED); + expect(old.destroyed).toBe(true); + + const missing = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { 'sec-websocket-version': undefined } }), + asSocket(missing), + Buffer.alloc(0), + () => {}, + ); + expect(missing.text).toBe(VERSION_REQUIRED); + }); + + it('rejects a missing, non-string, or malformed Sec-WebSocket-Key', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + + const cases: Array = [ + undefined, + ['dGhlIHNhbXBsZSBub25jZQ=='], + 'short==', + 'AAAAAAAAAAAAAAAAAAAAA==', + 'AAAAAAAAAAAAAAAAAAAAAA', + '**********************==', + ]; + for (const key of cases) { + const socket = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { 'sec-websocket-key': key } }), + asSocket(socket), + Buffer.alloc(0), + () => {}, + ); + expect(socket.text).toBe(BAD_KEY); + expect(socket.destroyed).toBe(true); + } + }); + + it('swallows write and destroy errors while aborting', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + const socket = new MockSocket({ throwOnWrite: true, throwOnDestroy: true }); + expect(() => { + wss.handleUpgrade(upgradeRequest({ method: 'PUT' }), asSocket(socket), Buffer.alloc(0), () => {}); + }).not.toThrow(); + }); + + it('swallows write and destroy errors on the 426 version path', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + const socket = new MockSocket({ throwOnWrite: true, throwOnDestroy: true }); + expect(() => { + wss.handleUpgrade( + upgradeRequest({ headers: { 'sec-websocket-version': '7' } }), + asSocket(socket), + Buffer.alloc(0), + () => {}, + ); + }).not.toThrow(); + }); + + it('accepts a RFC 6455 handshake and tracks the client', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + const socket = new MockSocket(); + const req = upgradeRequest({ headers: { upgrade: 'WebSocket' } }); + let acceptedReq: IncomingMessage | undefined; + wss.handleUpgrade(req, asSocket(socket), Buffer.alloc(0), (ws, request) => { + acceptedReq = request; + expect(ws.readyState).toBe(1); + expect(ws.protocol).toBe(''); + expect(ws.extensions).toBe(''); + expect(wss.clients.has(ws)).toBe(true); + ws.terminate(); + }); + + expect(acceptedReq).toBe(req); + expect(socket.text).toBe(RFC_SWITCHING); + expect(socket.timeout).toBe(0); + expect(socket.noDelay).toBe(true); + expect(wss.clients.size).toBe(0); + }); + + it('joins an array Connection header before testing for upgrade', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { connection: ['Keep-Alive', 'Upgrade'] } }), + asSocket(socket), + Buffer.alloc(0), + (ws) => ws.terminate(), + ); + expect(socket.text).toBe(RFC_SWITCHING); + }); + + it('accepts Connection: keep-alive, Upgrade', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { connection: 'keep-alive, Upgrade' } }), + asSocket(socket), + Buffer.alloc(0), + (ws) => ws.terminate(), + ); + expect(socket.text).toBe(RFC_SWITCHING); + }); + + it('skips setTimeout and setNoDelay when the socket does not implement them', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + const socket = new MockSocket(); + (socket as { setTimeout?: unknown }).setTimeout = undefined; + (socket as { setNoDelay?: unknown }).setNoDelay = undefined; + wss.handleUpgrade(upgradeRequest(), asSocket(socket), Buffer.alloc(0), (ws) => ws.terminate()); + expect(socket.text).toBe(RFC_SWITCHING); + }); + + it('selects the first server protocol that the client offered', () => { + const wss = new WebSocketServer({ noServer: true, protocols: ['chat.v2', 'chat.v1'] }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { 'sec-websocket-protocol': 'chat.v1, chat.v2' } }), + asSocket(socket), + Buffer.alloc(0), + (ws) => { + expect(ws.protocol).toBe('chat.v2'); + ws.terminate(); + }, + ); + expect(socket.text).toBe( + 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + 'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n' + + 'Sec-WebSocket-Protocol: chat.v2\r\n' + + '\r\n', + ); + }); + + it('accepts a comma-separated protocols string and a Set', () => { + const asString = new WebSocketServer({ noServer: true, protocols: 'chat' }); + ownedServers.push(asString); + const stringSocket = new MockSocket(); + asString.handleUpgrade( + upgradeRequest({ headers: { 'sec-websocket-protocol': 'chat' } }), + asSocket(stringSocket), + Buffer.alloc(0), + (ws) => { + expect(ws.protocol).toBe('chat'); + ws.terminate(); + }, + ); + expect(stringSocket.text).toContain('Sec-WebSocket-Protocol: chat\r\n'); + + const asSet = new WebSocketServer({ noServer: true, protocols: new Set(['superchat', 'chat']) }); + ownedServers.push(asSet); + const setSocket = new MockSocket(); + asSet.handleUpgrade( + upgradeRequest({ headers: { 'sec-websocket-protocol': 'chat, superchat' } }), + asSocket(setSocket), + Buffer.alloc(0), + (ws) => { + expect(ws.protocol).toBe('superchat'); + ws.terminate(); + }, + ); + expect(setSocket.text).toContain('Sec-WebSocket-Protocol: superchat\r\n'); + }); + + it('uses a protocol selector only when the result was requested', () => { + const requestedSeen: string[][] = []; + const wss = new WebSocketServer({ + noServer: true, + protocols: (requested) => { + requestedSeen.push(requested); + return 'chat'; + }, + }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { 'sec-websocket-protocol': 'chat, extra' } }), + asSocket(socket), + Buffer.alloc(0), + (ws) => { + expect(ws.protocol).toBe('chat'); + ws.terminate(); + }, + ); + expect(requestedSeen).toEqual([['chat', 'extra']]); + expect(socket.text).toContain('Sec-WebSocket-Protocol: chat\r\n'); + }); + + it('omits Sec-WebSocket-Protocol when the selector result was not offered', () => { + const wss = new WebSocketServer({ + noServer: true, + protocols: () => 'other', + }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { 'sec-websocket-protocol': 'chat' } }), + asSocket(socket), + Buffer.alloc(0), + (ws) => { + expect(ws.protocol).toBe(''); + ws.terminate(); + }, + ); + expect(socket.text).toBe(RFC_SWITCHING); + }); + + it('omits Sec-WebSocket-Protocol when nothing overlaps', () => { + const wss = new WebSocketServer({ noServer: true, protocols: ['json'] }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { 'sec-websocket-protocol': 'chat' } }), + asSocket(socket), + Buffer.alloc(0), + (ws) => { + expect(ws.protocol).toBe(''); + ws.terminate(); + }, + ); + expect(socket.text).toBe(RFC_SWITCHING); + }); + + it('negotiates permessage-deflate when offered and enabled', () => { + const wss = new WebSocketServer({ noServer: true, perMessageDeflate: true }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { 'sec-websocket-extensions': 'permessage-deflate' } }), + asSocket(socket), + Buffer.alloc(0), + (ws) => { + expect(ws.extensions).toBe('permessage-deflate'); + ws.terminate(); + }, + ); + expect(socket.text).toBe( + 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + 'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n' + + 'Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n' + + '\r\n', + ); + }); + + it('does not advertise permessage-deflate when disabled or not offered', () => { + const disabled = new WebSocketServer({ noServer: true, perMessageDeflate: false }); + ownedServers.push(disabled); + const disabledSocket = new MockSocket(); + disabled.handleUpgrade( + upgradeRequest({ headers: { 'sec-websocket-extensions': 'permessage-deflate' } }), + asSocket(disabledSocket), + Buffer.alloc(0), + (ws) => { + expect(ws.extensions).toBe(''); + ws.terminate(); + }, + ); + expect(disabledSocket.text).toBe(RFC_SWITCHING); + + const noOffer = new WebSocketServer({ noServer: true, perMessageDeflate: true }); + ownedServers.push(noOffer); + const noOfferSocket = new MockSocket(); + noOffer.handleUpgrade(upgradeRequest(), asSocket(noOfferSocket), Buffer.alloc(0), (ws) => { + expect(ws.extensions).toBe(''); + ws.terminate(); + }); + expect(noOfferSocket.text).toBe(RFC_SWITCHING); + }); + + it('honors permessage-deflate takeover flags from the config object', () => { + const wss = new WebSocketServer({ + noServer: true, + perMessageDeflate: { clientNoContextTakeover: false, serverNoContextTakeover: false }, + }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ headers: { 'sec-websocket-extensions': 'permessage-deflate' } }), + asSocket(socket), + Buffer.alloc(0), + (ws) => ws.terminate(), + ); + expect(socket.text).toBe( + 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + 'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n' + + 'Sec-WebSocket-Extensions: permessage-deflate\r\n' + + '\r\n', + ); + }); + + it('writes extensions before protocol when both are selected', () => { + const wss = new WebSocketServer({ + noServer: true, + protocols: ['chat'], + perMessageDeflate: true, + }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade( + upgradeRequest({ + headers: { + 'sec-websocket-protocol': 'chat', + 'sec-websocket-extensions': 'permessage-deflate', + }, + }), + asSocket(socket), + Buffer.alloc(0), + (ws) => { + expect(ws.protocol).toBe('chat'); + expect(ws.extensions).toBe('permessage-deflate'); + ws.terminate(); + }, + ); + expect(socket.text).toBe( + 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + 'Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n' + + 'Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n' + + 'Sec-WebSocket-Protocol: chat\r\n' + + '\r\n', + ); + }); + + it('destroys the socket and skips the callback when the 101 write fails', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + const socket = new MockSocket({ throwOnWrite: true }); + let accepted = false; + wss.handleUpgrade(upgradeRequest(), asSocket(socket), Buffer.alloc(0), () => { + accepted = true; + }); + expect(accepted).toBe(false); + expect(wss.clients.size).toBe(0); + expect(socket.destroyed).toBe(true); + }); + + it('feeds leftover handshake bytes into the new socket', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + const socket = new MockSocket(); + const ping = Buffer.from([0x89, 0x80, 0x00, 0x00, 0x00, 0x00]); + wss.handleUpgrade(upgradeRequest(), asSocket(socket), ping, (ws) => ws.terminate()); + expect(socket.writes[0]!.toString('utf8')).toBe(RFC_SWITCHING); + expect(socket.writes[1]!.equals(Buffer.from([0x8a, 0x00]))).toBe(true); + }); + + it('does not emit connection from handleUpgrade in noServer mode', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + let connected = false; + wss.on('connection', () => { + connected = true; + }); + const socket = new MockSocket(); + wss.handleUpgrade(upgradeRequest(), asSocket(socket), Buffer.alloc(0), (ws) => ws.terminate()); + expect(connected).toBe(false); + }); + + it('ignores options.path inside handleUpgrade itself', () => { + const wss = new WebSocketServer({ noServer: true, path: '/ws' }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade(upgradeRequest({ url: '/other' }), asSocket(socket), Buffer.alloc(0), (ws) => { + ws.terminate(); + }); + expect(socket.text).toBe(RFC_SWITCHING); + }); +}); + +describe('WebSocketServer verifyClient', () => { + it('accepts when the sync verifier returns true', () => { + const infos: Array<{ origin?: string; secure: boolean; req: IncomingMessage }> = []; + const req = upgradeRequest({ headers: { origin: 'https://chat.example' } }); + const wss = new WebSocketServer({ + noServer: true, + verifyClient: (info) => { + infos.push(info); + return true; + }, + }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade(req, asSocket(socket), Buffer.alloc(0), (ws) => ws.terminate()); + expect(infos).toEqual([{ origin: 'https://chat.example', secure: false, req }]); + expect(socket.text).toBe(RFC_SWITCHING); + }); + + it('rejects a sync verifier false with 401 Unauthorized', () => { + const wss = new WebSocketServer({ noServer: true, verifyClient: () => false }); + ownedServers.push(wss); + const socket = new MockSocket(); + let accepted = false; + wss.handleUpgrade(upgradeRequest(), asSocket(socket), Buffer.alloc(0), () => { + accepted = true; + }); + expect(accepted).toBe(false); + expect(socket.text).toBe(UNAUTHORIZED); + expect(socket.destroyed).toBe(true); + }); + + it('marks verify info secure when the socket is encrypted', () => { + let secure: boolean | undefined; + const wss = new WebSocketServer({ + noServer: true, + verifyClient: (info) => { + secure = info.secure; + return true; + }, + }); + ownedServers.push(wss); + const socket = new MockSocket({ encrypted: true }); + wss.handleUpgrade(upgradeRequest(), asSocket(socket), Buffer.alloc(0), (ws) => ws.terminate()); + expect(secure).toBe(true); + }); + + it('accepts when the async verifier calls back true', () => { + const wss = new WebSocketServer({ + noServer: true, + verifyClient: (_info, cb) => { + cb(true); + }, + }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade(upgradeRequest(), asSocket(socket), Buffer.alloc(0), (ws) => ws.terminate()); + expect(socket.text).toBe(RFC_SWITCHING); + }); + + it('rejects an async verifier false with the default 401 body', () => { + const wss = new WebSocketServer({ + noServer: true, + verifyClient: (_info, cb) => { + cb(false); + }, + }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade(upgradeRequest(), asSocket(socket), Buffer.alloc(0), () => {}); + expect(socket.text).toBe(UNAUTHORIZED); + }); + + it('rejects an async verifier with a custom status and message', () => { + const wss = new WebSocketServer({ + noServer: true, + verifyClient: (_info, cb) => { + cb(false, 403, 'go away'); + }, + }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade(upgradeRequest(), asSocket(socket), Buffer.alloc(0), () => {}); + expect(socket.text).toBe( + 'HTTP/1.1 403 Forbidden\r\n' + + 'Connection: close\r\n' + + 'Content-Length: 7\r\n' + + 'Content-Type: text/plain\r\n' + + '\r\n' + + 'go away', + ); + }); + + it('uses status text Error and an empty body for an unknown async reject code', () => { + const wss = new WebSocketServer({ + noServer: true, + verifyClient: (_info, cb) => { + cb(false, 599); + }, + }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade(upgradeRequest(), asSocket(socket), Buffer.alloc(0), () => {}); + expect(socket.text).toBe( + 'HTTP/1.1 599 Error\r\n' + + 'Connection: close\r\n' + + 'Content-Length: 0\r\n' + + 'Content-Type: text/plain\r\n' + + '\r\n', + ); + }); + + it('waits for a deferred async verifier before writing 101', () => { + let decide: ((allow: boolean) => void) | undefined; + const wss = new WebSocketServer({ + noServer: true, + verifyClient: (_info, cb) => { + decide = (allow) => cb(allow); + }, + }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade(upgradeRequest(), asSocket(socket), Buffer.alloc(0), (ws) => ws.terminate()); + expect(socket.writes).toEqual([]); + decide!(true); + expect(socket.text).toBe(RFC_SWITCHING); + }); +}); + +describe('WebSocketServer path filtering', () => { + it('aborts a mismatched path when it is the only upgrade listener', () => { + const server = http.createServer(); + httpServers.push(server); + const wss = new WebSocketServer({ server, path: '/ws' }); + ownedServers.push(wss); + const socket = new MockSocket(); + server.emit('upgrade', upgradeRequest({ url: '/other' }), asSocket(socket), Buffer.alloc(0)); + expect(socket.text).toBe(BAD_PATH); + expect(socket.destroyed).toBe(true); + }); + + it('leaves a mismatched path alone when another upgrade listener exists', () => { + const server = http.createServer(); + httpServers.push(server); + const wss = new WebSocketServer({ server, path: '/ws' }); + ownedServers.push(wss); + let other = false; + server.on('upgrade', () => { + other = true; + }); + const socket = new MockSocket(); + server.emit('upgrade', upgradeRequest({ url: '/other' }), asSocket(socket), Buffer.alloc(0)); + expect(other).toBe(true); + expect(socket.writes).toEqual([]); + expect(socket.destroyed).toBe(false); + }); + + it('matches the path after stripping the query string', () => { + const server = http.createServer(); + httpServers.push(server); + const wss = new WebSocketServer({ server, path: '/ws' }); + ownedServers.push(wss); + const req = upgradeRequest({ url: '/ws?x=1' }); + const socket = new MockSocket(); + const seen: IncomingMessage[] = []; + wss.on('connection', (ws, request) => { + seen.push(request); + ws.terminate(); + }); + server.emit('upgrade', req, asSocket(socket), Buffer.alloc(0)); + expect(seen).toEqual([req]); + expect(socket.text).toBe(RFC_SWITCHING); + }); + + it('treats a missing url as /', () => { + const server = http.createServer(); + httpServers.push(server); + const wss = new WebSocketServer({ server, path: '/' }); + ownedServers.push(wss); + const req = upgradeRequest({ url: undefined }); + const socket = new MockSocket(); + let connected = false; + wss.on('connection', (ws) => { + connected = true; + ws.terminate(); + }); + server.emit('upgrade', req, asSocket(socket), Buffer.alloc(0)); + expect(connected).toBe(true); + expect(socket.text).toBe(RFC_SWITCHING); + }); + + it('rejects a missing url when the configured path is not /', () => { + const server = http.createServer(); + httpServers.push(server); + const wss = new WebSocketServer({ server, path: '/ws' }); + ownedServers.push(wss); + const socket = new MockSocket(); + server.emit('upgrade', upgradeRequest({ url: undefined }), asSocket(socket), Buffer.alloc(0)); + expect(socket.text).toBe(BAD_PATH); + }); +}); + +describe('WebSocketServer.close', () => { + it('invokes the callback on the next immediate tick in noServer mode', async () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + let called = false; + wss.close(() => { + called = true; + }); + expect(called).toBe(false); + await new Promise((resolve) => setImmediate(resolve)); + expect(called).toBe(true); + }); + + it('returns without throwing when noServer close has no callback', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + expect(() => wss.close()).not.toThrow(); + }); + + it('detaches the upgrade listener from an external server and still calls back', async () => { + const server = http.createServer(); + httpServers.push(server); + const wss = new WebSocketServer({ server }); + ownedServers.push(wss); + expect(server.listenerCount('upgrade')).toBe(1); + await closeWss(wss); + expect(server.listenerCount('upgrade')).toBe(0); + await closeWss(wss); + expect(server.listenerCount('upgrade')).toBe(0); + }); + + it('sends 1001 Server shutting down to live clients', () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + const socket = new MockSocket(); + wss.handleUpgrade(upgradeRequest(), asSocket(socket), Buffer.alloc(0), () => {}); + wss.close(); + expect(socket.writes[0]!.toString('utf8')).toBe(RFC_SWITCHING); + expect(socket.writes[1]!.equals(SHUTDOWN_CLOSE_FRAME)).toBe(true); + }); + + it('swallows a client close that throws', async () => { + const wss = new WebSocketServer({ noServer: true }); + ownedServers.push(wss); + wss.clients.add({ + close() { + throw new Error('boom'); + }, + } as never); + await closeWss(wss); + }); + + it('forwards the owned HTTP server close callback', async () => { + const wss = new WebSocketServer({ port: 0, host: '127.0.0.1' }); + ownedServers.push(wss); + await waitListening(wss); + await closeWss(wss); + }); +}); diff --git a/packages/websocket/tests/websocket.test.ts b/packages/websocket/tests/websocket.test.ts new file mode 100644 index 00000000..55602940 --- /dev/null +++ b/packages/websocket/tests/websocket.test.ts @@ -0,0 +1,939 @@ +import { EventEmitter } from 'node:events'; +import type { Socket } from 'node:net'; +import zlib from 'node:zlib'; +import { afterEach, describe, expect, it } from 'vitest'; + +import { compressRaw } from '../src/extensions'; +import native from '../src/native'; +import { + CLOSED, + CLOSING, + CONNECTING, + OPEN, + OP_BIN, + OP_CLOSE, + OP_CONT, + OP_PING, + OP_PONG, + OP_TEXT, + RSV1, + WebSocket, + encodeClosePayload, + isValidCloseCode, + randomMaskKey, +} from '../src/websocket'; + +const MASK = Buffer.from([0x11, 0x22, 0x33, 0x44]); +const ZLIB_TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const DEFLATE = { + enabled: true as const, + requestNoContextTakeover: true, + responseNoContextTakeover: true, + threshold: 1024, +}; + +let nativeIo = true; +try { + native.buildFrame(OP_TEXT, true, Buffer.from([0x61]), null, 0); +} catch (err) { + nativeIo = !String((err as Error).message).includes('native addon is stubbed'); +} + +class FakeSocket extends EventEmitter { + readonly written: Buffer[] = []; + ended = false; + endedPayload: Buffer | undefined; + destroyed = false; + throwOnEnd = false; + throwOnDestroy = false; + autoCloseOnEnd = false; + + write(chunk: Buffer, cb?: (err?: Error | null) => void): boolean { + this.written.push(Buffer.from(chunk)); + cb?.(null); + return true; + } + + end(chunk?: Buffer): this { + if (this.throwOnEnd) throw new Error('end failed'); + if (chunk !== undefined) this.endedPayload = Buffer.from(chunk); + this.ended = true; + if (this.autoCloseOnEnd) { + this.emit('end'); + this.emit('close'); + } + return this; + } + + destroy(): this { + if (this.throwOnDestroy) throw new Error('destroy failed'); + this.destroyed = true; + return this; + } +} + +const sockets: FakeSocket[] = []; + +function createWs( + options?: ConstructorParameters[1], + socket = new FakeSocket(), +): { ws: WebSocket; socket: FakeSocket } { + sockets.push(socket); + return { ws: new WebSocket(socket as unknown as Socket, options), socket }; +} + +function clientFrame(opcode: number, payload: Buffer, fin = true, rsv = 0): Buffer { + return native.buildFrame(opcode, fin, payload, MASK, rsv); +} + +function serverFrame(opcode: number, payload: Buffer, fin = true, rsv = 0): Buffer { + return native.buildFrame(opcode, fin, payload, null, rsv); +} + +function parseFrames(buffers: Array, expectMasked: boolean): Array<{ + fin: boolean; + opcode: number; + payload: Buffer; + rsv: number; +}> { + const parser = new native.Parser({ + isServer: expectMasked, + maxPayload: 100 * 1024 * 1024, + allowedRsv: 0x70, + }); + const frames: Array<{ fin: boolean; opcode: number; payload: Buffer; rsv: number }> = []; + for (const buf of buffers) { + if (!buf) continue; + const res = parser.push(buf); + if (res.error) throw new Error(res.message ?? 'parse failed'); + for (const frame of res.frames) { + frames.push({ + fin: frame.fin, + opcode: frame.opcode, + payload: frame.payload, + rsv: frame.rsv ?? 0, + }); + } + } + return frames; +} + +function inflateRawError(data: Buffer): Error & { code?: string } { + try { + zlib.inflateRawSync(Buffer.concat([data, ZLIB_TRAILER]), { + finishFlush: zlib.constants.Z_SYNC_FLUSH, + }); + } catch (err) { + return err as Error & { code?: string }; + } + throw new Error('expected inflateRawSync to fail'); +} + +afterEach(() => { + for (const socket of sockets) socket.emit('close'); + sockets.length = 0; +}); + +describe('opcode and ready-state constants', () => { + it('exports the RFC 6455 opcodes and ready-state numbers', () => { + expect(OP_CONT).toBe(0x0); + expect(OP_TEXT).toBe(0x1); + expect(OP_BIN).toBe(0x2); + expect(OP_CLOSE).toBe(0x8); + expect(OP_PING).toBe(0x9); + expect(OP_PONG).toBe(0xA); + expect(RSV1).toBe(0x40); + expect(CONNECTING).toBe(0); + expect(OPEN).toBe(1); + expect(CLOSING).toBe(2); + expect(CLOSED).toBe(3); + expect(WebSocket.CONNECTING).toBe(0); + expect(WebSocket.OPEN).toBe(1); + expect(WebSocket.CLOSING).toBe(2); + expect(WebSocket.CLOSED).toBe(3); + }); +}); + +describe('isValidCloseCode', () => { + it('accepts the RFC registered application codes and the 3000–4999 range', () => { + for (const code of [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011, 3000, 3001, 3999, 4000, 4999]) { + expect(isValidCloseCode(code)).toBe(true); + } + }); + + it('rejects reserved, unused, and out-of-range codes', () => { + for (const code of [0, 999, 1004, 1005, 1006, 1012, 1013, 1014, 1015, 1016, 2000, 2999, 5000, 65535, -1]) { + expect(isValidCloseCode(code)).toBe(false); + } + }); +}); + +describe('encodeClosePayload', () => { + it('returns an empty buffer when the code is omitted', () => { + expect(encodeClosePayload(undefined)).toEqual(Buffer.alloc(0)); + expect(encodeClosePayload(null)).toEqual(Buffer.alloc(0)); + expect(encodeClosePayload(1000, '')).toEqual(Buffer.from([0x03, 0xe8])); + }); + + it('rejects a reason without a close code', () => { + expect(() => encodeClosePayload(undefined, 'bye')).toThrow('Cannot send close reason without a code'); + expect(() => encodeClosePayload(null, 'bye')).toThrow('Cannot send close reason without a code'); + }); + + it('writes a big-endian code and the UTF-8 reason', () => { + expect(encodeClosePayload(1000)).toEqual(Buffer.from([0x03, 0xe8])); + expect(encodeClosePayload(1001, 'bye')).toEqual(Buffer.from([0x03, 0xe9, 0x62, 0x79, 0x65])); + expect(encodeClosePayload(4999, 'é')).toEqual(Buffer.from([0x13, 0x87, 0xc3, 0xa9])); + expect(encodeClosePayload(0x1_0000)).toEqual(Buffer.from([0x00, 0x00])); + }); +}); + +describe('randomMaskKey', () => { + it('returns a 4-byte Buffer', () => { + const key = randomMaskKey(); + expect(Buffer.isBuffer(key)).toBe(true); + expect(key).toHaveLength(4); + expect(randomMaskKey()).not.toEqual(key); + }); +}); + +describe('WebSocket constructor', () => { + it('defaults to an unmasked client socket in the OPEN state', () => { + const { ws } = createWs(); + expect(ws.readyState).toBe(1); + expect(ws.isServer).toBe(false); + expect(ws.protocol).toBe(''); + expect(ws.extensions).toBe(''); + }); + + it('applies server, protocol, payload, ready-state, and deflate options', () => { + const { ws } = createWs({ + isServer: true, + maxPayload: 32, + readyState: CONNECTING, + protocol: 'chat', + extensions: { perMessageDeflate: DEFLATE }, + }); + expect(ws.readyState).toBe(0); + expect(ws.isServer).toBe(true); + expect(ws.protocol).toBe('chat'); + expect(ws.extensions).toBe('permessage-deflate'); + }); + + it('treats a missing options object as empty', () => { + const { ws } = createWs(undefined); + expect(ws.readyState).toBe(OPEN); + expect(ws.isServer).toBe(false); + expect(ws.extensions).toBe(''); + }); +}); + +describe.skipIf(!nativeIo)('WebSocket send/ping/pong/close', () => { + it('sends a UTF-8 text frame for a string', () => { + const { ws, socket } = createWs({ isServer: true }); + ws.send('hi'); + expect(parseFrames(socket.written, false)).toEqual([ + { fin: true, opcode: 0x1, payload: Buffer.from([0x68, 0x69]), rsv: 0 }, + ]); + }); + + it('sends a string as binary when binary: true', () => { + const { ws, socket } = createWs({ isServer: true }); + ws.send('hi', { binary: true }); + expect(parseFrames(socket.written, false)[0]).toMatchObject({ + opcode: 0x2, + payload: Buffer.from([0x68, 0x69]), + }); + }); + + it('sends a Buffer as binary unless binary: false', () => { + const { ws, socket } = createWs({ isServer: true }); + ws.send(Buffer.from([0x01, 0x02])); + ws.send(Buffer.from([0x61]), { binary: false }); + const frames = parseFrames(socket.written, false); + expect(frames[0]).toMatchObject({ opcode: 0x2, payload: Buffer.from([0x01, 0x02]) }); + expect(frames[1]).toMatchObject({ opcode: 0x1, payload: Buffer.from([0x61]) }); + }); + + it('sends a Uint8Array view using byteOffset/byteLength', () => { + const { ws, socket } = createWs({ isServer: true }); + const view = new Uint8Array([0x00, 0x09, 0x08, 0x07, 0x00]).subarray(1, 4); + ws.send(view); + expect(parseFrames(socket.written, false)[0]).toMatchObject({ + opcode: 0x2, + payload: Buffer.from([0x09, 0x08, 0x07]), + }); + }); + + it('sends an ArrayBuffer as binary unless binary: false', () => { + const { ws, socket } = createWs({ isServer: true }); + ws.send(new Uint8Array([0x04, 0x05, 0x06]).buffer); + ws.send(new Uint8Array([0x7a]).buffer, { binary: false }); + const frames = parseFrames(socket.written, false); + expect(frames[0]).toMatchObject({ opcode: 0x2, payload: Buffer.from([0x04, 0x05, 0x06]) }); + expect(frames[1]).toMatchObject({ opcode: 0x1, payload: Buffer.from([0x7a]) }); + }); + + it('accepts the callback as the second argument', () => { + const { ws } = createWs({ isServer: true }); + const seen: Array = []; + ws.send('ok', (err) => { seen.push(err); }); + expect(seen).toEqual([null]); + }); + + it('passes the callback through with send options', () => { + const { ws, socket } = createWs({ isServer: true }); + const seen: Array = []; + ws.send('ok', { binary: false }, (err) => { seen.push(err); }); + expect(seen).toEqual([null]); + expect(parseFrames(socket.written, false)[0]!.opcode).toBe(0x1); + }); + + it('throws when send() is used while not OPEN', () => { + const { ws } = createWs({ isServer: true, readyState: CONNECTING }); + expect(() => ws.send('x')).toThrow('WebSocket is not open'); + }); + + it('delivers the not-open error to the send callback without throwing', () => { + const { ws } = createWs({ isServer: true, readyState: CLOSING }); + const seen: Array = []; + ws.send('x', (err) => { seen.push(err); }); + expect(seen).toHaveLength(1); + expect(seen[0]).toBeInstanceOf(Error); + expect(seen[0]!.message).toBe('WebSocket is not open'); + }); + + it('rejects unsupported send() data types', () => { + const { ws } = createWs({ isServer: true }); + expect(() => ws.send(1 as unknown as string)).toThrow(TypeError); + expect(() => ws.send(1 as unknown as string)).toThrow('Unsupported data type for send()'); + const seen: Array = []; + ws.send({} as unknown as Buffer, (err) => { seen.push(err); }); + expect(seen).toHaveLength(1); + expect(seen[0]).toBeInstanceOf(TypeError); + expect(seen[0]!.message).toBe('Unsupported data type for send()'); + }); + + it('masks client frames and leaves server frames unmasked', () => { + const server = createWs({ isServer: true }); + server.ws.send('a'); + expect(server.socket.written[0]![1]! & 0x80).toBe(0); + + const client = createWs({ isServer: false }); + client.ws.send('a'); + expect(client.socket.written[0]![1]! & 0x80).toBe(0x80); + expect(parseFrames(client.socket.written, true)[0]).toMatchObject({ + opcode: 0x1, + payload: Buffer.from([0x61]), + }); + }); + + it('compresses payloads at or above the deflate threshold', () => { + const { ws, socket } = createWs({ + isServer: true, + extensions: { perMessageDeflate: DEFLATE }, + }); + const body = Buffer.alloc(1024, 0x61); + ws.send(body); + const frame = parseFrames(socket.written, false)[0]!; + expect(frame.opcode).toBe(0x2); + expect(frame.rsv).toBe(0x40); + expect(frame.payload.equals(body)).toBe(false); + expect(zlib.inflateRawSync(Buffer.concat([frame.payload, ZLIB_TRAILER]), { + finishFlush: zlib.constants.Z_SYNC_FLUSH, + })).toEqual(body); + }); + + it('uses 1024 as the compress threshold when the negotiated value is missing', () => { + const { ws, socket } = createWs({ + isServer: true, + extensions: { + perMessageDeflate: { + enabled: true, + requestNoContextTakeover: true, + responseNoContextTakeover: true, + } as typeof DEFLATE, + }, + }); + ws.send(Buffer.alloc(1023, 0x62)); + ws.send(Buffer.alloc(1024, 0x62)); + const frames = parseFrames(socket.written, false); + expect(frames[0]!.rsv).toBe(0); + expect(frames[0]!.payload).toEqual(Buffer.alloc(1023, 0x62)); + expect(frames[1]!.rsv).toBe(0x40); + }); + + it('skips compression when compress is false or the payload is under the threshold', () => { + const { ws, socket } = createWs({ + isServer: true, + extensions: { perMessageDeflate: { ...DEFLATE, threshold: 8 } }, + }); + ws.send(Buffer.alloc(8, 0x63), { compress: false }); + ws.send(Buffer.alloc(7, 0x63)); + const frames = parseFrames(socket.written, false); + expect(frames[0]).toMatchObject({ rsv: 0, payload: Buffer.alloc(8, 0x63) }); + expect(frames[1]).toMatchObject({ rsv: 0, payload: Buffer.alloc(7, 0x63) }); + }); + + it('does not compress when permessage-deflate was not negotiated', () => { + const { ws, socket } = createWs({ isServer: true }); + ws.send(Buffer.alloc(2048, 0x64), { compress: true }); + expect(parseFrames(socket.written, false)[0]!.rsv).toBe(0); + }); + + it('sends ping and pong control frames', () => { + const { ws, socket } = createWs({ isServer: true }); + ws.ping(); + ws.ping('ab'); + ws.ping(Buffer.from([0x01])); + ws.pong(); + ws.pong('cd'); + ws.pong(Buffer.from([0x02])); + const frames = parseFrames(socket.written, false); + expect(frames).toEqual([ + { fin: true, opcode: 0x9, payload: Buffer.alloc(0), rsv: 0 }, + { fin: true, opcode: 0x9, payload: Buffer.from([0x61, 0x62]), rsv: 0 }, + { fin: true, opcode: 0x9, payload: Buffer.from([0x01]), rsv: 0 }, + { fin: true, opcode: 0xa, payload: Buffer.alloc(0), rsv: 0 }, + { fin: true, opcode: 0xa, payload: Buffer.from([0x63, 0x64]), rsv: 0 }, + { fin: true, opcode: 0xa, payload: Buffer.from([0x02]), rsv: 0 }, + ]); + }); + + it('accepts a callback as the first ping/pong argument', () => { + const { ws } = createWs({ isServer: true }); + const seen: Array = []; + ws.ping((err) => { seen.push(err); }); + ws.pong((err) => { seen.push(err); }); + expect(seen).toEqual([null, null]); + }); + + it('accepts ping/pong callbacks after the unused mask argument', () => { + const { ws, socket } = createWs({ isServer: true }); + const seen: Array = []; + ws.ping('z', undefined, (err) => { seen.push(err); }); + ws.pong('z', undefined, (err) => { seen.push(err); }); + expect(seen).toEqual([null, null]); + expect(parseFrames(socket.written, false).map((f) => f.opcode)).toEqual([0x9, 0xa]); + }); + + it('rejects ping/pong payloads larger than 125 bytes before checking readyState', () => { + const { ws } = createWs({ isServer: true, readyState: CLOSED }); + expect(() => ws.ping(Buffer.alloc(126))).toThrow('Ping payload must be <=125 bytes'); + expect(() => ws.pong('x'.repeat(126))).toThrow('Pong payload must be <=125 bytes'); + expect(() => ws.ping(Buffer.alloc(125))).toThrow('WebSocket is not open'); + expect(() => ws.pong(Buffer.alloc(125))).toThrow('WebSocket is not open'); + }); + + it('delivers the not-open error to ping/pong callbacks', () => { + const { ws } = createWs({ isServer: true, readyState: CONNECTING }); + const seen: Error[] = []; + ws.ping(Buffer.from('a'), undefined, (err) => { if (err) seen.push(err); }); + ws.pong('a', undefined, (err) => { if (err) seen.push(err); }); + expect(seen.map((err) => err.message)).toEqual([ + 'WebSocket is not open', + 'WebSocket is not open', + ]); + }); + + it('writes a close frame, then half-closes the socket', () => { + const { ws, socket } = createWs({ isServer: true }); + ws.close(1000, 'done'); + expect(ws.readyState).toBe(2); + expect(parseFrames(socket.written, false)).toEqual([ + { fin: true, opcode: 0x8, payload: Buffer.from([0x03, 0xe8, 0x64, 0x6f, 0x6e, 0x65]), rsv: 0 }, + ]); + expect(socket.ended).toBe(true); + expect(socket.endedPayload).toBeUndefined(); + }); + + it('allows a 123-byte close reason and rejects 124 bytes', () => { + const ok = createWs({ isServer: true }); + ok.ws.close(1001, 'n'.repeat(123)); + expect(parseFrames(ok.socket.written, false)[0]!.payload).toEqual( + Buffer.concat([Buffer.from([0x03, 0xe9]), Buffer.from('n'.repeat(123))]), + ); + + const tooLong = createWs({ isServer: true }); + expect(() => tooLong.ws.close(1000, 'n'.repeat(124))).toThrow(RangeError); + expect(() => tooLong.ws.close(1000, 'é'.repeat(62))).toThrow('Close reason must be <=123 bytes'); + expect(tooLong.socket.written).toEqual([]); + }); + + it('rejects invalid close codes and ignores close() after CLOSING/CLOSED', () => { + const open = createWs({ isServer: true }); + expect(() => open.ws.close(1005)).toThrow(RangeError); + expect(() => open.ws.close(1006)).toThrow('Invalid close code: 1006'); + expect(() => open.ws.close(0)).toThrow('Invalid close code: 0'); + expect(open.socket.written).toEqual([]); + + open.ws.close(); + expect(open.ws.readyState).toBe(CLOSING); + expect(parseFrames(open.socket.written, false)[0]!.payload).toEqual(Buffer.alloc(0)); + open.ws.close(1000, 'again'); + expect(open.socket.written).toHaveLength(1); + + const closed = createWs({ isServer: true, readyState: CLOSED }); + closed.ws.close(1000); + expect(closed.socket.written).toEqual([]); + }); + + it('masks a client close frame', () => { + const { ws, socket } = createWs({ isServer: false }); + ws.close(3000); + expect(socket.written[0]![1]! & 0x80).toBe(0x80); + expect(parseFrames(socket.written, true)[0]!.payload).toEqual(Buffer.from([0x0b, 0xb8])); + }); + + it('terminate() force-destroys the socket while leaving the state CLOSING', () => { + const { ws, socket } = createWs({ isServer: true }); + ws.terminate(); + expect(ws.readyState).toBe(2); + expect(socket.destroyed).toBe(true); + expect(socket.written).toEqual([]); + }); + + it('swallows destroy() failures from terminate()', () => { + const { ws, socket } = createWs({ isServer: true }); + socket.throwOnDestroy = true; + expect(() => ws.terminate()).not.toThrow(); + expect(ws.readyState).toBe(CLOSING); + }); + + it('swallows end() failures from close()', () => { + const { ws, socket } = createWs({ isServer: true }); + socket.throwOnEnd = true; + expect(() => ws.close(1000)).not.toThrow(); + expect(ws.readyState).toBe(CLOSING); + expect(socket.written).toHaveLength(1); + }); +}); + +describe.skipIf(!nativeIo)('WebSocket incoming frames', () => { + it('emits a complete text message and a complete binary message', () => { + const { ws, socket } = createWs({ isServer: true }); + const messages: Array<{ data: Buffer; isBinary: boolean }> = []; + ws.on('message', (data, isBinary) => { messages.push({ data, isBinary }); }); + socket.emit('data', clientFrame(OP_TEXT, Buffer.from('hello'))); + socket.emit('data', clientFrame(OP_BIN, Buffer.from([0xde, 0xad]))); + expect(messages).toEqual([ + { data: Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), isBinary: false }, + { data: Buffer.from([0xde, 0xad]), isBinary: true }, + ]); + }); + + it('reassembles fragmented messages, including an empty continuation', () => { + const { ws, socket } = createWs({ isServer: true }); + const messages: Array<{ text: string; isBinary: boolean }> = []; + ws.on('message', (data, isBinary) => { + messages.push({ text: data.toString('utf8'), isBinary }); + }); + socket.emit('data', clientFrame(OP_TEXT, Buffer.from('he'), false)); + socket.emit('data', clientFrame(OP_CONT, Buffer.alloc(0), false)); + socket.emit('data', clientFrame(OP_CONT, Buffer.from('llo'), true)); + socket.emit('data', Buffer.concat([ + clientFrame(OP_BIN, Buffer.from([0x01]), false), + clientFrame(OP_CONT, Buffer.from([0x02, 0x03]), true), + ])); + expect(messages).toEqual([ + { text: 'hello', isBinary: false }, + { text: '\u0001\u0002\u0003', isBinary: true }, + ]); + }); + + it('accepts valid 2/3/4-byte UTF-8 text', () => { + const { ws, socket } = createWs({ isServer: true }); + const seen: string[] = []; + ws.on('message', (data) => { seen.push(data.toString('utf8')); }); + socket.emit('data', clientFrame(OP_TEXT, Buffer.from([0xc2, 0xa2]))); + socket.emit('data', clientFrame(OP_TEXT, Buffer.from([0xe2, 0x82, 0xac]))); + socket.emit('data', clientFrame(OP_TEXT, Buffer.from([0xf0, 0x9d, 0x84, 0x9e]))); + expect(seen).toEqual(['¢', '€', '𝄞']); + }); + + it('fails invalid UTF-8 text with 1007', () => { + const cases: Array<{ name: string; payload: Buffer }> = [ + { name: 'lone 0xFF', payload: Buffer.from([0xff]) }, + { name: 'incomplete 2-byte', payload: Buffer.from([0xc2]) }, + { name: 'overlong 2-byte', payload: Buffer.from([0xc0, 0x80]) }, + { name: 'overlong 3-byte', payload: Buffer.from([0xe0, 0x80, 0x80]) }, + { name: 'UTF-16 surrogate', payload: Buffer.from([0xed, 0xa0, 0x80]) }, + { name: 'out-of-range 4-byte lead', payload: Buffer.from([0xf5, 0x80, 0x80, 0x80]) }, + { name: 'lone continuation', payload: Buffer.from([0x80]) }, + ]; + for (const testCase of cases) { + const { ws, socket } = createWs({ isServer: true }); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_TEXT, testCase.payload)); + expect(errors, testCase.name).toHaveLength(1); + expect(errors[0]!.message).toBe('WebSocket protocol error: Invalid UTF-8'); + expect(errors[0]!.code).toBe(1007); + expect(ws.readyState).toBe(CLOSING); + } + }); + + it('answers a ping with a pong while OPEN, and only emits ping while not OPEN', () => { + const open = createWs({ isServer: true }); + const pings: Buffer[] = []; + open.ws.on('ping', (data) => { pings.push(data); }); + open.socket.emit('data', clientFrame(OP_PING, Buffer.from('hi'))); + expect(pings).toEqual([Buffer.from([0x68, 0x69])]); + expect(parseFrames(open.socket.written, false)).toEqual([ + { fin: true, opcode: 0xa, payload: Buffer.from([0x68, 0x69]), rsv: 0 }, + ]); + + const closing = createWs({ isServer: true, readyState: CLOSING }); + const ignored: Buffer[] = []; + closing.ws.on('ping', (data) => { ignored.push(data); }); + closing.socket.emit('data', clientFrame(OP_PING, Buffer.from('zz'))); + expect(ignored).toEqual([Buffer.from([0x7a, 0x7a])]); + expect(closing.socket.written).toEqual([]); + }); + + it('emits pong payloads without writing a reply', () => { + const { ws, socket } = createWs({ isServer: true }); + const pongs: Buffer[] = []; + ws.on('pong', (data) => { pongs.push(data); }); + socket.emit('data', clientFrame(OP_PONG, Buffer.from([0xaa]))); + expect(pongs).toEqual([Buffer.from([0xaa])]); + expect(socket.written).toEqual([]); + }); + + it('echoes a close code without the peer reason and then ends the socket', () => { + const { ws, socket } = createWs({ isServer: true }); + socket.emit('data', clientFrame(OP_CLOSE, Buffer.from([0x03, 0xe8, 0x62, 0x79, 0x65]))); + expect(ws.readyState).toBe(CLOSING); + expect(parseFrames(socket.written, false)).toEqual([ + { fin: true, opcode: 0x8, payload: Buffer.from([0x03, 0xe8]), rsv: 0 }, + ]); + expect(socket.ended).toBe(true); + const closes: Array<{ code: number; reason: string }> = []; + ws.on('close', (code, reason) => { closes.push({ code, reason }); }); + socket.emit('close'); + expect(closes).toEqual([{ code: 1000, reason: 'bye' }]); + }); + + it('treats an empty close payload as 1005 and echoes an empty close', () => { + const { ws, socket } = createWs({ isServer: true }); + socket.emit('data', clientFrame(OP_CLOSE, Buffer.alloc(0))); + expect(parseFrames(socket.written, false)).toEqual([ + { fin: true, opcode: 0x8, payload: Buffer.alloc(0), rsv: 0 }, + ]); + socket.emit('close'); + expect(ws.readyState).toBe(CLOSED); + }); + + it('accepts a UTF-8 close reason including non-ASCII', () => { + const { ws, socket } = createWs({ isServer: true }); + const closes: Array<{ code: number; reason: string }> = []; + ws.on('close', (code, reason) => { closes.push({ code, reason }); }); + socket.emit('data', clientFrame(OP_CLOSE, Buffer.from([0x03, 0xe8, 0xc3, 0xa9]))); + socket.emit('close'); + expect(closes).toEqual([{ code: 1000, reason: 'é' }]); + }); + + it('fails a 1-byte close payload', () => { + const { ws, socket } = createWs({ isServer: true }); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_CLOSE, Buffer.from([0x00]))); + expect(errors[0]!.message).toBe('WebSocket protocol error: Close payload length 1'); + expect(errors[0]!.code).toBe(1002); + expect(parseFrames([socket.endedPayload], false)[0]!.payload.subarray(0, 2)).toEqual(Buffer.from([0x03, 0xea])); + }); + + it('fails reserved close codes', () => { + const { ws, socket } = createWs({ isServer: true }); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_CLOSE, Buffer.from([0x03, 0xed]))); + expect(errors[0]!.message).toBe('WebSocket protocol error: Invalid close code'); + expect(errors[0]!.code).toBe(1002); + }); + + it('fails a close reason that is not valid UTF-8', () => { + const { ws, socket } = createWs({ isServer: true }); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_CLOSE, Buffer.from([0x03, 0xe8, 0xff]))); + expect(errors[0]!.message).toBe('WebSocket protocol error: Invalid UTF-8 in close reason'); + expect(errors[0]!.code).toBe(1007); + }); + + it('does not echo a close received while CONNECTING', () => { + const { ws, socket } = createWs({ isServer: true, readyState: CONNECTING }); + socket.emit('data', clientFrame(OP_CLOSE, Buffer.from([0x03, 0xe8]))); + expect(ws.readyState).toBe(CONNECTING); + expect(socket.written).toEqual([]); + expect(socket.ended).toBe(false); + const closes: Array<{ code: number; reason: string }> = []; + ws.on('close', (code, reason) => { closes.push({ code, reason }); }); + socket.emit('close'); + expect(closes).toEqual([{ code: 1000, reason: '' }]); + }); + + it('ends the socket again when a close arrives already CLOSING', () => { + const { ws, socket } = createWs({ isServer: true }); + ws.close(1000); + expect(socket.ended).toBe(true); + socket.ended = false; + socket.emit('data', clientFrame(OP_CLOSE, Buffer.from([0x03, 0xe8]))); + expect(ws.readyState).toBe(CLOSING); + expect(socket.ended).toBe(true); + expect(socket.written).toHaveLength(1); + }); + + it('stops the frame loop once a close handshake has already CLOSED the socket', () => { + const { ws, socket } = createWs({ isServer: true }); + socket.autoCloseOnEnd = true; + const messages: Buffer[] = []; + ws.on('message', (data) => { messages.push(data); }); + const closes: number[] = []; + ws.on('close', (code) => { closes.push(code); }); + socket.emit('data', Buffer.concat([ + clientFrame(OP_CLOSE, Buffer.from([0x03, 0xe8])), + clientFrame(OP_TEXT, Buffer.from('late')), + ])); + expect(closes).toEqual([1000]); + expect(messages).toEqual([]); + expect(ws.readyState).toBe(CLOSED); + }); + + it('fails a new data frame that starts before the previous fragment finishes', () => { + const { ws, socket } = createWs({ isServer: true }); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_TEXT, Buffer.from('ab'), false)); + socket.emit('data', clientFrame(OP_BIN, Buffer.from('cd'), true)); + expect(errors[0]!.message).toBe( + 'WebSocket protocol error: New data frame started before previous fragmented message finished', + ); + expect(errors[0]!.code).toBe(1002); + }); + + it('fails a continuation that has no active message', () => { + const { ws, socket } = createWs({ isServer: true }); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_CONT, Buffer.from('x'))); + expect(errors[0]!.message).toBe('WebSocket protocol error: Continuation frame without active message'); + expect(errors[0]!.code).toBe(1002); + }); + + it('fails RSV bits on a continuation after deflate was negotiated', () => { + const { ws, socket } = createWs({ + isServer: true, + extensions: { perMessageDeflate: DEFLATE }, + }); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_TEXT, Buffer.from('ab'), false)); + socket.emit('data', clientFrame(OP_CONT, Buffer.from('c'), true, RSV1)); + expect(errors[0]!.message).toBe('WebSocket protocol error: RSV bits set on continuation frame'); + expect(errors[0]!.code).toBe(1002); + }); + + it('fails when assembled fragments exceed maxPayload', () => { + const { ws, socket } = createWs({ isServer: true, maxPayload: 10 }); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_TEXT, Buffer.from('xxxxxx'), false)); + socket.emit('data', clientFrame(OP_CONT, Buffer.from('xxxxx'), true)); + expect(errors[0]!.message).toBe('WebSocket protocol error: Message too large'); + expect(errors[0]!.code).toBe(1009); + }); + + it('fails a single frame that the parser rejects as larger than maxPayload', () => { + const { ws, socket } = createWs({ isServer: true, maxPayload: 4 }); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_TEXT, Buffer.from('hello'))); + expect(errors[0]!.message).toBe('WebSocket protocol error: Payload exceeds configured max'); + expect(errors[0]!.code).toBe(1009); + }); + + it('inflates a compressed text frame when deflate was negotiated', () => { + const { ws, socket } = createWs({ + isServer: true, + extensions: { perMessageDeflate: DEFLATE }, + }); + const messages: Array<{ data: Buffer; isBinary: boolean }> = []; + ws.on('message', (data, isBinary) => { messages.push({ data, isBinary }); }); + const plain = Buffer.from('hello hello hello hello'); + socket.emit('data', clientFrame(OP_TEXT, compressRaw(plain), true, RSV1)); + expect(messages).toEqual([{ data: plain, isBinary: false }]); + }); + + it('inflates a compressed binary frame', () => { + const { ws, socket } = createWs({ + isServer: true, + extensions: { perMessageDeflate: { ...DEFLATE, threshold: 1 } }, + }); + const messages: Array<{ data: Buffer; isBinary: boolean }> = []; + ws.on('message', (data, isBinary) => { messages.push({ data, isBinary }); }); + const plain = Buffer.from([0x00, 0x01, 0x02, 0x03, 0x04]); + socket.emit('data', clientFrame(OP_BIN, compressRaw(plain), true, RSV1)); + expect(messages).toEqual([{ data: plain, isBinary: true }]); + }); + + it('fails compressed bytes that zlib cannot inflate', () => { + const { ws, socket } = createWs({ + isServer: true, + extensions: { perMessageDeflate: DEFLATE }, + }); + const garbage = Buffer.from([0x03, 0x01, 0x02, 0xff]); + const cause = inflateRawError(garbage); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_TEXT, garbage, true, RSV1)); + expect(errors[0]!.message).toBe(`WebSocket protocol error: ${cause.message}`); + expect(errors[0]!.code).toBe(cause.code); + expect(ws.readyState).toBe(CLOSING); + }); + + it('maps an inflated payload that exceeds maxPayload to 1009', () => { + const maxPayload = 32; + const { ws, socket } = createWs({ + isServer: true, + maxPayload, + extensions: { perMessageDeflate: DEFLATE }, + }); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_TEXT, compressRaw(Buffer.alloc(256, 0x61)), true, RSV1)); + expect(errors[0]!.message).toBe( + `WebSocket protocol error: Message too large after inflate (maxPayload=${maxPayload})`, + ); + expect(errors[0]!.code).toBe(1009); + }); + + it('validates UTF-8 after inflate', () => { + const { ws, socket } = createWs({ + isServer: true, + extensions: { perMessageDeflate: DEFLATE }, + }); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_TEXT, compressRaw(Buffer.from([0xff])), true, RSV1)); + expect(errors[0]!.message).toBe('WebSocket protocol error: Invalid UTF-8'); + expect(errors[0]!.code).toBe(1007); + }); + + it('fails RSV1 when permessage-deflate was not negotiated', () => { + const { ws, socket } = createWs({ isServer: true }); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_TEXT, Buffer.from('x'), true, RSV1)); + expect(errors[0]!.message).toBe('WebSocket protocol error: Unexpected RSV bits'); + expect(errors[0]!.code).toBe(1002); + }); + + it('fails unknown opcodes and unmasked client frames through the parser error path', () => { + const unknown = createWs({ isServer: true }); + const errors: Array = []; + unknown.ws.on('error', (err) => { errors.push(err); }); + unknown.socket.emit('data', clientFrame(0x3, Buffer.from('x'))); + expect(errors[0]!.message).toBe('WebSocket protocol error: Unknown opcode'); + expect(errors[0]!.code).toBe(1002); + + const unmasked = createWs({ isServer: true }); + const more: Array = []; + unmasked.ws.on('error', (err) => { more.push(err); }); + unmasked.socket.emit('data', serverFrame(OP_TEXT, Buffer.from('x'))); + expect(more[0]!.message).toBe('WebSocket protocol error: Expected masked frame from client'); + expect(more[0]!.code).toBe(1002); + }); + + it('fails a masked frame delivered to a client socket', () => { + const { ws, socket } = createWs({ isServer: false }); + const errors: Array = []; + ws.on('error', (err) => { errors.push(err); }); + socket.emit('data', clientFrame(OP_TEXT, Buffer.from('x'))); + expect(errors[0]!.message).toBe('WebSocket protocol error: Server must not mask frames'); + expect(errors[0]!.code).toBe(1002); + }); + + it('assembles a client-side message from unmasked server frames split across reads', () => { + const { ws, socket } = createWs({ isServer: false }); + const messages: Buffer[] = []; + ws.on('message', (data) => { messages.push(data); }); + const frame = serverFrame(OP_TEXT, Buffer.from('abc')); + socket.emit('data', frame.subarray(0, 2)); + expect(messages).toEqual([]); + socket.emit('data', frame.subarray(2)); + expect(messages).toEqual([Buffer.from([0x61, 0x62, 0x63])]); + }); + + it('ignores data after the socket has already CLOSED', () => { + const { ws, socket } = createWs({ isServer: true, readyState: CLOSED }); + const errors: Error[] = []; + const messages: Buffer[] = []; + ws.on('error', (err) => { errors.push(err); }); + ws.on('message', (data) => { messages.push(data); }); + socket.emit('data', clientFrame(OP_TEXT, Buffer.from('x'))); + expect(errors).toEqual([]); + expect(messages).toEqual([]); + }); +}); + +describe.skipIf(!nativeIo)('WebSocket socket lifecycle', () => { + it('maps a peer FIN without a close frame to 1006', () => { + const { ws, socket } = createWs({ isServer: true }); + const closes: Array<{ code: number; reason: string }> = []; + ws.on('close', (code, reason) => { closes.push({ code, reason }); }); + socket.emit('end'); + expect(socket.destroyed).toBe(true); + expect(ws.readyState).toBe(OPEN); + socket.emit('close'); + expect(ws.readyState).toBe(CLOSED); + expect(closes).toEqual([{ code: 1006, reason: '' }]); + }); + + it('keeps a previously received close code when the socket later ends', () => { + const { ws, socket } = createWs({ isServer: true }); + const closes: Array<{ code: number; reason: string }> = []; + ws.on('close', (code, reason) => { closes.push({ code, reason }); }); + socket.emit('data', clientFrame(OP_CLOSE, Buffer.from([0x03, 0xe9, 0x67, 0x6f]))); + socket.emit('end'); + socket.emit('close'); + expect(closes).toEqual([{ code: 1001, reason: 'go' }]); + }); + + it('does not emit a second close after the socket is already CLOSED', () => { + const { ws, socket } = createWs({ isServer: true }); + const closes: number[] = []; + ws.on('close', (code) => { closes.push(code); }); + socket.emit('close'); + socket.emit('end'); + socket.emit('close'); + expect(closes).toEqual([1006]); + expect(ws.readyState).toBe(CLOSED); + }); + + it('forwards socket errors', () => { + const { ws, socket } = createWs({ isServer: true }); + const err = new Error('ECONNRESET'); + const seen: Error[] = []; + ws.on('error', (e) => { seen.push(e); }); + socket.emit('error', err); + expect(seen).toEqual([err]); + }); + + it('swallows destroy() failures from a peer FIN', () => { + const { ws, socket } = createWs({ isServer: true }); + socket.throwOnDestroy = true; + expect(() => socket.emit('end')).not.toThrow(); + expect(ws.readyState).toBe(OPEN); + }); + + it('swallows end() failures while failing the connection', () => { + const { ws, socket } = createWs({ isServer: true }); + socket.throwOnEnd = true; + const errors: Error[] = []; + ws.on('error', (err) => { errors.push(err); }); + expect(() => socket.emit('data', clientFrame(0x3, Buffer.alloc(0)))).not.toThrow(); + expect(errors[0]!.message).toBe('WebSocket protocol error: Unknown opcode'); + expect(ws.readyState).toBe(CLOSING); + }); +}); diff --git a/packages/webui/package.json b/packages/webui/package.json index e8447d99..671c6e64 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -2,7 +2,7 @@ "license": "SEE LICENSE IN LICENSE", "name": "webui", "private": true, - "version": "1.14.7", + "version": "1.14.8", "type": "module", "scripts": { "dev": "vite",