Skip to content

Suno-style web UI for a self-hosted MiniMax-Music3 inference server

feat(auth): protect all UI API routes

Adam B.9ec66a619430
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
index 4c136c0..4cf8869 100644
--- a/.github/workflows/docker.yml
+++ b/.github/workflows/docker.yml
@@ -50,7 +50,7 @@ jobs:
- name: Smoke-test main image
run: |
set -euo pipefail
- container_id="$(docker run --detach minimax-music-ui:pr)"
+ container_id="$(docker run --detach --env UI_TOKEN=ci-smoke-token minimax-music-ui:pr)"
cleanup() {
docker rm --force "$container_id" >/dev/null 2>&1 || true
}
@@ -60,7 +60,7 @@ jobs:
while (( SECONDS < deadline )); do
status="$(
docker exec "$container_id" node -e '
- fetch("http://127.0.0.1:8787/api/library", { signal: AbortSignal.timeout(1000) })
+ fetch("http://127.0.0.1:8787/api/ping", { signal: AbortSignal.timeout(1000) })
.then((response) => {
console.log(response.status);
process.exit(response.status === 200 ? 0 : 1);
@@ -81,7 +81,7 @@ jobs:
done
docker logs "$container_id"
- echo "GET /api/library did not return HTTP 200 within 30 seconds" >&2
+ echo "GET /api/ping did not return HTTP 200 within 30 seconds" >&2
exit 1
- name: Prepare synthetic demo data
diff --git a/Dockerfile b/Dockerfile
index 04421be..c34ecd2 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -32,5 +32,5 @@ USER node
VOLUME ["/data"]
EXPOSE 8787
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s \
- CMD wget -qO- http://127.0.0.1:8787/api/library >/dev/null || exit 1
+ CMD wget -qO- http://127.0.0.1:8787/api/ping >/dev/null || exit 1
CMD ["node", "server/dist/index.js"]
diff --git a/README.md b/README.md
index dbb3940..c1cd317 100644
--- a/README.md
+++ b/README.md
@@ -119,6 +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. |
| `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) |
@@ -129,6 +130,8 @@ The inference server address is resolved in this order:
| `DATA_DIR` | `./data` | Where `library.json`, `templates.json`, `settings.json` and `tracks/` live |
| `STATIC_DIR` | `web/dist` (if built) | Directory of the built SPA to serve |
+When `UI_TOKEN` is unset, the server logs that the UI is unauthenticated. Non-GET/HEAD API requests also require an `Authorization` or `X-Requested-With` header to block cross-site writes; the web client sends `X-Requested-With`. During development, the Vite proxy adds the configured `UI_TOKEN` to safe reads and writes carrying `X-Requested-With`.
+
## Development
```bash
@@ -160,8 +163,12 @@ 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.
+
| Method | Path | Description |
|---|---|---|
+| `GET` | `/api/ping` | Public liveness check; does not contact the inference server |
+| `POST` | `/api/auth` | `{token}` → 204 and an authenticated session cookie; 401 for an incorrect token |
| `GET` | `/api/health` | `demo` (read-only demo, see above), `upstreamReachable` (via `/v1/models`), `ready` (false only if an optional upstream `/health` answers 503), `capabilities` from that `/health`, `enhance` (an LLM is configured), queue state |
| `GET` | `/api/library` | Tracks, newest first |
| `POST` | `/api/generate` | `{title?, prompt, lyrics?, duration, seed?, format, takes}` → created tracks (queued) |
diff --git a/docker-compose.yml b/docker-compose.yml
index d4edcd8..ad7291a 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -9,7 +9,8 @@ services:
- ./data:/data
environment:
# Optional. When set, these lock the corresponding fields in Settings.
- # Leave unset to configure the inference server from the UI instead.
MUSIC_API: ${MUSIC_API:-}
MUSIC_API_KEY: ${MUSIC_API_KEY:-}
+ # Optional. Use a random value of at least 32 characters to require API auth.
+ UI_TOKEN: ${UI_TOKEN:-}
restart: unless-stopped
diff --git a/server/src/app.ts b/server/src/app.ts
index cb250b2..31bc434 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -2,7 +2,7 @@ import express, { type NextFunction, type Request, type Response } from 'express
import fs from 'node:fs/promises';
import fsSync from 'node:fs';
import path from 'node:path';
-import { randomUUID } from 'node:crypto';
+import { createHash, createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
import type { JsonStore, Library } from './library.js';
import { extFor, RenderQueue, UpstreamClient, UpstreamError } from './upstream.js';
import { normalizeEnhance, normalizeGenerate, normalizeLyrics, ValidationError } from './validate.js';
@@ -30,6 +30,27 @@ export interface AppDeps {
}
const MIME: Record<string, string> = { wav: 'audio/wav' };
+const UI_SESSION_COOKIE = 'ui_session';
+
+function constantTimeMatch(candidate: string, expected: string): boolean {
+ const candidateDigest = createHash('sha256').update(candidate).digest();
+ const expectedDigest = createHash('sha256').update(expected).digest();
+ return timingSafeEqual(candidateDigest, expectedDigest);
+}
+
+function cookieValue(req: Request, name: string): string | null {
+ const prefix = `${name}=`;
+ const entry = (req.headers.cookie ?? '').split(';').map((part) => part.trim()).find((part) => part.startsWith(prefix));
+ return entry ? entry.slice(prefix.length) : null;
+}
+
+function hasUiCredential(req: Request, token: string, sessionCookie: string): boolean {
+ const authorization = req.get('authorization') ?? '';
+ const bearer = /^Bearer\s+(.+)$/i.exec(authorization)?.[1];
+ if (bearer && constantTimeMatch(bearer, token)) return true;
+ const cookie = cookieValue(req, UI_SESSION_COOKIE);
+ return cookie !== null && constantTimeMatch(cookie, sessionCookie);
+}
/** A WAV still being written: sizes in its header are 0 until done, so patch them to the current length on the way out. */
async function servePartialWav(req: Request, res: Response, abs: string, type: string): Promise<void> {
@@ -62,7 +83,34 @@ export function createApp(deps: AppDeps) {
const { library, templates, settings, upstream, queue, tracksDir } = deps;
const log = deps.log ?? ((m: string) => console.log(`[app] ${m}`));
const app = express();
+ const uiToken = process.env.UI_TOKEN || null;
+ const sessionCookie = uiToken ? createHmac('sha256', uiToken).update('minimax-music-ui-session').digest('base64url') : null;
+ if (!uiToken) log('WARNING: UI_TOKEN is unset; the UI server is unauthenticated');
+
+ app.use('/api', (req, res, next) => {
+ const hasProtectionHeader = req.headers.authorization !== undefined || req.headers['x-requested-with'] !== undefined;
+ if (req.method !== 'GET' && req.method !== 'HEAD' && !hasProtectionHeader) {
+ return res.status(403).json({ error: 'state-changing API requests require Authorization or X-Requested-With' });
+ }
+ if (!uiToken) return next();
+ const apiPath = req.path.toLowerCase();
+ const exempt = (req.method === 'GET' && apiPath === '/ping') || (req.method === 'POST' && apiPath === '/auth');
+ if (!exempt && !hasUiCredential(req, uiToken, sessionCookie!)) return res.status(401).json({ error: 'unauthorized' });
+ return next();
+ });
+
app.use(express.json({ limit: '1mb' }));
+ app.get('/api/ping', (_req, res) => res.status(200).end());
+ app.post('/api/auth', (req, res) => {
+ if (!uiToken || !sessionCookie) return res.status(404).end();
+ const candidate = typeof req.body?.token === 'string' ? req.body.token : '';
+ if (!constantTimeMatch(candidate, uiToken)) return res.status(401).end();
+ const attributes = [`${UI_SESSION_COOKIE}=${sessionCookie}`, 'HttpOnly', 'SameSite=Strict', 'Path=/api'];
+ if (req.secure) attributes.push('Secure');
+ res.setHeader('Set-Cookie', attributes.join('; '));
+ return res.status(204).end();
+ });
+
if (deps.demo) app.use(demoRouter(library, tracksDir, deps.demo));
app.get('/api/health', async (_req, res) => {
diff --git a/server/test/app.test.ts b/server/test/app.test.ts
index 423b38b..259019b 100644
--- a/server/test/app.test.ts
+++ b/server/test/app.test.ts
@@ -17,7 +17,13 @@ afterEach(async () => { await fake?.close(); fake = null; });
let llm: FakeLlm | null = null;
afterEach(async () => { await llm?.close(); llm = null; });
-async function setup(opts: Parameters<typeof startFakeUpstream>[0] = {}, apiKey: string | null = null, env: EnvOverrides | null = null) {
+const writeRequest = (app: ReturnType<typeof createApp>) => ({
+ post: (url: string) => request(app).post(url).set('X-Requested-With', 'XMLHttpRequest'),
+ put: (url: string) => request(app).put(url).set('X-Requested-With', 'XMLHttpRequest'),
+ delete: (url: string) => request(app).delete(url).set('X-Requested-With', 'XMLHttpRequest'),
+});
+
+async function setup(opts: Parameters<typeof startFakeUpstream>[0] = {}, apiKey: string | null = null, env: EnvOverrides | null = null, uiToken: string | null = null, log: (msg: string) => void = () => {}) {
fake = await startFakeUpstream(opts);
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'app-'));
const lib = new Library(path.join(dir, 'library.json'));
@@ -31,7 +37,12 @@ async function setup(opts: Parameters<typeof startFakeUpstream>[0] = {}, apiKey:
const queue = new RenderQueue(lib, upstream, tracksDir, () => {}, 20);
// unreachable base: tests never hit GitHub; they seed the cache instead
const skill = new SkillFiles(path.join(dir, 'skill-cache'), 'http://127.0.0.1:1');
- const app = createApp({ library: lib, templates, settings, upstream, queue, tracksDir, skill, log: () => {} });
+ const previousUiToken = process.env.UI_TOKEN;
+ if (uiToken === null) delete process.env.UI_TOKEN;
+ else process.env.UI_TOKEN = uiToken;
+ const app = createApp({ library: lib, templates, settings, upstream, queue, tracksDir, skill, log });
+ if (previousUiToken === undefined) delete process.env.UI_TOKEN;
+ else process.env.UI_TOKEN = previousUiToken;
return { app, lib, tracksDir, dir, upstream, queue };
}
@@ -63,7 +74,7 @@ describe('app', () => {
it('generate → queue → speech → file: maps fields, serialises takes, forwards bearer', async () => {
const { app, lib } = await setup({ renderMs: 120 }, 'sekrit');
- const res = await request(app).post('/api/generate').send({ prompt: 'ambient', lyrics: '', duration: 10, takes: 2, seed: 5 });
+ const res = await writeRequest(app).post('/api/generate').send({ prompt: 'ambient', lyrics: '', duration: 10, takes: 2, seed: 5 });
expect(res.status).toBe(201);
expect(res.body).toHaveLength(2);
expect(res.body[0]).toMatchObject({ status: 'queued', seed: 5, lyrics: '[Instrumental]' });
@@ -93,7 +104,7 @@ describe('app', () => {
it('uses the model id advertised by /v1/models', async () => {
const { app, lib } = await setup({ modelId: 'MiniMaxAI/MiniMax-Music3', strictModel: true });
- const res = await request(app).post('/api/generate').send({ prompt: 'x' });
+ const res = await writeRequest(app).post('/api/generate').send({ prompt: 'x' });
await until(() => lib.get(res.body[0].id)?.status === 'done');
expect(fake!.requests.find((r) => r.path === '/v1/audio/speech')?.body).toMatchObject({ model: 'MiniMaxAI/MiniMax-Music3' });
});
@@ -113,14 +124,14 @@ describe('app', () => {
const { app, lib } = await setup({ modelId: null, strictModel: true });
const h = await request(app).get('/api/health');
expect(h.body).toMatchObject({ upstreamReachable: true, ready: true, models: [] });
- const res = await request(app).post('/api/generate').send({ prompt: 'x' });
+ const res = await writeRequest(app).post('/api/generate').send({ prompt: 'x' });
await until(() => lib.get(res.body[0].id)?.status === 'done');
expect(fake!.requests.find((r) => r.path === '/v1/audio/speech')?.body).toMatchObject({ model: 'MiniMaxAI/MiniMax-Music3' });
});
it('random seed → seed reported by the server (X-Seed) is stored', async () => {
const { app, lib } = await setup();
- const res = await request(app).post('/api/generate').send({ prompt: 'x' });
+ const res = await writeRequest(app).post('/api/generate').send({ prompt: 'x' });
expect(res.body[0].seed).toBeNull();
await until(() => lib.get(res.body[0].id)?.status === 'done');
expect(lib.get(res.body[0].id)?.seed).toBe(4242);
@@ -129,15 +140,15 @@ describe('app', () => {
it('rejects bad input', async () => {
const { app } = await setup();
- expect((await request(app).post('/api/generate').send({})).status).toBe(400);
- expect((await request(app).post('/api/generate').send({ prompt: 'x', format: 'flac' })).status).toBe(400);
- expect((await request(app).post('/api/generate').send({ prompt: 'x', seed: 1.5 })).status).toBe(400);
+ expect((await writeRequest(app).post('/api/generate').send({})).status).toBe(400);
+ expect((await writeRequest(app).post('/api/generate').send({ prompt: 'x', format: 'flac' })).status).toBe(400);
+ expect((await writeRequest(app).post('/api/generate').send({ prompt: 'x', seed: 1.5 })).status).toBe(400);
});
it('records upstream failures on the track', async () => {
const { app, lib } = await setup();
await fake!.close(); fake = null;
- const res = await request(app).post('/api/generate').send({ prompt: 'x' });
+ const res = await writeRequest(app).post('/api/generate').send({ prompt: 'x' });
expect(res.status).toBe(201);
await until(() => lib.get(res.body[0].id)?.status === 'error');
expect(lib.get(res.body[0].id)?.error).toMatch(/unreachable/);
@@ -146,22 +157,22 @@ describe('app', () => {
it('delete: removes queued, aborts running, deletes finished files', async () => {
const { app, lib, queue, tracksDir } = await setup({ renderMs: 500 });
- const res = await request(app).post('/api/generate').send({ prompt: 'x', takes: 2 });
+ const res = await writeRequest(app).post('/api/generate').send({ prompt: 'x', takes: 2 });
const [a, b] = res.body as Track[];
await until(() => lib.get(a.id)?.status === 'running');
- expect((await request(app).delete(`/api/tracks/${b.id}`)).status).toBe(200);
+ expect((await writeRequest(app).delete(`/api/tracks/${b.id}`)).status).toBe(200);
expect(queue.queued).toBe(0);
- expect((await request(app).delete(`/api/tracks/${a.id}`)).status).toBe(200);
+ expect((await writeRequest(app).delete(`/api/tracks/${a.id}`)).status).toBe(200);
await until(() => !queue.busy);
await until(() => fake!.requests.some((r) => r.aborted));
expect(lib.all()).toEqual([]);
- expect((await request(app).delete(`/api/tracks/${a.id}`)).status).toBe(404);
+ expect((await writeRequest(app).delete(`/api/tracks/${a.id}`)).status).toBe(404);
- const done = await request(app).post('/api/generate').send({ prompt: 'y', title: 'ambient piano' });
+ const done = await writeRequest(app).post('/api/generate').send({ prompt: 'y', title: 'ambient piano' });
const id = done.body[0].id;
await until(() => lib.get(id)?.status === 'done');
await fs.access(path.join(tracksDir, `${id}.wav`));
- expect((await request(app).delete(`/api/tracks/${id}`)).status).toBe(200);
+ expect((await writeRequest(app).delete(`/api/tracks/${id}`)).status).toBe(200);
await expect(fs.access(path.join(tracksDir, `${id}.wav`))).rejects.toThrow();
});
@@ -179,34 +190,34 @@ describe('app', () => {
it('uses the given title when present, random otherwise', async () => {
const { app } = await setup();
- expect((await request(app).post('/api/generate').send({ prompt: 'x', title: ' Pine Morning ' })).body[0].title).toBe('Pine Morning');
- expect((await request(app).post('/api/generate').send({ prompt: 'x' })).body[0].title).toMatch(/^[A-Z][A-Za-z&' ]+$/);
+ expect((await writeRequest(app).post('/api/generate').send({ prompt: 'x', title: ' Pine Morning ' })).body[0].title).toBe('Pine Morning');
+ expect((await writeRequest(app).post('/api/generate').send({ prompt: 'x' })).body[0].title).toMatch(/^[A-Z][A-Za-z&' ]+$/);
});
it('works with a path-prefixed upstream base URL and trailing slash', async () => {
const { app, lib } = await setup({ prefix: '/upstream/music3' }, null, { musicApi: null, apiKey: null });
- const put = await request(app).put('/api/settings').send({ musicApi: `${fake!.url}/` });
+ const put = await writeRequest(app).put('/api/settings').send({ musicApi: `${fake!.url}/` });
expect(put.status).toBe(200);
expect(put.body.musicApi).toBe(fake!.url);
expect((await request(app).get('/api/health')).body.upstreamReachable).toBe(true);
- const res = await request(app).post('/api/generate').send({ prompt: 'x' });
+ const res = await writeRequest(app).post('/api/generate').send({ prompt: 'x' });
await until(() => lib.get(res.body[0].id)?.status === 'done');
expect(fake!.requests.map((r) => r.path)).toEqual(expect.arrayContaining(['/v1/models', '/v1/audio/speech']));
});
it('templates: create, upsert by name, list, delete', async () => {
const { app } = await setup();
- expect((await request(app).post('/api/templates').send({ prompt: 'x' })).status).toBe(400);
- expect((await request(app).post('/api/templates').send({ name: 'Lo-fi' })).status).toBe(400);
- const c = await request(app).post('/api/templates').send({ name: 'Lo-fi', prompt: 'lo-fi hip hop', lyrics: '', duration: 90 });
+ expect((await writeRequest(app).post('/api/templates').send({ prompt: 'x' })).status).toBe(400);
+ expect((await writeRequest(app).post('/api/templates').send({ name: 'Lo-fi' })).status).toBe(400);
+ const c = await writeRequest(app).post('/api/templates').send({ name: 'Lo-fi', prompt: 'lo-fi hip hop', lyrics: '', duration: 90 });
expect(c.status).toBe(201);
expect(c.body).toMatchObject({ name: 'Lo-fi', prompt: 'lo-fi hip hop', lyrics: '[Instrumental]', duration: 90, format: 'wav' });
- const u = await request(app).post('/api/templates').send({ name: 'lo-fi', prompt: 'lo-fi v2' });
+ const u = await writeRequest(app).post('/api/templates').send({ name: 'lo-fi', prompt: 'lo-fi v2' });
expect(u.status).toBe(200);
expect(u.body.id).toBe(c.body.id);
expect((await request(app).get('/api/templates')).body).toHaveLength(1);
- expect((await request(app).delete(`/api/templates/${c.body.id}`)).status).toBe(200);
- expect((await request(app).delete(`/api/templates/${c.body.id}`)).status).toBe(404);
+ expect((await writeRequest(app).delete(`/api/templates/${c.body.id}`)).status).toBe(200);
+ expect((await writeRequest(app).delete(`/api/templates/${c.body.id}`)).status).toBe(404);
});
it('settings: env-locked values cannot be changed and the key is never returned', async () => {
@@ -214,46 +225,46 @@ describe('app', () => {
const s = await request(app).get('/api/settings');
expect(s.body).toMatchObject({ apiKeySet: true, locked: { musicApi: true, apiKey: true }, source: { musicApi: 'env', apiKey: 'env' } });
expect(JSON.stringify(s.body)).not.toContain('"k"');
- expect((await request(app).put('/api/settings').send({ musicApi: 'http://x:1' })).status).toBe(400);
+ expect((await writeRequest(app).put('/api/settings').send({ musicApi: 'http://x:1' })).status).toBe(400);
});
it('settings: stored values apply, persist, and re-point the upstream client', async () => {
const { app, dir, upstream } = await setup({}, null, { musicApi: null, apiKey: null });
expect((await request(app).get('/api/settings')).body).toMatchObject({ musicApi: 'http://127.0.0.1:7862', apiKeySet: false, source: { musicApi: 'default', apiKey: 'none' } });
- expect((await request(app).put('/api/settings').send({ musicApi: 'not a url' })).status).toBe(400);
- const put = await request(app).put('/api/settings').send({ musicApi: `${fake!.url}/`, apiKey: 'sekrit' });
+ expect((await writeRequest(app).put('/api/settings').send({ musicApi: 'not a url' })).status).toBe(400);
+ const put = await writeRequest(app).put('/api/settings').send({ musicApi: `${fake!.url}/`, apiKey: 'sekrit' });
expect(put.body).toMatchObject({ musicApi: fake!.url, apiKeySet: true, source: { musicApi: 'settings', apiKey: 'settings' } });
expect(upstream.url).toBe(fake!.url);
expect(JSON.parse(await fs.readFile(path.join(dir, 'settings.json'), 'utf8'))).toEqual({ musicApi: fake!.url, apiKey: 'sekrit', compat: false, llmApi: null, llmApiKey: null, llmModel: null });
await request(app).get('/api/health');
expect(fake!.requests.at(-1)?.auth).toBe('Bearer sekrit');
- expect((await request(app).put('/api/settings').send({ apiKey: '' })).body.apiKeySet).toBe(false);
+ expect((await writeRequest(app).put('/api/settings').send({ apiKey: '' })).body.apiKeySet).toBe(false);
});
it('settings/test probes a candidate URL without saving', async () => {
const { app } = await setup({}, null, { musicApi: null, apiKey: null });
- const ok = await request(app).post('/api/settings/test').send({ musicApi: fake!.url });
+ const ok = await writeRequest(app).post('/api/settings/test').send({ musicApi: fake!.url });
expect(ok.body).toMatchObject({ ok: true, musicApi: fake!.url, health: { ready: true, models: ['minimax_ttm'] } });
- const bad = await request(app).post('/api/settings/test').send({ musicApi: 'http://127.0.0.1:1' });
+ const bad = await writeRequest(app).post('/api/settings/test').send({ musicApi: 'http://127.0.0.1:1' });
expect(bad.body.ok).toBe(false);
expect((await request(app).get('/api/settings')).body.musicApi).toBe('http://127.0.0.1:7862');
});
it('settings/test only reuses a saved music key for the same origin', async () => {
const { app } = await setup({}, null, { musicApi: null, apiKey: null });
- await request(app).put('/api/settings').send({ musicApi: fake!.url, apiKey: 'saved-key' });
+ await writeRequest(app).put('/api/settings').send({ musicApi: fake!.url, apiKey: 'saved-key' });
const other = await startFakeUpstream();
try {
- const withoutKey = await request(app).post('/api/settings/test').send({ musicApi: other.url });
+ const withoutKey = await writeRequest(app).post('/api/settings/test').send({ musicApi: other.url });
expect(withoutKey.status).toBe(200);
expect(withoutKey.body.ok).toBe(true);
expect(other.requests[0]?.auth).toBeUndefined();
- const withKey = await request(app).post('/api/settings/test').send({ musicApi: other.url, apiKey: 'candidate-key' });
+ const withKey = await writeRequest(app).post('/api/settings/test').send({ musicApi: other.url, apiKey: 'candidate-key' });
expect(withKey.status).toBe(200);
expect(other.requests.at(-1)?.auth).toBe('Bearer candidate-key');
- const sameOrigin = await request(app).post('/api/settings/test').send({ musicApi: `${fake!.url}/` });
+ const sameOrigin = await writeRequest(app).post('/api/settings/test').send({ musicApi: `${fake!.url}/` });
expect(sameOrigin.body.ok).toBe(true);
expect(fake!.requests.at(-1)?.auth).toBe('Bearer saved-key');
} finally {
@@ -268,35 +279,35 @@ describe('app', () => {
const newLlm = await startFakeLlm([{ content: 'ok' }]);
await seedSkill(dir);
try {
- await request(app).put('/api/settings').send({ musicApi: fake!.url, apiKey: 'music-old', llmApi: oldLlm.url, llmApiKey: 'llm-old', llmModel: 'test-model' });
+ await writeRequest(app).put('/api/settings').send({ musicApi: fake!.url, apiKey: 'music-old', llmApi: oldLlm.url, llmApiKey: 'llm-old', llmModel: 'test-model' });
- const sameOrigin = await request(app).put('/api/settings').send({ musicApi: `${fake!.url}/path`, llmApi: `${oldLlm.url}/path` });
+ const sameOrigin = await writeRequest(app).put('/api/settings').send({ musicApi: `${fake!.url}/path`, llmApi: `${oldLlm.url}/path` });
expect(sameOrigin.body).toMatchObject({ apiKeySet: true, llmKeySet: true });
- await request(app).put('/api/settings').send({ musicApi: fake!.url, llmApi: oldLlm.url });
+ await writeRequest(app).put('/api/settings').send({ musicApi: fake!.url, llmApi: oldLlm.url });
await request(app).get('/api/health');
expect(fake!.requests.at(-1)?.auth).toBe('Bearer music-old');
- await request(app).post('/api/enhance').send({ prompt: 'test' });
+ await writeRequest(app).post('/api/enhance').send({ prompt: 'test' });
expect(oldLlm.requests.at(-1)?.auth).toBe('Bearer llm-old');
- const movedMusic = await request(app).put('/api/settings').send({ musicApi: otherMusic.url });
+ const movedMusic = await writeRequest(app).put('/api/settings').send({ musicApi: otherMusic.url });
expect(movedMusic.body.apiKeySet).toBe(false);
await request(app).get('/api/health');
expect(otherMusic.requests.at(-1)?.auth).toBeUndefined();
- const replacedMusic = await request(app).put('/api/settings').send({ musicApi: fake!.url, apiKey: 'music-new' });
+ const replacedMusic = await writeRequest(app).put('/api/settings').send({ musicApi: fake!.url, apiKey: 'music-new' });
expect(replacedMusic.body.apiKeySet).toBe(true);
await request(app).get('/api/health');
expect(fake!.requests.at(-1)?.auth).toBe('Bearer music-new');
- const movedLlm = await request(app).put('/api/settings').send({ llmApi: newLlm.url });
+ const movedLlm = await writeRequest(app).put('/api/settings').send({ llmApi: newLlm.url });
expect(movedLlm.body.llmKeySet).toBe(false);
- await request(app).post('/api/enhance').send({ prompt: 'test' });
+ await writeRequest(app).post('/api/enhance').send({ prompt: 'test' });
expect(newLlm.requests.at(-1)?.auth).toBeUndefined();
- const replacedLlm = await request(app).put('/api/settings').send({ llmApi: oldLlm.url, llmApiKey: 'llm-new' });
+ const replacedLlm = await writeRequest(app).put('/api/settings').send({ llmApi: oldLlm.url, llmApiKey: 'llm-new' });
expect(replacedLlm.body.llmKeySet).toBe(true);
- await request(app).post('/api/enhance').send({ prompt: 'test' });
+ await writeRequest(app).post('/api/enhance').send({ prompt: 'test' });
expect(oldLlm.requests.at(-1)?.auth).toBe('Bearer llm-new');
} finally {
await otherMusic.close();
@@ -309,16 +320,16 @@ describe('app', () => {
const { app, dir } = await setup({}, null, { musicApi: null, apiKey: 'env-music-key', llmApi: null, llmApiKey: 'env-llm-key', llmModel: null });
const otherLlm = await startFakeLlm([{ content: 'ok' }]);
try {
- const test = await request(app).post('/api/settings/test').send({ musicApi: fake!.url });
+ const test = await writeRequest(app).post('/api/settings/test').send({ musicApi: fake!.url });
expect(test.status).toBe(400);
expect(test.body.error).toMatch(/MUSIC_API_KEY/);
expect(fake!.requests).toHaveLength(0);
- const music = await request(app).put('/api/settings').send({ musicApi: fake!.url });
+ const music = await writeRequest(app).put('/api/settings').send({ musicApi: fake!.url });
expect(music.status).toBe(400);
expect(music.body.error).toMatch(/MUSIC_API_KEY/);
- const llm = await request(app).put('/api/settings').send({ llmApi: otherLlm.url });
+ const llm = await writeRequest(app).put('/api/settings').send({ llmApi: otherLlm.url });
expect(llm.status).toBe(400);
expect(llm.body.error).toMatch(/LLM_API_KEY/);
expect(otherLlm.requests).toHaveLength(0);
@@ -335,8 +346,8 @@ describe('app', () => {
it('settings: LLM fields persist, gate health.enhance, and never return the key', async () => {
const { app, dir } = await setup();
expect((await request(app).get('/api/health')).body.enhance).toBe(false);
- expect((await request(app).put('/api/settings').send({ llmApi: 'ftp://x' })).status).toBe(400);
- const put = await request(app).put('/api/settings').send({ llmApi: 'http://llm.test/v1/', llmApiKey: 'llm-sekrit', llmModel: 'gpt-x' });
+ expect((await writeRequest(app).put('/api/settings').send({ llmApi: 'ftp://x' })).status).toBe(400);
+ const put = await writeRequest(app).put('/api/settings').send({ llmApi: 'http://llm.test/v1/', llmApiKey: 'llm-sekrit', llmModel: 'gpt-x' });
expect(put.body).toMatchObject({
llmApi: 'http://llm.test/v1', llmModel: 'gpt-x', llmKeySet: true,
source: { llmApi: 'settings', llmApiKey: 'settings', llmModel: 'settings' },
@@ -345,23 +356,23 @@ describe('app', () => {
expect(JSON.stringify(put.body)).not.toContain('llm-sekrit');
expect((await request(app).get('/api/health')).body.enhance).toBe(true);
expect(JSON.parse(await fs.readFile(path.join(dir, 'settings.json'), 'utf8'))).toMatchObject({ llmApi: 'http://llm.test/v1', llmApiKey: 'llm-sekrit', llmModel: 'gpt-x' });
- expect((await request(app).put('/api/settings').send({ llmModel: '' })).body.llmModel).toBeNull();
+ expect((await writeRequest(app).put('/api/settings').send({ llmModel: '' })).body.llmModel).toBeNull();
expect((await request(app).get('/api/health')).body.enhance).toBe(false);
await fake!.close(); fake = null;
- await request(app).put('/api/settings').send({ llmModel: 'gpt-x' });
+ await writeRequest(app).put('/api/settings').send({ llmModel: 'gpt-x' });
expect((await request(app).get('/api/health')).body).toMatchObject({ upstreamReachable: false, enhance: true });
});
it('enhance: 400 without a prompt, 409 until an LLM is configured, then returns the caption', async () => {
const { app, dir } = await setup();
- expect((await request(app).post('/api/enhance').send({ prompt: ' ' })).status).toBe(400);
- const off = await request(app).post('/api/enhance').send({ prompt: 'sad piano' });
+ expect((await writeRequest(app).post('/api/enhance').send({ prompt: ' ' })).status).toBe(400);
+ const off = await writeRequest(app).post('/api/enhance').send({ prompt: 'sad piano' });
expect(off.status).toBe(409);
expect(off.body.error).toMatch(/not configured/);
await seedSkill(dir);
llm = await startFakeLlm([{ content: '### Global Metadata\nslow piano' }]);
- await request(app).put('/api/settings').send({ llmApi: llm.url, llmModel: 'm' });
- const on = await request(app).post('/api/enhance').send({ prompt: 'sad piano', lyrics: '[Verse]\nx', instrumental: false });
+ await writeRequest(app).put('/api/settings').send({ llmApi: llm.url, llmModel: 'm' });
+ const on = await writeRequest(app).post('/api/enhance').send({ prompt: 'sad piano', lyrics: '[Verse]\nx', instrumental: false });
expect(on.status).toBe(200);
expect(on.body).toEqual({ prompt: '### Global Metadata\nslow piano' });
expect(llm.requests[0].body.messages[1].content).toBe('Caption: sad piano\n\nLyrics:\n[Verse]\nx');
@@ -370,13 +381,13 @@ describe('app', () => {
it('lyrics: 400 without a prompt, 409 until an LLM is configured, then returns lyrics', async () => {
const { app } = await setup();
- expect((await request(app).post('/api/lyrics').send({ prompt: '' })).status).toBe(400);
- const off = await request(app).post('/api/lyrics').send({ prompt: 'night drive', duration: 30 });
+ expect((await writeRequest(app).post('/api/lyrics').send({ prompt: '' })).status).toBe(400);
+ const off = await writeRequest(app).post('/api/lyrics').send({ prompt: 'night drive', duration: 30 });
expect(off.status).toBe(409);
expect(off.body.error).toMatch(/not configured/);
llm = await startFakeLlm([{ content: '[Verse]\nNeon' }]);
- await request(app).put('/api/settings').send({ llmApi: llm.url, llmModel: 'm' });
- const on = await request(app).post('/api/lyrics').send({ prompt: 'night drive', duration: 30 });
+ await writeRequest(app).put('/api/settings').send({ llmApi: llm.url, llmModel: 'm' });
+ const on = await writeRequest(app).post('/api/lyrics').send({ prompt: 'night drive', duration: 30 });
expect(on.status).toBe(200);
expect(on.body).toEqual({ lyrics: '[Verse]\nNeon' });
expect(llm.requests[0].body.messages[1].content).toContain('Target length: 30 s');
@@ -386,17 +397,17 @@ describe('app', () => {
const { app, dir } = await setup();
await seedSkill(dir);
llm = await startFakeLlm([{ status: 500 }]);
- await request(app).put('/api/settings').send({ llmApi: llm.url, llmModel: 'm' });
- const res = await request(app).post('/api/enhance').send({ prompt: 'sad piano' });
+ await writeRequest(app).put('/api/settings').send({ llmApi: llm.url, llmModel: 'm' });
+ const res = await writeRequest(app).post('/api/enhance').send({ prompt: 'sad piano' });
expect(res.status).toBe(502);
expect(res.body.error).toMatch(/LLM error 500/);
});
it('settings: a rejected PUT changes nothing, even fields that validated', async () => {
const { app, dir } = await setup();
- expect((await request(app).put('/api/settings').send({ llmApi: 'http://ok.test/v1', llmModel: 5 })).status).toBe(400);
+ expect((await writeRequest(app).put('/api/settings').send({ llmApi: 'http://ok.test/v1', llmModel: 5 })).status).toBe(400);
expect((await request(app).get('/api/settings')).body.llmApi).toBeNull();
- await request(app).put('/api/settings').send({ compat: true });
+ await writeRequest(app).put('/api/settings').send({ compat: true });
expect(JSON.parse(await fs.readFile(path.join(dir, 'settings.json'), 'utf8'))).toMatchObject({ compat: true, llmApi: null });
});
@@ -405,15 +416,15 @@ describe('app', () => {
const s = await request(app).get('/api/settings');
expect(s.body).toMatchObject({ llmApi: 'http://env-llm/v1', llmModel: 'm', llmKeySet: true, locked: { llmApi: true, llmApiKey: true, llmModel: true }, source: { llmApi: 'env', llmApiKey: 'env', llmModel: 'env' } });
expect(JSON.stringify(s.body)).not.toContain('envk');
- expect((await request(app).put('/api/settings').send({ llmModel: 'other' })).status).toBe(400);
- expect((await request(app).put('/api/settings').send({ llmApiKey: 'x' })).status).toBe(400);
+ expect((await writeRequest(app).put('/api/settings').send({ llmModel: 'other' })).status).toBe(400);
+ expect((await writeRequest(app).put('/api/settings').send({ llmApiKey: 'x' })).status).toBe(400);
});
it('streams when advertised: real stage/progress/renderedSeconds, file appears early, valid WAV at the end', async () => {
const { app, lib, tracksDir } = await setup({ stream: { windows: 4, secondsPerWindow: 0.1, windowMs: 40 } });
const h = await request(app).get('/api/health');
expect(h.body.capabilities).toEqual(['stream']);
- const res = await request(app).post('/api/generate').send({ prompt: 'x', duration: 10, stream: true });
+ const res = await writeRequest(app).post('/api/generate').send({ prompt: 'x', duration: 10, stream: true });
const id = res.body[0].id as string;
await until(() => lib.get(id)?.stage === 'semantic');
await until(() => (lib.get(id)?.renderedSeconds ?? 0) > 0);
@@ -433,7 +444,7 @@ describe('app', () => {
it('without the per-track stream flag: progress is still real over SSE (stream_audio:false), no early audio, valid WAV', async () => {
const { app, lib, tracksDir } = await setup({ stream: { windows: 3, secondsPerWindow: 0.1, windowMs: 40 } });
- const res = await request(app).post('/api/generate').send({ prompt: 'x' });
+ const res = await writeRequest(app).post('/api/generate').send({ prompt: 'x' });
const id = res.body[0].id as string;
await until(() => lib.get(id)?.stage === 'denoise');
expect(lib.get(id)?.renderedSeconds).toBeNull();
@@ -450,7 +461,7 @@ describe('app', () => {
it('never sends stream:true to servers that do not advertise it', async () => {
const { app, lib } = await setup({ loading: false });
- const res = await request(app).post('/api/generate').send({ prompt: 'x', stream: true });
+ const res = await writeRequest(app).post('/api/generate').send({ prompt: 'x', stream: true });
await until(() => lib.get(res.body[0].id)?.status === 'done');
expect(fake!.requests.find((r) => r.path === '/v1/audio/speech')?.body).toMatchObject({ stream: false });
expect(lib.get(res.body[0].id)?.renderedSeconds).toBeNull();
@@ -458,14 +469,14 @@ describe('app', () => {
it('compat mode ignores /health and never streams, even when the server advertises it', async () => {
const { app, lib } = await setup({ stream: { windows: 3, windowMs: 40 } }, null, { musicApi: null, apiKey: null });
- await request(app).put('/api/settings').send({ musicApi: fake!.url });
+ await writeRequest(app).put('/api/settings').send({ musicApi: fake!.url });
expect((await request(app).get('/api/health')).body).toMatchObject({ ready: true, capabilities: ['stream'] });
- const put = await request(app).put('/api/settings').send({ compat: true });
+ const put = await writeRequest(app).put('/api/settings').send({ compat: true });
expect(put.status).toBe(200);
expect(put.body.compat).toBe(true);
fake!.requests.length = 0;
expect((await request(app).get('/api/health')).body).toMatchObject({ ready: true, capabilities: [] });
- const res = await request(app).post('/api/generate').send({ prompt: 'x', stream: true });
+ const res = await writeRequest(app).post('/api/generate').send({ prompt: 'x', stream: true });
await until(() => lib.get(res.body[0].id)?.status === 'done');
expect(fake!.requests.map((r) => r.path)).not.toContain('/health');
expect(fake!.requests.find((r) => r.path === '/v1/audio/speech')?.body).toMatchObject({ stream: false });
@@ -474,17 +485,17 @@ describe('app', () => {
it('cancel mid-stream aborts upstream and marks cancelled', async () => {
const { app, lib } = await setup({ stream: { windows: 50, windowMs: 40 } });
- const res = await request(app).post('/api/generate').send({ prompt: 'x', stream: true });
+ const res = await writeRequest(app).post('/api/generate').send({ prompt: 'x', stream: true });
const id = res.body[0].id as string;
await until(() => (lib.get(id)?.renderedSeconds ?? 0) > 0);
- await request(app).delete(`/api/tracks/${id}`);
+ await writeRequest(app).delete(`/api/tracks/${id}`);
await until(() => fake!.requests.find((r) => r.path === '/v1/audio/speech')?.aborted === true);
expect(lib.get(id)).toBeUndefined();
});
it('audio route serves the partial WAV of a running track with a patched header and honours Range', async () => {
const { app, lib } = await setup({ stream: { windows: 40, secondsPerWindow: 0.1, windowMs: 40 } });
- const res = await request(app).post('/api/generate').send({ prompt: 'x', stream: true });
+ const res = await writeRequest(app).post('/api/generate').send({ prompt: 'x', stream: true });
const id = res.body[0].id as string;
await until(() => (lib.get(id)?.renderedSeconds ?? 0) >= 0.2);
const bin = (r: request.Response, cb: (err: Error | null, body: Buffer) => void) => { const c: Buffer[] = []; r.on('data', (d: Buffer) => c.push(d)); r.on('end', () => cb(null, Buffer.concat(c))); };
@@ -500,6 +511,95 @@ describe('app', () => {
expect(part.status).toBe(206);
expect((part.body as Buffer).length).toBe(12);
expect(part.headers['content-range']).toMatch(/^bytes 40-51\/\d+$/);
- await request(app).delete(`/api/tracks/${id}`);
+ await writeRequest(app).delete(`/api/tracks/${id}`);
+ });
+
+ it('requires credentials for API reads when UI_TOKEN is set', async () => {
+ const { app } = await setup({}, null, null, 'test-ui-token');
+ expect((await request(app).get('/api/library')).status).toBe(401);
+ expect((await request(app).get('/api/future-route')).status).toBe(401);
+ });
+
+ it('requires credentials for API reads regardless of path casing', async () => {
+ const { app } = await setup({}, null, null, 'test-ui-token');
+ expect((await request(app).get('/API/library')).status).toBe(401);
+ });
+
+ it('applies the write guard to paths with different casing', async () => {
+ const { app } = await setup({}, null, null, 'test-ui-token');
+ expect((await request(app).post('/API/generate').send({ prompt: 'x' })).status).toBe(403);
+ });
+
+ it('requires credentials for API writes when UI_TOKEN is set', async () => {
+ const { app } = await setup({}, null, null, 'test-ui-token');
+ const res = await request(app).post('/api/generate').set('X-Requested-With', 'XMLHttpRequest').send({ prompt: 'x' });
+ expect(res.status).toBe(401);
+ });
+
+ it('accepts the configured UI_TOKEN as a bearer credential', async () => {
+ const { app } = await setup({}, null, null, 'test-ui-token');
+ const res = await request(app).get('/api/library').set('Authorization', 'Bearer test-ui-token');
+ expect(res.status).toBe(200);
+ });
+
+ it('sets a strict HttpOnly auth cookie that grants access without a request header', async () => {
+ const logs: string[] = [];
+ const { app, lib } = await setup({ renderMs: 30 }, null, null, 'test-ui-token', (msg) => logs.push(msg));
+ const auth = await request(app).post('/api/auth').set('X-Requested-With', 'XMLHttpRequest').send({ token: 'test-ui-token' });
+ expect(auth.status).toBe(204);
+ const cookie = auth.headers['set-cookie']?.[0];
+ expect(cookie).toBeDefined();
+ expect(cookie).not.toContain('test-ui-token');
+ expect(cookie).toContain('; HttpOnly');
+ expect(cookie).toContain('; SameSite=Strict');
+ expect(cookie).toContain('; Path=/api');
+ expect(cookie).not.toContain('; Secure');
+ expect(JSON.stringify(auth.body)).not.toContain('test-ui-token');
+
+ const res = await request(app).get('/api/library').set('Cookie', cookie!.split(';', 1)[0]);
+ expect(res.status).toBe(200);
+
+ const created = await request(app).post('/api/generate').set('Authorization', 'Bearer test-ui-token').send({ prompt: 'x' });
+ const id = created.body[0].id as string;
+ await until(() => lib.get(id)?.status === 'done');
+ const audio = await request(app).get(`/api/tracks/${id}/audio`).set('Cookie', cookie!.split(';', 1)[0]);
+ expect(audio.status).toBe(200);
+ expect(audio.headers['content-type']).toMatch(/^audio\/wav/);
+ const download = await request(app).get(`/api/tracks/${id}/audio?download`).set('Cookie', cookie!.split(';', 1)[0]);
+ expect(download.headers['content-disposition']).toMatch(/^attachment; filename=".+\.wav"$/);
+ expect(logs.join('\n')).not.toContain('test-ui-token');
+ });
+
+ it('rejects an incorrect auth token without setting a cookie', async () => {
+ const { app } = await setup({}, null, null, 'test-ui-token');
+ const res = await request(app).post('/api/auth').set('X-Requested-With', 'XMLHttpRequest').send({ token: 'wrong-token' });
+ expect(res.status).toBe(401);
+ expect(res.headers['set-cookie']).toBeUndefined();
+ expect(JSON.stringify(res.body)).not.toContain('wrong-token');
+ });
+
+ it('keeps GET /api/ping public without probing the upstream', async () => {
+ const { app } = await setup({}, null, null, 'test-ui-token');
+ const res = await request(app).get('/api/ping');
+ expect(res.status).toBe(200);
+ expect(fake!.requests).toEqual([]);
+ });
+
+ it('rejects a write without either protection header when UI_TOKEN is unset', async () => {
+ const { app } = await setup();
+ const res = await request(app).post('/api/generate').send({ prompt: 'x' });
+ expect(res.status).toBe(403);
+ });
+
+ it('applies the write guard even when UI_TOKEN is set', async () => {
+ const { app } = await setup({}, null, null, 'test-ui-token');
+ const res = await request(app).post('/api/generate').send({ prompt: 'x' });
+ expect(res.status).toBe(403);
+ });
+
+ it('warns at startup when UI_TOKEN is unset', async () => {
+ const logs: string[] = [];
+ await setup({}, null, null, null, (msg) => logs.push(msg));
+ expect(logs.join('\n')).toMatch(/unauthenticated/i);
});
});
diff --git a/server/test/demo.test.ts b/server/test/demo.test.ts
index 8fb104f..98540db 100644
--- a/server/test/demo.test.ts
+++ b/server/test/demo.test.ts
@@ -16,7 +16,7 @@ const seedTrack = (id: string, file: string): Track => ({
createdAt: '2026-01-01T00:00:00.000Z', finishedAt: '2026-01-01T00:00:30.000Z',
});
-async function setup() {
+async function setup(uiToken: string | null = null) {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'demo-'));
const tracksDir = path.join(dir, 'tracks');
await fs.mkdir(tracksDir);
@@ -30,7 +30,12 @@ async function setup() {
const templates = new JsonStore<Template>(path.join(dir, 'templates.json'));
await templates.load();
const queue = new RenderQueue(lib, upstream, tracksDir, () => {}, 20);
+ const previousUiToken = process.env.UI_TOKEN;
+ if (uiToken === null) delete process.env.UI_TOKEN;
+ else process.env.UI_TOKEN = uiToken;
const app = createApp({ library: lib, templates, settings, upstream, queue, tracksDir, skill: new SkillFiles(path.join(dir, 'skill-cache'), 'http://127.0.0.1:1'), log: () => {}, demo: { renderMs: 120, tickMs: 20 } });
+ if (previousUiToken === undefined) delete process.env.UI_TOKEN;
+ else process.env.UI_TOKEN = previousUiToken;
return { app, lib };
}
@@ -49,23 +54,32 @@ describe('demo mode', () => {
expect(h.body).toMatchObject({ demo: true, upstreamReachable: true, ready: true, capabilities: [], enhance: false });
});
+ it('requires UI_TOKEN for demo API reads while leaving ping public', async () => {
+ const { app } = await setup('test-ui-token');
+ expect((await request(app).get('/api/health')).status).toBe(401);
+ const health = await request(app).get('/api/health').set('Authorization', 'Bearer test-ui-token');
+ expect(health.status).toBe(200);
+ expect(health.body.demo).toBe(true);
+ expect((await request(app).get('/api/ping')).status).toBe(200);
+ });
+
it('refuses writes to seed tracks, settings and templates', async () => {
const { app, lib } = await setup();
- expect((await request(app).delete('/api/tracks/s1')).status).toBe(403);
+ expect((await request(app).delete('/api/tracks/s1').set('X-Requested-With', 'XMLHttpRequest')).status).toBe(403);
expect(lib.get('s1')).toBeDefined();
- expect((await request(app).put('/api/settings').send({ musicApi: 'http://x:1' })).status).toBe(403);
- expect((await request(app).post('/api/enhance').send({ prompt: 'x' })).status).toBe(403);
- expect((await request(app).post('/api/lyrics').send({ prompt: 'x' })).status).toBe(403);
- expect((await request(app).post('/api/settings/test').send({})).status).toBe(403);
- expect((await request(app).post('/api/templates').send({ name: 'n', prompt: 'p' })).status).toBe(403);
- expect((await request(app).delete('/api/templates/x')).status).toBe(403);
+ expect((await request(app).put('/api/settings').set('X-Requested-With', 'XMLHttpRequest').send({ musicApi: 'http://x:1' })).status).toBe(403);
+ expect((await request(app).post('/api/enhance').set('X-Requested-With', 'XMLHttpRequest').send({ prompt: 'x' })).status).toBe(403);
+ expect((await request(app).post('/api/lyrics').set('X-Requested-With', 'XMLHttpRequest').send({ prompt: 'x' })).status).toBe(403);
+ expect((await request(app).post('/api/settings/test').set('X-Requested-With', 'XMLHttpRequest').send({})).status).toBe(403);
+ expect((await request(app).post('/api/templates').set('X-Requested-With', 'XMLHttpRequest').send({ name: 'n', prompt: 'p' })).status).toBe(403);
+ expect((await request(app).delete('/api/templates/x').set('X-Requested-With', 'XMLHttpRequest')).status).toBe(403);
});
it('simulates a render per visitor and hands out a seed file as the result', async () => {
const { app, lib } = await setup();
const agent = request.agent(app);
const other = request.agent(app);
- const res = await agent.post('/api/generate').send({ prompt: 'lofi', duration: 30, takes: 2, seed: 9 });
+ const res = await agent.post('/api/generate').set('X-Requested-With', 'XMLHttpRequest').send({ prompt: 'lofi', duration: 30, takes: 2, seed: 9 });
expect(res.status).toBe(201);
expect(res.body).toHaveLength(2);
expect(res.body[0]).toMatchObject({ status: 'queued', seed: 9 });
@@ -88,16 +102,16 @@ describe('demo mode', () => {
// other visitors cannot see or fetch it
expect((await other.get(`/api/tracks/${id}/audio`)).status).toBe(404);
// the visitor can delete their own simulated track
- expect((await agent.delete(`/api/tracks/${id}`)).status).toBe(200);
+ expect((await agent.delete(`/api/tracks/${id}`).set('X-Requested-With', 'XMLHttpRequest')).status).toBe(200);
expect((await agent.get('/api/library')).body.map((t: Track) => t.id)).toEqual([res.body[1].id, 's1']);
});
it('cancelling a queued simulated track removes it', async () => {
const { app } = await setup();
const agent = request.agent(app);
- const res = await agent.post('/api/generate').send({ prompt: 'x', duration: 60, takes: 2 });
+ const res = await agent.post('/api/generate').set('X-Requested-With', 'XMLHttpRequest').send({ prompt: 'x', duration: 60, takes: 2 });
const second = res.body[1].id as string;
- expect((await agent.delete(`/api/tracks/${second}`)).status).toBe(200);
+ expect((await agent.delete(`/api/tracks/${second}`).set('X-Requested-With', 'XMLHttpRequest')).status).toBe(200);
expect((await agent.get('/api/library')).body.map((t: Track) => t.id)).toEqual([res.body[0].id, 's1']);
});
});
diff --git a/web/src/api.ts b/web/src/api.ts
index c0ec2a6..9a66d02 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -1,5 +1,8 @@
import type { GenerateInput, Health, Settings, SettingsTestResult, Template, Track } from './types';
+const API_HEADERS = { 'X-Requested-With': 'XMLHttpRequest' };
+const JSON_HEADERS = { ...API_HEADERS, 'Content-Type': 'application/json' };
+
async function json<T>(res: Response): Promise<T> {
if (!res.ok) {
let msg = `${res.status} ${res.statusText}`;
@@ -13,24 +16,24 @@ async function json<T>(res: Response): Promise<T> {
}
export const api = {
- health: () => fetch('/api/health').then((r) => json<Health>(r)),
- library: () => fetch('/api/library').then((r) => json<Track[]>(r)),
+ health: () => fetch('/api/health', { headers: API_HEADERS }).then((r) => json<Health>(r)),
+ library: () => fetch('/api/library', { headers: API_HEADERS }).then((r) => json<Track[]>(r)),
generate: (input: GenerateInput) =>
- fetch('/api/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) }).then((r) => json<Track[]>(r)),
+ fetch('/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: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) }).then((r) => json<{ prompt: string }>(r)),
+ fetch('/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: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) }).then((r) => json<{ lyrics: string }>(r)),
- deleteTrack: (id: string) => fetch(`/api/tracks/${id}`, { method: 'DELETE' }).then((r) => json<{ ok: true }>(r)),
- templates: () => fetch('/api/templates').then((r) => json<Template[]>(r)),
+ 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)),
saveTemplate: (t: Omit<Template, 'id' | 'createdAt'>) =>
- fetch('/api/templates', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(t) }).then((r) => json<Template>(r)),
- deleteTemplate: (id: string) => fetch(`/api/templates/${id}`, { method: 'DELETE' }).then((r) => json<{ ok: true }>(r)),
- settings: () => fetch('/api/settings').then((r) => json<Settings>(r)),
+ 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)),
saveSettings: (patch: { musicApi?: string; apiKey?: string; compat?: boolean; llmApi?: string; llmApiKey?: string; llmModel?: string }) =>
- fetch('/api/settings', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(patch) }).then((r) => json<Settings>(r)),
+ fetch('/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: { 'Content-Type': 'application/json' }, body: JSON.stringify(candidate) }).then((r) => json<SettingsTestResult>(r)),
+ fetch('/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/lib/peaks.ts b/web/src/lib/peaks.ts
index 190d4bd..d3c786d 100644
--- a/web/src/lib/peaks.ts
+++ b/web/src/lib/peaks.ts
@@ -8,7 +8,7 @@ export function loadPeaks(url: string, buckets = BUCKETS): Promise<number[]> {
let p = cache.get(key);
if (!p) {
p = (async () => {
- const res = await fetch(url);
+ const res = await fetch(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/api.test.ts b/web/test/api.test.ts
new file mode 100644
index 0000000..2f464ac
--- /dev/null
+++ b/web/test/api.test.ts
@@ -0,0 +1,31 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { api } from '../src/api';
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('API request headers', () => {
+ it('marks every fetch with X-Requested-With', async () => {
+ const fetch = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ json: async () => ({}),
+ } as Response);
+
+ await api.health();
+ await api.library();
+ await api.generate({ title: 'T', prompt: 'P', lyrics: '', duration: 10, seed: null, format: 'wav', takes: 1, stream: false });
+ await api.enhance({ prompt: 'P', lyrics: '', instrumental: false });
+ await api.lyrics({ prompt: 'P', duration: 10 });
+ await api.deleteTrack('track');
+ await api.templates();
+ await api.saveTemplate({ name: 'T', prompt: 'P', lyrics: '', duration: 10, format: 'wav' });
+ await api.deleteTemplate('template');
+ await api.settings();
+ await api.saveSettings({ compat: true });
+ await api.testSettings({ musicApi: 'http://localhost:7862' });
+
+ expect(fetch).toHaveBeenCalledTimes(12);
+ for (const [, init] of fetch.mock.calls) {
+ expect(new Headers(init?.headers).get('X-Requested-With')).toBe('XMLHttpRequest');
+ }
+ });
+});
diff --git a/web/test/viteProxy.test.ts b/web/test/viteProxy.test.ts
new file mode 100644
index 0000000..8e193b0
--- /dev/null
+++ b/web/test/viteProxy.test.ts
@@ -0,0 +1,45 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+type ProxyRequest = { setHeader: (name: string, value: string) => void };
+type IncomingRequest = { method: string; headers: Record<string, string | undefined> };
+type ProxyRequestHandler = (proxyReq: ProxyRequest, req: IncomingRequest) => void;
+
+async function loadProxyRequestHandler() {
+ vi.resetModules();
+ vi.stubEnv('UI_TOKEN', 'test-ui-token');
+ const { default: config } = await import('../vite.config');
+ const options = config.server?.proxy?.['/api'];
+ const configure = typeof options === 'object' ? options.configure : undefined;
+ let handler: ProxyRequestHandler | undefined;
+ configure?.({
+ on: (_event: string, callback: unknown) => { handler = callback as ProxyRequestHandler; },
+ } as unknown as Parameters<NonNullable<typeof configure>>[0], options as Parameters<NonNullable<typeof configure>>[1]);
+ if (!handler) throw new Error('Vite API proxy did not register its request handler');
+ return handler;
+}
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.resetModules();
+});
+
+describe('Vite API proxy authentication', () => {
+ it('does not add the UI token to unsafe requests without X-Requested-With', async () => {
+ const handler = await loadProxyRequestHandler();
+ const setHeader = vi.fn();
+ handler({ setHeader }, { method: 'POST', headers: {} });
+ expect(setHeader).not.toHaveBeenCalledWith('Authorization', 'Bearer test-ui-token');
+ });
+
+ it('adds the UI token to reads and writes carrying X-Requested-With', async () => {
+ const handler = await loadProxyRequestHandler();
+ for (const req of [
+ { method: 'GET', headers: {} },
+ { method: 'POST', headers: { 'x-requested-with': 'XMLHttpRequest' } },
+ ]) {
+ const setHeader = vi.fn();
+ handler({ setHeader }, req);
+ expect(setHeader).toHaveBeenCalledWith('Authorization', 'Bearer test-ui-token');
+ }
+ });
+});
diff --git a/web/vite.config.ts b/web/vite.config.ts
index f254518..6339bd0 100644
--- a/web/vite.config.ts
+++ b/web/vite.config.ts
@@ -2,10 +2,25 @@ import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
+const uiToken = process.env.UI_TOKEN;
+
export default defineConfig({
plugins: [react(), tailwindcss()],
server: {
port: 5173,
- proxy: { '/api': { target: process.env.SERVER_URL ?? 'http://127.0.0.1:8787', changeOrigin: true } },
+ proxy: {
+ '/api': {
+ target: process.env.SERVER_URL ?? 'http://127.0.0.1:8787',
+ changeOrigin: true,
+ configure: (proxy) => {
+ if (uiToken) proxy.on('proxyReq', (proxyReq, req) => {
+ const isRead = req.method === 'GET' || req.method === 'HEAD';
+ if (isRead || req.headers['x-requested-with'] !== undefined) {
+ proxyReq.setHeader('Authorization', `Bearer ${uiToken}`);
+ }
+ });
+ },
+ },
+ },
},
});