fix(webui): strengthen public session handling

Bound unauthenticated sign-in requests and require active sessions for browser-served account images.

Keep live updates authenticated without exposing session material in request URLs, and apply conservative response protections without restricting existing WebUI assets.
This commit is contained in:
DrSmoothl committed 2026-08-01 16:36:33 +08:00
1 parent 958d17ecc0
commit e4179ffb47
7 files changed
+391 -53

No files matched your search

@@ -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
+98 -14
View File
@@ -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<LogsStreamOptions>();
@@ -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<T>(
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<typeof setTimeout> | 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 {
@@ -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<Uint8Array> | undefined;
const stream = new ReadableStream<Uint8Array>({
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<unknown>((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<Response>((_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();
}
});
});