Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(api): public API surface with per-API auth gating (voice/TTS + sdapi)
Adam Eivy7ceb50ce2ed5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..72c9767da3--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,5 @@+# Unreleased Changes++## Added++- **Public API surface with per-API auth gating (Voice/TTS + sdapi):** PortOS can now serve individual services as HTTP APIs on your tailnet. A new **Settings → API Access** tab exposes per-API toggles — *Expose on the network* (off by default) and *Require auth* (off = passwordless) — so you can keep the whole app behind your PortOS password while leaving the **Voice/TTS** and **Image Gen (sdapi)** APIs open for other machines to call. A deliberately-minimal `POST /api/voice/public/synthesize` (plus `/voices` and `/engines`) turns text into WAV audio with any engine/voice/rate; config and process-control endpoints always stay gated. A single in-tree registry (`server/lib/apiRegistry.js`) drives the auth-gate exemptions, the settings UI, and a native **OpenAPI 3.1 spec** at `GET /api/api-docs/openapi.json` (no swagger dependency — request bodies are generated from the same Zod schemas the routes validate against). The API Access tab shows each API's public base URL and a copy-paste `curl` example, and the Voice settings tab links to it. Defaults are safe: both APIs ship not-exposed and passwordless-once-exposed, with a migration seeding the key for existing installs.diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex d6aaf78ccb..6460605efc 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -263,6 +263,7 @@ const navItems = [defaultTo: '/settings/general',children: [{ to: '/settings/ai-assignments', label: 'AI Assignments', icon: Bot },+ { to: '/settings/api-access', label: 'API Access', icon: Globe },{ to: '/settings/backup', label: 'Backup', icon: Download },{ to: '/settings/database', label: 'Database', icon: Database },{ to: '/settings/general', label: 'General', icon: Settings },diff --git a/client/src/components/settings/ApiAccessTab.jsx b/client/src/components/settings/ApiAccessTab.jsxnew file mode 100644index 0000000000..a0c6015263--- /dev/null+++ b/client/src/components/settings/ApiAccessTab.jsx@@ -0,0 +1,211 @@+import { useState, useEffect, useCallback } from 'react';+import { Globe, Lock, Unlock, Copy, RefreshCw } from 'lucide-react';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import { getSettings, updateSettings, getOpenApiSpec } from '../../services/apiSystem';+import { copyToClipboard } from '../../lib/clipboard';++// Mirror of server/lib/apiRegistry.js — the client can't import the server+// module, so the display metadata is duplicated here. The server stays the+// source of truth for gating; this only drives the UI cards. The OpenAPI spec+// (fetched below) is what actually reflects which paths exist per API.+const API_CARDS = [+ {+ id: 'voice',+ label: 'Voice / TTS',+ description: 'Text-to-speech synthesis and voice enumeration (Kokoro, Piper).',+ publicBase: '/api/voice/public',+ exampleCurl: (base) =>+ `curl -X POST ${base}/api/voice/public/synthesize \\\n` ++ ` -H 'content-type: application/json' \\\n` ++ ` -d '{"text":"Hello from PortOS","engine":"kokoro"}' \\\n` ++ ` --output speech.wav`,+ },+ {+ id: 'sdapi',+ label: 'Image Gen (A1111-compatible)',+ description: 'AUTOMATIC1111-compatible txt2img + model/sampler catalog. Also requires the "Expose A1111 API" toggle under Settings → Image Gen.',+ publicBase: '/sdapi/v1',+ exampleCurl: (base) =>+ `curl -X POST ${base}/sdapi/v1/txt2img \\\n` ++ ` -H 'content-type: application/json' \\\n` ++ ` -d '{"prompt":"a neon city","steps":20}'`,+ },+];++const DEFAULT_ACCESS = { exposed: false, requireAuth: false };++const Toggle = ({ checked, onChange, label, hint, disabled }) => (+ <label className={`flex items-start gap-3 ${disabled ? 'opacity-50' : 'cursor-pointer'}`}>+ <input+ type="checkbox"+ checked={checked}+ disabled={disabled}+ onChange={(e) => onChange(e.target.checked)}+ className="w-4 h-4 mt-0.5 shrink-0"+ />+ <div className="flex flex-col min-w-0 flex-1">+ <span className="text-sm text-white">{label}</span>+ {hint && <span className="text-xs text-gray-500">{hint}</span>}+ </div>+ </label>+);++export function ApiAccessTab() {+ const [loading, setLoading] = useState(true);+ const [savingId, setSavingId] = useState(null);+ const [access, setAccess] = useState({});+ const [spec, setSpec] = useState(null);++ // window.location.origin is the tailnet host the user is browsing from, so+ // the example curls are copy-pasteable from this machine.+ const baseUrl = typeof window !== 'undefined' ? window.location.origin : '';++ const loadSpec = useCallback(() => {+ getOpenApiSpec({ silent: true })+ .then(setSpec)+ .catch(() => setSpec(null));+ }, []);++ useEffect(() => {+ getSettings({ silent: true })+ .then((s) => setAccess(s?.apiAccess || {}))+ .catch(() => toast.error('Failed to load API access settings'))+ .finally(() => setLoading(false));+ loadSpec();+ }, [loadSpec]);++ const entryFor = (id) => ({ ...DEFAULT_ACCESS, ...(access[id] || {}) });++ // Persist a single API's flags. Optimistic local update; revert on failure.+ const patchAccess = async (id, partial) => {+ const prev = entryFor(id);+ const next = { ...prev, ...partial };+ setAccess((a) => ({ ...a, [id]: next }));+ setSavingId(id);+ try {+ await updateSettings({ apiAccess: { [id]: next } }, { silent: true });+ loadSpec(); // exposed-set changed → refresh the documented paths+ } catch (err) {+ setAccess((a) => ({ ...a, [id]: prev })); // revert+ toast.error(`Failed to save: ${err.message}`);+ } finally {+ setSavingId(null);+ }+ };++ if (loading) return <BrailleSpinner text="Loading API access settings" />;++ return (+ <div className="space-y-6">+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-2">+ <div className="flex items-center gap-2 text-white">+ <Globe size={18} />+ <h2 className="text-lg font-semibold">API Access</h2>+ </div>+ <p className="text-xs text-gray-500">+ Expose individual PortOS services as HTTP APIs on your network. When you enable a+ PortOS password (Settings → Security), the whole app is gated by default — but an+ exposed API here can stay <strong>passwordless</strong> so other machines on your+ tailnet can call it. Toggle <em>Require auth</em> to gate a specific API behind the+ password while leaving the rest open. Only read/synthesis endpoints are public;+ config and control endpoints always require the password.+ </p>+ </div>++ {API_CARDS.map((card) => {+ const entry = entryFor(card.id);+ const busy = savingId === card.id;+ return (+ <div key={card.id} className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="flex items-center gap-2 text-white">+ <h3 className="text-base font-semibold">{card.label}</h3>+ {entry.exposed ? (+ entry.requireAuth+ ? <span className="inline-flex items-center gap-1 text-xs text-port-warning"><Lock size={12} /> auth required</span>+ : <span className="inline-flex items-center gap-1 text-xs text-port-success"><Unlock size={12} /> passwordless</span>+ ) : (+ <span className="text-xs text-gray-500">not exposed</span>+ )}+ </div>+ <p className="text-xs text-gray-500 mt-1">{card.description}</p>+ </div>+ {busy && <BrailleSpinner />}+ </div>++ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <Toggle+ checked={entry.exposed}+ disabled={busy}+ onChange={(v) => patchAccess(card.id, { exposed: v })}+ label="Expose on the network"+ hint="Off by default. Nothing is reachable until you turn this on."+ />+ <Toggle+ checked={entry.requireAuth}+ disabled={busy || !entry.exposed}+ onChange={(v) => patchAccess(card.id, { requireAuth: v })}+ label="Require auth (password)"+ hint="When off, this API is callable without the PortOS password."+ />+ </div>++ <div className="space-y-2">+ <div className="text-xs text-gray-400">Public base URL</div>+ <code className="block bg-port-bg border border-port-border rounded-lg px-3 py-2 text-xs text-port-accent break-all">+ {baseUrl}{card.publicBase}+ </code>+ </div>++ <details className="text-xs text-gray-500">+ <summary className="cursor-pointer select-none">Example request</summary>+ <div className="mt-2 relative">+ <pre className="bg-port-bg border border-port-border rounded-lg p-3 overflow-x-auto text-[11px] text-gray-300 whitespace-pre">+{card.exampleCurl(baseUrl)}+ </pre>+ <button+ type="button"+ onClick={() => copyToClipboard(card.exampleCurl(baseUrl), 'Example copied')}+ className="absolute top-2 right-2 p-1.5 rounded bg-port-border hover:bg-port-border/70 text-white"+ aria-label="Copy example request"+ title="Copy example request"+ >+ <Copy size={12} />+ </button>+ </div>+ </details>+ </div>+ );+ })}++ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-2">+ <div className="flex items-center justify-between gap-2">+ <h3 className="text-base font-semibold text-white">OpenAPI spec</h3>+ <button+ type="button"+ onClick={loadSpec}+ className="inline-flex items-center gap-2 px-3 py-1.5 bg-port-border hover:bg-port-border/70 text-white text-xs rounded-lg"+ >+ <RefreshCw size={12} /> Refresh+ </button>+ </div>+ <p className="text-xs text-gray-500">+ Machine-readable description of every exposed API. Served at{' '}+ <code className="text-port-accent">/api/api-docs/openapi.json</code>.+ </p>+ {spec ? (+ <div className="text-xs text-gray-400">+ <span className="text-port-success">{Object.keys(spec.paths || {}).length}</span> path(s) documented+ {Object.keys(spec.paths || {}).length === 0 && ' — expose an API above to populate the spec.'}+ </div>+ ) : (+ <div className="text-xs text-gray-500">Spec unavailable.</div>+ )}+ </div>+ </div>+ );+}++export default ApiAccessTab;diff --git a/client/src/components/settings/SettingsTabsHeader.jsx b/client/src/components/settings/SettingsTabsHeader.jsxindex c10f6225c6..26fb0fcc39 100644--- a/client/src/components/settings/SettingsTabsHeader.jsx+++ b/client/src/components/settings/SettingsTabsHeader.jsx@@ -11,6 +11,7 @@ import TabPills from '../ui/TabPills';// pages use the `<tab>` slug; the standalone pages use `providers` / `prompts`.export const TABS = [{ id: 'ai-assignments', label: 'AI Assignments', to: '/settings/ai-assignments' },+ { id: 'api-access', label: 'API Access', to: '/settings/api-access' },{ id: 'autofixer', label: 'Autofixer', to: '/settings/autofixer' },{ id: 'backup', label: 'Backup', to: '/settings/backup' },{ id: 'catalog', label: 'Catalog', to: '/settings/catalog' },diff --git a/client/src/components/settings/VoiceTab.jsx b/client/src/components/settings/VoiceTab.jsxindex 4bc701afef..a6ba6f71c4 100644--- a/client/src/components/settings/VoiceTab.jsx+++ b/client/src/components/settings/VoiceTab.jsx@@ -1,5 +1,6 @@import { useState, useEffect, useCallback, useId, Children, cloneElement, isValidElement } from 'react';-import { Save, Mic, Play, Zap, RefreshCw } from 'lucide-react';+import { Link } from 'react-router-dom';+import { Save, Mic, Play, Zap, RefreshCw, Globe } from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import {@@ -312,6 +313,17 @@ export function VoiceTab() {))}</div>+ <div className="flex items-start gap-3 bg-port-bg border border-port-border rounded-lg p-3">+ <Globe size={16} className="text-port-accent mt-0.5 shrink-0" />+ <div className="text-xs text-gray-400 min-w-0">+ <span className="text-white">Serve TTS as an API.</span>{' '}+ Expose <code className="text-port-accent">POST /api/voice/public/synthesize</code> so other+ machines on your tailnet can request audio (any engine/voice). Configure exposure and+ passwordless/auth gating under{' '}+ <Link to="/settings/api-access" className="text-port-accent hover:underline">Settings → API Access</Link>.+ </div>+ </div>+<div className="grid grid-cols-1 md:grid-cols-2 gap-4"><Field label="Hotkey" hint="Hold to talk (keyboard)."><inputdiff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex a1e5ebeaaf..8f7d4ea76c 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -1,4 +1,5 @@import { useParams, Navigate } from 'react-router-dom';+import { ApiAccessTab } from '../components/settings/ApiAccessTab';import { AutofixerTab } from '../components/settings/AutofixerTab';import AiAssignmentsTab from '../components/settings/AiAssignmentsTab';import { BackupTab } from '../components/settings/BackupTab';@@ -33,6 +34,7 @@ export default function Settings() {switch (activeTab) {case 'general': return <GeneralTab />;case 'ai-assignments': return <AiAssignmentsTab />;+ case 'api-access': return <ApiAccessTab />;case 'autofixer': return <AutofixerTab />;case 'backup': return <BackupTab />;case 'catalog': return <CatalogTypesTab />;diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 294b7e4dad..fb7193dd51 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -42,6 +42,10 @@ export const updateSettings = (data, options) => request('/settings', {...options});export const getAiAssignments = (options) => request('/settings/ai-assignments', options);++// API Access — the OpenAPI 3.1 spec for the public API surface (built from the+// exposed entries in apiAccess settings). Rendered by the API Access settings tab.+export const getOpenApiSpec = (options) => request('/api-docs/openapi.json', options);export const updateAiAssignment = (id, data, options) => request(`/settings/ai-assignments/${encodeURIComponent(id)}`, {method: 'PUT',body: JSON.stringify(data),diff --git a/data.reference/settings.json b/data.reference/settings.jsonindex 40836dadb3..3fd040e6c7 100644--- a/data.reference/settings.json+++ b/data.reference/settings.json@@ -50,5 +50,9 @@"enabled": true,"intervalMinutes": 5,"maxSnapshots": 1000+ },+ "apiAccess": {+ "voice": { "exposed": false, "requireAuth": false },+ "sdapi": { "exposed": false, "requireAuth": false }}}\ No newline at end of filediff --git a/scripts/migrations/082-seed-api-access-defaults.js b/scripts/migrations/082-seed-api-access-defaults.jsnew file mode 100644index 0000000000..64eead60fe--- /dev/null+++ b/scripts/migrations/082-seed-api-access-defaults.js@@ -0,0 +1,78 @@+/**+ * Migration 082 — seed the `apiAccess` settings key for existing installs.+ *+ * The public API surface (server/lib/apiRegistry.js) reads per-API exposure+ * flags from `settings.apiAccess.{voice,sdapi}`. Fresh installs get the block+ * from data.reference/settings.json, but `scripts/setup-data.js` only merges+ * NEW keys into a handful of structured JSONs (stage-config, variables,+ * providers) — NOT settings.json. So an existing install would never gain the+ * key from setup-data alone.+ *+ * This migration adds the default `apiAccess` block (both APIs not-exposed ++ * passwordless) when it's absent, so the Settings UI renders a clean persisted+ * state. The registry already falls back to the same defaults when the key is+ * missing, so behavior is correct even before this runs — this is purely about+ * materializing the key on disk.+ *+ * Idempotent: if `apiAccess` already exists (any value), it's left untouched.+ * ENOENT (no settings.json yet) → skip; a fresh install copies the seeded file+ * from data.reference. Runs in the boot-time migration runner before the+ * service layer is wired, so it reads/writes settings.json directly.+ */++import { readFile, writeFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';++export const API_ACCESS_DEFAULTS = Object.freeze({+ voice: { exposed: false, requireAuth: false },+ sdapi: { exposed: false, requireAuth: false },+});++/**+ * Pure transform, exported for tests. Returns `{ settings, changed }`.+ * Adds the default `apiAccess` block only when absent. Never overwrites an+ * existing value (even a partial / hand-edited one).+ */+export function computeApiAccessSeed(settings) {+ if (!settings || typeof settings !== 'object') return { settings, changed: false };+ if (settings.apiAccess !== undefined) return { settings, changed: false };+ return {+ settings: { ...settings, apiAccess: { ...API_ACCESS_DEFAULTS } },+ changed: true,+ };+}++export async function up({ rootDir }) {+ const settingsPath = join(rootDir, 'data', 'settings.json');+ if (!existsSync(settingsPath)) {+ console.log('🔌 api-access-seed: no settings.json yet — fresh install seeds from data.reference.');+ return { ok: true, reason: 'no-state' };+ }++ const raw = await readFile(settingsPath, 'utf-8').catch(() => null);+ if (raw == null) {+ console.log('🔌 api-access-seed: settings.json unreadable — skipping.');+ return { ok: false, reason: 'unreadable' };+ }++ let settings;+ try {+ settings = JSON.parse(raw);+ } catch {+ console.log('🔌 api-access-seed: settings.json is not valid JSON — skipping.');+ return { ok: false, reason: 'invalid-json' };+ }++ const { settings: next, changed } = computeApiAccessSeed(settings);+ if (!changed) {+ console.log('🔌 api-access-seed: apiAccess already present — no-op.');+ return { ok: true, reason: 'already-present' };+ }++ await writeFile(settingsPath, JSON.stringify(next, null, 2) + '\n');+ console.log('🔌 api-access-seed: added default apiAccess block (voice + sdapi, not-exposed + passwordless).');+ return { ok: true, reason: 'seeded' };+}++export default { up };diff --git a/scripts/migrations/082-seed-api-access-defaults.test.js b/scripts/migrations/082-seed-api-access-defaults.test.jsnew file mode 100644index 0000000000..e310871f1e--- /dev/null+++ b/scripts/migrations/082-seed-api-access-defaults.test.js@@ -0,0 +1,83 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration, { computeApiAccessSeed, API_ACCESS_DEFAULTS } from './082-seed-api-access-defaults.js';++let rootDir;+let dataDir;++beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-082-'));+ dataDir = join(rootDir, 'data');+ mkdirSync(dataDir, { recursive: true });+});++afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+});++const writeSettings = (obj) => writeFileSync(join(dataDir, 'settings.json'), JSON.stringify(obj, null, 2) + '\n');+const readSettings = () => JSON.parse(readFileSync(join(dataDir, 'settings.json'), 'utf-8'));++describe('computeApiAccessSeed (pure)', () => {+ it('adds the default apiAccess block when absent', () => {+ const { settings, changed } = computeApiAccessSeed({ timezone: 'UTC' });+ expect(changed).toBe(true);+ expect(settings.apiAccess).toEqual(API_ACCESS_DEFAULTS);+ expect(settings.timezone).toBe('UTC'); // preserved+ });++ it('leaves an existing apiAccess value untouched (idempotent)', () => {+ const existing = { apiAccess: { voice: { exposed: true, requireAuth: true } } };+ const { settings, changed } = computeApiAccessSeed(existing);+ expect(changed).toBe(false);+ expect(settings.apiAccess.voice.exposed).toBe(true);+ });++ it('does not overwrite a partial hand-edited apiAccess', () => {+ const existing = { apiAccess: { sdapi: { exposed: true } } };+ const { changed } = computeApiAccessSeed(existing);+ expect(changed).toBe(false);+ });++ it('handles a non-object input gracefully', () => {+ expect(computeApiAccessSeed(null).changed).toBe(false);+ });+});++describe('migration 082 up()', () => {+ it('skips when settings.json is absent (fresh install)', async () => {+ const result = await migration.up({ rootDir });+ expect(result.reason).toBe('no-state');+ expect(existsSync(join(dataDir, 'settings.json'))).toBe(false);+ });++ it('seeds the default block when missing', async () => {+ writeSettings({ timezone: 'UTC' });+ const result = await migration.up({ rootDir });+ expect(result.reason).toBe('seeded');+ expect(readSettings().apiAccess).toEqual(API_ACCESS_DEFAULTS);+ });++ it('is a no-op when apiAccess already present', async () => {+ writeSettings({ apiAccess: { voice: { exposed: true, requireAuth: false } } });+ const result = await migration.up({ rootDir });+ expect(result.reason).toBe('already-present');+ expect(readSettings().apiAccess.voice.exposed).toBe(true);+ });++ it('skips invalid JSON without throwing', async () => {+ writeFileSync(join(dataDir, 'settings.json'), '{ not valid');+ const result = await migration.up({ rootDir });+ expect(result.reason).toBe('invalid-json');+ });++ it('re-running after seeding is idempotent', async () => {+ writeSettings({ timezone: 'UTC' });+ await migration.up({ rootDir });+ const result = await migration.up({ rootDir });+ expect(result.reason).toBe('already-present');+ });+});diff --git a/server/index.js b/server/index.jsindex 44b165708b..e7fa2902c3 100644--- a/server/index.js+++ b/server/index.js@@ -57,6 +57,8 @@ import digitalTwinRoutes from './routes/digital-twin.js';import socialAccountsRoutes from './routes/socialAccounts.js';import lmstudioRoutes from './routes/lmstudio.js';import voiceRoutes from './routes/voice.js';+import voicePublicRoutes from './routes/voicePublic.js';+import apiDocsRoutes from './routes/apiDocs.js';import { getVoiceConfig } from './services/voice/config.js';import { reconcile as reconcileVoice } from './services/voice/bootstrap.js';import { initVoiceTimers } from './services/voice/timers.js';@@ -478,7 +480,14 @@ app.use('/api/digital-twin', digitalTwinRoutes);app.use('/api/lmstudio', lmstudioRoutes);app.use('/api/local-llm', localLlmRoutes);app.use('/api/code-review', codeReviewRoutes);+// Public, externally-callable TTS surface. Mounted BEFORE the main voice+// router for readability; Express matches the more specific `/api/voice/public`+// regardless of order since `voiceRoutes` defines no `/public/*` paths. This+// mount is the only voice surface `authGate` will re-open when exposed — the+// main `/api/voice` router (config/whisper/etc.) stays fully gated.+app.use('/api/voice/public', voicePublicRoutes);app.use('/api/voice', voiceRoutes);+app.use('/api/api-docs', apiDocsRoutes);app.use('/api/browser', browserRoutes);app.use('/api/data', dataManagerRoutes);app.use('/api/datadog', datadogRoutes);diff --git a/server/lib/README.md b/server/lib/README.mdindex 39bace10c7..c12d8fc2ba 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -201,13 +201,15 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|+| `apiRegistry.js` | Single source of truth for which PortOS services are externally-callable HTTP APIs (`voice`, `sdapi`). `API_REGISTRY` declares each API's `publicPrefixes` (read/compute-safe surface only) + defaults; `isRegistryPublic(settings, path)` tells `authGate` when an `exposed && !requireAuth` API re-opens its prefix; `resolveApiAccess(settings)` merges persisted `apiAccess` flags for the Settings UI + OpenAPI docs. || `asyncMutex.js` | Promise-based async mutex. |-| `authGate.js` | Express + Socket.IO middleware that gates `/api/*` and `/data/*` behind the password set in `settings.secrets.auth`. No-op when auth is off; emits 401 `AUTH_REQUIRED` (or plain text for `/data/*`) when on and the request has no valid session token. |+| `authGate.js` | Express + Socket.IO middleware that gates `/api/*` and `/data/*` behind the password set in `settings.secrets.auth`. No-op when auth is off; emits 401 `AUTH_REQUIRED` (or plain text for `/data/*`) when on and the request has no valid session token. Consults `apiRegistry.isRegistryPublic` so an exposed+passwordless API (voice/sdapi) bypasses the gate on its public prefix only. || `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). || `domainBudgets.js` | Per-domain daily autonomy budgets (pure). `BUDGET_LIMIT_FIELDS` (`maxActionsPerDay`/`maxMinutesPerDay`), `getDomainBudget(config, id)`, `normalizeDomainBudgets(raw)`, `hasBudget(budget)`, and `evaluateBudget(budget, usage)` → `{ withinBudget, exceeded }`. A `null`/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in `services/domainUsage.js`. || `errorHandler.js` | `ServerError` + `asyncHandler` middleware. || `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. || `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |+| `openapiSpec.js` | `buildOpenApiSpec(settings, { baseUrl, version })` — builds an OpenAPI 3.1 document for the currently-exposed public APIs from `apiRegistry`, reusing route Zod schemas via `z.toJSONSchema`. Exposed+`requireAuth` operations get a `security` requirement; passwordless ones don't. Served by `routes/apiDocs.js`. || `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. || `sseUtils.js` | Per-job SSE stream helpers (imageGen + others). || `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |diff --git a/server/lib/apiRegistry.js b/server/lib/apiRegistry.jsnew file mode 100644index 0000000000..113ea946e5--- /dev/null+++ b/server/lib/apiRegistry.js@@ -0,0 +1,100 @@+/**+ * Public API registry — the single source of truth for which PortOS services+ * are usable as externally-callable HTTP APIs.+ *+ * One declaration here drives THREE consumers, so they can never drift:+ * 1. `authGate` (server/lib/authGate.js) — when the PortOS password is on, an+ * entry that is `exposed && !requireAuth` re-opens ONLY its `publicPrefixes`+ * so external callers can reach it without a session.+ * 2. The Settings UI (VoiceTab + the API Access page) — renders the per-API+ * `exposed` / `requireAuth` toggles via `resolveApiAccess()`.+ * 3. The OpenAPI spec builder (server/lib/openapiSpec.js) — documents each+ * exposed API's `docPaths`.+ *+ * SECURITY INVARIANT: `publicPrefixes` lists ONLY read/compute-safe surfaces.+ * Config-mutation / process-control routes (e.g. `/api/voice/config`,+ * `/api/voice/whisper`) are deliberately NOT listed here and stay gated. The+ * voice API uses a dedicated `/api/voice/public/*` mount precisely so the+ * public surface is an explicit allowlist that cannot accidentally grow when a+ * new route is added to the main `/api/voice` router.+ *+ * Per-API runtime state (`exposed`, `requireAuth`) lives in the top-level+ * `apiAccess` settings key — NOT under `secrets` (which is stripped from+ * GET /api/settings), so the client can read these flags to render toggles.+ */++// Static declaration. `defaults` apply when an install has no persisted+// `apiAccess.<settingsKey>` value yet (fresh install / pre-migration): both+// APIs default to NOT exposed (nothing on the network until the user opts in)+// and passwordless (requireAuth:false) once exposed.+export const API_REGISTRY = [+ {+ id: 'voice',+ label: 'Voice / TTS',+ description: 'Text-to-speech synthesis and voice enumeration (Kokoro, Piper).',+ publicPrefixes: ['/api/voice/public/'],+ settingsKey: 'voice',+ defaults: { exposed: false, requireAuth: false },+ docPaths: [+ '/api/voice/public/synthesize',+ '/api/voice/public/voices',+ '/api/voice/public/engines',+ ],+ },+ {+ id: 'sdapi',+ label: 'Image Gen (A1111-compatible)',+ description: 'AUTOMATIC1111-compatible txt2img + model/sampler catalog.',+ publicPrefixes: ['/sdapi/'],+ settingsKey: 'sdapi',+ defaults: { exposed: false, requireAuth: false },+ docPaths: [+ '/sdapi/v1/txt2img',+ '/sdapi/v1/sd-models',+ '/sdapi/v1/samplers',+ '/sdapi/v1/options',+ '/sdapi/v1/progress',+ ],+ },+];++// Resolve one registry entry's runtime flags against persisted settings,+// falling back to the entry's defaults when `apiAccess.<settingsKey>` (or a+// specific flag) is absent. The `?? defaults` fallback is what keeps an install+// with no `apiAccess` key (fresh / pre-migration) fully gated.+const resolveEntry = (entry, settings) => {+ const persisted = settings?.apiAccess?.[entry.settingsKey] ?? {};+ return {+ ...entry,+ exposed: persisted.exposed ?? entry.defaults.exposed,+ requireAuth: persisted.requireAuth ?? entry.defaults.requireAuth,+ };+};++/**+ * True iff some registry entry is `exposed && !requireAuth` AND `path` starts+ * with one of that entry's `publicPrefixes`. This is the ONLY thing that+ * re-opens a gated prefix when the PortOS password is on — and it matches only+ * `publicPrefixes`, so mutation routes outside those prefixes stay gated.+ * @param {object} settings full settings object (NOT the secrets-stripped copy)+ * @param {string} path request path (req.path)+ * @returns {boolean}+ */+export const isRegistryPublic = (settings, path) => {+ if (typeof path !== 'string') return false;+ for (const entry of API_REGISTRY) {+ const { exposed, requireAuth } = resolveEntry(entry, settings);+ if (!exposed || requireAuth) continue;+ if (entry.publicPrefixes.some((prefix) => path.startsWith(prefix))) return true;+ }+ return false;+};++/**+ * Merge each registry entry's static metadata with its persisted `exposed` /+ * `requireAuth` flags. Consumed by the Settings UI and the OpenAPI builder.+ * @param {object} settings full settings object+ * @returns {Array<object>} registry entries decorated with resolved flags+ */+export const resolveApiAccess = (settings) =>+ API_REGISTRY.map((entry) => resolveEntry(entry, settings));diff --git a/server/lib/apiRegistry.test.js b/server/lib/apiRegistry.test.jsnew file mode 100644index 0000000000..a384b67960--- /dev/null+++ b/server/lib/apiRegistry.test.js@@ -0,0 +1,112 @@+import { describe, it, expect } from 'vitest';+import { API_REGISTRY, isRegistryPublic, resolveApiAccess } from './apiRegistry.js';++const settingsWith = (apiAccess) => ({ apiAccess });++describe('apiRegistry', () => {+ describe('API_REGISTRY shape', () => {+ it('declares voice and sdapi with required fields', () => {+ const ids = API_REGISTRY.map((a) => a.id);+ expect(ids).toContain('voice');+ expect(ids).toContain('sdapi');+ for (const entry of API_REGISTRY) {+ expect(typeof entry.id).toBe('string');+ expect(typeof entry.label).toBe('string');+ expect(Array.isArray(entry.publicPrefixes)).toBe(true);+ expect(entry.publicPrefixes.length).toBeGreaterThan(0);+ expect(typeof entry.settingsKey).toBe('string');+ expect(typeof entry.defaults.exposed).toBe('boolean');+ expect(typeof entry.defaults.requireAuth).toBe('boolean');+ }+ });++ it('defaults both APIs to not-exposed + passwordless', () => {+ for (const entry of API_REGISTRY) {+ expect(entry.defaults.exposed).toBe(false);+ expect(entry.defaults.requireAuth).toBe(false);+ }+ });++ it('never lists a mutation/config path in publicPrefixes', () => {+ const voice = API_REGISTRY.find((a) => a.id === 'voice');+ // The voice public surface is a dedicated sub-mount, NOT the main router.+ expect(voice.publicPrefixes).toEqual(['/api/voice/public/']);+ expect(voice.publicPrefixes.some((p) => p === '/api/voice/')).toBe(false);+ });+ });++ describe('isRegistryPublic', () => {+ it('returns false when no apiAccess settings present (pre-migration)', () => {+ expect(isRegistryPublic({}, '/api/voice/public/synthesize')).toBe(false);+ expect(isRegistryPublic(undefined, '/api/voice/public/synthesize')).toBe(false);+ });++ it('opens a public prefix when exposed && !requireAuth', () => {+ const s = settingsWith({ voice: { exposed: true, requireAuth: false } });+ expect(isRegistryPublic(s, '/api/voice/public/synthesize')).toBe(true);+ expect(isRegistryPublic(s, '/api/voice/public/voices')).toBe(true);+ });++ it('stays gated when exposed but requireAuth', () => {+ const s = settingsWith({ voice: { exposed: true, requireAuth: true } });+ expect(isRegistryPublic(s, '/api/voice/public/synthesize')).toBe(false);+ });++ it('stays gated when not exposed even if passwordless', () => {+ const s = settingsWith({ voice: { exposed: false, requireAuth: false } });+ expect(isRegistryPublic(s, '/api/voice/public/synthesize')).toBe(false);+ });++ it('NEVER opens a mutation path even when the API is exposed+passwordless', () => {+ const s = settingsWith({ voice: { exposed: true, requireAuth: false } });+ // These are NOT under /api/voice/public/ — they must stay gated.+ expect(isRegistryPublic(s, '/api/voice/config')).toBe(false);+ expect(isRegistryPublic(s, '/api/voice/whisper')).toBe(false);+ expect(isRegistryPublic(s, '/api/voice/test')).toBe(false);+ });++ it('opens sdapi when exposed+passwordless', () => {+ const s = settingsWith({ sdapi: { exposed: true, requireAuth: false } });+ expect(isRegistryPublic(s, '/sdapi/v1/txt2img')).toBe(true);+ });++ it('resolves each API independently', () => {+ const s = settingsWith({+ voice: { exposed: true, requireAuth: false },+ sdapi: { exposed: false, requireAuth: false },+ });+ expect(isRegistryPublic(s, '/api/voice/public/synthesize')).toBe(true);+ expect(isRegistryPublic(s, '/sdapi/v1/txt2img')).toBe(false);+ });++ it('returns false for non-string path', () => {+ expect(isRegistryPublic(settingsWith({ voice: { exposed: true } }), null)).toBe(false);+ });+ });++ describe('resolveApiAccess', () => {+ it('falls back to defaults when apiAccess absent', () => {+ const resolved = resolveApiAccess({});+ const voice = resolved.find((a) => a.id === 'voice');+ expect(voice.exposed).toBe(false);+ expect(voice.requireAuth).toBe(false);+ });++ it('merges persisted flags over defaults', () => {+ const resolved = resolveApiAccess(settingsWith({ voice: { exposed: true, requireAuth: true } }));+ const voice = resolved.find((a) => a.id === 'voice');+ expect(voice.exposed).toBe(true);+ expect(voice.requireAuth).toBe(true);+ // Static metadata preserved.+ expect(voice.label).toBe('Voice / TTS');+ expect(voice.docPaths.length).toBeGreaterThan(0);+ });++ it('uses default for a flag the persisted entry omits', () => {+ const resolved = resolveApiAccess(settingsWith({ voice: { exposed: true } }));+ const voice = resolved.find((a) => a.id === 'voice');+ expect(voice.exposed).toBe(true);+ expect(voice.requireAuth).toBe(false); // default+ });+ });+});diff --git a/server/lib/authGate.js b/server/lib/authGate.jsindex 9177788850..50b3d60cda 100644--- a/server/lib/authGate.js+++ b/server/lib/authGate.js@@ -1,6 +1,7 @@import { createHash } from 'node:crypto';import { extractToken, isAuthEnabled, verifyPassword, verifySession } from '../services/auth.js';-import { settingsEvents } from '../services/settings.js';+import { getSettings, settingsEvents } from '../services/settings.js';+import { isRegistryPublic } from './apiRegistry.js';// Paths that bypass the auth gate even when a password is set:// - /api/auth/status, /api/auth/whoami, /api/auth/login → the login UI@@ -132,6 +133,16 @@ export const authGate = async (req, res, next) => {}const path = req.path;if (isPublicPath(path)) return next();+ // Per-API public exemptions. When the user has marked an API exposed ++ // passwordless in Settings (`apiAccess.<id>`), re-open ONLY its declared+ // public prefix (e.g. /api/voice/public/, /sdapi/). `isRegistryPublic`+ // matches only those prefixes, so config-mutation routes outside them+ // (/api/voice/config, etc.) stay gated. This sits AFTER the cross-origin+ // CSRF guard above (a public API is still not a CSRF bypass) and after the+ // static public-path set. `getSettings()` is a cheap file read; no cache is+ // introduced here so a Settings toggle takes effect on the very next request.+ const settings = await getSettings();+ if (isRegistryPublic(settings, path)) return next();const token = extractToken(req);if (await verifySession(token)) return next();// Also accept HTTP Basic auth — used by peer-to-peer federation probes.@@ -155,6 +166,11 @@ export const authGate = async (req, res, next) => {// `req.headers.cookie` is available on `socket.handshake.headers`. When auth// is off, every connection is allowed; when on, the handshake must carry a// valid cookie/header.+//+// NOTE: there is intentionally NO `isRegistryPublic` check here. The public+// API surface (apiRegistry) is HTTP-only — external callers hit REST endpoints,+// not the interactive socket. The socket carries the authenticated UI session+// (voice streaming, live updates) and must stay fully gated when auth is on.export const socketAuthGate = async (socket, next) => {const enabled = await isAuthEnabled();if (!enabled) return next();diff --git a/server/lib/authGate.test.js b/server/lib/authGate.test.jsindex b50e4558a8..4ac8d700c7 100644--- a/server/lib/authGate.test.js+++ b/server/lib/authGate.test.js@@ -1,5 +1,5 @@import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';-import { writeFileSync } from 'fs';+import { readFileSync, writeFileSync } from 'fs';import { join } from 'path';import { mockPathsDataRoot } from './mockPathsDataRoot.js';@@ -15,6 +15,15 @@ const resetSettings = () => {writeFileSync(join(tempRoot, 'auth-sessions.json'), '{"tokens":[]}\n');};+// Merge an apiAccess block into settings.json (preserving any auth secrets a+// prior setPassword() call wrote). setPassword persists secrets to the same+// file, so read-modify-write rather than clobbering.+const writeApiAccess = (apiAccess) => {+ const raw = JSON.parse(readFileSync(join(tempRoot, 'settings.json'), 'utf-8'));+ raw.apiAccess = apiAccess;+ writeFileSync(join(tempRoot, 'settings.json'), JSON.stringify(raw, null, 2) + '\n');+};+beforeEach(() => {vi.resetModules();resetSettings();@@ -234,6 +243,84 @@ describe('authGate middleware', () => {});});+describe('authGate per-API public registry (apiAccess)', () => {+ it('opens /api/voice/public/* when voice is exposed + passwordless', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ writeApiAccess({ voice: { exposed: true, requireAuth: false } });+ const { authGate } = await import('./authGate.js');+ const synth = await runGate(authGate, { path: '/api/voice/public/synthesize', headers: {} });+ expect(synth.called).toBe(true);+ const voices = await runGate(authGate, { path: '/api/voice/public/voices', headers: {} });+ expect(voices.called).toBe(true);+ });++ it('KEEPS mutation routes gated even when voice is exposed + passwordless', async () => {+ // The key safety invariant: exposing the public surface must NOT open the+ // config / process-control routes on the main /api/voice router.+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ writeApiAccess({ voice: { exposed: true, requireAuth: false } });+ const { authGate } = await import('./authGate.js');+ for (const path of ['/api/voice/config', '/api/voice/whisper', '/api/voice/test']) {+ const result = await runGate(authGate, { path, headers: {} });+ expect(result.called).toBe(false);+ expect(result.res.statusCode).toBe(401);+ }+ });++ it('gates the public surface when exposed but requireAuth is true', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ writeApiAccess({ voice: { exposed: true, requireAuth: true } });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, { path: '/api/voice/public/synthesize', headers: {} });+ expect(result.called).toBe(false);+ expect(result.res.statusCode).toBe(401);+ });++ it('gates the public surface when not exposed', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ writeApiAccess({ voice: { exposed: false, requireAuth: false } });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, { path: '/api/voice/public/synthesize', headers: {} });+ expect(result.called).toBe(false);+ expect(result.res.statusCode).toBe(401);+ });++ it('opens /sdapi/* when sdapi is exposed + passwordless', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ writeApiAccess({ sdapi: { exposed: true, requireAuth: false } });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, { path: '/sdapi/v1/txt2img', headers: {} });+ expect(result.called).toBe(true);+ });++ it('still applies the CSRF cross-origin guard to an exposed public path', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ writeApiAccess({ voice: { exposed: true, requireAuth: false } });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, {+ path: '/api/voice/public/synthesize',+ headers: { host: 'portos.tailnet.ts.net', origin: 'https://evil.tailnet.ts.net' },+ });+ expect(result.called).toBe(false);+ expect(result.res.statusCode).toBe(403);+ expect(result.res.body.code).toBe('CROSS_ORIGIN_BLOCKED');+ });++ it('ignores apiAccess entirely when auth is disabled (no regression)', async () => {+ // Auth off → everything passes regardless of apiAccess flags.+ writeApiAccess({ voice: { exposed: false, requireAuth: true } });+ const { authGate } = await import('./authGate.js');+ const result = await runGate(authGate, { path: '/api/voice/public/synthesize', headers: {} });+ expect(result.called).toBe(true);+ });+});+describe('authGate HTTP Basic auth (peer federation)', () => {const basicHeader = (password, username = '') =>`Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;diff --git a/server/lib/index.js b/server/lib/index.jsindex d653a98b8c..7a505d62b4 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -168,6 +168,7 @@ export * from './ports.js';export * from './timezone.js';// === General utilities ===+export * from './apiRegistry.js';export * from './asyncMutex.js';export * from './authGate.js';export * from './domainAutonomy.js';@@ -175,6 +176,7 @@ export * from './domainBudgets.js';export * from './errorHandler.js';export * from './mapWithConcurrency.js';export * from './objects.js';+export * from './openapiSpec.js';export * from './singleFlight.js';export * from './streamBackpressure.js';export * from './sseUtils.js';diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 889d81fe70..504cd8c7c2 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -142,6 +142,7 @@ export const NAV_COMMANDS = [{ id: 'nav.post.wordplay', path: '/post/wordplay', label: 'Wordplay', section: 'POST', aliases: ['post-wordplay'] },{ id: 'nav.settings.ai-assignments', path: '/settings/ai-assignments', label: 'AI Assignments', section: 'Settings', aliases: ['ai-assignments', 'assignments', 'settings-ai-assignments', 'ai-inventory'], keywords: ['provider', 'model', 'pin', 'inventory', 'migration', 'llm'] },+ { id: 'nav.settings.api-access', path: '/settings/api-access', label: 'API Access', section: 'Settings', aliases: ['api-access', 'settings-api-access', 'public-api', 'swagger', 'openapi'], keywords: ['rest', 'external', 'tts api', 'sdapi', 'voice api', 'docs', 'curl', 'expose', 'passwordless', 'auth gating'] },{ id: 'nav.settings.autofixer', path: '/settings/autofixer', label: 'Autofixer', section: 'Settings', aliases: ['autofixer', 'settings-autofixer', 'auto-fixer'], keywords: ['crash', 'fix', 'pm2', 'repair', 'ai provider', 'restart'] },{ id: 'nav.settings.backup', path: '/settings/backup', label: 'Backup', section: 'Settings', aliases: ['backup', 'settings-backup'] },{ id: 'nav.settings.catalog', path: '/settings/catalog', label: 'Catalog Types', section: 'Settings', aliases: ['settings-catalog', 'catalog-types'], keywords: ['catalog', 'types', 'character', 'place', 'object', 'taxonomy'] },diff --git a/server/lib/openapiSpec.js b/server/lib/openapiSpec.jsnew file mode 100644index 0000000000..9db8892c7d--- /dev/null+++ b/server/lib/openapiSpec.js@@ -0,0 +1,140 @@+/**+ * OpenAPI 3.1 spec builder for PortOS's public API surface.+ *+ * Native (no swagger-ui dependency): builds the document from the API registry+ * (server/lib/apiRegistry.js) plus per-path operation metadata declared here.+ * Request bodies reuse the same Zod schemas the routes validate against+ * (via `z.toJSONSchema`), so the docs can't drift from validation.+ *+ * Only APIs that are currently `exposed` appear in `paths`. An exposed API+ * with `requireAuth:true` gets a `security` requirement on each of its+ * operations; a passwordless one omits it (anonymous access allowed).+ */++import { z } from 'zod';+import { resolveApiAccess } from './apiRegistry.js';++// Request-body schema for POST /api/voice/public/synthesize. A LIGHT copy of+// the route's schema (routes/voicePublic.js) — kept here rather than imported+// because the route file pulls in heavy TTS service modules and this builder+// must stay a pure, dependency-light lib module. The two are asserted to+// produce identical JSON Schema by the parity test in openapiSpec.test.js, so+// they can't silently drift.+// `text` max mirrors MAX_PROACTIVE_TEXT_LEN (4000) used by the route. If that+// constant changes, the parity test in openapiSpec.test.js fails until this is+// updated to match — so the documented limit can't understate the real one.+// Mirrors the route schema field-for-field, including `.trim()` (which the+// route applies so whitespace-only text 400s). `.trim()` doesn't surface in+// `z.toJSONSchema` output, so the parity test can't catch its absence — keep+// it here by hand so the two definitions stay literally identical.+const synthesizeBodySchema = z.object({+ text: z.string().trim().min(1).max(4000),+ engine: z.enum(['kokoro', 'piper']).optional(),+ voice: z.string().max(128).optional(),+ rate: z.number().min(0.25).max(4).optional(),+});++const jsonSchema = (schema) => {+ const s = z.toJSONSchema(schema);+ // OpenAPI 3.1 path objects don't want the top-level $schema dialect marker.+ delete s.$schema;+ return s;+};++// Per-path operation metadata, keyed by the path strings in API_REGISTRY's+// `docPaths`. A path absent here still appears as a bare documented path (so+// the registry stays the source of truth for WHICH paths exist) but with a+// generic description.+const OPERATIONS = {+ '/api/voice/public/synthesize': {+ post: {+ summary: 'Synthesize speech',+ description: 'Convert text to spoken audio (WAV) using the selected engine and voice.',+ requestBody: {+ required: true,+ content: { 'application/json': { schema: jsonSchema(synthesizeBodySchema) } },+ },+ responses: {+ 200: { description: 'WAV audio', content: { 'audio/wav': { schema: { type: 'string', format: 'binary' } } } },+ 400: { description: 'Invalid payload or unknown voice' },+ },+ },+ },+ '/api/voice/public/voices': {+ get: {+ summary: 'List voices',+ description: 'Enumerate available voices for an engine (query param `engine`, default = active).',+ parameters: [{ name: 'engine', in: 'query', required: false, schema: { type: 'string', enum: ['kokoro', 'piper'] } }],+ responses: { 200: { description: 'Voice list' } },+ },+ },+ '/api/voice/public/engines': {+ get: {+ summary: 'List engines',+ description: 'Discover available TTS engines and the configured default voice per engine.',+ responses: { 200: { description: 'Engine list + defaults' } },+ },+ },+ '/sdapi/v1/txt2img': {+ post: { summary: 'Text-to-image (AUTOMATIC1111-compatible)', responses: { 200: { description: 'Generated image(s)' } } },+ },+ '/sdapi/v1/sd-models': { get: { summary: 'List image models', responses: { 200: { description: 'Model catalog' } } } },+ '/sdapi/v1/samplers': { get: { summary: 'List samplers', responses: { 200: { description: 'Sampler list' } } } },+ '/sdapi/v1/options': { get: { summary: 'Active model/options', responses: { 200: { description: 'Options' } } } },+ '/sdapi/v1/progress': { get: { summary: 'Generation progress', responses: { 200: { description: 'Progress' } } } },+};++// Attach a `security` requirement to every operation under a path item when the+// API requires auth. Passwordless APIs get an empty array (anonymous allowed).+const applySecurity = (pathItem, requireAuth) => {+ const out = {};+ for (const [method, op] of Object.entries(pathItem)) {+ out[method] = requireAuth ? { ...op, security: [{ bearerAuth: [] }, { basicAuth: [] }] } : { ...op, security: [] };+ }+ return out;+};++/**+ * Build the OpenAPI 3.1 document for the currently-exposed public APIs.+ * @param {object} settings full settings object (for resolveApiAccess)+ * @param {object} [opts]+ * @param {string} [opts.baseUrl] server base URL (e.g. https://host:5555)+ * @param {string} [opts.version] PortOS version for info.version+ * @returns {object} OpenAPI 3.1 document+ */+export const buildOpenApiSpec = (settings, { baseUrl, version = '0.0.0' } = {}) => {+ const apis = resolveApiAccess(settings);+ const paths = {};+ const tags = [];++ for (const api of apis) {+ if (!api.exposed) continue;+ tags.push({ name: api.id, description: api.description });+ for (const path of api.docPaths) {+ const pathItem = OPERATIONS[path] || { get: { summary: path, responses: { 200: { description: 'OK' } } } };+ // Tag each operation with the API id so docs UIs can group them.+ const tagged = Object.fromEntries(+ Object.entries(pathItem).map(([method, op]) => [method, { tags: [api.id], ...op }]),+ );+ paths[path] = applySecurity(tagged, api.requireAuth);+ }+ }++ return {+ openapi: '3.1.0',+ info: {+ title: 'PortOS Public API',+ version,+ description: 'Externally-callable PortOS services. Only APIs you have exposed in Settings → API Access appear here.',+ },+ servers: baseUrl ? [{ url: baseUrl }] : [],+ tags,+ paths,+ components: {+ securitySchemes: {+ bearerAuth: { type: 'http', scheme: 'bearer', description: 'PortOS session token (when the API requires auth).' },+ basicAuth: { type: 'http', scheme: 'basic', description: 'PortOS password via HTTP Basic (username ignored).' },+ },+ },+ };+};diff --git a/server/lib/openapiSpec.test.js b/server/lib/openapiSpec.test.jsnew file mode 100644index 0000000000..c8c20c69d3--- /dev/null+++ b/server/lib/openapiSpec.test.js@@ -0,0 +1,74 @@+import { describe, it, expect } from 'vitest';+import { z } from 'zod';+import { buildOpenApiSpec } from './openapiSpec.js';+import { synthesizeBodySchema as routeSchema } from '../routes/voicePublic.js';++const exposed = (apiAccess) => ({ apiAccess });++describe('buildOpenApiSpec', () => {+ it('produces a valid 3.1 envelope with security schemes', () => {+ const spec = buildOpenApiSpec({}, { baseUrl: 'https://host:5555', version: '1.2.3' });+ expect(spec.openapi).toBe('3.1.0');+ expect(spec.info.version).toBe('1.2.3');+ expect(spec.servers).toEqual([{ url: 'https://host:5555' }]);+ expect(spec.components.securitySchemes.bearerAuth).toBeDefined();+ expect(spec.components.securitySchemes.basicAuth).toBeDefined();+ });++ it('includes NO paths when nothing is exposed', () => {+ const spec = buildOpenApiSpec({}, {});+ expect(Object.keys(spec.paths)).toHaveLength(0);+ expect(spec.tags).toHaveLength(0);+ });++ it('includes voice paths only when voice is exposed', () => {+ const spec = buildOpenApiSpec(exposed({ voice: { exposed: true, requireAuth: false } }), {});+ expect(spec.paths['/api/voice/public/synthesize']).toBeDefined();+ expect(spec.paths['/api/voice/public/voices']).toBeDefined();+ expect(spec.paths['/sdapi/v1/txt2img']).toBeUndefined();+ expect(spec.tags.map((t) => t.name)).toContain('voice');+ });++ it('reuses the synthesize Zod schema as the request body JSON Schema', () => {+ const spec = buildOpenApiSpec(exposed({ voice: { exposed: true, requireAuth: false } }), {});+ const body = spec.paths['/api/voice/public/synthesize'].post.requestBody.content['application/json'].schema;+ expect(body.type).toBe('object');+ expect(body.properties.text).toBeDefined();+ expect(body.required).toContain('text');+ expect(body.properties.engine.enum).toEqual(['kokoro', 'piper']);+ // OpenAPI path schemas must not carry the JSON-Schema dialect marker.+ expect(body.$schema).toBeUndefined();+ });++ it('omits security on passwordless operations, requires it when requireAuth', () => {+ const passwordless = buildOpenApiSpec(exposed({ voice: { exposed: true, requireAuth: false } }), {});+ expect(passwordless.paths['/api/voice/public/synthesize'].post.security).toEqual([]);++ const gated = buildOpenApiSpec(exposed({ voice: { exposed: true, requireAuth: true } }), {});+ expect(gated.paths['/api/voice/public/synthesize'].post.security).toEqual([+ { bearerAuth: [] },+ { basicAuth: [] },+ ]);+ });++ it('tags each operation with its API id', () => {+ const spec = buildOpenApiSpec(exposed({ sdapi: { exposed: true, requireAuth: false } }), {});+ expect(spec.paths['/sdapi/v1/txt2img'].post.tags).toEqual(['sdapi']);+ });++ it('emits empty servers when no baseUrl given', () => {+ const spec = buildOpenApiSpec({}, {});+ expect(spec.servers).toEqual([]);+ });++ it('synthesize body schema stays in sync with the route schema (parity)', () => {+ // The lib keeps a light copy of the route's schema (so it doesn't pull the+ // heavy TTS chain). Assert the documented body matches the route's actual+ // validation shape — properties + required — so the two can't drift.+ const spec = buildOpenApiSpec(exposed({ voice: { exposed: true, requireAuth: false } }), {});+ const documented = spec.paths['/api/voice/public/synthesize'].post.requestBody.content['application/json'].schema;+ const route = z.toJSONSchema(routeSchema);+ expect(documented.properties).toEqual(route.properties);+ expect((documented.required || []).sort()).toEqual((route.required || []).sort());+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 60d8f06df0..fd5b45a88d 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -789,6 +789,22 @@ export const backupConfigSchema = z.object({disabledDefaultExcludes: z.array(z.string()).optional().default([])});+// Per-API external-access flags (issue: public API surface). Stored under the+// top-level `apiAccess` settings key (client-readable — NOT under `secrets`).+// Drives `server/lib/apiRegistry.js`: an entry that is `exposed && !requireAuth`+// re-opens its public mount even when the PortOS password is on. Both flags are+// optional so a partial PUT only patches what it carries; the registry fills+// absent flags from its per-API defaults (exposed:false, requireAuth:false).+export const apiAccessEntrySchema = z.object({+ exposed: z.boolean().optional(),+ requireAuth: z.boolean().optional(),+}).strict();++export const apiAccessSettingsSchema = z.object({+ voice: apiAccessEntrySchema.optional(),+ sdapi: apiAccessEntrySchema.optional(),+}).strict();+export const restoreRequestSchema = z.object({snapshotId: z.string().min(1),subdirFilter: z.string().optional().nullable(),diff --git a/server/routes/apiDocs.js b/server/routes/apiDocs.jsnew file mode 100644index 0000000000..ecffed4268--- /dev/null+++ b/server/routes/apiDocs.js@@ -0,0 +1,37 @@+/**+ * API Docs routes.+ *+ * Serves a native OpenAPI 3.1 spec describing PortOS's public API surface+ * (built from server/lib/apiRegistry.js + openapiSpec.js). The client renders+ * it on the /api-access page — no swagger-ui dependency.+ *+ * Mounted at /api/api-docs. Stays GATED when the PortOS password is on (it's a+ * normal /api/* route, not in the registry's public prefixes): the spec+ * describes config and is read from the authenticated UI; external callers+ * don't need it to call the documented endpoints.+ */++import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { getSettings } from '../services/settings.js';+import { getCurrentVersion } from '../services/updateChecker.js';+import { buildOpenApiSpec } from '../lib/openapiSpec.js';++const router = Router();++// Derive the base URL the client is reaching us on so the spec's `servers`+// entry (and the example curls the UI renders) are copy-pasteable. Honors a+// reverse proxy's X-Forwarded-* headers when present.+const baseUrlFromReq = (req) => {+ const proto = (req.headers['x-forwarded-proto'] || req.protocol || 'http').toString().split(',')[0].trim();+ const host = (req.headers['x-forwarded-host'] || req.headers.host || '').toString().split(',')[0].trim();+ return host ? `${proto}://${host}` : '';+};++// GET /api/api-docs/openapi.json — the OpenAPI 3.1 document for exposed APIs.+router.get('/openapi.json', asyncHandler(async (req, res) => {+ const [settings, version] = await Promise.all([getSettings(), getCurrentVersion()]);+ res.json(buildOpenApiSpec(settings, { baseUrl: baseUrlFromReq(req), version }));+}));++export default router;diff --git a/server/routes/apiDocs.test.js b/server/routes/apiDocs.test.jsnew file mode 100644index 0000000000..fe46cfd4af--- /dev/null+++ b/server/routes/apiDocs.test.js@@ -0,0 +1,43 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++// Drive the docs route off a controllable settings mock so we can flip exposure.+let store = {};+vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn(async () => ({ ...store })),+}));++import apiDocsRoutes from './apiDocs.js';++const buildApp = () => {+ const app = express();+ app.use('/api/api-docs', apiDocsRoutes);+ return app;+};++describe('GET /api/api-docs/openapi.json', () => {+ beforeEach(() => { store = {}; });++ it('returns an empty-paths 3.1 spec when nothing exposed', async () => {+ const res = await request(buildApp()).get('/api/api-docs/openapi.json');+ expect(res.status).toBe(200);+ expect(res.body.openapi).toBe('3.1.0');+ expect(Object.keys(res.body.paths)).toHaveLength(0);+ expect(res.body.info.version).not.toBe('0.0.0'); // real package.json version+ });++ it('documents voice paths once exposed', async () => {+ store = { apiAccess: { voice: { exposed: true, requireAuth: false } } };+ const res = await request(buildApp()).get('/api/api-docs/openapi.json');+ expect(res.status).toBe(200);+ expect(res.body.paths['/api/voice/public/synthesize']).toBeDefined();+ expect(res.body.paths['/api/voice/public/synthesize'].post.security).toEqual([]);+ });++ it('derives the server URL from the request Host header', async () => {+ store = { apiAccess: { voice: { exposed: true, requireAuth: false } } };+ const res = await request(buildApp()).get('/api/api-docs/openapi.json');+ expect(res.body.servers[0].url).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/);+ });+});diff --git a/server/routes/publicApiIntegration.test.js b/server/routes/publicApiIntegration.test.jsnew file mode 100644index 0000000000..5efabe7365--- /dev/null+++ b/server/routes/publicApiIntegration.test.js@@ -0,0 +1,120 @@+/**+ * End-to-end integration: the REAL authGate middleware + the REAL voicePublic+ * router + the REAL voice router, wired against a temp data dir. Exercises the+ * full request path the plan's verification section describes:+ * - auth OFF → public synth works+ * - auth ON + exposed+passwordless → public synth works, config mutation 401s+ * - auth ON + requireAuth → public synth 401s without a token, works with one+ * Only the TTS engine modules are mocked (so no ML models load); everything+ * else is the production code path.+ */+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { writeFileSync, readFileSync } from 'fs';+import { join } from 'path';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';++const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-publicapi-' });++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makeProxy(actual);+});++// Mock only the TTS engine backends so synthesize()/listVoices() don't load+// Kokoro/Piper. The dispatcher (tts.js), config, and routes are all real.+vi.mock('../services/voice/tts-kokoro.js', () => ({+ synthesizeKokoro: vi.fn(async () => ({ wav: Buffer.from('RIFFkokoro'), latencyMs: 5 })),+ listKokoroVoices: vi.fn(async () => [{ name: 'af_heart' }]),+ readyState: vi.fn(() => 'lazy'),+ unloadKokoro: vi.fn(() => ({ unloaded: false })),+ loadedModelKey: vi.fn(() => null),+}));+vi.mock('../services/voice/tts-piper.js', () => ({+ synthesizePiper: vi.fn(async () => ({ wav: Buffer.from('RIFFpiper'), latencyMs: 7 })),+ listPiperVoices: vi.fn(async () => [{ name: 'en_GB-jenny_dioco-medium' }]),+}));++const resetSettings = (extra = {}) => {+ writeFileSync(join(tempRoot, 'settings.json'), JSON.stringify(extra, null, 2) + '\n');+ writeFileSync(join(tempRoot, 'auth-sessions.json'), '{"tokens":[]}\n');+};+const setApiAccess = (apiAccess) => {+ const raw = JSON.parse(readFileSync(join(tempRoot, 'settings.json'), 'utf-8'));+ raw.apiAccess = apiAccess;+ writeFileSync(join(tempRoot, 'settings.json'), JSON.stringify(raw, null, 2) + '\n');+};++const buildApp = async () => {+ const { authGate } = await import('../lib/authGate.js');+ const voicePublicRoutes = (await import('./voicePublic.js')).default;+ const voiceRoutes = (await import('./voice.js')).default;+ const app = express();+ app.use(express.json());+ app.use(authGate);+ app.set('io', { emit: () => {} });+ app.use('/api/voice/public', voicePublicRoutes);+ app.use('/api/voice', voiceRoutes);+ return app;+};++beforeEach(() => {+ vi.resetModules();+ resetSettings();+});+afterAll(() => cleanup());++describe('public voice API — end-to-end through authGate', () => {+ it('auth OFF: public synthesize returns WAV', async () => {+ const app = await buildApp();+ const res = await request(app).post('/api/voice/public/synthesize').send({ text: 'hello' });+ expect(res.status).toBe(200);+ expect(res.headers['content-type']).toMatch(/audio\/wav/);+ });++ it('auth ON + exposed + passwordless: public synthesize works WITHOUT a token', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ setApiAccess({ voice: { exposed: true, requireAuth: false } });+ const app = await buildApp();+ const res = await request(app).post('/api/voice/public/synthesize').send({ text: 'hi', engine: 'piper' });+ expect(res.status).toBe(200);+ expect(res.body).toBeDefined();+ });++ it('auth ON + exposed + passwordless: config mutation is STILL 401', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ setApiAccess({ voice: { exposed: true, requireAuth: false } });+ const app = await buildApp();+ const res = await request(app).put('/api/voice/config').send({ enabled: true });+ expect(res.status).toBe(401);+ expect(res.body.code).toBe('AUTH_REQUIRED');+ });++ it('auth ON + requireAuth: public synthesize 401s without a token, works with one', async () => {+ const auth = await import('../services/auth.js');+ const { token } = await auth.setPassword({ newPassword: 'correct-horse' });+ setApiAccess({ voice: { exposed: true, requireAuth: true } });+ const app = await buildApp();++ const denied = await request(app).post('/api/voice/public/synthesize').send({ text: 'hi' });+ expect(denied.status).toBe(401);++ const allowed = await request(app)+ .post('/api/voice/public/synthesize')+ .set('Authorization', `Bearer ${token}`)+ .send({ text: 'hi' });+ expect(allowed.status).toBe(200);+ });++ it('auth ON + not exposed: public synthesize 401s', async () => {+ const auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'correct-horse' });+ setApiAccess({ voice: { exposed: false, requireAuth: false } });+ const app = await buildApp();+ const res = await request(app).post('/api/voice/public/synthesize').send({ text: 'hi' });+ expect(res.status).toBe(401);+ });+});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex f0942663da..0f8d8ffdb0 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -9,7 +9,7 @@ import {CODEX_PARALLEL_DEFAULT,} from '../services/mediaJobQueue/index.js';import { asyncHandler } from '../lib/errorHandler.js';-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, validateRequest } from '../lib/validation.js';+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, apiAccessSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -96,6 +96,12 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.citySnapshots !== undefined) {validateRequest(citySnapshotConfigSchema.partial(), req.body.citySnapshots);}+ // Per-API external-access flags (voice/sdapi). Validate the slice when present+ // so a malformed toggle save can't write a non-boolean exposed/requireAuth to+ // disk (the registry would then silently treat it as its default).+ if (req.body?.apiAccess !== undefined) {+ validateRequest(apiAccessSettingsSchema.partial(), req.body.apiAccess);+ }// User-defined catalog types moved out of settings.json into PostgreSQL// (`catalog_user_types`, #1001). The `/api/catalog/types` routes are the only// write path; a `catalogUserTypes` key in a PUT /api/settings body (legacydiff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsnew file mode 100644index 0000000000..01e477a168--- /dev/null+++ b/server/routes/settings.test.js@@ -0,0 +1,77 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++// In-memory settings store backing the mocked service.+let store = {};++vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn(async () => ({ ...store })),+ updateSettings: vi.fn(async (patch) => {+ store = { ...store, ...patch };+ return { ...store };+ }),+}));+vi.mock('../services/aiAssignments.js', () => ({+ getAiAssignments: vi.fn(async () => ({})),+ updateAiAssignment: vi.fn(async () => ({})),+}));+vi.mock('../services/mediaJobQueue/index.js', () => ({+ setCodexParallelLimit: vi.fn(),+ CODEX_PARALLEL_MIN: 1,+ CODEX_PARALLEL_MAX: 8,+ CODEX_PARALLEL_DEFAULT: 2,+}));++import settingsRoutes from './settings.js';++const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/settings', settingsRoutes);+ return app;+};++describe('Settings routes — apiAccess slice', () => {+ beforeEach(() => {+ store = {};+ vi.clearAllMocks();+ });++ it('accepts a valid apiAccess patch and persists it', async () => {+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ apiAccess: { voice: { exposed: true, requireAuth: false } } });+ expect(res.status).toBe(200);+ expect(res.body.apiAccess.voice.exposed).toBe(true);+ });++ it('rejects a non-boolean exposed flag', async () => {+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ apiAccess: { voice: { exposed: 'yes' } } });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ });++ it('rejects unknown keys inside an apiAccess entry (strict)', async () => {+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ apiAccess: { voice: { open: true } } });+ expect(res.status).toBe(400);+ });++ it('rejects an unknown API id (strict)', async () => {+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ apiAccess: { elevenlabs: { exposed: true } } });+ expect(res.status).toBe(400);+ });++ it('GET returns apiAccess (not stripped like secrets)', async () => {+ store = { apiAccess: { sdapi: { exposed: true, requireAuth: false } } };+ const res = await request(buildApp()).get('/api/settings');+ expect(res.status).toBe(200);+ expect(res.body.apiAccess.sdapi.exposed).toBe(true);+ });+});diff --git a/server/routes/voicePublic.js b/server/routes/voicePublic.jsnew file mode 100644index 0000000000..d9f32a97fd--- /dev/null+++ b/server/routes/voicePublic.js@@ -0,0 +1,90 @@+/**+ * Public Voice / TTS API.+ *+ * A deliberately-minimal, externally-callable surface mounted at+ * `/api/voice/public/*`. When the PortOS password is on, `authGate` re-opens+ * THIS prefix (and only this prefix) for callers without a session, gated by+ * the `apiAccess.voice` settings (see server/lib/apiRegistry.js). Default is+ * not-exposed + passwordless-once-exposed.+ *+ * SECURITY: this router contains ONLY read/compute operations — text→audio+ * synthesis and voice/engine enumeration. It has NO config mutation, NO process+ * control, NO PUT. The full `/api/voice/*` router (config, whisper, unload,+ * speak) stays fully gated and is never part of the public registry. Keeping+ * the public surface on its own mount means it can't accidentally grow when a+ * new route is added to the main voice router.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { synthesize, listVoices, VALID_ENGINES } from '../services/voice/tts.js';+import { getVoiceConfig } from '../services/voice/config.js';+import { MAX_PROACTIVE_TEXT_LEN } from '../services/voice/proactiveSpeech.js';++const router = Router();++// Shared cap with the in-process function boundary (proactiveSpeech) and the+// internal /api/voice/test route — imported so the three can't drift.+const MAX_VOICE_TEXT_LEN = MAX_PROACTIVE_TEXT_LEN;++const validEngine = (v) => (VALID_ENGINES.has(v) ? v : undefined);++// .strict() rejects unknown keys so a typo'd field (e.g. "voiceId") fails loudly+// rather than being silently ignored. `text` is trimmed before the length check+// so whitespace-only payloads 400 instead of synthesizing empty audio.+// Exported so server/lib/openapiSpec.js can assert its (light) copy stays in+// sync — see openapiSpec.test.js's parity test.+export const synthesizeBodySchema = z.object({+ text: z.string().trim().min(1).max(MAX_VOICE_TEXT_LEN),+ engine: z.enum(['kokoro', 'piper']).optional(),+ voice: z.string().max(128).optional(),+ rate: z.number().min(0.25).max(4).optional(),+}).strict();++// POST /api/voice/public/synthesize — body { text, engine?, voice?, rate? } → WAV.+// Mirrors /api/voice/test but is the external-facing surface. `synthesize()`+// validates the voice id against the curated catalog (throws 400 UNKNOWN_VOICE),+// so a bad voice can't silently produce the wrong audio.+router.post('/synthesize', asyncHandler(async (req, res) => {+ const parsed = synthesizeBodySchema.safeParse(req.body || {});+ if (!parsed.success) {+ throw new ServerError(+ `Invalid synthesize payload: ${parsed.error.issues.map((i) => `${i.path.join('.')} ${i.message}`).join('; ')}`,+ { status: 400, code: 'VALIDATION_ERROR' },+ );+ }+ const { text, engine, voice, rate } = parsed.data;+ const { wav, latencyMs, engine: usedEngine } = await synthesize(text, {+ voice: voice || undefined,+ engine: validEngine(engine),+ rate,+ });+ res.setHeader('Content-Type', 'audio/wav');+ res.setHeader('X-TTS-Latency-Ms', String(latencyMs));+ res.setHeader('X-TTS-Engine', usedEngine);+ res.send(wav);+}));++// GET /api/voice/public/voices?engine=kokoro|piper — enumerate available voices+// for the given engine (or the configured default when unspecified).+router.get('/voices', asyncHandler(async (req, res) => {+ res.json(await listVoices(validEngine(req.query?.engine)));+}));++// GET /api/voice/public/engines — discover the available engines + the+// configured default voice per engine, so an external caller can build a+// request without first listing every voice.+router.get('/engines', asyncHandler(async (_req, res) => {+ const cfg = await getVoiceConfig();+ res.json({+ engines: [...VALID_ENGINES],+ active: cfg.tts?.engine,+ defaults: {+ kokoro: cfg.tts?.kokoro?.voice,+ piper: cfg.tts?.piper?.voice,+ },+ });+}));++export default router;diff --git a/server/routes/voicePublic.test.js b/server/routes/voicePublic.test.jsnew file mode 100644index 0000000000..37dff9ab97--- /dev/null+++ b/server/routes/voicePublic.test.js@@ -0,0 +1,108 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++vi.mock('../services/voice/tts.js', () => ({+ synthesize: vi.fn(),+ listVoices: vi.fn(),+ VALID_ENGINES: new Set(['kokoro', 'piper']),+}));+vi.mock('../services/voice/config.js', () => ({+ getVoiceConfig: vi.fn(),+}));+vi.mock('../services/voice/proactiveSpeech.js', () => ({+ MAX_PROACTIVE_TEXT_LEN: 2000,+}));++import * as tts from '../services/voice/tts.js';+import * as config from '../services/voice/config.js';+import voicePublicRoutes from './voicePublic.js';++const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/voice/public', voicePublicRoutes);+ return app;+};++describe('Public Voice API (/api/voice/public)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ config.getVoiceConfig.mockResolvedValue({+ tts: { engine: 'kokoro', kokoro: { voice: 'af_heart' }, piper: { voice: 'en_GB-jenny_dioco-medium' } },+ });+ });++ describe('POST /synthesize', () => {+ it('synthesizes text and returns audio/wav with headers', async () => {+ tts.synthesize.mockResolvedValue({ wav: Buffer.from('RIFFfake'), latencyMs: 42, engine: 'kokoro' });+ const res = await request(buildApp()).post('/api/voice/public/synthesize').send({ text: 'hello' });+ expect(res.status).toBe(200);+ expect(res.headers['content-type']).toMatch(/audio\/wav/);+ expect(res.headers['x-tts-latency-ms']).toBe('42');+ expect(res.headers['x-tts-engine']).toBe('kokoro');+ expect(tts.synthesize).toHaveBeenCalledWith('hello', expect.objectContaining({ engine: undefined }));+ });++ it('passes engine/voice/rate overrides through', async () => {+ tts.synthesize.mockResolvedValue({ wav: Buffer.from('x'), latencyMs: 1, engine: 'piper' });+ await request(buildApp()).post('/api/voice/public/synthesize')+ .send({ text: 'hi', engine: 'piper', voice: 'en_US-amy-medium', rate: 1.5 });+ expect(tts.synthesize).toHaveBeenCalledWith('hi', { engine: 'piper', voice: 'en_US-amy-medium', rate: 1.5 });+ });++ it('400s on empty text', async () => {+ const res = await request(buildApp()).post('/api/voice/public/synthesize').send({ text: ' ' });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expect(tts.synthesize).not.toHaveBeenCalled();+ });++ it('400s on unknown engine', async () => {+ const res = await request(buildApp()).post('/api/voice/public/synthesize').send({ text: 'hi', engine: 'elevenlabs' });+ expect(res.status).toBe(400);+ expect(tts.synthesize).not.toHaveBeenCalled();+ });++ it('400s on unknown keys (strict schema)', async () => {+ const res = await request(buildApp()).post('/api/voice/public/synthesize').send({ text: 'hi', voiceId: 'oops' });+ expect(res.status).toBe(400);+ expect(tts.synthesize).not.toHaveBeenCalled();+ });++ it('surfaces synthesize() UNKNOWN_VOICE as 400', async () => {+ const { ServerError } = await import('../lib/errorHandler.js');+ tts.synthesize.mockRejectedValue(new ServerError('unknown piper voice: bogus', { status: 400, code: 'UNKNOWN_VOICE' }));+ const res = await request(buildApp()).post('/api/voice/public/synthesize').send({ text: 'hi', engine: 'piper', voice: 'bogus' });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('UNKNOWN_VOICE');+ });+ });++ describe('GET /voices', () => {+ it('delegates to listVoices with the requested engine', async () => {+ tts.listVoices.mockResolvedValue({ engine: 'kokoro', voices: [{ id: 'af_heart' }] });+ const res = await request(buildApp()).get('/api/voice/public/voices?engine=kokoro');+ expect(res.status).toBe(200);+ expect(res.body.engine).toBe('kokoro');+ expect(tts.listVoices).toHaveBeenCalledWith('kokoro');+ });++ it('ignores an unknown engine query value', async () => {+ tts.listVoices.mockResolvedValue({ engine: 'kokoro', voices: [] });+ await request(buildApp()).get('/api/voice/public/voices?engine=bogus');+ expect(tts.listVoices).toHaveBeenCalledWith(undefined);+ });+ });++ describe('GET /engines', () => {+ it('returns engines + active + per-engine default voice', async () => {+ const res = await request(buildApp()).get('/api/voice/public/engines');+ expect(res.status).toBe(200);+ expect(res.body.engines).toEqual(expect.arrayContaining(['kokoro', 'piper']));+ expect(res.body.active).toBe('kokoro');+ expect(res.body.defaults.kokoro).toBe('af_heart');+ expect(res.body.defaults.piper).toBe('en_GB-jenny_dioco-medium');+ });+ });+});diff --git a/server/services/voice/tts.js b/server/services/voice/tts.jsindex 37d676338d..b60f6f5518 100644--- a/server/services/voice/tts.js+++ b/server/services/voice/tts.js@@ -29,6 +29,7 @@ const backend = (engine) => {* @param {AbortSignal} [opts.signal]* @param {string} [opts.voice] transient voice override* @param {string} [opts.engine] transient engine override ('kokoro'|'piper')+ * @param {number} [opts.rate] transient speech-rate override (0.25–4)* @returns {Promise<{ wav: Buffer, latencyMs: number, engine: string }>}*/export const synthesize = async (text, opts = {}) => {@@ -36,9 +37,17 @@ export const synthesize = async (text, opts = {}) => {const engine = resolveEngine(opts.engine || cfg.tts.engine);const { synth } = backend(engine);let ttsCfg = cfg.tts;+ // Transient rate override (external public API lets a caller set speed per+ // request without persisting it). Clamp defensively even though the route+ // schema already bounds it — direct in-process callers bypass the route.+ if (typeof opts.rate === 'number' && Number.isFinite(opts.rate)) {+ ttsCfg = { ...ttsCfg, rate: Math.min(4, Math.max(0.25, opts.rate)) };+ }if (opts.voice) {+ // Spread from `ttsCfg` (not `cfg.tts`) so a transient rate override applied+ // above is preserved alongside the voice override.if (engine === 'kokoro') {- ttsCfg = { ...cfg.tts, kokoro: { ...cfg.tts.kokoro, voice: opts.voice } };+ ttsCfg = { ...ttsCfg, kokoro: { ...ttsCfg.kokoro, voice: opts.voice } };} else {// Reject Piper voice overrides that aren't in the curated catalog —// otherwise `voice` would change but `voicePath` would remain the@@ -51,9 +60,9 @@ export const synthesize = async (text, opts = {}) => {});}ttsCfg = {- ...cfg.tts,+ ...ttsCfg,piper: {- ...cfg.tts.piper,+ ...ttsCfg.piper,voice: opts.voice,voicePath: piperVoiceTildePath(opts.voice),speakerId: null,