diff --git a/docs/spa-conventions.md b/docs/spa-conventions.md
index 50de7523e..8c0789a93 100644
--- a/docs/spa-conventions.md
+++ b/docs/spa-conventions.md
@@ -207,6 +207,29 @@ session — if a preference needs to be shared across devices or is really serve
(e.g. Blazor's `ConfigElement`-backed settings), it belongs behind an API endpoint instead; see
`docs/decisions.md` 2026-07-11 for the specific reasoning on logs page-size.
+## 5e. API key: the one keyless screen + the global 401 signal (#197)
+
+The whole `/api` surface is gated behind an `X-Api-Key` header (server-side #197): writes always
+require it and reads require it too (`Api:RequireKeyForReads` defaults true), so a missing/wrong key
+yields **401** on every call. Two SPA seams support this:
+
+- **The request client sends the key on every request** (`web/src/api/client.ts`): whenever
+ `getStoredApiKey()` returns a value it's attached to `X-Api-Key`, regardless of method (there is no
+ reads-vs-mutations split — that older guard was removed). The key lives in `localStorage`
+ (`ctv-api-key`) via `web/src/api/auth.ts` (`get/set/clearStoredApiKey`), per §5d.
+- **The API Key screen is the one screen that must render with ZERO successful `/api` calls**
+ (`web/src/screens/ApiKeyScreen.tsx`, route `/app/api-key`, System nav group). A keyless first load
+ 401s every read, so this screen reads/writes **only** `localStorage` (the `auth.ts` helpers) and
+ never fetches from `/api`. It shows a masked "key set / no key" state (never echoes the stored key
+ in plaintext — a `type="password"` input), Save (`setStoredApiKey`) and Clear (`clearStoredApiKey`),
+ and copy pointing at the server-generated `/config/api.key`. If you add a keyless bootstrap screen,
+ keep it `localStorage`-only for the same reason.
+- **401 UX is one shell-level banner, not per-screen handling.** Rather than special-casing 401 in
+ every screen's error path, the request client emits a single app-wide signal on 401
+ (`auth.ts` `notifyUnauthorized` / `subscribeUnauthorized`), and `web/src/UnauthorizedBanner.tsx`
+ (rendered once in the App shell) subscribes and points the user at `/app/api-key`. This is the DRY
+ seam for "the server rejected us" — reuse it instead of adding bespoke 401 branches.
+
## 6. Tests
- **vitest**, colocated `*.test.ts` / `*.test.tsx` next to the source file.
diff --git a/web/src/App.tsx b/web/src/App.tsx
index a66d29410..c814eb19d 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -27,6 +27,7 @@ import {
FolderTree,
Info,
Layers,
+ KeyRound,
LayoutDashboard,
LayoutGrid,
Library,
@@ -81,6 +82,8 @@ import {
import { ImageBrowserScreen } from './screens/ImageBrowserScreen';
import { SearchScreen } from './screens/SearchScreen';
import { SettingsScreen } from './screens/SettingsScreen';
+import { ApiKeyScreen } from './screens/ApiKeyScreen';
+import { UnauthorizedBanner } from './UnauthorizedBanner';
import { TraktListsScreen } from './screens/TraktListsScreen';
import { TrashScreen } from './screens/TrashScreen';
import { TroubleshootingScreen } from './screens/TroubleshootingScreen';
@@ -187,6 +190,7 @@ type ScreenId =
| 'ffmpegProfiles'
| 'watermarks'
| 'settings'
+ | 'apiKey'
| 'logs'
| 'troubleshooting'
| 'blockPlayoutTroubleshooting'
@@ -504,6 +508,19 @@ const routes: ScreenRoute[] = [
placeholder: 'Settings workspace',
allowSubPaths: true
},
+ {
+ // Keyless by design: this screen reads/writes only localStorage (auth.ts) and never calls
+ // `/api`, so it works on a fresh install where every `/api` read 401s (#280 / #197).
+ id: 'apiKey',
+ path: '/app/api-key',
+ label: 'API Key',
+ title: 'API Key',
+ kicker: 'System',
+ description: 'Store the API key this server requires on every request.',
+ icon: ,
+ primaryAction: 'Save key',
+ placeholder: 'API key workspace'
+ },
{
id: 'logs',
path: '/app/logs',
@@ -589,6 +606,7 @@ const mediaNavIds: ScreenId[] = [
];
const systemNavIds: ScreenId[] = [
'settings',
+ 'apiKey',
'logs',
'troubleshooting',
'blockPlayoutTroubleshooting',
@@ -2663,6 +2681,10 @@ function ScreenContent({
return ;
}
+ if (route.id === 'apiKey') {
+ return ;
+ }
+
if (route.id === 'media') {
return ;
}
@@ -2813,6 +2835,7 @@ export function App() {
+
diff --git a/web/src/UnauthorizedBanner.test.tsx b/web/src/UnauthorizedBanner.test.tsx
new file mode 100644
index 000000000..f707b1828
--- /dev/null
+++ b/web/src/UnauthorizedBanner.test.tsx
@@ -0,0 +1,45 @@
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { notifyUnauthorized } from './api';
+import { UnauthorizedBanner } from './UnauthorizedBanner';
+
+describe('UnauthorizedBanner', () => {
+ beforeEach(() => {
+ window.history.pushState(null, '', '/app');
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('stays hidden until a 401 signal fires', () => {
+ render();
+
+ expect(screen.queryByRole('alert')).toBeNull();
+
+ act(() => notifyUnauthorized());
+
+ expect(screen.getByRole('alert')).toBeTruthy();
+ expect(screen.getByText(/requires an API key/)).toBeTruthy();
+ expect(screen.getByText(/Settings → API Key/)).toBeTruthy();
+ });
+
+ it('navigates to the API Key screen from the pointer link', () => {
+ render();
+ act(() => notifyUnauthorized());
+
+ fireEvent.click(screen.getByRole('button', { name: 'Open API Key' }));
+
+ expect(window.location.pathname).toBe('/app/api-key');
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+
+ it('can be dismissed', () => {
+ render();
+ act(() => notifyUnauthorized());
+
+ fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));
+
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+});
diff --git a/web/src/UnauthorizedBanner.tsx b/web/src/UnauthorizedBanner.tsx
new file mode 100644
index 000000000..e5b3cba8b
--- /dev/null
+++ b/web/src/UnauthorizedBanner.tsx
@@ -0,0 +1,39 @@
+import { useEffect, useState } from 'react';
+import { KeyRound, X } from 'lucide-react';
+import { subscribeUnauthorized } from './api';
+import { navigateToPath } from './routing';
+
+const API_KEY_PATH = '/app/api-key';
+
+// Shell-level pointer shown when any `/api` request returns 401 (#197). Rather than teach every
+// screen's error path to special-case 401, the request client emits one app-wide signal (auth.ts)
+// and this single banner subscribes — DRY, and it renders regardless of which screen triggered it.
+export function UnauthorizedBanner() {
+ const [visible, setVisible] = useState(false);
+
+ useEffect(() => subscribeUnauthorized(() => setVisible(true)), []);
+
+ if (!visible) {
+ return null;
+ }
+
+ const goToApiKey = () => {
+ setVisible(false);
+ navigateToPath(API_KEY_PATH);
+ };
+
+ return (
+
+
+
+ This server requires an API key. Enter it in Settings → API Key.
+
+
+
+
+ );
+}
diff --git a/web/src/api/auth.test.ts b/web/src/api/auth.test.ts
index df1b23d91..f6c9d4eb0 100644
--- a/web/src/api/auth.test.ts
+++ b/web/src/api/auth.test.ts
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { clearStoredApiKey, getStoredApiKey, setStoredApiKey } from './auth';
+import { clearStoredApiKey, getStoredApiKey, notifyUnauthorized, setStoredApiKey, subscribeUnauthorized } from './auth';
describe('API key storage', () => {
beforeEach(() => {
@@ -40,3 +40,17 @@ describe('API key storage', () => {
localStorageGetter.mockRestore();
});
});
+
+describe('unauthorized signal', () => {
+ it('notifies subscribers and stops after unsubscribe', () => {
+ const listener = vi.fn();
+ const unsubscribe = subscribeUnauthorized(listener);
+
+ notifyUnauthorized();
+ expect(listener).toHaveBeenCalledTimes(1);
+
+ unsubscribe();
+ notifyUnauthorized();
+ expect(listener).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/web/src/api/auth.ts b/web/src/api/auth.ts
index 9cb28502e..e028af88c 100644
--- a/web/src/api/auth.ts
+++ b/web/src/api/auth.ts
@@ -31,3 +31,26 @@ export function setStoredApiKey(apiKey: string): void {
export function clearStoredApiKey(): void {
getStorage()?.removeItem(apiKeyStorageKey);
}
+
+// --- 401 signal -------------------------------------------------------------
+// The whole `/api` surface is gated behind the API key (#197). Rather than teach
+// every screen's error path to special-case 401, the request client emits a single
+// app-wide signal when any request comes back Unauthorized; a shell-level banner
+// subscribes and points the user at the API Key screen. Kept here (next to the key
+// storage it concerns) so it never depends on a successful `/api` call.
+type UnauthorizedListener = () => void;
+
+const unauthorizedListeners = new Set();
+
+export function subscribeUnauthorized(listener: UnauthorizedListener): () => void {
+ unauthorizedListeners.add(listener);
+ return () => {
+ unauthorizedListeners.delete(listener);
+ };
+}
+
+export function notifyUnauthorized(): void {
+ for (const listener of unauthorizedListeners) {
+ listener();
+ }
+}
diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts
index af118b423..06aa893fc 100644
--- a/web/src/api/client.test.ts
+++ b/web/src/api/client.test.ts
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { setStoredApiKey } from './auth';
+import { setStoredApiKey, subscribeUnauthorized } from './auth';
import { ApiError, request, requestWithMeta } from './client';
describe('API request client', () => {
@@ -8,21 +8,39 @@ describe('API request client', () => {
vi.restoreAllMocks();
});
- it('omits the API key header for read requests', async () => {
+ it('adds the API key header for read requests when a key is stored', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(
new Response(JSON.stringify([{ id: 1, number: '1', name: 'News' }]), {
headers: { 'Content-Type': 'application/json' },
status: 200
})
);
- setStoredApiKey('write-secret');
+ setStoredApiKey('read-secret');
await request('/api/channels');
expect(fetchMock).toHaveBeenCalledWith(
'/api/channels',
expect.objectContaining({
- headers: expect.not.objectContaining({ 'X-Api-Key': 'write-secret' })
+ headers: expect.objectContaining({ 'X-Api-Key': 'read-secret' })
+ })
+ );
+ });
+
+ it('sends no API key header when none is stored', async () => {
+ const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(
+ new Response(JSON.stringify([]), {
+ headers: { 'Content-Type': 'application/json' },
+ status: 200
+ })
+ );
+
+ await request('/api/channels');
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/api/channels',
+ expect.objectContaining({
+ headers: expect.not.objectContaining({ 'X-Api-Key': expect.anything() })
})
);
});
@@ -63,6 +81,40 @@ describe('API request client', () => {
await expect(request('/api/channels', { method: 'POST' })).resolves.toBeUndefined();
});
+ it('signals unauthorized subscribers on a 401 response', async () => {
+ vi.spyOn(window, 'fetch').mockResolvedValue(
+ new Response(JSON.stringify({ status: 401, title: 'Unauthorized' }), {
+ headers: { 'Content-Type': 'application/problem+json' },
+ status: 401
+ })
+ );
+
+ const onUnauthorized = vi.fn();
+ const unsubscribe = subscribeUnauthorized(onUnauthorized);
+
+ await expect(request('/api/channels')).rejects.toMatchObject({ status: 401 });
+
+ expect(onUnauthorized).toHaveBeenCalledTimes(1);
+ unsubscribe();
+ });
+
+ it('does not signal unauthorized subscribers on other error statuses', async () => {
+ vi.spyOn(window, 'fetch').mockResolvedValue(
+ new Response(JSON.stringify({ status: 403, title: 'Forbidden' }), {
+ headers: { 'Content-Type': 'application/problem+json' },
+ status: 403
+ })
+ );
+
+ const onUnauthorized = vi.fn();
+ const unsubscribe = subscribeUnauthorized(onUnauthorized);
+
+ await expect(request('/api/channels')).rejects.toMatchObject({ status: 403 });
+
+ expect(onUnauthorized).not.toHaveBeenCalled();
+ unsubscribe();
+ });
+
it('reads problem details from application/problem+json responses', async () => {
vi.spyOn(window, 'fetch').mockResolvedValue(
new Response(JSON.stringify({ status: 401, title: 'Unauthorized', detail: 'A valid API key is required for write requests.' }), {
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index e433016b2..f68e69856 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -1,4 +1,4 @@
-import { getStoredApiKey } from './auth';
+import { getStoredApiKey, notifyUnauthorized } from './auth';
import type { components } from './generated/v1';
type ProblemDetails = components['schemas']['ProblemDetails'];
@@ -22,8 +22,6 @@ export interface ApiRequestOptions extends Omit {
body?: RequestBody;
}
-const mutatingMethods = new Set(['DELETE', 'PATCH', 'POST', 'PUT']);
-
export interface ResponseWithMeta {
data: T;
/** Strong ETag of the resource's version, when the endpoint emits one (issue #253). */
@@ -48,7 +46,9 @@ export async function requestWithMeta(
const body = serializeBody(options.body, headers);
const apiKey = getStoredApiKey();
- if (apiKey && mutatingMethods.has(method)) {
+ // #197/#282: the whole `/api` surface is gated (reads too, since `Api:RequireKeyForReads`
+ // defaults true), so send the key on every request whenever one is stored — not only mutations.
+ if (apiKey) {
headers['X-Api-Key'] = apiKey;
}
@@ -60,6 +60,12 @@ export async function requestWithMeta(
});
if (!response.ok) {
+ // A gated `/api` surface answers a missing/wrong key with 401 (#197). Signal the shell so it can
+ // point the user at the API Key screen, regardless of which screen made the call.
+ if (response.status === 401) {
+ notifyUnauthorized();
+ }
+
throw new ApiError(response.status, await readProblemDetails(response));
}
diff --git a/web/src/screens/ApiKeyScreen.test.tsx b/web/src/screens/ApiKeyScreen.test.tsx
new file mode 100644
index 000000000..ae8789ac6
--- /dev/null
+++ b/web/src/screens/ApiKeyScreen.test.tsx
@@ -0,0 +1,69 @@
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { ApiKeyScreen } from './ApiKeyScreen';
+
+describe('ApiKeyScreen', () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ vi.restoreAllMocks();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('renders and functions without any /api call', () => {
+ const fetchSpy = vi.spyOn(window, 'fetch');
+
+ render();
+
+ expect(screen.getByText('No key')).toBeTruthy();
+ expect(screen.getByText(/No key is stored in this browser/)).toBeTruthy();
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it('saves a pasted key to local storage and shows the key-set state', () => {
+ render();
+
+ fireEvent.change(screen.getByLabelText('API key'), { target: { value: ' secret-123 ' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save key' }));
+
+ // Trimmed and written through to the shared ctv-api-key slot.
+ expect(window.localStorage.getItem('ctv-api-key')).toBe('secret-123');
+ expect(screen.getByText('Key set')).toBeTruthy();
+ expect(screen.getByText(/Key saved/)).toBeTruthy();
+ });
+
+ it('does not render the stored key value in plaintext', () => {
+ window.localStorage.setItem('ctv-api-key', 'super-secret');
+
+ render();
+
+ expect(screen.getByText('Key set')).toBeTruthy();
+ // The masked state never echoes the stored key back to the DOM.
+ expect(screen.queryByText(/super-secret/)).toBeNull();
+ expect(document.body.innerHTML).not.toContain('super-secret');
+ });
+
+ it('clears a stored key', () => {
+ window.localStorage.setItem('ctv-api-key', 'super-secret');
+
+ render();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Clear key' }));
+
+ expect(window.localStorage.getItem('ctv-api-key')).toBeNull();
+ expect(screen.getByText('No key')).toBeTruthy();
+ });
+
+ it('ignores a save with only whitespace', () => {
+ render();
+
+ const save = screen.getByRole('button', { name: 'Save key' });
+ expect(save.hasAttribute('disabled')).toBe(true);
+
+ fireEvent.change(screen.getByLabelText('API key'), { target: { value: ' ' } });
+ expect(save.hasAttribute('disabled')).toBe(true);
+ expect(window.localStorage.getItem('ctv-api-key')).toBeNull();
+ });
+});
diff --git a/web/src/screens/ApiKeyScreen.tsx b/web/src/screens/ApiKeyScreen.tsx
new file mode 100644
index 000000000..55c119308
--- /dev/null
+++ b/web/src/screens/ApiKeyScreen.tsx
@@ -0,0 +1,99 @@
+import { useState } from 'react';
+import { Check, KeyRound, ShieldCheck, Trash2, TriangleAlert } from 'lucide-react';
+import { Badge, Button, Card, Input } from '../components';
+import { clearStoredApiKey, getStoredApiKey, setStoredApiKey } from '../api';
+
+// The one screen that must work with ZERO successful `/api` calls: a keyless first load 401s every
+// read, so this screen relies only on localStorage (auth.ts helpers) and never fetches from `/api`.
+// It's how a fresh install gets its key in before anything else can load (#280 / #197).
+export function ApiKeyScreen() {
+ const [hasKey, setHasKey] = useState(() => getStoredApiKey() !== null);
+ const [draft, setDraft] = useState('');
+ const [justSaved, setJustSaved] = useState(false);
+
+ const trimmed = draft.trim();
+
+ const save = () => {
+ if (trimmed.length === 0) {
+ return;
+ }
+
+ setStoredApiKey(trimmed);
+ setHasKey(true);
+ setDraft('');
+ setJustSaved(true);
+ };
+
+ const clear = () => {
+ clearStoredApiKey();
+ setHasKey(false);
+ setJustSaved(false);
+ };
+
+ return (
+
+ Key set
+ ) : (
+ No key
+ )
+ }
+ padded
+ subtitle="This server requires an API key on every request. The server generates one on first run and writes it to /config/api.key on the server host — open that file and paste its contents below."
+ title="API Key"
+ >
+ {hasKey ? (
+
+
+ A key is stored in this browser. It's sent with every request to this server.
+
+ ) : (
+
+
+ No key is stored in this browser, so requests to this server will be rejected. Paste your key to continue.
+