diff --git a/packages/core/src/webui/request-security.ts b/packages/core/src/webui/request-security.ts new file mode 100644 index 00000000..dfdf6b5c --- /dev/null +++ b/packages/core/src/webui/request-security.ts @@ -0,0 +1,65 @@ +import { bodyLimit } from 'hono/body-limit'; +import { deleteCookie, getCookie, setCookie } from 'hono/cookie'; +import type { Context, Hono, MiddlewareHandler } from 'hono'; + +export const LOGIN_BODY_LIMIT_BYTES = 16 * 1024; +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'); +} + +/** 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(); + }); +} + +/** 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'", + ); +}; + +export function extractBearerToken(request: Request): string { + 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', +}); + +export function setAvatarSessionCookie(c: Context, token: string, secure: boolean): void { + 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)); +} + +export function readAvatarSessionToken(c: Context): string { + return getCookie(c, AVATAR_SESSION_COOKIE) ?? ''; +} diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 993c58d2..fdc53b1f 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -79,6 +79,14 @@ import type { NotificationManager } from '../notifications/manager'; import { StorageManagementService } from './storage-management'; import { registerStorageRoutes } from './storage-routes'; import { LogStorageSettingsManager } from './storage-settings'; +import { + clearAvatarSessionCookie, + extractBearerToken, + readAvatarSessionToken, + registerLoginRequestSecurity, + setAvatarSessionCookie, + webuiSecurityHeaders, +} from './request-security'; const log = createLogger('WebUI'); const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -199,21 +207,6 @@ const CONSENT_ALLOWLIST = new Set([ '/api/logout', ]); -// Endpoints that may authenticate via `?token=` query parameter. Reserved -// for SSE streams: EventSource cannot set custom headers, so these MUST -// accept the token via query. All other endpoints use the Authorization -// header so tokens never leak into access logs / Referer / browser history. -// -// Exported so the regression test can lock the invariant — a missing entry -// here silently 401s the EventSource and the whole push channel goes dark, -// which has happened (see /api/state/stream's first cut). -export const SSE_TOKEN_QUERY_PATHS: ReadonlySet = new Set([ - '/api/logs/stream', - '/api/debug/stream', - '/api/state/stream', -]); -const TOKEN_QUERY_ALLOWLIST = SSE_TOKEN_QUERY_PATHS; - // uin = QQ number; 5–10 digits (real QQ UINs fit in uint32, max 4294967295). // Used to construct config file paths, so we MUST refuse anything else (path // traversal, NUL bytes, etc.) — and the 10-digit cap also rejects the garbage @@ -533,6 +526,8 @@ export async function initWebUI( } const app = new Hono(); + app.use('*', webuiSecurityHeaders); + registerLoginRequestSecurity(app); const storageManagement = new StorageManagementService({ dataDir: 'data', getLogStatus: getLogStorageStatus, @@ -583,10 +578,7 @@ export async function initWebUI( // nothing sensitive (no layout, no secrets) — see ui-config.ts. if (reqPath === '/api/login' || reqPath === '/api/ui/public') return next(); - const authHeader = c.req.header('Authorization'); - const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : ''; - const queryToken = TOKEN_QUERY_ALLOWLIST.has(reqPath) ? (c.req.query('token') ?? '') : ''; - const token = bearerToken || queryToken; + const token = extractBearerToken(c.req.raw); if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401); const info = sessionTokens.get(token); @@ -650,12 +642,14 @@ export async function initWebUI( const token = randomBytes(32).toString('hex'); const mustChange = auth.mustChangePassword(); sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange }); + setAvatarSessionCookie(c, token, listener.tlsEnabled === true); return c.json({ success: true, token, mustChangePassword: mustChange }); }); app.post('/api/logout', (c) => { const token = c.get('sessionToken' as never) as string | undefined; if (token) sessionTokens.delete(token); + clearAvatarSessionCookie(c, listener.tlsEnabled === true); return c.json({ success: true }); }); @@ -709,6 +703,7 @@ export async function initWebUI( // password was compromised, the attacker may already hold the current // token; rotating credentials must rotate sessions too. sessionTokens.clear(); + clearAvatarSessionCookie(c, listener.tlsEnabled === true); log.info('password updated; all sessions invalidated'); return c.json({ success: true, requireRelogin: true }); }); @@ -750,6 +745,12 @@ export async function initWebUI( // ─── Avatar proxy (uin validated) ──────────────────────────────────────── app.get('/avatar/:uin', async (c) => { + const sessionToken = readAvatarSessionToken(c); + const session = sessionTokens.get(sessionToken); + if (!session || Date.now() > session.expiresAt) { + if (sessionToken) sessionTokens.delete(sessionToken); + return c.text('unauthorized', 401); + } const uin = c.req.param('uin'); if (!UIN_REGEX.test(uin)) return c.text('invalid uin', 400); @@ -768,7 +769,8 @@ export async function initWebUI( return new Response(cached.body, { headers: { 'Content-Type': cached.contentType, - 'Cache-Control': `public, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`, + 'Cache-Control': `private, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`, + Vary: 'Cookie', }, }); }); @@ -793,7 +795,13 @@ export async function initWebUI( }); // ─── Read-only API ─────────────────────────────────────────────────────── - app.get('/api/status', (c) => c.json({ status: 'running' })); + app.get('/api/status', (c) => { + // Refresh the path-scoped avatar cookie for a still-valid localStorage + // session (for example after upgrading from a version without the cookie). + const token = c.get('sessionToken' as never) as string; + setAvatarSessionCookie(c, token, listener.tlsEnabled === true); + return c.json({ status: 'running' }); + }); // Advisory update check — compares the running build against the latest // GitHub stable release and links the user to it. Read-only: SnowLuma diff --git a/packages/core/tests/webui-request-security.test.ts b/packages/core/tests/webui-request-security.test.ts new file mode 100644 index 00000000..a6746a5e --- /dev/null +++ b/packages/core/tests/webui-request-security.test.ts @@ -0,0 +1,97 @@ +import { Hono } from 'hono'; +import { describe, expect, it } from 'vitest'; +import { + clearAvatarSessionCookie, + extractBearerToken, + LOGIN_BODY_LIMIT_BYTES, + readAvatarSessionToken, + registerLoginRequestSecurity, + setAvatarSessionCookie, + webuiSecurityHeaders, +} from '../src/webui/request-security'; + +describe('WebUI public request security', () => { + it('rejects an oversized login body before JSON parsing', async () => { + const app = new Hono(); + app.use('*', webuiSecurityHeaders); + registerLoginRequestSecurity(app); + app.post('/api/login', async (c) => c.json(await c.req.json())); + + const response = await app.request('/api/login', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ password: 'x'.repeat(LOGIN_BODY_LIMIT_BYTES) }), + }); + + expect(response.status).toBe(413); + expect(response.headers.get('x-frame-options')).toBe('DENY'); + await expect(response.json()).resolves.toMatchObject({ success: false }); + }); + + it('accepts normal JSON login requests and rejects misleading content types', async () => { + const app = new Hono(); + registerLoginRequestSecurity(app); + app.post('/api/login', async (c) => c.json(await c.req.json())); + + const accepted = await app.request('/api/login', { + method: 'POST', + headers: { 'content-type': 'application/problem+json' }, + body: JSON.stringify({ password: 'normal-password' }), + }); + const rejected = await app.request('/api/login', { + method: 'POST', + headers: { 'content-type': 'text/plain' }, + body: JSON.stringify({ password: 'normal-password' }), + }); + + expect(accepted.status).toBe(200); + expect(rejected.status).toBe(415); + }); + + it('never treats a query parameter as a bearer credential', () => { + expect(extractBearerToken(new Request('http://localhost/api/state/stream?token=leaked'))).toBe(''); + expect(extractBearerToken(new Request('http://localhost/api/state/stream', { + headers: { authorization: 'Bearer header-token' }, + }))).toBe('header-token'); + }); + + it('round-trips an HttpOnly avatar session cookie and clears it on logout', async () => { + const app = new Hono(); + app.get('/set', (c) => { + setAvatarSessionCookie(c, 'session-token', false); + return c.text('ok'); + }); + app.get('/read', (c) => c.text(readAvatarSessionToken(c))); + app.get('/clear', (c) => { + clearAvatarSessionCookie(c, false); + return c.text('ok'); + }); + + const setResponse = await app.request('/set'); + const setCookie = setResponse.headers.get('set-cookie') ?? ''; + expect(setCookie).toContain('HttpOnly'); + expect(setCookie).toContain('SameSite=Strict'); + expect(setCookie).toContain('Path=/avatar'); + + const cookie = setCookie.split(';', 1)[0]; + const readResponse = await app.request('/read', { headers: { cookie } }); + expect(await readResponse.text()).toBe('session-token'); + + const clearResponse = await app.request('/clear'); + expect(clearResponse.headers.get('set-cookie')).toMatch(/Max-Age=0/i); + }); + + it('adds security headers without imposing a script or style policy', async () => { + const app = new Hono(); + app.use('*', webuiSecurityHeaders); + app.get('/', (c) => c.html('
SnowLuma
')); + + const response = await app.request('/'); + expect(response.headers.get('x-frame-options')).toBe('DENY'); + expect(response.headers.get('x-content-type-options')).toBe('nosniff'); + expect(response.headers.get('referrer-policy')).toBe('no-referrer'); + expect(response.headers.get('content-security-policy')).toBe( + "frame-ancestors 'none'; base-uri 'self'; object-src 'none'", + ); + }); +}); diff --git a/packages/core/tests/webui-sse-auth-allowlist.test.ts b/packages/core/tests/webui-sse-auth-allowlist.test.ts index b4889361..c8bae06d 100644 --- a/packages/core/tests/webui-sse-auth-allowlist.test.ts +++ b/packages/core/tests/webui-sse-auth-allowlist.test.ts @@ -1,24 +1,19 @@ import { describe, expect, it } from 'vitest'; -import { SSE_TOKEN_QUERY_PATHS } from '../src/webui/server'; +import { extractBearerToken } from '../src/webui/request-security'; -// Regression lock for a class of bug that has bricked an SSE endpoint -// before: EventSource cannot set Authorization headers, so every SSE -// path MUST appear in this allowlist or the auth middleware computes -// `queryToken = ''` and 401s every connect. A missing entry is silent — -// the only symptom is "live updates don't work, refresh fixes it" — so -// keep this list short and verified. -describe('SSE_TOKEN_QUERY_PATHS', () => { - it('contains every SSE stream the WebUI subscribes to', () => { - expect(SSE_TOKEN_QUERY_PATHS.has('/api/logs/stream')).toBe(true); - expect(SSE_TOKEN_QUERY_PATHS.has('/api/debug/stream')).toBe(true); - expect(SSE_TOKEN_QUERY_PATHS.has('/api/state/stream')).toBe(true); +describe('WebUI stream authentication', () => { + it('accepts bearer credentials for every live stream', () => { + for (const path of ['/api/logs/stream', '/api/debug/stream', '/api/state/stream']) { + const request = new Request(`http://localhost${path}`, { + headers: { authorization: 'Bearer stream-token' }, + }); + expect(extractBearerToken(request)).toBe('stream-token'); + } }); - it('does NOT carry any non-stream endpoint — token-via-query is reserved for SSE', () => { - // The auth middleware accepts `?token=...` for these paths only; any - // bearer-only endpoint listed here would leak tokens via access logs. - for (const path of SSE_TOKEN_QUERY_PATHS) { - expect(path.endsWith('/stream')).toBe(true); + it('does not accept tokens from stream query parameters', () => { + for (const path of ['/api/logs/stream', '/api/debug/stream', '/api/state/stream']) { + expect(extractBearerToken(new Request(`http://localhost${path}?token=leaked`))).toBe(''); } }); }); diff --git a/packages/webui/src/components/debug/live-activity.tsx b/packages/webui/src/components/debug/live-activity.tsx index b8f361fe..3bcf16c0 100644 --- a/packages/webui/src/components/debug/live-activity.tsx +++ b/packages/webui/src/components/debug/live-activity.tsx @@ -99,7 +99,7 @@ export function LiveActivity() { const [query, setQuery] = useState(''); const idRef = useRef(0); - // Pausing truly drops the EventSource instead of connecting-and-discarding: + // Pausing truly drops the live fetch stream instead of connecting-and-discarding: // `paused` is an effect dependency, so it closes the stream on pause and // reopens it on resume. (The always-on-across-tabs behaviour is intentional — // debug-page keeps this mounted so actions fired from other tabs still land in diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index 78ec39c7..a7e27668 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -43,7 +43,7 @@ class HttpApiClient implements ApiClient { private currentToken: string | null; private onUnauthorized?: () => void; - // Shared, ref-counted /api/logs/stream: a single EventSource fans out to every + // Shared, ref-counted /api/logs/stream: a single authenticated fetch stream fans out to every // subscriber (any number of dashboard alert widgets + the log viewer) instead // of opening one connection each. See openLogStream. private logSubscribers = new Set(); @@ -381,8 +381,8 @@ class HttpApiClient implements ApiClient { const changed = this.currentToken !== token; this.currentToken = token; this.tokenStore.save(token); - // The shared log stream URL carries the token — rebuild it on any change so - // a re-login doesn't leave subscribers on a stale-token connection (#185). + // Rebuild the shared stream on any change so a re-login doesn't leave + // subscribers on a stale Authorization header (#185). if (changed) this.reopenSharedLogStream(); } @@ -485,10 +485,10 @@ class HttpApiClient implements ApiClient { /** * Open a token-authed SSE channel to `path`, dispatching each parsed frame to * `onMessage` and surfacing transport state ('open' / 'reconnecting' / - * 'closed') via `onStatus`. EventSource auto-reconnects on drop — `onerror` - * fires once per loss, so a single 'reconnecting' is enough. A malformed - * frame (or a throw from `onMessage`) is swallowed; the next frame arrives - * normally. The returned disposer closes the source and reports 'closed'. + * 'closed') via `onStatus`. The fetch stream reconnects after transport loss + * so it retains EventSource's user-visible behaviour while keeping the token + * in the Authorization header. A malformed frame (or a throw from + * `onMessage`) is skipped. The returned disposer aborts the active request. */ private openSseChannel( path: string, @@ -496,14 +496,98 @@ class HttpApiClient implements ApiClient { onStatus?: (s: StreamStatus) => void, ): () => void { if (!this.currentToken) { onStatus?.('closed'); return () => {}; } - const url = `${path}?token=${encodeURIComponent(this.currentToken)}`; - const source = new EventSource(url); - source.onopen = () => onStatus?.('open'); - source.onerror = () => onStatus?.('reconnecting'); - source.onmessage = (event) => { - try { onMessage(JSON.parse(event.data) as T); } catch { /* malformed frame — skip */ } + let disposed = false; + let active: AbortController | null = null; + let reconnectTimer: ReturnType | null = null; + + const scheduleReconnect = () => { + if (disposed || reconnectTimer !== null) return; + onStatus?.('reconnecting'); + reconnectTimer = setTimeout(() => { + reconnectTimer = null; + void connect(); + }, 1_000); + }; + + const connect = async () => { + const token = this.currentToken; + if (disposed || !token) { onStatus?.('closed'); return; } + const controller = new AbortController(); + active = controller; + try { + const response = await fetch(path, { + headers: { + Accept: 'text/event-stream', + Authorization: `Bearer ${token}`, + }, + signal: controller.signal, + }); + if (response.status === 401) { + disposed = true; + active = null; + this.setToken(null); + this.onUnauthorized?.(); + onStatus?.('closed'); + return; + } + if (!response.ok || !response.body) { + throw new ApiError(response.status, response.statusText || '实时连接失败'); + } + onStatus?.('open'); + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + try { + while (!disposed) { + const { done, value } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + if (buffer.length > 1024 * 1024) throw new Error('SSE frame buffer exceeded 1 MiB'); + for (;;) { + const lf = buffer.indexOf('\n\n'); + const crlf = buffer.indexOf('\r\n\r\n'); + let separator = -1; + let separatorLength = 0; + if (lf >= 0 && (crlf < 0 || lf < crlf)) { + separator = lf; + separatorLength = 2; + } else if (crlf >= 0) { + separator = crlf; + separatorLength = 4; + } + if (separator < 0) break; + const block = buffer.slice(0, separator); + buffer = buffer.slice(separator + separatorLength); + const data = block + .split(/\r?\n/u) + .filter((line) => line.startsWith('data:')) + .map((line) => line.slice(5).replace(/^ /u, '')) + .join('\n'); + if (!data) continue; + try { onMessage(JSON.parse(data) as T); } catch { /* malformed frame — skip */ } + } + } + } finally { + reader.releaseLock(); + } + if (!disposed) scheduleReconnect(); + } catch { + if (!disposed && !controller.signal.aborted) scheduleReconnect(); + } finally { + if (active === controller) active = null; + } + }; + + void connect(); + return () => { + if (disposed) return; + disposed = true; + if (reconnectTimer !== null) clearTimeout(reconnectTimer); + reconnectTimer = null; + active?.abort(); + active = null; + onStatus?.('closed'); }; - return () => { source.close(); onStatus?.('closed'); }; } private openLogStream(options: LogsStreamOptions): () => void { diff --git a/packages/webui/tests/api-client-sse-auth.test.ts b/packages/webui/tests/api-client-sse-auth.test.ts new file mode 100644 index 00000000..e768ffe2 --- /dev/null +++ b/packages/webui/tests/api-client-sse-auth.test.ts @@ -0,0 +1,89 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createApiClient } from '../src/lib/api/client'; + +const encoder = new TextEncoder(); + +describe('API client SSE authentication', () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it('uses an Authorization header, parses frames, and never puts the token in the URL', async () => { + let streamController: ReadableStreamDefaultController | undefined; + const stream = new ReadableStream({ + start(controller) { streamController = controller; }, + }); + const fetchMock = vi.fn().mockResolvedValue(new Response(stream, { + status: 200, + headers: { 'content-type': 'text/event-stream' }, + })); + vi.stubGlobal('fetch', fetchMock); + + const client = createApiClient({ + tokenStore: { load: () => 'secret-session-token', save: vi.fn() }, + }); + const received = new Promise((resolve) => { + const dispose = client.stateStream({ + onEvent: (event) => { + resolve(event); + dispose(); + }, + }); + }); + + await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + streamController?.enqueue(encoder.encode('data: {"kind":"ready"}\n\n')); + + await expect(received).resolves.toEqual({ kind: 'ready' }); + const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(url).toBe('/api/state/stream'); + expect(new Headers(init.headers).get('authorization')).toBe('Bearer secret-session-token'); + expect(init.signal?.aborted).toBe(true); + }); + + it('clears the session and stops reconnecting after an unauthorized response', async () => { + const save = vi.fn(); + const onUnauthorized = vi.fn(); + const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 401 })); + vi.stubGlobal('fetch', fetchMock); + const client = createApiClient({ + tokenStore: { load: () => 'expired-token', save }, + onUnauthorized, + }); + const statuses: string[] = []; + + client.stateStream({ onEvent: vi.fn(), onStatus: (status) => statuses.push(status) }); + + await vi.waitFor(() => expect(onUnauthorized).toHaveBeenCalledTimes(1)); + expect(save).toHaveBeenCalledWith(null); + expect(statuses.at(-1)).toBe('closed'); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('reconnects after a completed stream without leaking the token', async () => { + vi.useFakeTimers(); + try { + const fetchMock = vi.fn() + .mockResolvedValueOnce(new Response('data: {"kind":"ready"}\r\n\r\n', { status: 200 })) + .mockImplementationOnce((_url: string, init?: RequestInit) => new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')), { once: true }); + })); + vi.stubGlobal('fetch', fetchMock); + const client = createApiClient({ + tokenStore: { load: () => 'reconnect-token', save: vi.fn() }, + }); + const onEvent = vi.fn(); + const statuses: string[] = []; + const dispose = client.stateStream({ onEvent, onStatus: (status) => statuses.push(status) }); + + await vi.waitFor(() => expect(onEvent).toHaveBeenCalledWith({ kind: 'ready' })); + expect(statuses).toContain('reconnecting'); + await vi.advanceTimersByTimeAsync(1_000); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(fetchMock.mock.calls.every(([url]) => url === '/api/state/stream')).toBe(true); + dispose(); + } finally { + vi.useRealTimers(); + } + }); +});