diff --git a/packages/core/src/webui/request-security.ts b/packages/core/src/webui/request-security.ts index 77e44781..26a390a9 100644 --- a/packages/core/src/webui/request-security.ts +++ b/packages/core/src/webui/request-security.ts @@ -41,7 +41,15 @@ export const webuiSecurityHeaders: MiddlewareHandler = async (c, next) => { ); }; -export function extractBearerToken(request: Request): string { +export function extractWebuiSessionToken(request: Request): string { + const sessionToken = request.headers.get('x-snowluma-token'); + + // Authorization belongs to the proxy when it uses HTTP authentication. + // Only clients without the dedicated header use the legacy Bearer transport. + if (sessionToken !== null) { + return sessionToken; + } + const authorization = request.headers.get('authorization'); return authorization?.startsWith('Bearer ') ? authorization.slice(7) : ''; } diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index cdfd2de4..4b0074cf 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -108,7 +108,7 @@ import { registerStorageRoutes } from './storage-routes'; import { LogStorageSettingsManager } from './storage-settings'; import { clearAvatarSessionCookie, - extractBearerToken, + extractWebuiSessionToken, readAvatarSessionToken, registerLoginRequestSecurity, setAvatarSessionCookie, @@ -801,7 +801,7 @@ export async function initWebUI( return next(); } - const token = extractBearerToken(c.req.raw); + const token = extractWebuiSessionToken(c.req.raw); if (!token) { return c.json({ status: 'failed', message: 'Unauthorized' }, 401); @@ -1672,9 +1672,8 @@ export async function initWebUI( }); // Invoke a Stream API action (or any action) and relay every frame to the - // browser over an SSE body. The frontend reads this with fetch()+a stream - // reader (Bearer auth in the header), so — unlike /api/debug/stream — it does - // NOT need a query-token allowlist entry. Frames are never dropped. + // browser over an SSE body. The frontend uses fetch()+a stream reader so + // the session token stays in a header on this POST. Frames are never dropped. app.post('/api/debug/invoke-stream', async (c) => { let body: unknown; diff --git a/packages/core/tests/webui-request-security.test.ts b/packages/core/tests/webui-request-security.test.ts index d76d15d7..f4d80e91 100644 --- a/packages/core/tests/webui-request-security.test.ts +++ b/packages/core/tests/webui-request-security.test.ts @@ -2,7 +2,7 @@ import { Hono } from 'hono'; import { describe, expect, it } from 'vitest'; import { clearAvatarSessionCookie, - extractBearerToken, + extractWebuiSessionToken, LOGIN_BODY_LIMIT_BYTES, readAvatarSessionToken, registerLoginRequestSecurity, @@ -50,10 +50,10 @@ describe('WebUI public request security', () => { it('never treats a query parameter as a bearer credential', () => { expect( - extractBearerToken(new Request('http://localhost/api/state/stream?token=leaked')), + extractWebuiSessionToken(new Request('http://localhost/api/state/stream?token=leaked')), ).toBe(''); expect( - extractBearerToken( + extractWebuiSessionToken( new Request('http://localhost/api/state/stream', { headers: { authorization: 'Bearer header-token' }, }), @@ -61,6 +61,39 @@ describe('WebUI public request security', () => { ).toBe('header-token'); }); + it('reads the WebUI session without consuming reverse proxy Basic credentials', () => { + const request = new Request('http://localhost/api/auth/state', { + headers: { + authorization: 'Basic cHJveHk6cGFzc3dvcmQ=', + 'X-SnowLuma-Token': 'session-token', + }, + }); + expect(extractWebuiSessionToken(request)).toBe('session-token'); + }); + + it.each(['session-token', 'invalid-token', ''])( + 'uses an explicit WebUI credential even when it is %j', + (token) => { + const request = new Request('http://localhost/api/auth/state', { + headers: { + authorization: 'Bearer legacy-token', + 'X-SnowLuma-Token': token, + }, + }); + expect(extractWebuiSessionToken(request)).toBe(token); + }, + ); + + it('does not treat proxy credentials or the avatar cookie as an API session', () => { + const request = new Request('http://localhost/api/auth/state?token=leaked', { + headers: { + authorization: 'Basic cHJveHk6cGFzc3dvcmQ=', + cookie: 'snowluma_avatar_session=avatar-token', + }, + }); + expect(extractWebuiSessionToken(request)).toBe(''); + }); + it('round-trips an HttpOnly avatar session cookie and clears it on logout', async () => { const app = new Hono(); app.get('/set', (c) => { diff --git a/packages/core/tests/webui-sse-auth-allowlist.test.ts b/packages/core/tests/webui-sse-auth-allowlist.test.ts index 1397f36b..28e69806 100644 --- a/packages/core/tests/webui-sse-auth-allowlist.test.ts +++ b/packages/core/tests/webui-sse-auth-allowlist.test.ts @@ -1,21 +1,38 @@ import { describe, expect, it } from 'vitest'; -import { extractBearerToken } from '../src/webui/request-security'; +import { extractWebuiSessionToken } from '../src/webui/request-security'; describe('WebUI stream authentication', () => { + it('accepts a dedicated session header alongside proxy credentials for every stream', () => { + for (const path of [ + '/api/logs/stream', + '/api/debug/stream', + '/api/state/stream', + '/api/debug/invoke-stream', + ]) { + const request = new Request(`http://localhost${path}`, { + headers: { + authorization: 'Basic cHJveHk6cGFzc3dvcmQ=', + 'X-SnowLuma-Token': 'stream-token', + }, + }); + expect(extractWebuiSessionToken(request)).toBe('stream-token'); + } + }); + 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'); + expect(extractWebuiSessionToken(request)).toBe('stream-token'); } }); 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( - '', - ); + expect( + extractWebuiSessionToken(new Request(`http://localhost${path}?token=leaked`)), + ).toBe(''); } }); }); diff --git a/packages/webui/README.md b/packages/webui/README.md index ecd49370..b4b83821 100644 --- a/packages/webui/README.md +++ b/packages/webui/README.md @@ -30,6 +30,15 @@ status, OneBot configuration, logs, storage, and server settings. visible developer page for safely replaying this wizard and exercising the page-level crash screen; replayed consent and passwords are never persisted. +## Authentication behind a reverse proxy + +Authenticated WebUI requests send the session token in `X-SnowLuma-Token`, leaving +`Authorization` available for the reverse proxy's HTTP authentication (such as +Nginx Basic Auth). Forward `X-SnowLuma-Token` unchanged if the proxy filters +request headers. The backend still accepts `Authorization: Bearer ` for +existing clients when the dedicated header is absent. Both layers still require +their own valid credentials. + ## Local development On Windows, the native API logs the process token and EXE integrity label once diff --git a/packages/webui/src/contexts/ThemeContext.tsx b/packages/webui/src/contexts/ThemeContext.tsx index 46385a04..82a4dba8 100644 --- a/packages/webui/src/contexts/ThemeContext.tsx +++ b/packages/webui/src/contexts/ThemeContext.tsx @@ -12,6 +12,7 @@ import { import { flushSync } from 'react-dom'; import { MotionConfig } from 'motion/react'; import { actionErrorMessage, useActionFeedback } from '@/contexts/ActionFeedbackContext'; +import { webuiSessionHeaders } from '@/lib/api/session-headers'; import type { Palette, ThemeMode, UiAppearance, UiBackground } from '@/types'; // Re-export the appearance value types so consumers (settings page etc.) can @@ -942,7 +943,7 @@ async function fetchAppearance(): Promise { // Authed: fetch the full config so we get `customCss` (which the public // subset strips). Pre-auth (login page): the cosmetic public subset only. if (token) { - const res = await fetch('/api/ui', { headers: { Authorization: `Bearer ${token}` } }); + const res = await fetch('/api/ui', { headers: webuiSessionHeaders(token) }); if (res.ok) { const data = (await res.json()) as { @@ -995,7 +996,7 @@ async function persistAppearance(appearance: UiAppearance): Promise { const response = await fetch('/api/ui', { method: 'POST', - headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, + headers: webuiSessionHeaders(token, { 'Content-Type': 'application/json' }), // Section-level save: only `appearance`; the server preserves `layout`. body: JSON.stringify({ appearance }), }); @@ -1347,7 +1348,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) { form.append('file', file); const res = await fetch('/api/ui/background', { method: 'POST', - headers: { Authorization: `Bearer ${token}` }, + headers: webuiSessionHeaders(token), body: form, }); @@ -1388,7 +1389,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) { const res = await fetch('/api/ui/background', { method: 'DELETE', - headers: { Authorization: `Bearer ${token}` }, + headers: webuiSessionHeaders(token), }); if (!res.ok) { diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index a1a65839..38040186 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -42,6 +42,7 @@ import { type TotpStatus, } from './types'; import { localStorageTokenStore } from './token-store'; +import { WEBUI_SESSION_HEADER, webuiSessionHeaders } from './session-headers'; const DEFAULT_TOKEN_KEY = 'snowluma_token'; const REQUEST_TIMEOUT_MS = 30_000; @@ -314,15 +315,9 @@ class HttpApiClient implements ApiClient { // bearer header directly — mirroring login()'s deliberate bypass. const form = new FormData(); form.append('file', file); - const headers: Record = {}; - - if (this.currentToken) { - headers['Authorization'] = `Bearer ${this.currentToken}`; - } - const res = await fetch('/api/ui/background', { method: 'POST', - headers, + headers: webuiSessionHeaders(this.currentToken), body: form, }); @@ -532,16 +527,10 @@ class HttpApiClient implements ApiClient { // ---------- HTTP helpers ---------- async request(url: string, init: RequestInit = {}): Promise { - const headers: Record = { - ...((init.headers as Record | undefined) ?? {}), - }; + const headers = webuiSessionHeaders(this.currentToken, init.headers); - if (this.currentToken) { - headers['Authorization'] = `Bearer ${this.currentToken}`; - } - - if (init.body && !(init.body instanceof FormData) && !headers['Content-Type']) { - headers['Content-Type'] = 'application/json'; + if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) { + headers.set('Content-Type', 'application/json'); } const res = await this.fetchWithDeadline(url, { ...init, headers }); @@ -616,7 +605,7 @@ class HttpApiClient implements ApiClient { this.tokenStore.save(token); // Rebuild the shared stream on any change so a re-login doesn't leave - // subscribers on a stale Authorization header (#185). + // subscribers on a stale session token (#185). if (changed) { this.reopenSharedLogStream(); } @@ -763,7 +752,7 @@ class HttpApiClient implements ApiClient { * `onMessage` and surfacing transport state ('open' / 'reconnecting' / * '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 + * in the WebUI session header. A malformed frame (or a throw from * `onMessage`) is skipped. The returned disposer aborts the active request. */ private openSseChannel( @@ -807,11 +796,10 @@ class HttpApiClient implements ApiClient { try { const response = await fetch(path, { cache: 'no-store', - headers: { + headers: webuiSessionHeaders(token, { Accept: 'text/event-stream', - Authorization: `Bearer ${token}`, 'Cache-Control': 'no-cache', - }, + }), signal: controller.signal, }); @@ -1081,15 +1069,11 @@ class HttpApiClient implements ApiClient { onFrame: (frame: import('@/types').DebugStreamFrame) => void, signal?: AbortSignal, ): Promise { - const headers: Record = { + const headers = webuiSessionHeaders(this.currentToken, { 'Content-Type': 'application/json', Accept: 'text/event-stream', 'Cache-Control': 'no-cache', - }; - - if (this.currentToken) { - headers['Authorization'] = `Bearer ${this.currentToken}`; - } + }); const res = await fetch('/api/debug/invoke-stream', { method: 'POST', @@ -1203,7 +1187,7 @@ class HttpApiClient implements ApiClient { xhr.open('POST', `/api/debug/upload?filename=${encodeURIComponent(name)}`); if (this.currentToken) { - xhr.setRequestHeader('Authorization', `Bearer ${this.currentToken}`); + xhr.setRequestHeader(WEBUI_SESSION_HEADER, this.currentToken); } xhr.responseType = 'json'; diff --git a/packages/webui/src/lib/api/session-headers.ts b/packages/webui/src/lib/api/session-headers.ts new file mode 100644 index 00000000..e3ffb545 --- /dev/null +++ b/packages/webui/src/lib/api/session-headers.ts @@ -0,0 +1,12 @@ +export const WEBUI_SESSION_HEADER = 'X-SnowLuma-Token'; + +/** Leave Authorization available for HTTP authentication at the reverse proxy. */ +export function webuiSessionHeaders(token: string | null, initial?: HeadersInit): Headers { + const headers = new Headers(initial); + + if (token) { + headers.set(WEBUI_SESSION_HEADER, token); + } + + return headers; +} diff --git a/packages/webui/tests/api-client-log-export.test.ts b/packages/webui/tests/api-client-log-export.test.ts index aa9c1a25..e1bab7a4 100644 --- a/packages/webui/tests/api-client-log-export.test.ts +++ b/packages/webui/tests/api-client-log-export.test.ts @@ -32,7 +32,7 @@ describe('API client full TRACE export', () => { expect(fetchMock).toHaveBeenCalledExactlyOnceWith( '/api/logs/export/trace', expect.objectContaining({ - headers: { Authorization: 'Bearer trace-token' }, + headers: new Headers({ 'X-SnowLuma-Token': 'trace-token' }), }), ); }); diff --git a/packages/webui/tests/api-client-proxy-auth.test.ts b/packages/webui/tests/api-client-proxy-auth.test.ts new file mode 100644 index 00000000..ac59a898 --- /dev/null +++ b/packages/webui/tests/api-client-proxy-auth.test.ts @@ -0,0 +1,124 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createApiClient } from '../src/lib/api/client'; + +const sessionToken = 'webui-session-token'; +const proxyAuthorization = 'Basic cHJveHk6cGFzc3dvcmQ='; +const proxyHeaderEntries: [string, string][] = [['Authorization', proxyAuthorization]]; +const tokenStore = { load: () => sessionToken, save: vi.fn() }; + +afterEach(() => { + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + +describe('WebUI authentication behind a Basic-auth proxy', () => { + it.each([ + { kind: 'object', headers: { Authorization: proxyAuthorization } }, + { kind: 'Headers', headers: new Headers({ Authorization: proxyAuthorization }) }, + { kind: 'tuples', headers: proxyHeaderEntries }, + ])('preserves supplied proxy credentials from $kind', async ({ headers }) => { + const fetchMock = vi.fn(async (_url: string, init?: RequestInit) => { + const sent = new Headers(init?.headers); + + if (sent.get('authorization') !== proxyAuthorization) { + return new Response(null, { status: 401 }); + } + + return new Response(null, { + status: sent.get('x-snowluma-token') === sessionToken ? 204 : 403, + }); + }); + vi.stubGlobal('fetch', fetchMock); + const onUnauthorized = vi.fn(); + const client = createApiClient({ tokenStore, onUnauthorized }); + + const response = await client.request('/api/auth/state', { headers }); + + expect(response.status).toBe(204); + expect(onUnauthorized).not.toHaveBeenCalled(); + expect(tokenStore.save).not.toHaveBeenCalled(); + }); + + it('leaves browser-managed proxy authentication available on JSON requests', async () => { + const fetchMock = vi.fn().mockResolvedValue(Response.json({ list: [] })); + vi.stubGlobal('fetch', fetchMock); + const client = createApiClient({ tokenStore }); + + await expect(client.qqList()).resolves.toEqual([]); + + const headers = new Headers(fetchMock.mock.calls[0]![1]?.headers); + expect(headers.get('x-snowluma-token')).toBe(sessionToken); + expect(headers.has('authorization')).toBe(false); + }); + + it('authenticates multipart uploads without replacing the browser multipart boundary', async () => { + const fetchMock = vi.fn().mockResolvedValue(Response.json({ config: {} })); + vi.stubGlobal('fetch', fetchMock); + const client = createApiClient({ tokenStore }); + const file = new File(['image'], 'background.png', { type: 'image/png' }); + + await client.ui.uploadBackground(file); + + const [url, init] = fetchMock.mock.calls[0]!; + const headers = new Headers(init?.headers); + expect(url).toBe('/api/ui/background'); + expect(headers.get('x-snowluma-token')).toBe(sessionToken); + expect(headers.has('authorization')).toBe(false); + expect(headers.has('content-type')).toBe(false); + expect(init?.body).toBeInstanceOf(FormData); + expect((init?.body as FormData).get('file')).toBe(file); + }); + + it('authenticates streamed action requests without overriding proxy authentication', async () => { + const fetchMock = vi.fn().mockResolvedValue( + new Response('data: {"type":"done"}\n\n', { + headers: { 'Content-Type': 'text/event-stream' }, + }), + ); + vi.stubGlobal('fetch', fetchMock); + const client = createApiClient({ tokenStore }); + const onFrame = vi.fn(); + + await client.debug.invokeStream('12345', 'test_action', {}, onFrame); + + const [url, init] = fetchMock.mock.calls[0]!; + const headers = new Headers(init?.headers); + expect(url).toBe('/api/debug/invoke-stream'); + expect(headers.get('x-snowluma-token')).toBe(sessionToken); + expect(headers.has('authorization')).toBe(false); + expect(headers.get('content-type')).toBe('application/json'); + expect(onFrame).toHaveBeenCalledWith({ type: 'done' }); + }); + + it('authenticates XHR uploads without overriding proxy authentication', async () => { + const headers = new Headers(); + const send = vi.fn(); + class UploadRequest { + upload = {}; + responseType = ''; + status = 200; + response = { path: '/tmp/uploaded-file', size: 4 }; + onload?: () => void; + open = vi.fn(); + setRequestHeader(name: string, value: string) { + headers.set(name, value); + } + send(file: File) { + send(file); + this.onload?.(); + } + } + vi.stubGlobal('XMLHttpRequest', UploadRequest); + const client = createApiClient({ tokenStore }); + const file = new File(['test'], 'test.txt'); + + await expect(client.debug.upload(file)).resolves.toEqual({ + path: '/tmp/uploaded-file', + size: 4, + }); + + expect(send).toHaveBeenCalledWith(file); + expect(headers.get('x-snowluma-token')).toBe(sessionToken); + expect(headers.has('authorization')).toBe(false); + }); +}); diff --git a/packages/webui/tests/api-client-sse-auth.test.ts b/packages/webui/tests/api-client-sse-auth.test.ts index dc54fdd6..78435db3 100644 --- a/packages/webui/tests/api-client-sse-auth.test.ts +++ b/packages/webui/tests/api-client-sse-auth.test.ts @@ -8,7 +8,7 @@ describe('API client SSE authentication', () => { vi.unstubAllGlobals(); }); - it('uses an Authorization header, parses frames, and never puts the token in the URL', async () => { + it('keeps Authorization available for the proxy while authenticating and parsing frames', async () => { let streamController: ReadableStreamDefaultController | undefined; const stream = new ReadableStream({ start(controller) { @@ -41,7 +41,8 @@ describe('API client SSE authentication', () => { 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(new Headers(init.headers).get('x-snowluma-token')).toBe('secret-session-token'); + expect(new Headers(init.headers).has('authorization')).toBe(false); expect(init.signal?.aborted).toBe(true); }); diff --git a/packages/webui/tests/password-strength-api.test.ts b/packages/webui/tests/password-strength-api.test.ts index 1172ab47..49efa46a 100644 --- a/packages/webui/tests/password-strength-api.test.ts +++ b/packages/webui/tests/password-strength-api.test.ts @@ -41,10 +41,10 @@ describe('password strength API client', () => { expect.objectContaining({ method: 'POST', body: JSON.stringify({ password: 'Strong-password' }), - headers: { - Authorization: 'Bearer test-token', + headers: new Headers({ + 'X-SnowLuma-Token': 'test-token', 'Content-Type': 'application/json', - }, + }), signal: expect.any(AbortSignal), }), ); diff --git a/packages/webui/tests/storage-api.test.ts b/packages/webui/tests/storage-api.test.ts index 0336f024..37282ab1 100644 --- a/packages/webui/tests/storage-api.test.ts +++ b/packages/webui/tests/storage-api.test.ts @@ -49,7 +49,7 @@ describe('storage API client', () => { expect(fetchMock).toHaveBeenCalledWith( '/api/system/storage', expect.objectContaining({ - headers: { Authorization: 'Bearer test-token' }, + headers: new Headers({ 'X-SnowLuma-Token': 'test-token' }), signal: expect.any(AbortSignal), }), ); @@ -82,10 +82,10 @@ describe('storage API client', () => { expect.objectContaining({ method: 'POST', body: JSON.stringify({ logRetainDays: 0 }), - headers: { - Authorization: 'Bearer test-token', + headers: new Headers({ + 'X-SnowLuma-Token': 'test-token', 'Content-Type': 'application/json', - }, + }), signal: expect.any(AbortSignal), }), );