fix(webui): tighten auth handling and remove read-side write effects
Stack of WebUI fixes prompted by an internal security/correctness pass:
* getClientIp now resolves the real socket peer via @hono/node-server's
getConnInfo helper instead of trusting `X-Forwarded-For`. The previous
behaviour let any client rotate that header to bypass the 5-attempts/
15-minute login lockout.
* `?token=` is restricted to /api/logs/stream (the only endpoint that
can't use the Authorization header, because EventSource lacks custom
headers). Other routes used to leak tokens via access logs / Referer
/ browser history.
* change-password now invalidates every session (including the current
one) and signals requireRelogin. Keeping the current token alive made
the rotation pointless if the old credentials were already in an
attacker's hands.
* GET /api/config/:uin no longer writes defaults to disk and no longer
doubles up the payload (`{config}` only, dropping the {…config, config}
legacy shape). Frontend's `data?.config ?? data` fallback still works.
* webui.json is moved to .bak.<ts> instead of being silently overwritten
when it fails to parse — losing the prior hash silently was rotating
operator credentials with no warning.
* Process load/unload/refresh routes are deduped into a single helper;
internal error messages are logged but no longer surfaced verbatim to
the client.
* SSE log stream tolerates a closed controller (try/catch around enqueue
+ central teardown) and runs an unref'd janitor to GC expired session
tokens + login attempt counters every minute.
This commit is contained in:
1 parent
2c80e1a267
commit
917f08ce4d
2 files changed
+118
-84
No files matched your search
@@ -1,6 +1,9 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
const log = createLogger('WebUI.Auth');
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const WEBUI_CONFIG_PATH = path.join(CONFIG_DIR, 'webui.json');
|
||||
@@ -84,6 +87,16 @@ function generateInitialState(initialPassword: string): WebuiAuthState {
|
||||
};
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
function atomicWrite(state: WebuiAuthState): void {
|
||||
ensureConfigDir();
|
||||
const tmp = WEBUI_CONFIG_PATH + '.tmp';
|
||||
@@ -130,8 +143,14 @@ export class WebuiAuth {
|
||||
if (isValidState(parsed)) {
|
||||
return new WebuiAuth(parsed, null, false);
|
||||
}
|
||||
} catch {
|
||||
/* fallthrough — regenerate */
|
||||
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 initialPassword = randomBytes(8).toString('hex');
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { serve } from '@hono/node-server';
|
||||
import { getConnInfo } from '@hono/node-server/conninfo';
|
||||
import { serveStatic } from '@hono/node-server/serve-static';
|
||||
import { Hono } from 'hono';
|
||||
import { Hono, type Context } from 'hono';
|
||||
import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger';
|
||||
import { randomBytes } from 'crypto';
|
||||
import type { OneBotManager } from '../onebot/manager';
|
||||
import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config';
|
||||
import type { OneBotConfig } from '../onebot/types';
|
||||
import type { HookManager } from '../hook/hook-manager';
|
||||
import type { HookManager, HookProcessInfo } from '../hook/hook-manager';
|
||||
import path from 'path';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
@@ -40,6 +41,14 @@ const MUST_CHANGE_ALLOWLIST = new Set([
|
||||
'/api/logout',
|
||||
]);
|
||||
|
||||
// Endpoints that may authenticate via `?token=` query parameter. Only the
|
||||
// SSE log stream is here because EventSource cannot set custom headers; all
|
||||
// other endpoints MUST use the Authorization header so tokens never leak
|
||||
// into access logs / Referer / browser history.
|
||||
const TOKEN_QUERY_ALLOWLIST = new Set([
|
||||
'/api/logs/stream',
|
||||
]);
|
||||
|
||||
// uin = QQ number; 5–12 digits. Used to construct config file paths,
|
||||
// so we MUST refuse anything else (path traversal, NUL bytes, etc.).
|
||||
const UIN_REGEX = /^\d{5,12}$/;
|
||||
@@ -51,10 +60,24 @@ function purgeExpiredTokens() {
|
||||
for (const [token, info] of sessionTokens) {
|
||||
if (now > info.expiresAt) sessionTokens.delete(token);
|
||||
}
|
||||
for (const [ip, attempt] of loginAttempts) {
|
||||
if (now > attempt.resetAt) loginAttempts.delete(ip);
|
||||
}
|
||||
}
|
||||
|
||||
function getClientIp(req: Request): string {
|
||||
return req.headers.get('x-forwarded-for')?.split(',')[0].trim() ?? '127.0.0.1';
|
||||
/**
|
||||
* Resolve the client IP from the underlying TCP socket via the official
|
||||
* @hono/node-server conninfo helper. We deliberately do NOT trust
|
||||
* `X-Forwarded-For` — the WebUI listens on a local port with no required
|
||||
* reverse proxy, so accepting that header would let any client rotate it
|
||||
* to bypass the per-IP login lockout.
|
||||
*/
|
||||
function getClientIp(c: Context): string {
|
||||
try {
|
||||
return getConnInfo(c).remote.address ?? '127.0.0.1';
|
||||
} catch {
|
||||
return '127.0.0.1';
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> {
|
||||
@@ -96,11 +119,10 @@ export async function initWebUI(
|
||||
|
||||
const authHeader = c.req.header('Authorization');
|
||||
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
|
||||
const queryToken = c.req.query('token') ?? '';
|
||||
const queryToken = TOKEN_QUERY_ALLOWLIST.has(reqPath) ? (c.req.query('token') ?? '') : '';
|
||||
const token = bearerToken || queryToken;
|
||||
if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
|
||||
|
||||
purgeExpiredTokens();
|
||||
const info = sessionTokens.get(token);
|
||||
if (!info || Date.now() > info.expiresAt) {
|
||||
return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401);
|
||||
@@ -114,9 +136,14 @@ export async function initWebUI(
|
||||
await next();
|
||||
});
|
||||
|
||||
// Periodic janitor — keeps sessionTokens / loginAttempts from growing
|
||||
// unbounded and replaces the per-request O(n) sweep we used to do.
|
||||
const tokenJanitor = setInterval(purgeExpiredTokens, 60_000);
|
||||
tokenJanitor.unref?.();
|
||||
|
||||
// ─── Login ───────────────────────────────────────────────────────────────
|
||||
app.post('/api/login', async (c) => {
|
||||
const ip = getClientIp(c.req.raw);
|
||||
const ip = getClientIp(c);
|
||||
const now = Date.now();
|
||||
const attempt = loginAttempts.get(ip);
|
||||
if (attempt && attempt.count >= LOGIN_MAX_ATTEMPTS && now < attempt.resetAt) {
|
||||
@@ -140,7 +167,6 @@ export async function initWebUI(
|
||||
}
|
||||
|
||||
loginAttempts.delete(ip);
|
||||
purgeExpiredTokens();
|
||||
const token = randomBytes(32).toString('hex');
|
||||
const mustChange = auth.mustChangePassword();
|
||||
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange });
|
||||
@@ -196,20 +222,15 @@ export async function initWebUI(
|
||||
try {
|
||||
auth.setPassword(newPassword);
|
||||
} catch (err) {
|
||||
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 400);
|
||||
log.warn('change password failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '密码修改失败' }, 400);
|
||||
}
|
||||
// Invalidate all other sessions; current keeps but loses must-change flag.
|
||||
const currentToken = c.get('sessionToken' as never) as string | undefined;
|
||||
for (const [tok, info] of sessionTokens) {
|
||||
if (tok === currentToken) {
|
||||
info.mustChangePassword = false;
|
||||
sessionTokens.set(tok, info);
|
||||
} else {
|
||||
sessionTokens.delete(tok);
|
||||
}
|
||||
}
|
||||
log.info('password updated');
|
||||
return c.json({ success: true });
|
||||
// Invalidate every session, including the current one. If the old
|
||||
// password was compromised, the attacker may already hold the current
|
||||
// token; rotating credentials must rotate sessions too.
|
||||
sessionTokens.clear();
|
||||
log.info('password updated; all sessions invalidated');
|
||||
return c.json({ success: true, requireRelogin: true });
|
||||
});
|
||||
|
||||
// ─── Avatar proxy (uin validated) ────────────────────────────────────────
|
||||
@@ -319,23 +340,35 @@ export async function initWebUI(
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
let unsubscribe: (() => void) | undefined;
|
||||
let heartbeat: NodeJS.Timeout | undefined;
|
||||
const teardown = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
unsubscribe?.();
|
||||
try { controller.close(); } catch { /* ignore */ }
|
||||
};
|
||||
const safeEnqueue = (chunk: Uint8Array) => {
|
||||
if (closed) return;
|
||||
try {
|
||||
controller.enqueue(chunk);
|
||||
} catch {
|
||||
// The peer dropped between abort and the next enqueue —
|
||||
// treat as end-of-stream so we don't leak listeners.
|
||||
teardown();
|
||||
}
|
||||
};
|
||||
const send = (event: unknown) => {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
|
||||
safeEnqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
|
||||
};
|
||||
send({ type: 'ready' });
|
||||
const unsubscribe = subscribeLogs((entry) => send(entry));
|
||||
const heartbeat = setInterval(() => {
|
||||
controller.enqueue(encoder.encode(': heartbeat\n\n'));
|
||||
unsubscribe = subscribeLogs((entry) => send(entry));
|
||||
heartbeat = setInterval(() => {
|
||||
safeEnqueue(encoder.encode(': heartbeat\n\n'));
|
||||
}, 15000);
|
||||
c.req.raw.signal.addEventListener('abort', () => {
|
||||
clearInterval(heartbeat);
|
||||
unsubscribe();
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
});
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
@@ -356,62 +389,43 @@ export async function initWebUI(
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/processes/:pid/load', async (c) => {
|
||||
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
|
||||
const pid = Number(c.req.param('pid'));
|
||||
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
|
||||
return c.json({ success: false, message: 'invalid pid' }, 400);
|
||||
}
|
||||
try {
|
||||
const processInfo = await hookManager.loadProcess(pid);
|
||||
return c.json({ success: processInfo.status !== 'error', process: processInfo });
|
||||
} catch (err) {
|
||||
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/processes/:pid/unload', async (c) => {
|
||||
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
|
||||
const pid = Number(c.req.param('pid'));
|
||||
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
|
||||
return c.json({ success: false, message: 'invalid pid' }, 400);
|
||||
}
|
||||
try {
|
||||
const processInfo = await hookManager.unloadProcess(pid);
|
||||
return c.json({ success: processInfo.status !== 'error', process: processInfo });
|
||||
} catch (err) {
|
||||
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/processes/:pid/refresh', async (c) => {
|
||||
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
|
||||
const pid = Number(c.req.param('pid'));
|
||||
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
|
||||
return c.json({ success: false, message: 'invalid pid' }, 400);
|
||||
}
|
||||
try {
|
||||
const processInfo = await hookManager.refreshProcess(pid);
|
||||
return c.json({ success: processInfo.status !== 'error', process: processInfo });
|
||||
} catch (err) {
|
||||
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
|
||||
}
|
||||
});
|
||||
// Per-process action handler. The three routes below differ only in
|
||||
// which HookManager method they call.
|
||||
const MAX_PID = 4_194_304;
|
||||
function processAction(label: string, action: (pid: number) => Promise<HookProcessInfo>) {
|
||||
return async (c: Context) => {
|
||||
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
|
||||
const pid = Number(c.req.param('pid'));
|
||||
if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) {
|
||||
return c.json({ success: false, message: 'invalid pid' }, 400);
|
||||
}
|
||||
try {
|
||||
const processInfo = await action(pid);
|
||||
return c.json({ success: processInfo.status !== 'error', process: processInfo });
|
||||
} catch (err) {
|
||||
log.warn('%s pid=%d failed: %s', label, pid, err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '操作失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
};
|
||||
}
|
||||
app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid)));
|
||||
app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid)));
|
||||
app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid)));
|
||||
|
||||
app.get('/api/config/:uin', (c) => {
|
||||
const uin = c.req.param('uin');
|
||||
if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400);
|
||||
// Read-only: never write defaults to disk on a GET. The persisted
|
||||
// file is created when manager.onSessionStarted boots an instance
|
||||
// or when the operator POSTs from this very endpoint.
|
||||
const config = loadOneBotConfig(uin);
|
||||
return c.json({
|
||||
...config,
|
||||
config,
|
||||
});
|
||||
return c.json({ config });
|
||||
});
|
||||
|
||||
app.post('/api/config/:uin', async (c) => {
|
||||
const uin = c.req.param('uin');
|
||||
if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400);
|
||||
try {
|
||||
const uin = c.req.param('uin');
|
||||
if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400);
|
||||
const body = (await c.req.json()) as OneBotConfig;
|
||||
saveOneBotConfig(uin, body);
|
||||
const reloaded = oneBotManager.reloadConfig(uin);
|
||||
@@ -422,7 +436,8 @@ export async function initWebUI(
|
||||
message: reloaded ? '配置保存成功,已热重载当前会话。' : '配置保存成功,当前会话未在线,将在下次连接时生效。',
|
||||
});
|
||||
} catch (err) {
|
||||
return c.json({ success: false, message: String(err) }, 400);
|
||||
log.warn('save config for uin=%s failed: %s', uin, err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '配置保存失败,请检查服务器日志' }, 400);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user