feat(spa): API key entry, send key on all requests, 401 pointer (#197)

Bundle A SPA slice: the /api surface is now gated behind X-Api-Key on
every request (reads too, RequireKeyForReads defaults true), so a wrong/
missing key 401s everything.

- #282: send X-Api-Key on ALL requests when a key is stored, not only
  mutations (removed the mutatingMethods split in api/client.ts).
- #280: new keyless API Key screen (/app/api-key, System nav) that reads/
  writes only localStorage via auth.ts and never calls /api, so it works
  on a fresh install where every read 401s. Masked key state, Save/Clear,
  points at server-generated /config/api.key.
- 401 UX: client emits one app-wide unauthorized signal (auth.ts
  notify/subscribeUnauthorized); a shell-level UnauthorizedBanner points
  the user at the API Key screen. DRY, no per-screen 401 branches.
- Tests: inverted the GET header assertion (key now sent on reads), added
  no-key and 401-signal client tests, auth signal tests, and screen +
  banner tests. spa-conventions.md §5e documents the new seams.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-12 00:01:55 +02:00
co-authored by Claude Opus 4.8
parent cc414dfd7c
commit ab6d31309f
11 changed files with 443 additions and 9 deletions
+15 -1
View File
@@ -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);
});
});
+23
View File
@@ -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<UnauthorizedListener>();
export function subscribeUnauthorized(listener: UnauthorizedListener): () => void {
unauthorizedListeners.add(listener);
return () => {
unauthorizedListeners.delete(listener);
};
}
export function notifyUnauthorized(): void {
for (const listener of unauthorizedListeners) {
listener();
}
}
+56 -4
View File
@@ -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.' }), {
+10 -4
View File
@@ -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<RequestInit, 'body'> {
body?: RequestBody;
}
const mutatingMethods = new Set(['DELETE', 'PATCH', 'POST', 'PUT']);
export interface ResponseWithMeta<T> {
data: T;
/** Strong ETag of the resource's version, when the endpoint emits one (issue #253). */
@@ -48,7 +46,9 @@ export async function requestWithMeta<TResponse = unknown>(
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<TResponse = unknown>(
});
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));
}