Suno-style web UI for a self-hosted MiniMax-Music3 inference server
TypeScript ai-musicdiffusersdockerexpressminimaxminimax-musicmusic-generationreactself-hostedsgl-omnisunotailwindcsstext-to-musictypescriptvite
Prompt for UI server token after 401
Adam B.4338abef9bbd
diff --git a/README.md b/README.mdindex c1cd317..35a52c9 100644--- a/README.md+++ b/README.md@@ -119,7 +119,7 @@ The inference server address is resolved in this order:| Variable | Default | Description ||---|---|---|-| `UI_TOKEN` | – | Optional shared token that protects every `/api/*` route; use a random value of at least 32 characters. The UI does not show a token prompt yet; a follow-up will add one. Scripts should send `Authorization: Bearer $UI_TOKEN`; browser clients can exchange the token at `POST /api/auth` for an HttpOnly session cookie. |+| `UI_TOKEN` | – | Optional shared token that protects every `/api/*` route; use a random value of at least 32 characters. The UI prompts for it after its first unauthorized API request and exchanges it at `POST /api/auth` for an HttpOnly session cookie. Scripts should send `Authorization: Bearer $UI_TOKEN`. || `MUSIC_API` | – | Base URL of the inference server, path prefix allowed, e.g. `http://host:8000` (overrides Settings) || `MUSIC_API_KEY` | – | Sent as `Authorization: Bearer …` if the inference server was started with `--api-key` (overrides Settings) || `LLM_API` | – | OpenAI-compatible base URL incl. `/v1` for prompt enhancement, e.g. `https://api.openai.com/v1`, `http://localhost:11434/v1` (overrides Settings) |@@ -163,7 +163,7 @@ docker run --read-only -p 8787:8787 minimax-music-ui-demo## UI server API-When `UI_TOKEN` is set, all API routes require a bearer token or the session cookie from `POST /api/auth`, except `POST /api/auth` itself and `GET /api/ping`. The auth endpoint accepts `{"token":"..."}` and sets an `HttpOnly; SameSite=Strict; Path=/api` cookie (plus `Secure` over HTTPS). The UI has no token prompt yet, so a browser needs that cookie; scripts can use the bearer header directly.+When `UI_TOKEN` is set, all API routes require a bearer token or the session cookie from `POST /api/auth`, except `POST /api/auth` itself and `GET /api/ping`. The auth endpoint accepts `{"token":"..."}` and sets an `HttpOnly; SameSite=Strict; Path=/api` cookie (plus `Secure` over HTTPS). The UI prompts when an API request is unauthorized, then reuses the cookie; scripts can use the bearer header directly.| Method | Path | Description ||---|---|---|diff --git a/web/src/App.tsx b/web/src/App.tsxindex 4c1e3ab..8518244 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -1,5 +1,5 @@-import { useCallback, useEffect, useMemo, useState } from 'react';-import { api } from './api';+import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent, type KeyboardEvent } from 'react';+import { api, setAuthPromptHandler } from './api';import { useHealth, useLibrary } from './hooks/usePolling';import { isInflight, type GenerateInput, type Track } from './types';import { Sidebar, type View } from './components/Sidebar';@@ -28,10 +28,46 @@ export default function App() {const [activeId, setActiveId] = useState<string | null>(null);const [selectedId, setSelectedId] = useState<string | null>(null);const [playing, setPlaying] = useState(false);+ const [authPromptOpen, setAuthPromptOpen] = useState(false);+ const [authToken, setAuthToken] = useState('');+ const [authError, setAuthError] = useState<string | null>(null);+ const [authSubmitting, setAuthSubmitting] = useState(false);+ const authPending = useRef<{ resolve: () => void; reject: (reason: Error) => void } | null>(null);+ const authInput = useRef<HTMLInputElement>(null);+ const authDialog = useRef<HTMLElement>(null);+ const authReturnFocus = useRef<HTMLElement | null>(null);++ const requestAuthentication = useCallback(() => new Promise<void>((resolve, reject) => {+ const activeElement = document.activeElement;+ authReturnFocus.current = activeElement instanceof HTMLElement && activeElement !== document.body ? activeElement : null;+ setAuthToken('');+ setAuthError(null);+ setAuthPromptOpen(true);+ authPending.current = { resolve, reject };+ }), []);++ useEffect(() => {+ const unregister = setAuthPromptHandler(requestAuthentication);+ return () => {+ unregister();+ authPending.current?.reject(new Error('Authentication prompt closed'));+ authPending.current = null;+ };+ }, [requestAuthentication]);+const health = useHealth();const { tracks, error: libError, refresh, setTracks } = useLibrary();useEffect(() => { localStorage.setItem(FORM_KEY, JSON.stringify(form)); }, [form]);+ useEffect(() => {+ if (!authPromptOpen) {+ const target = authReturnFocus.current;+ if (target?.isConnected) target.focus();+ authReturnFocus.current = null;+ return;+ }+ authInput.current?.focus();+ }, [authPromptOpen]);const doneTracks = useMemo(() => tracks.filter((t) => t.status === 'done'), [tracks]);const active = useMemo(() => tracks.find((t) => t.id === activeId) ?? null, [tracks, activeId]);@@ -39,6 +75,57 @@ export default function App() {const closeDetail = useCallback(() => setSelectedId(null), []);const inflight = tracks.filter(isInflight).length;+ const submitAuthToken = async (event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ if (!authToken.trim() || authSubmitting) return;+ const candidate = authToken;+ setAuthError(null);+ setAuthSubmitting(true);+ try {+ if (!await api.authenticate(candidate)) {+ setAuthError('That token is wrong. Check it and try again.');+ return;+ }+ setAuthToken('');+ const pending = authPending.current;+ authPending.current = null;+ setAuthPromptOpen(false);+ pending?.resolve();+ } catch (error) {+ setAuthError((error as Error).message);+ } finally {+ setAuthSubmitting(false);+ }+ };++ const cancelAuthPrompt = () => {+ const pending = authPending.current;+ authPending.current = null;+ setAuthPromptOpen(false);+ setAuthToken('');+ setAuthError(null);+ pending?.reject(new Error('Authentication canceled'));+ };++ const handleAuthKeyDown = (event: KeyboardEvent<HTMLElement>) => {+ event.stopPropagation();+ if (event.key === 'Escape') {+ event.preventDefault();+ if (!authSubmitting) cancelAuthPrompt();+ return;+ }+ if (event.key !== 'Tab') return;+ const controls = Array.from(authDialog.current?.querySelectorAll<HTMLElement>('input:not(:disabled), button:not(:disabled)') ?? []);+ if (!controls.length) return;+ if (event.shiftKey && document.activeElement === controls[0]) {+ event.preventDefault();+ controls[controls.length - 1].focus();+ } else if (!event.shiftKey && document.activeElement === controls[controls.length - 1]) {+ event.preventDefault();+ controls[0].focus();+ }+ };+const visible = useMemo(() => {if (view !== 'library' || !query.trim()) return tracks;const q = query.toLowerCase();@@ -148,6 +235,44 @@ export default function App() {)}</div><Player track={active} playing={playing} onPlayingChange={setPlaying} onPrev={() => step(-1)} onNext={() => step(1)} onEnded={() => step(1)} />+ {authPromptOpen && (+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-ink-950/80 p-4">+ <section+ ref={authDialog}+ role="dialog"+ aria-modal="true"+ aria-labelledby="ui-token-title"+ aria-describedby="ui-token-help"+ className="w-full max-w-[320px] rounded-lg border border-ink-700 bg-ink-900 p-6 text-zinc-100 shadow-2xl"+ onKeyDown={handleAuthKeyDown}+ >+ <h2 id="ui-token-title" className="text-base font-semibold">UI server token</h2>+ <p id="ui-token-help" className="mt-1 text-xs text-zinc-500">Enter the token configured by the UI server.</p>+ <form className="mt-4" onSubmit={(event) => void submitAuthToken(event)}>+ <label className="label mb-1 block" htmlFor="ui-token">Token</label>+ <input+ ref={authInput}+ id="ui-token"+ name="ui-token"+ type="password"+ className={`field ${authError ? 'border-red-500/70 focus:border-red-400 focus:ring-red-400/40' : ''}`}+ value={authToken}+ onChange={(event) => { setAuthToken(event.target.value); setAuthError(null); }}+ autoComplete="off"+ autoFocus+ disabled={authSubmitting}+ aria-invalid={!!authError}+ aria-describedby={authError ? 'ui-token-help ui-token-error' : 'ui-token-help'}+ />+ {authError && <p id="ui-token-error" className="mt-1 text-xs text-red-400" role="alert">{authError}</p>}+ <div className="mt-4 flex justify-end gap-2">+ <button type="button" className="btn-ghost" onClick={cancelAuthPrompt} disabled={authSubmitting}>Cancel</button>+ <button type="submit" className="btn-primary" disabled={!authToken.trim() || authSubmitting}>{authSubmitting ? 'Checking…' : 'Continue'}</button>+ </div>+ </form>+ </section>+ </div>+ )}</div>);}diff --git a/web/src/api.ts b/web/src/api.tsindex 9a66d02..18a8f94 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -3,6 +3,38 @@ import type { GenerateInput, Health, Settings, SettingsTestResult, Template, Traconst API_HEADERS = { 'X-Requested-With': 'XMLHttpRequest' };const JSON_HEADERS = { ...API_HEADERS, 'Content-Type': 'application/json' };+type AuthPromptHandler = () => Promise<void>;++let authPromptHandler: AuthPromptHandler | null = null;+let authInProgress: Promise<void> | null = null;+let authVersion = 0;++export function setAuthPromptHandler(handler: AuthPromptHandler) {+ authPromptHandler = handler;+ return () => {+ if (authPromptHandler === handler) authPromptHandler = null;+ };+}++function requestAuthentication() {+ if (!authInProgress) {+ if (!authPromptHandler) return Promise.reject(new Error('UI authentication is required'));+ authInProgress = authPromptHandler()+ .then(() => { authVersion++; })+ .finally(() => { authInProgress = null; });+ }+ return authInProgress;+}++export async function apiFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {+ const requestVersion = authVersion;+ const options = { ...init, credentials: init?.credentials ?? 'same-origin' };+ const response = await fetch(input, options);+ if (response.status !== 401 || !String(input).startsWith('/api/')) return response;+ if (requestVersion === authVersion) await requestAuthentication();+ return fetch(input, options);+}+async function json<T>(res: Response): Promise<T> {if (!res.ok) {let msg = `${res.status} ${res.statusText}`;@@ -16,24 +48,35 @@ async function json<T>(res: Response): Promise<T> {}export const api = {- health: () => fetch('/api/health', { headers: API_HEADERS }).then((r) => json<Health>(r)),- library: () => fetch('/api/library', { headers: API_HEADERS }).then((r) => json<Track[]>(r)),+ authenticate: async (token: string) => {+ const res = await fetch('/api/auth', {+ method: 'POST',+ headers: JSON_HEADERS,+ credentials: 'same-origin',+ body: JSON.stringify({ token }),+ });+ if (res.status === 401) return false;+ if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);+ return true;+ },+ health: () => apiFetch('/api/health', { headers: API_HEADERS }).then((r) => json<Health>(r)),+ library: () => apiFetch('/api/library', { headers: API_HEADERS }).then((r) => json<Track[]>(r)),generate: (input: GenerateInput) =>- fetch('/api/generate', { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify(input) }).then((r) => json<Track[]>(r)),+ apiFetch('/api/generate', { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify(input) }).then((r) => json<Track[]>(r)),enhance: (input: { prompt: string; lyrics: string; instrumental: boolean }) =>- fetch('/api/enhance', { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify(input) }).then((r) => json<{ prompt: string }>(r)),+ apiFetch('/api/enhance', { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify(input) }).then((r) => json<{ prompt: string }>(r)),lyrics: (input: { prompt: string; duration: number }) =>- fetch('/api/lyrics', { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify(input) }).then((r) => json<{ lyrics: string }>(r)),- deleteTrack: (id: string) => fetch(`/api/tracks/${id}`, { method: 'DELETE', headers: API_HEADERS }).then((r) => json<{ ok: true }>(r)),- templates: () => fetch('/api/templates', { headers: API_HEADERS }).then((r) => json<Template[]>(r)),+ apiFetch('/api/lyrics', { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify(input) }).then((r) => json<{ lyrics: string }>(r)),+ deleteTrack: (id: string) => apiFetch(`/api/tracks/${id}`, { method: 'DELETE', headers: API_HEADERS }).then((r) => json<{ ok: true }>(r)),+ templates: () => apiFetch('/api/templates', { headers: API_HEADERS }).then((r) => json<Template[]>(r)),saveTemplate: (t: Omit<Template, 'id' | 'createdAt'>) =>- fetch('/api/templates', { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify(t) }).then((r) => json<Template>(r)),- deleteTemplate: (id: string) => fetch(`/api/templates/${id}`, { method: 'DELETE', headers: API_HEADERS }).then((r) => json<{ ok: true }>(r)),- settings: () => fetch('/api/settings', { headers: API_HEADERS }).then((r) => json<Settings>(r)),+ apiFetch('/api/templates', { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify(t) }).then((r) => json<Template>(r)),+ deleteTemplate: (id: string) => apiFetch(`/api/templates/${id}`, { method: 'DELETE', headers: API_HEADERS }).then((r) => json<{ ok: true }>(r)),+ settings: () => apiFetch('/api/settings', { headers: API_HEADERS }).then((r) => json<Settings>(r)),saveSettings: (patch: { musicApi?: string; apiKey?: string; compat?: boolean; llmApi?: string; llmApiKey?: string; llmModel?: string }) =>- fetch('/api/settings', { method: 'PUT', headers: JSON_HEADERS, body: JSON.stringify(patch) }).then((r) => json<Settings>(r)),+ apiFetch('/api/settings', { method: 'PUT', headers: JSON_HEADERS, body: JSON.stringify(patch) }).then((r) => json<Settings>(r)),testSettings: (candidate: { musicApi?: string; apiKey?: string }) =>- fetch('/api/settings/test', { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify(candidate) }).then((r) => json<SettingsTestResult>(r)),+ apiFetch('/api/settings/test', { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify(candidate) }).then((r) => json<SettingsTestResult>(r)),audioUrl: (id: string) => `/api/tracks/${id}/audio`,downloadUrl: (id: string) => `/api/tracks/${id}/audio?download`,};diff --git a/web/src/components/DownloadButton.tsx b/web/src/components/DownloadButton.tsxnew file mode 100644index 0000000..8b625a8--- /dev/null+++ b/web/src/components/DownloadButton.tsx@@ -0,0 +1,53 @@+import { useState, type ReactNode } from 'react';+import { apiFetch } from '../api';++interface Props {+ url: string | null;+ className: string;+ title: string;+ children: ReactNode;+}++export function DownloadButton({ url, className, title, children }: Props) {+ const [busy, setBusy] = useState(false);+ const [failed, setFailed] = useState(false);++ const download = async () => {+ if (!url || busy) return;+ setBusy(true);+ setFailed(false);+ try {+ const response = await apiFetch(url, { method: 'HEAD' });+ if (!response.ok) throw new Error(`download ${response.status}`);+ const anchor = document.createElement('a');+ anchor.href = url;+ anchor.hidden = true;+ document.body.append(anchor);+ anchor.click();+ anchor.remove();+ } catch {+ setFailed(true);+ } finally {+ setBusy(false);+ }+ };++ const label = busy ? 'Preparing download' : failed ? 'Download failed' : title;+ return (+ <>+ <button+ type="button"+ className={className}+ onClick={() => { void download(); }}+ disabled={!url}+ aria-disabled={busy}+ title={label}+ aria-label={label}+ aria-busy={busy}+ >+ {children}+ </button>+ <span className="sr-only" role="status">{busy ? 'Preparing download' : failed ? 'Download failed' : ''}</span>+ </>+ );+}diff --git a/web/src/components/Player.tsx b/web/src/components/Player.tsxindex 8023eb7..fbc7a34 100644--- a/web/src/components/Player.tsx+++ b/web/src/components/Player.tsx@@ -1,10 +1,11 @@import { useEffect, useRef, useState } from 'react';import type { Track } from '../types';-import { api } from '../api';+import { api, apiFetch } from '../api';import { coverStyle } from '../lib/cover';import { fmtTime } from '../lib/format';import { Waveform } from './Waveform';import { Download, Next, Pause, Play, Prev, Spinner } from './Icons';+import { DownloadButton } from './DownloadButton';interface Props {track: Track | null;@@ -23,6 +24,7 @@ export function Player({ track, playing, onPlayingChange, onPrev, onNext, onEndeconst [starved, setStarved] = useState(false);const starvedRef = useRef(false);const loadedSrc = useRef('');+ const recoveredSrc = useRef('');const pendingSeek = useRef<number | null>(null);// a play() cut short by our own src swap rejects with AbortError — expected, not a playback problem@@ -43,6 +45,7 @@ export function Player({ track, playing, onPlayingChange, onPrev, onNext, onEndeif (sameTrack) return;// armed: nothing to load yet — behave as starved so the first window resumes playbackloadedSrc.current = `${api.audioUrl(track.id)}#pending`;+ recoveredSrc.current = '';el.pause(); el.removeAttribute('src'); el.load();setTime(0); setDur(0); setErr(null);starvedRef.current = true; setStarved(true);@@ -61,6 +64,7 @@ export function Player({ track, playing, onPlayingChange, onPrev, onNext, onEndeif (sameTrack && live && playing && !starved && !nearEnd) return;const pos = sameTrack ? el.currentTime : 0;loadedSrc.current = src;+ recoveredSrc.current = '';if (!sameTrack) { setTime(0); setDur(0); }setErr(null);pendingSeek.current = pos > 0 ? pos : null;@@ -103,6 +107,28 @@ export function Player({ track, playing, onPlayingChange, onPrev, onNext, onEndeonEnded();};+ const recoverAudioSource = async () => {+ const el = audio.current;+ const failedSrc = src;+ if (!el || !failedSrc) return;+ if (recoveredSrc.current === failedSrc) { setErr('playback error'); return; }+ recoveredSrc.current = failedSrc;+ try {+ // Native media requests cannot open the shared token prompt. A cheap HEAD request+ // uses the same auth flow, then reloading the native source preserves audio streaming.+ const response = await apiFetch(failedSrc, { method: 'HEAD' });+ if (!response.ok) throw new Error(`audio ${response.status}`);+ if (loadedSrc.current !== failedSrc || audio.current !== el) return;+ el.src = failedSrc;+ el.load();+ setErr(null);+ if (playing || starvedRef.current) el.play().catch(reportPlayError);+ } catch {+ if (recoveredSrc.current === failedSrc) recoveredSrc.current = '';+ if (loadedSrc.current === failedSrc) setErr('playback error');+ }+ };+const subtitle = err ?? (starved && rendered === 0 ? 'Waiting for the first audio…' : starved ? 'Buffering — waiting for the renderer…' : live ? `Live · ${fmtTime(rendered)} rendered` : track ? track.prompt : 'Pick a track');return (@@ -121,7 +147,7 @@ export function Player({ track, playing, onPlayingChange, onPrev, onNext, onEndeif (live && (el.ended || (el.duration > 0 && el.duration - el.currentTime < 0.05))) { starvedRef.current = true; setStarved(true); return; }if (!starvedRef.current) onPlayingChange(false);}}- onError={() => setErr('playback error')}+ onError={() => { void recoverAudioSource(); }}/><div className="flex items-center gap-3 w-36 md:w-64 min-w-0"><div className="w-12 h-12 rounded-lg shrink-0" style={track ? coverStyle(track.id) : { background: '#22222f' }} />@@ -150,7 +176,9 @@ export function Player({ track, playing, onPlayingChange, onPrev, onNext, onEnde</div><span className="text-[11px] text-zinc-400 tabular-nums w-10">{fmtTime(total)}</span></div>- <a className={`icon-btn hidden md:inline-flex ${track ? '' : 'pointer-events-none opacity-40'}`} href={track ? api.downloadUrl(track.id) : '#'} title="Download"><Download width={18} height={18} /></a>+ <DownloadButton className="icon-btn hidden md:inline-flex" url={track ? api.downloadUrl(track.id) : null} title="Download">+ <Download width={18} height={18} />+ </DownloadButton></div>);}diff --git a/web/src/components/TrackCard.tsx b/web/src/components/TrackCard.tsxindex fd4118c..6fd7b87 100644--- a/web/src/components/TrackCard.tsx+++ b/web/src/components/TrackCard.tsx@@ -4,6 +4,7 @@ import { coverStyle } from '../lib/cover';import { fmtAgo, fmtTime, fmtTook } from '../lib/format';import { api } from '../api';import { Alert, Download, Pause, Play, Refresh, Reuse, Spinner, Trash, X } from './Icons';+import { DownloadButton } from './DownloadButton';import { ProgressDetail } from './ProgressDetail';interface Props {@@ -60,7 +61,7 @@ export function TrackCard({ track: t, groupSize, active, playing, selected, onSe</div><div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition shrink-0">{done && (- <a className="icon-btn" href={api.downloadUrl(t.id)} title="Download"><Download width={16} height={16} /></a>+ <DownloadButton className="icon-btn" url={api.downloadUrl(t.id)} title="Download"><Download width={16} height={16} /></DownloadButton>)}<button className="icon-btn" title="Reuse settings" onClick={() => onReuse(t)}><Reuse width={16} height={16} /></button>{err && <button className="icon-btn" title="Retry" onClick={() => onRetry(t)}><Refresh width={16} height={16} /></button>}diff --git a/web/src/components/TrackDetail.tsx b/web/src/components/TrackDetail.tsxindex 7a95ad1..03744b2 100644--- a/web/src/components/TrackDetail.tsx+++ b/web/src/components/TrackDetail.tsx@@ -4,6 +4,7 @@ import { coverStyle } from '../lib/cover';import { fmtTime, fmtTook } from '../lib/format';import { api } from '../api';import { Download, Pause, Play, Refresh, Reuse, Spinner, Trash, X } from './Icons';+import { DownloadButton } from './DownloadButton';import { ProgressDetail } from './ProgressDetail';interface Props {@@ -82,7 +83,7 @@ export function TrackDetail({ track: t, groupSize, active, playing, onClose, onP{err && <div className="text-xs text-red-400 break-words rounded-lg bg-red-500/10 border border-red-500/30 px-3 py-2">{t.error}</div>}<div className="flex flex-wrap items-center gap-2">- {done && <a className="btn-ghost border border-ink-600" href={api.downloadUrl(t.id)}><Download width={16} height={16} /> Download</a>}+ {done && <DownloadButton className="btn-ghost border border-ink-600" url={api.downloadUrl(t.id)} title="Download"><Download width={16} height={16} /> Download</DownloadButton>}<button className="btn-ghost border border-ink-600" onClick={() => onReuse(t)}><Reuse width={16} height={16} /> Reuse settings</button>{err && <button className="btn-ghost border border-ink-600" onClick={() => onRetry(t)}><Refresh width={16} height={16} /> Retry</button>}<button className="btn-ghost border border-ink-600 hover:!text-red-400" onClick={() => onDelete(t)}>diff --git a/web/src/lib/peaks.ts b/web/src/lib/peaks.tsindex d3c786d..f241600 100644--- a/web/src/lib/peaks.ts+++ b/web/src/lib/peaks.ts@@ -1,3 +1,5 @@+import { apiFetch } from '../api';+export const BUCKETS = 160;const cache = new Map<string, Promise<number[]>>();@@ -8,7 +10,7 @@ export function loadPeaks(url: string, buckets = BUCKETS): Promise<number[]> {let p = cache.get(key);if (!p) {p = (async () => {- const res = await fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });+ const res = await apiFetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });if (!res.ok) throw new Error(`audio ${res.status}`);const buf = await res.arrayBuffer();const ctx = new (window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext)();diff --git a/web/test/DownloadButton.test.ts b/web/test/DownloadButton.test.tsnew file mode 100644index 0000000..9809806--- /dev/null+++ b/web/test/DownloadButton.test.ts@@ -0,0 +1,79 @@+import { act, createElement } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { setAuthPromptHandler } from '../src/api';+import { DownloadButton } from '../src/components/DownloadButton';++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });++const mountedRoots: { root: Root; host: HTMLDivElement }[] = [];+let unregisterAuthHandler: (() => void) | undefined;++async function flush() {+ for (let i = 0; i < 8; i++) {+ await act(async () => { await Promise.resolve(); });+ }+}++afterEach(() => {+ unregisterAuthHandler?.();+ unregisterAuthHandler = undefined;+ for (const { root } of mountedRoots.splice(0)) act(() => root.unmount());+ document.body.replaceChildren();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe('authenticated downloads', () => {+ it('opens the shared auth flow on a protected download and starts it after retry', async () => {+ let authorized = false;+ let completeAuthentication!: () => void;+ const prompt = vi.fn(() => new Promise<void>((resolve) => {+ completeAuthentication = () => { authorized = true; resolve(); };+ }));+ unregisterAuthHandler = setAuthPromptHandler(prompt);++ const requests: { url: string; method: string; authorized: boolean }[] = [];+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ requests.push({ url: String(input), method: init?.method ?? 'GET', authorized });+ return { ok: authorized, status: authorized ? 200 : 401 } as Response;+ }));++ const clickedHrefs: string[] = [];+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {+ clickedHrefs.push(this.getAttribute('href') ?? '');+ });++ const host = document.createElement('div');+ document.body.append(host);+ const root = createRoot(host);+ mountedRoots.push({ root, host });+ await act(async () => {+ root.render(createElement(DownloadButton, {+ url: '/api/tracks/protected/audio?download',+ className: 'btn-ghost',+ title: 'Download',+ children: 'Download',+ }));+ });++ const button = host.querySelector<HTMLButtonElement>('button')!;+ await act(async () => { button.click(); await Promise.resolve(); });+ await flush();++ expect(prompt).toHaveBeenCalledTimes(1);+ expect(requests).toEqual([{+ url: '/api/tracks/protected/audio?download', method: 'HEAD', authorized: false,+ }]);++ await act(async () => { completeAuthentication(); await Promise.resolve(); });+ await flush();++ expect(requests).toEqual([+ { url: '/api/tracks/protected/audio?download', method: 'HEAD', authorized: false },+ { url: '/api/tracks/protected/audio?download', method: 'HEAD', authorized: true },+ ]);+ expect(clickedHrefs).toEqual(['/api/tracks/protected/audio?download']);+ expect(button.disabled).toBe(false);+ });+});diff --git a/web/test/Player.test.ts b/web/test/Player.test.tsindex 6fad5fd..7518826 100644--- a/web/test/Player.test.ts+++ b/web/test/Player.test.ts@@ -1,6 +1,7 @@import { act, createElement } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { setAuthPromptHandler } from '../src/api';import { Player } from '../src/components/Player';import type { Track } from '../src/types';@@ -17,6 +18,7 @@ let mediaStates: WeakMap<HTMLMediaElement, MediaState>;let play: ReturnType<typeof vi.fn>;let load: ReturnType<typeof vi.fn>;let mediaDescriptors: Map<string, PropertyDescriptor | undefined>;+let unregisterAuthHandler: (() => void) | undefined;function mediaState(element: HTMLMediaElement): MediaState {let state = mediaStates.get(element);@@ -82,6 +84,12 @@ async function dispatchMediaEvent(audio: HTMLAudioElement, type: string) {});}+async function flush() {+ for (let i = 0; i < 8; i++) {+ await act(async () => { await Promise.resolve(); });+ }+}+beforeEach(() => {const prototype = HTMLMediaElement.prototype;const properties = ['currentTime', 'duration', 'ended', 'load', 'pause', 'play'];@@ -117,6 +125,8 @@ beforeEach(() => {});afterEach(() => {+ unregisterAuthHandler?.();+ unregisterAuthHandler = undefined;for (const root of mountedRoots.splice(0)) act(() => root.unmount());document.body.replaceChildren();vi.unstubAllGlobals();@@ -209,4 +219,86 @@ describe('Player live playback', () => {expect(audio.getAttribute('src')).toBe('/api/tracks/second/audio');expect(audio.currentTime).toBe(0);});++ it('authenticates and retries a native audio source after its request fails with 401', async () => {+ let authorized = false;+ let completeAuthentication!: () => void;+ const prompt = vi.fn(() => new Promise<void>((resolve) => {+ completeAuthentication = () => { authorized = true; resolve(); };+ }));+ unregisterAuthHandler = setAuthPromptHandler(prompt);++ const requests: { url: string; method: string; authorized: boolean }[] = [];+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const method = init?.method ?? 'GET';+ requests.push({ url: String(input), method, authorized });+ const ok = method !== 'HEAD' || authorized;+ return { ok, status: ok ? 200 : 401, arrayBuffer: async () => new ArrayBuffer(8) } as Response;+ }));++ const { audio } = await mount(track('protected', 'done', null), true);+ const loadsBeforeFailure = load.mock.calls.length;+ await dispatchMediaEvent(audio, 'error');+ await flush();++ expect(prompt).toHaveBeenCalledTimes(1);+ expect(requests.filter((request) => request.method === 'HEAD')).toEqual([+ { url: '/api/tracks/protected/audio', method: 'HEAD', authorized: false },+ ]);++ await act(async () => { completeAuthentication(); await Promise.resolve(); });+ await flush();++ expect(requests.filter((request) => request.method === 'HEAD')).toEqual([+ { url: '/api/tracks/protected/audio', method: 'HEAD', authorized: false },+ { url: '/api/tracks/protected/audio', method: 'HEAD', authorized: true },+ ]);+ expect(audio.getAttribute('src')).toBe('/api/tracks/protected/audio');+ expect(load.mock.calls.length).toBeGreaterThan(loadsBeforeFailure);+ });++ it('prompts again when playback recovery is retried after authentication is canceled', async () => {+ let authorized = false;+ let completeAuthentication!: () => void;+ const prompt = vi.fn()+ .mockRejectedValueOnce(new Error('Authentication canceled'))+ .mockImplementationOnce(() => new Promise<void>((resolve) => {+ completeAuthentication = () => { authorized = true; resolve(); };+ }));+ unregisterAuthHandler = setAuthPromptHandler(prompt);++ const requests: { method: string; authorized: boolean }[] = [];+ vi.stubGlobal('fetch', vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {+ const method = init?.method ?? 'GET';+ requests.push({ method, authorized });+ const ok = method !== 'HEAD' || authorized;+ return { ok, status: ok ? 200 : 401, arrayBuffer: async () => new ArrayBuffer(8) } as Response;+ }));++ const { audio, host } = await mount(track('canceled', 'done', null), true);+ await dispatchMediaEvent(audio, 'error');+ await flush();++ expect(prompt).toHaveBeenCalledTimes(1);+ expect(host.textContent).toContain('playback error');++ await dispatchMediaEvent(audio, 'error');+ await flush();++ expect(prompt).toHaveBeenCalledTimes(2);+ expect(requests.filter((request) => request.method === 'HEAD')).toEqual([+ { method: 'HEAD', authorized: false },+ { method: 'HEAD', authorized: false },+ ]);++ await act(async () => { completeAuthentication(); await Promise.resolve(); });+ await flush();++ expect(requests.filter((request) => request.method === 'HEAD')).toEqual([+ { method: 'HEAD', authorized: false },+ { method: 'HEAD', authorized: false },+ { method: 'HEAD', authorized: true },+ ]);+ expect(host.textContent).not.toContain('playback error');+ });});diff --git a/web/test/auth.test.ts b/web/test/auth.test.tsnew file mode 100644index 0000000..1aee709--- /dev/null+++ b/web/test/auth.test.ts@@ -0,0 +1,216 @@+import { act, createElement } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import App from '../src/App';++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });++interface MockResponse {+ ok: boolean;+ status: number;+ statusText: string;+ json: () => Promise<unknown>;+}++function response(status: number, body?: unknown): Response {+ return {+ ok: status >= 200 && status < 300,+ status,+ statusText: status === 401 ? 'Unauthorized' : 'OK',+ json: async () => body,+ } satisfies MockResponse as Response;+}++function successBody(url: string) {+ if (url === '/api/health') {+ return { upstreamReachable: true, ready: true, busy: false, queued: 0, formats: ['wav'] };+ }+ return [];+}++function mockApi({ validToken = 'right-token', initiallyAuthorized = false } = {}) {+ let authorized = initiallyAuthorized;+ const apiCalls: { url: string; authorized: boolean }[] = [];+ const authTokens: string[] = [];++ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (url === '/api/auth') {+ const body = JSON.parse(String(init?.body)) as { token: string };+ authTokens.push(body.token);+ if (body.token === validToken) {+ authorized = true;+ return response(204);+ }+ return response(401);+ }++ apiCalls.push({ url, authorized });+ return authorized ? response(200, successBody(url)) : response(401, { error: 'unauthorized' });+ });+ vi.stubGlobal('fetch', fetchMock);+ return { apiCalls, authTokens, fetchMock };+}++function mockDownloadApi() {+ let authorized = false;+ const authTokens: string[] = [];+ const track = {+ id: 'focus-track', groupId: 'focus-track', takeIndex: 0,+ title: 'Focus return track', prompt: 'An instrumental song', lyrics: '[Instrumental]',+ duration: 10, seed: null, format: 'wav', status: 'done', progress: 1, stage: 'done',+ eta: null, stream: false, renderedSeconds: null, error: null, file: 'focus-track.wav',+ createdAt: '2026-01-01T00:00:00.000Z', finishedAt: '2026-01-01T00:01:00.000Z',+ };+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (url === '/api/auth') {+ const body = JSON.parse(String(init?.body)) as { token: string };+ authTokens.push(body.token);+ authorized = body.token === 'right-token';+ return response(authorized ? 204 : 401);+ }+ if (url === '/api/tracks/focus-track/audio?download') return response(authorized ? 200 : 401);+ if (url === '/api/library') return response(200, [track]);+ return response(200, successBody(url));+ });+ vi.stubGlobal('fetch', fetchMock);+ return { authTokens };+}++const mountedRoots: { root: Root; host: HTMLDivElement }[] = [];++async function mountApp() {+ const host = document.createElement('div');+ document.body.append(host);+ const root = createRoot(host);+ mountedRoots.push({ root, host });+ await act(async () => {+ root.render(createElement(App));+ await Promise.resolve();+ await Promise.resolve();+ });+ await flush();+ return host;+}++async function flush() {+ for (let i = 0; i < 8; i++) {+ await act(async () => { await Promise.resolve(); });+ }+}++async function enterTokenAndSubmit(host: HTMLElement, token: string) {+ const input = host.querySelector<HTMLInputElement>('input[name="ui-token"]');+ const submit = host.querySelector<HTMLButtonElement>('button[type="submit"]');+ expect(input).not.toBeNull();+ expect(submit).not.toBeNull();++ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ await act(async () => {+ setValue.call(input, token);+ input!.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await act(async () => { submit!.click(); });+ await flush();+}++function downloadButton(host: HTMLElement) {+ const button = Array.from(host.querySelectorAll<HTMLButtonElement>('button[aria-label="Download"]')).find((item) => !item.disabled);+ if (!button) throw new Error('Expected an enabled track download button');+ return button;+}++async function requestDownloadAuth(host: HTMLElement, button: HTMLButtonElement) {+ await act(async () => {+ button.focus();+ expect(document.activeElement).toBe(button);+ button.click();+ });+ await flush();+ expect(host.querySelector('[role="dialog"]')).not.toBeNull();+}++afterEach(() => {+ for (const { root } of mountedRoots.splice(0)) act(() => root.unmount());+ document.body.replaceChildren();+ localStorage.clear();+ sessionStorage.clear();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe('UI token authentication', () => {+ it('keeps the prompt open after a wrong token and retries the original calls after success', async () => {+ const { apiCalls, authTokens } = mockApi();+ const host = await mountApp();++ const dialog = host.querySelector('[role="dialog"]');+ expect(dialog).not.toBeNull();+ expect(host.querySelectorAll('[role="dialog"]')).toHaveLength(1);++ await enterTokenAndSubmit(host, 'wrong-token');+ expect(host.querySelector('[role="dialog"]')).not.toBeNull();+ expect(host.textContent).toContain('That token is wrong.');+ expect(host.querySelector<HTMLInputElement>('input[name="ui-token"]')?.value).toBe('wrong-token');++ await enterTokenAndSubmit(host, 'right-token');++ expect(host.querySelector('[role="dialog"]')).toBeNull();+ expect(authTokens).toEqual(['wrong-token', 'right-token']);+ expect(apiCalls.some((call) => call.authorized)).toBe(true);+ expect(apiCalls.filter((call) => call.url === '/api/library')).toHaveLength(2);+ expect(JSON.stringify(localStorage)).not.toContain('right-token');+ expect(JSON.stringify(sessionStorage)).not.toContain('right-token');+ expect(window.location.href).not.toContain('right-token');+ });++ it('uses one prompt for concurrent unauthorized API calls', async () => {+ const { apiCalls, authTokens } = mockApi();+ const host = await mountApp();++ expect(host.querySelectorAll('[role="dialog"]')).toHaveLength(1);+ await enterTokenAndSubmit(host, 'right-token');++ expect(authTokens).toEqual(['right-token']);+ expect(apiCalls.filter((call) => call.url === '/api/health')).toHaveLength(2);+ expect(apiCalls.filter((call) => call.url === '/api/library')).toHaveLength(2);+ expect(apiCalls.filter((call) => call.url === '/api/templates')).toHaveLength(2);+ expect(apiCalls.every((call, index) => index < 3 || call.authorized)).toBe(true);+ });++ it('restores focus to the download button after canceling authentication', async () => {+ mockDownloadApi();+ const host = await mountApp();+ const trigger = downloadButton(host);++ await requestDownloadAuth(host, trigger);+ await act(async () => { host.querySelector<HTMLButtonElement>('[role="dialog"] button[type="button"]')?.click(); });+ await flush();++ expect(host.querySelector('[role="dialog"]')).toBeNull();+ expect(document.activeElement).toBe(trigger);+ });++ it('restores focus to the download button after successful authentication', async () => {+ const { authTokens } = mockDownloadApi();+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});+ const host = await mountApp();+ const trigger = downloadButton(host);++ await requestDownloadAuth(host, trigger);+ await enterTokenAndSubmit(host, 'right-token');++ expect(host.querySelector('[role="dialog"]')).toBeNull();+ expect(authTokens).toEqual(['right-token']);+ expect(document.activeElement).toBe(trigger);+ });++ it('does not show a token prompt when API calls succeed without authentication', async () => {+ const { authTokens } = mockApi({ initiallyAuthorized: true });+ const host = await mountApp();++ expect(host.querySelector('[role="dialog"]')).toBeNull();+ expect(authTokens).toEqual([]);+ });+});