Merge pull request #278 from SnowLuma/dev

chore: promote dev → main (c64f9d3)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-07-24 06:16:20 +00:00
commit e1cd0176ca
53 files changed
+5408 -209

No files matched your search

+13 -1
View File
@@ -41,7 +41,7 @@ SnowLuma 将会话接入、协议解析、身份映射、OneBot 转换和网络
| OneBot 接入 | OneBot v11 动作与事件,支持 WebSocket 服务端 / 客户端及 HTTP 服务端 / 上报 |
| 消息与媒体 | 文本、图片、语音、视频、文件、回复、提及、转发及 JSON / XML 卡片等常见消息元素 |
| 多账号运行 | 每个 QQ 账号独立维护会话、身份映射、消息存储与网络适配器 |
| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试、密码管理与可定制总览 |
| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试、存储管理、密码管理与可定制总览 |
| 开发者工具 | 提供 [`@snowluma/sdk`](packages/sdk/README.md) 与 [`@snowluma/mcp`](packages/mcp/README.md) |
| 可观察错误 | 关键解析与执行失败会留下明确上下文,不以静默丢弃掩盖问题 |
@@ -86,6 +86,18 @@ SNOWLUMA_ACCEPT_PRIVACY=1
</details>
## 日志与存储管理
WebUI 的“系统设置 → 存储管理”可查看受管数据占用、调整日志策略,并清理日志、非活动传输临时文件或离线账号的消息、媒体和表情回应数据库。清理范围固定,不包含配置、凭据或其他文件。
| 设置 | 默认值 | 环境变量 |
| --- | --- | --- |
| 日志树总量上限 | 1024 MB | `SNOWLUMA_LOG_MAX_TOTAL_MB` |
| 日志保留天数 | 7 天;`0` 表示关闭按日期清理 | `SNOWLUMA_LOG_RETAIN_DAYS` |
| 按账号额外写日志 | 关闭 | `SNOWLUMA_LOG_PER_UIN` |
环境变量优先于 `config/runtime.json`,对应字段会在 WebUI 中显示为锁定。`SNOWLUMA_LOG_MAX_MB` 仅控制单个日志分卷大小,不是日志树总量上限。
## 选择接入方式
| 入口 | 适合场景 | 参考 |
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.12.8",
"version": "1.12.9",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.12.8",
"version": "1.12.9",
"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).",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.12.8",
"version": "1.12.9",
"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).",
File diff suppressed because it is too large. Load diff
+135 -1
View File
@@ -16,6 +16,12 @@ export interface RuntimeConfig {
/** Raw trust-proxy directive (same domain as SNOWLUMA_WEBUI_TRUST_PROXY),
* consumed by the WebUI's client-ip resolver. '' = trust nobody. */
trustProxy?: string;
/** Aggregate cap for every managed file below the log root. */
logMaxTotalMb?: number;
/** Calendar-day retention. Zero disables date-based deletion. */
logRetainDays?: number;
/** Duplicate UIN-scoped lines into logs/<uin>/ in addition to the shared log. */
logPerUin?: boolean;
}
const CONFIG_DIR = 'config';
@@ -23,6 +29,13 @@ const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
const DEFAULT_WEBUI_PORT = 5099;
const DEFAULT_WEBUI_HOST = '0.0.0.0';
export const DEFAULT_LOG_MAX_TOTAL_MB = 1024;
export const DEFAULT_LOG_RETAIN_DAYS = 7;
export const DEFAULT_LOG_PER_UIN = false;
export const MAX_LOG_TOTAL_MB = Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024));
export const MAX_LOG_RETAIN_DAYS = Math.floor(
Number.MAX_SAFE_INTEGER / (24 * 60 * 60 * 1000),
);
/**
* Pure on-disk-object → typed config normalization (defaults + validation,
@@ -36,6 +49,21 @@ export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
webuiHost: normalizeHost(obj.webuiHost),
webuiTls: { enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false },
trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '',
logMaxTotalMb: normalizeRequiredInteger(
obj.logMaxTotalMb,
DEFAULT_LOG_MAX_TOTAL_MB,
1,
MAX_LOG_TOTAL_MB,
'logMaxTotalMb',
),
logRetainDays: normalizeRequiredInteger(
obj.logRetainDays,
DEFAULT_LOG_RETAIN_DAYS,
0,
MAX_LOG_RETAIN_DAYS,
'logRetainDays',
),
logPerUin: normalizeRequiredBool(obj.logPerUin, DEFAULT_LOG_PER_UIN, 'logPerUin'),
};
}
@@ -58,6 +86,28 @@ export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<Runt
const tp = env.SNOWLUMA_WEBUI_TRUST_PROXY;
if (typeof tp === 'string') out.trustProxy = tp;
const logMaxTotalMb = parseRequiredIntegerEnv(
env.SNOWLUMA_LOG_MAX_TOTAL_MB,
1,
MAX_LOG_TOTAL_MB,
'SNOWLUMA_LOG_MAX_TOTAL_MB',
);
if (logMaxTotalMb !== undefined) out.logMaxTotalMb = logMaxTotalMb;
const logRetainDays = parseRequiredIntegerEnv(
env.SNOWLUMA_LOG_RETAIN_DAYS,
0,
MAX_LOG_RETAIN_DAYS,
'SNOWLUMA_LOG_RETAIN_DAYS',
);
if (logRetainDays !== undefined) out.logRetainDays = logRetainDays;
const logPerUin = parseRequiredBoolEnv(
env.SNOWLUMA_LOG_PER_UIN,
'SNOWLUMA_LOG_PER_UIN',
);
if (logPerUin !== undefined) out.logPerUin = logPerUin;
return out;
}
@@ -109,7 +159,23 @@ function tryLoadRuntimeConfig(): Record<string, unknown> | null {
}
function saveRuntimeConfig(config: RuntimeConfig): void {
fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
const temporaryPath = `${RUNTIME_CONFIG_PATH}.tmp-${String(process.pid)}`;
try {
fs.writeFileSync(temporaryPath, JSON.stringify(config, null, 2), 'utf8');
fs.renameSync(temporaryPath, RUNTIME_CONFIG_PATH);
} catch (error) {
try {
fs.unlinkSync(temporaryPath);
} catch (cleanupError) {
if (!isErrnoCode(cleanupError, 'ENOENT')) {
throw new AggregateError(
[error, cleanupError],
'failed to persist runtime config and remove its temporary file',
);
}
}
throw error;
}
}
/** True when the raw on-disk object already matches the normalized config
@@ -122,6 +188,9 @@ function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): b
&& parsed.webuiHost === n.webuiHost
&& parsedTls === n.webuiTls?.enabled
&& parsed.trustProxy === n.trustProxy
&& parsed.logMaxTotalMb === n.logMaxTotalMb
&& parsed.logRetainDays === n.logRetainDays
&& parsed.logPerUin === n.logPerUin
);
}
@@ -155,6 +224,37 @@ function normalizePort(value: unknown, fallback: number): number {
return fallback;
}
function normalizeRequiredInteger(
value: unknown,
fallback: number,
min: number,
max: number,
field: string,
): number {
if (value === undefined) return fallback;
const n = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
if (
typeof n === 'number'
&& Number.isSafeInteger(n)
&& n >= min
&& n <= max
) {
return n;
}
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
}
function normalizeRequiredBool(
value: unknown,
fallback: boolean,
field: string,
): boolean {
if (value === undefined) return fallback;
const parsed = parseBoolValue(value);
if (parsed !== undefined) return parsed;
throw new TypeError(`${field} must be a boolean`);
}
function normalizeBool(value: unknown, fallback: boolean): boolean {
if (typeof value === 'boolean') return value;
if (typeof value === 'number') return value !== 0;
@@ -166,6 +266,40 @@ function normalizeBool(value: unknown, fallback: boolean): boolean {
return fallback;
}
function parseRequiredIntegerEnv(
raw: unknown,
min: number,
max: number,
field: string,
): number | undefined {
if (typeof raw !== 'string' || !raw.trim()) return undefined;
const n = Number(raw.trim());
if (Number.isSafeInteger(n) && n >= min && n <= max) return n;
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
}
function parseRequiredBoolEnv(raw: unknown, field: string): boolean | undefined {
if (typeof raw !== 'string' || !raw.trim()) return undefined;
const parsed = parseBoolValue(raw);
if (parsed !== undefined) return parsed;
throw new TypeError(`${field} must be a boolean`);
}
function parseBoolValue(raw: unknown): boolean | undefined {
if (typeof raw === 'boolean') return raw;
if (raw === 1) return true;
if (raw === 0) return false;
if (typeof raw !== 'string') return undefined;
const value = raw.trim().toLowerCase();
if (value === 'true' || value === '1' || value === 'yes' || value === 'on') return true;
if (value === 'false' || value === '0' || value === 'no' || value === 'off') return false;
return undefined;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isErrnoCode(error: unknown, code: string): boolean {
return error instanceof Error && 'code' in error && error.code === code;
}
+76 -2
View File
@@ -1,4 +1,6 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { normalizeRuntimeConfig, resolveRuntimeEnvOverrides } from '../src/runtime';
describe('normalizeRuntimeConfig', () => {
@@ -9,6 +11,9 @@ describe('normalizeRuntimeConfig', () => {
webuiHost: '0.0.0.0',
webuiTls: { enabled: false },
trustProxy: '',
logMaxTotalMb: 1024,
logRetainDays: 7,
logPerUin: false,
});
});
@@ -19,12 +24,18 @@ describe('normalizeRuntimeConfig', () => {
webuiHost: '127.0.0.1',
webuiTls: { enabled: true },
trustProxy: '1',
logMaxTotalMb: 2048,
logRetainDays: 0,
logPerUin: true,
})).toEqual({
webuiPort: 8080,
hookAutoLoad: true,
webuiHost: '127.0.0.1',
webuiTls: { enabled: true },
trustProxy: '1',
logMaxTotalMb: 2048,
logRetainDays: 0,
logPerUin: true,
});
});
@@ -41,6 +52,21 @@ describe('normalizeRuntimeConfig', () => {
expect(out.trustProxy).toBe('');
});
it('fails fast on invalid persisted log settings', () => {
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: 0 }))
.toThrow(/logMaxTotalMb/);
expect(() => normalizeRuntimeConfig({ logRetainDays: -1 }))
.toThrow(/logRetainDays/);
expect(() => normalizeRuntimeConfig({ logPerUin: 'maybe' }))
.toThrow(/logPerUin/);
expect(() => normalizeRuntimeConfig({ logPerUin: '' }))
.toThrow(/logPerUin/);
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: Number.MAX_SAFE_INTEGER }))
.toThrow(/logMaxTotalMb/);
expect(() => normalizeRuntimeConfig({ logRetainDays: Number.MAX_SAFE_INTEGER }))
.toThrow(/logRetainDays/);
});
it('coerces webuiTls.enabled loosely and trims a blank host to default', () => {
expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true });
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('0.0.0.0');
@@ -65,6 +91,39 @@ describe('resolveRuntimeEnvOverrides', () => {
})).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
});
it('parses log storage overrides including retainDays=0', () => {
expect(resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_MAX_TOTAL_MB: '4096',
SNOWLUMA_LOG_RETAIN_DAYS: '0',
SNOWLUMA_LOG_PER_UIN: '1',
})).toEqual({
logMaxTotalMb: 4096,
logRetainDays: 0,
logPerUin: true,
});
});
it('fails fast on invalid log storage overrides', () => {
expect(() => resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_MAX_TOTAL_MB: '0',
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
expect(() => resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_RETAIN_DAYS: '-1',
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
expect(() => resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_PER_UIN: 'maybe',
})).toThrow(/SNOWLUMA_LOG_PER_UIN/);
});
it('fails fast when converted log storage overrides would be unsafe', () => {
expect(() => resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_MAX_TOTAL_MB: String(Number.MAX_SAFE_INTEGER),
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
expect(() => resolveRuntimeEnvOverrides({
SNOWLUMA_LOG_RETAIN_DAYS: String(Number.MAX_SAFE_INTEGER),
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
});
it('ignores an out-of-range / non-numeric port env', () => {
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({});
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({});
@@ -88,11 +147,11 @@ describe('updateRuntimeConfig (fs)', () => {
delete process.env.SNOWLUMA_WEBUI_PORT;
});
afterEach(async () => {
const fs = await import('fs');
process.chdir(prevCwd);
if (prevPortEnv === undefined) delete process.env.SNOWLUMA_WEBUI_PORT;
else process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
fs.rmSync(dir, { recursive: true, force: true });
vi.restoreAllMocks();
});
it('merges a patch over on-disk values and persists normalized', async () => {
@@ -114,4 +173,19 @@ describe('updateRuntimeConfig (fs)', () => {
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
expect(onDisk.webuiPort).toBe(5099); // default on-disk, NOT the env 9999
});
it('keeps the previous runtime file intact when atomic replacement fails', async () => {
const { updateRuntimeConfig } = await import('../src/runtime');
updateRuntimeConfig({ logRetainDays: 7 });
const runtimePath = path.join('config', 'runtime.json');
const before = fs.readFileSync(runtimePath, 'utf8');
vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
throw Object.assign(new Error('disk replacement failed'), { code: 'EIO' });
});
expect(() => updateRuntimeConfig({ logRetainDays: 0 }))
.toThrow(/disk replacement failed/);
expect(fs.readFileSync(runtimePath, 'utf8')).toBe(before);
expect(fs.readdirSync('config').filter((name) => name.includes('.tmp-'))).toEqual([]);
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.12.8",
"version": "1.12.9",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
+36 -2
View File
@@ -213,8 +213,42 @@ export class GroupAlbumApi {
// OneBot compatibility shape used by get_group_album_list.
async list(groupId: number): Promise<GroupAlbumList> {
const result = await this.fetchAlbumList(groupId, '');
return result.albumList.map(toLegacyAlbum);
const albumList: GroupAlbumList = [];
const seenCursors = new Set<string>();
let attachInfo = '';
let page = 0;
while (true) {
const result = await this.fetchAlbumList(groupId, attachInfo);
page += 1;
albumList.push(...result.albumList.map(toLegacyAlbum));
if (!result.hasMore) {
log.debug(
'get complete album list: group=%d pages=%d albums=%d',
groupId,
page,
albumList.length,
);
return albumList;
}
const nextAttachInfo = result.attachInfo;
if (!nextAttachInfo) {
throw new Error(
`get group album list pagination failed: group=${groupId} page=${page} `
+ 'hasMore=true but cursor is empty',
);
}
if (seenCursors.has(nextAttachInfo)) {
throw new Error(
`get group album list pagination failed: group=${groupId} repeated cursor at page ${page}`,
);
}
seenCursors.add(nextAttachInfo);
attachInfo = nextAttachInfo;
}
}
// 上传图片到现有相册(HTTP 分片上传)。
+12 -1
View File
@@ -1,6 +1,12 @@
import { HookManager } from '@snowluma/bridge';
import { configureFileTransport } from '@snowluma/common/log-file-transport';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import { loadRuntimeConfig } from '@snowluma/common/runtime';
import {
DEFAULT_LOG_MAX_TOTAL_MB,
DEFAULT_LOG_PER_UIN,
DEFAULT_LOG_RETAIN_DAYS,
loadRuntimeConfig,
} from '@snowluma/common/runtime';
import { OneBotManager } from '@snowluma/onebot/manager';
import { migrateGlobalSettings } from '@snowluma/onebot/global-config';
import { cleanupInvalidPerUinConfigs } from '@snowluma/onebot/config';
@@ -28,6 +34,11 @@ process.on('uncaughtException', (error) => {
});
async function main() {
await configureFileTransport({
maxTotalMb: runtimeConfig.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB,
retainDays: runtimeConfig.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS,
perUinEnabled: runtimeConfig.logPerUin ?? DEFAULT_LOG_PER_UIN,
});
log.info('SnowLuma starting');
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
+57
View File
@@ -1,6 +1,11 @@
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
import {
clearManagedLogs,
configureFileTransport,
getLogStorageStatus,
} from '@snowluma/common/log-file-transport';
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
import {
loadOneBotConfig,
@@ -9,6 +14,10 @@ import {
} from '@snowluma/onebot/config';
import { loadGlobalSettings, saveGlobalSettings } from '@snowluma/onebot/global-config';
import type { OneBotManager } from '@snowluma/onebot/manager';
import {
clearInactiveStreamStorage,
snapshotStreamStorage,
} from '@snowluma/onebot/stream-storage';
import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types';
import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime';
import { execSync } from 'child_process';
@@ -55,6 +64,9 @@ import {
import { getUpdateInfo } from './update-check';
import { loadNotificationsConfig, saveNotificationsConfig } from '../notifications/config';
import type { NotificationManager } from '../notifications/manager';
import { StorageManagementService } from './storage-management';
import { registerStorageRoutes } from './storage-routes';
import { LogStorageSettingsManager } from './storage-settings';
const log = createLogger('WebUI');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -524,6 +536,27 @@ export async function initWebUI(
}
const app = new Hono();
const storageManagement = new StorageManagementService({
dataDir: 'data',
getLogStatus: getLogStorageStatus,
clearLogs: clearManagedLogs,
temporary: {
snapshot: snapshotStreamStorage,
clearInactive: clearInactiveStreamStorage,
},
// Connection statuses include active and still-retiring generations.
// A retiring instance may still hold SQLite handles after disappearing
// from getInstances(), so it must continue to block destructive cleanup.
listOnlineAccounts: () => oneBotManager.getConnectionStatuses()
.map((account) => ({ uin: account.uin, nickname: account.nickname })),
});
const logStorageSettings = new LogStorageSettingsManager({
readPersisted: readRuntimeConfig,
readEnvOverrides: () => resolveRuntimeEnvOverrides(process.env),
readEffective: getLogStorageStatus,
persist: updateRuntimeConfig,
apply: configureFileTransport,
});
// ─── Anti-indexing ───────────────────────────────────────────────────────
// The WebUI is an admin surface that has no business showing up in
@@ -889,6 +922,30 @@ export async function initWebUI(
});
});
registerStorageRoutes(app, {
storage: storageManagement,
settings: logStorageSettings,
audit: (event) => {
log.info(
'storage cleanup scope=%s accountScope=%s category=%s uin=%s deletedFiles=%d freedBytes=%d failures=%d',
event.scope,
event.accountScope,
event.category ?? '-',
event.uin ?? '-',
event.deletedFiles,
event.freedBytes,
event.failureCount,
);
},
reportError: (operation, error) => {
log.error(
'%s failed: %s',
operation,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
},
});
app.post('/api/system/tls/cert', async (c) => {
let body: unknown;
try {
@@ -0,0 +1,333 @@
import fs from 'node:fs';
import path from 'node:path';
import type {
LogCleanupResult,
LogStorageStatus,
} from '@snowluma/common/log-file-transport';
import { isRealUin } from '@snowluma/common/uin';
export interface TemporaryStorageSnapshot {
totalBytes: number;
fileCount: number;
activeItemCount: number;
}
export interface TemporaryCleanupResult {
deletedFiles: number;
freedBytes: number;
skippedActiveItems: number;
failures: Array<{ item: string; message: string }>;
}
export interface TemporaryStorageAdapter {
snapshot(): TemporaryStorageSnapshot;
clearInactive(): TemporaryCleanupResult;
}
export interface OnlineStorageAccount {
uin: string;
nickname: string;
}
export interface AccountStorageSnapshot {
uin: string;
nickname?: string;
online: boolean;
messagesBytes: number;
mediaBytes: number;
reactionsBytes: number;
totalBytes: number;
}
export type PublicLogStorageStatus = Omit<LogStorageStatus, 'directory'>;
export function publicLogStorageStatus(status: LogStorageStatus): PublicLogStorageStatus {
const { directory, ...publicStatus } = status;
if (!publicStatus.lastError) return publicStatus;
return {
...publicStatus,
lastError: redactFilesystemPath(publicStatus.lastError, directory, '[日志目录]'),
};
}
export interface PublicLogCleanupResult extends Omit<LogCleanupResult, 'status'> {
status: PublicLogStorageStatus;
}
export interface StorageSnapshot {
logs: PublicLogStorageStatus;
temporary: TemporaryStorageSnapshot;
accounts: AccountStorageSnapshot[];
totals: {
logsBytes: number;
temporaryBytes: number;
accountDataBytes: number;
managedBytes: number;
};
}
export type AccountStorageCategory = 'messages' | 'media' | 'reactions';
export interface AccountDataCleanupResult {
category: AccountStorageCategory;
uins: string[];
deletedFiles: number;
freedBytes: number;
failures: Array<{ uin: string; file: string; message: string }>;
}
export class StorageManagementInputError extends Error {
constructor(message: string) {
super(message);
this.name = 'StorageManagementInputError';
}
}
export class StorageAccountOnlineError extends Error {
constructor(readonly uins: string[]) {
super(`account data cleanup requires offline accounts: ${uins.join(', ')}`);
this.name = 'StorageAccountOnlineError';
}
}
export interface StorageManagementDependencies {
dataDir: string;
getLogStatus(): LogStorageStatus;
clearLogs(): Promise<LogCleanupResult>;
temporary: TemporaryStorageAdapter;
listOnlineAccounts(): OnlineStorageAccount[];
}
const DATABASE_FILES = {
messages: ['messages.db', 'messages.db-wal', 'messages.db-shm', 'messages.db-journal'],
media: ['media.db', 'media.db-wal', 'media.db-shm', 'media.db-journal'],
reactions: ['reactions.db', 'reactions.db-wal', 'reactions.db-shm', 'reactions.db-journal'],
} as const;
export class StorageManagementService {
constructor(private readonly deps: StorageManagementDependencies) {}
snapshot(): StorageSnapshot {
const logStatus = this.deps.getLogStatus();
const logs = publicLogStorageStatus(logStatus);
const temporary = this.deps.temporary.snapshot();
const accounts = this.accountSnapshots();
const accountDataBytes = accounts.reduce((sum, account) => sum + account.totalBytes, 0);
return {
logs,
temporary,
accounts,
totals: {
logsBytes: logs.totalBytes,
temporaryBytes: temporary.totalBytes,
accountDataBytes,
managedBytes: logs.totalBytes + temporary.totalBytes + accountDataBytes,
},
};
}
async clearLogs(): Promise<PublicLogCleanupResult> {
const result = await this.deps.clearLogs();
return {
...result,
failures: result.failures.map((failure) => ({
...failure,
message: redactFilesystemPath(
failure.message,
result.status.directory,
'[日志目录]',
),
})),
status: publicLogStorageStatus(result.status),
};
}
clearTemporary(): TemporaryCleanupResult {
return this.deps.temporary.clearInactive();
}
clearAccountData(category: string, uin: string): AccountDataCleanupResult {
const validatedCategory = validateAccountStorageCategory(category);
if (!isRealUin(uin)) {
throw new StorageManagementInputError(`invalid UIN: ${uin}`);
}
return this.clearAccountDataForUins(validatedCategory, [uin]);
}
clearAllAccountData(category: string): AccountDataCleanupResult {
const validatedCategory = validateAccountStorageCategory(category);
const uins = listDirectoryNames(this.deps.dataDir)
.filter((name) => isRealUin(name))
.sort((a, b) => Number(a) - Number(b));
return this.clearAccountDataForUins(validatedCategory, uins);
}
private clearAccountDataForUins(
category: AccountStorageCategory,
uins: string[],
): AccountDataCleanupResult {
const hasManagedRoot = assertManagedDataRootOrMissing(this.deps.dataDir);
const onlineUins = new Set(
this.deps.listOnlineAccounts()
.map((account) => account.uin)
.filter((uin) => isRealUin(uin)),
);
const blockedUins = uins.filter((uin) => onlineUins.has(uin));
if (blockedUins.length > 0) throw new StorageAccountOnlineError(blockedUins);
const failures: AccountDataCleanupResult['failures'] = [];
let deletedFiles = 0;
let freedBytes = 0;
if (!hasManagedRoot) {
return { category, uins, deletedFiles, freedBytes, failures };
}
for (const uin of uins) {
const dir = path.join(this.deps.dataDir, uin);
if (!isManagedDirectory(dir)) continue;
for (const name of DATABASE_FILES[category]) {
const filePath = path.join(dir, name);
let bytes: number;
try {
const stat = fs.lstatSync(filePath);
if (!stat.isFile()) continue;
bytes = stat.size;
} catch (error) {
if (isMissing(error)) continue;
failures.push({
uin,
file: name,
message: redactFilesystemPath(
errorMessage(error),
filePath,
'[账号数据库]',
),
});
continue;
}
try {
fs.unlinkSync(filePath);
deletedFiles += 1;
freedBytes += bytes;
} catch (error) {
if (isMissing(error)) continue;
failures.push({
uin,
file: name,
message: redactFilesystemPath(
errorMessage(error),
filePath,
'[账号数据库]',
),
});
}
}
}
return { category, uins, deletedFiles, freedBytes, failures };
}
private accountSnapshots(): AccountStorageSnapshot[] {
const online = new Map(
this.deps.listOnlineAccounts()
.filter((account) => isRealUin(account.uin))
.map((account) => [account.uin, account.nickname]),
);
const uins = new Set(online.keys());
for (const name of listDirectoryNames(this.deps.dataDir)) {
if (isRealUin(name)) uins.add(name);
}
return [...uins]
.sort((a, b) => Number(a) - Number(b))
.map((uin) => {
const dir = path.join(this.deps.dataDir, uin);
const managedDirectory = isManagedDirectory(dir);
const messagesBytes = managedDirectory
? sumAllowlistedFiles(dir, DATABASE_FILES.messages)
: 0;
const mediaBytes = managedDirectory
? sumAllowlistedFiles(dir, DATABASE_FILES.media)
: 0;
const reactionsBytes = managedDirectory
? sumAllowlistedFiles(dir, DATABASE_FILES.reactions)
: 0;
const nickname = online.get(uin);
return {
uin,
...(nickname ? { nickname } : {}),
online: online.has(uin),
messagesBytes,
mediaBytes,
reactionsBytes,
totalBytes: messagesBytes + mediaBytes + reactionsBytes,
};
});
}
}
function listDirectoryNames(dir: string): string[] {
if (!assertManagedDataRootOrMissing(dir)) return [];
try {
return fs.readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name);
} catch (error) {
if (isMissing(error)) return [];
throw error;
}
}
function assertManagedDataRootOrMissing(dir: string): boolean {
try {
const stat = fs.lstatSync(dir);
if (!stat.isDirectory()) {
throw new Error('managed data root must be a real directory');
}
return true;
} catch (error) {
if (isMissing(error)) return false;
throw error;
}
}
function sumAllowlistedFiles(dir: string, names: readonly string[]): number {
let total = 0;
for (const name of names) {
const filePath = path.join(dir, name);
try {
const stat = fs.lstatSync(filePath);
if (stat.isFile()) total += stat.size;
} catch (error) {
if (!isMissing(error)) throw error;
}
}
return total;
}
function isMissing(error: unknown): boolean {
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
}
function isManagedDirectory(dir: string): boolean {
try {
return fs.lstatSync(dir).isDirectory();
} catch (error) {
if (isMissing(error)) return false;
throw error;
}
}
function validateAccountStorageCategory(value: string): AccountStorageCategory {
if (value === 'messages' || value === 'media' || value === 'reactions') return value;
throw new StorageManagementInputError(`unsupported account storage category: ${value}`);
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function redactFilesystemPath(message: string, filePath: string, label: string): string {
const absolute = path.resolve(filePath);
return message
.split(absolute).join(label)
.split(filePath).join(label);
}
+317
View File
@@ -0,0 +1,317 @@
import { isRealUin } from '@snowluma/common/uin';
import type { Hono } from 'hono';
import {
StorageAccountOnlineError,
StorageManagementInputError,
type AccountDataCleanupResult,
type AccountStorageCategory,
type PublicLogCleanupResult,
type StorageManagementService,
type StorageSnapshot,
type TemporaryCleanupResult,
} from './storage-management';
import {
StorageSettingsInputError,
StorageSettingsLockedError,
StorageSettingsTransactionError,
type LogStorageSettingsManager,
} from './storage-settings';
export const ALL_ACCOUNTS_CONFIRMATION = '清理全部账号';
type StorageCleanupRequest =
| { scope: 'logs' }
| { scope: 'temporary' }
| { scope: 'account'; category: AccountStorageCategory; uin: string }
| {
scope: 'allAccounts';
category: AccountStorageCategory;
confirmation: typeof ALL_ACCOUNTS_CONFIRMATION;
};
type StorageCleanupResult =
| PublicLogCleanupResult
| TemporaryCleanupResult
| AccountDataCleanupResult;
export interface StorageCleanupAuditEvent {
scope: StorageCleanupRequest['scope'];
accountScope: 'global' | 'single' | 'all';
category?: AccountStorageCategory;
uin?: string;
deletedFiles: number;
freedBytes: number;
failureCount: number;
}
export interface LastStorageCleanup extends StorageCleanupAuditEvent {
at: string;
skippedActiveItems?: number;
failures: Array<{ item: string; message: string }>;
}
export interface StorageRouteDependencies {
storage: Pick<
StorageManagementService,
'snapshot'
| 'clearLogs'
| 'clearTemporary'
| 'clearAccountData'
| 'clearAllAccountData'
>;
settings: Pick<LogStorageSettingsManager, 'read' | 'update'>;
audit(event: StorageCleanupAuditEvent): void;
reportError(operation: string, error: unknown): void;
now?: () => Date;
}
export function registerStorageRoutes(app: Hono, deps: StorageRouteDependencies): void {
let lastCleanup: LastStorageCleanup | null = null;
let mutationQueue: Promise<void> = Promise.resolve();
const serializeMutation = <T>(operation: () => Promise<T>): Promise<T> => {
const result = mutationQueue.then(operation);
mutationQueue = result.then(
() => undefined,
() => undefined,
);
return result;
};
app.get('/api/system/storage', (c) => {
try {
return c.json({
settings: deps.settings.read(),
snapshot: deps.storage.snapshot(),
lastCleanup,
});
} catch (error) {
deps.reportError('read storage snapshot', error);
return c.json({ success: false, message: '读取存储信息失败,请检查服务器日志' }, 500);
}
});
app.post('/api/system/storage/settings', async (c) => {
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
let result: Awaited<ReturnType<LogStorageSettingsManager['update']>>;
try {
result = await serializeMutation(() => deps.settings.update(body));
} catch (error) {
if (error instanceof StorageSettingsInputError) {
return c.json({ success: false, message: error.message }, 400);
}
if (error instanceof StorageSettingsLockedError) {
return c.json({
success: false,
message: '这些设置已由环境变量锁定',
lockedFields: error.fields,
}, 409);
}
deps.reportError('update log storage settings', error);
if (error instanceof StorageSettingsTransactionError) {
deps.reportError('update log storage settings operation', error.operationError);
error.rollbackErrors.forEach((rollbackError, index) => {
deps.reportError(
`rollback log storage settings step=${String(index + 1)}`,
rollbackError,
);
});
return c.json({
success: false,
message: error.rollbackErrors.length > 0
? '保存失败且回滚不完整,请立即检查服务器日志'
: '保存失败,原设置已恢复',
}, 500);
}
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
}
try {
return c.json({
success: true,
settings: result.settings,
status: result.status,
snapshot: deps.storage.snapshot(),
});
} catch (error) {
deps.reportError('refresh storage snapshot after settings update', error);
return c.json({
success: false,
message: '设置已生效,但刷新存储统计失败,请检查服务器日志',
settings: result.settings,
status: result.status,
}, 500);
}
});
app.post('/api/system/storage/cleanup', async (c) => {
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
let request: StorageCleanupRequest;
try {
request = parseCleanupRequest(body);
} catch (error) {
const message = error instanceof Error ? error.message : '请求格式错误';
return c.json({ success: false, message }, 400);
}
let cleanup: StorageCleanupResult;
try {
cleanup = await serializeMutation(() => executeCleanup(deps.storage, request));
} catch (error) {
if (error instanceof StorageAccountOnlineError) {
return c.json({
success: false,
message: '账号在线,必须先下线后才能清理数据库',
onlineUins: error.uins,
}, 409);
}
if (error instanceof StorageManagementInputError) {
return c.json({ success: false, message: error.message }, 400);
}
deps.reportError(`clean storage scope=${request.scope}`, error);
return c.json({ success: false, message: '清理失败,请检查服务器日志' }, 500);
}
const auditEvent: StorageCleanupAuditEvent = {
scope: request.scope,
accountScope: accountScope(request),
...('category' in request ? { category: request.category } : {}),
...(request.scope === 'account' ? { uin: request.uin } : {}),
deletedFiles: cleanup.deletedFiles,
freedBytes: cleanup.freedBytes,
failureCount: cleanup.failures.length,
};
deps.audit(auditEvent);
for (const failure of cleanup.failures) {
deps.reportError(
`clean storage scope=${request.scope} item=${cleanupFailureItem(failure)}`,
new Error(failure.message),
);
}
lastCleanup = {
at: (deps.now?.() ?? new Date()).toISOString(),
...auditEvent,
...('skippedActiveItems' in cleanup
? { skippedActiveItems: cleanup.skippedActiveItems }
: {}),
failures: cleanup.failures.map((failure) => ({
item: cleanupFailureItem(failure),
message: failure.message,
})),
};
let snapshot: StorageSnapshot;
try {
snapshot = deps.storage.snapshot();
} catch (error) {
deps.reportError(`refresh storage snapshot after cleanup scope=${request.scope}`, error);
return c.json({
success: false,
message: '清理已执行,但刷新存储统计失败,请检查服务器日志',
scope: request.scope,
cleanup,
lastCleanup,
}, 500);
}
const success = cleanup.failures.length === 0;
return c.json({
success,
...(success ? {} : { message: '部分文件清理失败,请检查失败明细' }),
scope: request.scope,
cleanup,
snapshot,
lastCleanup,
}, success ? 200 : 500);
});
}
function parseCleanupRequest(body: unknown): StorageCleanupRequest {
if (!isObject(body) || typeof body.scope !== 'string') {
throw new StorageManagementInputError('scope is required');
}
if (body.scope === 'logs' || body.scope === 'temporary') {
assertExactKeys(body, ['scope']);
return { scope: body.scope };
}
if (body.scope === 'account') {
assertExactKeys(body, ['scope', 'category', 'uin']);
const category = parseCategory(body.category);
if (typeof body.uin !== 'string' || !isRealUin(body.uin)) {
throw new StorageManagementInputError('invalid UIN');
}
return { scope: 'account', category, uin: body.uin };
}
if (body.scope === 'allAccounts') {
assertExactKeys(body, ['scope', 'category', 'confirmation']);
const category = parseCategory(body.category);
if (body.confirmation !== ALL_ACCOUNTS_CONFIRMATION) {
throw new StorageManagementInputError('all-account cleanup requires confirmation');
}
return {
scope: 'allAccounts',
category,
confirmation: ALL_ACCOUNTS_CONFIRMATION,
};
}
throw new StorageManagementInputError(`unsupported cleanup scope: ${body.scope}`);
}
async function executeCleanup(
storage: StorageRouteDependencies['storage'],
request: StorageCleanupRequest,
): Promise<StorageCleanupResult> {
if (request.scope === 'logs') return storage.clearLogs();
if (request.scope === 'temporary') return storage.clearTemporary();
if (request.scope === 'account') {
return storage.clearAccountData(request.category, request.uin);
}
return storage.clearAllAccountData(request.category);
}
function parseCategory(value: unknown): AccountStorageCategory {
if (value === 'messages' || value === 'media' || value === 'reactions') return value;
throw new StorageManagementInputError('unsupported account storage category');
}
function assertExactKeys(body: Record<string, unknown>, allowed: string[]): void {
const allowedSet = new Set(allowed);
const unknown = Object.keys(body).filter((key) => !allowedSet.has(key));
const missing = allowed.filter((key) => !(key in body));
if (unknown.length > 0 || missing.length > 0) {
throw new StorageManagementInputError('cleanup request has unexpected or missing fields');
}
}
function accountScope(request: StorageCleanupRequest): StorageCleanupAuditEvent['accountScope'] {
if (request.scope === 'account') return 'single';
if (request.scope === 'allAccounts') return 'all';
return 'global';
}
function cleanupFailureItem(
failure: StorageCleanupResult['failures'][number],
): string {
if ('uin' in failure) return `${failure.uin}/${failure.file}`;
if ('file' in failure) return failure.file;
return failure.item;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+312
View File
@@ -0,0 +1,312 @@
import type {
LogStoragePolicy,
LogStorageStatus,
} from '@snowluma/common/log-file-transport';
import {
DEFAULT_LOG_MAX_TOTAL_MB,
DEFAULT_LOG_PER_UIN,
DEFAULT_LOG_RETAIN_DAYS,
MAX_LOG_RETAIN_DAYS,
MAX_LOG_TOTAL_MB,
type RuntimeConfig,
} from '@snowluma/common/runtime';
import {
publicLogStorageStatus,
type PublicLogStorageStatus,
} from './storage-management';
export type LogStorageSettingsField =
| 'logMaxTotalMb'
| 'logRetainDays'
| 'logPerUin';
export interface LogStorageSettings {
logMaxTotalMb: number;
logRetainDays: number;
logPerUin: boolean;
}
export interface LogStorageSettingsState {
saved: LogStorageSettings;
effective: LogStorageSettings;
envOverrides: LogStorageSettingsField[];
}
export interface LogStorageSettingsUpdateResult {
settings: LogStorageSettingsState;
status: PublicLogStorageStatus;
}
export class StorageSettingsInputError extends Error {
constructor(message: string) {
super(message);
this.name = 'StorageSettingsInputError';
}
}
export class StorageSettingsLockedError extends Error {
constructor(readonly fields: LogStorageSettingsField[]) {
super(`settings are locked by environment variables: ${fields.join(', ')}`);
this.name = 'StorageSettingsLockedError';
}
}
export class StorageSettingsTransactionError extends Error {
constructor(
message: string,
readonly operationError: unknown,
readonly rollbackErrors: unknown[],
) {
super(message, { cause: operationError });
this.name = 'StorageSettingsTransactionError';
}
}
export interface LogStorageSettingsDependencies {
readPersisted(): RuntimeConfig;
readEnvOverrides(): Partial<RuntimeConfig>;
readEffective(): LogStorageStatus;
persist(patch: Partial<RuntimeConfig>): RuntimeConfig;
apply(policy: LogStoragePolicy): Promise<LogStorageStatus>;
}
const SETTINGS_FIELDS: LogStorageSettingsField[] = [
'logMaxTotalMb',
'logRetainDays',
'logPerUin',
];
const SETTINGS_FIELD_SET = new Set<string>(SETTINGS_FIELDS);
export class LogStorageSettingsManager {
private updateQueue: Promise<void> = Promise.resolve();
constructor(private readonly deps: LogStorageSettingsDependencies) {}
read(): LogStorageSettingsState {
return settingsState(
this.deps.readPersisted(),
this.deps.readEnvOverrides(),
settingsFromStatus(this.deps.readEffective()),
);
}
update(body: unknown): Promise<LogStorageSettingsUpdateResult> {
const operation = this.updateQueue.then(() => this.performUpdate(body));
this.updateQueue = operation.then(
() => undefined,
() => undefined,
);
return operation;
}
private async performUpdate(body: unknown): Promise<LogStorageSettingsUpdateResult> {
const patch = coerceLogStorageSettingsPatch(body);
const previousRuntime = this.deps.readPersisted();
const envOverrides = this.deps.readEnvOverrides();
const previous = settingsState(
previousRuntime,
envOverrides,
settingsFromStatus(this.deps.readEffective()),
);
const locked = SETTINGS_FIELDS.filter(
(field) => field in patch && field in envOverrides,
);
if (locked.length > 0) throw new StorageSettingsLockedError(locked);
const nextSaved = { ...previous.saved, ...patch };
const nextEffective = { ...previous.effective, ...patch };
const previousPolicy = toPolicy(previous.effective);
const nextPolicy = toPolicy(nextEffective);
let status: LogStorageStatus;
try {
status = await this.deps.apply(nextPolicy);
assertApplied(status, nextPolicy);
} catch (error) {
const rollbackErrors = await this.rollbackRuntime(previousPolicy);
throw new StorageSettingsTransactionError(
rollbackErrors.length > 0
? 'failed to apply log settings and runtime rollback was incomplete'
: 'failed to apply log settings; runtime state was rolled back',
error,
rollbackErrors,
);
}
let persistedRuntime: RuntimeConfig;
try {
persistedRuntime = this.deps.persist(patch);
assertPersistedSettings(persistedRuntime, nextSaved);
} catch (error) {
const rollbackErrors = await this.rollbackAll(previousPolicy, previousRuntime);
throw new StorageSettingsTransactionError(
rollbackErrors.length > 0
? 'failed to persist log settings and rollback was incomplete'
: 'failed to persist log settings; previous settings were restored',
error,
rollbackErrors,
);
}
return {
settings: settingsState(
persistedRuntime,
envOverrides,
settingsFromStatus(status),
),
status: publicLogStorageStatus(status),
};
}
private async rollbackRuntime(policy: LogStoragePolicy): Promise<unknown[]> {
try {
const status = await this.deps.apply(policy);
assertApplied(status, policy);
return [];
} catch (error) {
return [error];
}
}
private async rollbackAll(
policy: LogStoragePolicy,
runtime: RuntimeConfig,
): Promise<unknown[]> {
const errors = await this.rollbackRuntime(policy);
try {
this.deps.persist(runtime);
} catch (error) {
errors.push(error);
}
return errors;
}
}
function coerceLogStorageSettingsPatch(body: unknown): Partial<LogStorageSettings> {
if (!isObject(body)) throw new StorageSettingsInputError('body must be an object');
const keys = Object.keys(body);
if (keys.length === 0) throw new StorageSettingsInputError('at least one setting is required');
const unknown = keys.filter((key) => !SETTINGS_FIELD_SET.has(key));
if (unknown.length > 0) {
throw new StorageSettingsInputError(`unknown setting: ${unknown.join(', ')}`);
}
const patch: Partial<LogStorageSettings> = {};
if ('logMaxTotalMb' in body) {
const value = body.logMaxTotalMb;
if (
typeof value !== 'number'
|| !Number.isSafeInteger(value)
|| value < 1
|| value > MAX_LOG_TOTAL_MB
) {
throw new StorageSettingsInputError(
`logMaxTotalMb must be an integer in 1..${MAX_LOG_TOTAL_MB}`,
);
}
patch.logMaxTotalMb = value;
}
if ('logRetainDays' in body) {
const value = body.logRetainDays;
if (
typeof value !== 'number'
|| !Number.isSafeInteger(value)
|| value < 0
|| value > MAX_LOG_RETAIN_DAYS
) {
throw new StorageSettingsInputError(
`logRetainDays must be an integer in 0..${MAX_LOG_RETAIN_DAYS}`,
);
}
patch.logRetainDays = value;
}
if ('logPerUin' in body) {
if (typeof body.logPerUin !== 'boolean') {
throw new StorageSettingsInputError('logPerUin must be a boolean');
}
patch.logPerUin = body.logPerUin;
}
return patch;
}
function settingsState(
runtime: RuntimeConfig,
envOverrides: Partial<RuntimeConfig>,
liveEffective?: LogStorageSettings,
): LogStorageSettingsState {
const saved = settingsFromRuntime(runtime);
const envOverridesList = SETTINGS_FIELDS.filter((field) => field in envOverrides);
const effective = liveEffective ?? {
...saved,
...settingsPatchFromRuntime(envOverrides),
};
return { saved, effective, envOverrides: envOverridesList };
}
function settingsFromStatus(status: LogStorageStatus): LogStorageSettings {
const maxTotalMb = status.maxTotalBytes / (1024 * 1024);
if (!Number.isSafeInteger(maxTotalMb)) {
throw new Error('live log storage limit is not an integer number of megabytes');
}
return {
logMaxTotalMb: maxTotalMb,
logRetainDays: status.retainDays,
logPerUin: status.perUinEnabled,
};
}
function settingsFromRuntime(runtime: RuntimeConfig): LogStorageSettings {
return {
logMaxTotalMb: runtime.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB,
logRetainDays: runtime.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS,
logPerUin: runtime.logPerUin ?? DEFAULT_LOG_PER_UIN,
};
}
function settingsPatchFromRuntime(runtime: Partial<RuntimeConfig>): Partial<LogStorageSettings> {
const patch: Partial<LogStorageSettings> = {};
if (runtime.logMaxTotalMb !== undefined) patch.logMaxTotalMb = runtime.logMaxTotalMb;
if (runtime.logRetainDays !== undefined) patch.logRetainDays = runtime.logRetainDays;
if (runtime.logPerUin !== undefined) patch.logPerUin = runtime.logPerUin;
return patch;
}
function toPolicy(settings: LogStorageSettings): LogStoragePolicy {
return {
maxTotalMb: settings.logMaxTotalMb,
retainDays: settings.logRetainDays,
perUinEnabled: settings.logPerUin,
};
}
function assertApplied(status: LogStorageStatus, policy: LogStoragePolicy): void {
const expectedBytes = policy.maxTotalMb * 1024 * 1024;
if (
status.state === 'warning'
|| status.state === 'degraded'
|| status.lastError !== undefined
|| status.maxTotalBytes !== expectedBytes
|| status.retainDays !== policy.retainDays
|| status.perUinEnabled !== policy.perUinEnabled
) {
throw new Error(status.lastError ?? 'log storage policy did not become effective');
}
}
function assertPersistedSettings(
runtime: RuntimeConfig,
expected: LogStorageSettings,
): void {
const actual = settingsFromRuntime(runtime);
if (
actual.logMaxTotalMb !== expected.logMaxTotalMb
|| actual.logRetainDays !== expected.logRetainDays
|| actual.logPerUin !== expected.logPerUin
) {
throw new Error('persisted log storage settings do not match the requested values');
}
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
@@ -108,6 +108,98 @@ describe('apis/group-album', () => {
}]);
});
it('fetches every AlbumService page for the legacy album list action', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<GetAlbumListResponse>({
data: {
albumList: [{
albumId: 'album-1',
name: '第一页',
createTime: 1n,
uploadNumber: 1n,
}],
attachInfo: 'next-cursor',
hasMore: true,
},
})),
})
.mockResolvedValueOnce({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<GetAlbumListResponse>({
data: {
albumList: [{
albumId: 'album-2',
name: '第二页',
createTime: 2n,
uploadNumber: 2n,
}],
hasMore: false,
},
})),
});
const result = await new GroupAlbumApi(bridge as never).list(12345);
expect(result.map((album) => album.id)).toEqual(['album-1', 'album-2']);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
const secondRequest = protobuf_decode<GroupAlbumListRequestWireOracle>(
bridge.sendRawPacket.mock.calls[1]![1],
);
expect(secondRequest.data?.cursor).toBe('next-cursor');
});
it('rejects a legacy album page that claims more data without a cursor', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<GetAlbumListResponse>({
data: {
albumList: [],
hasMore: true,
},
})),
});
await expect(new GroupAlbumApi(bridge as never).list(12345))
.rejects.toThrow('hasMore=true but cursor is empty');
});
it('rejects a repeated AlbumService cursor instead of looping or truncating', async () => {
const bridge = mockBridge();
const repeatedPage = {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<GetAlbumListResponse>({
data: {
albumList: [],
attachInfo: 'same-cursor',
hasMore: true,
},
})),
};
bridge.sendRawPacket
.mockResolvedValueOnce(repeatedPage)
.mockResolvedValueOnce(repeatedPage);
await expect(new GroupAlbumApi(bridge as never).list(12345))
.rejects.toThrow('repeated cursor at page 2');
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
});
it('returns the native AlbumService cursor and creator fields for get_qun_album_list', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce({
+279 -1
View File
@@ -13,7 +13,9 @@ 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<string, string | undefined> = {};
@@ -35,7 +37,9 @@ beforeEach(() => {
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',
});
});
@@ -84,6 +88,41 @@ describe('FileTransport', () => {
expect(split).toBeDefined();
});
it('keeps the whole managed log tree within the aggregate byte limit', async () => {
const t = new FileTransport();
const oneKB = 'x'.repeat(1023); // +1 byte newline = 1024
for (let i = 0; i < 4096; i++) t.write(oneKB);
await t.close();
const totalBytes = listLogFiles(tmpDir)
.map((name) => fs.statSync(path.join(tmpDir, name)).size)
.reduce((sum, bytes) => sum + bytes, 0);
expect(totalBytes).toBeLessThanOrEqual(2 * 1024 * 1024);
});
it('enters one observable degraded state instead of retrying every dropped line', async () => {
setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '1' });
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
const t = new FileTransport();
const oneKB = 'x'.repeat(1023);
for (let i = 0; i < 1024; i++) t.write(oneKB);
for (let i = 0; i < 10; i++) t.write('dropped');
expect(t.getStorageStatus()).toMatchObject({
state: 'degraded',
maxTotalBytes: 1024 * 1024,
droppedLines: 10,
});
const quotaErrors = stderr.mock.calls
.map(([message]) => String(message))
.filter((message) => message.includes('no closed log can be reclaimed'));
expect(quotaErrors).toHaveLength(1);
await t.close();
stderr.mockRestore();
});
it('opens a new file when the day rolls over mid-process', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date(2026, 4, 18, 23, 59, 0));
@@ -112,6 +151,162 @@ describe('FileTransport', () => {
expect(fs.existsSync(stalePath)).toBe(false);
});
it('runs retention again after a writer closes during rotation or shutdown', async () => {
const t = new FileTransport();
t.write('open the active writer');
const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log');
fs.writeFileSync(stalePath, 'stale\n');
await t.close();
expect(fs.existsSync(stalePath)).toBe(false);
});
it('retainDays=0 disables date cleanup while keeping the byte limit active', async () => {
setEnv({ SNOWLUMA_LOG_RETAIN_DAYS: '0' });
const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log');
fs.writeFileSync(stalePath, 'stale\n');
const t = new FileTransport();
await t.close();
expect(fs.existsSync(stalePath)).toBe(true);
expect(t.getStorageStatus().maxTotalBytes).toBe(2 * 1024 * 1024);
});
it('never deletes an active log when a retention update makes its date stale', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date(2026, 0, 1, 12, 0, 0));
const activePath = path.join(tmpDir, 'snowluma-2026-01-01.log');
fs.writeFileSync(activePath, 'existing\n');
const t = new FileTransport();
t.write('still active');
expect(t.currentPath).toBe(activePath);
vi.setSystemTime(new Date(2026, 0, 3, 12, 0, 0));
await t.updatePolicy({
maxTotalMb: 2,
retainDays: 1,
perUinEnabled: false,
});
expect(fs.existsSync(activePath)).toBe(true);
expect(t.getStorageStatus().activeFileCount).toBe(1);
await t.close();
});
it('applies a lower aggregate limit immediately across shared and account logs', async () => {
setEnv({
SNOWLUMA_LOG_MAX_TOTAL_MB: '4',
SNOWLUMA_LOG_RETAIN_DAYS: '0',
});
const oldPath = path.join(tmpDir, 'snowluma-2026-07-24.log');
const accountDir = path.join(tmpDir, '12345');
const newerPath = path.join(accountDir, 'snowluma-2026-07-24.log');
fs.mkdirSync(accountDir);
fs.writeFileSync(oldPath, Buffer.alloc(700 * 1024));
fs.writeFileSync(newerPath, Buffer.alloc(700 * 1024));
const oldTime = new Date('2026-07-24T01:00:00Z');
const newTime = new Date('2026-07-24T02:00:00Z');
fs.utimesSync(oldPath, oldTime, oldTime);
fs.utimesSync(newerPath, newTime, newTime);
const t = new FileTransport();
const status = await t.updatePolicy({
maxTotalMb: 1,
retainDays: 0,
perUinEnabled: false,
});
expect(fs.existsSync(oldPath)).toBe(false);
expect(fs.existsSync(newerPath)).toBe(true);
expect(status).toMatchObject({
state: 'healthy',
maxTotalBytes: 1024 * 1024,
totalBytes: 700 * 1024,
});
await t.close();
});
it('disables per-account writer creation before awaiting old writer shutdown', async () => {
setEnv({ SNOWLUMA_LOG_PER_UIN: '1' });
const t = new FileTransport();
t.write('before policy update', 12345);
expect(t.perUinPath(12345)).not.toBeNull();
const updating = t.updatePolicy({
maxTotalMb: 2,
retainDays: 7,
perUinEnabled: false,
});
t.write('during policy update', 12345);
expect(t.perUinPath(12345)).toBeNull();
await updating;
expect(t.getStorageStatus().perUinEnabled).toBe(false);
await t.close();
});
it('rejects policies whose unit conversion would exceed safe integer bytes', async () => {
const t = new FileTransport();
await expect(t.updatePolicy({
maxTotalMb: Number.MAX_SAFE_INTEGER,
retainDays: 7,
perUinEnabled: false,
})).rejects.toThrow(/maxTotalMb/);
await expect(t.updatePolicy({
maxTotalMb: 2,
retainDays: Number.MAX_SAFE_INTEGER,
perUinEnabled: false,
})).rejects.toThrow(/retainDays/);
await t.close();
});
it('fails fast on invalid direct log-storage environment values', () => {
setEnv({ SNOWLUMA_LOG_MAX_MB: '0' });
expect(() => new FileTransport()).toThrow(/SNOWLUMA_LOG_MAX_MB/);
setEnv({ SNOWLUMA_LOG_MAX_MB: '1' });
setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '0' });
expect(() => new FileTransport()).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
setEnv({ SNOWLUMA_LOG_MAX_TOTAL_MB: '2', SNOWLUMA_LOG_RETAIN_DAYS: '-1' });
expect(() => new FileTransport()).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
setEnv({ SNOWLUMA_LOG_RETAIN_DAYS: '7', SNOWLUMA_LOG_PER_UIN: 'maybe' });
expect(() => new FileTransport()).toThrow(/SNOWLUMA_LOG_PER_UIN/);
});
it('exposes initialization failures in storage status', async () => {
const invalidRoot = path.join(tmpDir, 'not-a-directory');
fs.writeFileSync(invalidRoot, 'occupied');
setEnv({ SNOWLUMA_LOG_DIR: invalidRoot });
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
const t = new FileTransport();
expect(t.getStorageStatus()).toMatchObject({
state: 'disabled',
lastError: expect.stringMatching(/failed to initialize log storage/),
});
await t.close();
stderr.mockRestore();
});
it('clears active shared and account logs by rotating them into fresh empty files', async () => {
setEnv({ SNOWLUMA_LOG_PER_UIN: '1' });
const t = new FileTransport();
t.write('shared and account', 12345);
const result = await t.clearManagedLogs();
expect(result.deletedFiles).toBe(2);
expect(result.freedBytes).toBeGreaterThan(0);
expect(result.failures).toEqual([]);
expect(fs.statSync(t.currentPath!).size).toBe(0);
expect(fs.statSync(t.perUinPath(12345)!).size).toBe(0);
await t.close();
});
it('keeps files inside the retention window', async () => {
const recent = new Date();
recent.setDate(recent.getDate() - 2);
@@ -135,6 +330,88 @@ describe('FileTransport', () => {
expect(listLogFiles(tmpDir)).toHaveLength(0);
});
it('clears existing managed logs even when file output is disabled', async () => {
const managed = path.join(tmpDir, 'snowluma-2020-01-01.log');
const unrelated = path.join(tmpDir, 'keep.txt');
fs.writeFileSync(managed, 'managed\n');
fs.writeFileSync(unrelated, 'unrelated\n');
setEnv({ SNOWLUMA_LOG_FILE: '0' });
const t = new FileTransport();
const result = await t.clearManagedLogs();
expect(result).toMatchObject({
deletedFiles: 1,
failures: [],
status: { state: 'disabled', totalBytes: 0, fileCount: 0 },
});
expect(fs.existsSync(managed)).toBe(false);
expect(fs.existsSync(unrelated)).toBe(true);
await t.close();
});
it('automatically retries initialization after the log root becomes writable', async () => {
vi.useFakeTimers();
const invalidRoot = path.join(tmpDir, 'blocked-root');
fs.writeFileSync(invalidRoot, 'occupied');
setEnv({ SNOWLUMA_LOG_DIR: invalidRoot });
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
const t = new FileTransport();
expect(t.getStorageStatus().state).toBe('disabled');
fs.unlinkSync(invalidRoot);
fs.mkdirSync(invalidRoot);
vi.advanceTimersByTime(5_000);
t.write('recovered');
await t.close();
expect(listLogFiles(invalidRoot)).toHaveLength(1);
expect(fs.readFileSync(path.join(invalidRoot, listLogFiles(invalidRoot)[0]!), 'utf8'))
.toBe('recovered\n');
stderr.mockRestore();
});
it('reopens the shared writer after a write-stream open failure', async () => {
vi.useFakeTimers();
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
vi.spyOn(fs, 'createWriteStream').mockImplementationOnce(() => {
throw Object.assign(new Error('open failed'), { code: 'EIO' });
});
const t = new FileTransport();
t.write('dropped while opening');
expect(t.getStorageStatus().state).toBe('degraded');
vi.advanceTimersByTime(5_000);
t.write('written after recovery');
await t.close();
const files = listLogFiles(tmpDir);
expect(files).toHaveLength(1);
expect(fs.readFileSync(path.join(tmpDir, files[0]!), 'utf8'))
.toBe('written after recovery\n');
stderr.mockRestore();
});
it('can clear managed logs before the failed writer retry delay expires', async () => {
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
vi.spyOn(fs, 'createWriteStream').mockImplementationOnce(() => {
throw Object.assign(new Error('open failed'), { code: 'EIO' });
});
const t = new FileTransport();
t.write('dropped while opening');
const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log');
fs.writeFileSync(stalePath, 'stale\n');
const result = await t.clearManagedLogs();
expect(result.failures).toEqual([]);
expect(fs.existsSync(stalePath)).toBe(false);
expect(t.currentPath).not.toBeNull();
await t.close();
stderr.mockRestore();
});
it('appends to the existing today file across restarts', async () => {
const a = new FileTransport();
a.write('before restart');
@@ -150,10 +427,11 @@ describe('FileTransport', () => {
.toBe('before restart\nafter restart\n');
});
it('exposes the current file path while open', () => {
it('exposes the current file path while open', async () => {
const t = new FileTransport();
t.write('x');
expect(t.currentPath).not.toBeNull();
expect(t.currentPath!).toMatch(/snowluma-\d{4}-\d{2}-\d{2}\.log$/);
await t.close();
});
});
+24 -1
View File
@@ -12,7 +12,10 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createLogger, getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import { _resetFileTransportForTesting } from '@snowluma/common/log-file-transport';
import {
_resetFileTransportForTesting,
configureFileTransport,
} from '@snowluma/common/log-file-transport';
let tmpDir: string;
const ENV_KEYS = [
@@ -20,6 +23,7 @@ const ENV_KEYS = [
'SNOWLUMA_LOG_PER_UIN',
'SNOWLUMA_LOG_DIR',
'SNOWLUMA_LOG_MAX_MB',
'SNOWLUMA_LOG_MAX_TOTAL_MB',
'SNOWLUMA_LOG_RETAIN_DAYS',
'SNOWLUMA_LOG_LEVEL',
'NO_COLOR',
@@ -41,6 +45,7 @@ beforeEach(async () => {
SNOWLUMA_LOG_FILE: '1',
SNOWLUMA_LOG_PER_UIN: '1',
SNOWLUMA_LOG_MAX_MB: '5',
SNOWLUMA_LOG_MAX_TOTAL_MB: '100',
SNOWLUMA_LOG_RETAIN_DAYS: '7',
NO_COLOR: '1',
});
@@ -177,6 +182,24 @@ describe('createLogger', () => {
const entries = fs.readdirSync(tmpDir);
expect(entries).toHaveLength(0);
});
it('applies the runtime storage policy through the singleton before writing', async () => {
const status = await configureFileTransport({
maxTotalMb: 3,
retainDays: 0,
perUinEnabled: false,
});
expect(status).toMatchObject({
maxTotalBytes: 3 * 1024 * 1024,
retainDays: 0,
perUinEnabled: false,
});
createLogger('Bridge').child({ uin: 24680 }).info('runtime policy');
await _resetFileTransportForTesting();
expect(fs.existsSync(path.join(tmpDir, '24680'))).toBe(false);
});
});
describe('setLogLevel / getLogLevel — runtime level toggle', () => {
@@ -0,0 +1,345 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
StorageAccountOnlineError,
StorageManagementInputError,
StorageManagementService,
type TemporaryStorageAdapter,
} from '../src/webui/storage-management';
import type { LogStorageStatus } from '@snowluma/common/log-file-transport';
let root: string;
let dataDir: string;
const healthyLogs: LogStorageStatus = {
state: 'healthy',
directory: '/must/not/leak',
totalBytes: 100,
maxTotalBytes: 1024,
retainDays: 7,
perUinEnabled: false,
fileCount: 2,
activeFileCount: 1,
droppedLines: 0,
};
const temporary: TemporaryStorageAdapter = {
snapshot: () => ({ totalBytes: 20, fileCount: 2, activeItemCount: 1 }),
clearInactive: () => ({ deletedFiles: 0, freedBytes: 0, skippedActiveItems: 1, failures: [] }),
};
function writeSized(filePath: string, bytes: number): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, Buffer.alloc(bytes));
}
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-storage-'));
dataDir = path.join(root, 'data');
});
afterEach(() => {
vi.restoreAllMocks();
fs.rmSync(root, { recursive: true, force: true });
});
describe('StorageManagementService', () => {
it('summarizes allowlisted account databases and their SQLite sidecars', () => {
const accountDir = path.join(dataDir, '12345');
writeSized(path.join(accountDir, 'messages.db'), 10);
writeSized(path.join(accountDir, 'messages.db-wal'), 2);
writeSized(path.join(accountDir, 'messages.db-shm'), 3);
writeSized(path.join(accountDir, 'media.db'), 4);
writeSized(path.join(accountDir, 'reactions.db'), 5);
writeSized(path.join(accountDir, 'unmanaged.bin'), 999);
writeSized(path.join(dataDir, 'not-an-account', 'messages.db'), 888);
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [{ uin: '12345', nickname: 'Alice' }],
});
expect(service.snapshot()).toEqual({
logs: {
state: 'healthy',
totalBytes: 100,
maxTotalBytes: 1024,
retainDays: 7,
perUinEnabled: false,
fileCount: 2,
activeFileCount: 1,
droppedLines: 0,
},
temporary: { totalBytes: 20, fileCount: 2, activeItemCount: 1 },
accounts: [{
uin: '12345',
nickname: 'Alice',
online: true,
messagesBytes: 15,
mediaBytes: 4,
reactionsBytes: 5,
totalBytes: 24,
}],
totals: {
logsBytes: 100,
temporaryBytes: 20,
accountDataBytes: 24,
managedBytes: 144,
},
});
});
it('redacts the managed log directory from observable error messages', () => {
const service = new StorageManagementService({
dataDir,
getLogStatus: () => ({
...healthyLogs,
state: 'degraded',
lastError: 'write /must/not/leak/snowluma-2026-07-24.log: disk full',
}),
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [],
});
expect(service.snapshot().logs.lastError)
.toBe('write [日志目录]/snowluma-2026-07-24.log: disk full');
});
it('clears only the selected database category for an offline account', () => {
const accountDir = path.join(dataDir, '12345');
writeSized(path.join(accountDir, 'messages.db'), 10);
writeSized(path.join(accountDir, 'messages.db-wal'), 2);
writeSized(path.join(accountDir, 'messages.db-shm'), 3);
writeSized(path.join(accountDir, 'media.db'), 4);
writeSized(path.join(accountDir, 'unmanaged.bin'), 99);
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [],
});
expect(service.clearAccountData('messages', '12345')).toEqual({
category: 'messages',
uins: ['12345'],
deletedFiles: 3,
freedBytes: 15,
failures: [],
});
expect(fs.existsSync(path.join(accountDir, 'messages.db'))).toBe(false);
expect(fs.existsSync(path.join(accountDir, 'media.db'))).toBe(true);
expect(fs.existsSync(path.join(accountDir, 'unmanaged.bin'))).toBe(true);
});
it('rejects online account cleanup before deleting any database file', () => {
const accountDir = path.join(dataDir, '12345');
const messages = path.join(accountDir, 'messages.db');
writeSized(messages, 10);
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [{ uin: '12345', nickname: 'Alice' }],
});
expect(() => service.clearAccountData('messages', '12345'))
.toThrow(StorageAccountOnlineError);
expect(fs.existsSync(messages)).toBe(true);
});
it('rejects unsupported categories and invalid UINs', () => {
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [],
});
expect(() => service.clearAccountData('../config', '12345'))
.toThrow(StorageManagementInputError);
expect(() => service.clearAccountData('messages', '../12345'))
.toThrow(StorageManagementInputError);
});
it('preflights every account before clearing a category across all accounts', () => {
const firstMessages = path.join(dataDir, '12345', 'messages.db');
const secondMessages = path.join(dataDir, '67890', 'messages.db');
writeSized(firstMessages, 10);
writeSized(secondMessages, 20);
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [{ uin: '67890', nickname: 'Bob' }],
});
expect(() => service.clearAllAccountData('messages'))
.toThrow(StorageAccountOnlineError);
expect(fs.existsSync(firstMessages)).toBe(true);
expect(fs.existsSync(secondMessages)).toBe(true);
});
it('never follows an account-directory symlink outside the managed data root', () => {
const externalDir = path.join(root, 'external');
const externalMessages = path.join(externalDir, 'messages.db');
writeSized(externalMessages, 10);
fs.mkdirSync(dataDir, { recursive: true });
fs.symlinkSync(externalDir, path.join(dataDir, '12345'));
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [],
});
expect(service.clearAccountData('messages', '12345')).toEqual({
category: 'messages',
uins: ['12345'],
deletedFiles: 0,
freedBytes: 0,
failures: [],
});
expect(fs.existsSync(externalMessages)).toBe(true);
});
it('never follows a managed data-root symlink outside SnowLuma storage', () => {
const externalDir = path.join(root, 'external');
const externalMessages = path.join(externalDir, '12345', 'messages.db');
writeSized(externalMessages, 10);
fs.symlinkSync(externalDir, dataDir);
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [],
});
expect(() => service.clearAllAccountData('messages'))
.toThrow(/data root/i);
expect(fs.existsSync(externalMessages)).toBe(true);
});
it('does not expose account database absolute paths in cleanup failures', () => {
const messages = path.join(dataDir, '12345', 'messages.db');
writeSized(messages, 10);
const originalLstat = fs.lstatSync.bind(fs);
vi.spyOn(fs, 'lstatSync').mockImplementation((filePath) => {
if (String(filePath) === messages) {
throw Object.assign(
new Error(`EACCES: permission denied, lstat '${messages}'`),
{ code: 'EACCES' },
);
}
return originalLstat(filePath);
});
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary,
listOnlineAccounts: () => [],
});
const result = service.clearAccountData('messages', '12345');
expect(result.failures).toHaveLength(1);
expect(result.failures[0]).toMatchObject({ uin: '12345', file: 'messages.db' });
expect(result.failures[0]?.message).not.toContain(root);
expect(result.failures[0]?.message).toContain('[账号数据库]');
});
it('clears logs without exposing their absolute directory', async () => {
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => ({
deletedFiles: 4,
freedBytes: 90,
failures: [{
file: 'snowluma-2026-07-24.log',
message: 'unlink /must/not/leak/snowluma-2026-07-24.log: permission denied',
}],
status: { ...healthyLogs, totalBytes: 10, fileCount: 1 },
}),
temporary,
listOnlineAccounts: () => [],
});
await expect(service.clearLogs()).resolves.toEqual({
deletedFiles: 4,
freedBytes: 90,
failures: [{
file: 'snowluma-2026-07-24.log',
message: 'unlink [日志目录]/snowluma-2026-07-24.log: permission denied',
}],
status: {
state: 'healthy',
totalBytes: 10,
maxTotalBytes: 1024,
retainDays: 7,
perUinEnabled: false,
fileCount: 1,
activeFileCount: 1,
droppedLines: 0,
},
});
});
it('clears only inactive temporary stream data through its adapter', () => {
const clearResult = {
deletedFiles: 3,
freedBytes: 42,
skippedActiveItems: 2,
failures: [],
};
const service = new StorageManagementService({
dataDir,
getLogStatus: () => healthyLogs,
clearLogs: async () => {
throw new Error('not used');
},
temporary: {
snapshot: temporary.snapshot,
clearInactive: () => clearResult,
},
listOnlineAccounts: () => [],
});
expect(service.clearTemporary()).toBe(clearResult);
});
});
+335
View File
@@ -0,0 +1,335 @@
import { Hono } from 'hono';
import { describe, expect, it } from 'vitest';
import { StorageAccountOnlineError } from '../src/webui/storage-management';
import {
ALL_ACCOUNTS_CONFIRMATION,
registerStorageRoutes,
type StorageRouteDependencies,
} from '../src/webui/storage-routes';
import { StorageSettingsTransactionError } from '../src/webui/storage-settings';
const settingsState = {
saved: { logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false },
effective: { logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false },
envOverrides: [],
};
const snapshot = {
logs: {
state: 'healthy' as const,
totalBytes: 100,
maxTotalBytes: 1024 * 1024 * 1024,
retainDays: 7,
perUinEnabled: false,
fileCount: 1,
activeFileCount: 1,
droppedLines: 0,
},
temporary: { totalBytes: 20, fileCount: 2, activeItemCount: 0 },
accounts: [],
totals: {
logsBytes: 100,
temporaryBytes: 20,
accountDataBytes: 0,
managedBytes: 120,
},
};
function createDependencies(
overrides: Partial<StorageRouteDependencies> = {},
): StorageRouteDependencies {
return {
storage: {
snapshot: () => snapshot,
clearLogs: async () => ({
deletedFiles: 1,
freedBytes: 90,
failures: [],
status: { ...snapshot.logs, totalBytes: 10 },
}),
clearTemporary: () => ({
deletedFiles: 2,
freedBytes: 20,
skippedActiveItems: 0,
failures: [],
}),
clearAccountData: (category, uin) => ({
category: category as 'messages' | 'media' | 'reactions',
uins: [uin],
deletedFiles: 1,
freedBytes: 10,
failures: [],
}),
clearAllAccountData: (category) => ({
category: category as 'messages' | 'media' | 'reactions',
uins: ['12345', '67890'],
deletedFiles: 2,
freedBytes: 20,
failures: [],
}),
},
settings: {
read: () => settingsState,
update: async () => ({
settings: settingsState,
status: snapshot.logs,
}),
},
audit: () => undefined,
reportError: () => undefined,
now: () => new Date('2026-07-24T04:00:00.000Z'),
...overrides,
};
}
function createApp(deps: StorageRouteDependencies): Hono {
const app = new Hono();
registerStorageRoutes(app, deps);
return app;
}
describe('storage management routes', () => {
it('returns settings and a path-free storage snapshot', async () => {
const response = await createApp(createDependencies()).request('/api/system/storage');
expect(response.status).toBe(200);
const body = await response.json();
expect(body).toEqual({ settings: settingsState, snapshot, lastCleanup: null });
expect(JSON.stringify(body)).not.toContain('/private/');
});
it('updates log settings and returns the refreshed snapshot', async () => {
let received: unknown;
const deps = createDependencies({
settings: {
read: () => settingsState,
update: async (body) => {
received = body;
return { settings: settingsState, status: snapshot.logs };
},
},
});
const response = await createApp(deps).request('/api/system/storage/settings', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ logRetainDays: 0 }),
});
expect(response.status).toBe(200);
expect(received).toEqual({ logRetainDays: 0 });
await expect(response.json()).resolves.toMatchObject({
success: true,
settings: settingsState,
snapshot,
});
});
it('reports both the failed settings operation and every failed rollback', async () => {
const operationError = new Error('apply failed');
const rollbackError = new Error('rollback failed');
const reports: Array<{ operation: string; error: unknown }> = [];
const deps = createDependencies({
settings: {
read: () => settingsState,
update: async () => {
throw new StorageSettingsTransactionError(
'transaction failed',
operationError,
[rollbackError],
);
},
},
reportError: (operation, error) => reports.push({ operation, error }),
});
const response = await createApp(deps).request('/api/system/storage/settings', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ logRetainDays: 0 }),
});
expect(response.status).toBe(500);
expect(reports).toEqual([
{ operation: 'update log storage settings', error: expect.any(StorageSettingsTransactionError) },
{ operation: 'update log storage settings operation', error: operationError },
{ operation: 'rollback log storage settings step=1', error: rollbackError },
]);
});
it('serializes settings changes and cleanup operations', async () => {
let releaseSettings!: () => void;
let notifySettingsStarted!: () => void;
const settingsGate = new Promise<void>((resolve) => {
releaseSettings = resolve;
});
const settingsStarted = new Promise<void>((resolve) => {
notifySettingsStarted = resolve;
});
let cleanupCalls = 0;
const deps = createDependencies({
settings: {
read: () => settingsState,
update: async () => {
notifySettingsStarted();
await settingsGate;
return { settings: settingsState, status: snapshot.logs };
},
},
});
deps.storage.clearTemporary = () => {
cleanupCalls += 1;
return {
deletedFiles: 0,
freedBytes: 0,
skippedActiveItems: 0,
failures: [],
};
};
const app = createApp(deps);
const settingsRequest = app.request('/api/system/storage/settings', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ logRetainDays: 0 }),
});
await settingsStarted;
const cleanupRequest = app.request('/api/system/storage/cleanup', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ scope: 'temporary' }),
});
await Promise.resolve();
expect(cleanupCalls).toBe(0);
releaseSettings();
await expect(settingsRequest).resolves.toMatchObject({ status: 200 });
await expect(cleanupRequest).resolves.toMatchObject({ status: 200 });
expect(cleanupCalls).toBe(1);
});
it('rejects arbitrary paths, unknown scopes, and missing cleanup fields', async () => {
const app = createApp(createDependencies());
for (const body of [
{ scope: 'logs', path: '/etc' },
{ scope: 'everything' },
{ scope: 'account', category: 'messages', uin: '../12345' },
{ scope: 'account', category: '../config', uin: '12345' },
{ scope: 'account', category: 'messages' },
]) {
const response = await app.request('/api/system/storage/cleanup', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
});
expect(response.status, JSON.stringify(body)).toBe(400);
}
});
it('requires the fixed second confirmation for all-account cleanup', async () => {
const app = createApp(createDependencies());
const rejected = await app.request('/api/system/storage/cleanup', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
scope: 'allAccounts',
category: 'messages',
confirmation: 'yes',
}),
});
expect(rejected.status).toBe(400);
const accepted = await app.request('/api/system/storage/cleanup', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
scope: 'allAccounts',
category: 'messages',
confirmation: ALL_ACCOUNTS_CONFIRMATION,
}),
});
expect(accepted.status).toBe(200);
await expect(accepted.json()).resolves.toMatchObject({
success: true,
scope: 'allAccounts',
cleanup: { uins: ['12345', '67890'], deletedFiles: 2 },
});
});
it('maps an online-account preflight failure to conflict', async () => {
const deps = createDependencies();
deps.storage.clearAccountData = () => {
throw new StorageAccountOnlineError(['12345']);
};
const response = await createApp(deps).request('/api/system/storage/cleanup', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ scope: 'account', category: 'messages', uin: '12345' }),
});
expect(response.status).toBe(409);
await expect(response.json()).resolves.toMatchObject({
success: false,
onlineUins: ['12345'],
});
});
it('returns HTTP 500 with the structured partial result when deletion fails', async () => {
const audits: unknown[] = [];
const reports: Array<{ operation: string; error: unknown }> = [];
const deps = createDependencies({
audit: (event) => audits.push(event),
reportError: (operation, error) => reports.push({ operation, error }),
});
deps.storage.clearTemporary = () => ({
deletedFiles: 1,
freedBytes: 5,
skippedActiveItems: 0,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
});
const app = createApp(deps);
const response = await app.request('/api/system/storage/cleanup', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ scope: 'temporary' }),
});
expect(response.status).toBe(500);
await expect(response.json()).resolves.toMatchObject({
success: false,
cleanup: {
deletedFiles: 1,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
},
lastCleanup: {
failureCount: 1,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
},
snapshot,
});
expect(audits).toEqual([{
scope: 'temporary',
accountScope: 'global',
deletedFiles: 1,
freedBytes: 5,
failureCount: 1,
}]);
expect(reports).toEqual([{
operation: 'clean storage scope=temporary item=locked.bin',
error: expect.objectContaining({ message: 'permission denied' }),
}]);
const refreshed = await app.request('/api/system/storage');
await expect(refreshed.json()).resolves.toMatchObject({
lastCleanup: {
at: '2026-07-24T04:00:00.000Z',
scope: 'temporary',
accountScope: 'global',
deletedFiles: 1,
freedBytes: 5,
failureCount: 1,
skippedActiveItems: 0,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
},
});
});
});
@@ -0,0 +1,278 @@
import { describe, expect, it } from 'vitest';
import type { LogStoragePolicy, LogStorageStatus } from '@snowluma/common/log-file-transport';
import type { RuntimeConfig } from '@snowluma/common/runtime';
import {
LogStorageSettingsManager,
StorageSettingsInputError,
StorageSettingsLockedError,
StorageSettingsTransactionError,
} from '../src/webui/storage-settings';
const persisted: RuntimeConfig = {
webuiPort: 5099,
hookAutoLoad: false,
webuiHost: '0.0.0.0',
webuiTls: { enabled: false },
trustProxy: '',
logMaxTotalMb: 1024,
logRetainDays: 7,
logPerUin: false,
};
const persistedPolicy: LogStoragePolicy = {
maxTotalMb: 1024,
retainDays: 7,
perUinEnabled: false,
};
function status(
policy: LogStoragePolicy,
state: LogStorageStatus['state'] = 'healthy',
): LogStorageStatus {
return {
state,
directory: '/private/logs',
totalBytes: state === 'degraded' ? policy.maxTotalMb * 1024 * 1024 + 1 : 0,
maxTotalBytes: policy.maxTotalMb * 1024 * 1024,
retainDays: policy.retainDays,
perUinEnabled: policy.perUinEnabled,
fileCount: 0,
activeFileCount: 0,
droppedLines: 0,
...(state === 'healthy' ? {} : { lastError: 'quota could not be enforced' }),
};
}
describe('LogStorageSettingsManager', () => {
it('reports persisted, effective, and environment-locked settings separately', () => {
const manager = new LogStorageSettingsManager({
readPersisted: () => persisted,
readEnvOverrides: () => ({ logRetainDays: 0, logPerUin: true }),
readEffective: () => status({
maxTotalMb: 1024,
retainDays: 0,
perUinEnabled: true,
}),
persist: () => {
throw new Error('not used');
},
apply: async (policy) => status(policy),
});
expect(manager.read()).toEqual({
saved: {
logMaxTotalMb: 1024,
logRetainDays: 7,
logPerUin: false,
},
effective: {
logMaxTotalMb: 1024,
logRetainDays: 0,
logPerUin: true,
},
envOverrides: ['logRetainDays', 'logPerUin'],
});
});
it('reports the actual live policy separately from externally changed disk values', () => {
const manager = new LogStorageSettingsManager({
readPersisted: () => ({ ...persisted, logRetainDays: 30 }),
readEnvOverrides: () => ({}),
readEffective: () => status(persistedPolicy),
persist: () => {
throw new Error('not used');
},
apply: async (policy) => status(policy),
});
expect(manager.read()).toMatchObject({
saved: { logRetainDays: 30 },
effective: { logRetainDays: 7 },
});
});
it('strictly rejects malformed, unknown, and empty patches', async () => {
const manager = new LogStorageSettingsManager({
readPersisted: () => persisted,
readEnvOverrides: () => ({}),
readEffective: () => status(persistedPolicy),
persist: () => persisted,
apply: async (policy) => status(policy),
});
await expect(manager.update(null)).rejects.toThrow(StorageSettingsInputError);
await expect(manager.update({})).rejects.toThrow(StorageSettingsInputError);
await expect(manager.update({ unknown: 1 })).rejects.toThrow(StorageSettingsInputError);
await expect(manager.update({ logMaxTotalMb: 0 })).rejects.toThrow(StorageSettingsInputError);
await expect(manager.update({ logRetainDays: -1 })).rejects.toThrow(StorageSettingsInputError);
await expect(manager.update({ logPerUin: 1 })).rejects.toThrow(StorageSettingsInputError);
});
it('rejects edits to fields pinned by environment variables', async () => {
let applied = false;
const manager = new LogStorageSettingsManager({
readPersisted: () => persisted,
readEnvOverrides: () => ({ logMaxTotalMb: 2048 }),
readEffective: () => status({
maxTotalMb: 2048,
retainDays: 7,
perUinEnabled: false,
}),
persist: () => persisted,
apply: async (policy) => {
applied = true;
return status(policy);
},
});
await expect(manager.update({ logMaxTotalMb: 512 }))
.rejects.toThrow(StorageSettingsLockedError);
expect(applied).toBe(false);
});
it('applies before persisting and returns the new effective settings', async () => {
const order: string[] = [];
let current = persisted;
const manager = new LogStorageSettingsManager({
readPersisted: () => current,
readEnvOverrides: () => ({}),
readEffective: () => status({
maxTotalMb: current.logMaxTotalMb ?? 1024,
retainDays: current.logRetainDays ?? 7,
perUinEnabled: current.logPerUin ?? false,
}),
persist: (patch) => {
order.push('persist');
current = { ...current, ...patch };
return current;
},
apply: async (policy) => {
order.push('apply');
return status(policy);
},
});
await expect(manager.update({
logMaxTotalMb: 512,
logRetainDays: 0,
logPerUin: true,
})).resolves.toMatchObject({
settings: {
saved: {
logMaxTotalMb: 512,
logRetainDays: 0,
logPerUin: true,
},
effective: {
logMaxTotalMb: 512,
logRetainDays: 0,
logPerUin: true,
},
},
status: {
state: 'healthy',
maxTotalBytes: 512 * 1024 * 1024,
},
});
expect(order).toEqual(['apply', 'persist']);
});
it('does not persist a policy that cannot be enforced and rolls runtime state back', async () => {
const applied: LogStoragePolicy[] = [];
let persistCalls = 0;
const manager = new LogStorageSettingsManager({
readPersisted: () => persisted,
readEnvOverrides: () => ({}),
readEffective: () => status(persistedPolicy),
persist: () => {
persistCalls += 1;
return persisted;
},
apply: async (policy) => {
applied.push(policy);
return status(policy, applied.length === 1 ? 'degraded' : 'healthy');
},
});
await expect(manager.update({ logMaxTotalMb: 1 }))
.rejects.toThrow(StorageSettingsTransactionError);
expect(persistCalls).toBe(0);
expect(applied).toEqual([
{ maxTotalMb: 1, retainDays: 7, perUinEnabled: false },
{ maxTotalMb: 1024, retainDays: 7, perUinEnabled: false },
]);
});
it('restores both runtime state and persisted settings when persistence fails', async () => {
const applied: LogStoragePolicy[] = [];
const persistedPatches: Partial<RuntimeConfig>[] = [];
let persistCalls = 0;
const manager = new LogStorageSettingsManager({
readPersisted: () => persisted,
readEnvOverrides: () => ({}),
readEffective: () => status(persistedPolicy),
persist: (patch) => {
persistedPatches.push(patch);
persistCalls += 1;
if (persistCalls === 1) throw new Error('disk full');
return persisted;
},
apply: async (policy) => {
applied.push(policy);
return status(policy);
},
});
await expect(manager.update({ logRetainDays: 30 }))
.rejects.toThrow(StorageSettingsTransactionError);
expect(applied).toEqual([
{ maxTotalMb: 1024, retainDays: 30, perUinEnabled: false },
{ maxTotalMb: 1024, retainDays: 7, perUinEnabled: false },
]);
expect(persistedPatches).toEqual([
{ logRetainDays: 30 },
persisted,
]);
});
it('serializes concurrent updates so invocation order remains authoritative', async () => {
let current = persisted;
let livePolicy = persistedPolicy;
const applied: LogStoragePolicy[] = [];
const releases: Array<() => void> = [];
let notifySecondStarted!: () => void;
const secondStarted = new Promise<void>((resolve) => {
notifySecondStarted = resolve;
});
const manager = new LogStorageSettingsManager({
readPersisted: () => current,
readEnvOverrides: () => ({}),
readEffective: () => status(livePolicy),
persist: (patch) => {
current = { ...current, ...patch };
return current;
},
apply: async (policy) => {
applied.push(policy);
if (applied.length === 2) notifySecondStarted();
await new Promise<void>((resolve) => releases.push(resolve));
livePolicy = policy;
return status(policy);
},
});
const first = manager.update({ logRetainDays: 30 });
const second = manager.update({ logRetainDays: 60 });
await Promise.resolve();
expect(applied).toHaveLength(1);
releases.shift()?.();
await secondStarted;
expect(applied).toHaveLength(2);
releases.shift()?.();
await Promise.all([first, second]);
expect(current.logRetainDays).toBe(60);
expect(applied.map((policy) => policy.retainDays)).toEqual([30, 60]);
});
});
+12 -1
View File
@@ -114,10 +114,21 @@ describe('prepareRestorePlan — strict semantic preflight', () => {
webuiHost: '0.0.0.0',
webuiTls: { enabled: false },
trustProxy: '',
logMaxTotalMb: 1024,
logRetainDays: 7,
logPerUin: false,
});
expect(prepared.migrated).toEqual([{
name: 'runtime.json',
fields: ['$.hookAutoLoad', '$.trustProxy', '$.webuiHost', '$.webuiTls'],
fields: [
'$.hookAutoLoad',
'$.logMaxTotalMb',
'$.logPerUin',
'$.logRetainDays',
'$.trustProxy',
'$.webuiHost',
'$.webuiTls',
],
}]);
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.12.8",
"version": "1.12.9",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
+26 -26
View File
@@ -7466,7 +7466,7 @@
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -7474,7 +7474,7 @@
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
}
],
@@ -7483,10 +7483,10 @@
"type": "object",
"properties": {
"messages": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"additionalProperties": true
@@ -7635,7 +7635,7 @@
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -7643,7 +7643,7 @@
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
}
],
@@ -7658,10 +7658,10 @@
"x-role": "group_id"
},
"messages": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"required": [
@@ -7694,7 +7694,7 @@
"type": "message",
"required": true,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -7718,7 +7718,7 @@
"x-role": "group_id"
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"auto_escape": {
"type": "boolean",
@@ -7794,7 +7794,7 @@
"type": "message",
"required": true,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -7840,7 +7840,7 @@
"type": "object",
"properties": {
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"message_type": {
"type": "string"
@@ -7998,7 +7998,7 @@
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -8006,7 +8006,7 @@
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
}
],
@@ -8020,10 +8020,10 @@
"x-role": "user_id"
},
"messages": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"required": [
@@ -8055,7 +8055,7 @@
"type": "message",
"required": true,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -8087,7 +8087,7 @@
"x-role": "user_id"
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"group_id": {
"type": "integer",
@@ -10528,7 +10528,7 @@
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -10536,7 +10536,7 @@
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -10555,10 +10555,10 @@
"type": "object",
"properties": {
"messages": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"group_id": {
"type": "integer",
@@ -10581,7 +10581,7 @@
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -10589,7 +10589,7 @@
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -10608,10 +10608,10 @@
"type": "object",
"properties": {
"messages": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"group_id": {
"type": "integer",
+26 -26
View File
@@ -7469,7 +7469,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -7477,7 +7477,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
}
],
@@ -7486,10 +7486,10 @@ export const ACTIONS: CatalogAction[] = [
"type": "object",
"properties": {
"messages": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"additionalProperties": true
@@ -7638,7 +7638,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -7646,7 +7646,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
}
],
@@ -7661,10 +7661,10 @@ export const ACTIONS: CatalogAction[] = [
"x-role": "group_id"
},
"messages": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"required": [
@@ -7697,7 +7697,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "message",
"required": true,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -7721,7 +7721,7 @@ export const ACTIONS: CatalogAction[] = [
"x-role": "group_id"
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"auto_escape": {
"type": "boolean",
@@ -7797,7 +7797,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "message",
"required": true,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -7843,7 +7843,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "object",
"properties": {
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"message_type": {
"type": "string"
@@ -8001,7 +8001,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -8009,7 +8009,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
}
],
@@ -8023,10 +8023,10 @@ export const ACTIONS: CatalogAction[] = [
"x-role": "user_id"
},
"messages": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
"required": [
@@ -8058,7 +8058,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "message",
"required": true,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -8090,7 +8090,7 @@ export const ACTIONS: CatalogAction[] = [
"x-role": "user_id"
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"group_id": {
"type": "integer",
@@ -10531,7 +10531,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -10539,7 +10539,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -10558,10 +10558,10 @@ export const ACTIONS: CatalogAction[] = [
"type": "object",
"properties": {
"messages": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"group_id": {
"type": "integer",
@@ -10584,7 +10584,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -10592,7 +10592,7 @@ export const ACTIONS: CatalogAction[] = [
"type": "message",
"required": false,
"schema": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
}
},
{
@@ -10611,10 +10611,10 @@ export const ACTIONS: CatalogAction[] = [
"type": "object",
"properties": {
"messages": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"message": {
"description": "OneBot message: string | segment[] | object"
"description": "OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly \"\" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation."
},
"group_id": {
"type": "integer",
+5 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.12.8",
"version": "1.12.9",
"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.<area>.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/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
@@ -91,6 +91,10 @@
"./instance-rkey": {
"types": "./src/instance-rkey.ts",
"default": "./src/instance-rkey.ts"
},
"./stream-storage": {
"types": "./src/stream-storage.ts",
"default": "./src/stream-storage.ts"
}
},
"scripts": {
+7 -1
View File
@@ -323,7 +323,13 @@ export const f = {
}
}
return ok(raw);
}, { type: 'message', required: true, schema: { description: 'OneBot message: string | segment[] | object' } });
}, {
type: 'message',
required: true,
schema: {
description: 'OneBot message: string | segment[] | object. In segment arrays, text segments whose text field is exactly "" are compatibility placeholders and do not count as sendable segments; missing, null, and whitespace-only text remain subject to normal validation.',
},
});
},
/** Homogeneous array; `.nonEmpty()` rejects []. */
array<E>(el: Field<E>): Field<E[]> & { nonEmpty(): Field<E[]> } {
+39 -18
View File
@@ -26,7 +26,7 @@ import { defineStreamAction, f } from '../action-kit';
import type { ApiActionContext } from '../api-handler';
import { okResponse, type ApiResponse, type JsonObject, type JsonValue } from '../types';
import { type StreamSink, StreamStatus } from '../streaming';
import { STREAM_ROOT } from './stream-file';
import { STREAM_ROOT, registerActiveStreamItem } from '../stream-storage';
const DEFAULT_CHUNK_BYTES = 64 * 1024;
const MAX_CHUNK_REQUEST_BYTES = 16 * 1024 * 1024; // cap the client-requested chunk size
@@ -145,6 +145,8 @@ interface DownloadSource {
name: string;
size: number; // 0 when unknown
iterable: AsyncIterable<Uint8Array>;
/** Local stream-storage path that must be protected from cleanup while read. */
managedPath?: string;
/** Force the underlying source closed (idle-timeout watchdog / abort). */
abort?: () => void;
}
@@ -228,7 +230,13 @@ async function resolveDownload(
try { real = fs.realpathSync(local); } catch { /* keep lexical */ }
if (!isWithinStreamRoot(real)) throw new DownloadError('local downloads are restricted to the stream temp directory');
const rs = fs.createReadStream(real, { highWaterMark: chunkSize });
return { name: path.basename(real), size: st.size, iterable: rs, abort: () => rs.destroy() };
return {
name: path.basename(real),
size: st.size,
iterable: rs,
managedPath: real,
abort: () => rs.destroy(),
};
}
}
@@ -304,22 +312,35 @@ async function runDownload(
if (chunkSize > MAX_CHUNK_REQUEST_BYTES) chunkSize = MAX_CHUNK_REQUEST_BYTES;
const src = await resolveDownload(target, ctx, prefer, chunkSize);
await sink.send({
type: StreamStatus.Stream,
data_type: 'file_info',
file_name: src.name,
file_size: src.size,
chunk_size: chunkSize,
});
const { totalChunks, totalBytes } = await streamChunks(sink, src.iterable, src.size, 'file_chunk', src.abort);
return okResponse({
type: StreamStatus.Response,
data_type: 'file_complete',
file_name: src.name,
total_chunks: totalChunks,
total_bytes: totalBytes,
message: 'Download completed',
});
const releaseStorageActivity = src.managedPath
? registerActiveStreamItem([src.managedPath])
: undefined;
try {
await sink.send({
type: StreamStatus.Stream,
data_type: 'file_info',
file_name: src.name,
file_size: src.size,
chunk_size: chunkSize,
});
const { totalChunks, totalBytes } = await streamChunks(
sink,
src.iterable,
src.size,
'file_chunk',
src.abort,
);
return okResponse({
type: StreamStatus.Response,
data_type: 'file_complete',
file_name: src.name,
total_chunks: totalChunks,
total_bytes: totalBytes,
message: 'Download completed',
});
} finally {
releaseStorageActivity?.();
}
}
// ─────────────────────────── action definitions ───────────────────────────
+57 -14
View File
@@ -17,7 +17,6 @@
// (no single-request OOM or disk/fd exhaustion); chunk indices are claimed
// synchronously (no double-count race); state is namespaced per account.
import os from 'os';
import path from 'path';
import fs from 'fs';
import { createHash } from 'crypto';
@@ -26,12 +25,17 @@ import { defineAction, defineStreamAction, f } from '../action-kit';
import type { ApiActionContext } from '../api-handler';
import { okResponse, type ApiResponse } from '../types';
import { StreamStatus } from '../streaming';
import {
STREAM_DOWNLOAD_DIR,
STREAM_ROOT,
STREAM_UPLOAD_DIR,
clearInactiveStreamStorage,
registerActiveStreamItem,
} from '../stream-storage';
const log = createLogger('OneBot.Stream');
export const STREAM_ROOT = path.join(os.tmpdir(), 'snowluma-stream');
export const STREAM_UPLOAD_DIR = path.join(STREAM_ROOT, 'upload');
export const STREAM_DOWNLOAD_DIR = path.join(STREAM_ROOT, 'download');
export { STREAM_DOWNLOAD_DIR, STREAM_ROOT, STREAM_UPLOAD_DIR };
const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000; // idle stream reaped after 10 min
const DEFAULT_RETENTION_MS = 5 * 60 * 1000; // reassembled file auto-deleted after 5 min
@@ -95,6 +99,7 @@ interface UploadState {
finalPath: string;
fileRetention: number;
timeoutId: NodeJS.Timeout;
releaseStorageActivity: () => void;
}
/** Process-wide. Key is account-namespaced so two accounts (same process) can't
@@ -111,11 +116,16 @@ function cleanupUpload(key: string, deleteFinal: boolean): void {
const state = uploads.get(key);
if (!state) return;
clearTimeout(state.timeoutId);
try { fs.rmSync(state.tempDir, { recursive: true, force: true }); } catch { /* best effort */ }
try { fs.rmSync(state.tempDir, { recursive: true, force: true }); } catch (error) {
log.warn('failed to delete stream upload chunks %s: %s', state.tempDir, errorMessage(error));
}
if (deleteFinal) {
try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ }
try { fs.rmSync(state.finalPath, { force: true }); } catch (error) {
log.warn('failed to delete stream upload file %s: %s', state.finalPath, errorMessage(error));
}
}
uploads.delete(key);
state.releaseStorageActivity();
}
function safeFilename(name: string | undefined, id: string): string {
@@ -142,6 +152,7 @@ function createUpload(p: UploadParams, account: string): UploadState {
fs.mkdirSync(tempDir, { recursive: true });
const key = account ? `${account}:${p.stream_id}` : p.stream_id;
const releaseStorageActivity = registerActiveStreamItem([tempDir, finalPath]);
const state: UploadState = {
id: p.stream_id,
key,
@@ -156,6 +167,7 @@ function createUpload(p: UploadParams, account: string): UploadState {
finalPath,
fileRetention: p.file_retention,
timeoutId: reapTimer(key),
releaseStorageActivity,
};
uploads.set(key, state);
return state;
@@ -200,13 +212,17 @@ async function completeUpload(state: UploadState): Promise<ApiResponse> {
await new Promise<void>((resolve, reject) => out.end((err?: Error | null) => (err ? reject(err) : resolve())));
} catch (err) {
out.destroy();
try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ }
try { fs.rmSync(state.finalPath, { force: true }); } catch (error) {
log.warn('failed to delete incomplete stream file %s: %s', state.finalPath, errorMessage(error));
}
throw err;
}
const sha256 = hash.digest('hex');
if (state.expectedSha256 && sha256 !== state.expectedSha256) {
try { fs.rmSync(state.finalPath, { force: true }); } catch { /* best effort */ }
try { fs.rmSync(state.finalPath, { force: true }); } catch (error) {
log.warn('failed to delete invalid stream file %s: %s', state.finalPath, errorMessage(error));
}
throw new StreamError(`sha256 mismatch (expected ${state.expectedSha256}, got ${sha256})`);
}
@@ -337,7 +353,12 @@ const uploadFileStream = defineStreamAction({
function cleanDir(dir: string): number {
let removed = 0;
let entries: string[];
try { entries = fs.readdirSync(dir); } catch { return 0; } // dir absent → nothing to clean
try {
entries = fs.readdirSync(dir);
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return 0;
throw error;
}
for (const name of entries) {
try { fs.rmSync(path.join(dir, name), { recursive: true, force: true }); removed++; } catch (err) {
log.warn('failed to remove stream temp %s: %s', path.join(dir, name), err instanceof Error ? err.message : String(err));
@@ -352,14 +373,36 @@ const cleanStreamTempFile = defineAction({
returns: '{ message, removed }',
params: {},
run: () => {
const removed = cleanDir(STREAM_UPLOAD_DIR) + cleanDir(STREAM_DOWNLOAD_DIR);
// Active uploads' chunk dirs may have been wiped — drop their state too.
for (const k of [...uploads.keys()]) cleanupUpload(k, false);
return okResponse({ message: 'success', removed });
const result = clearInactiveStreamStorage();
for (const failure of result.failures) {
log.warn('failed to remove stream temp %s: %s', failure.item, failure.message);
}
if (result.failures.length > 0) {
throw new StreamError(`failed to remove ${result.failures.length} stream temp item(s)`);
}
return okResponse({
message: 'success',
removed: result.deletedFiles,
freed_bytes: result.freedBytes,
skipped_active: result.skippedActiveItems,
});
},
});
export const actions = [uploadFileStream, cleanStreamTempFile];
// Exposed for tests.
export const __test = { uploads, handleUpload, cleanDir, validateStreamId, STREAM_UPLOAD_DIR, MAX_CONCURRENT_STREAMS, MAX_CHUNKS };
export const __test = {
uploads,
handleUpload,
cleanupUpload,
cleanDir,
validateStreamId,
STREAM_UPLOAD_DIR,
MAX_CONCURRENT_STREAMS,
MAX_CHUNKS,
};
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+15 -4
View File
@@ -64,6 +64,10 @@ function isSegmentArray(val: unknown): val is MessageSegment[] {
);
}
function normalizeSegmentType(type: string): string {
return type.toLowerCase();
}
function outboundInputSegmentTypes(message: JsonValue, autoEscape: boolean): string[] {
if (typeof message === 'string') {
if (autoEscape) return ['text'];
@@ -71,7 +75,7 @@ function outboundInputSegmentTypes(message: JsonValue, autoEscape: boolean): str
let lastIndex = 0;
for (const match of message.matchAll(CQ_REGEX)) {
if (match.index! > lastIndex) types.push('text');
types.push((match[1] ?? '').toLowerCase());
types.push(normalizeSegmentType(match[1] ?? ''));
lastIndex = match.index! + match[0].length;
}
if (lastIndex < message.length) types.push('text');
@@ -81,12 +85,12 @@ function outboundInputSegmentTypes(message: JsonValue, autoEscape: boolean): str
return message.flatMap((item) => {
if (typeof item !== 'object' || item === null || Array.isArray(item)) return [];
const type = (item as { type?: unknown }).type;
return typeof type === 'string' ? [type.toLowerCase()] : [];
return typeof type === 'string' ? [normalizeSegmentType(type)] : [];
});
}
if (typeof message === 'object' && message !== null) {
const type = (message as { type?: unknown }).type;
return typeof type === 'string' ? [type.toLowerCase()] : [];
return typeof type === 'string' ? [normalizeSegmentType(type)] : [];
}
return [];
}
@@ -173,7 +177,7 @@ function requireCoordinate(
}
export async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
const normalizedType = type.toLowerCase();
const normalizedType = normalizeSegmentType(type);
// Ordinary OneBot segment fields are scalar. Reject objects/arrays before
// codecs can stringify them into "[object Object]" and alter caller intent.
@@ -408,6 +412,13 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti
const elements: MessageElement[] = [];
for (const seg of message) {
const data = segmentPayload(seg);
// Some OneBot clients insert empty text between media as a separator.
// Only the exact empty string is a no-op; malformed and whitespace text
// must still pass through strict element validation.
if (normalizeSegmentType(seg.type) === 'text' && data.text === '') {
log.debug('ignored explicit empty text placeholder in message segment array');
continue;
}
const elem = await segmentToElement(seg.type, data, options);
if (elem) elements.push(elem);
}
+238
View File
@@ -0,0 +1,238 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
export interface StreamStorageSnapshot {
totalBytes: number;
fileCount: number;
activeItemCount: number;
}
export interface StreamStorageCleanupResult {
deletedFiles: number;
freedBytes: number;
skippedActiveItems: number;
failures: Array<{ item: string; message: string }>;
}
export class StreamStorage {
readonly root: string;
readonly uploadDir: string;
readonly downloadDir: string;
private readonly activeItems = new Map<number, string[]>();
private nextActiveItemId = 1;
constructor(root: string) {
this.root = resolveWithExistingAncestor(root);
this.uploadDir = path.join(this.root, 'upload');
this.downloadDir = path.join(this.root, 'download');
}
registerActiveItem(paths: string[]): () => void {
const normalized = paths.map((item) => {
const resolved = path.resolve(item);
if (!isStrictDescendant(this.root, resolved)) {
throw new Error(`active stream path is outside the managed root: ${item}`);
}
return resolved;
});
const id = this.nextActiveItemId++;
this.activeItems.set(id, normalized);
let released = false;
return () => {
if (released) return;
released = true;
this.activeItems.delete(id);
};
}
snapshot(): StreamStorageSnapshot {
if (!this.assertRootDirectoryOrMissing()) {
return {
totalBytes: 0,
fileCount: 0,
activeItemCount: this.activeItems.size,
};
}
let totalBytes = 0;
let fileCount = 0;
this.walkFiles(this.root, (stat) => {
totalBytes += stat.size;
fileCount += 1;
});
return { totalBytes, fileCount, activeItemCount: this.activeItems.size };
}
clearInactive(): StreamStorageCleanupResult {
const result: StreamStorageCleanupResult = {
deletedFiles: 0,
freedBytes: 0,
skippedActiveItems: this.activeItems.size,
failures: [],
};
if (!this.assertRootDirectoryOrMissing()) return result;
const activePaths = [...this.activeItems.values()].flat();
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(this.root, { withFileTypes: true });
} catch (error) {
result.failures.push({ item: '.', message: this.publicErrorMessage(error) });
return result;
}
for (const entry of entries) {
this.clearNode(path.join(this.root, entry.name), activePaths, result);
}
return result;
}
private assertRootDirectoryOrMissing(): boolean {
try {
const stat = fs.lstatSync(this.root);
if (!stat.isDirectory()) {
throw new Error(`managed stream root is not a directory: ${this.root}`);
}
return true;
} catch (error) {
if (isMissing(error)) return false;
throw error;
}
}
private walkFiles(dir: string, visit: (stat: fs.Stats) => void): void {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const item = path.join(dir, entry.name);
const stat = fs.lstatSync(item);
if (stat.isDirectory()) this.walkFiles(item, visit);
else visit(stat);
}
}
private clearNode(
item: string,
activePaths: string[],
result: StreamStorageCleanupResult,
): void {
const resolved = path.resolve(item);
if (activePaths.some((active) => isSameOrDescendant(active, resolved))) return;
let stat: fs.Stats;
try {
stat = fs.lstatSync(resolved);
} catch (error) {
if (!isMissing(error)) {
result.failures.push({
item: this.displayPath(resolved),
message: this.publicErrorMessage(error),
});
}
return;
}
if (!stat.isDirectory()) {
try {
fs.unlinkSync(resolved);
result.deletedFiles += 1;
result.freedBytes += stat.size;
} catch (error) {
if (!isMissing(error)) {
result.failures.push({
item: this.displayPath(resolved),
message: this.publicErrorMessage(error),
});
}
}
return;
}
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(resolved, { withFileTypes: true });
} catch (error) {
result.failures.push({
item: this.displayPath(resolved),
message: this.publicErrorMessage(error),
});
return;
}
for (const entry of entries) {
this.clearNode(path.join(resolved, entry.name), activePaths, result);
}
try {
if (fs.readdirSync(resolved).length === 0) fs.rmdirSync(resolved);
} catch (error) {
if (!isMissing(error)) {
result.failures.push({
item: this.displayPath(resolved),
message: this.publicErrorMessage(error),
});
}
}
}
private displayPath(item: string): string {
const relative = path.relative(this.root, item);
return relative || '.';
}
private publicErrorMessage(error: unknown): string {
return errorMessage(error).split(this.root).join('[临时目录]');
}
}
function isStrictDescendant(root: string, candidate: string): boolean {
const relative = path.relative(root, candidate);
return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative);
}
function isSameOrDescendant(root: string, candidate: string): boolean {
return root === candidate || isStrictDescendant(root, candidate);
}
function isMissing(error: unknown): boolean {
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function resolveWithExistingAncestor(input: string): string {
let existing = path.resolve(input);
const suffix: string[] = [];
while (true) {
try {
fs.lstatSync(existing);
break;
} catch (error) {
if (!isMissing(error)) throw error;
const parent = path.dirname(existing);
if (parent === existing) throw error;
suffix.unshift(path.basename(existing));
existing = parent;
}
}
const canonical = fs.realpathSync(existing);
return path.join(canonical, ...suffix);
}
export const streamStorage = new StreamStorage(path.join(os.tmpdir(), 'snowluma-stream'));
export const STREAM_ROOT = streamStorage.root;
export const STREAM_UPLOAD_DIR = streamStorage.uploadDir;
export const STREAM_DOWNLOAD_DIR = streamStorage.downloadDir;
export function registerActiveStreamItem(paths: string[]): () => void {
return streamStorage.registerActiveItem(paths);
}
export function snapshotStreamStorage(): StreamStorageSnapshot {
return streamStorage.snapshot();
}
export function clearInactiveStreamStorage(): StreamStorageCleanupResult {
return streamStorage.clearInactive();
}
@@ -91,6 +91,83 @@ describe('parseMessage', () => {
expect(result).toEqual([{ type: 'text', text: 'hello' }]);
});
it('ignores explicit empty text placeholders between sendable segments (issue #273)', async () => {
const result = await parseMessage(
[
{ type: 'image', data: { file: 'https://example.com/first.png' } },
{ type: 'text', data: { text: '' } },
{ type: 'image', data: { file: 'https://example.com/second.png' } },
] as any,
false,
);
expect(result).toHaveLength(2);
expect(result).toMatchObject([
{ type: 'image', url: 'https://example.com/first.png' },
{ type: 'image', url: 'https://example.com/second.png' },
]);
});
it('rejects a segment array containing only empty text placeholders', async () => {
await expect(parseMessage(
[
{ type: 'text', data: { text: '' } },
{ type: 'text', data: { text: '' } },
] as any,
false,
)).rejects.toMatchObject({
code: 'MISSING_FIELD',
field: 'message',
});
});
it('keeps a single empty text segment invalid', async () => {
await expect(parseMessage(
{ type: 'text', data: { text: '' } } as any,
false,
)).rejects.toMatchObject({
code: 'MISSING_FIELD',
elementType: 'text',
});
});
it('does not treat missing or null text fields as empty placeholders', async () => {
await expect(parseMessage(
[{ type: 'text', data: {} }] as any,
false,
)).rejects.toMatchObject({
code: 'MISSING_FIELD',
elementType: 'text',
});
await expect(parseMessage(
[{ type: 'text', data: { text: null } }] as any,
false,
)).rejects.toMatchObject({
code: 'MISSING_FIELD',
elementType: 'text',
});
});
it('does not treat whitespace-padded segment types as empty text placeholders', async () => {
await expect(parseMessage(
[
{ type: 'image', data: { file: 'https://example.com/image.png' } },
{ type: ' text ', data: { text: '' } },
] as any,
false,
)).rejects.toMatchObject({
code: 'UNKNOWN_TYPE',
elementType: ' text ',
});
});
it('preserves whitespace-only text segments', async () => {
await expect(parseMessage(
[{ type: 'text', data: { text: ' ' } }] as any,
false,
)).resolves.toEqual([{ type: 'text', text: ' ' }]);
});
it('rejects object-valued fields instead of stringifying caller input', async () => {
await expect(parseMessage(
[{ type: 'text', data: { text: { bad: true } } }] as any,
+26
View File
@@ -0,0 +1,26 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterAll } from 'vitest';
const originalTempEnv = {
TMPDIR: process.env.TMPDIR,
TMP: process.env.TMP,
TEMP: process.env.TEMP,
};
const testTempDir = fs.mkdtempSync(path.join(
os.tmpdir(),
`snowluma-onebot-vitest-${process.pid}-${process.env.VITEST_POOL_ID ?? '0'}-`,
));
process.env.TMPDIR = testTempDir;
process.env.TMP = testTempDir;
process.env.TEMP = testTempDir;
afterAll(() => {
for (const [name, value] of Object.entries(originalTempEnv)) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
fs.rmSync(testTempDir, { recursive: true, force: true });
});
@@ -5,6 +5,8 @@ import path from 'path';
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
import { __test } from '../src/actions/stream-download';
import { STREAM_DOWNLOAD_DIR, __test as fileTest } from '../src/actions/stream-file';
import { clearInactiveStreamStorage } from '../src/stream-storage';
import type { StreamSink } from '../src/streaming';
const parse = (frames: string[]) => frames.map((f) => JSON.parse(f) as Record<string, any>);
@@ -74,6 +76,49 @@ describe('download_file_stream (local, fenced)', () => {
await h.processStreamRequest(JSON.stringify({ action: 'download_file_stream', params: { file: '/etc/passwd' } }), (j) => frames.push(j));
expect(parse(frames).at(-1)).toMatchObject({ status: 'failed', data: { type: 'error' } });
});
it('protects a local stream file from cleanup while it is being downloaded', async () => {
fs.mkdirSync(STREAM_DOWNLOAD_DIR, { recursive: true });
const fp = path.join(STREAM_DOWNLOAD_DIR, 'active.bin');
fs.writeFileSync(fp, 'active download');
let unblock!: () => void;
let reachedFirstFrame!: () => void;
const blocked = new Promise<void>((resolve) => { unblock = resolve; });
const firstFrame = new Promise<void>((resolve) => { reachedFirstFrame = resolve; });
let sent = false;
const sink: StreamSink = {
send: async () => {
if (sent) return;
sent = true;
reachedFirstFrame();
await blocked;
},
};
const running = __test.runDownload(
fp,
65536,
{} as ApiActionContext,
sink,
'auto',
);
await firstFrame;
try {
const duringDownload = clearInactiveStreamStorage();
expect(duringDownload.skippedActiveItems).toBeGreaterThanOrEqual(1);
expect(duringDownload.failures).toEqual([]);
expect(fs.existsSync(fp)).toBe(true);
} finally {
unblock();
await running;
}
const afterDownload = clearInactiveStreamStorage();
expect(afterDownload.deletedFiles).toBeGreaterThanOrEqual(1);
expect(afterDownload.failures).toEqual([]);
expect(fs.existsSync(fp)).toBe(false);
});
});
describe('SSRF guard', () => {
+25 -2
View File
@@ -7,7 +7,7 @@ import { createHash } from 'crypto';
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
import { __test, STREAM_UPLOAD_DIR } from '../src/actions/stream-file';
const { handleUpload, cleanDir, uploads } = __test;
const { handleUpload, cleanupUpload, cleanDir, uploads } = __test;
type UP = Parameters<typeof handleUpload>[0];
const b64 = (s: string | Buffer): string => Buffer.from(s).toString('base64');
@@ -23,8 +23,8 @@ function mk(p: Partial<UP> & { stream_id: string }): UP {
}
afterEach(() => {
for (const key of [...uploads.keys()]) cleanupUpload(key, true);
cleanDir(STREAM_UPLOAD_DIR);
uploads.clear();
});
describe('upload_file_stream', () => {
@@ -181,4 +181,27 @@ describe('clean_stream_temp_file', () => {
expect(fs.existsSync(outside)).toBe(true);
fs.rmSync(outside, { force: true });
});
it('preserves active uploads while removing inactive stream files', async () => {
const id = 'active-clean';
await handleUpload(mk({
stream_id: id,
total_chunks: 2,
chunk_index: 0,
chunk_data: b64('first'),
}));
const state = uploads.get(id)!;
const activeChunk = path.join(state.tempDir, '0.chunk');
const stale = path.join(STREAM_UPLOAD_DIR, 'stale.bin');
fs.writeFileSync(stale, 'stale');
const h = new ApiHandler({} as ApiActionContext);
const result = await h.handle('clean_stream_temp_file', {});
expect(result.status).toBe('ok');
expect(result.data).toMatchObject({ skipped_active: 1 });
expect(uploads.has(id)).toBe(true);
expect(fs.existsSync(activeChunk)).toBe(true);
expect(fs.existsSync(stale)).toBe(false);
});
});
@@ -0,0 +1,113 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { StreamStorage } from '../src/stream-storage';
let container: string;
let root: string;
let storage: StreamStorage;
function writeSized(filePath: string, bytes: number): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, Buffer.alloc(bytes));
}
beforeEach(() => {
container = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-stream-storage-'));
root = path.join(container, 'managed');
storage = new StreamStorage(root);
});
afterEach(() => {
vi.restoreAllMocks();
fs.rmSync(container, { recursive: true, force: true });
});
describe('StreamStorage', () => {
it('summarizes only the managed stream root', () => {
writeSized(path.join(storage.uploadDir, 'upload.bin'), 10);
writeSized(path.join(storage.downloadDir, 'download.bin'), 20);
writeSized(path.join(root, '..', `${path.basename(root)}-outside.bin`), 99);
expect(storage.snapshot()).toEqual({
totalBytes: 30,
fileCount: 2,
activeItemCount: 0,
});
});
it('clears inactive files while preserving every path of an active transfer', () => {
const activeDir = path.join(storage.uploadDir, 'active');
const activeChunk = path.join(activeDir, '0.chunk');
const activeFinal = path.join(storage.uploadDir, 'active__file.bin');
const staleUpload = path.join(storage.uploadDir, 'stale.bin');
const staleDownload = path.join(storage.downloadDir, 'stale.bin');
writeSized(activeChunk, 3);
writeSized(activeFinal, 5);
writeSized(staleUpload, 7);
writeSized(staleDownload, 11);
const release = storage.registerActiveItem([activeDir, activeFinal]);
expect(storage.clearInactive()).toEqual({
deletedFiles: 2,
freedBytes: 18,
skippedActiveItems: 1,
failures: [],
});
expect(fs.existsSync(activeChunk)).toBe(true);
expect(fs.existsSync(activeFinal)).toBe(true);
expect(fs.existsSync(staleUpload)).toBe(false);
expect(fs.existsSync(staleDownload)).toBe(false);
release();
expect(storage.clearInactive()).toMatchObject({
deletedFiles: 2,
freedBytes: 8,
skippedActiveItems: 0,
failures: [],
});
});
it('rejects active paths outside its managed root', () => {
expect(() => storage.registerActiveItem([path.join(root, '..', 'outside')]))
.toThrow(/outside/i);
});
it('does not hide canonicalization failures while establishing its root', () => {
vi.spyOn(fs, 'realpathSync').mockImplementationOnce(() => {
throw Object.assign(new Error('canonicalization denied'), { code: 'EACCES' });
});
expect(() => new StreamStorage(path.join(container, 'another-managed')))
.toThrow(/canonicalization denied/);
});
it('does not treat root inspection failures as a missing ancestor', () => {
const candidate = path.join(container, 'inspection-denied');
const originalLstat = fs.lstatSync.bind(fs);
vi.spyOn(fs, 'lstatSync').mockImplementation((filePath) => {
if (String(filePath) === candidate) {
throw Object.assign(new Error('root inspection denied'), { code: 'EACCES' });
}
return originalLstat(filePath);
});
expect(() => new StreamStorage(candidate))
.toThrow(/root inspection denied/);
});
it('removes a symlink without following it outside the managed root', () => {
const externalDir = path.join(root, '..', `${path.basename(root)}-external`);
const externalFile = path.join(externalDir, 'keep.bin');
writeSized(externalFile, 12);
fs.mkdirSync(storage.uploadDir, { recursive: true });
fs.symlinkSync(externalDir, path.join(storage.uploadDir, 'linked'));
const result = storage.clearInactive();
expect(result.deletedFiles).toBe(1);
expect(result.failures).toEqual([]);
expect(fs.existsSync(externalFile)).toBe(true);
});
});
+1
View File
@@ -14,6 +14,7 @@ export default defineConfig({
plugins: [protobufVitePlugin()],
test: {
include: ['tests/**/*.test.ts'],
setupFiles: ['./tests/setup.ts'],
// Per-RoadMap-#5 bench files live in `bench/*.bench.ts`. Use the
// vitest `--mode bench` (via `pnpm bench`) to pick them up; default
// `test` runs leave them inert.
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "1.12.8",
"version": "1.12.9",
"private": true,
"type": "module",
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` 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).",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "1.12.8",
"version": "1.12.9",
"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/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "1.12.8",
"version": "1.12.9",
"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.",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "1.12.8",
"version": "1.12.9",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.12.8",
"version": "1.12.9",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.12.8",
"version": "1.12.9",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/websocket",
"version": "1.12.8",
"version": "1.12.9",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -2,7 +2,7 @@
"license": "SEE LICENSE IN LICENSE",
"name": "webui",
"private": true,
"version": "1.12.8",
"version": "1.12.9",
"type": "module",
"scripts": {
"dev": "vite",
@@ -3,7 +3,7 @@ import { motion } from 'motion/react';
import {
Accessibility, AlertTriangle, Bell, Bug, Check, Clock, Code2, Download, ExternalLink, Github, Image as ImageIcon,
Info, KeyRound, Loader2, Monitor, Moon, Palette, PanelTop, Plus, RefreshCw, RotateCcw, Server, ShieldCheck,
SlidersHorizontal, Sparkles, Star, Sun, Tag, Upload, Trash2,
SlidersHorizontal, Sparkles, Star, Sun, Tag, Upload, Trash2, HardDrive,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
@@ -44,6 +44,7 @@ import { settingsRoute, type SettingsTab } from '@/router';
import { NotificationsPanel } from '@/components/settings/notifications-panel';
import { GlobalConfigPanel } from '@/components/settings/global-config-panel';
import { SystemPanel } from '@/components/settings/system-panel';
import { StoragePanel } from '@/components/settings/storage-panel';
interface TabDef { key: SettingsTab; label: string; icon: typeof Sun }
@@ -64,6 +65,7 @@ const TAB_GROUPS: { title: string; tabs: TabDef[] }[] = [
title: 'SnowLuma',
tabs: [
{ key: 'globalConfig', label: '全局配置', icon: SlidersHorizontal },
{ key: 'storage', label: '存储管理', icon: HardDrive },
{ key: 'notifications', label: '通知', icon: Bell },
],
},
@@ -107,6 +109,7 @@ export function SettingsPage() {
{tab === 'advanced' && <AdvancedPanel />}
{tab === 'account' && <AccountPanel />}
{tab === 'system' && <SystemPanel />}
{tab === 'storage' && <StoragePanel />}
{tab === 'notifications' && <NotificationsPanel />}
{tab === 'globalConfig' && <GlobalConfigPanel />}
{tab === 'about' && <AboutPanel />}
@@ -0,0 +1,817 @@
import { useEffect, useState } from 'react';
import {
Activity,
AlertTriangle,
Clock3,
Database,
FileClock,
HardDrive,
Image,
Loader2,
Lock,
MessageSquare,
RefreshCw,
Save,
SmilePlus,
Trash2,
Users,
type LucideIcon,
} from 'lucide-react';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge, type BadgeProps } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Progress } from '@/components/ui/progress';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { useFlashMessage } from '@/hooks/use-flash-message';
import { useApi } from '@/lib/api';
import {
buildLogSettingsPatch,
formatBytes,
isAllAccountsConfirmation,
logStoragePresentation,
type StorageTone,
} from '@/lib/storage-presentation';
import { cn } from '@/lib/utils';
import {
ALL_ACCOUNTS_CONFIRMATION,
type AccountStorageCategory,
type AccountStorageSnapshot,
type LastStorageCleanup,
type LogStorageSettings,
type LogStorageSettingsField,
type StorageCleanupRequest,
type StorageOverviewResponse,
} from '@/types';
const CATEGORY_INFO: Record<
AccountStorageCategory,
{ label: string; description: string; icon: LucideIcon; bytes: keyof AccountStorageSnapshot }
> = {
messages: {
label: '消息历史',
description: 'OneBot 消息与回复索引',
icon: MessageSquare,
bytes: 'messagesBytes',
},
media: {
label: '媒体索引',
description: '图片、语音与视频的元数据',
icon: Image,
bytes: 'mediaBytes',
},
reactions: {
label: '表情回应',
description: '群消息表情回应记录',
icon: SmilePlus,
bytes: 'reactionsBytes',
},
};
const CATEGORIES = Object.keys(CATEGORY_INFO) as AccountStorageCategory[];
interface PendingCleanup {
request: Exclude<StorageCleanupRequest, { scope: 'allAccounts' }>;
title: string;
description: string;
}
export function StoragePanel() {
const api = useApi();
const [data, setData] = useState<StorageOverviewResponse | null>(null);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [saving, setSaving] = useState(false);
const [operation, setOperation] = useState<string | null>(null);
const [maxTotalMb, setMaxTotalMb] = useState('');
const [retainDays, setRetainDays] = useState('');
const [perUin, setPerUin] = useState(false);
const [pendingCleanup, setPendingCleanup] = useState<PendingCleanup | null>(null);
const [allAccountsCategory, setAllAccountsCategory] =
useState<AccountStorageCategory | null>(null);
const { msg, flash, setMsg } = useFlashMessage(5000);
const applyOverview = (overview: StorageOverviewResponse) => {
setData(overview);
setMaxTotalMb(String(overview.settings.effective.logMaxTotalMb));
setRetainDays(String(overview.settings.effective.logRetainDays));
setPerUin(overview.settings.effective.logPerUin);
};
const load = async (showSpinner = false): Promise<boolean> => {
if (showSpinner) setRefreshing(true);
try {
const overview = await api.storage.get();
applyOverview(overview);
return true;
} catch (error) {
setMsg({
kind: 'err',
text: error instanceof Error ? error.message : '加载存储信息失败',
});
return false;
} finally {
setLoading(false);
setRefreshing(false);
}
};
useEffect(() => {
void load();
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const isLocked = (field: LogStorageSettingsField): boolean =>
data?.settings.envOverrides.includes(field) ?? false;
const saveSettings = async () => {
if (!data || saving || operation !== null) return;
const nextMaxTotalMb = Number(maxTotalMb);
const nextRetainDays = Number(retainDays);
if (!Number.isSafeInteger(nextMaxTotalMb) || nextMaxTotalMb < 1) {
flash('err', '日志总量上限必须是大于 0 的整数');
return;
}
if (!Number.isSafeInteger(nextRetainDays) || nextRetainDays < 0) {
flash('err', '保留天数必须是大于或等于 0 的整数');
return;
}
const current: LogStorageSettings = {
logMaxTotalMb: nextMaxTotalMb,
logRetainDays: nextRetainDays,
logPerUin: perUin,
};
const patch = buildLogSettingsPatch(
current,
data.settings.saved,
data.settings.envOverrides,
);
if (Object.keys(patch).length === 0) {
flash('ok', '没有需要保存的更改');
return;
}
setSaving(true);
try {
const result = await api.storage.saveSettings(patch);
applyOverview({
settings: result.settings,
snapshot: result.snapshot,
lastCleanup: data.lastCleanup,
});
flash('ok', '日志策略已保存并立即生效');
} catch (error) {
flash('err', error instanceof Error ? error.message : '保存失败');
await load();
} finally {
setSaving(false);
}
};
const runCleanup = async (request: StorageCleanupRequest): Promise<boolean> => {
if (saving || operation !== null) return false;
const key = cleanupKey(request);
setOperation(key);
try {
const result = await api.storage.cleanup(request);
if (result.snapshot) {
setData((previous) => previous
? {
...previous,
snapshot: result.snapshot!,
lastCleanup: result.lastCleanup ?? previous.lastCleanup,
}
: previous);
} else {
await load();
}
const summary = [
`删除 ${result.cleanup.deletedFiles} 个文件`,
`释放 ${formatBytes(result.cleanup.freedBytes)}`,
];
if ('skippedActiveItems' in result.cleanup && result.cleanup.skippedActiveItems > 0) {
summary.push(`跳过 ${result.cleanup.skippedActiveItems} 个活动传输`);
}
if (result.cleanup.failures.length > 0) {
summary.push(`${result.cleanup.failures.length} 项失败`);
}
flash(result.success ? 'ok' : 'err', summary.join(','));
return result.success;
} catch (error) {
flash('err', error instanceof Error ? error.message : '清理失败');
await load();
return false;
} finally {
setOperation(null);
}
};
if (loading) {
return (
<div className="flex items-center gap-2 px-1 py-8 text-sm text-muted-foreground">
<Loader2 className="size-4 animate-spin" />
加载存储信息…
</div>
);
}
if (!data) {
return (
<Card>
<CardContent className="flex flex-col items-start gap-3 pt-5">
<p className="text-sm text-muted-foreground">存储信息暂时不可用。</p>
<Button variant="outline" onClick={() => void load(true)}>
<RefreshCw className="size-4" />
重试
</Button>
</CardContent>
</Card>
);
}
const { snapshot } = data;
const logPresentation = logStoragePresentation(snapshot.logs);
const onlineCount = snapshot.accounts.filter((account) => account.online).length;
const allCategoryBytes = Object.fromEntries(
CATEGORIES.map((category) => [
category,
snapshot.accounts.reduce(
(sum, account) => sum + Number(account[CATEGORY_INFO[category].bytes]),
0,
),
]),
) as Record<AccountStorageCategory, number>;
return (
<div className="flex flex-col gap-5">
{msg && (
<div
role="status"
className={cn(
'rounded-lg px-3 py-2 text-xs',
msg.kind === 'ok'
? 'bg-emerald-500/10 text-emerald-700 dark:text-emerald-300'
: 'bg-red-500/10 text-red-700 dark:text-red-300',
)}
>
{msg.text}
</div>
)}
<Card>
<CardHeader className="gap-3 sm:flex-row sm:items-start sm:justify-between">
<div className="min-w-0">
<CardTitle className="flex items-center gap-2 text-sm">
<HardDrive className="size-4" />
存储概览
</CardTitle>
<CardDescription className="mt-1">
只统计 SnowLuma 管理的日志、账号数据库和文件传输临时数据。
</CardDescription>
</div>
<Button
variant="outline"
size="sm"
onClick={() => void load(true)}
disabled={refreshing || saving || operation !== null}
className="shrink-0"
>
<RefreshCw className={cn('size-4', refreshing && 'animate-spin')} />
刷新
</Button>
</CardHeader>
<CardContent className="flex flex-col gap-5">
<div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
<Metric label="受管数据总量" value={formatBytes(snapshot.totals.managedBytes)} />
<Metric label="日志" value={formatBytes(snapshot.totals.logsBytes)} />
<Metric label="账号数据库" value={formatBytes(snapshot.totals.accountDataBytes)} />
<Metric label="传输临时数据" value={formatBytes(snapshot.totals.temporaryBytes)} />
</div>
<div className="rounded-lg bg-muted/35 p-3">
<div className="mb-2 flex flex-wrap items-center justify-between gap-2">
<div>
<p className="text-sm font-medium">日志容量</p>
<p className="mt-0.5 text-xs tabular-nums text-muted-foreground">
{formatBytes(snapshot.logs.totalBytes)} / {formatBytes(snapshot.logs.maxTotalBytes)}
</p>
</div>
<Badge variant={toneBadgeVariant(logPresentation.tone)}>
{logPresentation.label}
</Badge>
</div>
<Progress
value={logPresentation.percent}
aria-label="日志容量使用率"
indicatorClassName={toneProgressClass(logPresentation.tone)}
/>
<div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
<span>{snapshot.logs.fileCount} 个文件</span>
<span>{snapshot.logs.activeFileCount} 个活动文件</span>
<span>丢弃 {snapshot.logs.droppedLines} 行磁盘日志</span>
</div>
{snapshot.logs.lastError && (
<div className="mt-3 flex items-start gap-2 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive">
<AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
<span className="break-words">{snapshot.logs.lastError}</span>
</div>
)}
</div>
{data.lastCleanup && <LastCleanupSummary cleanup={data.lastCleanup} />}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm">
<FileClock className="size-4" />
日志策略
</CardTitle>
<CardDescription>
总量上限始终生效;保留天数设为 0 时仅按总量淘汰。保存后立即应用。
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="storage-log-max" className="flex flex-wrap items-center gap-1">
日志总量上限(MB)
<EnvironmentBadge locked={isLocked('logMaxTotalMb')} />
</Label>
<Input
id="storage-log-max"
type="number"
min={1}
step={1}
inputMode="numeric"
value={maxTotalMb}
onChange={(event) => setMaxTotalMb(event.target.value)}
disabled={isLocked('logMaxTotalMb') || saving || operation !== null}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="storage-log-days" className="flex flex-wrap items-center gap-1">
保留天数
<EnvironmentBadge locked={isLocked('logRetainDays')} />
</Label>
<Input
id="storage-log-days"
type="number"
min={0}
step={1}
inputMode="numeric"
value={retainDays}
onChange={(event) => setRetainDays(event.target.value)}
disabled={isLocked('logRetainDays') || saving || operation !== null}
/>
</div>
</div>
<div className="flex min-h-11 items-center justify-between gap-4 rounded-lg bg-muted/35 px-3 py-2">
<div className="min-w-0">
<p className="flex flex-wrap items-center gap-1 text-sm font-medium">
按账号额外写入日志
<EnvironmentBadge locked={isLocked('logPerUin')} />
</p>
<p className="mt-0.5 text-xs leading-relaxed text-muted-foreground">
开启后,同一条带账号上下文的日志还会写入账号子目录,占用会增加。
</p>
</div>
<ToggleSwitch
value={perUin}
onChange={setPerUin}
ariaLabel="按账号额外写入日志"
disabled={isLocked('logPerUin') || saving || operation !== null}
/>
</div>
<div>
<Button
onClick={() => void saveSettings()}
disabled={
saving
|| operation !== null
|| data.settings.envOverrides.length === 3
}
>
{saving ? <Loader2 className="size-4 animate-spin" /> : <Save className="size-4" />}
保存并应用
</Button>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm">
<Trash2 className="size-4" />
全局数据清理
</CardTitle>
<CardDescription>
日志清理会轮转活动文件;临时数据清理会自动跳过正在进行的上传和下载。
</CardDescription>
</CardHeader>
<CardContent className="divide-y divide-border/60 p-0">
<CleanupRow
icon={FileClock}
title="日志"
description={`${snapshot.logs.fileCount} 个文件 · ${formatBytes(snapshot.logs.totalBytes)}`}
busy={operation === 'logs'}
disabled={saving || operation !== null}
onClick={() => setPendingCleanup({
request: { scope: 'logs' },
title: '清理全部日志?',
description: 'SnowLuma 会先轮转活动日志,再删除旧日志,只保留新建的空文件。',
})}
/>
<CleanupRow
icon={Activity}
title="文件传输临时数据"
description={`${snapshot.temporary.fileCount} 个文件 · ${formatBytes(snapshot.temporary.totalBytes)} · ${snapshot.temporary.activeItemCount} 个活动传输`}
busy={operation === 'temporary'}
disabled={saving || operation !== null}
onClick={() => setPendingCleanup({
request: { scope: 'temporary' },
title: '清理非活动临时数据?',
description: '正在上传或下载的项目会保留,其余 SnowLuma 文件传输临时数据将被删除。',
})}
/>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm">
<Database className="size-4" />
账号数据
</CardTitle>
<CardDescription>
仅清理选中的数据库分类。账号必须离线,配置、凭据和聊天内容导出不在此页面提供。
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{snapshot.accounts.length === 0 ? (
<div className="rounded-lg bg-muted/35 px-4 py-6 text-center text-sm text-muted-foreground">
尚未发现账号数据库。
</div>
) : (
snapshot.accounts.map((account) => (
<AccountStorageCard
key={account.uin}
account={account}
operation={operation}
saving={saving}
onRequest={(category) => {
const info = CATEGORY_INFO[category];
setPendingCleanup({
request: { scope: 'account', category, uin: account.uin },
title: `清理 ${account.nickname || account.uin} 的${info.label}?`,
description: `将删除账号 ${account.uin} 的${info.label}数据库及其边车文件,其他分类和配置不受影响。`,
});
}}
/>
))
)}
{snapshot.accounts.length > 0 && (
<div className="rounded-lg bg-muted/35 p-3">
<div className="mb-3 flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between">
<div>
<p className="flex items-center gap-2 text-sm font-medium">
<Users className="size-4" />
全部账号
</p>
<p className="mt-0.5 text-xs text-muted-foreground">
{onlineCount > 0
? `${onlineCount} 个账号仍在线,全部账号清理暂不可用`
: '选择一个分类,并在弹窗中输入确认短语'}
</p>
</div>
</div>
<div className="grid gap-2 sm:grid-cols-3">
{CATEGORIES.map((category) => (
<Button
key={category}
variant="outline"
onClick={() => setAllAccountsCategory(category)}
disabled={
operation !== null
|| saving
|| onlineCount > 0
|| allCategoryBytes[category] === 0
}
className="justify-between"
>
<span>清理全部{CATEGORY_INFO[category].label}</span>
<span className="text-xs tabular-nums text-muted-foreground">
{formatBytes(allCategoryBytes[category])}
</span>
</Button>
))}
</div>
</div>
)}
</CardContent>
</Card>
<ConfirmDialog
open={pendingCleanup !== null}
onOpenChange={(open) => {
if (!open && operation === null) setPendingCleanup(null);
}}
title={pendingCleanup?.title ?? ''}
description={pendingCleanup?.description}
confirmText="确认清理"
destructive
onConfirm={async () => {
if (!pendingCleanup) return;
await runCleanup(pendingCleanup.request);
setPendingCleanup(null);
}}
/>
<AllAccountsCleanupDialog
category={allAccountsCategory}
busy={operation?.startsWith('allAccounts:') ?? false}
onOpenChange={(open) => {
if (!open && operation === null) setAllAccountsCategory(null);
}}
onConfirm={async (category) => {
await runCleanup({
scope: 'allAccounts',
category,
confirmation: ALL_ACCOUNTS_CONFIRMATION,
});
setAllAccountsCategory(null);
}}
/>
</div>
);
}
function Metric({ label, value }: { label: string; value: string }) {
return (
<div className="rounded-lg bg-muted/35 p-3">
<p className="text-xs text-muted-foreground">{label}</p>
<p className="mt-1 text-sm font-semibold tabular-nums">{value}</p>
</div>
);
}
function EnvironmentBadge({ locked }: { locked: boolean }) {
if (!locked) return null;
return (
<Badge variant="secondary" className="gap-1 text-micro">
<Lock className="size-3" />
环境变量锁定
</Badge>
);
}
function CleanupRow({
icon: Icon,
title,
description,
busy,
disabled,
onClick,
}: {
icon: LucideIcon;
title: string;
description: string;
busy: boolean;
disabled: boolean;
onClick: () => void;
}) {
return (
<div className="flex flex-col gap-3 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 items-start gap-3">
<div className="flex size-9 shrink-0 items-center justify-center rounded-md bg-muted">
<Icon className="size-4" />
</div>
<div className="min-w-0">
<p className="text-sm font-medium">{title}</p>
<p className="mt-0.5 text-xs leading-relaxed text-muted-foreground">{description}</p>
</div>
</div>
<Button
variant="outline"
onClick={onClick}
disabled={disabled}
className="w-full text-destructive hover:bg-destructive/10 hover:text-destructive sm:w-auto"
>
{busy ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
清理
</Button>
</div>
);
}
function AccountStorageCard({
account,
operation,
saving,
onRequest,
}: {
account: AccountStorageSnapshot;
operation: string | null;
saving: boolean;
onRequest: (category: AccountStorageCategory) => void;
}) {
return (
<div className="rounded-lg border border-border/60 p-3">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div className="min-w-0">
<p className="truncate text-sm font-medium">{account.nickname || `账号 ${account.uin}`}</p>
<p className="text-xs tabular-nums text-muted-foreground">{account.uin}</p>
</div>
<div className="flex items-center gap-2">
<span className="text-xs tabular-nums text-muted-foreground">
{formatBytes(account.totalBytes)}
</span>
<Badge variant={account.online ? 'warning' : 'secondary'}>
{account.online ? '在线' : '离线'}
</Badge>
</div>
</div>
<div className="grid gap-2 sm:grid-cols-3">
{CATEGORIES.map((category) => {
const info = CATEGORY_INFO[category];
const Icon = info.icon;
const bytes = Number(account[info.bytes]);
const key = `account:${account.uin}:${category}`;
return (
<div key={category} className="flex flex-col gap-3 rounded-md bg-muted/35 p-3">
<div className="flex items-start gap-2">
<Icon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
<div className="min-w-0">
<p className="text-xs font-medium">{info.label}</p>
<p className="mt-0.5 text-micro leading-relaxed text-muted-foreground">
{info.description}
</p>
</div>
</div>
<div className="mt-auto flex items-center justify-between gap-2">
<span className="text-xs tabular-nums text-muted-foreground">
{formatBytes(bytes)}
</span>
<Button
variant="outline"
size="sm"
onClick={() => onRequest(category)}
disabled={saving || operation !== null || account.online || bytes === 0}
aria-label={`清理 ${account.uin} 的${info.label}`}
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
>
{operation === key
? <Loader2 className="size-4 animate-spin" />
: <Trash2 className="size-4" />}
清理
</Button>
</div>
</div>
);
})}
</div>
</div>
);
}
function LastCleanupSummary({ cleanup }: { cleanup: LastStorageCleanup }) {
const label = cleanup.category
? CATEGORY_INFO[cleanup.category].label
: cleanup.scope === 'logs'
? '日志'
: '传输临时数据';
return (
<div className="flex items-start gap-2 rounded-lg bg-muted/35 px-3 py-2 text-xs text-muted-foreground">
<Clock3 className="mt-0.5 size-3.5 shrink-0" />
<div className="min-w-0">
<p>
最近清理:{label},删除 {cleanup.deletedFiles} 个文件,释放 {formatBytes(cleanup.freedBytes)}
{cleanup.failureCount > 0 ? `,${cleanup.failureCount} 项失败` : ''}
{' · '}
{formatTimestamp(cleanup.at)}
</p>
{cleanup.failures.length > 0 && (
<ul className="mt-1 list-disc space-y-0.5 pl-4 text-destructive">
{cleanup.failures.slice(0, 3).map((failure, index) => (
<li key={`${failure.item}:${String(index)}`} className="break-words">
{failure.item}:{failure.message}
</li>
))}
{cleanup.failures.length > 3 && (
<li>另有 {cleanup.failures.length - 3} 项失败,请检查服务器日志</li>
)}
</ul>
)}
</div>
</div>
);
}
function AllAccountsCleanupDialog({
category,
busy,
onOpenChange,
onConfirm,
}: {
category: AccountStorageCategory | null;
busy: boolean;
onOpenChange: (open: boolean) => void;
onConfirm: (category: AccountStorageCategory) => Promise<void>;
}) {
const [confirmation, setConfirmation] = useState('');
const open = category !== null;
const close = () => {
setConfirmation('');
onOpenChange(false);
};
return (
<AlertDialog
open={open}
onOpenChange={(nextOpen) => {
if (!nextOpen && !busy) close();
}}
>
<AlertDialogContent className="max-h-[calc(100dvh-2rem)] w-[calc(100%-2rem)] max-w-md overflow-y-auto p-5 sm:p-6">
<AlertDialogHeader>
<AlertDialogTitle>
清理全部账号的{category ? CATEGORY_INFO[category].label : '数据'}?
</AlertDialogTitle>
<AlertDialogDescription className="leading-relaxed">
该操作会删除所有离线账号的对应数据库及边车文件,无法撤销。请输入
<strong className="mx-1 text-foreground">{ALL_ACCOUNTS_CONFIRMATION}</strong>
继续。
</AlertDialogDescription>
</AlertDialogHeader>
<div className="flex flex-col gap-1.5">
<Label htmlFor="all-account-cleanup-confirmation">确认短语</Label>
<Input
id="all-account-cleanup-confirmation"
value={confirmation}
onChange={(event) => setConfirmation(event.target.value)}
placeholder={ALL_ACCOUNTS_CONFIRMATION}
autoComplete="off"
disabled={busy}
/>
</div>
<AlertDialogFooter>
<AlertDialogCancel disabled={busy} onClick={() => setConfirmation('')}>
取消
</AlertDialogCancel>
<AlertDialogAction
disabled={!isAllAccountsConfirmation(confirmation) || busy || !category}
onClick={(event) => {
event.preventDefault();
if (!category || !isAllAccountsConfirmation(confirmation)) return;
void onConfirm(category);
}}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{busy ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
确认清理
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
function cleanupKey(request: StorageCleanupRequest): string {
if (request.scope === 'account') return `account:${request.uin}:${request.category}`;
if (request.scope === 'allAccounts') return `allAccounts:${request.category}`;
return request.scope;
}
function toneBadgeVariant(tone: StorageTone): BadgeProps['variant'] {
if (tone === 'success') return 'success';
if (tone === 'warning') return 'warning';
if (tone === 'danger') return 'destructive';
return 'secondary';
}
function toneProgressClass(tone: StorageTone): string {
if (tone === 'danger') return 'bg-destructive';
if (tone === 'warning') return 'bg-warning';
if (tone === 'neutral') return 'bg-muted-foreground';
return 'bg-success';
}
function formatTimestamp(value: string): string {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
}
+26 -1
View File
@@ -1,4 +1,4 @@
import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionDoc, DebugInvokeResult, DebugStreamMessage, GlobalSettings, HookProcessInfo, LogEntry, LogLevel, NotificationDeliveryRecord, NotificationsConfig, QQInfo, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types';
import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionDoc, DebugInvokeResult, DebugStreamMessage, GlobalSettings, HookProcessInfo, LogEntry, LogLevel, LogStorageSettingsPatch, NotificationDeliveryRecord, NotificationsConfig, QQInfo, StorageCleanupRequest, StorageCleanupResponse, StorageOverviewResponse, StorageSettingsUpdateResponse, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-page';
import { normalizeOneBotConfig } from '@/lib/onebot-config';
import {
@@ -58,6 +58,7 @@ class HttpApiClient implements ApiClient {
readonly notifications: ApiClient['notifications'];
readonly globalConfig: ApiClient['globalConfig'];
readonly systemSettings: ApiClient['systemSettings'];
readonly storage: ApiClient['storage'];
readonly debug: ApiClient['debug'];
readonly agreements: ApiClient['agreements'];
@@ -167,6 +168,30 @@ class HttpApiClient implements ApiClient {
this.postJson<BackupImportResult>('/api/system/backup/import', { backup, restoreCredentials }),
};
this.storage = {
get: () => this.getJson<StorageOverviewResponse>('/api/system/storage'),
saveSettings: (patch: LogStorageSettingsPatch) =>
this.postJson<StorageSettingsUpdateResponse>('/api/system/storage/settings', patch),
cleanup: async (request: StorageCleanupRequest) => {
const response = await this.request('/api/system/storage/cleanup', {
method: 'POST',
body: JSON.stringify(request),
});
const payload = await readJson<StorageCleanupResponse & ErrorPayload>(response);
// A cleanup can partially succeed and return HTTP 500 with the exact
// deleted/failed items. Preserve that result so the operator sees the
// real outcome instead of a generic exception.
if (!response.ok && !payload.cleanup) {
throw new ApiError(
response.status,
extractErrorMessage(payload, response.statusText || '清理失败'),
payload.code,
);
}
return payload;
},
};
this.debug = {
actions: () => this.getJson<{ actions: DebugActionDoc[]; categories: { category: string; count: number }[] }>('/api/debug/actions'),
invoke: (uin: string, action: string, params: Record<string, unknown>) =>
+12
View File
@@ -16,6 +16,11 @@ import type {
OneBotConfig,
QQInfo,
SystemInfo,
LogStorageSettingsPatch,
StorageCleanupRequest,
StorageCleanupResponse,
StorageOverviewResponse,
StorageSettingsUpdateResponse,
SystemSettings,
SystemSettingsPatch,
SystemSettingsResponse,
@@ -168,6 +173,13 @@ export interface ApiClient {
importBackup(backup: BackupBundle, restoreCredentials: boolean): Promise<BackupImportResult>;
};
// ---- managed storage (logs / stream temp / per-account databases) ----
storage: {
get(): Promise<StorageOverviewResponse>;
saveSettings(patch: LogStorageSettingsPatch): Promise<StorageSettingsUpdateResponse>;
cleanup(request: StorageCleanupRequest): Promise<StorageCleanupResponse>;
};
// ---- debug tools (action tester + live event/action stream) ----
debug: {
actions(): Promise<{ actions: DebugActionDoc[]; categories: { category: string; count: number }[] }>;
@@ -0,0 +1,75 @@
import {
ALL_ACCOUNTS_CONFIRMATION,
type LogStorageSettings,
type LogStorageSettingsField,
type LogStorageSettingsPatch,
type LogStorageState,
} from '@/types';
export type StorageTone = 'neutral' | 'success' | 'warning' | 'danger';
export interface LogStoragePresentation {
label: string;
tone: StorageTone;
percent: number;
}
export function formatBytes(bytes: number): string {
const safeBytes = Number.isFinite(bytes) ? Math.max(0, bytes) : 0;
if (safeBytes < 1024) return `${Math.round(safeBytes)} B`;
const units = ['KB', 'MB', 'GB', 'TB', 'PB'];
let value = safeBytes / 1024;
let unitIndex = 0;
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024;
unitIndex += 1;
}
const rounded = value < 10 && !Number.isInteger(value)
? Number(value.toFixed(1))
: Math.round(value);
return `${rounded} ${units[unitIndex]}`;
}
export function buildLogSettingsPatch(
current: LogStorageSettings,
saved: LogStorageSettings,
lockedFields: LogStorageSettingsField[],
): LogStorageSettingsPatch {
const locked = new Set(lockedFields);
const patch: LogStorageSettingsPatch = {};
if (!locked.has('logMaxTotalMb') && current.logMaxTotalMb !== saved.logMaxTotalMb) {
patch.logMaxTotalMb = current.logMaxTotalMb;
}
if (!locked.has('logRetainDays') && current.logRetainDays !== saved.logRetainDays) {
patch.logRetainDays = current.logRetainDays;
}
if (!locked.has('logPerUin') && current.logPerUin !== saved.logPerUin) {
patch.logPerUin = current.logPerUin;
}
return patch;
}
export function logStoragePresentation(input: {
state: LogStorageState;
totalBytes: number;
maxTotalBytes: number;
}): LogStoragePresentation {
const percent = input.maxTotalBytes > 0
? Math.max(0, Math.min(100, (input.totalBytes / input.maxTotalBytes) * 100))
: 0;
if (input.state === 'degraded') {
return { label: '磁盘写入已暂停', tone: 'danger', percent };
}
if (input.state === 'warning') {
return { label: '清理异常', tone: 'warning', percent };
}
if (input.state === 'disabled') {
return { label: '文件日志已关闭', tone: 'neutral', percent };
}
if (percent >= 80) return { label: '接近上限', tone: 'warning', percent };
return { label: '正常', tone: 'success', percent };
}
export function isAllAccountsConfirmation(value: string): boolean {
return value === ALL_ACCOUNTS_CONFIRMATION;
}
+1 -1
View File
@@ -74,7 +74,7 @@ const debugRoute = createRoute({
});
/** Settings sub-tabs — also the contract for the `?tab=` deep link. */
export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'notifications', 'globalConfig', 'about'] as const;
export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'storage', 'notifications', 'globalConfig', 'about'] as const;
export type SettingsTab = (typeof SETTINGS_TABS)[number];
export const settingsRoute = createRoute({
+132
View File
@@ -173,6 +173,138 @@ export interface SystemSettingsResponse {
restartRequiredToApply: boolean;
}
// Storage management under Settings → SnowLuma → 存储管理.
export type LogStorageState = 'disabled' | 'healthy' | 'warning' | 'degraded';
export interface LogStorageStatus {
state: LogStorageState;
totalBytes: number;
maxTotalBytes: number;
retainDays: number;
perUinEnabled: boolean;
fileCount: number;
activeFileCount: number;
droppedLines: number;
lastError?: string;
}
export interface LogStorageSettings {
logMaxTotalMb: number;
logRetainDays: number;
logPerUin: boolean;
}
export type LogStorageSettingsField = keyof LogStorageSettings;
export type LogStorageSettingsPatch = Partial<LogStorageSettings>;
export interface LogStorageSettingsState {
saved: LogStorageSettings;
effective: LogStorageSettings;
envOverrides: LogStorageSettingsField[];
}
export interface TemporaryStorageSnapshot {
totalBytes: number;
fileCount: number;
activeItemCount: number;
}
export interface AccountStorageSnapshot {
uin: string;
nickname?: string;
online: boolean;
messagesBytes: number;
mediaBytes: number;
reactionsBytes: number;
totalBytes: number;
}
export interface StorageSnapshot {
logs: LogStorageStatus;
temporary: TemporaryStorageSnapshot;
accounts: AccountStorageSnapshot[];
totals: {
logsBytes: number;
temporaryBytes: number;
accountDataBytes: number;
managedBytes: number;
};
}
export type AccountStorageCategory = 'messages' | 'media' | 'reactions';
export type StorageCleanupScope = 'logs' | 'temporary' | 'account' | 'allAccounts';
export interface LastStorageCleanup {
at: string;
scope: StorageCleanupScope;
accountScope: 'global' | 'single' | 'all';
category?: AccountStorageCategory;
uin?: string;
deletedFiles: number;
freedBytes: number;
failureCount: number;
skippedActiveItems?: number;
failures: StorageCleanupFailure[];
}
export interface StorageOverviewResponse {
settings: LogStorageSettingsState;
snapshot: StorageSnapshot;
lastCleanup: LastStorageCleanup | null;
}
export interface StorageSettingsUpdateResponse {
success: true;
settings: LogStorageSettingsState;
status: LogStorageStatus;
snapshot: StorageSnapshot;
}
export const ALL_ACCOUNTS_CONFIRMATION = '清理全部账号' as const;
export type StorageCleanupRequest =
| { scope: 'logs' }
| { scope: 'temporary' }
| { scope: 'account'; category: AccountStorageCategory; uin: string }
| {
scope: 'allAccounts';
category: AccountStorageCategory;
confirmation: typeof ALL_ACCOUNTS_CONFIRMATION;
};
export interface StorageCleanupFailure {
item?: string;
file?: string;
uin?: string;
message: string;
}
export type StorageCleanupResult =
| {
deletedFiles: number;
freedBytes: number;
failures: StorageCleanupFailure[];
status: LogStorageStatus;
}
| {
deletedFiles: number;
freedBytes: number;
skippedActiveItems: number;
failures: StorageCleanupFailure[];
}
| {
category: AccountStorageCategory;
uins: string[];
deletedFiles: number;
freedBytes: number;
failures: StorageCleanupFailure[];
};
export interface StorageCleanupResponse {
success: boolean;
message?: string;
scope: StorageCleanupScope;
cleanup: StorageCleanupResult;
snapshot?: StorageSnapshot;
lastCleanup?: LastStorageCleanup;
}
// Debug tools (Wave A3; roles + streaming added in the console expansion).
/** Semantic role of a param, mirrored from the backend's `FieldRole`. Drives
+108
View File
@@ -0,0 +1,108 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
const tokenStore = {
load: () => 'test-token',
save: () => undefined,
};
afterEach(() => {
vi.unstubAllGlobals();
});
describe('storage API client', () => {
it('reads the authenticated storage overview', async () => {
const payload = {
settings: {
saved: { logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false },
effective: { logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false },
envOverrides: [],
},
snapshot: {
logs: {
state: 'healthy',
totalBytes: 0,
maxTotalBytes: 1024 * 1024 * 1024,
retainDays: 7,
perUinEnabled: false,
fileCount: 1,
activeFileCount: 1,
droppedLines: 0,
},
temporary: { totalBytes: 0, fileCount: 0, activeItemCount: 0 },
accounts: [],
totals: { logsBytes: 0, temporaryBytes: 0, accountDataBytes: 0, managedBytes: 0 },
},
lastCleanup: null,
};
const fetchMock = vi.fn(async () => new Response(JSON.stringify(payload), {
status: 200,
headers: { 'content-type': 'application/json' },
}));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
await expect(client.storage.get()).resolves.toEqual(payload);
expect(fetchMock).toHaveBeenCalledWith('/api/system/storage', {
headers: { Authorization: 'Bearer test-token' },
});
});
it('posts a partial log-settings patch', async () => {
const fetchMock = vi.fn(async () => new Response(JSON.stringify({
success: true,
settings: {
saved: { logMaxTotalMb: 1024, logRetainDays: 0, logPerUin: false },
effective: { logMaxTotalMb: 1024, logRetainDays: 0, logPerUin: false },
envOverrides: [],
},
status: { state: 'healthy' },
snapshot: {},
}), { status: 200, headers: { 'content-type': 'application/json' } }));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
await client.storage.saveSettings({ logRetainDays: 0 });
expect(fetchMock).toHaveBeenCalledWith('/api/system/storage/settings', {
method: 'POST',
body: JSON.stringify({ logRetainDays: 0 }),
headers: {
Authorization: 'Bearer test-token',
'Content-Type': 'application/json',
},
});
});
it('returns a structured partial cleanup result from an HTTP 500 response', async () => {
const payload = {
success: false,
message: '部分文件清理失败,请检查失败明细',
scope: 'temporary',
cleanup: {
deletedFiles: 1,
freedBytes: 5,
skippedActiveItems: 0,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
},
snapshot: {},
lastCleanup: {
at: '2026-07-24T04:00:00.000Z',
scope: 'temporary',
accountScope: 'global',
deletedFiles: 1,
freedBytes: 5,
failureCount: 1,
skippedActiveItems: 0,
failures: [{ item: 'locked.bin', message: 'permission denied' }],
},
};
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(payload), {
status: 500,
headers: { 'content-type': 'application/json' },
})));
const client = createApiClient({ tokenStore });
await expect(client.storage.cleanup({ scope: 'temporary' })).resolves.toEqual(payload);
});
});
@@ -0,0 +1,50 @@
import { describe, expect, it } from 'vitest';
import {
buildLogSettingsPatch,
formatBytes,
isAllAccountsConfirmation,
logStoragePresentation,
} from '../src/lib/storage-presentation';
describe('storage presentation helpers', () => {
it('omits environment-locked and unchanged fields from a settings patch', () => {
expect(buildLogSettingsPatch(
{ logMaxTotalMb: 2048, logRetainDays: 0, logPerUin: true },
{ logMaxTotalMb: 1024, logRetainDays: 7, logPerUin: false },
['logMaxTotalMb'],
)).toEqual({
logRetainDays: 0,
logPerUin: true,
});
});
it('prioritizes degraded state over capacity percentage and warns at 80 percent', () => {
expect(logStoragePresentation({
state: 'degraded',
totalBytes: 10,
maxTotalBytes: 100,
})).toMatchObject({ label: '磁盘写入已暂停', tone: 'danger', percent: 10 });
expect(logStoragePresentation({
state: 'healthy',
totalBytes: 80,
maxTotalBytes: 100,
})).toMatchObject({ label: '接近上限', tone: 'warning', percent: 80 });
expect(logStoragePresentation({
state: 'healthy',
totalBytes: 20,
maxTotalBytes: 100,
})).toMatchObject({ label: '正常', tone: 'success', percent: 20 });
});
it('formats byte counts without exposing implementation units', () => {
expect(formatBytes(0)).toBe('0 B');
expect(formatBytes(1536)).toBe('1.5 KB');
expect(formatBytes(1024 * 1024)).toBe('1 MB');
});
it('requires the exact all-account confirmation phrase', () => {
expect(isAllAccountsConfirmation('清理全部账号')).toBe(true);
expect(isAllAccountsConfirmation(' 清理全部账号 ')).toBe(false);
expect(isAllAccountsConfirmation('确认')).toBe(false);
});
});