feat(web): #295 PR2 SPA consumers — troubleshoot POST/blob downloads + machine-key screen + password change
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
+32
-17
@@ -207,28 +207,43 @@ 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)
|
||||
## 5e. Session auth: the boot gate, the machine-key screen + the global 401 signal (#295)
|
||||
|
||||
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:
|
||||
Since #295 the browser authenticates with a **session cookie**, not an API key. The whole `/api`
|
||||
surface still answers a missing/expired session with **401**, and mutating verbs additionally require a
|
||||
CSRF header. The former keyless-bootstrap `ApiKeyScreen` (the `X-Api-Key`/`localStorage` model of #197)
|
||||
is gone. The SPA seams now are:
|
||||
|
||||
- **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.
|
||||
- **The request client sends no API key; it relies on the cookie and adds CSRF automatically**
|
||||
(`web/src/api/client.ts`): the session cookie rides along with every same-origin request, and every
|
||||
mutating verb (POST/PUT/PATCH/DELETE) gets an `X-Csrf` header set automatically — screens making a
|
||||
POST get CSRF for free. There is **no** `getStoredApiKey`/`X-Api-Key` path anymore; the only residual
|
||||
`localStorage` touch is `clearLegacyStoredApiKey()` (`web/src/api/auth.ts`), a one-shot cleanup the
|
||||
boot gate runs once to purge any stale `ctv-api-key`.
|
||||
- **The boot gate owns login/setup** (`web/src/AuthGate.tsx`), wrapping `<App/>` outside the
|
||||
shell/router. It asks the PUBLIC `/api/auth/config`, then `/api/auth/session`, and renders Setup /
|
||||
Login / the app. It also publishes `AuthContext` (`{ username, method, signOut, requireLogin }`) —
|
||||
read `method` via `useContext(AuthContext)` to branch on the auth kind (e.g. `'local'` vs OIDC).
|
||||
- **The machine-key screen is a normal authenticated screen** (`web/src/screens/ApiKeyScreen.tsx`,
|
||||
route `/app/api-key`, System nav group). It loads the server machine key from `/api/auth/machine-key`
|
||||
(via `getMachineKey()`) and displays it **masked** (a masked `<code>` that never puts the key in the
|
||||
DOM until Reveal) with Reveal + Copy affordances — the key is for MCP / external REST clients; the
|
||||
browser no longer uses it. For **local** accounts only (`AuthContext.method === 'local'`) it also
|
||||
renders a "Local admin password" card that calls `changePassword(current, new)`, mapping a wrong-
|
||||
current-password **401** to the server ProblemDetails detail inline.
|
||||
- **File-download endpoints go through a fetch-blob helper, never a browser tab.** Endpoints that
|
||||
return a binary body (the troubleshooting archive / media-sample POSTs) must **not** go through
|
||||
`request()` (it JSON-parses) and must **not** be opened with `window.open` (a session-cookie GET in a
|
||||
new tab can't carry the CSRF header and bypasses error handling). Instead `fetch(path, { method:
|
||||
'POST', headers: { 'X-Csrf': '1' } })`, then `response.blob()` → object URL → anchor-click →
|
||||
revoke, reading the filename from `Content-Disposition`; a non-ok response throws an `ApiError`. See
|
||||
`downloadTroubleshootingArchive` / `downloadTroubleshootingMediaSample` in `web/src/api/troubleshoot.ts`.
|
||||
- **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.
|
||||
(rendered once in the App shell) subscribes and prompts re-login. This is the DRY seam for "the server
|
||||
rejected us" — reuse it instead of adding bespoke 401 branches. Auth flows that expect a 401 as an
|
||||
inline answer (login, change-password) pass `suppressUnauthorizedSignal` so they don't trip it.
|
||||
|
||||
## 6. Tests
|
||||
|
||||
|
||||
+2
-27
@@ -42,37 +42,12 @@ function getStorage(): Storage | undefined {
|
||||
|
||||
// The SPA no longer stores or sends an API key — it authenticates with the session cookie (#295). This
|
||||
// one-shot cleanup removes any legacy `ctv-api-key` left over from the pre-session model; AuthGate calls
|
||||
// it once on reaching `ready`.
|
||||
// it once on reaching `ready`. (The former `get/set/clearStoredApiKey` shims were removed once the
|
||||
// ApiKeyScreen stopped consuming them — this is the sole remaining reader of the legacy key.)
|
||||
export function clearLegacyStoredApiKey(): void {
|
||||
getStorage()?.removeItem(legacyApiKeyStorageKey);
|
||||
}
|
||||
|
||||
// --- legacy API-key storage (DEPRECATED, #295) ------------------------------
|
||||
// The session-auth plan (PR #295 slice B) deletes these — the client no longer sends the key and the
|
||||
// key is no longer stored by the SPA. They are retained here ONLY so the still-shipping
|
||||
// `screens/ApiKeyScreen.tsx` (migrated by the separate machine-key slice) keeps compiling without a
|
||||
// cross-slice merge conflict; nothing else reads them and `client.ts` no longer attaches the key.
|
||||
// Remove these with the ApiKeyScreen slice.
|
||||
export function getStoredApiKey(): string | null {
|
||||
const value = getStorage()?.getItem(legacyApiKeyStorageKey);
|
||||
return value && value.trim().length > 0 ? value : null;
|
||||
}
|
||||
|
||||
export function setStoredApiKey(apiKey: string): void {
|
||||
const trimmed = apiKey.trim();
|
||||
|
||||
if (trimmed.length === 0) {
|
||||
clearStoredApiKey();
|
||||
return;
|
||||
}
|
||||
|
||||
getStorage()?.setItem(legacyApiKeyStorageKey, trimmed);
|
||||
}
|
||||
|
||||
export function clearStoredApiKey(): void {
|
||||
getStorage()?.removeItem(legacyApiKeyStorageKey);
|
||||
}
|
||||
|
||||
// --- 401 signal -------------------------------------------------------------
|
||||
// The whole `/api` surface is gated behind an authenticated session cookie (#295). Rather than teach
|
||||
// every screen's error path to special-case 401, the request client emits a single app-wide signal when
|
||||
|
||||
@@ -1,12 +1,25 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
downloadTroubleshootingArchive,
|
||||
downloadTroubleshootingMediaSample,
|
||||
getTroubleshootingInfo,
|
||||
getTroubleshootingPlaybackStatus,
|
||||
getTroubleshootingStreamSelectors,
|
||||
getTroubleshootingSubtitles,
|
||||
validateSequentialSchedule
|
||||
startTroubleshootingPlayback,
|
||||
validateSequentialSchedule,
|
||||
type StartTroubleshootingPlaybackBody
|
||||
} from './troubleshoot';
|
||||
|
||||
function headerValue(init: RequestInit | undefined, name: string): string | undefined {
|
||||
const headers = init?.headers as Record<string, string> | undefined;
|
||||
if (!headers) {
|
||||
return undefined;
|
||||
}
|
||||
const match = Object.keys(headers).find((key) => key.toLowerCase() === name.toLowerCase());
|
||||
return match ? headers[match] : undefined;
|
||||
}
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
|
||||
}
|
||||
@@ -119,3 +132,129 @@ describe('troubleshooting playback wrappers', () => {
|
||||
expect(fetchSpy.mock.calls[0][0]).toBe('/api/troubleshoot/playback/status');
|
||||
});
|
||||
});
|
||||
|
||||
describe('startTroubleshootingPlayback', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('POSTs /api/troubleshoot/playback/start with the mapped body and a CSRF header, returning the url', async () => {
|
||||
const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue(
|
||||
jsonResponse({ url: '/iptv/session/.troubleshooting/live.m3u8' })
|
||||
);
|
||||
|
||||
// Arrays are carried through, and the mutually-exclusive pair is preserved as the caller mapped it
|
||||
// (streamSelector set → subtitleId null).
|
||||
const body: StartTroubleshootingPlaybackBody = {
|
||||
mediaItem: 5,
|
||||
channel: 0,
|
||||
ffmpegProfile: 2,
|
||||
streamingMode: 'HttpLiveStreamingSegmenter',
|
||||
watermark: [10, 11],
|
||||
graphicsElement: [20],
|
||||
streamSelector: 'selector-a',
|
||||
subtitleId: null,
|
||||
seekSeconds: 1200,
|
||||
start: null
|
||||
};
|
||||
|
||||
await expect(startTroubleshootingPlayback(body)).resolves.toEqual({
|
||||
url: '/iptv/session/.troubleshooting/live.m3u8'
|
||||
});
|
||||
|
||||
const [url, init] = fetchSpy.mock.calls[0];
|
||||
expect(url).toBe('/api/troubleshoot/playback/start');
|
||||
expect((init?.method ?? 'GET').toUpperCase()).toBe('POST');
|
||||
expect(headerValue(init, 'X-Csrf')).toBe('1');
|
||||
expect(JSON.parse(String(init?.body))).toEqual(body);
|
||||
});
|
||||
|
||||
it('rejects with the ApiError status (409) so the screen can surface "another session running"', async () => {
|
||||
vi.spyOn(window, 'fetch').mockResolvedValue(
|
||||
new Response(JSON.stringify({ status: 409, title: 'Conflict', detail: 'Another session is running.' }), {
|
||||
headers: { 'Content-Type': 'application/problem+json' },
|
||||
status: 409
|
||||
})
|
||||
);
|
||||
|
||||
await expect(
|
||||
startTroubleshootingPlayback({
|
||||
mediaItem: 5,
|
||||
channel: 0,
|
||||
ffmpegProfile: 1,
|
||||
streamingMode: 'HttpLiveStreamingSegmenter',
|
||||
watermark: [],
|
||||
graphicsElement: [],
|
||||
streamSelector: null,
|
||||
subtitleId: null,
|
||||
seekSeconds: 0,
|
||||
start: null
|
||||
})
|
||||
).rejects.toMatchObject({ status: 409, detail: 'Another session is running.' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('troubleshooting download helpers', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function zipResponse(filename: string): Response {
|
||||
return new Response(new Blob(['zip-bytes']), {
|
||||
headers: {
|
||||
'Content-Type': 'application/zip',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`
|
||||
},
|
||||
status: 200
|
||||
});
|
||||
}
|
||||
|
||||
function stubBrowserDownload() {
|
||||
const createObjectURL = vi.fn(() => 'blob:mock');
|
||||
const revokeObjectURL = vi.fn();
|
||||
// jsdom does not implement these on URL; install spies so the anchor-click download path runs.
|
||||
(URL as unknown as { createObjectURL: unknown }).createObjectURL = createObjectURL;
|
||||
(URL as unknown as { revokeObjectURL: unknown }).revokeObjectURL = revokeObjectURL;
|
||||
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
|
||||
return { createObjectURL, revokeObjectURL, clickSpy };
|
||||
}
|
||||
|
||||
it('POSTs (not GETs) the archive with a CSRF header and triggers a download', async () => {
|
||||
const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue(zipResponse('ersatztv-troubleshooting-123.zip'));
|
||||
const { createObjectURL, revokeObjectURL, clickSpy } = stubBrowserDownload();
|
||||
|
||||
await downloadTroubleshootingArchive();
|
||||
|
||||
const [url, init] = fetchSpy.mock.calls[0];
|
||||
expect(url).toBe('/api/troubleshoot/playback/archive');
|
||||
expect((init?.method ?? 'GET').toUpperCase()).toBe('POST');
|
||||
expect(headerValue(init, 'X-Csrf')).toBe('1');
|
||||
expect(createObjectURL).toHaveBeenCalledTimes(1);
|
||||
expect(clickSpy).toHaveBeenCalledTimes(1);
|
||||
expect(revokeObjectURL).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('POSTs the media sample for a given id with a CSRF header', async () => {
|
||||
const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue(zipResponse('ersatztv-media-sample-123.zip'));
|
||||
stubBrowserDownload();
|
||||
|
||||
await downloadTroubleshootingMediaSample(42);
|
||||
|
||||
const [url, init] = fetchSpy.mock.calls[0];
|
||||
expect(url).toBe('/api/troubleshoot/playback/sample/42');
|
||||
expect((init?.method ?? 'GET').toUpperCase()).toBe('POST');
|
||||
expect(headerValue(init, 'X-Csrf')).toBe('1');
|
||||
});
|
||||
|
||||
it('throws an ApiError on a non-ok download response', async () => {
|
||||
vi.spyOn(window, 'fetch').mockResolvedValue(
|
||||
new Response(JSON.stringify({ status: 404, title: 'Not Found' }), {
|
||||
headers: { 'Content-Type': 'application/problem+json' },
|
||||
status: 404
|
||||
})
|
||||
);
|
||||
stubBrowserDownload();
|
||||
|
||||
await expect(downloadTroubleshootingArchive()).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,8 @@ export type TroubleshootingInfo = components['schemas']['TroubleshootingInfoResp
|
||||
export type ValidateScheduleResult = components['schemas']['ValidateSequentialScheduleResponseModel'];
|
||||
export type TroubleshootingSubtitle = components['schemas']['TroubleshootingSubtitleResponseModel'];
|
||||
export type TroubleshootingPlaybackStatus = components['schemas']['TroubleshootingPlaybackStatusResponseModel'];
|
||||
export type StartTroubleshootingPlaybackBody = components['schemas']['StartTroubleshootingPlaybackRequest'];
|
||||
export type TroubleshootingPlaybackStarted = components['schemas']['TroubleshootingPlaybackStartedResponseModel'];
|
||||
|
||||
export function getTroubleshootingInfo(): Promise<TroubleshootingInfo> {
|
||||
return request<TroubleshootingInfo>('/api/troubleshoot/info');
|
||||
@@ -28,6 +30,89 @@ export function getTroubleshootingPlaybackStatus(): Promise<TroubleshootingPlayb
|
||||
return request<TroubleshootingPlaybackStatus>('/api/troubleshoot/playback/status');
|
||||
}
|
||||
|
||||
// Start a troubleshooting playback session (#295 — was a GET on `playback.m3u8` that started the
|
||||
// session as a side effect of the manifest fetch; now an explicit POST with a JSON body). The server
|
||||
// blocks until the first segments exist, then returns the open `/iptv` live manifest URL to feed to
|
||||
// HlsPlayer. A 404/409/422 surfaces as an ApiError the caller can show inline.
|
||||
export function startTroubleshootingPlayback(
|
||||
body: StartTroubleshootingPlaybackBody
|
||||
): Promise<TroubleshootingPlaybackStarted> {
|
||||
return request<TroubleshootingPlaybackStarted>('/api/troubleshoot/playback/start', {
|
||||
body,
|
||||
method: 'POST'
|
||||
});
|
||||
}
|
||||
|
||||
// File-download endpoints — these return a binary zip, not JSON, so they must NOT go through
|
||||
// `request()` (which JSON-parses the body). Fetch directly with the CSRF header (both are POST since
|
||||
// #295), read the blob, and trigger a browser download. Same-origin fetch can read Content-Disposition
|
||||
// so we use the server-provided filename when present.
|
||||
export function downloadTroubleshootingArchive(): Promise<void> {
|
||||
return downloadViaPost('/api/troubleshoot/playback/archive', 'ersatztv-troubleshooting.zip');
|
||||
}
|
||||
|
||||
export function downloadTroubleshootingMediaSample(id: number): Promise<void> {
|
||||
return downloadViaPost(`/api/troubleshoot/playback/sample/${id}`, 'ersatztv-media-sample.zip');
|
||||
}
|
||||
|
||||
async function downloadViaPost(path: string, fallbackName: string): Promise<void> {
|
||||
const response = await fetch(path, { method: 'POST', headers: { 'X-Csrf': '1' } });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ApiError(response.status, await readProblemDetailsSafe(response));
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
const filename = filenameFromContentDisposition(response.headers.get('Content-Disposition'), fallbackName);
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
try {
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = objectUrl;
|
||||
anchor.download = filename;
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
} finally {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
}
|
||||
|
||||
async function readProblemDetailsSafe(response: Response): Promise<components['schemas']['ProblemDetails'] | undefined> {
|
||||
const contentType = response.headers.get('Content-Type') ?? '';
|
||||
if (!contentType.includes('application/json') && !contentType.includes('problem+json')) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
return (await response.json()) as components['schemas']['ProblemDetails'];
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Parse `filename="…"` / `filename*=UTF-8''…` from a Content-Disposition header, falling back when the
|
||||
// header is absent or unparseable.
|
||||
function filenameFromContentDisposition(header: null | string, fallback: string): string {
|
||||
if (!header) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const extended = /filename\*=(?:UTF-8'')?([^;]+)/i.exec(header);
|
||||
if (extended?.[1]) {
|
||||
try {
|
||||
return decodeURIComponent(extended[1].trim().replace(/^"|"$/g, ''));
|
||||
} catch {
|
||||
// fall through to the plain filename form
|
||||
}
|
||||
}
|
||||
|
||||
const plain = /filename="?([^";]+)"?/i.exec(header);
|
||||
if (plain?.[1]) {
|
||||
return plain[1].trim();
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function validateSequentialSchedule(yaml: string, isImport: boolean): Promise<ValidateScheduleResult> {
|
||||
return request<ValidateScheduleResult>('/api/troubleshoot/validate-schedule', {
|
||||
body: { yaml, isImport },
|
||||
|
||||
@@ -1,69 +1,138 @@
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { ReactNode } from 'react';
|
||||
import { ApiKeyScreen } from './ApiKeyScreen';
|
||||
import { AuthContext, type AuthContextValue } from '../AuthGate';
|
||||
|
||||
// The repurposed screen (#295) is a normal authenticated screen: it loads the machine key from
|
||||
// `/api/auth/machine-key` and, for local accounts, changes the password via `/api/auth/password`. Its
|
||||
// self-contained fetch mock (spa-conventions §6) covers only those two endpoints.
|
||||
function json(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
|
||||
}
|
||||
|
||||
function installFetch(options: { machineKey?: string; passwordStatus?: number } = {}) {
|
||||
const { machineKey = 'machine-secret', passwordStatus = 204 } = options;
|
||||
return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => {
|
||||
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
|
||||
if (url === '/api/auth/machine-key') {
|
||||
return Promise.resolve(json({ key: machineKey }));
|
||||
}
|
||||
if (url === '/api/auth/password') {
|
||||
if (passwordStatus >= 400) {
|
||||
return Promise.resolve(
|
||||
new Response(JSON.stringify({ status: passwordStatus, title: 'Unauthorized', detail: 'Wrong password.' }), {
|
||||
headers: { 'Content-Type': 'application/problem+json' },
|
||||
status: passwordStatus
|
||||
})
|
||||
);
|
||||
}
|
||||
return Promise.resolve(new Response(null, { status: passwordStatus }));
|
||||
}
|
||||
return Promise.resolve(json({}, 404));
|
||||
});
|
||||
}
|
||||
|
||||
function renderWith(method: string | null, children: ReactNode = <ApiKeyScreen />) {
|
||||
const value: AuthContextValue = {
|
||||
username: 'admin',
|
||||
method,
|
||||
signOut: () => {},
|
||||
requireLogin: () => {}
|
||||
};
|
||||
return render(<AuthContext.Provider value={value}>{children}</AuthContext.Provider>);
|
||||
}
|
||||
|
||||
describe('ApiKeyScreen', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
Object.assign(navigator, { clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it('renders and functions without any /api call', () => {
|
||||
const fetchSpy = vi.spyOn(window, 'fetch');
|
||||
it('shows the machine key masked by default, then reveals it', async () => {
|
||||
installFetch({ machineKey: 'machine-secret' });
|
||||
|
||||
render(<ApiKeyScreen />);
|
||||
renderWith('local');
|
||||
|
||||
expect(screen.getByText('No key')).toBeTruthy();
|
||||
expect(screen.getByText(/No key is stored in this browser/)).toBeTruthy();
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
// The masked code cell renders without leaking the key into the DOM.
|
||||
const cell = await screen.findByTestId('machine-key');
|
||||
expect(cell.textContent).not.toContain('machine-secret');
|
||||
expect(document.body.innerHTML).not.toContain('machine-secret');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Reveal/i }));
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('machine-key').textContent).toBe('machine-secret'));
|
||||
});
|
||||
|
||||
it('saves a pasted key to local storage and shows the key-set state', () => {
|
||||
render(<ApiKeyScreen />);
|
||||
it('copies the real machine key regardless of the masked state', async () => {
|
||||
installFetch({ machineKey: 'machine-secret' });
|
||||
|
||||
fireEvent.change(screen.getByLabelText('API key'), { target: { value: ' secret-123 ' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save key' }));
|
||||
renderWith('local');
|
||||
await screen.findByTestId('machine-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();
|
||||
fireEvent.click(screen.getByRole('button', { name: /Copy/i }));
|
||||
|
||||
expect(navigator.clipboard.writeText).toHaveBeenCalledWith('machine-secret');
|
||||
});
|
||||
|
||||
it('does not render the stored key value in plaintext', () => {
|
||||
window.localStorage.setItem('ctv-api-key', 'super-secret');
|
||||
it('renders the local-password card only for a local account', async () => {
|
||||
installFetch();
|
||||
|
||||
render(<ApiKeyScreen />);
|
||||
|
||||
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');
|
||||
renderWith('local');
|
||||
expect(await screen.findByText('Local admin password')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('clears a stored key', () => {
|
||||
window.localStorage.setItem('ctv-api-key', 'super-secret');
|
||||
it('hides the local-password card for a non-local (oidc) account', async () => {
|
||||
installFetch();
|
||||
|
||||
render(<ApiKeyScreen />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Clear key' }));
|
||||
|
||||
expect(window.localStorage.getItem('ctv-api-key')).toBeNull();
|
||||
expect(screen.getByText('No key')).toBeTruthy();
|
||||
renderWith('oidc');
|
||||
// Machine key card still loads.
|
||||
await screen.findByTestId('machine-key');
|
||||
expect(screen.queryByText('Local admin password')).toBeNull();
|
||||
});
|
||||
|
||||
it('ignores a save with only whitespace', () => {
|
||||
render(<ApiKeyScreen />);
|
||||
it('changes the password via /api/auth/password and confirms on success', async () => {
|
||||
const fetchSpy = installFetch({ passwordStatus: 204 });
|
||||
|
||||
const save = screen.getByRole('button', { name: 'Save key' });
|
||||
expect(save.hasAttribute('disabled')).toBe(true);
|
||||
renderWith('local');
|
||||
await screen.findByText('Local admin password');
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Current password'), { target: { value: 'old-pass' } });
|
||||
fireEvent.change(screen.getByLabelText('New password'), { target: { value: 'new-pass' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /Change password/i }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Password changed.')).toBeTruthy());
|
||||
|
||||
const passwordCall = fetchSpy.mock.calls.find((call) => call[0] === '/api/auth/password');
|
||||
expect(passwordCall).toBeTruthy();
|
||||
expect((passwordCall?.[1]?.method ?? 'GET').toUpperCase()).toBe('POST');
|
||||
expect(JSON.parse(String(passwordCall?.[1]?.body))).toEqual({ currentPassword: 'old-pass', newPassword: 'new-pass' });
|
||||
});
|
||||
|
||||
it('surfaces the ProblemDetails detail inline on a wrong-current-password 401', async () => {
|
||||
installFetch({ passwordStatus: 401 });
|
||||
|
||||
renderWith('local');
|
||||
await screen.findByText('Local admin password');
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Current password'), { target: { value: 'wrong' } });
|
||||
fireEvent.change(screen.getByLabelText('New password'), { target: { value: 'new-pass' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /Change password/i }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Wrong password.')).toBeTruthy());
|
||||
});
|
||||
|
||||
it('never touches the legacy ctv-api-key localStorage slot', async () => {
|
||||
installFetch();
|
||||
|
||||
renderWith('local');
|
||||
await screen.findByTestId('machine-key');
|
||||
|
||||
fireEvent.change(screen.getByLabelText('API key'), { target: { value: ' ' } });
|
||||
expect(save.hasAttribute('disabled')).toBe(true);
|
||||
expect(window.localStorage.getItem('ctv-api-key')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,99 +1,256 @@
|
||||
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';
|
||||
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
|
||||
import { Check, Copy, Eye, EyeOff, KeyRound, Lock, ShieldCheck, TriangleAlert } from 'lucide-react';
|
||||
import { Button, Card, Input, Spinner } from '../components';
|
||||
import { ApiError, changePassword, getMachineKey } from '../api';
|
||||
import { AuthContext } from '../AuthGate';
|
||||
|
||||
// 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);
|
||||
// Since #295 the browser authenticates with the session cookie, so this screen no longer bootstraps an
|
||||
// API key. It now MANAGES the server's machine key (for MCP / external REST clients) and — for local
|
||||
// admin accounts — offers a password change. It's a normal authenticated screen: it reads the machine
|
||||
// key from `/api/auth/machine-key` (a real `/api` call), unlike the old keyless localStorage-only shape.
|
||||
type KeyState =
|
||||
| { status: 'loading' }
|
||||
| { status: 'error'; message: string }
|
||||
| { status: 'success'; key: string };
|
||||
|
||||
const trimmed = draft.trim();
|
||||
function messageFromError(error: unknown, fallback: string): string {
|
||||
if (error instanceof ApiError) {
|
||||
return error.detail ?? error.message;
|
||||
}
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const save = () => {
|
||||
if (trimmed.length === 0) {
|
||||
return;
|
||||
}
|
||||
function CopyButton({ text }: { text: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
setStoredApiKey(trimmed);
|
||||
setHasKey(true);
|
||||
setDraft('');
|
||||
setJustSaved(true);
|
||||
};
|
||||
|
||||
const clear = () => {
|
||||
clearStoredApiKey();
|
||||
setHasKey(false);
|
||||
setJustSaved(false);
|
||||
const copy = () => {
|
||||
void navigator.clipboard?.writeText(text).then(() => {
|
||||
setCopied(true);
|
||||
window.setTimeout(() => setCopied(false), 1500);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="ctv-collections">
|
||||
<Card
|
||||
actions={
|
||||
hasKey ? (
|
||||
<Badge tone="ok">Key set</Badge>
|
||||
) : (
|
||||
<Badge tone="warn">No key</Badge>
|
||||
)
|
||||
<Button
|
||||
onClick={copy}
|
||||
size="sm"
|
||||
startIcon={copied ? <Check aria-hidden="true" size={14} /> : <Copy aria-hidden="true" size={14} />}
|
||||
variant="secondary"
|
||||
>
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function MachineKeyCard() {
|
||||
const [state, setState] = useState<KeyState>({ status: 'loading' });
|
||||
const [revealed, setRevealed] = useState(false);
|
||||
const activeRef = useRef(true);
|
||||
const seqRef = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
activeRef.current = true;
|
||||
return () => {
|
||||
activeRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
// State transitions live in the promise callbacks (never synchronously in the effect body) per
|
||||
// docs/spa-conventions.md §3.
|
||||
const load = useCallback(() => {
|
||||
const seq = ++seqRef.current;
|
||||
getMachineKey()
|
||||
.then((result) => {
|
||||
if (!activeRef.current || seq !== seqRef.current) {
|
||||
return;
|
||||
}
|
||||
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 ? (
|
||||
<div className="ctv-settings-warn-callout" role="status" style={{ borderColor: 'var(--status-ok)' }}>
|
||||
<ShieldCheck aria-hidden="true" color="var(--status-ok)" size={15} />
|
||||
<span>A key is stored in this browser. It's sent with every request to this server.</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="ctv-settings-warn-callout" role="status">
|
||||
<TriangleAlert aria-hidden="true" color="var(--status-warn)" size={15} />
|
||||
<span>No key is stored in this browser, so requests to this server will be rejected. Paste your key to continue.</span>
|
||||
</div>
|
||||
)}
|
||||
setState({ status: 'success', key: result.key });
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!activeRef.current || seq !== seqRef.current) {
|
||||
return;
|
||||
}
|
||||
setState({ status: 'error', message: messageFromError(error, 'Unable to load the machine key') });
|
||||
});
|
||||
}, []);
|
||||
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<Input
|
||||
label={hasKey ? 'Replace key' : 'API key'}
|
||||
leadingIcon={<KeyRound aria-hidden="true" size={14} />}
|
||||
onChange={(event) => {
|
||||
setDraft(event.target.value);
|
||||
setJustSaved(false);
|
||||
}}
|
||||
placeholder="Paste the contents of /config/api.key"
|
||||
style={{ fontFamily: 'var(--font-mono)' }}
|
||||
type="password"
|
||||
value={draft}
|
||||
/>
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
return (
|
||||
<Card
|
||||
padded
|
||||
subtitle="This key authenticates MCP and external REST clients. The browser no longer uses it — you sign in with your account instead."
|
||||
title="Machine API Key"
|
||||
>
|
||||
{state.status === 'loading' && (
|
||||
<div className="ctv-collections-loading" role="status">
|
||||
<Spinner size={16} />
|
||||
<span>Loading machine key…</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="ctv-channels-actionbar" style={{ marginTop: 16 }}>
|
||||
{justSaved && (
|
||||
<span style={{ alignItems: 'center', color: 'var(--status-ok)', display: 'inline-flex', gap: 6 }}>
|
||||
<Check aria-hidden="true" size={14} />
|
||||
<span>Key saved — reload a screen to load its data.</span>
|
||||
</span>
|
||||
)}
|
||||
{state.status === 'error' && (
|
||||
<div className="ctv-channels-error" role="alert">
|
||||
<TriangleAlert aria-hidden="true" size={15} />
|
||||
<span>{state.message}</span>
|
||||
<span className="ctv-channels-spacer" />
|
||||
{hasKey && (
|
||||
<Button onClick={clear} startIcon={<Trash2 aria-hidden="true" size={14} />} variant="ghost">
|
||||
Clear key
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
disabled={trimmed.length === 0}
|
||||
onClick={save}
|
||||
startIcon={<Check aria-hidden="true" size={14} />}
|
||||
variant="primary"
|
||||
onClick={() => {
|
||||
setState({ status: 'loading' });
|
||||
load();
|
||||
}}
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
>
|
||||
Save key
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{state.status === 'success' && (
|
||||
<>
|
||||
<div className="ctv-settings-warn-callout" role="status" style={{ borderColor: 'var(--status-ok)' }}>
|
||||
<ShieldCheck aria-hidden="true" color="var(--status-ok)" size={15} />
|
||||
<span>Give this key to an MCP server or external REST client to let it call this server's API.</span>
|
||||
</div>
|
||||
|
||||
<div className="ctv-field ctv-field-full" style={{ marginTop: 16 }}>
|
||||
<span className="ctv-field-label">Machine key</span>
|
||||
<span className="ctv-field-frame" style={{ fontFamily: 'var(--font-mono)' }}>
|
||||
<span className="ctv-field-icon">
|
||||
<KeyRound aria-hidden="true" size={14} />
|
||||
</span>
|
||||
{/* Masked by default: the real key is never in the DOM until Reveal — Copy always copies
|
||||
the real value regardless of the masked/revealed toggle. */}
|
||||
<code
|
||||
aria-label="Machine key"
|
||||
data-testid="machine-key"
|
||||
style={{ flex: 1, overflowX: 'auto', whiteSpace: 'nowrap' }}
|
||||
>
|
||||
{revealed ? state.key : '••••••••••••••••••••••••'}
|
||||
</code>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="ctv-channels-actionbar" style={{ marginTop: 16 }}>
|
||||
<span className="ctv-channels-spacer" />
|
||||
<Button
|
||||
onClick={() => setRevealed((current) => !current)}
|
||||
size="sm"
|
||||
startIcon={revealed ? <EyeOff aria-hidden="true" size={14} /> : <Eye aria-hidden="true" size={14} />}
|
||||
variant="ghost"
|
||||
>
|
||||
{revealed ? 'Hide' : 'Reveal'}
|
||||
</Button>
|
||||
<CopyButton text={state.key} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function LocalPasswordCard() {
|
||||
const [currentPassword, setCurrentPassword] = useState('');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<null | string>(null);
|
||||
const [justSaved, setJustSaved] = useState(false);
|
||||
|
||||
const canSubmit = currentPassword.length > 0 && newPassword.length > 0 && !saving;
|
||||
|
||||
const submit = async () => {
|
||||
if (!canSubmit) {
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
setJustSaved(false);
|
||||
try {
|
||||
await changePassword(currentPassword, newPassword);
|
||||
setCurrentPassword('');
|
||||
setNewPassword('');
|
||||
setJustSaved(true);
|
||||
} catch (err: unknown) {
|
||||
// A 401 is the expected wrong-current-password answer — surface its ProblemDetails detail inline.
|
||||
if (err instanceof ApiError && err.status === 401) {
|
||||
setError(err.detail ?? 'Your current password is incorrect.');
|
||||
} else {
|
||||
setError(messageFromError(err, 'Unable to change your password'));
|
||||
}
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card padded subtitle="Change the password for your local admin account." title="Local admin password">
|
||||
{error && (
|
||||
<div className="ctv-settings-warn-callout" role="alert">
|
||||
<TriangleAlert aria-hidden="true" color="var(--status-warn)" size={15} />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ marginTop: error ? 16 : 0 }}>
|
||||
<Input
|
||||
label="Current password"
|
||||
leadingIcon={<Lock aria-hidden="true" size={14} />}
|
||||
onChange={(event) => {
|
||||
setCurrentPassword(event.target.value);
|
||||
setJustSaved(false);
|
||||
}}
|
||||
type="password"
|
||||
value={currentPassword}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<Input
|
||||
label="New password"
|
||||
leadingIcon={<Lock aria-hidden="true" size={14} />}
|
||||
onChange={(event) => {
|
||||
setNewPassword(event.target.value);
|
||||
setJustSaved(false);
|
||||
}}
|
||||
type="password"
|
||||
value={newPassword}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="ctv-channels-actionbar" style={{ marginTop: 16 }}>
|
||||
{justSaved && (
|
||||
<span style={{ alignItems: 'center', color: 'var(--status-ok)', display: 'inline-flex', gap: 6 }}>
|
||||
<Check aria-hidden="true" size={14} />
|
||||
<span>Password changed.</span>
|
||||
</span>
|
||||
)}
|
||||
<span className="ctv-channels-spacer" />
|
||||
<Button
|
||||
disabled={!canSubmit}
|
||||
onClick={() => void submit()}
|
||||
startIcon={<Check aria-hidden="true" size={14} />}
|
||||
variant="primary"
|
||||
>
|
||||
{saving ? 'Changing…' : 'Change password'}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function ApiKeyScreen() {
|
||||
const { method } = useContext(AuthContext);
|
||||
|
||||
return (
|
||||
<div className="ctv-collections" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
<MachineKeyCard />
|
||||
{method === 'local' && <LocalPasswordCard />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -39,11 +39,43 @@ function json(body: unknown, status = 200): Response {
|
||||
|
||||
const IDLE: Status = { state: 'idle', exitCode: null, speed: null, logs: null };
|
||||
|
||||
// The open `/iptv` live manifest the start endpoint returns (was the manifest GET's own URL pre-#295).
|
||||
const LIVE_MANIFEST = '/iptv/session/.troubleshooting/live.m3u8';
|
||||
|
||||
function zipResponse(): Response {
|
||||
return new Response(new Blob(['zip-bytes']), {
|
||||
headers: { 'Content-Type': 'application/zip', 'Content-Disposition': 'attachment; filename="out.zip"' },
|
||||
status: 200
|
||||
});
|
||||
}
|
||||
|
||||
// A fetch stub keyed by URL. `statusRef.current` lets a test flip the polled status over time.
|
||||
function installFetch(statusRef: { current: Status }) {
|
||||
return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => {
|
||||
// `startBody` captures the POSTed start-playback body; `startStatus` lets a test force a start error.
|
||||
function installFetch(
|
||||
statusRef: { current: Status },
|
||||
options: { startStatus?: number; startBody?: { current: unknown } } = {}
|
||||
) {
|
||||
return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
|
||||
|
||||
if (url === '/api/troubleshoot/playback/start') {
|
||||
if (options.startBody) {
|
||||
options.startBody.current = init?.body ? JSON.parse(String(init.body)) : null;
|
||||
}
|
||||
if (options.startStatus && options.startStatus >= 400) {
|
||||
return Promise.resolve(
|
||||
new Response(JSON.stringify({ status: options.startStatus, title: 'Conflict', detail: 'Another session is running.' }), {
|
||||
headers: { 'Content-Type': 'application/problem+json' },
|
||||
status: options.startStatus
|
||||
})
|
||||
);
|
||||
}
|
||||
return Promise.resolve(json({ url: LIVE_MANIFEST }));
|
||||
}
|
||||
if (url === '/api/troubleshoot/playback/archive' || url.startsWith('/api/troubleshoot/playback/sample/')) {
|
||||
return Promise.resolve(zipResponse());
|
||||
}
|
||||
|
||||
if (url.startsWith('/api/ffmpeg/profiles')) {
|
||||
return Promise.resolve(json([{ id: 1, name: 'Default' }, { id: 2, name: 'Hardware' }]));
|
||||
}
|
||||
@@ -155,10 +187,11 @@ describe('PlaybackTroubleshootingScreen', () => {
|
||||
expect(screen.queryByText('Seek Seconds')).toBeNull();
|
||||
});
|
||||
|
||||
it('sends the channel profile id (not 0) in the channel-mode playback URL', async () => {
|
||||
it('sends the channel profile id (not 0) in the channel-mode start body', async () => {
|
||||
setLocation('/app/troubleshooting/playback?channel=7');
|
||||
const statusRef = { current: IDLE };
|
||||
installFetch(statusRef);
|
||||
const startBody = { current: null as unknown };
|
||||
installFetch(statusRef, { startBody });
|
||||
|
||||
render(<PlaybackTroubleshootingScreen />);
|
||||
await screen.findByText(/Channel Settings — Channel Seven/i);
|
||||
@@ -172,21 +205,26 @@ describe('PlaybackTroubleshootingScreen', () => {
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
|
||||
|
||||
expect(hlsMock.loadSource).toHaveBeenCalledTimes(1);
|
||||
const params = new URLSearchParams(String(hlsMock.loadSource.mock.calls[0][0]).split('?')[1]);
|
||||
// The start endpoint returns the live manifest, which is fed to hls.js.
|
||||
await waitFor(() => expect(hlsMock.loadSource).toHaveBeenCalledWith(LIVE_MANIFEST));
|
||||
|
||||
// The regression this pins: the runtime channel JSON key is ffmpegProfileId (#198). Before the
|
||||
// spec was aligned, reading the spec-cased fFmpegProfileId left the profile null and the URL
|
||||
// spec was aligned, reading the spec-cased fFmpegProfileId left the profile null and the body
|
||||
// fell back to ffmpegProfile=0.
|
||||
expect(params.get('ffmpegProfile')).toBe('2');
|
||||
expect(params.get('channel')).toBe('7');
|
||||
expect(params.get('start')).toBe(new Date('2026-07-09T20:00').toISOString());
|
||||
expect(params.get('mediaItem')).toBeNull();
|
||||
expect(startBody.current).toMatchObject({
|
||||
ffmpegProfile: 2,
|
||||
channel: 7,
|
||||
mediaItem: 0,
|
||||
streamingMode: 'HttpLiveStreamingSegmenter',
|
||||
start: new Date('2026-07-09T20:00').toISOString()
|
||||
});
|
||||
});
|
||||
|
||||
it('builds the correct playback.m3u8 query on Play and starts polling', async () => {
|
||||
it('POSTs the correct start body on Play, feeds the returned manifest to hls.js, and starts polling', async () => {
|
||||
setLocation('/app/troubleshooting/playback?mediaItem=5');
|
||||
const statusRef = { current: IDLE };
|
||||
installFetch(statusRef);
|
||||
const startBody = { current: null as unknown };
|
||||
installFetch(statusRef, { startBody });
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
@@ -198,15 +236,16 @@ describe('PlaybackTroubleshootingScreen', () => {
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
|
||||
|
||||
expect(hlsMock.loadSource).toHaveBeenCalledTimes(1);
|
||||
const url = String(hlsMock.loadSource.mock.calls[0][0]);
|
||||
expect(url.startsWith('/api/troubleshoot/playback.m3u8?')).toBe(true);
|
||||
const params = new URLSearchParams(url.split('?')[1]);
|
||||
expect(params.get('ffmpegProfile')).toBe('1');
|
||||
expect(params.get('streamingMode')).toBe('4');
|
||||
expect(params.get('mediaItem')).toBe('5');
|
||||
expect(params.get('seekSeconds')).toBe('1200'); // 40 min / 2
|
||||
expect(params.get('channel')).toBeNull();
|
||||
// The POST resolves with the live manifest, which is handed to hls.js.
|
||||
await vi.waitFor(() => expect(hlsMock.loadSource).toHaveBeenCalledWith(LIVE_MANIFEST));
|
||||
|
||||
expect(startBody.current).toMatchObject({
|
||||
ffmpegProfile: 1,
|
||||
streamingMode: 'HttpLiveStreamingSegmenter',
|
||||
mediaItem: 5,
|
||||
channel: 0,
|
||||
seekSeconds: 1200 // 40 min / 2
|
||||
});
|
||||
|
||||
// Polling picks up the running status → Play becomes disabled.
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
@@ -216,6 +255,22 @@ describe('PlaybackTroubleshootingScreen', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('surfaces the ProblemDetails detail and returns to idle when start fails (409)', async () => {
|
||||
setLocation('/app/troubleshooting/playback?mediaItem=5');
|
||||
const statusRef = { current: IDLE };
|
||||
installFetch(statusRef, { startStatus: 409 });
|
||||
|
||||
render(<PlaybackTroubleshootingScreen />);
|
||||
await screen.findByText(/Movie Settings/i);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
|
||||
|
||||
// 409 detail surfaces via the notice, and Play returns to the idle (enabled) phase.
|
||||
await waitFor(() => expect(screen.getByText('Another session is running.')).toBeTruthy());
|
||||
await waitFor(() => expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(false));
|
||||
expect(hlsMock.loadSource).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('surfaces logs and a speed badge when polling transitions running → completed', async () => {
|
||||
setLocation('/app/troubleshooting/playback?mediaItem=5');
|
||||
const statusRef = { current: IDLE };
|
||||
@@ -256,10 +311,11 @@ describe('PlaybackTroubleshootingScreen', () => {
|
||||
render(<PlaybackTroubleshootingScreen />);
|
||||
await vi.waitFor(() => expect(screen.getByText(/Movie Settings/i)).toBeTruthy());
|
||||
|
||||
// First play through to completion.
|
||||
// First play through to completion. The start POST resolves with the constant live manifest.
|
||||
statusRef.current = { state: 'running', exitCode: null, speed: null, logs: null };
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
|
||||
expect(hlsMock.loadSource).toHaveBeenCalledTimes(1);
|
||||
await vi.waitFor(() => expect(hlsMock.loadSource).toHaveBeenCalledTimes(1));
|
||||
expect(hlsMock.loadSource.mock.calls[0][0]).toBe(LIVE_MANIFEST);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000); // observe running
|
||||
statusRef.current = { state: 'completed', exitCode: 0, speed: 1.1, logs: 'done' };
|
||||
@@ -268,10 +324,11 @@ describe('PlaybackTroubleshootingScreen', () => {
|
||||
expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(false)
|
||||
);
|
||||
|
||||
// Repeat Play with untouched settings: identical URL, but the manifest request MUST fire
|
||||
// again (the GET is what starts a session server-side).
|
||||
// Repeat Play with untouched settings: the manifest URL is identical, but HlsPlayer MUST
|
||||
// re-attach (the playToken bump) so the returned live manifest is re-requested.
|
||||
statusRef.current = { state: 'running', exitCode: null, speed: null, logs: null };
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
|
||||
expect(hlsMock.loadSource).toHaveBeenCalledTimes(2);
|
||||
await vi.waitFor(() => expect(hlsMock.loadSource).toHaveBeenCalledTimes(2));
|
||||
expect(hlsMock.loadSource.mock.calls[1][0]).toBe(hlsMock.loadSource.mock.calls[0][0]);
|
||||
expect(hlsMock.destroy).toHaveBeenCalled(); // previous instance torn down before re-attach
|
||||
} finally {
|
||||
@@ -345,20 +402,32 @@ describe('PlaybackTroubleshootingScreen', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('opens the archive and media-sample downloads, gated while a session is active', async () => {
|
||||
it('downloads the archive and media sample via a POST-blob fetch (never a browser tab), gated while active', async () => {
|
||||
setLocation('/app/troubleshooting/playback?mediaItem=5');
|
||||
const statusRef = { current: IDLE };
|
||||
installFetch(statusRef);
|
||||
const fetchSpy = installFetch(statusRef);
|
||||
// Never open a download endpoint in a browser tab.
|
||||
const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
|
||||
// jsdom lacks these on URL — stub the object-URL/anchor-click download path.
|
||||
(URL as unknown as { createObjectURL: unknown }).createObjectURL = vi.fn(() => 'blob:mock');
|
||||
(URL as unknown as { revokeObjectURL: unknown }).revokeObjectURL = vi.fn();
|
||||
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
|
||||
|
||||
const postCall = (path: string) =>
|
||||
fetchSpy.mock.calls.find(
|
||||
(call) => call[0] === path && (call[1]?.method ?? 'GET').toUpperCase() === 'POST'
|
||||
);
|
||||
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
render(<PlaybackTroubleshootingScreen />);
|
||||
await vi.waitFor(() => expect(screen.getByText(/Movie Settings/i)).toBeTruthy());
|
||||
|
||||
// Download Media Sample is available while idle.
|
||||
// Download Media Sample is available while idle → POST-blob, not window.open.
|
||||
fireEvent.click(screen.getByRole('button', { name: /Download Media Sample/i }));
|
||||
expect(openSpy).toHaveBeenCalledWith('/api/troubleshoot/playback/sample/5');
|
||||
await vi.waitFor(() => expect(postCall('/api/troubleshoot/playback/sample/5')).toBeTruthy());
|
||||
expect(openSpy).not.toHaveBeenCalled();
|
||||
|
||||
// Both downloads are gated while a session is starting/running.
|
||||
statusRef.current = { state: 'running', exitCode: null, speed: null, logs: null };
|
||||
@@ -366,15 +435,18 @@ describe('PlaybackTroubleshootingScreen', () => {
|
||||
expect((screen.getByRole('button', { name: /Download Results/i }) as HTMLButtonElement).disabled).toBe(true);
|
||||
expect((screen.getByRole('button', { name: /Download Media Sample/i }) as HTMLButtonElement).disabled).toBe(true);
|
||||
|
||||
// Run to completion → Download Results enabled (hasPlayed && not busy).
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
// Drive to completion so Download Results enables (hasPlayed && not busy).
|
||||
await vi.advanceTimersByTimeAsync(2000); // observe running
|
||||
statusRef.current = { state: 'completed', exitCode: 0, speed: 1, logs: 'done' };
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await vi.advanceTimersByTimeAsync(2000); // observe completed
|
||||
await vi.waitFor(() =>
|
||||
expect((screen.getByRole('button', { name: /Download Results/i }) as HTMLButtonElement).disabled).toBe(false)
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Download Results/i }));
|
||||
expect(openSpy).toHaveBeenCalledWith('/api/troubleshoot/playback/archive');
|
||||
await vi.waitFor(() => expect(postCall('/api/troubleshoot/playback/archive')).toBeTruthy());
|
||||
expect(clickSpy).toHaveBeenCalled();
|
||||
expect(openSpy).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } fro
|
||||
import { Download, DownloadCloud, PlayCircle, Stethoscope, TriangleAlert } from 'lucide-react';
|
||||
import { Button, Card, Checkbox, Input, Select, Spinner, Toast } from '../components';
|
||||
import {
|
||||
downloadTroubleshootingArchive,
|
||||
downloadTroubleshootingMediaSample,
|
||||
getChannelById,
|
||||
getFFmpegProfiles,
|
||||
getGraphicsElements,
|
||||
@@ -11,10 +13,12 @@ import {
|
||||
getTroubleshootingSubtitles,
|
||||
getWatermarks,
|
||||
messageFromTroubleshootError,
|
||||
startTroubleshootingPlayback,
|
||||
type Channel,
|
||||
type FFmpegProfile,
|
||||
type GraphicsElement,
|
||||
type MediaItemInfo,
|
||||
type StartTroubleshootingPlaybackBody,
|
||||
type TroubleshootingPlaybackStatus,
|
||||
type TroubleshootingSubtitle,
|
||||
type Watermark
|
||||
@@ -23,8 +27,9 @@ import { HlsPlayer } from '../media/HlsPlayer';
|
||||
import { parseDurationSeconds } from '../media/mediaKinds';
|
||||
|
||||
// StreamingMode.HttpLiveStreamingSegmenter — mirrors PlaybackTroubleshooting.razor, which always
|
||||
// requests the segmenter mode for troubleshooting playback.
|
||||
const STREAMING_MODE_HLS_SEGMENTER = 4;
|
||||
// requests the segmenter mode for troubleshooting playback. The start endpoint takes the StreamingMode
|
||||
// as its serialized enum name (the generated request type is a string union), not the numeric value.
|
||||
const STREAMING_MODE_HLS_SEGMENTER: StartTroubleshootingPlaybackBody['streamingMode'] = 'HttpLiveStreamingSegmenter';
|
||||
const STATUS_POLL_MS = 2000;
|
||||
// How long after Play we keep waiting for the server to report 'running' before giving up.
|
||||
// PrepareTroubleshootingPlayback runs several DB queries before it takes the playback lock, so the
|
||||
@@ -364,15 +369,48 @@ export function PlaybackTroubleshootingScreen() {
|
||||
// Busy = a session this screen is aware of is starting or transcoding; gates Play + downloads.
|
||||
const isBusy = playPhase !== 'idle';
|
||||
|
||||
// Build the playback.m3u8 query string, mirroring PlaybackTroubleshooting.razor PreviewChannel.
|
||||
const buildPlaybackUrl = useCallback((): null | string => {
|
||||
// Sending ffmpegProfile=0 is always wrong (no such profile) — refuse to build a URL without one.
|
||||
const onDownloadArchive = async () => {
|
||||
try {
|
||||
await downloadTroubleshootingArchive();
|
||||
} catch (error: unknown) {
|
||||
setNotice({ tone: 'error', message: messageFromTroubleshootError(error, 'Unable to download results') });
|
||||
}
|
||||
};
|
||||
|
||||
const onDownloadMediaSample = async (id: number) => {
|
||||
try {
|
||||
await downloadTroubleshootingMediaSample(id);
|
||||
} catch (error: unknown) {
|
||||
setNotice({ tone: 'error', message: messageFromTroubleshootError(error, 'Unable to download media sample') });
|
||||
}
|
||||
};
|
||||
|
||||
// Build the start-playback request body, mirroring PlaybackTroubleshooting.razor PreviewChannel.
|
||||
// Returns null on invalid input (no profile, or a channel without a valid start datetime) — the same
|
||||
// guard the old URL builder used; Play is also disabled in those states so null is defensive.
|
||||
const buildPlaybackParams = useCallback((): StartTroubleshootingPlaybackBody | null => {
|
||||
// Sending ffmpegProfile=0 is always wrong (no such profile) — refuse without one.
|
||||
if (form.ffmpegProfileId == null) {
|
||||
return null;
|
||||
}
|
||||
const params = new URLSearchParams();
|
||||
params.set('ffmpegProfile', String(form.ffmpegProfileId));
|
||||
params.set('streamingMode', String(STREAMING_MODE_HLS_SEGMENTER));
|
||||
|
||||
// Stream selector and subtitle are mutually exclusive (selector wins).
|
||||
let streamSelector: null | string = null;
|
||||
let subtitleId: null | number = null;
|
||||
if (form.streamSelector !== '') {
|
||||
streamSelector = form.streamSelector;
|
||||
} else if (form.subtitleId != null) {
|
||||
subtitleId = form.subtitleId;
|
||||
}
|
||||
|
||||
const common = {
|
||||
ffmpegProfile: form.ffmpegProfileId,
|
||||
streamingMode: STREAMING_MODE_HLS_SEGMENTER,
|
||||
watermark: form.watermarkIds,
|
||||
graphicsElement: form.graphicsElementIds,
|
||||
streamSelector,
|
||||
subtitleId
|
||||
};
|
||||
|
||||
if (mode.kind === 'channel') {
|
||||
if (form.startValue === '') {
|
||||
@@ -382,35 +420,31 @@ export function PlaybackTroubleshootingScreen() {
|
||||
if (Number.isNaN(parsed.getTime())) {
|
||||
return null;
|
||||
}
|
||||
params.set('channel', String(mode.channelId));
|
||||
params.set('start', parsed.toISOString());
|
||||
} else if (mode.kind === 'media') {
|
||||
params.set('mediaItem', String(mode.mediaItemId));
|
||||
params.set('seekSeconds', String(form.seekSeconds));
|
||||
} else {
|
||||
return null;
|
||||
return {
|
||||
...common,
|
||||
mediaItem: 0,
|
||||
channel: mode.channelId,
|
||||
seekSeconds: 0,
|
||||
start: parsed.toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
for (const id of form.watermarkIds) {
|
||||
params.append('watermark', String(id));
|
||||
}
|
||||
for (const id of form.graphicsElementIds) {
|
||||
params.append('graphicsElement', String(id));
|
||||
if (mode.kind === 'media') {
|
||||
return {
|
||||
...common,
|
||||
mediaItem: mode.mediaItemId,
|
||||
channel: 0,
|
||||
seekSeconds: form.seekSeconds,
|
||||
start: null
|
||||
};
|
||||
}
|
||||
|
||||
// Stream selector and subtitle are mutually exclusive (selector wins).
|
||||
if (form.streamSelector !== '') {
|
||||
params.set('streamSelector', form.streamSelector);
|
||||
} else if (form.subtitleId != null) {
|
||||
params.set('subtitleId', String(form.subtitleId));
|
||||
}
|
||||
|
||||
return `/api/troubleshoot/playback.m3u8?${params.toString()}`;
|
||||
return null;
|
||||
}, [form, mode]);
|
||||
|
||||
const onPlay = () => {
|
||||
const url = buildPlaybackUrl();
|
||||
if (url === null) {
|
||||
const onPlay = async () => {
|
||||
const body = buildPlaybackParams();
|
||||
if (body === null) {
|
||||
return;
|
||||
}
|
||||
setNotice(null);
|
||||
@@ -418,10 +452,29 @@ export function PlaybackTroubleshootingScreen() {
|
||||
setPhase('starting');
|
||||
startingSinceRef.current = Date.now();
|
||||
setHasPlayed(true);
|
||||
setPlayerSrc(url);
|
||||
// Bump the token so HlsPlayer re-attaches even when the URL is identical to the previous play.
|
||||
setPlayToken((current) => current + 1);
|
||||
startPolling();
|
||||
|
||||
try {
|
||||
const result = await startTroubleshootingPlayback(body);
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
// The start endpoint returns the open `/iptv` live manifest — feed it to HlsPlayer. The URL is
|
||||
// constant across plays, so bump the token to force a re-attach even on a repeat play.
|
||||
setPlayerSrc(result.url);
|
||||
setPlayToken((current) => current + 1);
|
||||
} catch (error: unknown) {
|
||||
if (!activeRef.current) {
|
||||
return;
|
||||
}
|
||||
// A 409 (another session running) / 404 / 422 now surfaces its ProblemDetails detail inline.
|
||||
stopPolling();
|
||||
setPhase('idle');
|
||||
setNotice({
|
||||
tone: 'error',
|
||||
message: messageFromTroubleshootError(error, 'Unable to start troubleshooting playback')
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (mode.kind === 'empty') {
|
||||
@@ -506,7 +559,7 @@ export function PlaybackTroubleshootingScreen() {
|
||||
<div className="ctv-channels-actionbar">
|
||||
<Button
|
||||
disabled={!hasPlayed || downloadsDisabled}
|
||||
onClick={() => window.open('/api/troubleshoot/playback/archive')}
|
||||
onClick={() => void onDownloadArchive()}
|
||||
size="sm"
|
||||
startIcon={<Download aria-hidden="true" size={14} />}
|
||||
variant="secondary"
|
||||
@@ -516,7 +569,7 @@ export function PlaybackTroubleshootingScreen() {
|
||||
{mode.kind === 'media' && (
|
||||
<Button
|
||||
disabled={downloadsDisabled}
|
||||
onClick={() => window.open(`/api/troubleshoot/playback/sample/${mode.mediaItemId}`)}
|
||||
onClick={() => void onDownloadMediaSample(mode.mediaItemId)}
|
||||
size="sm"
|
||||
startIcon={<DownloadCloud aria-hidden="true" size={14} />}
|
||||
variant="secondary"
|
||||
@@ -627,7 +680,7 @@ export function PlaybackTroubleshootingScreen() {
|
||||
<Card padded subtitle="Live segmenter output" title="Preview">
|
||||
<Button
|
||||
disabled={isBusy || form.ffmpegProfileId == null || (isChannelMode && form.startValue === '')}
|
||||
onClick={onPlay}
|
||||
onClick={() => void onPlay()}
|
||||
startIcon={<PlayCircle aria-hidden="true" size={15} />}
|
||||
variant="primary"
|
||||
>
|
||||
|
||||
Reference in New Issue
Block a user