Skip to content

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

13.1 KB
Raw Blame
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 { 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';
import { writeLyrics } from './lyrics.js';
import { EnhanceError, enhancePrompt, type SkillFiles } from './enhance.js';
import { normalizeMusicApi, sameOrigin, SettingsStore } from './settings.js';
import { randomTitle } from './names.js';
import { FORMATS, type Template, type Track } from './types.js';
import { patchWavSizes, WAV_HEADER_BYTES } from './wav.js';
import { demoRouter, type DemoOptions } from './demo.js';

export interface AppDeps {
  library: Library;
  templates: JsonStore<Template>;
  settings: SettingsStore;
  upstream: UpstreamClient;
  queue: RenderQueue;
  tracksDir: string;
  staticDir?: string | null;
  /** MiniMax's caption-rewriter skill files, for POST /api/enhance */
  skill: SkillFiles;
  log?: (msg: string) => void;
  /** read-only public demo: showcase library, simulated per-visitor renders, no upstream, no writes */
  demo?: DemoOptions | null;
}

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> {
  let size: number;
  try { size = (await fs.stat(abs)).size; } catch { res.status(404).json({ error: 'no audio yet' }); return; }
  if (size < WAV_HEADER_BYTES) { res.status(404).json({ error: 'no audio yet' }); return; }
  const raw = Buffer.alloc(WAV_HEADER_BYTES);
  const fh = await fs.open(abs, 'r');
  try { await fh.read(raw, 0, WAV_HEADER_BYTES, 0); } finally { await fh.close(); }
  const header = patchWavSizes(raw, size);
  let start = 0, end = size - 1;
  const m = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range ?? '');
  if (m) {
    if (m[1]) start = Number(m[1]);
    if (m[2]) end = m[1] ? Math.min(size - 1, Number(m[2])) : size - 1;
    if (!m[1] && m[2]) start = Math.max(0, size - Number(m[2]));
    if (start > end || start >= size) { res.status(416).set('Content-Range', `bytes */${size}`).end(); return; }
  }
  res.status(m ? 206 : 200).set({
    'Content-Type': type, 'Accept-Ranges': 'bytes', 'Cache-Control': 'no-store',
    'Content-Length': String(end - start + 1),
    ...(m ? { 'Content-Range': `bytes ${start}-${end}/${size}` } : {}),
  });
  if (start < WAV_HEADER_BYTES) res.write(header.subarray(start, Math.min(WAV_HEADER_BYTES, end + 1)));
  if (end >= WAV_HEADER_BYTES) fsSync.createReadStream(abs, { start: Math.max(WAV_HEADER_BYTES, start), end }).pipe(res);
  else res.end();
}

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) => {
    try {
      const h = await upstream.health();
      res.json({ upstreamReachable: true, ready: h.ready, models: h.models, capabilities: h.capabilities, busy: queue.busy, queued: queue.queued, formats: FORMATS, enhance: settings.llm() !== null });
    } catch (err) {
      res.json({ upstreamReachable: false, ready: false, capabilities: [], busy: queue.busy, queued: queue.queued, formats: FORMATS, enhance: settings.llm() !== null, error: (err as Error).message });
    }
  });

  app.get('/api/library', (_req, res) => {
    res.json(library.all());
  });

  app.post('/api/generate', async (req, res, next) => {
    try {
      const g = normalizeGenerate(req.body);
      const groupId = randomUUID();
      const title = g.title || randomTitle();
      const created: Track[] = [];
      for (let i = 0; i < g.takes; i++) {
        const track: Track = {
          id: randomUUID(),
          groupId,
          takeIndex: i,
          title,
          prompt: g.prompt,
          lyrics: g.lyrics,
          duration: g.duration,
          seed: g.seed === null ? null : g.seed + i,
          format: g.format,
          status: 'queued',
          progress: 0,
          stage: 'queued',
          eta: null,
          stream: g.stream,
          renderedSeconds: null,
          error: null,
          file: null,
          createdAt: new Date().toISOString(),
          finishedAt: null,
        };
        await library.add(track);
        queue.enqueue(track.id);
        created.push(track);
      }
      res.status(201).json(created);
    } catch (err) {
      next(err);
    }
  });

  app.post('/api/enhance', async (req, res, next) => {
    try {
      const input = normalizeEnhance(req.body);
      const llm = settings.llm();
      if (!llm) return res.status(409).json({ error: 'Prompt enhancement is not configured — set an LLM in Settings' });
      res.json({ prompt: await enhancePrompt(input, llm, deps.skill) });
    } catch (err) {
      next(err);
    }
  });

  app.post('/api/lyrics', async (req, res, next) => {
    try {
      const input = normalizeLyrics(req.body);
      const llm = settings.llm();
      if (!llm) return res.status(409).json({ error: 'Lyrics writing is not configured — set an LLM in Settings' });
      res.json({ lyrics: await writeLyrics(input, llm) });
    } catch (err) {
      next(err);
    }
  });

  app.delete('/api/tracks/:id', async (req, res) => {
    const track = library.get(req.params.id);
    if (!track) return res.status(404).json({ error: 'not found' });
    if (track.status === 'queued' || track.status === 'running') queue.cancel(track.id);
    if (track.file) await fs.rm(path.join(tracksDir, track.file), { force: true });
    await library.remove(track.id);
    res.json({ ok: true });
  });

  app.get('/api/tracks/:id/audio', (req, res) => {
    const track = library.get(req.params.id);
    if (!track || !track.file) return res.status(404).json({ error: 'no audio' });
    const abs = path.join(tracksDir, track.file);
    const type = MIME[extFor(track.format)] ?? 'application/octet-stream';
    if (track.status === 'running') return void servePartialWav(req, res, abs, type);
    const download = req.query.download !== undefined;
    res.sendFile(abs, {
      headers: {
        'Content-Type': type,
        ...(download ? { 'Content-Disposition': `attachment; filename="${safeName(track.title)}.${extFor(track.format)}"` } : {}),
      },
    }, (err) => {
      if (err && !res.headersSent) res.status(404).json({ error: 'file missing' });
    });
  });

  app.get('/api/settings', (_req, res) => {
    res.json(settings.publicView());
  });

  app.put('/api/settings', async (req, res, next) => {
    try {
      const b = (req.body ?? {}) as Record<string, unknown>;
      await settings.update({ musicApi: b.musicApi, apiKey: b.apiKey, compat: b.compat, llmApi: b.llmApi, llmApiKey: b.llmApiKey, llmModel: b.llmModel });
      const e = settings.effective();
      upstream.configure(e.musicApi, e.apiKey, e.compat);
      log(`upstream reconfigured → ${e.musicApi}${e.apiKey ? ' (bearer set)' : ''}${e.compat ? ' (compat mode)' : ''}`);
      res.json(settings.publicView());
    } catch (err) {
      next(err);
    }
  });

  app.post('/api/settings/test', async (req, res) => {
    const b = (req.body ?? {}) as Record<string, unknown>;
    const e = settings.effective();
    const locked = settings.publicView().locked;
    let url = e.musicApi;
    let key = e.apiKey;
    try {
      if (typeof b.musicApi === 'string' && !locked.musicApi) {
        url = normalizeMusicApi(b.musicApi);
        if (!sameOrigin(e.musicApi, url)) {
          if (locked.apiKey) throw new ValidationError('MUSIC_API_KEY is set in the environment and cannot be used with a different musicApi origin');
          key = null;
        }
      }
      if (typeof b.apiKey === 'string' && !locked.apiKey) key = b.apiKey.trim() || null;
    } catch (err) {
      return res.status(400).json({ ok: false, error: (err as Error).message });
    }
    try {
      const h = await new UpstreamClient(url, key, e.compat).health();
      res.json({ ok: true, musicApi: url, health: { ...h, formats: FORMATS } });
    } catch (err) {
      res.json({ ok: false, musicApi: url, error: (err as Error).message });
    }
  });

  app.get('/api/templates', (_req, res) => {
    res.json(templates.all());
  });

  app.post('/api/templates', async (req, res, next) => {
    try {
      const b = (req.body ?? {}) as Record<string, unknown>;
      const name = typeof b.name === 'string' ? b.name.trim().slice(0, 80) : '';
      if (!name) throw new ValidationError('name is required');
      const g = normalizeGenerate({ ...b, prompt: b.prompt, takes: 1 });
      const existing = templates.all().find((t) => t.name.toLowerCase() === name.toLowerCase());
      const tpl: Template = {
        id: existing?.id ?? randomUUID(),
        name,
        prompt: g.prompt,
        lyrics: g.lyrics,
        duration: g.duration,
        format: g.format,
        createdAt: new Date().toISOString(),
      };
      if (existing) await templates.update(existing.id, tpl);
      else await templates.add(tpl);
      res.status(existing ? 200 : 201).json(tpl);
    } catch (err) {
      next(err);
    }
  });

  app.delete('/api/templates/:id', async (req, res) => {
    const removed = await templates.remove(req.params.id);
    if (!removed) return res.status(404).json({ error: 'not found' });
    res.json({ ok: true });
  });

  if (deps.staticDir) {
    app.use(express.static(deps.staticDir));
    app.get(/^(?!\/api\/).*/, (_req, res) => res.sendFile(path.join(deps.staticDir!, 'index.html')));
  }

  app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => {
    if (err instanceof ValidationError) return res.status(400).json({ error: err.message });
    if (err instanceof UpstreamError) return res.status(502).json({ error: err.message });
    if (err instanceof EnhanceError) return res.status(err.status).json({ error: err.message });
    if (err && typeof err === 'object' && 'type' in err && (err as { type: string }).type === 'entity.parse.failed') {
      return res.status(400).json({ error: 'invalid JSON' });
    }
    log(`unhandled: ${(err as Error).stack ?? err}`);
    res.status(500).json({ error: 'internal error' });
  });

  return app;
}

const safeName = (s: string) => s.replace(/[^\w\- ]+/g, '').trim().slice(0, 60) || 'track';