lint
This commit is contained in:
977 files changed
+198426
-158324
No files matched your search
+332
-256
@@ -3,10 +3,10 @@ import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import {
|
||||
parseTotpStateLenient,
|
||||
prepareTotpStateForRestore,
|
||||
rewrapTotpSecret,
|
||||
type TotpPersistedState,
|
||||
parseTotpStateLenient,
|
||||
prepareTotpStateForRestore,
|
||||
rewrapTotpSecret,
|
||||
type TotpPersistedState,
|
||||
} from './totp';
|
||||
|
||||
const log = createLogger('WebUI.Auth');
|
||||
@@ -22,53 +22,62 @@ const SCRYPT_P = 1;
|
||||
const DEV_PASSWORD = 'snowluma-dev';
|
||||
|
||||
export function isDevAuthMode(): boolean {
|
||||
return process.env.SNOWLUMA_DEV_MODE === '1';
|
||||
return process.env.SNOWLUMA_DEV_MODE === '1';
|
||||
}
|
||||
|
||||
function envBootstrapPassword(): string | null {
|
||||
const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
|
||||
if (!raw || typeof raw !== 'string') return null;
|
||||
if (raw.length < 8) return null;
|
||||
return raw;
|
||||
const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
|
||||
|
||||
if (!raw || typeof raw !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (raw.length < 8) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return raw;
|
||||
}
|
||||
|
||||
export interface WebuiAuthState {
|
||||
passwordHash: string; // hex
|
||||
passwordSalt: string; // hex
|
||||
mustChangePassword: boolean;
|
||||
generatedAt: string;
|
||||
updatedAt: string;
|
||||
totp?: TotpPersistedState;
|
||||
passwordHash: string; // hex
|
||||
passwordSalt: string; // hex
|
||||
mustChangePassword: boolean;
|
||||
generatedAt: string;
|
||||
updatedAt: string;
|
||||
totp?: TotpPersistedState;
|
||||
}
|
||||
|
||||
export interface PasswordRule {
|
||||
id: string;
|
||||
label: string;
|
||||
test: (pwd: string) => boolean;
|
||||
id: string;
|
||||
label: string;
|
||||
test: (pwd: string) => boolean;
|
||||
}
|
||||
|
||||
export const PASSWORD_RULES: PasswordRule[] = [
|
||||
{ id: 'length', label: '长度不少于 10 位', test: (p) => p.length >= 10 },
|
||||
{ id: 'lower', label: '包含小写字母', test: (p) => /[a-z]/.test(p) },
|
||||
{ id: 'upper', label: '包含大写字母', test: (p) => /[A-Z]/.test(p) },
|
||||
{ id: 'special', label: '包含特殊符号 (!@#$%…)', test: (p) => /[^A-Za-z0-9\s]/.test(p) },
|
||||
{ id: 'no-space', label: '不包含空格', test: (p) => !/\s/.test(p) && p.length > 0 },
|
||||
{ id: 'length', label: '长度不少于 10 位', test: (p) => p.length >= 10 },
|
||||
{ id: 'lower', label: '包含小写字母', test: (p) => /[a-z]/.test(p) },
|
||||
{ id: 'upper', label: '包含大写字母', test: (p) => /[A-Z]/.test(p) },
|
||||
{ id: 'special', label: '包含特殊符号 (!@#$%…)', test: (p) => /[^A-Za-z0-9\s]/.test(p) },
|
||||
{ id: 'no-space', label: '不包含空格', test: (p) => !/\s/.test(p) && p.length > 0 },
|
||||
];
|
||||
|
||||
export function evaluatePasswordRules(password: string): { id: string; label: string; ok: boolean }[] {
|
||||
return PASSWORD_RULES.map((r) => ({ id: r.id, label: r.label, ok: r.test(password) }));
|
||||
export function evaluatePasswordRules(
|
||||
password: string,
|
||||
): { id: string; label: string; ok: boolean }[] {
|
||||
return PASSWORD_RULES.map((r) => ({ id: r.id, label: r.label, ok: r.test(password) }));
|
||||
}
|
||||
|
||||
export function isStrongPassword(password: string): boolean {
|
||||
return PASSWORD_RULES.every((r) => r.test(password));
|
||||
return PASSWORD_RULES.every((r) => r.test(password));
|
||||
}
|
||||
|
||||
function hashPassword(password: string, salt: Buffer): Buffer {
|
||||
return scryptSync(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
|
||||
return scryptSync(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
|
||||
}
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -79,265 +88,332 @@ function ensureConfigDir(): void {
|
||||
* operator would be locked out after a restore.
|
||||
*/
|
||||
export function prepareWebuiAuthStateForRestore(value: unknown): WebuiAuthState {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error('credential state must be an object');
|
||||
}
|
||||
const v = value as Record<string, unknown>;
|
||||
if (typeof v.passwordHash !== 'string' || !/^[0-9a-f]{128}$/i.test(v.passwordHash)) {
|
||||
throw new Error('passwordHash must be exactly 128 hexadecimal characters');
|
||||
}
|
||||
if (typeof v.passwordSalt !== 'string' || !/^[0-9a-f]{32}$/i.test(v.passwordSalt)) {
|
||||
throw new Error('passwordSalt must be exactly 32 hexadecimal characters');
|
||||
}
|
||||
if (typeof v.mustChangePassword !== 'boolean') {
|
||||
throw new Error('mustChangePassword must be a boolean');
|
||||
}
|
||||
if (typeof v.generatedAt !== 'string' || !Number.isFinite(Date.parse(v.generatedAt))) {
|
||||
throw new Error('generatedAt must be a valid timestamp');
|
||||
}
|
||||
if (typeof v.updatedAt !== 'string' || !Number.isFinite(Date.parse(v.updatedAt))) {
|
||||
throw new Error('updatedAt must be a valid timestamp');
|
||||
}
|
||||
const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt', 'totp']);
|
||||
const unknown = Object.keys(v).find((key) => !allowed.has(key));
|
||||
if (unknown) throw new Error(`unknown field $.${unknown}`);
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: v.passwordHash,
|
||||
passwordSalt: v.passwordSalt,
|
||||
mustChangePassword: v.mustChangePassword,
|
||||
generatedAt: v.generatedAt,
|
||||
updatedAt: v.updatedAt,
|
||||
};
|
||||
if (!Object.prototype.hasOwnProperty.call(v, 'totp') || v.totp === undefined) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error('credential state must be an object');
|
||||
}
|
||||
|
||||
const v = value as Record<string, unknown>;
|
||||
|
||||
if (typeof v.passwordHash !== 'string' || !/^[0-9a-f]{128}$/i.test(v.passwordHash)) {
|
||||
throw new Error('passwordHash must be exactly 128 hexadecimal characters');
|
||||
}
|
||||
|
||||
if (typeof v.passwordSalt !== 'string' || !/^[0-9a-f]{32}$/i.test(v.passwordSalt)) {
|
||||
throw new Error('passwordSalt must be exactly 32 hexadecimal characters');
|
||||
}
|
||||
|
||||
if (typeof v.mustChangePassword !== 'boolean') {
|
||||
throw new Error('mustChangePassword must be a boolean');
|
||||
}
|
||||
|
||||
if (typeof v.generatedAt !== 'string' || !Number.isFinite(Date.parse(v.generatedAt))) {
|
||||
throw new Error('generatedAt must be a valid timestamp');
|
||||
}
|
||||
|
||||
if (typeof v.updatedAt !== 'string' || !Number.isFinite(Date.parse(v.updatedAt))) {
|
||||
throw new Error('updatedAt must be a valid timestamp');
|
||||
}
|
||||
|
||||
const allowed = new Set([
|
||||
'passwordHash',
|
||||
'passwordSalt',
|
||||
'mustChangePassword',
|
||||
'generatedAt',
|
||||
'updatedAt',
|
||||
'totp',
|
||||
]);
|
||||
const unknown = Object.keys(v).find((key) => !allowed.has(key));
|
||||
|
||||
if (unknown) {
|
||||
throw new Error(`unknown field $.${unknown}`);
|
||||
}
|
||||
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: v.passwordHash,
|
||||
passwordSalt: v.passwordSalt,
|
||||
mustChangePassword: v.mustChangePassword,
|
||||
generatedAt: v.generatedAt,
|
||||
updatedAt: v.updatedAt,
|
||||
};
|
||||
|
||||
if (!Object.prototype.hasOwnProperty.call(v, 'totp') || v.totp === undefined) {
|
||||
return state;
|
||||
}
|
||||
|
||||
state.totp = prepareTotpStateForRestore(v.totp);
|
||||
return state;
|
||||
}
|
||||
state.totp = prepareTotpStateForRestore(v.totp);
|
||||
return state;
|
||||
}
|
||||
|
||||
function parseLiveAuthState(value: unknown): WebuiAuthState | null {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
||||
const v = value as Record<string, unknown>;
|
||||
const totpValue = v.totp;
|
||||
const withoutTotp = { ...v };
|
||||
delete withoutTotp.totp;
|
||||
try {
|
||||
const state = prepareWebuiAuthStateForRestore(
|
||||
Object.prototype.hasOwnProperty.call(v, 'totp')
|
||||
? withoutTotp
|
||||
: value,
|
||||
);
|
||||
const totp = parseTotpStateLenient(totpValue);
|
||||
if (Object.prototype.hasOwnProperty.call(v, 'totp') && totpValue !== undefined && !totp) {
|
||||
log.warn('webui.json totp field is invalid and will be ignored; password credentials are unchanged');
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const v = value as Record<string, unknown>;
|
||||
const totpValue = v.totp;
|
||||
const withoutTotp = { ...v };
|
||||
delete withoutTotp.totp;
|
||||
|
||||
try {
|
||||
const state = prepareWebuiAuthStateForRestore(
|
||||
Object.prototype.hasOwnProperty.call(v, 'totp') ? withoutTotp : value,
|
||||
);
|
||||
const totp = parseTotpStateLenient(totpValue);
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(v, 'totp') && totpValue !== undefined && !totp) {
|
||||
log.warn(
|
||||
'webui.json totp field is invalid and will be ignored; password credentials are unchanged',
|
||||
);
|
||||
}
|
||||
|
||||
if (totp) {
|
||||
state.totp = totp;
|
||||
}
|
||||
|
||||
return state;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (totp) state.totp = totp;
|
||||
return state;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function generateInitialState(initialPassword: string): WebuiAuthState {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(initialPassword, salt);
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: true,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(initialPassword, salt);
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: true,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
function backupCorruptConfig(): void {
|
||||
try {
|
||||
const dest = `${WEBUI_CONFIG_PATH}.bak.${Date.now()}`;
|
||||
fs.renameSync(WEBUI_CONFIG_PATH, dest);
|
||||
log.warn('previous webui.json moved to %s', dest);
|
||||
} catch (err) {
|
||||
log.warn('failed to back up corrupt webui.json: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
try {
|
||||
const dest = `${WEBUI_CONFIG_PATH}.bak.${Date.now()}`;
|
||||
fs.renameSync(WEBUI_CONFIG_PATH, dest);
|
||||
log.warn('previous webui.json moved to %s', dest);
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'failed to back up corrupt webui.json: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function atomicWrite(state: WebuiAuthState): void {
|
||||
ensureConfigDir();
|
||||
const tmp = WEBUI_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 });
|
||||
try {
|
||||
fs.chmodSync(tmp, 0o600);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
fs.renameSync(tmp, WEBUI_CONFIG_PATH);
|
||||
ensureConfigDir();
|
||||
const tmp = WEBUI_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 });
|
||||
|
||||
try {
|
||||
fs.chmodSync(tmp, 0o600);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
fs.renameSync(tmp, WEBUI_CONFIG_PATH);
|
||||
}
|
||||
|
||||
export class WebuiAuth {
|
||||
private state: WebuiAuthState;
|
||||
private initialPlain: string | null;
|
||||
private readonly devMode: boolean;
|
||||
private state: WebuiAuthState;
|
||||
private initialPlain: string | null;
|
||||
private readonly devMode: boolean;
|
||||
|
||||
private constructor(state: WebuiAuthState, initialPlain: string | null, devMode: boolean) {
|
||||
this.state = state;
|
||||
this.initialPlain = initialPlain;
|
||||
this.devMode = devMode;
|
||||
}
|
||||
|
||||
static load(): WebuiAuth {
|
||||
if (isDevAuthMode()) {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(DEV_PASSWORD, salt);
|
||||
const now = new Date().toISOString();
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
return new WebuiAuth(state, null, true);
|
||||
private constructor(state: WebuiAuthState, initialPlain: string | null, devMode: boolean) {
|
||||
this.state = state;
|
||||
this.initialPlain = initialPlain;
|
||||
this.devMode = devMode;
|
||||
}
|
||||
ensureConfigDir();
|
||||
if (fs.existsSync(WEBUI_CONFIG_PATH)) {
|
||||
try {
|
||||
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
const live = parseLiveAuthState(parsed);
|
||||
if (live) {
|
||||
if (live.mustChangePassword) {
|
||||
// Previous start generated a bootstrap password but the operator
|
||||
// never completed the forced-change flow. The plaintext is gone
|
||||
// (only the hash is on disk, and the log line from last run may
|
||||
// be lost), so rotate to a fresh CSPRNG password they can see.
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
log.warn('previous bootstrap password was never rotated; regenerated a new one');
|
||||
return new WebuiAuth(state, initialPassword, false);
|
||||
}
|
||||
return new WebuiAuth(live, null, false);
|
||||
|
||||
static load(): WebuiAuth {
|
||||
if (isDevAuthMode()) {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(DEV_PASSWORD, salt);
|
||||
const now = new Date().toISOString();
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
return new WebuiAuth(state, null, true);
|
||||
}
|
||||
log.error('webui.json schema invalid; backing up and regenerating credentials');
|
||||
backupCorruptConfig();
|
||||
} catch (err) {
|
||||
log.error(
|
||||
'webui.json is corrupt and will be regenerated; the previous file is backed up: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
backupCorruptConfig();
|
||||
}
|
||||
|
||||
ensureConfigDir();
|
||||
|
||||
if (fs.existsSync(WEBUI_CONFIG_PATH)) {
|
||||
try {
|
||||
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
const live = parseLiveAuthState(parsed);
|
||||
|
||||
if (live) {
|
||||
if (live.mustChangePassword) {
|
||||
// Previous start generated a bootstrap password but the operator
|
||||
// never completed the forced-change flow. The plaintext is gone
|
||||
// (only the hash is on disk, and the log line from last run may
|
||||
// be lost), so rotate to a fresh CSPRNG password they can see.
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
log.warn(
|
||||
'previous bootstrap password was never rotated; regenerated a new one',
|
||||
);
|
||||
return new WebuiAuth(state, initialPassword, false);
|
||||
}
|
||||
|
||||
return new WebuiAuth(live, null, false);
|
||||
}
|
||||
|
||||
log.error('webui.json schema invalid; backing up and regenerating credentials');
|
||||
backupCorruptConfig();
|
||||
} catch (err) {
|
||||
log.error(
|
||||
'webui.json is corrupt and will be regenerated; the previous file is backed up: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
backupCorruptConfig();
|
||||
}
|
||||
}
|
||||
|
||||
const envPassword = envBootstrapPassword();
|
||||
|
||||
if (envPassword !== null) {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(envPassword, salt);
|
||||
const now = new Date().toISOString();
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
atomicWrite(state);
|
||||
log.info('webui credentials seeded from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD');
|
||||
return new WebuiAuth(state, null, false);
|
||||
}
|
||||
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
return new WebuiAuth(state, initialPassword, false);
|
||||
}
|
||||
const envPassword = envBootstrapPassword();
|
||||
if (envPassword !== null) {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(envPassword, salt);
|
||||
const now = new Date().toISOString();
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
atomicWrite(state);
|
||||
log.info('webui credentials seeded from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD');
|
||||
return new WebuiAuth(state, null, false);
|
||||
|
||||
/** True when SNOWLUMA_DEV_MODE was active at load time. */
|
||||
isDevMode(): boolean {
|
||||
return this.devMode;
|
||||
}
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
return new WebuiAuth(state, initialPassword, false);
|
||||
}
|
||||
|
||||
/** True when SNOWLUMA_DEV_MODE was active at load time. */
|
||||
isDevMode(): boolean {
|
||||
return this.devMode;
|
||||
}
|
||||
|
||||
/** Fixed dev password (only meaningful when {@link isDevMode} is true). */
|
||||
static get devPassword(): string {
|
||||
return DEV_PASSWORD;
|
||||
}
|
||||
|
||||
/** Returns the auto-generated initial password if this is a fresh install, else null. */
|
||||
takeInitialPassword(): string | null {
|
||||
const p = this.initialPlain;
|
||||
this.initialPlain = null;
|
||||
return p;
|
||||
}
|
||||
|
||||
mustChangePassword(): boolean {
|
||||
return this.state.mustChangePassword;
|
||||
}
|
||||
|
||||
verify(password: string): boolean {
|
||||
if (typeof password !== 'string' || password.length === 0) return false;
|
||||
try {
|
||||
const salt = Buffer.from(this.state.passwordSalt, 'hex');
|
||||
const expected = Buffer.from(this.state.passwordHash, 'hex');
|
||||
const got = hashPassword(password, salt);
|
||||
if (got.length !== expected.length) return false;
|
||||
return timingSafeEqual(got, expected);
|
||||
} catch {
|
||||
return false;
|
||||
/** Fixed dev password (only meaningful when {@link isDevMode} is true). */
|
||||
static get devPassword(): string {
|
||||
return DEV_PASSWORD;
|
||||
}
|
||||
}
|
||||
|
||||
setPassword(newPassword: string, currentPassword?: string): void {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
|
||||
/** Returns the auto-generated initial password if this is a fresh install, else null. */
|
||||
takeInitialPassword(): string | null {
|
||||
const p = this.initialPlain;
|
||||
this.initialPlain = null;
|
||||
return p;
|
||||
}
|
||||
if (!isStrongPassword(newPassword)) {
|
||||
throw new Error('密码不符合强度要求');
|
||||
|
||||
mustChangePassword(): boolean {
|
||||
return this.state.mustChangePassword;
|
||||
}
|
||||
let totp = this.state.totp;
|
||||
if (totp) {
|
||||
if (typeof currentPassword !== 'string' || currentPassword.length === 0) {
|
||||
throw new Error('修改密码需要当前密码以重新保护 2FA 密钥');
|
||||
}
|
||||
totp = rewrapTotpSecret(currentPassword, newPassword, totp);
|
||||
|
||||
verify(password: string): boolean {
|
||||
if (typeof password !== 'string' || password.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const salt = Buffer.from(this.state.passwordSalt, 'hex');
|
||||
const expected = Buffer.from(this.state.passwordHash, 'hex');
|
||||
const got = hashPassword(password, salt);
|
||||
|
||||
if (got.length !== expected.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return timingSafeEqual(got, expected);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(newPassword, salt);
|
||||
const next: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: this.state.generatedAt,
|
||||
updatedAt: new Date().toISOString(),
|
||||
...(totp ? { totp } : {}),
|
||||
};
|
||||
atomicWrite(next);
|
||||
this.state = next;
|
||||
}
|
||||
|
||||
totpEnabled(): boolean {
|
||||
return this.state.totp !== undefined;
|
||||
}
|
||||
setPassword(newPassword: string, currentPassword?: string): void {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
|
||||
}
|
||||
|
||||
totpStatus(): { enabled: false } | { enabled: true; remainingRecoveryCodes: number; label: string } {
|
||||
const totp = this.state.totp;
|
||||
if (!totp) return { enabled: false };
|
||||
return {
|
||||
enabled: true,
|
||||
remainingRecoveryCodes: totp.recoveryCodeHashes.length,
|
||||
label: totp.label,
|
||||
};
|
||||
}
|
||||
if (!isStrongPassword(newPassword)) {
|
||||
throw new Error('密码不符合强度要求');
|
||||
}
|
||||
|
||||
totpState(): TotpPersistedState | undefined {
|
||||
return this.state.totp;
|
||||
}
|
||||
let totp = this.state.totp;
|
||||
|
||||
persistTotp(totp: TotpPersistedState | undefined): void {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用 2FA');
|
||||
if (totp) {
|
||||
if (typeof currentPassword !== 'string' || currentPassword.length === 0) {
|
||||
throw new Error('修改密码需要当前密码以重新保护 2FA 密钥');
|
||||
}
|
||||
|
||||
totp = rewrapTotpSecret(currentPassword, newPassword, totp);
|
||||
}
|
||||
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(newPassword, salt);
|
||||
const next: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: this.state.generatedAt,
|
||||
updatedAt: new Date().toISOString(),
|
||||
...(totp ? { totp } : {}),
|
||||
};
|
||||
atomicWrite(next);
|
||||
this.state = next;
|
||||
}
|
||||
|
||||
totpEnabled(): boolean {
|
||||
return this.state.totp !== undefined;
|
||||
}
|
||||
|
||||
totpStatus():
|
||||
{ enabled: false } | { enabled: true; remainingRecoveryCodes: number; label: string } {
|
||||
const totp = this.state.totp;
|
||||
|
||||
if (!totp) {
|
||||
return { enabled: false };
|
||||
}
|
||||
|
||||
return {
|
||||
enabled: true,
|
||||
remainingRecoveryCodes: totp.recoveryCodeHashes.length,
|
||||
label: totp.label,
|
||||
};
|
||||
}
|
||||
|
||||
totpState(): TotpPersistedState | undefined {
|
||||
return this.state.totp;
|
||||
}
|
||||
|
||||
persistTotp(totp: TotpPersistedState | undefined): void {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用 2FA');
|
||||
}
|
||||
|
||||
const next: WebuiAuthState = { ...this.state, updatedAt: new Date().toISOString() };
|
||||
|
||||
if (totp) {
|
||||
next.totp = totp;
|
||||
} else {
|
||||
delete next.totp;
|
||||
}
|
||||
|
||||
atomicWrite(next);
|
||||
this.state = next;
|
||||
}
|
||||
const next: WebuiAuthState = { ...this.state, updatedAt: new Date().toISOString() };
|
||||
if (totp) next.totp = totp;
|
||||
else delete next.totp;
|
||||
atomicWrite(next);
|
||||
this.state = next;
|
||||
}
|
||||
}
|
||||
+649
-381
File diff suppressed because it is too large.
Load diff
@@ -2,88 +2,131 @@ import { getConnInfo } from '@hono/node-server/conninfo';
|
||||
import type { Context } from 'hono';
|
||||
|
||||
export type TrustProxyMode =
|
||||
| { kind: 'none' }
|
||||
| { kind: 'loopback' }
|
||||
| { kind: 'all' }
|
||||
| { kind: 'ip-list'; ips: Set<string> };
|
||||
| { kind: 'none' }
|
||||
| { kind: 'loopback' }
|
||||
| { kind: 'all' }
|
||||
| { kind: 'ip-list'; ips: Set<string> };
|
||||
|
||||
export function parseTrustProxy(raw: string | undefined): TrustProxyMode {
|
||||
const value = raw?.trim().toLowerCase() ?? '';
|
||||
if (!value) return { kind: 'none' };
|
||||
if (value === '1' || value === 'true' || value === 'all') return { kind: 'all' };
|
||||
if (value === 'loopback') return { kind: 'loopback' };
|
||||
const ips = new Set(
|
||||
value.split(',').map((s) => s.trim()).filter(Boolean),
|
||||
);
|
||||
if (ips.size === 0) return { kind: 'none' };
|
||||
return { kind: 'ip-list', ips };
|
||||
const value = raw?.trim().toLowerCase() ?? '';
|
||||
|
||||
if (!value) {
|
||||
return { kind: 'none' };
|
||||
}
|
||||
|
||||
if (value === '1' || value === 'true' || value === 'all') {
|
||||
return { kind: 'all' };
|
||||
}
|
||||
|
||||
if (value === 'loopback') {
|
||||
return { kind: 'loopback' };
|
||||
}
|
||||
|
||||
const ips = new Set(
|
||||
value
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
);
|
||||
|
||||
if (ips.size === 0) {
|
||||
return { kind: 'none' };
|
||||
}
|
||||
|
||||
return { kind: 'ip-list', ips };
|
||||
}
|
||||
|
||||
export function describeTrustProxy(mode: TrustProxyMode): string {
|
||||
switch (mode.kind) {
|
||||
case 'none': return 'socket peer (default)';
|
||||
case 'all': return 'X-Real-IP / X-Forwarded-For from any peer';
|
||||
case 'loopback': return 'X-Real-IP / X-Forwarded-For when socket peer is loopback';
|
||||
case 'ip-list': return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`;
|
||||
}
|
||||
switch (mode.kind) {
|
||||
case 'none':
|
||||
return 'socket peer (default)';
|
||||
case 'all':
|
||||
return 'X-Real-IP / X-Forwarded-For from any peer';
|
||||
case 'loopback':
|
||||
return 'X-Real-IP / X-Forwarded-For when socket peer is loopback';
|
||||
case 'ip-list':
|
||||
return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`;
|
||||
}
|
||||
}
|
||||
|
||||
export function isLoopbackClientIp(ip: string): boolean {
|
||||
const normalized = ip.trim().toLowerCase();
|
||||
if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') return true;
|
||||
if (normalized.startsWith('::ffff:')) {
|
||||
return isLoopbackClientIp(normalized.slice('::ffff:'.length));
|
||||
}
|
||||
const octets = normalized.split('.');
|
||||
return octets.length === 4
|
||||
&& octets[0] === '127'
|
||||
&& octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
|
||||
const normalized = ip.trim().toLowerCase();
|
||||
|
||||
if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (normalized.startsWith('::ffff:')) {
|
||||
return isLoopbackClientIp(normalized.slice('::ffff:'.length));
|
||||
}
|
||||
|
||||
const octets = normalized.split('.');
|
||||
return (
|
||||
octets.length === 4 &&
|
||||
octets[0] === '127' &&
|
||||
octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255)
|
||||
);
|
||||
}
|
||||
|
||||
function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean {
|
||||
switch (mode.kind) {
|
||||
case 'none': return false;
|
||||
case 'all': return true;
|
||||
case 'loopback': return isLoopbackClientIp(socketIp);
|
||||
case 'ip-list': return mode.ips.has(socketIp);
|
||||
}
|
||||
switch (mode.kind) {
|
||||
case 'none':
|
||||
return false;
|
||||
case 'all':
|
||||
return true;
|
||||
case 'loopback':
|
||||
return isLoopbackClientIp(socketIp);
|
||||
case 'ip-list':
|
||||
return mode.ips.has(socketIp);
|
||||
}
|
||||
}
|
||||
|
||||
export function pickClientIp(
|
||||
c: Pick<Context, 'req'>,
|
||||
mode: TrustProxyMode,
|
||||
getSocketIp: () => string,
|
||||
fallbackIp = '127.0.0.1',
|
||||
c: Pick<Context, 'req'>,
|
||||
mode: TrustProxyMode,
|
||||
getSocketIp: () => string,
|
||||
fallbackIp = '127.0.0.1',
|
||||
): string {
|
||||
let socketIp: string;
|
||||
try {
|
||||
socketIp = getSocketIp();
|
||||
} catch {
|
||||
return fallbackIp;
|
||||
}
|
||||
if (!socketIp) return fallbackIp;
|
||||
let socketIp: string;
|
||||
|
||||
if (!shouldTrustHeaders(mode, socketIp)) return socketIp;
|
||||
try {
|
||||
socketIp = getSocketIp();
|
||||
} catch {
|
||||
return fallbackIp;
|
||||
}
|
||||
|
||||
const realIp = c.req.header('x-real-ip')?.trim();
|
||||
if (realIp) return realIp;
|
||||
const xff = c.req.header('x-forwarded-for');
|
||||
if (xff) {
|
||||
const first = xff.split(',')[0].trim();
|
||||
if (first) return first;
|
||||
}
|
||||
return socketIp;
|
||||
if (!socketIp) {
|
||||
return fallbackIp;
|
||||
}
|
||||
|
||||
if (!shouldTrustHeaders(mode, socketIp)) {
|
||||
return socketIp;
|
||||
}
|
||||
|
||||
const realIp = c.req.header('x-real-ip')?.trim();
|
||||
|
||||
if (realIp) {
|
||||
return realIp;
|
||||
}
|
||||
|
||||
const xff = c.req.header('x-forwarded-for');
|
||||
|
||||
if (xff) {
|
||||
const first = xff.split(',')[0].trim();
|
||||
|
||||
if (first) {
|
||||
return first;
|
||||
}
|
||||
}
|
||||
|
||||
return socketIp;
|
||||
}
|
||||
|
||||
/** Convenience binding for the live server: read socket via getConnInfo. */
|
||||
export function makeClientIpResolver(
|
||||
mode: TrustProxyMode,
|
||||
fallbackIp = '127.0.0.1',
|
||||
mode: TrustProxyMode,
|
||||
fallbackIp = '127.0.0.1',
|
||||
): (c: Context) => string {
|
||||
return (c) => pickClientIp(
|
||||
c,
|
||||
mode,
|
||||
() => getConnInfo(c).remote.address ?? fallbackIp,
|
||||
fallbackIp,
|
||||
);
|
||||
return (c) =>
|
||||
pickClientIp(c, mode, () => getConnInfo(c).remote.address ?? fallbackIp, fallbackIp);
|
||||
}
|
||||
@@ -11,138 +11,149 @@
|
||||
* something update.
|
||||
*/
|
||||
|
||||
import {
|
||||
createLogger,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import { createLogger, runWithTraceRequest } from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import type { StateBus } from './state-bus';
|
||||
|
||||
const log = createLogger('WebUI.Connections');
|
||||
|
||||
export interface ConnectionDiffLoopOptions {
|
||||
bus: StateBus;
|
||||
/** Read the current adapter-status snapshot for every live UIN. */
|
||||
getSnapshot: () => unknown;
|
||||
/** Optional projector — return the "comparable" subset of the snapshot.
|
||||
* The full snapshot is what the SSE handler ships to the WebUI; this
|
||||
* projection is what the diff loop compares between ticks. Use it to
|
||||
* strip volatile fields (e.g. HH:MM:SS timestamps embedded in adapter
|
||||
* `detail` strings) that would otherwise produce a publish every tick
|
||||
* under any active webhook — defeating the loop's whole purpose.
|
||||
* Default: identity. */
|
||||
pickComparable?: (snapshot: unknown) => unknown;
|
||||
/** Poll cadence in milliseconds; default 500. */
|
||||
intervalMs?: number;
|
||||
bus: StateBus;
|
||||
/** Read the current adapter-status snapshot for every live UIN. */
|
||||
getSnapshot: () => unknown;
|
||||
/** Optional projector — return the "comparable" subset of the snapshot.
|
||||
* The full snapshot is what the SSE handler ships to the WebUI; this
|
||||
* projection is what the diff loop compares between ticks. Use it to
|
||||
* strip volatile fields (e.g. HH:MM:SS timestamps embedded in adapter
|
||||
* `detail` strings) that would otherwise produce a publish every tick
|
||||
* under any active webhook — defeating the loop's whole purpose.
|
||||
* Default: identity. */
|
||||
pickComparable?: (snapshot: unknown) => unknown;
|
||||
/** Poll cadence in milliseconds; default 500. */
|
||||
intervalMs?: number;
|
||||
}
|
||||
|
||||
export interface ConnectionDiffLoopHandle {
|
||||
/** Stop the loop. Subsequent snapshot mutations produce nothing. */
|
||||
dispose(): void;
|
||||
/** Stop the loop. Subsequent snapshot mutations produce nothing. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle {
|
||||
const intervalMs = opts.intervalMs ?? 500;
|
||||
let lastSerialized = '';
|
||||
let haveBaseline = false;
|
||||
let disposed = false;
|
||||
// One-shot diagnostic latch: a projector that starts throwing only after
|
||||
// a shape regression would otherwise wedge the baseline silently — no
|
||||
// publishes, no log, no symptom besides "the dashboard's connections
|
||||
// card stops updating". Surface it ONCE so the failure is visible.
|
||||
let warnedSnapshotThrew = false;
|
||||
let warnedProjectorThrew = false;
|
||||
const intervalMs = opts.intervalMs ?? 500;
|
||||
let lastSerialized = '';
|
||||
let haveBaseline = false;
|
||||
let disposed = false;
|
||||
// One-shot diagnostic latch: a projector that starts throwing only after
|
||||
// a shape regression would otherwise wedge the baseline silently — no
|
||||
// publishes, no log, no symptom besides "the dashboard's connections
|
||||
// card stops updating". Surface it ONCE so the failure is visible.
|
||||
let warnedSnapshotThrew = false;
|
||||
let warnedProjectorThrew = false;
|
||||
|
||||
const tick = (): void => {
|
||||
if (disposed) return;
|
||||
let snap: unknown;
|
||||
try {
|
||||
snap = opts.getSnapshot();
|
||||
} catch (err) {
|
||||
if (!warnedSnapshotThrew) {
|
||||
warnedSnapshotThrew = true;
|
||||
const tick = (): void => {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
let snap: unknown;
|
||||
|
||||
try {
|
||||
snap = opts.getSnapshot();
|
||||
} catch (err) {
|
||||
if (!warnedSnapshotThrew) {
|
||||
warnedSnapshotThrew = true;
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace('connection_diff_start phase=snapshot_read');
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=failed reason=snapshot_failed error=%j elapsedMs=%d',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Snapshot read failed (e.g. mid-shutdown). Skip this tick; the
|
||||
// next one will retry. Don't reset the baseline so we don't
|
||||
// spuriously republish when the snapshot starts working again.
|
||||
return;
|
||||
}
|
||||
|
||||
let comparable: unknown;
|
||||
|
||||
try {
|
||||
comparable = opts.pickComparable ? opts.pickComparable(snap) : snap;
|
||||
} catch (err) {
|
||||
// A buggy projector must not crash the diff loop or wedge baseline.
|
||||
// But silent wedge is its own bug class — log the FIRST occurrence
|
||||
// so an operator can find it without re-running the loop locally.
|
||||
if (!warnedProjectorThrew) {
|
||||
warnedProjectorThrew = true;
|
||||
log.error(
|
||||
'connection snapshot projector failed; updates may be stale: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace(() => [
|
||||
'connection_diff_start phase=project snapshot=%s',
|
||||
renderParamsVerbose(snap),
|
||||
]);
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=failed reason=projector_failed error=%j elapsedMs=%d',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const serialized = JSON.stringify(comparable);
|
||||
|
||||
if (!haveBaseline) {
|
||||
// First successful observation. The SSE handler's sendAllInitial
|
||||
// already shipped a `connections` frame to every connected client
|
||||
// on connect, so the baseline is what they already have — emitting
|
||||
// it again would be a duplicate. Just store it.
|
||||
lastSerialized = serialized;
|
||||
haveBaseline = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (serialized === lastSerialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastSerialized = serialized;
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace('connection_diff_start phase=snapshot_read');
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=failed reason=snapshot_failed error=%j elapsedMs=%d',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
const startedAt = Date.now();
|
||||
log.trace(() => ['connection_diff_start snapshot=%s', renderParamsVerbose(snap)]);
|
||||
log.trace('connection_diff_branch branch=publish resource=connections');
|
||||
opts.bus.publish('connections');
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=completed reason=published elapsedMs=%d',
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
}
|
||||
// Snapshot read failed (e.g. mid-shutdown). Skip this tick; the
|
||||
// next one will retry. Don't reset the baseline so we don't
|
||||
// spuriously republish when the snapshot starts working again.
|
||||
return;
|
||||
}
|
||||
let comparable: unknown;
|
||||
try {
|
||||
comparable = opts.pickComparable ? opts.pickComparable(snap) : snap;
|
||||
} catch (err) {
|
||||
// A buggy projector must not crash the diff loop or wedge baseline.
|
||||
// But silent wedge is its own bug class — log the FIRST occurrence
|
||||
// so an operator can find it without re-running the loop locally.
|
||||
if (!warnedProjectorThrew) {
|
||||
warnedProjectorThrew = true;
|
||||
log.error(
|
||||
'connection snapshot projector failed; updates may be stale: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace(() => [
|
||||
'connection_diff_start phase=project snapshot=%s',
|
||||
renderParamsVerbose(snap),
|
||||
]);
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=failed reason=projector_failed error=%j elapsedMs=%d',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
const serialized = JSON.stringify(comparable);
|
||||
if (!haveBaseline) {
|
||||
// First successful observation. The SSE handler's sendAllInitial
|
||||
// already shipped a `connections` frame to every connected client
|
||||
// on connect, so the baseline is what they already have — emitting
|
||||
// it again would be a duplicate. Just store it.
|
||||
lastSerialized = serialized;
|
||||
haveBaseline = true;
|
||||
return;
|
||||
}
|
||||
if (serialized === lastSerialized) return;
|
||||
lastSerialized = serialized;
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace(() => [
|
||||
'connection_diff_start snapshot=%s',
|
||||
renderParamsVerbose(snap),
|
||||
]);
|
||||
log.trace('connection_diff_branch branch=publish resource=connections');
|
||||
opts.bus.publish('connections');
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=completed reason=published elapsedMs=%d',
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
const timer = setInterval(tick, intervalMs);
|
||||
// Don't pin the Node event loop: the loop is permanent for the server
|
||||
// lifetime by design, but tests / a future hot-reload scenario must be
|
||||
// able to exit cleanly without an outstanding interval ref. Mirrors the
|
||||
// tokenJanitor pattern in server.ts.
|
||||
timer.unref?.();
|
||||
const timer = setInterval(tick, intervalMs);
|
||||
// Don't pin the Node event loop: the loop is permanent for the server
|
||||
// lifetime by design, but tests / a future hot-reload scenario must be
|
||||
// able to exit cleanly without an outstanding interval ref. Mirrors the
|
||||
// tokenJanitor pattern in server.ts.
|
||||
timer.unref?.();
|
||||
|
||||
return {
|
||||
dispose(): void {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
return {
|
||||
dispose(): void {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
disposed = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,28 +1,31 @@
|
||||
import type { AccountConnections } from '@snowluma/onebot/manager';
|
||||
|
||||
export function comparableConnectionSnapshot(snapshot: unknown): unknown {
|
||||
if (!Array.isArray(snapshot)) return snapshot;
|
||||
return (snapshot as AccountConnections[]).map((account) => ({
|
||||
uin: account.uin,
|
||||
nickname: account.nickname,
|
||||
adapters: Array.isArray(account.adapters)
|
||||
? account.adapters.map((adapter) => ({
|
||||
name: adapter.name,
|
||||
kind: adapter.kind,
|
||||
status: adapter.status,
|
||||
lastErrorAt: adapter.lastErrorAt,
|
||||
}))
|
||||
: [],
|
||||
databaseMigration: account.databaseMigration
|
||||
? {
|
||||
phase: account.databaseMigration.phase,
|
||||
usable: account.databaseMigration.usable,
|
||||
processed: account.databaseMigration.processed,
|
||||
total: account.databaseMigration.total,
|
||||
progress: account.databaseMigration.progress,
|
||||
estimatedRemainingSeconds: account.databaseMigration.estimatedRemainingSeconds,
|
||||
error: account.databaseMigration.error,
|
||||
}
|
||||
: undefined,
|
||||
}));
|
||||
if (!Array.isArray(snapshot)) {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
return (snapshot as AccountConnections[]).map((account) => ({
|
||||
uin: account.uin,
|
||||
nickname: account.nickname,
|
||||
adapters: Array.isArray(account.adapters)
|
||||
? account.adapters.map((adapter) => ({
|
||||
name: adapter.name,
|
||||
kind: adapter.kind,
|
||||
status: adapter.status,
|
||||
lastErrorAt: adapter.lastErrorAt,
|
||||
}))
|
||||
: [],
|
||||
databaseMigration: account.databaseMigration
|
||||
? {
|
||||
phase: account.databaseMigration.phase,
|
||||
usable: account.databaseMigration.usable,
|
||||
processed: account.databaseMigration.processed,
|
||||
total: account.databaseMigration.total,
|
||||
progress: account.databaseMigration.progress,
|
||||
estimatedRemainingSeconds: account.databaseMigration.estimatedRemainingSeconds,
|
||||
error: account.databaseMigration.error,
|
||||
}
|
||||
: undefined,
|
||||
}));
|
||||
}
|
||||
+165
-118
@@ -14,8 +14,8 @@ const CONSENT_CONFIG_PATH = path.join(CONFIG_DIR, 'consent.json');
|
||||
// repo-root markdown; the build copies them next to the bundle (dist/) so the
|
||||
// same lookup works in a packaged deploy. See vite.config.ts cp targets.
|
||||
const AGREEMENT_FILES = [
|
||||
{ id: 'eula' as const, file: 'EULA.md' },
|
||||
{ id: 'privacy' as const, file: 'PRIVACY.md' },
|
||||
{ id: 'eula' as const, file: 'EULA.md' },
|
||||
{ id: 'privacy' as const, file: 'PRIVACY.md' },
|
||||
];
|
||||
|
||||
export const EULA_ACCEPT_ENV = 'SNOWLUMA_ACCEPT_EULA';
|
||||
@@ -24,54 +24,60 @@ export const PRIVACY_ACCEPT_ENV = 'SNOWLUMA_ACCEPT_PRIVACY';
|
||||
type ConsentEnvironment = Readonly<Record<string, string | undefined>>;
|
||||
|
||||
export interface EnvironmentConsent {
|
||||
eulaAccepted: boolean;
|
||||
privacyAccepted: boolean;
|
||||
/** Both documents must be accepted; a partial opt-in never unlocks the gate. */
|
||||
accepted: boolean;
|
||||
eulaAccepted: boolean;
|
||||
privacyAccepted: boolean;
|
||||
/** Both documents must be accepted; a partial opt-in never unlocks the gate. */
|
||||
accepted: boolean;
|
||||
}
|
||||
|
||||
export interface AgreementDoc {
|
||||
id: 'eula' | 'privacy';
|
||||
/** First markdown `# ` heading, for the tab/section title. */
|
||||
title: string;
|
||||
/** Declared "Version: x" from the doc — display only, NOT the consent key. */
|
||||
declaredVersion: string;
|
||||
/** Declared effective date (YYYY-MM-DD) — display only. */
|
||||
effectiveDate: string;
|
||||
/** Full markdown body the frontend renders. */
|
||||
text: string;
|
||||
id: 'eula' | 'privacy';
|
||||
/** First markdown `# ` heading, for the tab/section title. */
|
||||
title: string;
|
||||
/** Declared "Version: x" from the doc — display only, NOT the consent key. */
|
||||
declaredVersion: string;
|
||||
/** Declared effective date (YYYY-MM-DD) — display only. */
|
||||
effectiveDate: string;
|
||||
/** Full markdown body the frontend renders. */
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface ConsentRecord {
|
||||
/** The content-hash agreements version that was accepted. */
|
||||
version: string;
|
||||
/** ISO timestamp of acceptance. */
|
||||
acceptedAt: string;
|
||||
/** The content-hash agreements version that was accepted. */
|
||||
version: string;
|
||||
/** ISO timestamp of acceptance. */
|
||||
acceptedAt: string;
|
||||
}
|
||||
|
||||
export interface AgreementsPayload {
|
||||
/** Content-hash version of the current agreement set. */
|
||||
version: string;
|
||||
/**
|
||||
* True when the operator must (re-)accept: the agreements carry real text,
|
||||
* environment consent is incomplete, AND the stored consent version differs
|
||||
* from the current one. A missing or unreadable agreement set fails OPEN (no
|
||||
* gate) so a broken bundle can never lock the admin out of their own panel.
|
||||
*/
|
||||
consentRequired: boolean;
|
||||
documents: AgreementDoc[];
|
||||
/** Content-hash version of the current agreement set. */
|
||||
version: string;
|
||||
/**
|
||||
* True when the operator must (re-)accept: the agreements carry real text,
|
||||
* environment consent is incomplete, AND the stored consent version differs
|
||||
* from the current one. A missing or unreadable agreement set fails OPEN (no
|
||||
* gate) so a broken bundle can never lock the admin out of their own panel.
|
||||
*/
|
||||
consentRequired: boolean;
|
||||
documents: AgreementDoc[];
|
||||
}
|
||||
|
||||
function parseEnvironmentAcceptance(name: string, raw: string | undefined): boolean {
|
||||
if (raw === undefined || raw.trim() === '') return false;
|
||||
if (raw === undefined || raw.trim() === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized === '1' || normalized === 'true') return true;
|
||||
if (normalized === '0' || normalized === 'false') return false;
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
|
||||
throw new Error(
|
||||
`${name} must be one of: 1, true, 0, false; received ${JSON.stringify(raw)}`,
|
||||
);
|
||||
if (normalized === '1' || normalized === 'true') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (normalized === '0' || normalized === 'false') {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw new Error(`${name} must be one of: 1, true, 0, false; received ${JSON.stringify(raw)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,15 +86,15 @@ function parseEnvironmentAcceptance(name: string, raw: string | undefined): bool
|
||||
* versioned consent gate instead of silently writing a permanent record.
|
||||
*/
|
||||
export function resolveEnvironmentConsent(
|
||||
env: ConsentEnvironment = process.env,
|
||||
env: ConsentEnvironment = process.env,
|
||||
): EnvironmentConsent {
|
||||
const eulaAccepted = parseEnvironmentAcceptance(EULA_ACCEPT_ENV, env[EULA_ACCEPT_ENV]);
|
||||
const privacyAccepted = parseEnvironmentAcceptance(PRIVACY_ACCEPT_ENV, env[PRIVACY_ACCEPT_ENV]);
|
||||
return {
|
||||
eulaAccepted,
|
||||
privacyAccepted,
|
||||
accepted: eulaAccepted && privacyAccepted,
|
||||
};
|
||||
const eulaAccepted = parseEnvironmentAcceptance(EULA_ACCEPT_ENV, env[EULA_ACCEPT_ENV]);
|
||||
const privacyAccepted = parseEnvironmentAcceptance(PRIVACY_ACCEPT_ENV, env[PRIVACY_ACCEPT_ENV]);
|
||||
return {
|
||||
eulaAccepted,
|
||||
privacyAccepted,
|
||||
accepted: eulaAccepted && privacyAccepted,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Agreement loading (pure-ish; file read + parse, cached) ─────────────────
|
||||
@@ -101,35 +107,39 @@ export function resolveEnvironmentConsent(
|
||||
* root or dist/), so we probe a handful of candidates and take the first hit.
|
||||
*/
|
||||
function resolveAgreementFile(file: string): string | null {
|
||||
const candidates = [
|
||||
path.join(__dirname, file), // packaged: dist/<file>
|
||||
path.resolve(__dirname, '..', '..', '..', '..', file), // dev tsx: repoRoot/<file>
|
||||
path.resolve(process.cwd(), file), // started from repo root
|
||||
path.resolve(process.cwd(), '..', '..', file), // dev cwd = packages/core
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
if (fs.existsSync(candidate)) return candidate;
|
||||
} catch {
|
||||
/* unreadable candidate, try next */
|
||||
const candidates = [
|
||||
path.join(__dirname, file), // packaged: dist/<file>
|
||||
path.resolve(__dirname, '..', '..', '..', '..', file), // dev tsx: repoRoot/<file>
|
||||
path.resolve(process.cwd(), file), // started from repo root
|
||||
path.resolve(process.cwd(), '..', '..', file), // dev cwd = packages/core
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
} catch {
|
||||
/* unreadable candidate, try next */
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Extract title / declared version / effective date from a doc body. */
|
||||
export function parseAgreementMeta(text: string): {
|
||||
title: string;
|
||||
declaredVersion: string;
|
||||
effectiveDate: string;
|
||||
title: string;
|
||||
declaredVersion: string;
|
||||
effectiveDate: string;
|
||||
} {
|
||||
const title = text.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() ?? '';
|
||||
// Matches both "Version: 1.0" / "版本 / Version:** 1.0" style lines.
|
||||
const declaredVersion =
|
||||
text.match(/(?:Version|版本)[^\n0-9]*([0-9][0-9A-Za-z.-]*)/)?.[1]?.trim() ?? '';
|
||||
const effectiveDate =
|
||||
text.match(/(?:Effective date|生效日期)[^\n0-9]*(\d{4}-\d{2}-\d{2})/)?.[1] ?? '';
|
||||
return { title, declaredVersion, effectiveDate };
|
||||
const title = text.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() ?? '';
|
||||
// Matches both "Version: 1.0" / "版本 / Version:** 1.0" style lines.
|
||||
const declaredVersion =
|
||||
text.match(/(?:Version|版本)[^\n0-9]*([0-9][0-9A-Za-z.-]*)/)?.[1]?.trim() ?? '';
|
||||
const effectiveDate =
|
||||
text.match(/(?:Effective date|生效日期)[^\n0-9]*(\d{4}-\d{2}-\d{2})/)?.[1] ?? '';
|
||||
return { title, declaredVersion, effectiveDate };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -139,89 +149,126 @@ export function parseAgreementMeta(text: string): {
|
||||
* and changes the moment any agreement's TEXT changes (forcing re-consent).
|
||||
*/
|
||||
export function computeAgreementsVersion(docs: { id: string; text: string }[]): string {
|
||||
const hash = createHash('sha256');
|
||||
for (const doc of docs) {
|
||||
hash.update(doc.id);
|
||||
hash.update('\0');
|
||||
hash.update(doc.text);
|
||||
hash.update('\0');
|
||||
}
|
||||
return hash.digest('hex').slice(0, 16);
|
||||
const hash = createHash('sha256');
|
||||
|
||||
for (const doc of docs) {
|
||||
hash.update(doc.id);
|
||||
hash.update('\0');
|
||||
hash.update(doc.text);
|
||||
hash.update('\0');
|
||||
}
|
||||
|
||||
return hash.digest('hex').slice(0, 16);
|
||||
}
|
||||
|
||||
let cache: { docs: AgreementDoc[]; version: string } | null = null;
|
||||
|
||||
/** Load + parse both agreements and compute the version. Cached per process. */
|
||||
export function loadAgreements(): { docs: AgreementDoc[]; version: string } {
|
||||
if (cache) return cache;
|
||||
const docs: AgreementDoc[] = AGREEMENT_FILES.map(({ id, file }) => {
|
||||
const resolved = resolveAgreementFile(file);
|
||||
let text = '';
|
||||
if (resolved) {
|
||||
try {
|
||||
text = fs.readFileSync(resolved, 'utf8');
|
||||
} catch (err) {
|
||||
log.warn('failed to read %s: %s', file, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} else {
|
||||
log.warn('agreement file not found (looked for %s near the bundle and repo root)', file);
|
||||
if (cache) {
|
||||
return cache;
|
||||
}
|
||||
const meta = parseAgreementMeta(text);
|
||||
return { id, title: meta.title, declaredVersion: meta.declaredVersion, effectiveDate: meta.effectiveDate, text };
|
||||
});
|
||||
cache = { docs, version: computeAgreementsVersion(docs) };
|
||||
return cache;
|
||||
|
||||
const docs: AgreementDoc[] = AGREEMENT_FILES.map(({ id, file }) => {
|
||||
const resolved = resolveAgreementFile(file);
|
||||
let text = '';
|
||||
|
||||
if (resolved) {
|
||||
try {
|
||||
text = fs.readFileSync(resolved, 'utf8');
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'failed to read %s: %s',
|
||||
file,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
log.warn(
|
||||
'agreement file not found (looked for %s near the bundle and repo root)',
|
||||
file,
|
||||
);
|
||||
}
|
||||
|
||||
const meta = parseAgreementMeta(text);
|
||||
return {
|
||||
id,
|
||||
title: meta.title,
|
||||
declaredVersion: meta.declaredVersion,
|
||||
effectiveDate: meta.effectiveDate,
|
||||
text,
|
||||
};
|
||||
});
|
||||
cache = { docs, version: computeAgreementsVersion(docs) };
|
||||
return cache;
|
||||
}
|
||||
|
||||
// ── Consent persistence (config/consent.json, atomic) ───────────────────────
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function isConsentRecord(value: unknown): value is ConsentRecord {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
return typeof v.version === 'string' && v.version.length > 0 && typeof v.acceptedAt === 'string';
|
||||
if (!value || typeof value !== 'object') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const v = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof v.version === 'string' && v.version.length > 0 && typeof v.acceptedAt === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
export function loadConsentRecord(): ConsentRecord | null {
|
||||
try {
|
||||
if (!fs.existsSync(CONSENT_CONFIG_PATH)) return null;
|
||||
const parsed = JSON.parse(fs.readFileSync(CONSENT_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isConsentRecord(parsed) ? parsed : null;
|
||||
} catch (err) {
|
||||
log.warn('consent.json unreadable, treating as no consent: %s', err instanceof Error ? err.message : String(err));
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (!fs.existsSync(CONSENT_CONFIG_PATH)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(fs.readFileSync(CONSENT_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isConsentRecord(parsed) ? parsed : null;
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'consent.json unreadable, treating as no consent: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function atomicWrite(record: ConsentRecord): void {
|
||||
ensureConfigDir();
|
||||
const tmp = CONSENT_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(record, null, 2), { encoding: 'utf8' });
|
||||
fs.renameSync(tmp, CONSENT_CONFIG_PATH);
|
||||
ensureConfigDir();
|
||||
const tmp = CONSENT_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(record, null, 2), { encoding: 'utf8' });
|
||||
fs.renameSync(tmp, CONSENT_CONFIG_PATH);
|
||||
}
|
||||
|
||||
/** Persist that the operator accepted `version`. Returns the stored record. */
|
||||
export function recordConsent(version: string): ConsentRecord {
|
||||
const record: ConsentRecord = { version, acceptedAt: new Date().toISOString() };
|
||||
atomicWrite(record);
|
||||
return record;
|
||||
const record: ConsentRecord = { version, acceptedAt: new Date().toISOString() };
|
||||
atomicWrite(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
/** True when neither environment nor stored consent covers the current agreements. */
|
||||
export function isConsentRequired(env: ConsentEnvironment = process.env): boolean {
|
||||
if (resolveEnvironmentConsent(env).accepted) return false;
|
||||
if (resolveEnvironmentConsent(env).accepted) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const { docs, version } = loadAgreements();
|
||||
const hasContent = docs.some((d) => d.text.trim().length > 0);
|
||||
if (!hasContent) return false; // fail open: never brick the panel on a broken bundle
|
||||
return loadConsentRecord()?.version !== version;
|
||||
const { docs, version } = loadAgreements();
|
||||
const hasContent = docs.some((d) => d.text.trim().length > 0);
|
||||
|
||||
if (!hasContent) {
|
||||
return false;
|
||||
} // fail open: never brick the panel on a broken bundle
|
||||
|
||||
return loadConsentRecord()?.version !== version;
|
||||
}
|
||||
|
||||
/** Public payload for GET /api/agreements (texts + version + consentRequired). */
|
||||
export function getAgreementsPayload(): AgreementsPayload {
|
||||
const { docs, version } = loadAgreements();
|
||||
return { version, consentRequired: isConsentRequired(), documents: docs };
|
||||
const { docs, version } = loadAgreements();
|
||||
return { version, consentRequired: isConsentRequired(), documents: docs };
|
||||
}
|
||||
@@ -5,24 +5,33 @@
|
||||
// handler so this (easy-to-get-wrong) logic is unit-tested.
|
||||
|
||||
export interface FramePusherOptions {
|
||||
/** The stream controller's current desiredSize (null = no backpressure info). */
|
||||
desiredSize: () => number | null;
|
||||
/** Deliver an encoded SSE chunk (the caller maps this to the controller). */
|
||||
enqueue: (chunk: Uint8Array) => void;
|
||||
encode?: (s: string) => Uint8Array;
|
||||
/** The stream controller's current desiredSize (null = no backpressure info). */
|
||||
desiredSize: () => number | null;
|
||||
/** Deliver an encoded SSE chunk (the caller maps this to the controller). */
|
||||
enqueue: (chunk: Uint8Array) => void;
|
||||
encode?: (s: string) => Uint8Array;
|
||||
}
|
||||
|
||||
/** Returns a `push(payload)` that frames + delivers with backpressure dropping. */
|
||||
export function createFramePusher(opts: FramePusherOptions): (payload: unknown) => void {
|
||||
const encode = opts.encode ?? ((s: string) => new TextEncoder().encode(s));
|
||||
let dropped = 0;
|
||||
return (payload: unknown): void => {
|
||||
const d = opts.desiredSize();
|
||||
if (d !== null && d <= 0) { dropped += 1; return; }
|
||||
if (dropped > 0) {
|
||||
opts.enqueue(encode(`data: ${JSON.stringify({ kind: 'dropped', count: dropped })}\n\n`));
|
||||
dropped = 0;
|
||||
}
|
||||
opts.enqueue(encode(`data: ${JSON.stringify(payload)}\n\n`));
|
||||
};
|
||||
const encode = opts.encode ?? ((s: string) => new TextEncoder().encode(s));
|
||||
let dropped = 0;
|
||||
|
||||
return (payload: unknown): void => {
|
||||
const d = opts.desiredSize();
|
||||
|
||||
if (d !== null && d <= 0) {
|
||||
dropped += 1;
|
||||
return;
|
||||
}
|
||||
|
||||
if (dropped > 0) {
|
||||
opts.enqueue(
|
||||
encode(`data: ${JSON.stringify({ kind: 'dropped', count: dropped })}\n\n`),
|
||||
);
|
||||
dropped = 0;
|
||||
}
|
||||
|
||||
opts.enqueue(encode(`data: ${JSON.stringify(payload)}\n\n`));
|
||||
};
|
||||
}
|
||||
@@ -35,27 +35,29 @@ const UPLOAD_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
* with no path separators or traversal. The client path is NEVER trusted for
|
||||
* placement — this is only used to keep the stored name human-readable. */
|
||||
export function safeUploadName(raw: string | undefined): string {
|
||||
// Treat both separators as path delimiters, then take the basename so any
|
||||
// `../` / absolute prefix is discarded regardless of host platform.
|
||||
const base = path.basename(String(raw ?? '').replace(/\\/g, '/'));
|
||||
const cleaned = base
|
||||
.replace(/[^\w.-]+/g, '_') // collapse anything exotic to underscore
|
||||
.replace(/^\.+/, '') // no leading dots (no hidden / '..' names)
|
||||
.slice(0, 120);
|
||||
return cleaned || 'file';
|
||||
// Treat both separators as path delimiters, then take the basename so any
|
||||
// `../` / absolute prefix is discarded regardless of host platform.
|
||||
const base = path.basename(String(raw ?? '').replace(/\\/g, '/'));
|
||||
const cleaned = base
|
||||
.replace(/[^\w.-]+/g, '_') // collapse anything exotic to underscore
|
||||
.replace(/^\.+/, '') // no leading dots (no hidden / '..' names)
|
||||
.slice(0, 120);
|
||||
return cleaned || 'file';
|
||||
}
|
||||
|
||||
/** Unguessable destination path under DEBUG_UPLOAD_DIR for a sanitised name.
|
||||
* Throws if the composed path would escape the dir (defence in depth — it
|
||||
* can't, given the random id + basename, but we assert anyway). */
|
||||
export function uploadDestPath(safeName: string): string {
|
||||
const id = randomBytes(12).toString('hex');
|
||||
const dest = path.join(DEBUG_UPLOAD_DIR, `${id}__${safeName}`);
|
||||
const rel = path.relative(DEBUG_UPLOAD_DIR, dest);
|
||||
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
|
||||
throw new Error('invalid upload path');
|
||||
}
|
||||
return dest;
|
||||
const id = randomBytes(12).toString('hex');
|
||||
const dest = path.join(DEBUG_UPLOAD_DIR, `${id}__${safeName}`);
|
||||
const rel = path.relative(DEBUG_UPLOAD_DIR, dest);
|
||||
|
||||
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
|
||||
throw new Error('invalid upload path');
|
||||
}
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/** Stream raw request-body bytes to a temp file under DEBUG_UPLOAD_DIR, enforcing
|
||||
@@ -63,84 +65,126 @@ export function uploadDestPath(safeName: string): string {
|
||||
* error the partial file is removed and the call rejects. Never buffers the
|
||||
* whole body. */
|
||||
export async function streamUploadToDisk(
|
||||
body: ReadableStream<Uint8Array> | null,
|
||||
filename: string | undefined,
|
||||
opts: { maxBytes?: number } = {},
|
||||
body: ReadableStream<Uint8Array> | null,
|
||||
filename: string | undefined,
|
||||
opts: { maxBytes?: number } = {},
|
||||
): Promise<{ path: string; size: number }> {
|
||||
if (!body) throw new Error('empty body');
|
||||
const maxBytes = opts.maxBytes ?? MAX_UPLOAD_BYTES;
|
||||
await mkdir(DEBUG_UPLOAD_DIR, { recursive: true });
|
||||
void sweepOldUploads(); // fire-and-forget TTL cleanup
|
||||
|
||||
const dest = uploadDestPath(safeUploadName(filename));
|
||||
const out = createWriteStream(dest, { mode: 0o600 });
|
||||
// A WriteStream emits 'error' ASYNCHRONOUSLY (ENOSPC / EIO / quota) during a
|
||||
// background flush — typically while we're parked at reader.read() or waiting
|
||||
// on 'drain'. An unhandled 'error' event would crash the whole process, and a
|
||||
// backpressured error would leave 'drain' to never fire (a forever-hung await
|
||||
// + leaked fd). So turn it into a rejection and race it into every await; the
|
||||
// catch below then destroys + unlinks the partial.
|
||||
const errored = new Promise<never>((_, rej) => out.once('error', rej));
|
||||
errored.catch(() => { /* swallow a late error after success (still raced below) */ });
|
||||
let size = 0;
|
||||
try {
|
||||
const reader = body.getReader();
|
||||
for (;;) {
|
||||
const { done, value } = await Promise.race([errored, reader.read()]);
|
||||
if (done) break;
|
||||
if (!value || value.byteLength === 0) continue;
|
||||
const offset = size;
|
||||
size += value.byteLength;
|
||||
traceWebuiMutationRequestChunk(value, offset);
|
||||
if (size > maxBytes) throw new Error('上传超出大小上限');
|
||||
// Respect the write stream's backpressure (but never hang on an error).
|
||||
if (!out.write(value)) {
|
||||
await Promise.race([errored, new Promise<void>((res) => out.once('drain', res))]);
|
||||
}
|
||||
if (!body) {
|
||||
throw new Error('empty body');
|
||||
}
|
||||
|
||||
const maxBytes = opts.maxBytes ?? MAX_UPLOAD_BYTES;
|
||||
await mkdir(DEBUG_UPLOAD_DIR, { recursive: true });
|
||||
void sweepOldUploads(); // fire-and-forget TTL cleanup
|
||||
|
||||
const dest = uploadDestPath(safeUploadName(filename));
|
||||
const out = createWriteStream(dest, { mode: 0o600 });
|
||||
// A WriteStream emits 'error' ASYNCHRONOUSLY (ENOSPC / EIO / quota) during a
|
||||
// background flush — typically while we're parked at reader.read() or waiting
|
||||
// on 'drain'. An unhandled 'error' event would crash the whole process, and a
|
||||
// backpressured error would leave 'drain' to never fire (a forever-hung await
|
||||
// + leaked fd). So turn it into a rejection and race it into every await; the
|
||||
// catch below then destroys + unlinks the partial.
|
||||
const errored = new Promise<never>((_, rej) => out.once('error', rej));
|
||||
errored.catch(() => {
|
||||
/* swallow a late error after success (still raced below) */
|
||||
});
|
||||
let size = 0;
|
||||
|
||||
try {
|
||||
const reader = body.getReader();
|
||||
|
||||
for (;;) {
|
||||
const { done, value } = await Promise.race([errored, reader.read()]);
|
||||
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (!value || value.byteLength === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const offset = size;
|
||||
size += value.byteLength;
|
||||
traceWebuiMutationRequestChunk(value, offset);
|
||||
|
||||
if (size > maxBytes) {
|
||||
throw new Error('上传超出大小上限');
|
||||
}
|
||||
|
||||
// Respect the write stream's backpressure (but never hang on an error).
|
||||
if (!out.write(value)) {
|
||||
await Promise.race([errored, new Promise<void>((res) => out.once('drain', res))]);
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.race([
|
||||
errored,
|
||||
new Promise<void>((res, rej) =>
|
||||
out.end((err?: Error | null) => (err ? rej(err) : res())),
|
||||
),
|
||||
]);
|
||||
|
||||
if (size === 0) {
|
||||
throw new Error('empty body');
|
||||
}
|
||||
|
||||
return { path: dest, size };
|
||||
} catch (err) {
|
||||
// Wait for the stream to fully close BEFORE unlinking: createWriteStream
|
||||
// opens the fd asynchronously, so a fast failure can reach `rm` before the
|
||||
// file even exists on disk — then the late open would re-create it and leak
|
||||
// the partial. 'close' guarantees the fd is settled and no more writes land.
|
||||
out.destroy();
|
||||
|
||||
if (!out.closed) {
|
||||
await new Promise<void>((res) => out.once('close', () => res()));
|
||||
}
|
||||
|
||||
await rm(dest, { force: true }).catch(() => {
|
||||
/* best-effort */
|
||||
});
|
||||
throw err;
|
||||
}
|
||||
await Promise.race([errored, new Promise<void>((res, rej) => out.end((err?: Error | null) => (err ? rej(err) : res())))]);
|
||||
if (size === 0) throw new Error('empty body');
|
||||
return { path: dest, size };
|
||||
} catch (err) {
|
||||
// Wait for the stream to fully close BEFORE unlinking: createWriteStream
|
||||
// opens the fd asynchronously, so a fast failure can reach `rm` before the
|
||||
// file even exists on disk — then the late open would re-create it and leak
|
||||
// the partial. 'close' guarantees the fd is settled and no more writes land.
|
||||
out.destroy();
|
||||
if (!out.closed) await new Promise<void>((res) => out.once('close', () => res()));
|
||||
await rm(dest, { force: true }).catch(() => { /* best-effort */ });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove upload temp files older than the TTL. Best-effort; never throws. */
|
||||
export async function sweepOldUploads(now: number = Date.now()): Promise<number> {
|
||||
let removed = 0;
|
||||
try {
|
||||
const names = await readdir(DEBUG_UPLOAD_DIR);
|
||||
await Promise.all(
|
||||
names.map(async (n) => {
|
||||
const p = path.join(DEBUG_UPLOAD_DIR, n);
|
||||
try {
|
||||
const s = await stat(p);
|
||||
if (now - s.mtimeMs > UPLOAD_TTL_MS) {
|
||||
await rm(p, { force: true, recursive: true });
|
||||
removed += 1;
|
||||
}
|
||||
} catch { /* racing cleanup / vanished file */ }
|
||||
}),
|
||||
);
|
||||
} catch { /* dir absent yet */ }
|
||||
return removed;
|
||||
let removed = 0;
|
||||
|
||||
try {
|
||||
const names = await readdir(DEBUG_UPLOAD_DIR);
|
||||
await Promise.all(
|
||||
names.map(async (n) => {
|
||||
const p = path.join(DEBUG_UPLOAD_DIR, n);
|
||||
|
||||
try {
|
||||
const s = await stat(p);
|
||||
|
||||
if (now - s.mtimeMs > UPLOAD_TTL_MS) {
|
||||
await rm(p, { force: true, recursive: true });
|
||||
removed += 1;
|
||||
}
|
||||
} catch {
|
||||
/* racing cleanup / vanished file */
|
||||
}
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
/* dir absent yet */
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
/** Drives a stream-capable action and relays its frames. The driver is the
|
||||
* instance's `invokeStream` (which itself handles non-stream actions by emitting
|
||||
* a single frame). */
|
||||
export type StreamInvokeDriver = (
|
||||
rawRequest: string,
|
||||
emit: (json: string) => Promise<void>,
|
||||
isAlive: () => boolean,
|
||||
rawRequest: string,
|
||||
emit: (json: string) => Promise<void>,
|
||||
isAlive: () => boolean,
|
||||
) => Promise<void>;
|
||||
|
||||
/** How long emit() will wait for a backed-up consumer to drain before it gives
|
||||
@@ -154,47 +198,75 @@ const DRAIN_MAX_SPINS = 3000; // 3000 * 20ms ≈ 60s
|
||||
* becomes a terminal `failed` frame. Closing the request (signal abort) stops
|
||||
* delivery. `delay` is injectable for tests. */
|
||||
export function buildStreamInvokeResponse(
|
||||
driver: StreamInvokeDriver,
|
||||
rawRequest: string,
|
||||
signal: AbortSignal,
|
||||
delay: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
|
||||
driver: StreamInvokeDriver,
|
||||
rawRequest: string,
|
||||
signal: AbortSignal,
|
||||
delay: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
|
||||
): Response {
|
||||
const encoder = new TextEncoder();
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
let closed = false;
|
||||
const onAbort = () => { closed = true; };
|
||||
signal.addEventListener('abort', onAbort);
|
||||
const isAlive = () => !closed && !signal.aborted;
|
||||
const encoder = new TextEncoder();
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
let closed = false;
|
||||
|
||||
const emit = async (json: string): Promise<void> => {
|
||||
if (!isAlive()) throw new Error('stream transport closed');
|
||||
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
|
||||
let spins = 0;
|
||||
while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
|
||||
await delay(DRAIN_WAIT_MS);
|
||||
spins += 1;
|
||||
}
|
||||
if (!isAlive()) throw new Error('stream transport closed');
|
||||
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
||||
};
|
||||
const onAbort = () => {
|
||||
closed = true;
|
||||
};
|
||||
|
||||
try {
|
||||
await driver(rawRequest, emit, isAlive);
|
||||
} catch (err) {
|
||||
if (isAlive()) {
|
||||
const msg = err instanceof Error ? err.message : 'stream error';
|
||||
try {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`));
|
||||
} catch { /* controller already torn down */ }
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
try { controller.close(); } catch { /* already closed */ }
|
||||
}
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
});
|
||||
signal.addEventListener('abort', onAbort);
|
||||
const isAlive = () => !closed && !signal.aborted;
|
||||
|
||||
const emit = async (json: string): Promise<void> => {
|
||||
if (!isAlive()) {
|
||||
throw new Error('stream transport closed');
|
||||
}
|
||||
|
||||
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
|
||||
let spins = 0;
|
||||
|
||||
while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
|
||||
await delay(DRAIN_WAIT_MS);
|
||||
spins += 1;
|
||||
}
|
||||
|
||||
if (!isAlive()) {
|
||||
throw new Error('stream transport closed');
|
||||
}
|
||||
|
||||
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
||||
};
|
||||
|
||||
try {
|
||||
await driver(rawRequest, emit, isAlive);
|
||||
} catch (err) {
|
||||
if (isAlive()) {
|
||||
const msg = err instanceof Error ? err.message : 'stream error';
|
||||
|
||||
try {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`,
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
/* controller already torn down */
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
Connection: 'keep-alive',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,27 +1,40 @@
|
||||
import { isIP } from 'node:net';
|
||||
|
||||
export type ListenerExposureCheck =
|
||||
| { ok: true }
|
||||
| { ok: false; code: 'invalid-bind-host' | 'tls-pair-required' };
|
||||
{ ok: true } | { ok: false; code: 'invalid-bind-host' | 'tls-pair-required' };
|
||||
|
||||
/** TCP bind-host accepted by WebUI Listener Exposure (settings, restore, boot). */
|
||||
export function isValidBindHost(value: string): boolean {
|
||||
const host = value.trim();
|
||||
if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) return false;
|
||||
if (host.includes(':')) return isIP(host) === 6;
|
||||
if (/^[\d.]+$/.test(host)) {
|
||||
return isIP(host) === 4;
|
||||
}
|
||||
const normalized = host.endsWith('.') ? host.slice(0, -1) : host;
|
||||
return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/.test(label));
|
||||
const host = value.trim();
|
||||
|
||||
if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (host.includes(':')) {
|
||||
return isIP(host) === 6;
|
||||
}
|
||||
|
||||
if (/^[\d.]+$/.test(host)) {
|
||||
return isIP(host) === 4;
|
||||
}
|
||||
|
||||
const normalized = host.endsWith('.') ? host.slice(0, -1) : host;
|
||||
return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/.test(label));
|
||||
}
|
||||
|
||||
export function checkListenerExposure(input: {
|
||||
webuiHost: string;
|
||||
tlsEnabled: boolean;
|
||||
pairOk: boolean;
|
||||
webuiHost: string;
|
||||
tlsEnabled: boolean;
|
||||
pairOk: boolean;
|
||||
}): ListenerExposureCheck {
|
||||
if (!isValidBindHost(input.webuiHost)) return { ok: false, code: 'invalid-bind-host' };
|
||||
if (input.tlsEnabled && !input.pairOk) return { ok: false, code: 'tls-pair-required' };
|
||||
return { ok: true };
|
||||
if (!isValidBindHost(input.webuiHost)) {
|
||||
return { ok: false, code: 'invalid-bind-host' };
|
||||
}
|
||||
|
||||
if (input.tlsEnabled && !input.pairOk) {
|
||||
return { ok: false, code: 'tls-pair-required' };
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -1,69 +1,68 @@
|
||||
import type { LogEntry } from '@snowluma/common/logger';
|
||||
|
||||
export interface FullTraceExportMetadata {
|
||||
version: string;
|
||||
operatingSystem: string;
|
||||
architecture: string;
|
||||
nodeVersion: string;
|
||||
logLevel: LogEntry['level'];
|
||||
exportedAt: string;
|
||||
version: string;
|
||||
operatingSystem: string;
|
||||
architecture: string;
|
||||
nodeVersion: string;
|
||||
logLevel: LogEntry['level'];
|
||||
exportedAt: string;
|
||||
}
|
||||
|
||||
const PRIVACY_WARNING = 'WARNING: This export may contain unredacted private data and credentials. Sanitize it before submission.';
|
||||
const PRIVACY_WARNING =
|
||||
'WARNING: This export may contain unredacted private data and credentials. Sanitize it before submission.';
|
||||
|
||||
export interface FullTraceDownload {
|
||||
body: string;
|
||||
headers: {
|
||||
'Content-Type': string;
|
||||
'Content-Disposition': string;
|
||||
'Cache-Control': string;
|
||||
};
|
||||
body: string;
|
||||
headers: {
|
||||
'Content-Type': string;
|
||||
'Content-Disposition': string;
|
||||
'Cache-Control': string;
|
||||
};
|
||||
}
|
||||
|
||||
export function buildFullTraceDownload(
|
||||
entries: readonly LogEntry[],
|
||||
metadata: FullTraceExportMetadata,
|
||||
entries: readonly LogEntry[],
|
||||
metadata: FullTraceExportMetadata,
|
||||
): FullTraceDownload {
|
||||
const timestamp = metadata.exportedAt
|
||||
.slice(0, 19)
|
||||
.replace(/[:.]/g, '-');
|
||||
return {
|
||||
body: formatFullTraceExport(entries, metadata),
|
||||
headers: {
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'Content-Disposition': `attachment; filename="snowluma-trace-${timestamp}.log"`,
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
};
|
||||
const timestamp = metadata.exportedAt.slice(0, 19).replace(/[:.]/g, '-');
|
||||
return {
|
||||
body: formatFullTraceExport(entries, metadata),
|
||||
headers: {
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'Content-Disposition': `attachment; filename="snowluma-trace-${timestamp}.log"`,
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function formatFullTraceExport(
|
||||
entries: readonly LogEntry[],
|
||||
metadata: FullTraceExportMetadata,
|
||||
entries: readonly LogEntry[],
|
||||
metadata: FullTraceExportMetadata,
|
||||
): string {
|
||||
const lines = [
|
||||
'SnowLuma full TRACE export',
|
||||
'==========================',
|
||||
`SnowLuma version: ${metadata.version}`,
|
||||
`Operating system: ${metadata.operatingSystem}`,
|
||||
`Architecture: ${metadata.architecture}`,
|
||||
`Node.js version: ${metadata.nodeVersion}`,
|
||||
`Current log level: ${metadata.logLevel.toUpperCase()}`,
|
||||
`Export time: ${metadata.exportedAt}`,
|
||||
`Retained records: ${entries.length}`,
|
||||
'',
|
||||
PRIVACY_WARNING,
|
||||
'This is a snapshot of the normal and TRACE records still retained in memory; records already evicted cannot be recovered.',
|
||||
'',
|
||||
'Logs',
|
||||
'----',
|
||||
];
|
||||
const lines = [
|
||||
'SnowLuma full TRACE export',
|
||||
'==========================',
|
||||
`SnowLuma version: ${metadata.version}`,
|
||||
`Operating system: ${metadata.operatingSystem}`,
|
||||
`Architecture: ${metadata.architecture}`,
|
||||
`Node.js version: ${metadata.nodeVersion}`,
|
||||
`Current log level: ${metadata.logLevel.toUpperCase()}`,
|
||||
`Export time: ${metadata.exportedAt}`,
|
||||
`Retained records: ${entries.length}`,
|
||||
'',
|
||||
PRIVACY_WARNING,
|
||||
'This is a snapshot of the normal and TRACE records still retained in memory; records already evicted cannot be recovered.',
|
||||
'',
|
||||
'Logs',
|
||||
'----',
|
||||
];
|
||||
|
||||
if (entries.length === 0) {
|
||||
lines.push('(No log records are currently retained.)');
|
||||
} else {
|
||||
lines.push(...entries.map((entry) => entry.line));
|
||||
}
|
||||
if (entries.length === 0) {
|
||||
lines.push('(No log records are currently retained.)');
|
||||
} else {
|
||||
lines.push(...entries.map((entry) => entry.line));
|
||||
}
|
||||
|
||||
return `${lines.join('\n')}\n`;
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import {
|
||||
createLogger,
|
||||
currentRequestId,
|
||||
getLogLevel,
|
||||
renderTraceBytes,
|
||||
runWithRequestId,
|
||||
runWithTraceRequest,
|
||||
createLogger,
|
||||
currentRequestId,
|
||||
getLogLevel,
|
||||
renderTraceBytes,
|
||||
runWithRequestId,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
|
||||
const log = createLogger('WebUI.Mutation');
|
||||
@@ -14,284 +14,343 @@ const STREAMED_REQUEST_PATHS = new Set(['/api/debug/upload']);
|
||||
const STREAMED_RESPONSE_PATHS = new Set(['/api/debug/invoke-stream']);
|
||||
// This route can disable TRACE while its own operation is in flight; its
|
||||
// existing WebUI info record is the authoritative result.
|
||||
const TRACE_EXCLUDED_PATHS = new Set([
|
||||
'/api/auth/check-strength',
|
||||
'/api/logs/level',
|
||||
]);
|
||||
const TRACE_EXCLUDED_PATHS = new Set(['/api/auth/check-strength', '/api/logs/level']);
|
||||
|
||||
interface CapturedBody {
|
||||
bytes: Uint8Array;
|
||||
text: string;
|
||||
bytes: Uint8Array;
|
||||
text: string;
|
||||
}
|
||||
|
||||
function shouldTraceMutation(request: Request): boolean {
|
||||
if (getLogLevel() !== 'trace') return false;
|
||||
if (READ_ONLY_METHODS.has(request.method.toUpperCase())) return false;
|
||||
return !TRACE_EXCLUDED_PATHS.has(new URL(request.url).pathname);
|
||||
if (getLogLevel() !== 'trace') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (READ_ONLY_METHODS.has(request.method.toUpperCase())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !TRACE_EXCLUDED_PATHS.has(new URL(request.url).pathname);
|
||||
}
|
||||
|
||||
async function captureBody(message: Request | Response): Promise<CapturedBody> {
|
||||
const bytes = new Uint8Array(await message.arrayBuffer());
|
||||
return {
|
||||
bytes,
|
||||
text: new TextDecoder().decode(bytes),
|
||||
};
|
||||
const bytes = new Uint8Array(await message.arrayBuffer());
|
||||
return {
|
||||
bytes,
|
||||
text: new TextDecoder().decode(bytes),
|
||||
};
|
||||
}
|
||||
|
||||
function traceBody(
|
||||
branch: 'request_body' | 'response',
|
||||
body: CapturedBody,
|
||||
response?: Response,
|
||||
branch: 'request_body' | 'response',
|
||||
body: CapturedBody,
|
||||
response?: Response,
|
||||
): void {
|
||||
log.trace(() => [
|
||||
'webui_mutation_branch branch=%s%s length=%d text=%j body=%s',
|
||||
branch,
|
||||
response
|
||||
? ` status=${response.status} statusText=${JSON.stringify(response.statusText)} headers=${renderParamsVerbose([...response.headers.entries()])}`
|
||||
: '',
|
||||
body.bytes.byteLength,
|
||||
body.text,
|
||||
renderTraceBytes(body.bytes),
|
||||
]);
|
||||
log.trace(() => [
|
||||
'webui_mutation_branch branch=%s%s length=%d text=%j body=%s',
|
||||
branch,
|
||||
response
|
||||
? ` status=${response.status} statusText=${JSON.stringify(response.statusText)} headers=${renderParamsVerbose([...response.headers.entries()])}`
|
||||
: '',
|
||||
body.bytes.byteLength,
|
||||
body.text,
|
||||
renderTraceBytes(body.bytes),
|
||||
]);
|
||||
}
|
||||
|
||||
function traceStreamChunk(
|
||||
branch: 'request_body_chunk' | 'response_chunk',
|
||||
chunk: Uint8Array,
|
||||
offset: number,
|
||||
branch: 'request_body_chunk' | 'response_chunk',
|
||||
chunk: Uint8Array,
|
||||
offset: number,
|
||||
): void {
|
||||
log.trace(() => [
|
||||
'webui_mutation_branch branch=%s offset=%d length=%d body=%s',
|
||||
branch,
|
||||
offset,
|
||||
chunk.byteLength,
|
||||
renderTraceBytes(chunk),
|
||||
]);
|
||||
log.trace(() => [
|
||||
'webui_mutation_branch branch=%s offset=%d length=%d body=%s',
|
||||
branch,
|
||||
offset,
|
||||
chunk.byteLength,
|
||||
renderTraceBytes(chunk),
|
||||
]);
|
||||
}
|
||||
|
||||
export function traceWebuiMutationRequestChunk(chunk: Uint8Array, offset: number): void {
|
||||
traceStreamChunk('request_body_chunk', chunk, offset);
|
||||
traceStreamChunk('request_body_chunk', chunk, offset);
|
||||
}
|
||||
|
||||
function traceStreamedResponse(
|
||||
response: Response,
|
||||
requestBody: Promise<CapturedBody> | null,
|
||||
startedAt: number,
|
||||
response: Response,
|
||||
requestBody: Promise<CapturedBody> | null,
|
||||
startedAt: number,
|
||||
): Response {
|
||||
if (!response.body) {
|
||||
void settleMutation(
|
||||
requestBody,
|
||||
Promise.resolve({ bytes: new Uint8Array(), text: '' }),
|
||||
response,
|
||||
startedAt,
|
||||
false,
|
||||
);
|
||||
return response;
|
||||
}
|
||||
if (!response.body) {
|
||||
void settleMutation(
|
||||
requestBody,
|
||||
Promise.resolve({ bytes: new Uint8Array(), text: '' }),
|
||||
response,
|
||||
startedAt,
|
||||
false,
|
||||
);
|
||||
return response;
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const requestId = currentRequestId();
|
||||
const inContext = <T>(fn: () => T): T => requestId === undefined
|
||||
? fn()
|
||||
: runWithRequestId(requestId, fn);
|
||||
let offset = 0;
|
||||
let settled = false;
|
||||
const terminal = (outcome: 'completed' | 'failed' | 'cancelled', reason: string, error?: unknown) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
void inContext(() => traceRequestBody(requestBody)).then(() => {
|
||||
inContext(() => log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s status=%d%s elapsedMs=%d',
|
||||
outcome,
|
||||
reason,
|
||||
response.status,
|
||||
error === undefined ? '' : ` error=${JSON.stringify(error instanceof Error ? error.message : String(error))}`,
|
||||
Date.now() - startedAt,
|
||||
));
|
||||
});
|
||||
};
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
try {
|
||||
const result = await reader.read();
|
||||
if (result.done) {
|
||||
terminal(response.ok ? 'completed' : 'failed', response.ok ? 'response_completed' : 'http_status');
|
||||
controller.close();
|
||||
return;
|
||||
const reader = response.body.getReader();
|
||||
const requestId = currentRequestId();
|
||||
const inContext = <T>(fn: () => T): T =>
|
||||
requestId === undefined ? fn() : runWithRequestId(requestId, fn);
|
||||
let offset = 0;
|
||||
let settled = false;
|
||||
|
||||
const terminal = (
|
||||
outcome: 'completed' | 'failed' | 'cancelled',
|
||||
reason: string,
|
||||
error?: unknown,
|
||||
) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
const chunk = result.value;
|
||||
inContext(() => traceStreamChunk('response_chunk', chunk, offset));
|
||||
offset += chunk.byteLength;
|
||||
controller.enqueue(chunk);
|
||||
} catch (error) {
|
||||
terminal(error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed',
|
||||
error instanceof Error && error.name === 'AbortError' ? 'body_cancelled' : 'body_read_failed', error);
|
||||
controller.error(error);
|
||||
}
|
||||
},
|
||||
async cancel(reason) {
|
||||
terminal('cancelled', 'body_cancelled', reason);
|
||||
await reader.cancel(reason);
|
||||
},
|
||||
}, { highWaterMark: 0 });
|
||||
return new Response(body, response);
|
||||
|
||||
settled = true;
|
||||
void inContext(() => traceRequestBody(requestBody)).then(() => {
|
||||
inContext(() =>
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s status=%d%s elapsedMs=%d',
|
||||
outcome,
|
||||
reason,
|
||||
response.status,
|
||||
error === undefined
|
||||
? ''
|
||||
: ` error=${JSON.stringify(error instanceof Error ? error.message : String(error))}`,
|
||||
Date.now() - startedAt,
|
||||
),
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const body = new ReadableStream<Uint8Array>(
|
||||
{
|
||||
async pull(controller) {
|
||||
try {
|
||||
const result = await reader.read();
|
||||
|
||||
if (result.done) {
|
||||
terminal(
|
||||
response.ok ? 'completed' : 'failed',
|
||||
response.ok ? 'response_completed' : 'http_status',
|
||||
);
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
|
||||
const chunk = result.value;
|
||||
inContext(() => traceStreamChunk('response_chunk', chunk, offset));
|
||||
offset += chunk.byteLength;
|
||||
controller.enqueue(chunk);
|
||||
} catch (error) {
|
||||
terminal(
|
||||
error instanceof Error && error.name === 'AbortError'
|
||||
? 'cancelled'
|
||||
: 'failed',
|
||||
error instanceof Error && error.name === 'AbortError'
|
||||
? 'body_cancelled'
|
||||
: 'body_read_failed',
|
||||
error,
|
||||
);
|
||||
controller.error(error);
|
||||
}
|
||||
},
|
||||
async cancel(reason) {
|
||||
terminal('cancelled', 'body_cancelled', reason);
|
||||
await reader.cancel(reason);
|
||||
},
|
||||
},
|
||||
{ highWaterMark: 0 },
|
||||
);
|
||||
return new Response(body, response);
|
||||
}
|
||||
|
||||
async function traceRequestBody(requestBody: Promise<CapturedBody> | null): Promise<void> {
|
||||
if (!requestBody) return;
|
||||
try {
|
||||
traceBody('request_body', await requestBody);
|
||||
} catch (error) {
|
||||
log.trace(
|
||||
'webui_mutation_branch branch=request_body_failed error=%j',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
if (!requestBody) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
traceBody('request_body', await requestBody);
|
||||
} catch (error) {
|
||||
log.trace(
|
||||
'webui_mutation_branch branch=request_body_failed error=%j',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function settleMutation(
|
||||
requestBody: Promise<CapturedBody> | null,
|
||||
responseBody: Promise<CapturedBody>,
|
||||
response: Response,
|
||||
startedAt: number,
|
||||
requestCancelled: boolean,
|
||||
requestBody: Promise<CapturedBody> | null,
|
||||
responseBody: Promise<CapturedBody>,
|
||||
response: Response,
|
||||
startedAt: number,
|
||||
requestCancelled: boolean,
|
||||
): Promise<void> {
|
||||
const results = await Promise.allSettled([
|
||||
requestBody ?? Promise.resolve<CapturedBody>({ bytes: new Uint8Array(), text: '' }),
|
||||
responseBody,
|
||||
]);
|
||||
const [requestResult, responseResult] = results;
|
||||
if (requestBody && requestResult.status === 'fulfilled') traceBody('request_body', requestResult.value);
|
||||
if (requestBody && requestResult.status === 'rejected') {
|
||||
log.trace('webui_mutation_branch branch=request_body_failed error=%j',
|
||||
requestResult.reason instanceof Error ? requestResult.reason.message : String(requestResult.reason));
|
||||
}
|
||||
if (responseResult.status === 'fulfilled') traceBody('response', responseResult.value, response);
|
||||
else {
|
||||
log.trace(() => [
|
||||
'webui_mutation_branch branch=response_body_failed status=%d statusText=%j headers=%s error=%j',
|
||||
response.status,
|
||||
response.statusText,
|
||||
renderParamsVerbose([...response.headers.entries()]),
|
||||
responseResult.reason instanceof Error ? responseResult.reason.message : String(responseResult.reason),
|
||||
const results = await Promise.allSettled([
|
||||
requestBody ?? Promise.resolve<CapturedBody>({ bytes: new Uint8Array(), text: '' }),
|
||||
responseBody,
|
||||
]);
|
||||
}
|
||||
const error = responseResult.status === 'rejected'
|
||||
? responseResult.reason
|
||||
: requestResult.status === 'rejected'
|
||||
? requestResult.reason
|
||||
: undefined;
|
||||
if (error === undefined) {
|
||||
if (requestCancelled) {
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=cancelled reason=request_cancelled status=%d elapsedMs=%d',
|
||||
response.status,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return;
|
||||
const [requestResult, responseResult] = results;
|
||||
|
||||
if (requestBody && requestResult.status === 'fulfilled') {
|
||||
traceBody('request_body', requestResult.value);
|
||||
}
|
||||
|
||||
if (requestBody && requestResult.status === 'rejected') {
|
||||
log.trace(
|
||||
'webui_mutation_branch branch=request_body_failed error=%j',
|
||||
requestResult.reason instanceof Error
|
||||
? requestResult.reason.message
|
||||
: String(requestResult.reason),
|
||||
);
|
||||
}
|
||||
|
||||
if (responseResult.status === 'fulfilled') {
|
||||
traceBody('response', responseResult.value, response);
|
||||
} else {
|
||||
log.trace(() => [
|
||||
'webui_mutation_branch branch=response_body_failed status=%d statusText=%j headers=%s error=%j',
|
||||
response.status,
|
||||
response.statusText,
|
||||
renderParamsVerbose([...response.headers.entries()]),
|
||||
responseResult.reason instanceof Error
|
||||
? responseResult.reason.message
|
||||
: String(responseResult.reason),
|
||||
]);
|
||||
}
|
||||
|
||||
const error =
|
||||
responseResult.status === 'rejected'
|
||||
? responseResult.reason
|
||||
: requestResult.status === 'rejected'
|
||||
? requestResult.reason
|
||||
: undefined;
|
||||
|
||||
if (error === undefined) {
|
||||
if (requestCancelled) {
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=cancelled reason=request_cancelled status=%d elapsedMs=%d',
|
||||
response.status,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s status=%d elapsedMs=%d',
|
||||
response.ok ? 'completed' : 'failed',
|
||||
response.ok ? 'response_completed' : 'http_status',
|
||||
response.status,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s status=%d elapsedMs=%d',
|
||||
response.ok ? 'completed' : 'failed',
|
||||
response.ok ? 'response_completed' : 'http_status',
|
||||
response.status,
|
||||
Date.now() - startedAt,
|
||||
'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d',
|
||||
error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed',
|
||||
error instanceof Error && error.name === 'AbortError'
|
||||
? 'body_cancelled'
|
||||
: 'body_read_failed',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return;
|
||||
}
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d',
|
||||
error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed',
|
||||
error instanceof Error && error.name === 'AbortError' ? 'body_cancelled' : 'body_read_failed',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
}
|
||||
|
||||
function failureOutcome(error: unknown): {
|
||||
outcome: 'failed' | 'timeout' | 'cancelled';
|
||||
reason: string;
|
||||
outcome: 'failed' | 'timeout' | 'cancelled';
|
||||
reason: string;
|
||||
} {
|
||||
if (error instanceof Error && error.name === 'TimeoutError') {
|
||||
return { outcome: 'timeout', reason: 'handler_timeout' };
|
||||
}
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
return { outcome: 'cancelled', reason: 'handler_cancelled' };
|
||||
}
|
||||
return { outcome: 'failed', reason: 'handler_threw' };
|
||||
if (error instanceof Error && error.name === 'TimeoutError') {
|
||||
return { outcome: 'timeout', reason: 'handler_timeout' };
|
||||
}
|
||||
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
return { outcome: 'cancelled', reason: 'handler_cancelled' };
|
||||
}
|
||||
|
||||
return { outcome: 'failed', reason: 'handler_threw' };
|
||||
}
|
||||
|
||||
/** Trace one authenticated WebUI write without consuming its live streams. */
|
||||
export function traceAuthenticatedWebuiMutation(
|
||||
request: Request,
|
||||
next: () => Promise<Response>,
|
||||
request: Request,
|
||||
next: () => Promise<Response>,
|
||||
): Promise<Response> {
|
||||
if (!shouldTraceMutation(request)) return next();
|
||||
|
||||
return runWithTraceRequest(async () => {
|
||||
const startedAt = Date.now();
|
||||
const requestHeaders = [...request.headers.entries()];
|
||||
const pathname = new URL(request.url).pathname;
|
||||
let requestBody: Promise<CapturedBody> | null = null;
|
||||
|
||||
log.trace(() => [
|
||||
'webui_mutation_start method=%j url=%j headers=%s',
|
||||
request.method,
|
||||
request.url,
|
||||
renderParamsVerbose(requestHeaders),
|
||||
]);
|
||||
|
||||
if (!STREAMED_REQUEST_PATHS.has(pathname)) {
|
||||
try {
|
||||
requestBody = captureBody(request.clone());
|
||||
} catch (error) {
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=failed reason=request_clone_failed error=%j elapsedMs=%d',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
if (!shouldTraceMutation(request)) {
|
||||
return next();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await next();
|
||||
if (STREAMED_RESPONSE_PATHS.has(pathname)) {
|
||||
return traceStreamedResponse(response, requestBody, startedAt);
|
||||
}
|
||||
let responseBody: Promise<CapturedBody>;
|
||||
try {
|
||||
responseBody = captureBody(response.clone());
|
||||
} catch (error) {
|
||||
void traceRequestBody(requestBody).then(() => {
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=failed reason=response_clone_failed error=%j elapsedMs=%d',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
return response;
|
||||
}
|
||||
return runWithTraceRequest(async () => {
|
||||
const startedAt = Date.now();
|
||||
const requestHeaders = [...request.headers.entries()];
|
||||
const pathname = new URL(request.url).pathname;
|
||||
let requestBody: Promise<CapturedBody> | null = null;
|
||||
|
||||
void settleMutation(
|
||||
requestBody,
|
||||
responseBody,
|
||||
response,
|
||||
startedAt,
|
||||
STREAMED_REQUEST_PATHS.has(pathname) && request.signal.aborted,
|
||||
);
|
||||
return response;
|
||||
} catch (error) {
|
||||
await traceRequestBody(requestBody);
|
||||
const failure = failureOutcome(error);
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d',
|
||||
failure.outcome,
|
||||
failure.reason,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
log.trace(() => [
|
||||
'webui_mutation_start method=%j url=%j headers=%s',
|
||||
request.method,
|
||||
request.url,
|
||||
renderParamsVerbose(requestHeaders),
|
||||
]);
|
||||
|
||||
if (!STREAMED_REQUEST_PATHS.has(pathname)) {
|
||||
try {
|
||||
requestBody = captureBody(request.clone());
|
||||
} catch (error) {
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=failed reason=request_clone_failed error=%j elapsedMs=%d',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return next();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await next();
|
||||
|
||||
if (STREAMED_RESPONSE_PATHS.has(pathname)) {
|
||||
return traceStreamedResponse(response, requestBody, startedAt);
|
||||
}
|
||||
|
||||
let responseBody: Promise<CapturedBody>;
|
||||
|
||||
try {
|
||||
responseBody = captureBody(response.clone());
|
||||
} catch (error) {
|
||||
void traceRequestBody(requestBody).then(() => {
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=failed reason=response_clone_failed error=%j elapsedMs=%d',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
return response;
|
||||
}
|
||||
|
||||
void settleMutation(
|
||||
requestBody,
|
||||
responseBody,
|
||||
response,
|
||||
startedAt,
|
||||
STREAMED_REQUEST_PATHS.has(pathname) && request.signal.aborted,
|
||||
);
|
||||
return response;
|
||||
} catch (error) {
|
||||
await traceRequestBody(requestBody);
|
||||
const failure = failureOutcome(error);
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d',
|
||||
failure.outcome,
|
||||
failure.reason,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -3,22 +3,34 @@ import type { OneBotConfig } from '@snowluma/onebot/types';
|
||||
import { isLoopbackClientIp } from './client-ip';
|
||||
|
||||
function isLoopbackBindHost(host: string | undefined): boolean {
|
||||
const value = host?.trim().toLowerCase().replace(/^\[|\]$/gu, '').replace(/\.$/u, '') ?? '';
|
||||
if (!value) return false;
|
||||
if (value === 'localhost' || value.endsWith('.localhost')) return true;
|
||||
return isLoopbackClientIp(value);
|
||||
const value =
|
||||
host
|
||||
?.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^\[|\]$/gu, '')
|
||||
.replace(/\.$/u, '') ?? '';
|
||||
|
||||
if (!value) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (value === 'localhost' || value.endsWith('.localhost')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return isLoopbackClientIp(value);
|
||||
}
|
||||
|
||||
export class OneBotAccessTokenPolicyError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'OneBotAccessTokenPolicyError';
|
||||
}
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'OneBotAccessTokenPolicyError';
|
||||
}
|
||||
}
|
||||
|
||||
export interface OneBotAccessTokenPolicyOptions {
|
||||
clientIp: string;
|
||||
uin: string;
|
||||
clientIp: string;
|
||||
uin: string;
|
||||
}
|
||||
|
||||
type InboundKind = 'httpServers' | 'wsServers';
|
||||
@@ -26,63 +38,77 @@ type InboundKind = 'httpServers' | 'wsServers';
|
||||
const INBOUND_KINDS: readonly InboundKind[] = ['httpServers', 'wsServers'];
|
||||
|
||||
function sameTokenAtPreviousIdentity(
|
||||
previous: OneBotConfig['networks'][InboundKind],
|
||||
next: OneBotConfig['networks'][InboundKind],
|
||||
nextName: string,
|
||||
nextToken: string,
|
||||
index: number,
|
||||
previous: OneBotConfig['networks'][InboundKind],
|
||||
next: OneBotConfig['networks'][InboundKind],
|
||||
nextName: string,
|
||||
nextToken: string,
|
||||
index: number,
|
||||
): boolean {
|
||||
const named = previous.find((adapter) => adapter.name === nextName);
|
||||
if (named && (named.accessToken ?? '') === nextToken) return true;
|
||||
// Preserve a legacy token when the operator only renames the same list item.
|
||||
// Reordering keeps names stable and is covered by the lookup above.
|
||||
const sameIndex = previous[index];
|
||||
return sameIndex !== undefined
|
||||
&& !next.some((adapter) => adapter.name === sameIndex.name)
|
||||
&& (sameIndex.accessToken ?? '') === nextToken;
|
||||
const named = previous.find((adapter) => adapter.name === nextName);
|
||||
|
||||
if (named && (named.accessToken ?? '') === nextToken) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Preserve a legacy token when the operator only renames the same list item.
|
||||
// Reordering keeps names stable and is covered by the lookup above.
|
||||
const sameIndex = previous[index];
|
||||
return (
|
||||
sameIndex !== undefined &&
|
||||
!next.some((adapter) => adapter.name === sameIndex.name) &&
|
||||
(sameIndex.accessToken ?? '') === nextToken
|
||||
);
|
||||
}
|
||||
|
||||
export function validateOneBotAccessTokenChanges(
|
||||
previous: OneBotConfig | null,
|
||||
next: OneBotConfig,
|
||||
options: OneBotAccessTokenPolicyOptions,
|
||||
previous: OneBotConfig | null,
|
||||
next: OneBotConfig,
|
||||
options: OneBotAccessTokenPolicyOptions,
|
||||
): void {
|
||||
const allowEmptyFromClient = isLoopbackClientIp(options.clientIp);
|
||||
for (const kind of INBOUND_KINDS) {
|
||||
const previousList = previous?.networks[kind] ?? [];
|
||||
const nextList = next.networks[kind];
|
||||
for (let index = 0; index < nextList.length; index += 1) {
|
||||
const adapter = nextList[index];
|
||||
const token = adapter.accessToken ?? '';
|
||||
if (sameTokenAtPreviousIdentity(previousList, nextList, adapter.name, token, index)) continue;
|
||||
const allowEmptyFromClient = isLoopbackClientIp(options.clientIp);
|
||||
|
||||
if (!token) {
|
||||
if (!allowEmptyFromClient && !isLoopbackBindHost(adapter.host)) {
|
||||
throw new OneBotAccessTokenPolicyError(
|
||||
`节点“${adapter.name}”未绑定本机地址,远程保存必须填写令牌;请生成令牌或将主机改为 127.0.0.1。`,
|
||||
);
|
||||
for (const kind of INBOUND_KINDS) {
|
||||
const previousList = previous?.networks[kind] ?? [];
|
||||
const nextList = next.networks[kind];
|
||||
|
||||
for (let index = 0; index < nextList.length; index += 1) {
|
||||
const adapter = nextList[index];
|
||||
const token = adapter.accessToken ?? '';
|
||||
|
||||
if (sameTokenAtPreviousIdentity(previousList, nextList, adapter.name, token, index)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
if (!allowEmptyFromClient && !isLoopbackBindHost(adapter.host)) {
|
||||
throw new OneBotAccessTokenPolicyError(
|
||||
`节点“${adapter.name}”未绑定本机地址,远程保存必须填写令牌;请生成令牌或将主机改为 127.0.0.1。`,
|
||||
);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
const host = adapter.host ?? '0.0.0.0';
|
||||
const assessment = assessAccessToken(token, [
|
||||
options.uin,
|
||||
adapter.name,
|
||||
kind,
|
||||
host,
|
||||
adapter.port,
|
||||
]);
|
||||
|
||||
if (assessment.reason === 'too-short') {
|
||||
throw new OneBotAccessTokenPolicyError(
|
||||
`节点“${adapter.name}”的令牌至少需要 16 个字符;请重新生成或继续补充。`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!assessment.acceptable) {
|
||||
throw new OneBotAccessTokenPolicyError(
|
||||
`节点“${adapter.name}”的令牌容易被猜中;请重新生成随机令牌。`,
|
||||
);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const host = adapter.host ?? '0.0.0.0';
|
||||
const assessment = assessAccessToken(token, [
|
||||
options.uin,
|
||||
adapter.name,
|
||||
kind,
|
||||
host,
|
||||
adapter.port,
|
||||
]);
|
||||
if (assessment.reason === 'too-short') {
|
||||
throw new OneBotAccessTokenPolicyError(
|
||||
`节点“${adapter.name}”的令牌至少需要 16 个字符;请重新生成或继续补充。`,
|
||||
);
|
||||
}
|
||||
if (!assessment.acceptable) {
|
||||
throw new OneBotAccessTokenPolicyError(
|
||||
`节点“${adapter.name}”的令牌容易被猜中;请重新生成随机令牌。`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,33 @@
|
||||
import net from 'net';
|
||||
|
||||
function isPortAvailable(port: number, host = '127.0.0.1'): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer();
|
||||
let settled = false;
|
||||
const finalize = (ok: boolean) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
try {
|
||||
server.close(() => resolve(ok));
|
||||
} catch {
|
||||
resolve(ok);
|
||||
}
|
||||
};
|
||||
server.once('error', () => finalize(false));
|
||||
server.once('listening', () => finalize(true));
|
||||
try {
|
||||
server.listen(port, host);
|
||||
} catch {
|
||||
finalize(false);
|
||||
}
|
||||
});
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer();
|
||||
let settled = false;
|
||||
|
||||
const finalize = (ok: boolean) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
|
||||
try {
|
||||
server.close(() => resolve(ok));
|
||||
} catch {
|
||||
resolve(ok);
|
||||
}
|
||||
};
|
||||
|
||||
server.once('error', () => finalize(false));
|
||||
server.once('listening', () => finalize(true));
|
||||
|
||||
try {
|
||||
server.listen(port, host);
|
||||
} catch {
|
||||
finalize(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -28,15 +35,23 @@ function isPortAvailable(port: number, host = '127.0.0.1'): Promise<boolean> {
|
||||
* Skips reserved/invalid port numbers.
|
||||
*/
|
||||
export async function findAvailablePort(
|
||||
start: number,
|
||||
options: { maxTries?: number; host?: string } = {},
|
||||
start: number,
|
||||
options: { maxTries?: number; host?: string } = {},
|
||||
): Promise<number> {
|
||||
const { maxTries = 50, host = '127.0.0.1' } = options;
|
||||
let port = Math.max(1, Math.min(65535, Math.trunc(start)));
|
||||
for (let i = 0; i < maxTries; i++) {
|
||||
if (port > 65535) break;
|
||||
if (await isPortAvailable(port, host)) return port;
|
||||
port += 1;
|
||||
}
|
||||
throw new Error(`No available TCP port found near ${start}`);
|
||||
const { maxTries = 50, host = '127.0.0.1' } = options;
|
||||
let port = Math.max(1, Math.min(65535, Math.trunc(start)));
|
||||
|
||||
for (let i = 0; i < maxTries; i++) {
|
||||
if (port > 65535) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (await isPortAvailable(port, host)) {
|
||||
return port;
|
||||
}
|
||||
|
||||
port += 1;
|
||||
}
|
||||
|
||||
throw new Error(`No available TCP port found near ${start}`);
|
||||
}
|
||||
@@ -7,59 +7,63 @@ const AVATAR_SESSION_COOKIE = 'snowluma_avatar_session';
|
||||
const AVATAR_SESSION_MAX_AGE_SECONDS = 24 * 60 * 60;
|
||||
|
||||
function isJsonMediaType(value: string | undefined): boolean {
|
||||
const mediaType = value?.split(';', 1)[0]?.trim().toLowerCase() ?? '';
|
||||
return mediaType === 'application/json' || mediaType.endsWith('+json');
|
||||
const mediaType = value?.split(';', 1)[0]?.trim().toLowerCase() ?? '';
|
||||
return mediaType === 'application/json' || mediaType.endsWith('+json');
|
||||
}
|
||||
|
||||
/** Install guards before the login route is registered. */
|
||||
export function registerLoginRequestSecurity(app: Hono): void {
|
||||
app.use('/api/login', bodyLimit({
|
||||
maxSize: LOGIN_BODY_LIMIT_BYTES,
|
||||
onError: (c) => c.json({ success: false, message: '请求体过大' }, 413),
|
||||
}));
|
||||
app.use('/api/login', async (c, next) => {
|
||||
if (!isJsonMediaType(c.req.header('content-type'))) {
|
||||
return c.json({ success: false, message: 'Content-Type 必须为 application/json' }, 415);
|
||||
}
|
||||
return next();
|
||||
});
|
||||
app.use(
|
||||
'/api/login',
|
||||
bodyLimit({
|
||||
maxSize: LOGIN_BODY_LIMIT_BYTES,
|
||||
onError: (c) => c.json({ success: false, message: '请求体过大' }, 413),
|
||||
}),
|
||||
);
|
||||
app.use('/api/login', async (c, next) => {
|
||||
if (!isJsonMediaType(c.req.header('content-type'))) {
|
||||
return c.json({ success: false, message: 'Content-Type 必须为 application/json' }, 415);
|
||||
}
|
||||
|
||||
return next();
|
||||
});
|
||||
}
|
||||
|
||||
/** Minimal response policy that does not restrict the current script/style bundle. */
|
||||
export const webuiSecurityHeaders: MiddlewareHandler = async (c, next) => {
|
||||
await next();
|
||||
c.res.headers.set('X-Frame-Options', 'DENY');
|
||||
c.res.headers.set('X-Content-Type-Options', 'nosniff');
|
||||
c.res.headers.set('Referrer-Policy', 'no-referrer');
|
||||
c.res.headers.set(
|
||||
'Content-Security-Policy',
|
||||
"frame-ancestors 'none'; base-uri 'self'; object-src 'none'",
|
||||
);
|
||||
await next();
|
||||
c.res.headers.set('X-Frame-Options', 'DENY');
|
||||
c.res.headers.set('X-Content-Type-Options', 'nosniff');
|
||||
c.res.headers.set('Referrer-Policy', 'no-referrer');
|
||||
c.res.headers.set(
|
||||
'Content-Security-Policy',
|
||||
"frame-ancestors 'none'; base-uri 'self'; object-src 'none'",
|
||||
);
|
||||
};
|
||||
|
||||
export function extractBearerToken(request: Request): string {
|
||||
const authorization = request.headers.get('authorization');
|
||||
return authorization?.startsWith('Bearer ') ? authorization.slice(7) : '';
|
||||
const authorization = request.headers.get('authorization');
|
||||
return authorization?.startsWith('Bearer ') ? authorization.slice(7) : '';
|
||||
}
|
||||
|
||||
const avatarCookieOptions = (secure: boolean) => ({
|
||||
httpOnly: true,
|
||||
sameSite: 'Strict' as const,
|
||||
secure,
|
||||
path: '/avatar',
|
||||
httpOnly: true,
|
||||
sameSite: 'Strict' as const,
|
||||
secure,
|
||||
path: '/avatar',
|
||||
});
|
||||
|
||||
export function setAvatarSessionCookie(c: Context, token: string, secure: boolean): void {
|
||||
setCookie(c, AVATAR_SESSION_COOKIE, token, {
|
||||
...avatarCookieOptions(secure),
|
||||
maxAge: AVATAR_SESSION_MAX_AGE_SECONDS,
|
||||
});
|
||||
setCookie(c, AVATAR_SESSION_COOKIE, token, {
|
||||
...avatarCookieOptions(secure),
|
||||
maxAge: AVATAR_SESSION_MAX_AGE_SECONDS,
|
||||
});
|
||||
}
|
||||
|
||||
export function clearAvatarSessionCookie(c: Context, secure: boolean): void {
|
||||
deleteCookie(c, AVATAR_SESSION_COOKIE, avatarCookieOptions(secure));
|
||||
deleteCookie(c, AVATAR_SESSION_COOKIE, avatarCookieOptions(secure));
|
||||
}
|
||||
|
||||
export function readAvatarSessionToken(c: Context): string {
|
||||
return getCookie(c, AVATAR_SESSION_COOKIE) ?? '';
|
||||
return getCookie(c, AVATAR_SESSION_COOKIE) ?? '';
|
||||
}
|
||||
+374
-320
@@ -2,78 +2,74 @@ import { createLogger } from '@snowluma/common/logger';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
prepareRestorePlan,
|
||||
RestorePreflightError,
|
||||
type RestoreMigration,
|
||||
} from './backup';
|
||||
import { prepareRestorePlan, RestorePreflightError, type RestoreMigration } from './backup';
|
||||
|
||||
const log = createLogger('WebUI.Restore');
|
||||
|
||||
export type RestorePhase = 'preflight' | 'snapshot' | 'stage' | 'commit' | 'rollback' | 'cleanup';
|
||||
|
||||
export interface RestoreOperation {
|
||||
phase: Exclude<RestorePhase, 'preflight'>;
|
||||
operation:
|
||||
| 'copy-current'
|
||||
| 'write-staged'
|
||||
| 'chmod-staged'
|
||||
| 'rename-staged'
|
||||
| 'restore-current'
|
||||
| 'remove-created'
|
||||
| 'remove-transaction';
|
||||
file?: string;
|
||||
phase: Exclude<RestorePhase, 'preflight'>;
|
||||
operation:
|
||||
| 'copy-current'
|
||||
| 'write-staged'
|
||||
| 'chmod-staged'
|
||||
| 'rename-staged'
|
||||
| 'restore-current'
|
||||
| 'remove-created'
|
||||
| 'remove-transaction';
|
||||
file?: string;
|
||||
}
|
||||
|
||||
export interface RestoreBackupOptions {
|
||||
configDir: string;
|
||||
restoreCredentials: boolean;
|
||||
/** Deterministic id for tests/diagnostics; production normally omits it. */
|
||||
transactionId?: string;
|
||||
/** Filesystem-boundary fault hook used by the transaction fault matrix. */
|
||||
beforeOperation?: (operation: RestoreOperation) => void;
|
||||
configDir: string;
|
||||
restoreCredentials: boolean;
|
||||
/** Deterministic id for tests/diagnostics; production normally omits it. */
|
||||
transactionId?: string;
|
||||
/** Filesystem-boundary fault hook used by the transaction fault matrix. */
|
||||
beforeOperation?: (operation: RestoreOperation) => void;
|
||||
}
|
||||
|
||||
export interface RestoreBackupResult {
|
||||
transactionId: string;
|
||||
restored: string[];
|
||||
skipped: string[];
|
||||
migrated: RestoreMigration[];
|
||||
restartRequiredToApply: boolean;
|
||||
transactionId: string;
|
||||
restored: string[];
|
||||
skipped: string[];
|
||||
migrated: RestoreMigration[];
|
||||
restartRequiredToApply: boolean;
|
||||
}
|
||||
|
||||
export class RestoreTransactionError extends Error {
|
||||
readonly phase: RestorePhase;
|
||||
readonly transactionId: string;
|
||||
readonly rollbackSucceeded?: boolean;
|
||||
readonly snapshotDir?: string;
|
||||
readonly committed: boolean;
|
||||
readonly failedFiles: string[];
|
||||
readonly phase: RestorePhase;
|
||||
readonly transactionId: string;
|
||||
readonly rollbackSucceeded?: boolean;
|
||||
readonly snapshotDir?: string;
|
||||
readonly committed: boolean;
|
||||
readonly failedFiles: string[];
|
||||
|
||||
constructor(options: {
|
||||
phase: RestorePhase;
|
||||
transactionId: string;
|
||||
message: string;
|
||||
cause: unknown;
|
||||
rollbackSucceeded?: boolean;
|
||||
snapshotDir?: string;
|
||||
committed?: boolean;
|
||||
failedFiles?: string[];
|
||||
}) {
|
||||
super(options.message, { cause: options.cause });
|
||||
this.name = 'RestoreTransactionError';
|
||||
this.phase = options.phase;
|
||||
this.transactionId = options.transactionId;
|
||||
this.rollbackSucceeded = options.rollbackSucceeded;
|
||||
this.snapshotDir = options.snapshotDir;
|
||||
this.committed = options.committed ?? false;
|
||||
this.failedFiles = options.failedFiles ?? [];
|
||||
}
|
||||
constructor(options: {
|
||||
phase: RestorePhase;
|
||||
transactionId: string;
|
||||
message: string;
|
||||
cause: unknown;
|
||||
rollbackSucceeded?: boolean;
|
||||
snapshotDir?: string;
|
||||
committed?: boolean;
|
||||
failedFiles?: string[];
|
||||
}) {
|
||||
super(options.message, { cause: options.cause });
|
||||
this.name = 'RestoreTransactionError';
|
||||
this.phase = options.phase;
|
||||
this.transactionId = options.transactionId;
|
||||
this.rollbackSucceeded = options.rollbackSucceeded;
|
||||
this.snapshotDir = options.snapshotDir;
|
||||
this.committed = options.committed ?? false;
|
||||
this.failedFiles = options.failedFiles ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
interface CommittedFile {
|
||||
name: string;
|
||||
existed: boolean;
|
||||
name: string;
|
||||
existed: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -85,307 +81,365 @@ interface CommittedFile {
|
||||
* rollback retains the transaction directory and reports its recovery path.
|
||||
*/
|
||||
export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): RestoreBackupResult {
|
||||
const transactionId = options.transactionId ?? randomUUID();
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(transactionId)) {
|
||||
throw new Error('restore transactionId must contain only letters, numbers, _ or -');
|
||||
}
|
||||
const configDir = path.resolve(options.configDir);
|
||||
const readCurrent = (name: string): Buffer | null => {
|
||||
const file = path.join(configDir, name);
|
||||
try {
|
||||
return fs.readFileSync(file);
|
||||
} catch (error) {
|
||||
if (isMissingPathError(error)) return null;
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
const listCurrentOneBotNames = (): string[] => {
|
||||
try {
|
||||
return fs.readdirSync(configDir);
|
||||
} catch (error) {
|
||||
if (isMissingPathError(error)) return [];
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
const transactionId = options.transactionId ?? randomUUID();
|
||||
|
||||
log.info('restore transaction=%s phase=preflight', transactionId);
|
||||
let prepared: ReturnType<typeof prepareRestorePlan>;
|
||||
try {
|
||||
prepared = prepareRestorePlan(parsed, {
|
||||
restoreCredentials: options.restoreCredentials,
|
||||
readCurrent,
|
||||
listCurrentOneBotNames,
|
||||
});
|
||||
} catch (error) {
|
||||
const file = error instanceof RestorePreflightError ? error.file : undefined;
|
||||
log.warn(
|
||||
'restore transaction=%s phase=preflight file=%s failed error=%s',
|
||||
transactionId,
|
||||
file ?? '-',
|
||||
errorMessage(error),
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'preflight',
|
||||
transactionId,
|
||||
message: `restore preflight failed: ${errorMessage(error)}`,
|
||||
cause: error,
|
||||
failedFiles: file ? [file] : [],
|
||||
});
|
||||
}
|
||||
const names = prepared.restore.map((file) => file.name);
|
||||
log.info('restore transaction=%s phase=preflight-complete files=%s', transactionId, names.join(','));
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(transactionId)) {
|
||||
throw new Error('restore transactionId must contain only letters, numbers, _ or -');
|
||||
}
|
||||
|
||||
if (prepared.restore.length === 0) {
|
||||
return {
|
||||
transactionId,
|
||||
restored: [],
|
||||
skipped: prepared.skipped,
|
||||
migrated: prepared.migrated,
|
||||
restartRequiredToApply: false,
|
||||
const configDir = path.resolve(options.configDir);
|
||||
|
||||
const readCurrent = (name: string): Buffer | null => {
|
||||
const file = path.join(configDir, name);
|
||||
|
||||
try {
|
||||
return fs.readFileSync(file);
|
||||
} catch (error) {
|
||||
if (isMissingPathError(error)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const transactionDir = path.join(configDir, `.restore-transaction-${transactionId}`);
|
||||
const snapshotRoot = path.join(transactionDir, 'snapshot');
|
||||
const stagedRoot = path.join(transactionDir, 'staged');
|
||||
const rollbackRoot = path.join(transactionDir, 'rollback');
|
||||
const existed = new Map<string, boolean>();
|
||||
const committed: CommittedFile[] = [];
|
||||
let phase: 'snapshot' | 'stage' | 'commit' = 'snapshot';
|
||||
let activeFile: string | undefined;
|
||||
let transactionCreated = false;
|
||||
const listCurrentOneBotNames = (): string[] => {
|
||||
try {
|
||||
return fs.readdirSync(configDir);
|
||||
} catch (error) {
|
||||
if (isMissingPathError(error)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.mkdirSync(transactionDir, { mode: 0o700 });
|
||||
transactionCreated = true;
|
||||
fs.chmodSync(transactionDir, 0o700);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
log.info('restore transaction=%s phase=snapshot files=%s', transactionId, names.join(','));
|
||||
for (const file of prepared.restore) {
|
||||
activeFile = file.name;
|
||||
const live = path.join(configDir, file.name);
|
||||
let wasPresent: boolean;
|
||||
try {
|
||||
fs.lstatSync(live);
|
||||
wasPresent = true;
|
||||
} catch (error) {
|
||||
if (!isMissingPathError(error)) throw error;
|
||||
wasPresent = false;
|
||||
}
|
||||
existed.set(file.name, wasPresent);
|
||||
if (!wasPresent) continue;
|
||||
const snapshot = path.join(snapshotRoot, file.name);
|
||||
fs.mkdirSync(path.dirname(snapshot), { recursive: true });
|
||||
invoke(options, { phase: 'snapshot', operation: 'copy-current', file: file.name });
|
||||
fs.copyFileSync(live, snapshot);
|
||||
}
|
||||
log.info('restore transaction=%s phase=preflight', transactionId);
|
||||
let prepared: ReturnType<typeof prepareRestorePlan>;
|
||||
|
||||
phase = 'stage';
|
||||
log.info('restore transaction=%s phase=stage files=%s', transactionId, names.join(','));
|
||||
for (const file of prepared.restore) {
|
||||
activeFile = file.name;
|
||||
const staged = path.join(stagedRoot, file.name);
|
||||
fs.mkdirSync(path.dirname(staged), { recursive: true });
|
||||
invoke(options, { phase: 'stage', operation: 'write-staged', file: file.name });
|
||||
fs.writeFileSync(staged, file.data, { flag: 'wx', mode: file.mode });
|
||||
invoke(options, { phase: 'stage', operation: 'chmod-staged', file: file.name });
|
||||
fs.chmodSync(staged, file.mode);
|
||||
}
|
||||
|
||||
phase = 'commit';
|
||||
log.info('restore transaction=%s phase=commit files=%s', transactionId, names.join(','));
|
||||
for (const file of prepared.restore) {
|
||||
activeFile = file.name;
|
||||
const staged = path.join(stagedRoot, file.name);
|
||||
const live = path.join(configDir, file.name);
|
||||
fs.mkdirSync(path.dirname(live), { recursive: true });
|
||||
invoke(options, { phase: 'commit', operation: 'rename-staged', file: file.name });
|
||||
fs.renameSync(staged, live);
|
||||
committed.push({ name: file.name, existed: existed.get(file.name) === true });
|
||||
}
|
||||
activeFile = undefined;
|
||||
} catch (error) {
|
||||
if (phase !== 'commit') {
|
||||
const cleanupError = transactionCreated ? removeTransaction(options, transactionDir) : null;
|
||||
if (cleanupError) {
|
||||
log.error(
|
||||
'restore transaction=%s phase=cleanup failed-after=%s file=%s original-error=%s cleanup-error=%s',
|
||||
transactionId,
|
||||
phase,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
errorMessage(cleanupError),
|
||||
try {
|
||||
prepared = prepareRestorePlan(parsed, {
|
||||
restoreCredentials: options.restoreCredentials,
|
||||
readCurrent,
|
||||
listCurrentOneBotNames,
|
||||
});
|
||||
} catch (error) {
|
||||
const file = error instanceof RestorePreflightError ? error.file : undefined;
|
||||
log.warn(
|
||||
'restore transaction=%s phase=preflight file=%s failed error=%s',
|
||||
transactionId,
|
||||
file ?? '-',
|
||||
errorMessage(error),
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'cleanup',
|
||||
transactionId,
|
||||
message: `restore ${phase} failed and transaction cleanup also failed`,
|
||||
cause: new AggregateError([error, cleanupError], `restore ${phase} and cleanup both failed`),
|
||||
snapshotDir: transactionDir,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
phase: 'preflight',
|
||||
transactionId,
|
||||
message: `restore preflight failed: ${errorMessage(error)}`,
|
||||
cause: error,
|
||||
failedFiles: file ? [file] : [],
|
||||
});
|
||||
}
|
||||
log.warn(
|
||||
'restore transaction=%s phase=%s file=%s failed error=%s',
|
||||
transactionId,
|
||||
phase,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase,
|
||||
transactionId,
|
||||
message: `restore ${phase} failed before live commit`,
|
||||
cause: error,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
});
|
||||
}
|
||||
|
||||
const rollbackErrors = rollbackCommitted(options, configDir, snapshotRoot, rollbackRoot, committed);
|
||||
if (rollbackErrors.length > 0) {
|
||||
const failedFiles = rollbackErrors.map((entry) => entry.name);
|
||||
const rollbackDetails = rollbackErrors
|
||||
.map((entry) => `${entry.name}:${errorMessage(entry.error)}`)
|
||||
.join(';');
|
||||
log.error(
|
||||
'restore transaction=%s phase=rollback commit-file=%s commit-error=%s failed=%s snapshot=%s',
|
||||
const names = prepared.restore.map((file) => file.name);
|
||||
log.info(
|
||||
'restore transaction=%s phase=preflight-complete files=%s',
|
||||
transactionId,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
rollbackDetails,
|
||||
transactionDir,
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'rollback',
|
||||
transactionId,
|
||||
message: 'restore commit failed and rollback was incomplete',
|
||||
cause: new AggregateError(
|
||||
[error, ...rollbackErrors.map((entry) => entry.error)],
|
||||
'restore commit and rollback both failed',
|
||||
),
|
||||
rollbackSucceeded: false,
|
||||
snapshotDir: transactionDir,
|
||||
committed: committed.length > 0,
|
||||
failedFiles,
|
||||
});
|
||||
names.join(','),
|
||||
);
|
||||
|
||||
if (prepared.restore.length === 0) {
|
||||
return {
|
||||
transactionId,
|
||||
restored: [],
|
||||
skipped: prepared.skipped,
|
||||
migrated: prepared.migrated,
|
||||
restartRequiredToApply: false,
|
||||
};
|
||||
}
|
||||
|
||||
const transactionDir = path.join(configDir, `.restore-transaction-${transactionId}`);
|
||||
const snapshotRoot = path.join(transactionDir, 'snapshot');
|
||||
const stagedRoot = path.join(transactionDir, 'staged');
|
||||
const rollbackRoot = path.join(transactionDir, 'rollback');
|
||||
const existed = new Map<string, boolean>();
|
||||
const committed: CommittedFile[] = [];
|
||||
let phase: 'snapshot' | 'stage' | 'commit' = 'snapshot';
|
||||
let activeFile: string | undefined;
|
||||
let transactionCreated = false;
|
||||
|
||||
try {
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.mkdirSync(transactionDir, { mode: 0o700 });
|
||||
transactionCreated = true;
|
||||
fs.chmodSync(transactionDir, 0o700);
|
||||
|
||||
log.info('restore transaction=%s phase=snapshot files=%s', transactionId, names.join(','));
|
||||
|
||||
for (const file of prepared.restore) {
|
||||
activeFile = file.name;
|
||||
const live = path.join(configDir, file.name);
|
||||
let wasPresent: boolean;
|
||||
|
||||
try {
|
||||
fs.lstatSync(live);
|
||||
wasPresent = true;
|
||||
} catch (error) {
|
||||
if (!isMissingPathError(error)) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
wasPresent = false;
|
||||
}
|
||||
|
||||
existed.set(file.name, wasPresent);
|
||||
|
||||
if (!wasPresent) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const snapshot = path.join(snapshotRoot, file.name);
|
||||
fs.mkdirSync(path.dirname(snapshot), { recursive: true });
|
||||
invoke(options, { phase: 'snapshot', operation: 'copy-current', file: file.name });
|
||||
fs.copyFileSync(live, snapshot);
|
||||
}
|
||||
|
||||
phase = 'stage';
|
||||
log.info('restore transaction=%s phase=stage files=%s', transactionId, names.join(','));
|
||||
|
||||
for (const file of prepared.restore) {
|
||||
activeFile = file.name;
|
||||
const staged = path.join(stagedRoot, file.name);
|
||||
fs.mkdirSync(path.dirname(staged), { recursive: true });
|
||||
invoke(options, { phase: 'stage', operation: 'write-staged', file: file.name });
|
||||
fs.writeFileSync(staged, file.data, { flag: 'wx', mode: file.mode });
|
||||
invoke(options, { phase: 'stage', operation: 'chmod-staged', file: file.name });
|
||||
fs.chmodSync(staged, file.mode);
|
||||
}
|
||||
|
||||
phase = 'commit';
|
||||
log.info('restore transaction=%s phase=commit files=%s', transactionId, names.join(','));
|
||||
|
||||
for (const file of prepared.restore) {
|
||||
activeFile = file.name;
|
||||
const staged = path.join(stagedRoot, file.name);
|
||||
const live = path.join(configDir, file.name);
|
||||
fs.mkdirSync(path.dirname(live), { recursive: true });
|
||||
invoke(options, { phase: 'commit', operation: 'rename-staged', file: file.name });
|
||||
fs.renameSync(staged, live);
|
||||
committed.push({ name: file.name, existed: existed.get(file.name) === true });
|
||||
}
|
||||
|
||||
activeFile = undefined;
|
||||
} catch (error) {
|
||||
if (phase !== 'commit') {
|
||||
const cleanupError = transactionCreated
|
||||
? removeTransaction(options, transactionDir)
|
||||
: null;
|
||||
|
||||
if (cleanupError) {
|
||||
log.error(
|
||||
'restore transaction=%s phase=cleanup failed-after=%s file=%s original-error=%s cleanup-error=%s',
|
||||
transactionId,
|
||||
phase,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
errorMessage(cleanupError),
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'cleanup',
|
||||
transactionId,
|
||||
message: `restore ${phase} failed and transaction cleanup also failed`,
|
||||
cause: new AggregateError(
|
||||
[error, cleanupError],
|
||||
`restore ${phase} and cleanup both failed`,
|
||||
),
|
||||
snapshotDir: transactionDir,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
});
|
||||
}
|
||||
|
||||
log.warn(
|
||||
'restore transaction=%s phase=%s file=%s failed error=%s',
|
||||
transactionId,
|
||||
phase,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase,
|
||||
transactionId,
|
||||
message: `restore ${phase} failed before live commit`,
|
||||
cause: error,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
});
|
||||
}
|
||||
|
||||
const rollbackErrors = rollbackCommitted(
|
||||
options,
|
||||
configDir,
|
||||
snapshotRoot,
|
||||
rollbackRoot,
|
||||
committed,
|
||||
);
|
||||
|
||||
if (rollbackErrors.length > 0) {
|
||||
const failedFiles = rollbackErrors.map((entry) => entry.name);
|
||||
const rollbackDetails = rollbackErrors
|
||||
.map((entry) => `${entry.name}:${errorMessage(entry.error)}`)
|
||||
.join(';');
|
||||
log.error(
|
||||
'restore transaction=%s phase=rollback commit-file=%s commit-error=%s failed=%s snapshot=%s',
|
||||
transactionId,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
rollbackDetails,
|
||||
transactionDir,
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'rollback',
|
||||
transactionId,
|
||||
message: 'restore commit failed and rollback was incomplete',
|
||||
cause: new AggregateError(
|
||||
[error, ...rollbackErrors.map((entry) => entry.error)],
|
||||
'restore commit and rollback both failed',
|
||||
),
|
||||
rollbackSucceeded: false,
|
||||
snapshotDir: transactionDir,
|
||||
committed: committed.length > 0,
|
||||
failedFiles,
|
||||
});
|
||||
}
|
||||
|
||||
const cleanupError = removeTransaction(options, transactionDir);
|
||||
|
||||
if (cleanupError) {
|
||||
log.error(
|
||||
'restore transaction=%s phase=cleanup failed-after=rollback commit-file=%s commit-error=%s cleanup-error=%s snapshot=%s',
|
||||
transactionId,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
errorMessage(cleanupError),
|
||||
transactionDir,
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'cleanup',
|
||||
transactionId,
|
||||
message:
|
||||
'restore commit failed, rollback succeeded, but transaction cleanup failed',
|
||||
cause: new AggregateError(
|
||||
[error, cleanupError],
|
||||
'restore commit and post-rollback cleanup both failed',
|
||||
),
|
||||
rollbackSucceeded: true,
|
||||
snapshotDir: transactionDir,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
});
|
||||
}
|
||||
|
||||
log.warn(
|
||||
'restore transaction=%s phase=commit file=%s failed rollback=complete error=%s',
|
||||
transactionId,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'commit',
|
||||
transactionId,
|
||||
message: 'restore commit failed; every committed file was rolled back',
|
||||
cause: error,
|
||||
rollbackSucceeded: true,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
});
|
||||
}
|
||||
|
||||
const cleanupError = removeTransaction(options, transactionDir);
|
||||
|
||||
if (cleanupError) {
|
||||
log.error(
|
||||
'restore transaction=%s phase=cleanup failed-after=rollback commit-file=%s commit-error=%s cleanup-error=%s snapshot=%s',
|
||||
transactionId,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
errorMessage(cleanupError),
|
||||
transactionDir,
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'cleanup',
|
||||
transactionId,
|
||||
message: 'restore commit failed, rollback succeeded, but transaction cleanup failed',
|
||||
cause: new AggregateError([error, cleanupError], 'restore commit and post-rollback cleanup both failed'),
|
||||
rollbackSucceeded: true,
|
||||
snapshotDir: transactionDir,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
});
|
||||
log.error(
|
||||
'restore transaction=%s phase=cleanup failed-after=commit cleanup-error=%s snapshot=%s',
|
||||
transactionId,
|
||||
errorMessage(cleanupError),
|
||||
transactionDir,
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'cleanup',
|
||||
transactionId,
|
||||
message: 'restore committed successfully, but transaction cleanup failed',
|
||||
cause: cleanupError,
|
||||
snapshotDir: transactionDir,
|
||||
committed: true,
|
||||
});
|
||||
}
|
||||
log.warn(
|
||||
'restore transaction=%s phase=commit file=%s failed rollback=complete error=%s',
|
||||
transactionId,
|
||||
activeFile ?? '-',
|
||||
errorMessage(error),
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'commit',
|
||||
transactionId,
|
||||
message: 'restore commit failed; every committed file was rolled back',
|
||||
cause: error,
|
||||
rollbackSucceeded: true,
|
||||
failedFiles: activeFile ? [activeFile] : [],
|
||||
});
|
||||
}
|
||||
|
||||
const cleanupError = removeTransaction(options, transactionDir);
|
||||
if (cleanupError) {
|
||||
log.error(
|
||||
'restore transaction=%s phase=cleanup failed-after=commit cleanup-error=%s snapshot=%s',
|
||||
transactionId,
|
||||
errorMessage(cleanupError),
|
||||
transactionDir,
|
||||
);
|
||||
throw new RestoreTransactionError({
|
||||
phase: 'cleanup',
|
||||
transactionId,
|
||||
message: 'restore committed successfully, but transaction cleanup failed',
|
||||
cause: cleanupError,
|
||||
snapshotDir: transactionDir,
|
||||
committed: true,
|
||||
});
|
||||
}
|
||||
|
||||
log.info('restore transaction=%s phase=complete files=%s', transactionId, names.join(','));
|
||||
return {
|
||||
transactionId,
|
||||
restored: names,
|
||||
skipped: prepared.skipped,
|
||||
migrated: prepared.migrated,
|
||||
restartRequiredToApply: true,
|
||||
};
|
||||
log.info('restore transaction=%s phase=complete files=%s', transactionId, names.join(','));
|
||||
return {
|
||||
transactionId,
|
||||
restored: names,
|
||||
skipped: prepared.skipped,
|
||||
migrated: prepared.migrated,
|
||||
restartRequiredToApply: true,
|
||||
};
|
||||
}
|
||||
|
||||
function rollbackCommitted(
|
||||
options: RestoreBackupOptions,
|
||||
configDir: string,
|
||||
snapshotRoot: string,
|
||||
rollbackRoot: string,
|
||||
committed: readonly CommittedFile[],
|
||||
options: RestoreBackupOptions,
|
||||
configDir: string,
|
||||
snapshotRoot: string,
|
||||
rollbackRoot: string,
|
||||
committed: readonly CommittedFile[],
|
||||
): Array<{ name: string; error: unknown }> {
|
||||
const errors: Array<{ name: string; error: unknown }> = [];
|
||||
for (const file of [...committed].reverse()) {
|
||||
const live = path.join(configDir, file.name);
|
||||
try {
|
||||
if (!file.existed) {
|
||||
invoke(options, { phase: 'rollback', operation: 'remove-created', file: file.name });
|
||||
fs.rmSync(live, { force: true });
|
||||
continue;
|
||||
}
|
||||
const snapshot = path.join(snapshotRoot, file.name);
|
||||
const rollback = path.join(rollbackRoot, file.name);
|
||||
fs.mkdirSync(path.dirname(rollback), { recursive: true });
|
||||
invoke(options, { phase: 'rollback', operation: 'restore-current', file: file.name });
|
||||
fs.copyFileSync(snapshot, rollback);
|
||||
fs.chmodSync(rollback, fs.statSync(snapshot).mode & 0o777);
|
||||
fs.renameSync(rollback, live);
|
||||
} catch (error) {
|
||||
errors.push({ name: file.name, error });
|
||||
const errors: Array<{ name: string; error: unknown }> = [];
|
||||
|
||||
for (const file of [...committed].reverse()) {
|
||||
const live = path.join(configDir, file.name);
|
||||
|
||||
try {
|
||||
if (!file.existed) {
|
||||
invoke(options, {
|
||||
phase: 'rollback',
|
||||
operation: 'remove-created',
|
||||
file: file.name,
|
||||
});
|
||||
fs.rmSync(live, { force: true });
|
||||
continue;
|
||||
}
|
||||
|
||||
const snapshot = path.join(snapshotRoot, file.name);
|
||||
const rollback = path.join(rollbackRoot, file.name);
|
||||
fs.mkdirSync(path.dirname(rollback), { recursive: true });
|
||||
invoke(options, { phase: 'rollback', operation: 'restore-current', file: file.name });
|
||||
fs.copyFileSync(snapshot, rollback);
|
||||
fs.chmodSync(rollback, fs.statSync(snapshot).mode & 0o777);
|
||||
fs.renameSync(rollback, live);
|
||||
} catch (error) {
|
||||
errors.push({ name: file.name, error });
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
function removeTransaction(options: RestoreBackupOptions, transactionDir: string): unknown | null {
|
||||
try {
|
||||
invoke(options, { phase: 'cleanup', operation: 'remove-transaction' });
|
||||
fs.rmSync(transactionDir, { recursive: true, force: true });
|
||||
return null;
|
||||
} catch (error) {
|
||||
return error;
|
||||
}
|
||||
try {
|
||||
invoke(options, { phase: 'cleanup', operation: 'remove-transaction' });
|
||||
fs.rmSync(transactionDir, { recursive: true, force: true });
|
||||
return null;
|
||||
} catch (error) {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
function invoke(options: RestoreBackupOptions, operation: RestoreOperation): void {
|
||||
options.beforeOperation?.(operation);
|
||||
options.beforeOperation?.(operation);
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function isMissingPathError(error: unknown): boolean {
|
||||
return typeof error === 'object'
|
||||
&& error !== null
|
||||
&& 'code' in error
|
||||
&& error.code === 'ENOENT';
|
||||
return (
|
||||
typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'
|
||||
);
|
||||
}
|
||||
+2195
-1650
File diff suppressed because it is too large.
Load diff
@@ -6,18 +6,18 @@ import { type Context } from 'hono';
|
||||
* transport lifecycle (heartbeat / teardown / abort / headers).
|
||||
*/
|
||||
export interface SseChannel {
|
||||
/** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */
|
||||
raw(chunk: Uint8Array): void;
|
||||
/** Encode a string to bytes (shared TextEncoder). */
|
||||
encode(s: string): Uint8Array;
|
||||
/** Convenience: enqueue one `data: <json>\n\n` frame. */
|
||||
send(payload: unknown): void;
|
||||
/** Register a cleanup to run once on teardown (unsubscribe / dispose). */
|
||||
onClose(fn: () => void): void;
|
||||
/** True after teardown — guard sends from late subscription callbacks. */
|
||||
isClosed(): boolean;
|
||||
/** Underlying controller backpressure signal, for `createFramePusher`. */
|
||||
desiredSize(): number | null;
|
||||
/** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */
|
||||
raw(chunk: Uint8Array): void;
|
||||
/** Encode a string to bytes (shared TextEncoder). */
|
||||
encode(s: string): Uint8Array;
|
||||
/** Convenience: enqueue one `data: <json>\n\n` frame. */
|
||||
send(payload: unknown): void;
|
||||
/** Register a cleanup to run once on teardown (unsubscribe / dispose). */
|
||||
onClose(fn: () => void): void;
|
||||
/** True after teardown — guard sends from late subscription callbacks. */
|
||||
isClosed(): boolean;
|
||||
/** Underlying controller backpressure signal, for `createFramePusher`. */
|
||||
desiredSize(): number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -33,37 +33,71 @@ export interface SseChannel {
|
||||
* teardown-order / header change had to be kept in sync across all three.
|
||||
*/
|
||||
export function sseResponse(c: Context, start: (ch: SseChannel) => void): Response {
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
let heartbeat: ReturnType<typeof setInterval> | undefined;
|
||||
const cleanups: Array<() => void> = [];
|
||||
const teardown = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
for (const fn of cleanups) { try { fn(); } catch { /* ignore */ } }
|
||||
try { controller.close(); } catch { /* ignore */ }
|
||||
};
|
||||
const raw = (chunk: Uint8Array) => {
|
||||
if (closed) return;
|
||||
try { controller.enqueue(chunk); } catch { teardown(); }
|
||||
};
|
||||
const ch: SseChannel = {
|
||||
raw,
|
||||
encode: (s) => encoder.encode(s),
|
||||
send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)),
|
||||
onClose: (fn) => { cleanups.push(fn); },
|
||||
isClosed: () => closed,
|
||||
desiredSize: () => controller.desiredSize,
|
||||
};
|
||||
start(ch);
|
||||
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
});
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
let heartbeat: ReturnType<typeof setInterval> | undefined;
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
const teardown = () => {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
closed = true;
|
||||
|
||||
if (heartbeat) {
|
||||
clearInterval(heartbeat);
|
||||
}
|
||||
|
||||
for (const fn of cleanups) {
|
||||
try {
|
||||
fn();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
const raw = (chunk: Uint8Array) => {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
controller.enqueue(chunk);
|
||||
} catch {
|
||||
teardown();
|
||||
}
|
||||
};
|
||||
|
||||
const ch: SseChannel = {
|
||||
raw,
|
||||
encode: (s) => encoder.encode(s),
|
||||
send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)),
|
||||
onClose: (fn) => {
|
||||
cleanups.push(fn);
|
||||
},
|
||||
isClosed: () => closed,
|
||||
desiredSize: () => controller.desiredSize,
|
||||
};
|
||||
start(ch);
|
||||
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
Connection: 'keep-alive',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -22,46 +22,57 @@ export type StateResource = 'processes' | 'qq-list' | 'connections';
|
||||
export type StateListener = (resource: StateResource) => void;
|
||||
|
||||
export class StateBus {
|
||||
private readonly listeners = new Set<StateListener>();
|
||||
private disposed = false;
|
||||
private readonly listeners = new Set<StateListener>();
|
||||
private disposed = false;
|
||||
|
||||
/** Subscribe to every publish; returns an unsubscribe handle. Calling
|
||||
* the handle more than once is a no-op. */
|
||||
subscribe(listener: StateListener): () => void {
|
||||
if (this.disposed) return () => undefined;
|
||||
this.listeners.add(listener);
|
||||
let active = true;
|
||||
return () => {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
/** Subscribe to every publish; returns an unsubscribe handle. Calling
|
||||
* the handle more than once is a no-op. */
|
||||
subscribe(listener: StateListener): () => void {
|
||||
if (this.disposed) {
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
/** Notify every CURRENTLY-subscribed listener that `resource` is stale.
|
||||
* Iterates a frozen snapshot of the subscriber set so add/remove during
|
||||
* the emit don't change which listeners see THIS publish; subscriber
|
||||
* exceptions are isolated and do not abort the fan-out. */
|
||||
publish(resource: StateResource): void {
|
||||
if (this.disposed) return;
|
||||
// Snapshot the current subscribers — any subscribe()/unsubscribe()
|
||||
// called by a listener during the fan-out takes effect only for the
|
||||
// NEXT publish, not this one.
|
||||
const snapshot = [...this.listeners];
|
||||
for (const fn of snapshot) {
|
||||
try {
|
||||
fn(resource);
|
||||
} catch {
|
||||
// Subscriber-internal failure is its own problem. The bus's job
|
||||
// is to keep delivery moving — surfacing an error here would
|
||||
// partially abort the fan-out and create skip-the-listener bugs.
|
||||
}
|
||||
this.listeners.add(listener);
|
||||
let active = true;
|
||||
|
||||
return () => {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
|
||||
active = false;
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop every subscriber and refuse future subscribes / publishes. */
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
this.listeners.clear();
|
||||
}
|
||||
/** Notify every CURRENTLY-subscribed listener that `resource` is stale.
|
||||
* Iterates a frozen snapshot of the subscriber set so add/remove during
|
||||
* the emit don't change which listeners see THIS publish; subscriber
|
||||
* exceptions are isolated and do not abort the fan-out. */
|
||||
publish(resource: StateResource): void {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Snapshot the current subscribers — any subscribe()/unsubscribe()
|
||||
// called by a listener during the fan-out takes effect only for the
|
||||
// NEXT publish, not this one.
|
||||
const snapshot = [...this.listeners];
|
||||
|
||||
for (const fn of snapshot) {
|
||||
try {
|
||||
fn(resource);
|
||||
} catch {
|
||||
// Subscriber-internal failure is its own problem. The bus's job
|
||||
// is to keep delivery moving — surfacing an error here would
|
||||
// partially abort the fan-out and create skip-the-listener bugs.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop every subscriber and refuse future subscribes / publishes. */
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
this.listeners.clear();
|
||||
}
|
||||
}
|
||||
@@ -17,112 +17,140 @@
|
||||
import type { StateBus, StateResource } from './state-bus';
|
||||
|
||||
export interface StateStreamFrame {
|
||||
resource: StateResource;
|
||||
data: unknown;
|
||||
resource: StateResource;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
export interface BindStateStreamOptions {
|
||||
bus: StateBus;
|
||||
/** Read the current snapshot for one resource. May be sync or async. */
|
||||
snapshot: (resource: StateResource) => unknown | Promise<unknown>;
|
||||
/** Receive a fresh frame; called once per debounced publish.
|
||||
* Exceptions are caught — a dead controller must not abort the bus
|
||||
* subscription or break sibling resources. */
|
||||
send: (frame: StateStreamFrame) => void;
|
||||
/** Coalesce window in milliseconds; default 50. */
|
||||
debounceMs?: number;
|
||||
bus: StateBus;
|
||||
/** Read the current snapshot for one resource. May be sync or async. */
|
||||
snapshot: (resource: StateResource) => unknown | Promise<unknown>;
|
||||
/** Receive a fresh frame; called once per debounced publish.
|
||||
* Exceptions are caught — a dead controller must not abort the bus
|
||||
* subscription or break sibling resources. */
|
||||
send: (frame: StateStreamFrame) => void;
|
||||
/** Coalesce window in milliseconds; default 50. */
|
||||
debounceMs?: number;
|
||||
}
|
||||
|
||||
export interface StateStreamHandle {
|
||||
/** Emit one frame per resource using the current snapshot. Use on connect. */
|
||||
sendAllInitial(): Promise<void>;
|
||||
/** Stop subscribing + cancel pending timers. Subsequent bus publishes
|
||||
* produce nothing through this binding. */
|
||||
dispose(): void;
|
||||
/** Emit one frame per resource using the current snapshot. Use on connect. */
|
||||
sendAllInitial(): Promise<void>;
|
||||
/** Stop subscribing + cancel pending timers. Subsequent bus publishes
|
||||
* produce nothing through this binding. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
const ALL_RESOURCES: readonly StateResource[] = ['processes', 'qq-list', 'connections'];
|
||||
|
||||
export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle {
|
||||
const debounceMs = opts.debounceMs ?? 50;
|
||||
const timers = new Map<StateResource, ReturnType<typeof setTimeout>>();
|
||||
// Single-flight per resource: at most one in-flight flush per resource so
|
||||
// an uneven snapshot latency cannot interleave sends out of order (a slow
|
||||
// earlier snapshot landing AFTER a later one, leaving the client's last
|
||||
// observed frame stale). Publishes arriving while a flush is in flight
|
||||
// mark `pending` and rearm the debounce timer once the flush completes.
|
||||
const inFlight = new Set<StateResource>();
|
||||
const pending = new Set<StateResource>();
|
||||
let disposed = false;
|
||||
const debounceMs = opts.debounceMs ?? 50;
|
||||
const timers = new Map<StateResource, ReturnType<typeof setTimeout>>();
|
||||
// Single-flight per resource: at most one in-flight flush per resource so
|
||||
// an uneven snapshot latency cannot interleave sends out of order (a slow
|
||||
// earlier snapshot landing AFTER a later one, leaving the client's last
|
||||
// observed frame stale). Publishes arriving while a flush is in flight
|
||||
// mark `pending` and rearm the debounce timer once the flush completes.
|
||||
const inFlight = new Set<StateResource>();
|
||||
const pending = new Set<StateResource>();
|
||||
let disposed = false;
|
||||
|
||||
const flush = async (resource: StateResource): Promise<void> => {
|
||||
if (disposed) return;
|
||||
inFlight.add(resource);
|
||||
try {
|
||||
let data: unknown;
|
||||
try {
|
||||
data = await opts.snapshot(resource);
|
||||
} catch {
|
||||
// Per-resource snapshot failure (e.g. listProcesses threw): skip
|
||||
// this frame so siblings keep flowing. The next publish for the
|
||||
// same resource gets a fresh attempt.
|
||||
return;
|
||||
}
|
||||
if (disposed) return;
|
||||
try {
|
||||
opts.send({ resource, data });
|
||||
} catch {
|
||||
// Downstream consumer (e.g. closed SSE controller) — same isolation
|
||||
// contract as snapshot failures.
|
||||
}
|
||||
} finally {
|
||||
inFlight.delete(resource);
|
||||
// If a publish arrived during the in-flight window, schedule one
|
||||
// follow-up flush. Re-uses the debounce so a sustained publish
|
||||
// stream produces at most one frame per (debounceMs + flushLatency),
|
||||
// not back-to-back frames.
|
||||
if (!disposed && pending.has(resource)) {
|
||||
pending.delete(resource);
|
||||
schedule(resource);
|
||||
}
|
||||
}
|
||||
};
|
||||
const flush = async (resource: StateResource): Promise<void> => {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
const schedule = (resource: StateResource): void => {
|
||||
if (disposed) return;
|
||||
if (inFlight.has(resource)) {
|
||||
// Defer to the post-flush re-arm; no new timer until the in-flight
|
||||
// send completes. This is the load-bearing invariant for ordering.
|
||||
pending.add(resource);
|
||||
return;
|
||||
}
|
||||
const existing = timers.get(resource);
|
||||
if (existing) clearTimeout(existing);
|
||||
const t = setTimeout(() => {
|
||||
timers.delete(resource);
|
||||
void flush(resource);
|
||||
}, debounceMs);
|
||||
timers.set(resource, t);
|
||||
};
|
||||
inFlight.add(resource);
|
||||
|
||||
const unsubscribe = opts.bus.subscribe(schedule);
|
||||
try {
|
||||
let data: unknown;
|
||||
|
||||
return {
|
||||
async sendAllInitial(): Promise<void> {
|
||||
if (disposed) return;
|
||||
// Fire all three in parallel. Each resource's snapshot is independent
|
||||
// so a slow listProcesses() doesn't gate qq-list/connections. Each
|
||||
// call goes through the single-flight gate so a concurrent bus
|
||||
// publish during this initial fan-out coalesces correctly.
|
||||
await Promise.all(ALL_RESOURCES.map((r) => flush(r)));
|
||||
},
|
||||
dispose(): void {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
unsubscribe();
|
||||
for (const t of timers.values()) clearTimeout(t);
|
||||
timers.clear();
|
||||
pending.clear();
|
||||
},
|
||||
};
|
||||
try {
|
||||
data = await opts.snapshot(resource);
|
||||
} catch {
|
||||
// Per-resource snapshot failure (e.g. listProcesses threw): skip
|
||||
// this frame so siblings keep flowing. The next publish for the
|
||||
// same resource gets a fresh attempt.
|
||||
return;
|
||||
}
|
||||
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
opts.send({ resource, data });
|
||||
} catch {
|
||||
// Downstream consumer (e.g. closed SSE controller) — same isolation
|
||||
// contract as snapshot failures.
|
||||
}
|
||||
} finally {
|
||||
inFlight.delete(resource);
|
||||
|
||||
// If a publish arrived during the in-flight window, schedule one
|
||||
// follow-up flush. Re-uses the debounce so a sustained publish
|
||||
// stream produces at most one frame per (debounceMs + flushLatency),
|
||||
// not back-to-back frames.
|
||||
if (!disposed && pending.has(resource)) {
|
||||
pending.delete(resource);
|
||||
schedule(resource);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const schedule = (resource: StateResource): void => {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (inFlight.has(resource)) {
|
||||
// Defer to the post-flush re-arm; no new timer until the in-flight
|
||||
// send completes. This is the load-bearing invariant for ordering.
|
||||
pending.add(resource);
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = timers.get(resource);
|
||||
|
||||
if (existing) {
|
||||
clearTimeout(existing);
|
||||
}
|
||||
|
||||
const t = setTimeout(() => {
|
||||
timers.delete(resource);
|
||||
void flush(resource);
|
||||
}, debounceMs);
|
||||
timers.set(resource, t);
|
||||
};
|
||||
|
||||
const unsubscribe = opts.bus.subscribe(schedule);
|
||||
|
||||
return {
|
||||
async sendAllInitial(): Promise<void> {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Fire all three in parallel. Each resource's snapshot is independent
|
||||
// so a slow listProcesses() doesn't gate qq-list/connections. Each
|
||||
// call goes through the single-flight gate so a concurrent bus
|
||||
// publish during this initial fan-out coalesces correctly.
|
||||
await Promise.all(ALL_RESOURCES.map((r) => flush(r)));
|
||||
},
|
||||
dispose(): void {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
disposed = true;
|
||||
unsubscribe();
|
||||
|
||||
for (const t of timers.values()) {
|
||||
clearTimeout(t);
|
||||
}
|
||||
|
||||
timers.clear();
|
||||
pending.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -23,52 +23,58 @@ import { StateBus } from './state-bus';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
|
||||
export interface StateWiring {
|
||||
/** The bus the SSE handler subscribes to. */
|
||||
readonly bus: StateBus;
|
||||
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */
|
||||
onSessionsChanged: () => void;
|
||||
/** Hook into a BridgeManager so its session edges publish 'qq-list' and
|
||||
* 'connections'. Can be called at most once per wiring (subsequent calls
|
||||
* add duplicate listeners). */
|
||||
bindBridgeManager(bm: BridgeManager): void;
|
||||
/** Drop every listener + neuter the bus so further publishes do nothing. */
|
||||
dispose(): void;
|
||||
/** The bus the SSE handler subscribes to. */
|
||||
readonly bus: StateBus;
|
||||
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */
|
||||
onSessionsChanged: () => void;
|
||||
/** Hook into a BridgeManager so its session edges publish 'qq-list' and
|
||||
* 'connections'. Can be called at most once per wiring (subsequent calls
|
||||
* add duplicate listeners). */
|
||||
bindBridgeManager(bm: BridgeManager): void;
|
||||
/** Drop every listener + neuter the bus so further publishes do nothing. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export function createStateWiring(): StateWiring {
|
||||
const bus = new StateBus();
|
||||
let disposed = false;
|
||||
const bus = new StateBus();
|
||||
let disposed = false;
|
||||
|
||||
const publish = (resource: Parameters<StateBus['publish']>[0]): void => {
|
||||
if (disposed) return;
|
||||
bus.publish(resource);
|
||||
};
|
||||
const publish = (resource: Parameters<StateBus['publish']>[0]): void => {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
return {
|
||||
bus,
|
||||
onSessionsChanged: () => publish('processes'),
|
||||
bindBridgeManager(bm: BridgeManager): void {
|
||||
// Account appeared: the qq-list response gains an entry and the
|
||||
// connections response gains the new account's adapter row. Two
|
||||
// distinct resource invalidations, in source-of-truth order
|
||||
// (account exists → only then can adapters be enumerated for it).
|
||||
bm.addSessionStartedListener(() => {
|
||||
publish('qq-list');
|
||||
publish('connections');
|
||||
});
|
||||
// Account disappeared: same two resources shrink, same order so a
|
||||
// racy WebUI receiving both events independently sees the qq-list
|
||||
// shrink before it tries to render connections for a uin that's
|
||||
// about to vanish.
|
||||
bm.addSessionClosedListener(() => {
|
||||
publish('qq-list');
|
||||
publish('connections');
|
||||
});
|
||||
},
|
||||
dispose(): void {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
bus.dispose();
|
||||
},
|
||||
};
|
||||
bus.publish(resource);
|
||||
};
|
||||
|
||||
return {
|
||||
bus,
|
||||
onSessionsChanged: () => publish('processes'),
|
||||
bindBridgeManager(bm: BridgeManager): void {
|
||||
// Account appeared: the qq-list response gains an entry and the
|
||||
// connections response gains the new account's adapter row. Two
|
||||
// distinct resource invalidations, in source-of-truth order
|
||||
// (account exists → only then can adapters be enumerated for it).
|
||||
bm.addSessionStartedListener(() => {
|
||||
publish('qq-list');
|
||||
publish('connections');
|
||||
});
|
||||
// Account disappeared: same two resources shrink, same order so a
|
||||
// racy WebUI receiving both events independently sees the qq-list
|
||||
// shrink before it tries to render connections for a uin that's
|
||||
// about to vanish.
|
||||
bm.addSessionClosedListener(() => {
|
||||
publish('qq-list');
|
||||
publish('connections');
|
||||
});
|
||||
},
|
||||
dispose(): void {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
disposed = true;
|
||||
bus.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,333 +1,387 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type {
|
||||
LogCleanupResult,
|
||||
LogStorageStatus,
|
||||
} from '@snowluma/common/log-file-transport';
|
||||
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;
|
||||
totalBytes: number;
|
||||
fileCount: number;
|
||||
activeItemCount: number;
|
||||
}
|
||||
|
||||
export interface TemporaryCleanupResult {
|
||||
deletedFiles: number;
|
||||
freedBytes: number;
|
||||
skippedActiveItems: number;
|
||||
failures: Array<{ item: string; message: string }>;
|
||||
deletedFiles: number;
|
||||
freedBytes: number;
|
||||
skippedActiveItems: number;
|
||||
failures: Array<{ item: string; message: string }>;
|
||||
}
|
||||
|
||||
export interface TemporaryStorageAdapter {
|
||||
snapshot(): TemporaryStorageSnapshot;
|
||||
clearInactive(): TemporaryCleanupResult;
|
||||
snapshot(): TemporaryStorageSnapshot;
|
||||
clearInactive(): TemporaryCleanupResult;
|
||||
}
|
||||
|
||||
export interface OnlineStorageAccount {
|
||||
uin: string;
|
||||
nickname: string;
|
||||
uin: string;
|
||||
nickname: string;
|
||||
}
|
||||
|
||||
export interface AccountStorageSnapshot {
|
||||
uin: string;
|
||||
nickname?: string;
|
||||
online: boolean;
|
||||
messagesBytes: number;
|
||||
mediaBytes: number;
|
||||
reactionsBytes: number;
|
||||
totalBytes: number;
|
||||
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, '[日志目录]'),
|
||||
};
|
||||
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;
|
||||
status: PublicLogStorageStatus;
|
||||
}
|
||||
|
||||
export interface StorageSnapshot {
|
||||
logs: PublicLogStorageStatus;
|
||||
temporary: TemporaryStorageSnapshot;
|
||||
accounts: AccountStorageSnapshot[];
|
||||
totals: {
|
||||
logsBytes: number;
|
||||
temporaryBytes: number;
|
||||
accountDataBytes: number;
|
||||
managedBytes: number;
|
||||
};
|
||||
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 }>;
|
||||
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';
|
||||
}
|
||||
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';
|
||||
}
|
||||
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[];
|
||||
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'],
|
||||
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) {}
|
||||
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);
|
||||
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 {
|
||||
uin,
|
||||
...(nickname ? { nickname } : {}),
|
||||
online: online.has(uin),
|
||||
messagesBytes,
|
||||
mediaBytes,
|
||||
reactionsBytes,
|
||||
totalBytes: messagesBytes + mediaBytes + reactionsBytes,
|
||||
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;
|
||||
}
|
||||
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');
|
||||
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;
|
||||
}
|
||||
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;
|
||||
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;
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
function isMissing(error: unknown): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
|
||||
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;
|
||||
}
|
||||
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}`);
|
||||
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);
|
||||
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);
|
||||
const absolute = path.resolve(filePath);
|
||||
return message.split(absolute).join(label).split(filePath).join(label);
|
||||
}
|
||||
@@ -1,317 +1,373 @@
|
||||
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,
|
||||
StorageAccountOnlineError,
|
||||
StorageManagementInputError,
|
||||
type AccountDataCleanupResult,
|
||||
type AccountStorageCategory,
|
||||
type PublicLogCleanupResult,
|
||||
type StorageManagementService,
|
||||
type StorageSnapshot,
|
||||
type TemporaryCleanupResult,
|
||||
} from './storage-management';
|
||||
import {
|
||||
StorageSettingsInputError,
|
||||
StorageSettingsLockedError,
|
||||
StorageSettingsTransactionError,
|
||||
type LogStorageSettingsManager,
|
||||
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;
|
||||
};
|
||||
| { scope: 'logs' }
|
||||
| { scope: 'temporary' }
|
||||
| { scope: 'account'; category: AccountStorageCategory; uin: string }
|
||||
| {
|
||||
scope: 'allAccounts';
|
||||
category: AccountStorageCategory;
|
||||
confirmation: typeof ALL_ACCOUNTS_CONFIRMATION;
|
||||
};
|
||||
|
||||
type StorageCleanupResult =
|
||||
| PublicLogCleanupResult
|
||||
| TemporaryCleanupResult
|
||||
| AccountDataCleanupResult;
|
||||
PublicLogCleanupResult | TemporaryCleanupResult | AccountDataCleanupResult;
|
||||
|
||||
export interface StorageCleanupAuditEvent {
|
||||
scope: StorageCleanupRequest['scope'];
|
||||
accountScope: 'global' | 'single' | 'all';
|
||||
category?: AccountStorageCategory;
|
||||
uin?: string;
|
||||
deletedFiles: number;
|
||||
freedBytes: number;
|
||||
failureCount: number;
|
||||
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 }>;
|
||||
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;
|
||||
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;
|
||||
};
|
||||
let lastCleanup: LastStorageCleanup | null = null;
|
||||
let mutationQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
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,
|
||||
})),
|
||||
const serializeMutation = <T>(operation: () => Promise<T>): Promise<T> => {
|
||||
const result = mutationQueue.then(operation);
|
||||
mutationQueue = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return result;
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
});
|
||||
|
||||
const success = cleanup.failures.length === 0;
|
||||
return c.json({
|
||||
success,
|
||||
...(success ? {} : { message: '部分文件清理失败,请检查失败明细' }),
|
||||
scope: request.scope,
|
||||
cleanup,
|
||||
snapshot,
|
||||
lastCleanup,
|
||||
}, success ? 200 : 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');
|
||||
if (!isObject(body) || typeof body.scope !== 'string') {
|
||||
throw new StorageManagementInputError('scope is required');
|
||||
}
|
||||
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');
|
||||
if (body.scope === 'logs' || body.scope === 'temporary') {
|
||||
assertExactKeys(body, ['scope']);
|
||||
return { scope: body.scope };
|
||||
}
|
||||
return {
|
||||
scope: 'allAccounts',
|
||||
category,
|
||||
confirmation: ALL_ACCOUNTS_CONFIRMATION,
|
||||
};
|
||||
}
|
||||
|
||||
throw new StorageManagementInputError(`unsupported cleanup 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,
|
||||
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);
|
||||
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');
|
||||
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');
|
||||
}
|
||||
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';
|
||||
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 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);
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -1,312 +1,328 @@
|
||||
import type {
|
||||
LogStoragePolicy,
|
||||
LogStorageStatus,
|
||||
} from '@snowluma/common/log-file-transport';
|
||||
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,
|
||||
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';
|
||||
import { publicLogStorageStatus, type PublicLogStorageStatus } from './storage-management';
|
||||
|
||||
export type LogStorageSettingsField =
|
||||
| 'logMaxTotalMb'
|
||||
| 'logRetainDays'
|
||||
| 'logPerUin';
|
||||
export type LogStorageSettingsField = 'logMaxTotalMb' | 'logRetainDays' | 'logPerUin';
|
||||
|
||||
export interface LogStorageSettings {
|
||||
logMaxTotalMb: number;
|
||||
logRetainDays: number;
|
||||
logPerUin: boolean;
|
||||
logMaxTotalMb: number;
|
||||
logRetainDays: number;
|
||||
logPerUin: boolean;
|
||||
}
|
||||
|
||||
export interface LogStorageSettingsState {
|
||||
saved: LogStorageSettings;
|
||||
effective: LogStorageSettings;
|
||||
envOverrides: LogStorageSettingsField[];
|
||||
saved: LogStorageSettings;
|
||||
effective: LogStorageSettings;
|
||||
envOverrides: LogStorageSettingsField[];
|
||||
}
|
||||
|
||||
export interface LogStorageSettingsUpdateResult {
|
||||
settings: LogStorageSettingsState;
|
||||
status: PublicLogStorageStatus;
|
||||
settings: LogStorageSettingsState;
|
||||
status: PublicLogStorageStatus;
|
||||
}
|
||||
|
||||
export class StorageSettingsInputError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'StorageSettingsInputError';
|
||||
}
|
||||
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';
|
||||
}
|
||||
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';
|
||||
}
|
||||
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>;
|
||||
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_FIELDS: LogStorageSettingsField[] = ['logMaxTotalMb', 'logRetainDays', 'logPerUin'];
|
||||
const SETTINGS_FIELD_SET = new Set<string>(SETTINGS_FIELDS);
|
||||
|
||||
export class LogStorageSettingsManager {
|
||||
private updateQueue: Promise<void> = Promise.resolve();
|
||||
private updateQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
constructor(private readonly deps: LogStorageSettingsDependencies) {}
|
||||
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,
|
||||
);
|
||||
read(): LogStorageSettingsState {
|
||||
return settingsState(
|
||||
this.deps.readPersisted(),
|
||||
this.deps.readEnvOverrides(),
|
||||
settingsFromStatus(this.deps.readEffective()),
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
update(body: unknown): Promise<LogStorageSettingsUpdateResult> {
|
||||
const operation = this.updateQueue.then(() => this.performUpdate(body));
|
||||
this.updateQueue = operation.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return operation;
|
||||
}
|
||||
|
||||
return {
|
||||
settings: settingsState(
|
||||
persistedRuntime,
|
||||
envOverrides,
|
||||
settingsFromStatus(status),
|
||||
),
|
||||
status: publicLogStorageStatus(status),
|
||||
};
|
||||
}
|
||||
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);
|
||||
|
||||
private async rollbackRuntime(policy: LogStoragePolicy): Promise<unknown[]> {
|
||||
try {
|
||||
const status = await this.deps.apply(policy);
|
||||
assertApplied(status, policy);
|
||||
return [];
|
||||
} catch (error) {
|
||||
return [error];
|
||||
}
|
||||
}
|
||||
if (locked.length > 0) {
|
||||
throw new StorageSettingsLockedError(locked);
|
||||
}
|
||||
|
||||
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);
|
||||
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;
|
||||
}
|
||||
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(', ')}`);
|
||||
}
|
||||
if (!isObject(body)) {
|
||||
throw new StorageSettingsInputError('body must be an object');
|
||||
}
|
||||
|
||||
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}`,
|
||||
);
|
||||
const keys = Object.keys(body);
|
||||
|
||||
if (keys.length === 0) {
|
||||
throw new StorageSettingsInputError('at least one setting is required');
|
||||
}
|
||||
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}`,
|
||||
);
|
||||
|
||||
const unknown = keys.filter((key) => !SETTINGS_FIELD_SET.has(key));
|
||||
|
||||
if (unknown.length > 0) {
|
||||
throw new StorageSettingsInputError(`unknown setting: ${unknown.join(', ')}`);
|
||||
}
|
||||
patch.logRetainDays = value;
|
||||
}
|
||||
if ('logPerUin' in body) {
|
||||
if (typeof body.logPerUin !== 'boolean') {
|
||||
throw new StorageSettingsInputError('logPerUin must be a boolean');
|
||||
|
||||
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;
|
||||
}
|
||||
patch.logPerUin = body.logPerUin;
|
||||
}
|
||||
return patch;
|
||||
|
||||
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,
|
||||
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 };
|
||||
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,
|
||||
};
|
||||
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,
|
||||
};
|
||||
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;
|
||||
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,
|
||||
};
|
||||
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');
|
||||
}
|
||||
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 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);
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -6,70 +6,82 @@
|
||||
import type { RuntimeConfig } from '@snowluma/common/runtime';
|
||||
import { checkListenerExposure } from './listener-exposure';
|
||||
|
||||
export type SettingsPatch = Partial<Pick<RuntimeConfig, 'webuiPort' | 'webuiHost' | 'webuiTls' | 'trustProxy'>>;
|
||||
export type SettingsPatch = Partial<
|
||||
Pick<RuntimeConfig, 'webuiPort' | 'webuiHost' | 'webuiTls' | 'trustProxy'>
|
||||
>;
|
||||
|
||||
export type CoerceResult =
|
||||
| { ok: true; patch: SettingsPatch }
|
||||
| { ok: false; error: string };
|
||||
export type CoerceResult = { ok: true; patch: SettingsPatch } | { ok: false; error: string };
|
||||
|
||||
function isObject(v: unknown): v is Record<string, unknown> {
|
||||
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
||||
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
||||
}
|
||||
|
||||
export function coerceSettingsPatch(body: unknown): CoerceResult {
|
||||
if (!isObject(body)) return { ok: false, error: 'body must be an object' };
|
||||
const patch: SettingsPatch = {};
|
||||
|
||||
if ('webuiPort' in body) {
|
||||
const p = body.webuiPort;
|
||||
if (typeof p !== 'number' || !Number.isInteger(p) || p <= 0 || p > 65535) {
|
||||
return { ok: false, error: 'webuiPort must be an integer in 1..65535' };
|
||||
if (!isObject(body)) {
|
||||
return { ok: false, error: 'body must be an object' };
|
||||
}
|
||||
patch.webuiPort = p;
|
||||
}
|
||||
|
||||
if ('webuiHost' in body) {
|
||||
if (typeof body.webuiHost !== 'string' || !body.webuiHost.trim()) {
|
||||
return { ok: false, error: 'webuiHost must be a non-empty string' };
|
||||
const patch: SettingsPatch = {};
|
||||
|
||||
if ('webuiPort' in body) {
|
||||
const p = body.webuiPort;
|
||||
|
||||
if (typeof p !== 'number' || !Number.isInteger(p) || p <= 0 || p > 65535) {
|
||||
return { ok: false, error: 'webuiPort must be an integer in 1..65535' };
|
||||
}
|
||||
|
||||
patch.webuiPort = p;
|
||||
}
|
||||
patch.webuiHost = body.webuiHost.trim();
|
||||
}
|
||||
|
||||
if ('tlsEnabled' in body) {
|
||||
if (typeof body.tlsEnabled !== 'boolean') {
|
||||
return { ok: false, error: 'tlsEnabled must be a boolean' };
|
||||
if ('webuiHost' in body) {
|
||||
if (typeof body.webuiHost !== 'string' || !body.webuiHost.trim()) {
|
||||
return { ok: false, error: 'webuiHost must be a non-empty string' };
|
||||
}
|
||||
|
||||
patch.webuiHost = body.webuiHost.trim();
|
||||
}
|
||||
patch.webuiTls = { enabled: body.tlsEnabled };
|
||||
}
|
||||
|
||||
if ('trustProxy' in body) {
|
||||
if (typeof body.trustProxy !== 'string') {
|
||||
return { ok: false, error: 'trustProxy must be a string' };
|
||||
if ('tlsEnabled' in body) {
|
||||
if (typeof body.tlsEnabled !== 'boolean') {
|
||||
return { ok: false, error: 'tlsEnabled must be a boolean' };
|
||||
}
|
||||
|
||||
patch.webuiTls = { enabled: body.tlsEnabled };
|
||||
}
|
||||
patch.trustProxy = body.trustProxy;
|
||||
}
|
||||
|
||||
return { ok: true, patch };
|
||||
if ('trustProxy' in body) {
|
||||
if (typeof body.trustProxy !== 'string') {
|
||||
return { ok: false, error: 'trustProxy must be a string' };
|
||||
}
|
||||
|
||||
patch.trustProxy = body.trustProxy;
|
||||
}
|
||||
|
||||
return { ok: true, patch };
|
||||
}
|
||||
|
||||
const SETTINGS_ERRORS: Record<'invalid-bind-host' | 'tls-pair-required', string> = {
|
||||
'invalid-bind-host': '绑定地址不是有效的 TCP 地址',
|
||||
'tls-pair-required': '启用 TLS 前请先上传有效的证书与私钥',
|
||||
'invalid-bind-host': '绑定地址不是有效的 TCP 地址',
|
||||
'tls-pair-required': '启用 TLS 前请先上传有效的证书与私钥',
|
||||
};
|
||||
|
||||
/** Validate the listener that would be persisted after applying `patch` to `current`. */
|
||||
export function evaluateSettingsSave(
|
||||
current: RuntimeConfig,
|
||||
patch: SettingsPatch,
|
||||
pairOk: boolean,
|
||||
current: RuntimeConfig,
|
||||
patch: SettingsPatch,
|
||||
pairOk: boolean,
|
||||
): CoerceResult {
|
||||
const webuiHost = patch.webuiHost ?? current.webuiHost ?? '127.0.0.1';
|
||||
const tlsEnabled = patch.webuiTls?.enabled ?? current.webuiTls?.enabled ?? false;
|
||||
const check = checkListenerExposure({ webuiHost, tlsEnabled, pairOk });
|
||||
if (!check.ok) return { ok: false, error: SETTINGS_ERRORS[check.code] };
|
||||
return { ok: true, patch };
|
||||
const webuiHost = patch.webuiHost ?? current.webuiHost ?? '127.0.0.1';
|
||||
const tlsEnabled = patch.webuiTls?.enabled ?? current.webuiTls?.enabled ?? false;
|
||||
const check = checkListenerExposure({ webuiHost, tlsEnabled, pairOk });
|
||||
|
||||
if (!check.ok) {
|
||||
return { ok: false, error: SETTINGS_ERRORS[check.code] };
|
||||
}
|
||||
|
||||
return { ok: true, patch };
|
||||
}
|
||||
|
||||
export function tlsCertDeletionBlocked(tlsEnabled: boolean): boolean {
|
||||
return tlsEnabled;
|
||||
return tlsEnabled;
|
||||
}
|
||||
@@ -9,63 +9,81 @@ import path from 'path';
|
||||
import tls from 'tls';
|
||||
|
||||
export interface TlsValidation {
|
||||
ok: boolean;
|
||||
reason?: string;
|
||||
ok: boolean;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface TlsResolution {
|
||||
ok: boolean;
|
||||
cert?: Buffer;
|
||||
key?: Buffer;
|
||||
reason?: string;
|
||||
ok: boolean;
|
||||
cert?: Buffer;
|
||||
key?: Buffer;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface RequiredTlsContext {
|
||||
cert: Buffer;
|
||||
key: Buffer;
|
||||
cert: Buffer;
|
||||
key: Buffer;
|
||||
}
|
||||
|
||||
function errMsg(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
/** Parse-validate a cert/key pair (used by the save endpoint before writing). */
|
||||
export function validateTlsPair(cert: string | Buffer, key: string | Buffer): TlsValidation {
|
||||
if (!cert || !cert.toString().trim()) return { ok: false, reason: 'certificate is empty' };
|
||||
if (!key || !key.toString().trim()) return { ok: false, reason: 'private key is empty' };
|
||||
try {
|
||||
tls.createSecureContext({ cert, key });
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, reason: `invalid cert/key: ${errMsg(e)}` };
|
||||
}
|
||||
if (!cert || !cert.toString().trim()) {
|
||||
return { ok: false, reason: 'certificate is empty' };
|
||||
}
|
||||
|
||||
if (!key || !key.toString().trim()) {
|
||||
return { ok: false, reason: 'private key is empty' };
|
||||
}
|
||||
|
||||
try {
|
||||
tls.createSecureContext({ cert, key });
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, reason: `invalid cert/key: ${errMsg(e)}` };
|
||||
}
|
||||
}
|
||||
|
||||
/** Load + validate config/cert.pem + config/key.pem from `configDir`. */
|
||||
export function resolveTlsContext(configDir: string): TlsResolution {
|
||||
const certPath = path.join(configDir, 'cert.pem');
|
||||
const keyPath = path.join(configDir, 'key.pem');
|
||||
if (!fs.existsSync(certPath) || !fs.existsSync(keyPath)) {
|
||||
return { ok: false, reason: 'cert.pem or key.pem missing in config dir' };
|
||||
}
|
||||
let cert: Buffer;
|
||||
let key: Buffer;
|
||||
try {
|
||||
cert = fs.readFileSync(certPath);
|
||||
key = fs.readFileSync(keyPath);
|
||||
} catch (e) {
|
||||
return { ok: false, reason: `failed to read cert/key: ${errMsg(e)}` };
|
||||
}
|
||||
const valid = validateTlsPair(cert, key);
|
||||
if (!valid.ok) return { ok: false, reason: valid.reason };
|
||||
return { ok: true, cert, key };
|
||||
const certPath = path.join(configDir, 'cert.pem');
|
||||
const keyPath = path.join(configDir, 'key.pem');
|
||||
|
||||
if (!fs.existsSync(certPath) || !fs.existsSync(keyPath)) {
|
||||
return { ok: false, reason: 'cert.pem or key.pem missing in config dir' };
|
||||
}
|
||||
|
||||
let cert: Buffer;
|
||||
let key: Buffer;
|
||||
|
||||
try {
|
||||
cert = fs.readFileSync(certPath);
|
||||
key = fs.readFileSync(keyPath);
|
||||
} catch (e) {
|
||||
return { ok: false, reason: `failed to read cert/key: ${errMsg(e)}` };
|
||||
}
|
||||
|
||||
const valid = validateTlsPair(cert, key);
|
||||
|
||||
if (!valid.ok) {
|
||||
return { ok: false, reason: valid.reason };
|
||||
}
|
||||
|
||||
return { ok: true, cert, key };
|
||||
}
|
||||
|
||||
/** Resolve the configured pair for an enabled listener or abort startup. */
|
||||
export function requireTlsContext(configDir: string): RequiredTlsContext {
|
||||
const resolved = resolveTlsContext(configDir);
|
||||
if (!resolved.ok || !resolved.cert || !resolved.key) {
|
||||
throw new Error(`TLS listener cannot start: ${resolved.reason ?? 'certificate pair is unusable'}`);
|
||||
}
|
||||
return { cert: resolved.cert, key: resolved.key };
|
||||
const resolved = resolveTlsContext(configDir);
|
||||
|
||||
if (!resolved.ok || !resolved.cert || !resolved.key) {
|
||||
throw new Error(
|
||||
`TLS listener cannot start: ${resolved.reason ?? 'certificate pair is unusable'}`,
|
||||
);
|
||||
}
|
||||
|
||||
return { cert: resolved.cert, key: resolved.key };
|
||||
}
|
||||
+355
-241
@@ -1,4 +1,11 @@
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
|
||||
import {
|
||||
createCipheriv,
|
||||
createDecipheriv,
|
||||
createHash,
|
||||
randomBytes,
|
||||
scryptSync,
|
||||
timingSafeEqual,
|
||||
} from 'node:crypto';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
|
||||
const TOTP_PERIOD_SECONDS = 30;
|
||||
@@ -14,324 +21,431 @@ const SCRYPT_R = 8;
|
||||
const SCRYPT_P = 1;
|
||||
|
||||
export interface WrappedTotpSecret {
|
||||
wrapSalt: string;
|
||||
iv: string;
|
||||
ciphertext: string;
|
||||
authTag: string;
|
||||
wrapSalt: string;
|
||||
iv: string;
|
||||
ciphertext: string;
|
||||
authTag: string;
|
||||
}
|
||||
|
||||
export interface TotpPersistedState extends WrappedTotpSecret {
|
||||
recoveryCodeHashes: string[];
|
||||
lastUsedStep: number;
|
||||
label: string;
|
||||
recoveryCodeHashes: string[];
|
||||
lastUsedStep: number;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface TotpEnrollment {
|
||||
secret: string;
|
||||
otpauthUrl: string;
|
||||
issuer: string;
|
||||
accountName: string;
|
||||
secret: string;
|
||||
otpauthUrl: string;
|
||||
issuer: string;
|
||||
accountName: string;
|
||||
}
|
||||
|
||||
function totpFromSecret(secretBase32: string, issuer = '', accountName = 'admin'): OTPAuth.TOTP {
|
||||
return new OTPAuth.TOTP({
|
||||
issuer,
|
||||
label: accountName,
|
||||
algorithm: 'SHA1',
|
||||
digits: TOTP_DIGITS,
|
||||
period: TOTP_PERIOD_SECONDS,
|
||||
secret: OTPAuth.Secret.fromBase32(secretBase32),
|
||||
});
|
||||
return new OTPAuth.TOTP({
|
||||
issuer,
|
||||
label: accountName,
|
||||
algorithm: 'SHA1',
|
||||
digits: TOTP_DIGITS,
|
||||
period: TOTP_PERIOD_SECONDS,
|
||||
secret: OTPAuth.Secret.fromBase32(secretBase32),
|
||||
});
|
||||
}
|
||||
|
||||
export function verifyTotpCode(
|
||||
secretBase32: string,
|
||||
code: string,
|
||||
atMs: number,
|
||||
lastUsedStep?: number,
|
||||
secretBase32: string,
|
||||
code: string,
|
||||
atMs: number,
|
||||
lastUsedStep?: number,
|
||||
): { ok: true; step: number } | { ok: false } {
|
||||
const token = code.replace(/\s/g, '');
|
||||
if (!/^\d{6}$/.test(token)) return { ok: false };
|
||||
const token = code.replace(/\s/g, '');
|
||||
|
||||
let totp: OTPAuth.TOTP;
|
||||
try {
|
||||
totp = totpFromSecret(secretBase32);
|
||||
} catch {
|
||||
return { ok: false };
|
||||
}
|
||||
const delta = totp.validate({ token, timestamp: atMs, window: TOTP_WINDOW });
|
||||
if (delta === null) return { ok: false };
|
||||
if (!/^\d{6}$/.test(token)) {
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
const step = totp.counter({ timestamp: atMs }) + delta;
|
||||
if (lastUsedStep !== undefined && step === lastUsedStep) return { ok: false };
|
||||
return { ok: true, step };
|
||||
let totp: OTPAuth.TOTP;
|
||||
|
||||
try {
|
||||
totp = totpFromSecret(secretBase32);
|
||||
} catch {
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
const delta = totp.validate({ token, timestamp: atMs, window: TOTP_WINDOW });
|
||||
|
||||
if (delta === null) {
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
const step = totp.counter({ timestamp: atMs }) + delta;
|
||||
|
||||
if (lastUsedStep !== undefined && step === lastUsedStep) {
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
return { ok: true, step };
|
||||
}
|
||||
|
||||
function deriveWrapKey(password: string, salt: Buffer): Buffer {
|
||||
return scryptSync(password, salt, WRAP_KEY_BYTES, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
|
||||
return scryptSync(password, salt, WRAP_KEY_BYTES, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
|
||||
}
|
||||
|
||||
export function wrapTotpSecret(password: string, secret: string): WrappedTotpSecret {
|
||||
const wrapSalt = randomBytes(WRAP_SALT_BYTES);
|
||||
const iv = randomBytes(WRAP_IV_BYTES);
|
||||
const key = deriveWrapKey(password, wrapSalt);
|
||||
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
||||
const ciphertext = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);
|
||||
return {
|
||||
wrapSalt: wrapSalt.toString('hex'),
|
||||
iv: iv.toString('hex'),
|
||||
ciphertext: ciphertext.toString('hex'),
|
||||
authTag: cipher.getAuthTag().toString('hex'),
|
||||
};
|
||||
const wrapSalt = randomBytes(WRAP_SALT_BYTES);
|
||||
const iv = randomBytes(WRAP_IV_BYTES);
|
||||
const key = deriveWrapKey(password, wrapSalt);
|
||||
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
||||
const ciphertext = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);
|
||||
return {
|
||||
wrapSalt: wrapSalt.toString('hex'),
|
||||
iv: iv.toString('hex'),
|
||||
ciphertext: ciphertext.toString('hex'),
|
||||
authTag: cipher.getAuthTag().toString('hex'),
|
||||
};
|
||||
}
|
||||
|
||||
export function unwrapTotpSecret(password: string, wrapped: WrappedTotpSecret): string | null {
|
||||
try {
|
||||
const wrapSalt = Buffer.from(wrapped.wrapSalt, 'hex');
|
||||
const iv = Buffer.from(wrapped.iv, 'hex');
|
||||
const ciphertext = Buffer.from(wrapped.ciphertext, 'hex');
|
||||
const authTag = Buffer.from(wrapped.authTag, 'hex');
|
||||
if (wrapSalt.length !== WRAP_SALT_BYTES || iv.length !== WRAP_IV_BYTES || authTag.length !== 16) {
|
||||
return null;
|
||||
try {
|
||||
const wrapSalt = Buffer.from(wrapped.wrapSalt, 'hex');
|
||||
const iv = Buffer.from(wrapped.iv, 'hex');
|
||||
const ciphertext = Buffer.from(wrapped.ciphertext, 'hex');
|
||||
const authTag = Buffer.from(wrapped.authTag, 'hex');
|
||||
|
||||
if (
|
||||
wrapSalt.length !== WRAP_SALT_BYTES ||
|
||||
iv.length !== WRAP_IV_BYTES ||
|
||||
authTag.length !== 16
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const key = deriveWrapKey(password, wrapSalt);
|
||||
const decipher = createDecipheriv('aes-256-gcm', key, iv);
|
||||
decipher.setAuthTag(authTag);
|
||||
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const key = deriveWrapKey(password, wrapSalt);
|
||||
const decipher = createDecipheriv('aes-256-gcm', key, iv);
|
||||
decipher.setAuthTag(authTag);
|
||||
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function randomRecoveryChunk(): string {
|
||||
const bytes = randomBytes(4);
|
||||
let chunk = '';
|
||||
for (let i = 0; i < 4; i++) {
|
||||
chunk += RECOVERY_ALPHABET[bytes[i]! % RECOVERY_ALPHABET.length];
|
||||
}
|
||||
return chunk;
|
||||
const bytes = randomBytes(4);
|
||||
let chunk = '';
|
||||
|
||||
for (let i = 0; i < 4; i++) {
|
||||
chunk += RECOVERY_ALPHABET[bytes[i]! % RECOVERY_ALPHABET.length];
|
||||
}
|
||||
|
||||
return chunk;
|
||||
}
|
||||
|
||||
export function generateRecoveryCodes(): string[] {
|
||||
const codes = new Set<string>();
|
||||
while (codes.size < RECOVERY_CODE_COUNT) {
|
||||
codes.add(`${randomRecoveryChunk()}-${randomRecoveryChunk()}`);
|
||||
}
|
||||
return [...codes];
|
||||
const codes = new Set<string>();
|
||||
|
||||
while (codes.size < RECOVERY_CODE_COUNT) {
|
||||
codes.add(`${randomRecoveryChunk()}-${randomRecoveryChunk()}`);
|
||||
}
|
||||
|
||||
return [...codes];
|
||||
}
|
||||
|
||||
export function normalizeRecoveryCode(code: string): string {
|
||||
return code.replace(/[-\s]/g, '').toUpperCase();
|
||||
return code.replace(/[-\s]/g, '').toUpperCase();
|
||||
}
|
||||
|
||||
export function hashRecoveryCode(code: string): string {
|
||||
return createHash('sha256').update(normalizeRecoveryCode(code), 'utf8').digest('hex');
|
||||
return createHash('sha256').update(normalizeRecoveryCode(code), 'utf8').digest('hex');
|
||||
}
|
||||
|
||||
function hashesEqual(left: string, right: string): boolean {
|
||||
const a = Buffer.from(left, 'hex');
|
||||
const b = Buffer.from(right, 'hex');
|
||||
if (a.length !== b.length || a.length === 0) return false;
|
||||
return timingSafeEqual(a, b);
|
||||
const a = Buffer.from(left, 'hex');
|
||||
const b = Buffer.from(right, 'hex');
|
||||
|
||||
if (a.length !== b.length || a.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
export function consumeRecoveryCode(
|
||||
code: string,
|
||||
hashes: readonly string[],
|
||||
code: string,
|
||||
hashes: readonly string[],
|
||||
): { ok: true; remainingHashes: string[] } | { ok: false } {
|
||||
const candidate = hashRecoveryCode(code);
|
||||
const index = hashes.findIndex((hash) => hashesEqual(hash, candidate));
|
||||
if (index < 0) return { ok: false };
|
||||
return { ok: true, remainingHashes: hashes.filter((_, i) => i !== index) };
|
||||
const candidate = hashRecoveryCode(code);
|
||||
const index = hashes.findIndex((hash) => hashesEqual(hash, candidate));
|
||||
|
||||
if (index < 0) {
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
return { ok: true, remainingHashes: hashes.filter((_, i) => i !== index) };
|
||||
}
|
||||
|
||||
export function beginTotpEnrollment(options: {
|
||||
issuer: string;
|
||||
accountName: string;
|
||||
secret?: string;
|
||||
issuer: string;
|
||||
accountName: string;
|
||||
secret?: string;
|
||||
}): TotpEnrollment {
|
||||
const secret = options.secret ?? new OTPAuth.Secret({ size: 20 }).base32;
|
||||
const totp = totpFromSecret(secret, options.issuer, options.accountName);
|
||||
return {
|
||||
secret,
|
||||
otpauthUrl: totp.toString(),
|
||||
issuer: options.issuer,
|
||||
accountName: options.accountName,
|
||||
};
|
||||
const secret = options.secret ?? new OTPAuth.Secret({ size: 20 }).base32;
|
||||
const totp = totpFromSecret(secret, options.issuer, options.accountName);
|
||||
return {
|
||||
secret,
|
||||
otpauthUrl: totp.toString(),
|
||||
issuer: options.issuer,
|
||||
accountName: options.accountName,
|
||||
};
|
||||
}
|
||||
|
||||
export function confirmTotpEnrollment(options: {
|
||||
password: string;
|
||||
secret: string;
|
||||
code: string;
|
||||
label: string;
|
||||
atMs: number;
|
||||
password: string;
|
||||
secret: string;
|
||||
code: string;
|
||||
label: string;
|
||||
atMs: number;
|
||||
}): { state: TotpPersistedState; recoveryCodes: string[] } {
|
||||
const verified = verifyTotpCode(options.secret, options.code, options.atMs);
|
||||
if (!verified.ok) {
|
||||
throw new Error('验证码不正确');
|
||||
}
|
||||
const recoveryCodes = generateRecoveryCodes();
|
||||
return {
|
||||
recoveryCodes,
|
||||
state: {
|
||||
...wrapTotpSecret(options.password, options.secret),
|
||||
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
|
||||
lastUsedStep: verified.step,
|
||||
label: options.label,
|
||||
},
|
||||
};
|
||||
const verified = verifyTotpCode(options.secret, options.code, options.atMs);
|
||||
|
||||
if (!verified.ok) {
|
||||
throw new Error('验证码不正确');
|
||||
}
|
||||
|
||||
const recoveryCodes = generateRecoveryCodes();
|
||||
return {
|
||||
recoveryCodes,
|
||||
state: {
|
||||
...wrapTotpSecret(options.password, options.secret),
|
||||
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
|
||||
lastUsedStep: verified.step,
|
||||
label: options.label,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function verifySecondFactor(options: {
|
||||
password: string;
|
||||
state: TotpPersistedState;
|
||||
atMs: number;
|
||||
totp?: string;
|
||||
recoveryCode?: string;
|
||||
password: string;
|
||||
state: TotpPersistedState;
|
||||
atMs: number;
|
||||
totp?: string;
|
||||
recoveryCode?: string;
|
||||
}): { ok: true; state: TotpPersistedState } | { ok: false } {
|
||||
if (typeof options.recoveryCode === 'string' && options.recoveryCode.length > 0) {
|
||||
const consumed = consumeRecoveryCode(options.recoveryCode, options.state.recoveryCodeHashes);
|
||||
if (!consumed.ok) return { ok: false };
|
||||
return { ok: true, state: { ...options.state, recoveryCodeHashes: consumed.remainingHashes } };
|
||||
}
|
||||
if (typeof options.totp !== 'string') return { ok: false };
|
||||
const secret = unwrapTotpSecret(options.password, options.state);
|
||||
if (secret === null) return { ok: false };
|
||||
const checked = verifyTotpCode(secret, options.totp, options.atMs, options.state.lastUsedStep);
|
||||
if (!checked.ok) return { ok: false };
|
||||
return { ok: true, state: { ...options.state, lastUsedStep: checked.step } };
|
||||
if (typeof options.recoveryCode === 'string' && options.recoveryCode.length > 0) {
|
||||
const consumed = consumeRecoveryCode(
|
||||
options.recoveryCode,
|
||||
options.state.recoveryCodeHashes,
|
||||
);
|
||||
|
||||
if (!consumed.ok) {
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
state: { ...options.state, recoveryCodeHashes: consumed.remainingHashes },
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof options.totp !== 'string') {
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
const secret = unwrapTotpSecret(options.password, options.state);
|
||||
|
||||
if (secret === null) {
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
const checked = verifyTotpCode(secret, options.totp, options.atMs, options.state.lastUsedStep);
|
||||
|
||||
if (!checked.ok) {
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
return { ok: true, state: { ...options.state, lastUsedStep: checked.step } };
|
||||
}
|
||||
|
||||
export type SecondFactorDecision =
|
||||
| { kind: 'needs-totp' }
|
||||
| { kind: 'bad-second-factor' }
|
||||
| { kind: 'ok'; state?: TotpPersistedState };
|
||||
| { kind: 'needs-totp' }
|
||||
| { kind: 'bad-second-factor' }
|
||||
| { kind: 'ok'; state?: TotpPersistedState };
|
||||
|
||||
export function decideSecondFactorLogin(options: {
|
||||
totpEnabled: boolean;
|
||||
state?: TotpPersistedState;
|
||||
password: string;
|
||||
totp?: string;
|
||||
recoveryCode?: string;
|
||||
atMs: number;
|
||||
totpEnabled: boolean;
|
||||
state?: TotpPersistedState;
|
||||
password: string;
|
||||
totp?: string;
|
||||
recoveryCode?: string;
|
||||
atMs: number;
|
||||
}): SecondFactorDecision {
|
||||
if (!options.totpEnabled) return { kind: 'ok' };
|
||||
if (!options.state) return { kind: 'bad-second-factor' };
|
||||
const totp = typeof options.totp === 'string' && options.totp.trim().length > 0
|
||||
? options.totp.trim()
|
||||
: undefined;
|
||||
const recoveryCode = typeof options.recoveryCode === 'string' && options.recoveryCode.trim().length > 0
|
||||
? options.recoveryCode.trim()
|
||||
: undefined;
|
||||
if (!totp && !recoveryCode) return { kind: 'needs-totp' };
|
||||
const result = verifySecondFactor({
|
||||
password: options.password,
|
||||
state: options.state,
|
||||
atMs: options.atMs,
|
||||
totp,
|
||||
recoveryCode,
|
||||
});
|
||||
if (!result.ok) return { kind: 'bad-second-factor' };
|
||||
return { kind: 'ok', state: result.state };
|
||||
if (!options.totpEnabled) {
|
||||
return { kind: 'ok' };
|
||||
}
|
||||
|
||||
if (!options.state) {
|
||||
return { kind: 'bad-second-factor' };
|
||||
}
|
||||
|
||||
const totp =
|
||||
typeof options.totp === 'string' && options.totp.trim().length > 0
|
||||
? options.totp.trim()
|
||||
: undefined;
|
||||
const recoveryCode =
|
||||
typeof options.recoveryCode === 'string' && options.recoveryCode.trim().length > 0
|
||||
? options.recoveryCode.trim()
|
||||
: undefined;
|
||||
|
||||
if (!totp && !recoveryCode) {
|
||||
return { kind: 'needs-totp' };
|
||||
}
|
||||
|
||||
const result = verifySecondFactor({
|
||||
password: options.password,
|
||||
state: options.state,
|
||||
atMs: options.atMs,
|
||||
totp,
|
||||
recoveryCode,
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
return { kind: 'bad-second-factor' };
|
||||
}
|
||||
|
||||
return { kind: 'ok', state: result.state };
|
||||
}
|
||||
|
||||
export function regenerateRecoveryCodes(options: {
|
||||
password: string;
|
||||
state: TotpPersistedState;
|
||||
totp: string;
|
||||
atMs: number;
|
||||
password: string;
|
||||
state: TotpPersistedState;
|
||||
totp: string;
|
||||
atMs: number;
|
||||
}): { state: TotpPersistedState; recoveryCodes: string[] } {
|
||||
const verified = verifySecondFactor({
|
||||
password: options.password,
|
||||
state: options.state,
|
||||
totp: options.totp,
|
||||
atMs: options.atMs,
|
||||
});
|
||||
if (!verified.ok) {
|
||||
throw new Error('验证码不正确');
|
||||
}
|
||||
const recoveryCodes = generateRecoveryCodes();
|
||||
return {
|
||||
recoveryCodes,
|
||||
state: {
|
||||
...verified.state,
|
||||
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
|
||||
},
|
||||
};
|
||||
const verified = verifySecondFactor({
|
||||
password: options.password,
|
||||
state: options.state,
|
||||
totp: options.totp,
|
||||
atMs: options.atMs,
|
||||
});
|
||||
|
||||
if (!verified.ok) {
|
||||
throw new Error('验证码不正确');
|
||||
}
|
||||
|
||||
const recoveryCodes = generateRecoveryCodes();
|
||||
return {
|
||||
recoveryCodes,
|
||||
state: {
|
||||
...verified.state,
|
||||
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function rewrapTotpSecret(
|
||||
oldPassword: string,
|
||||
newPassword: string,
|
||||
state: TotpPersistedState,
|
||||
oldPassword: string,
|
||||
newPassword: string,
|
||||
state: TotpPersistedState,
|
||||
): TotpPersistedState {
|
||||
const secret = unwrapTotpSecret(oldPassword, state);
|
||||
if (secret === null) {
|
||||
throw new Error('无法使用当前密码解开 2FA 密钥');
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
...wrapTotpSecret(newPassword, secret),
|
||||
};
|
||||
const secret = unwrapTotpSecret(oldPassword, state);
|
||||
|
||||
if (secret === null) {
|
||||
throw new Error('无法使用当前密码解开 2FA 密钥');
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
...wrapTotpSecret(newPassword, secret),
|
||||
};
|
||||
}
|
||||
|
||||
const HEX = /^[0-9a-f]+$/i;
|
||||
|
||||
function isWrappedShape(value: Record<string, unknown>): value is WrappedTotpSecret & Record<string, unknown> {
|
||||
return typeof value.wrapSalt === 'string'
|
||||
&& HEX.test(value.wrapSalt)
|
||||
&& value.wrapSalt.length === WRAP_SALT_BYTES * 2
|
||||
&& typeof value.iv === 'string'
|
||||
&& HEX.test(value.iv)
|
||||
&& value.iv.length === WRAP_IV_BYTES * 2
|
||||
&& typeof value.ciphertext === 'string'
|
||||
&& HEX.test(value.ciphertext)
|
||||
&& value.ciphertext.length > 0
|
||||
&& value.ciphertext.length % 2 === 0
|
||||
&& typeof value.authTag === 'string'
|
||||
&& HEX.test(value.authTag)
|
||||
&& value.authTag.length === 32;
|
||||
function isWrappedShape(
|
||||
value: Record<string, unknown>,
|
||||
): value is WrappedTotpSecret & Record<string, unknown> {
|
||||
return (
|
||||
typeof value.wrapSalt === 'string' &&
|
||||
HEX.test(value.wrapSalt) &&
|
||||
value.wrapSalt.length === WRAP_SALT_BYTES * 2 &&
|
||||
typeof value.iv === 'string' &&
|
||||
HEX.test(value.iv) &&
|
||||
value.iv.length === WRAP_IV_BYTES * 2 &&
|
||||
typeof value.ciphertext === 'string' &&
|
||||
HEX.test(value.ciphertext) &&
|
||||
value.ciphertext.length > 0 &&
|
||||
value.ciphertext.length % 2 === 0 &&
|
||||
typeof value.authTag === 'string' &&
|
||||
HEX.test(value.authTag) &&
|
||||
value.authTag.length === 32
|
||||
);
|
||||
}
|
||||
|
||||
export function prepareTotpStateForRestore(value: unknown): TotpPersistedState {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error('totp state must be an object');
|
||||
}
|
||||
const v = value as Record<string, unknown>;
|
||||
if (!isWrappedShape(v)) {
|
||||
throw new Error('totp wrapped secret fields are invalid');
|
||||
}
|
||||
if (!Array.isArray(v.recoveryCodeHashes)
|
||||
|| v.recoveryCodeHashes.length > RECOVERY_CODE_COUNT
|
||||
|| v.recoveryCodeHashes.some((hash) => typeof hash !== 'string' || !/^[0-9a-f]{64}$/i.test(hash))) {
|
||||
throw new Error('totp recoveryCodeHashes must be SHA-256 hex strings');
|
||||
}
|
||||
if (typeof v.lastUsedStep !== 'number' || !Number.isInteger(v.lastUsedStep) || v.lastUsedStep < 0) {
|
||||
throw new Error('totp lastUsedStep must be a non-negative integer');
|
||||
}
|
||||
if (typeof v.label !== 'string' || v.label.length === 0 || v.label.length > 128) {
|
||||
throw new Error('totp label must be a non-empty string');
|
||||
}
|
||||
const allowed = new Set(['wrapSalt', 'iv', 'ciphertext', 'authTag', 'recoveryCodeHashes', 'lastUsedStep', 'label']);
|
||||
const unknown = Object.keys(v).find((key) => !allowed.has(key));
|
||||
if (unknown) throw new Error(`unknown totp field $.${unknown}`);
|
||||
return {
|
||||
wrapSalt: v.wrapSalt.toLowerCase(),
|
||||
iv: v.iv.toLowerCase(),
|
||||
ciphertext: v.ciphertext.toLowerCase(),
|
||||
authTag: v.authTag.toLowerCase(),
|
||||
recoveryCodeHashes: v.recoveryCodeHashes.map((hash) => (hash as string).toLowerCase()),
|
||||
lastUsedStep: v.lastUsedStep,
|
||||
label: v.label,
|
||||
};
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error('totp state must be an object');
|
||||
}
|
||||
|
||||
const v = value as Record<string, unknown>;
|
||||
|
||||
if (!isWrappedShape(v)) {
|
||||
throw new Error('totp wrapped secret fields are invalid');
|
||||
}
|
||||
|
||||
if (
|
||||
!Array.isArray(v.recoveryCodeHashes) ||
|
||||
v.recoveryCodeHashes.length > RECOVERY_CODE_COUNT ||
|
||||
v.recoveryCodeHashes.some(
|
||||
(hash) => typeof hash !== 'string' || !/^[0-9a-f]{64}$/i.test(hash),
|
||||
)
|
||||
) {
|
||||
throw new Error('totp recoveryCodeHashes must be SHA-256 hex strings');
|
||||
}
|
||||
|
||||
if (
|
||||
typeof v.lastUsedStep !== 'number' ||
|
||||
!Number.isInteger(v.lastUsedStep) ||
|
||||
v.lastUsedStep < 0
|
||||
) {
|
||||
throw new Error('totp lastUsedStep must be a non-negative integer');
|
||||
}
|
||||
|
||||
if (typeof v.label !== 'string' || v.label.length === 0 || v.label.length > 128) {
|
||||
throw new Error('totp label must be a non-empty string');
|
||||
}
|
||||
|
||||
const allowed = new Set([
|
||||
'wrapSalt',
|
||||
'iv',
|
||||
'ciphertext',
|
||||
'authTag',
|
||||
'recoveryCodeHashes',
|
||||
'lastUsedStep',
|
||||
'label',
|
||||
]);
|
||||
const unknown = Object.keys(v).find((key) => !allowed.has(key));
|
||||
|
||||
if (unknown) {
|
||||
throw new Error(`unknown totp field $.${unknown}`);
|
||||
}
|
||||
|
||||
return {
|
||||
wrapSalt: v.wrapSalt.toLowerCase(),
|
||||
iv: v.iv.toLowerCase(),
|
||||
ciphertext: v.ciphertext.toLowerCase(),
|
||||
authTag: v.authTag.toLowerCase(),
|
||||
recoveryCodeHashes: v.recoveryCodeHashes.map((hash) => (hash as string).toLowerCase()),
|
||||
lastUsedStep: v.lastUsedStep,
|
||||
label: v.label,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseTotpStateLenient(value: unknown): TotpPersistedState | undefined {
|
||||
if (value === undefined || value === null) return undefined;
|
||||
try {
|
||||
return prepareTotpStateForRestore(value);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (value === undefined || value === null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
return prepareTotpStateForRestore(value);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -21,38 +21,38 @@ const FETCH_TIMEOUT_MS = 8_000;
|
||||
const NOTES_MAX = 4_000; // cap the release-body we hand back to the client
|
||||
|
||||
export interface UpdateCheckResult {
|
||||
/** The running build's version (no `v` prefix). */
|
||||
current: string;
|
||||
/** Latest stable release version, or null when the check did not complete. */
|
||||
latest: string | null;
|
||||
/** True only when `latest` is strictly newer than `current`. */
|
||||
hasUpdate: boolean;
|
||||
/** GitHub release page URL for the latest release. */
|
||||
htmlUrl: string | null;
|
||||
/** Release notes (markdown), truncated to {@link NOTES_MAX}. */
|
||||
notes: string | null;
|
||||
/** ISO timestamp the latest release was published. */
|
||||
publishedAt: string | null;
|
||||
/** When this result was produced (epoch ms). */
|
||||
checkedAt: number;
|
||||
/** Set when the check was skipped or failed; the UI degrades silently. */
|
||||
error?: string;
|
||||
/** The running build's version (no `v` prefix). */
|
||||
current: string;
|
||||
/** Latest stable release version, or null when the check did not complete. */
|
||||
latest: string | null;
|
||||
/** True only when `latest` is strictly newer than `current`. */
|
||||
hasUpdate: boolean;
|
||||
/** GitHub release page URL for the latest release. */
|
||||
htmlUrl: string | null;
|
||||
/** Release notes (markdown), truncated to {@link NOTES_MAX}. */
|
||||
notes: string | null;
|
||||
/** ISO timestamp the latest release was published. */
|
||||
publishedAt: string | null;
|
||||
/** When this result was produced (epoch ms). */
|
||||
checkedAt: number;
|
||||
/** Set when the check was skipped or failed; the UI degrades silently. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface GithubRelease {
|
||||
tag_name?: string;
|
||||
html_url?: string;
|
||||
body?: string;
|
||||
published_at?: string;
|
||||
tag_name?: string;
|
||||
html_url?: string;
|
||||
body?: string;
|
||||
published_at?: string;
|
||||
}
|
||||
|
||||
export function currentVersion(): string {
|
||||
return typeof __APP_VERSION__ === 'string' && __APP_VERSION__ ? __APP_VERSION__ : '0.0.0';
|
||||
return typeof __APP_VERSION__ === 'string' && __APP_VERSION__ ? __APP_VERSION__ : '0.0.0';
|
||||
}
|
||||
|
||||
function isEnabled(): boolean {
|
||||
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
|
||||
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
|
||||
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
|
||||
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,78 +63,107 @@ function isEnabled(): boolean {
|
||||
* pulling in a `semver` runtime dependency (the dist bundle ships none).
|
||||
*/
|
||||
export function compareVersions(a: string, b: string): number {
|
||||
const parse = (v: string) => {
|
||||
const [core = '', pre = ''] = v.replace(/^v/, '').split('-', 2);
|
||||
const nums = core.split('.').map((n) => parseInt(n, 10) || 0);
|
||||
while (nums.length < 3) nums.push(0);
|
||||
return { nums, pre };
|
||||
};
|
||||
const pa = parse(a);
|
||||
const pb = parse(b);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (pa.nums[i] !== pb.nums[i]) return pa.nums[i] - pb.nums[i];
|
||||
}
|
||||
if (pa.pre === pb.pre) return 0;
|
||||
if (!pa.pre) return 1; // release > prerelease
|
||||
if (!pb.pre) return -1;
|
||||
return pa.pre < pb.pre ? -1 : 1;
|
||||
const parse = (v: string) => {
|
||||
const [core = '', pre = ''] = v.replace(/^v/, '').split('-', 2);
|
||||
const nums = core.split('.').map((n) => parseInt(n, 10) || 0);
|
||||
|
||||
while (nums.length < 3) {
|
||||
nums.push(0);
|
||||
}
|
||||
|
||||
return { nums, pre };
|
||||
};
|
||||
|
||||
const pa = parse(a);
|
||||
const pb = parse(b);
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (pa.nums[i] !== pb.nums[i]) {
|
||||
return pa.nums[i] - pb.nums[i];
|
||||
}
|
||||
}
|
||||
|
||||
if (pa.pre === pb.pre) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!pa.pre) {
|
||||
return 1;
|
||||
} // release > prerelease
|
||||
|
||||
if (!pb.pre) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return pa.pre < pb.pre ? -1 : 1;
|
||||
}
|
||||
|
||||
// TTL + single-flight: cache good results for CACHE_TTL_MS (well under GitHub's
|
||||
// 60 req/hr limit) and collapse concurrent checks onto one fetch. Error results
|
||||
// are intentionally not cached (shouldCache) so the next check retries.
|
||||
const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
|
||||
ttlMs: CACHE_TTL_MS,
|
||||
shouldCache: (r) => !r.error,
|
||||
load: async (current) => {
|
||||
const result = await fetchLatest(current);
|
||||
if (result.error) {
|
||||
log.debug('update check failed: %s', result.error);
|
||||
} else if (result.hasUpdate) {
|
||||
log.info('a newer release is available: v%s (running v%s)', result.latest, current);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
ttlMs: CACHE_TTL_MS,
|
||||
shouldCache: (r) => !r.error,
|
||||
load: async (current) => {
|
||||
const result = await fetchLatest(current);
|
||||
|
||||
if (result.error) {
|
||||
log.debug('update check failed: %s', result.error);
|
||||
} else if (result.hasUpdate) {
|
||||
log.info('a newer release is available: v%s (running v%s)', result.latest, current);
|
||||
}
|
||||
|
||||
return result;
|
||||
},
|
||||
});
|
||||
|
||||
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
const base: UpdateCheckResult = {
|
||||
current,
|
||||
latest: null,
|
||||
hasUpdate: false,
|
||||
htmlUrl: null,
|
||||
notes: null,
|
||||
publishedAt: null,
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
try {
|
||||
// `/releases/latest` already excludes drafts and prereleases, so this is
|
||||
// stable-channel by construction.
|
||||
const res = await fetch(LATEST_RELEASE_URL, {
|
||||
headers: {
|
||||
Accept: 'application/vnd.github+json',
|
||||
'User-Agent': `SnowLuma/${current}`,
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
},
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (!res.ok) return { ...base, error: `github ${res.status}` };
|
||||
const rel = (await res.json()) as GithubRelease;
|
||||
const tag = (rel.tag_name ?? '').trim();
|
||||
if (!tag) return { ...base, error: 'no tag' };
|
||||
const latest = tag.replace(/^v/, '');
|
||||
return {
|
||||
current,
|
||||
latest,
|
||||
hasUpdate: compareVersions(latest, current) > 0,
|
||||
htmlUrl: rel.html_url ?? null,
|
||||
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
|
||||
publishedAt: rel.published_at ?? null,
|
||||
checkedAt: Date.now(),
|
||||
const base: UpdateCheckResult = {
|
||||
current,
|
||||
latest: null,
|
||||
hasUpdate: false,
|
||||
htmlUrl: null,
|
||||
notes: null,
|
||||
publishedAt: null,
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
} catch (e) {
|
||||
return { ...base, error: e instanceof Error ? e.message : 'network error' };
|
||||
}
|
||||
|
||||
try {
|
||||
// `/releases/latest` already excludes drafts and prereleases, so this is
|
||||
// stable-channel by construction.
|
||||
const res = await fetch(LATEST_RELEASE_URL, {
|
||||
headers: {
|
||||
Accept: 'application/vnd.github+json',
|
||||
'User-Agent': `SnowLuma/${current}`,
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
},
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
return { ...base, error: `github ${res.status}` };
|
||||
}
|
||||
|
||||
const rel = (await res.json()) as GithubRelease;
|
||||
const tag = (rel.tag_name ?? '').trim();
|
||||
|
||||
if (!tag) {
|
||||
return { ...base, error: 'no tag' };
|
||||
}
|
||||
|
||||
const latest = tag.replace(/^v/, '');
|
||||
return {
|
||||
current,
|
||||
latest,
|
||||
hasUpdate: compareVersions(latest, current) > 0,
|
||||
htmlUrl: rel.html_url ?? null,
|
||||
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
|
||||
publishedAt: rel.published_at ?? null,
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
} catch (e) {
|
||||
return { ...base, error: e instanceof Error ? e.message : 'network error' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -144,21 +173,23 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
|
||||
* are not cached so the next check retries.
|
||||
*/
|
||||
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
|
||||
const current = currentVersion();
|
||||
if (!isEnabled()) {
|
||||
return { ...emptyResult(current), error: 'disabled' };
|
||||
}
|
||||
return updateCache.get(current, { force });
|
||||
const current = currentVersion();
|
||||
|
||||
if (!isEnabled()) {
|
||||
return { ...emptyResult(current), error: 'disabled' };
|
||||
}
|
||||
|
||||
return updateCache.get(current, { force });
|
||||
}
|
||||
|
||||
function emptyResult(current: string): UpdateCheckResult {
|
||||
return {
|
||||
current,
|
||||
latest: null,
|
||||
hasUpdate: false,
|
||||
htmlUrl: null,
|
||||
notes: null,
|
||||
publishedAt: null,
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
return {
|
||||
current,
|
||||
latest: null,
|
||||
hasUpdate: false,
|
||||
htmlUrl: null,
|
||||
notes: null,
|
||||
publishedAt: null,
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
@@ -1,51 +1,67 @@
|
||||
import { decideSecondFactorLogin, type TotpPersistedState } from './totp';
|
||||
|
||||
export interface WebuiLoginAuth {
|
||||
verify(password: string): boolean;
|
||||
totpEnabled(): boolean;
|
||||
totpState(): TotpPersistedState | undefined;
|
||||
mustChangePassword(): boolean;
|
||||
verify(password: string): boolean;
|
||||
totpEnabled(): boolean;
|
||||
totpState(): TotpPersistedState | undefined;
|
||||
mustChangePassword(): boolean;
|
||||
}
|
||||
|
||||
export type WebuiLoginResult =
|
||||
| { kind: 'bad-request' }
|
||||
| { kind: 'bad-password' }
|
||||
| { kind: 'needs-totp' }
|
||||
| { kind: 'bad-second-factor' }
|
||||
| { kind: 'ok'; mustChangePassword: boolean; totpState?: TotpPersistedState };
|
||||
| { kind: 'bad-request' }
|
||||
| { kind: 'bad-password' }
|
||||
| { kind: 'needs-totp' }
|
||||
| { kind: 'bad-second-factor' }
|
||||
| { kind: 'ok'; mustChangePassword: boolean; totpState?: TotpPersistedState };
|
||||
|
||||
function readString(value: unknown): string {
|
||||
return typeof value === 'string' ? value : '';
|
||||
return typeof value === 'string' ? value : '';
|
||||
}
|
||||
|
||||
export function completeWebuiLogin(auth: WebuiLoginAuth, body: unknown, atMs: number): WebuiLoginResult {
|
||||
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
||||
return { kind: 'bad-request' };
|
||||
}
|
||||
const record = body as Record<string, unknown>;
|
||||
const password = readString(record.password);
|
||||
if (!auth.verify(password)) {
|
||||
return { kind: 'bad-password' };
|
||||
}
|
||||
const decision = decideSecondFactorLogin({
|
||||
totpEnabled: auth.totpEnabled(),
|
||||
state: auth.totpState(),
|
||||
password,
|
||||
totp: readString(record.totp) || undefined,
|
||||
recoveryCode: readString(record.recoveryCode) || undefined,
|
||||
atMs,
|
||||
});
|
||||
if (decision.kind === 'needs-totp') return { kind: 'needs-totp' };
|
||||
if (decision.kind === 'bad-second-factor') return { kind: 'bad-second-factor' };
|
||||
return {
|
||||
kind: 'ok',
|
||||
mustChangePassword: auth.mustChangePassword(),
|
||||
...(decision.state ? { totpState: decision.state } : {}),
|
||||
};
|
||||
export function completeWebuiLogin(
|
||||
auth: WebuiLoginAuth,
|
||||
body: unknown,
|
||||
atMs: number,
|
||||
): WebuiLoginResult {
|
||||
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
||||
return { kind: 'bad-request' };
|
||||
}
|
||||
|
||||
const record = body as Record<string, unknown>;
|
||||
const password = readString(record.password);
|
||||
|
||||
if (!auth.verify(password)) {
|
||||
return { kind: 'bad-password' };
|
||||
}
|
||||
|
||||
const decision = decideSecondFactorLogin({
|
||||
totpEnabled: auth.totpEnabled(),
|
||||
state: auth.totpState(),
|
||||
password,
|
||||
totp: readString(record.totp) || undefined,
|
||||
recoveryCode: readString(record.recoveryCode) || undefined,
|
||||
atMs,
|
||||
});
|
||||
|
||||
if (decision.kind === 'needs-totp') {
|
||||
return { kind: 'needs-totp' };
|
||||
}
|
||||
|
||||
if (decision.kind === 'bad-second-factor') {
|
||||
return { kind: 'bad-second-factor' };
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'ok',
|
||||
mustChangePassword: auth.mustChangePassword(),
|
||||
...(decision.state ? { totpState: decision.state } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function invalidateOtherSessions<T>(sessions: Map<string, T>, keepToken: string): void {
|
||||
for (const token of sessions.keys()) {
|
||||
if (token !== keepToken) sessions.delete(token);
|
||||
}
|
||||
for (const token of sessions.keys()) {
|
||||
if (token !== keepToken) {
|
||||
sessions.delete(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user