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
fix: finish the host-control audit of the pre-guard open routes (#13055)
[._.]/ Adam Eivy809a3fe69f0f
diff --git a/server/hostControlCoverage.test.js b/server/hostControlCoverage.test.jsindex defd2cc039..528448d907 100644--- a/server/hostControlCoverage.test.js+++ b/server/hostControlCoverage.test.js@@ -15,8 +15,8 @@* lib/hostControlRoutes.js. A route that runs a process, git/npm/gh, a CoS* agent, or hands caller text or a caller-chosen provider to a runner that is* not tool-free belongs in HOST_CONTROL_ROUTES. Otherwise add it here with the- * reason constant that matches, or a new one. Never add PRE_GUARD_BASELINE:- * it is the burn-down of routes that were open when this guard landed (#13055).+ * reason constant that matches, or a new one. Every entry names what the+ * route actually does; there is no catch-all "not yet reviewed" reason (#13055).*/import { describe, expect, it } from 'vitest';import { scanRouteGraph } from './lib/apiRouteGraph.js';@@ -40,61 +40,76 @@ const TOOL_FREE_INFERENCE = 'Sends caller or stored text only through a tool-freconst IN_PROCESS_MEDIA = 'Transforms a stored gallery image in-process (sharp or pure JS) into a new variant; spawns no process and calls no provider.';const READ_OVER_POST = 'Reads or previews stored records over POST; writes nothing and runs nothing.';const DERIVED_REPORT = 'Recomputes a report from stored records without a provider; runs nothing on the host.';-const PRE_GUARD_BASELINE = 'Open when this guard landed and not yet re-audited route by route (#13055); do not add new entries.';+// From the route-by-route audit of the routes that were open when this guard landed (#13055).+const IN_PROCESS_COMPUTE = 'Runs a deterministic in-process computation over stored records and saves the derived result; spawns no process and calls no provider.';+const CLIENT_TELEMETRY = 'Records a caller-reported error, event or usage count as a PortOS record; runs nothing on the host.';+const CONFIGURED_SELECTION = 'Chooses which already-configured provider or model a feature uses and arms nothing; names no executable, endpoint or host path (#8721).';+const CONNECTOR_CREDENTIAL = 'Starts, validates or stores the credential an already-configured service uses with its fixed or operator-set endpoint; names no endpoint, host path or executable.';+const EXTERNAL_SYNC = 'Pulls from an already-configured external service with its stored credential into PortOS records; changes no external state and runs nothing on the host.';+const LOCAL_SOURCE_SYNC = 'Reads a fixed local source (the Messages or Contacts database at its built-in path) into PortOS records; the caller names no path and nothing external changes.';+const PEER_SYNC = 'Pushes or pulls records over the established peer-sync channel, only with peers the operator registered for sync, within their direction and categories.';+const PUBLIC_FETCH = 'Fetches a public http(s) URL through an SSRF-guarded fetcher with no stored credential, and returns or stores the result; runs nothing on the host.';+const REFERENCE_DATASET = 'Downloads a fixed public reference dataset from a hardcoded URL and indexes it in-process; no caller-chosen URL, executable or provider.';+const READ_ONLY_PROBE = 'Runs only a fixed read-only host probe (a process, port or disk-usage listing) with no caller-chosen command or path; changes no host state.';+const LOCAL_TTS = 'Synthesizes caller text on an already-installed TTS runtime, which runs no tools; names no executable or path (like local-llm test, #8798).';+const FIXED_ENCODE = 'Encodes audio PortOS synthesized itself with a fixed ffmpeg invocation; no caller-supplied media, path or argument reaches the process (#10893).';+const FEATURE_TOGGLE = 'Shows or hides an optional integration; the toggles that launch or tear down host executables are gated by path in COMPILED_BODY_ROUTES.';+const LOCAL_BRIDGE = 'Opens the fixed-target bridge to an already-installed local integration; spawns no process and lets the caller choose no target.';+const EXPOSED_API = 'Opt-in external API (lib/apiRegistry.js): open while the operator exposes it, otherwise the router requires host control (#11138).';+const CONFIGURED_WORLD_SYNC = 'Reconciles the local Eidoverse world with the operator-saved identities and projection recipe; takes no caller content, calls no provider and starts nothing.';+const MANAGED_VISITOR_BROKER = 'Managed-app visitor broker: its credentials work only for a local same-origin app (services/managedVisitors.js), so no remote or peer caller gains world or host authority.';// 'METHOD /path' as scanRouteGraph spells it (the declaring module's :param names).const REVIEWED_OPEN_MUTATIONS = [// /api/agent-context['DELETE /api/agent-context/mcp', REMOVES_RECORD],- ['POST /api/agent-context/mcp', PRE_GUARD_BASELINE],// /api/agents/accounts['DELETE /api/agents/accounts/:id', REMOVES_RECORD],// /api/agents/activity- ['POST /api/agents/activity/cleanup', PRE_GUARD_BASELINE],- ['POST /api/agents/activity/run-events/reconcile', PRE_GUARD_BASELINE],+ ['POST /api/agents/activity/cleanup', REMOVES_RECORD],+ ['POST /api/agents/activity/run-events/reconcile', RECORDS],// /api/agents/personalities- ['POST /api/agents/personalities', PRE_GUARD_BASELINE],['DELETE /api/agents/personalities/:id', REMOVES_RECORD],['POST /api/agents/personalities/:id/toggle', HANDLER_GATED],// /api/agents/schedules['DELETE /api/agents/schedules/:id', REMOVES_RECORD],['POST /api/agents/schedules/:id/toggle', HANDLER_GATED],// /api/agents/tools- ['POST /api/agents/tools/drafts', PRE_GUARD_BASELINE],+ ['POST /api/agents/tools/drafts', RECORDS],['DELETE /api/agents/tools/drafts/:draftId', REMOVES_RECORD],- ['PUT /api/agents/tools/drafts/:draftId', PRE_GUARD_BASELINE],- ['POST /api/agents/tools/generate-comment', PRE_GUARD_BASELINE],- ['POST /api/agents/tools/generate-post', PRE_GUARD_BASELINE],+ ['PUT /api/agents/tools/drafts/:draftId', RECORDS],+ ['POST /api/agents/tools/generate-comment', TOOL_FREE_INFERENCE],+ ['POST /api/agents/tools/generate-post', TOOL_FREE_INFERENCE],// /api/agents/tools/moltworld['DELETE /api/agents/tools/moltworld/queue/:id', REMOVES_RECORD],- ['POST /api/agents/tools/moltworld/queue/:id/complete', PRE_GUARD_BASELINE],- ['POST /api/agents/tools/moltworld/queue/:id/fail', PRE_GUARD_BASELINE],+ ['POST /api/agents/tools/moltworld/queue/:id/complete', RECORDS],+ ['POST /api/agents/tools/moltworld/queue/:id/fail', RECORDS],// /api/agents/tools/moltworld/ws['POST /api/agents/tools/moltworld/ws/disconnect', REDUCES_EXECUTION],// /api/albums- ['POST /api/albums', PRE_GUARD_BASELINE],+ ['POST /api/albums', RECORDS],['DELETE /api/albums/:id', REMOVES_RECORD],- ['PATCH /api/albums/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/albums/:id', RECORDS],// /api/apps['DELETE /api/apps/:id', REMOVES_RECORD],['POST /api/apps/:id/archive', RECORDS],- ['POST /api/apps/:id/detect-icon', PRE_GUARD_BASELINE],- ['POST /api/apps/:id/quality-schedule/preview', PRE_GUARD_BASELINE],+ ['POST /api/apps/:id/detect-icon', RECORDS],+ ['POST /api/apps/:id/quality-schedule/preview', READ_ONLY_EXTERNAL],['POST /api/apps/:id/scope-adherence', RECORDS],['POST /api/apps/:id/unarchive', RECORDS],// /api/apps/:appId/reference-repos['DELETE /api/apps/:appId/reference-repos/:refId', REMOVES_RECORD],['POST /api/apps/:appId/reference-repos/:refId/reviewed', RECORDS],// /api/artists- ['POST /api/artists', PRE_GUARD_BASELINE],+ ['POST /api/artists', RECORDS],['DELETE /api/artists/:id', REMOVES_RECORD],- ['PATCH /api/artists/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/artists/:id', RECORDS],// /api/ask['POST /api/ask', HANDLER_GATED],['DELETE /api/ask/:id', REMOVES_RECORD],['POST /api/ask/:id/promote', HANDLER_GATED],// /api/attachments- ['POST /api/attachments', PRE_GUARD_BASELINE],+ ['POST /api/attachments', RECORDS],['DELETE /api/attachments/:filename', REMOVES_RECORD],// /api/auth['POST /api/auth/login', AUTH_SESSION],@@ -103,112 +118,108 @@ const REVIEWED_OPEN_MUTATIONS = [['DELETE /api/auth/sessions', AUTH_SESSION],['DELETE /api/auth/sessions/:id', AUTH_SESSION],// /api/authors- ['POST /api/authors', PRE_GUARD_BASELINE],+ ['POST /api/authors', RECORDS],['DELETE /api/authors/:id', REMOVES_RECORD],- ['PATCH /api/authors/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/authors/:id', RECORDS],// /api/beeper- ['PATCH /api/beeper/attachments/:messageId/:idx', PRE_GUARD_BASELINE],- ['POST /api/beeper/attachments/:messageId/:idx/fetch', PRE_GUARD_BASELINE],- ['POST /api/beeper/attachments/backfill', PRE_GUARD_BASELINE],- ['POST /api/beeper/conversations', PRE_GUARD_BASELINE],+ ['PATCH /api/beeper/attachments/:messageId/:idx', RECORDS],+ ['POST /api/beeper/attachments/:messageId/:idx/fetch', EXTERNAL_SYNC],+ ['POST /api/beeper/attachments/backfill', EXTERNAL_SYNC],['DELETE /api/beeper/conversations/:id', REMOVES_RECORD],- ['POST /api/beeper/conversations/:id/archive', PRE_GUARD_BASELINE],- ['POST /api/beeper/conversations/:id/low-priority', PRE_GUARD_BASELINE],- ['POST /api/beeper/conversations/:id/seen', PRE_GUARD_BASELINE],- ['POST /api/beeper/oauth/start', PRE_GUARD_BASELINE],+ ['POST /api/beeper/conversations/:id/seen', RECORDS],+ ['POST /api/beeper/oauth/start', CONNECTOR_CREDENTIAL],['DELETE /api/beeper/outbox/:id', REMOVES_RECORD],- ['POST /api/beeper/outbox/:id/reconcile', PRE_GUARD_BASELINE],- ['POST /api/beeper/scopes', PRE_GUARD_BASELINE],+ ['POST /api/beeper/outbox/:id/reconcile', READ_ONLY_EXTERNAL],+ ['POST /api/beeper/scopes', RECORDS],['DELETE /api/beeper/scopes/:id', REMOVES_RECORD],- ['PATCH /api/beeper/scopes/:id', PRE_GUARD_BASELINE],- ['POST /api/beeper/status/check', PRE_GUARD_BASELINE],- ['POST /api/beeper/sync', PRE_GUARD_BASELINE],+ ['PATCH /api/beeper/scopes/:id', RECORDS],+ ['POST /api/beeper/status/check', READ_ONLY_EXTERNAL],+ ['POST /api/beeper/sync', EXTERNAL_SYNC],['DELETE /api/beeper/token', REMOVES_RECORD],- ['POST /api/beeper/token', PRE_GUARD_BASELINE],+ ['POST /api/beeper/token', CONNECTOR_CREDENTIAL],// /api/brain- ['POST /api/brain/admin', PRE_GUARD_BASELINE],+ ['POST /api/brain/admin', RECORDS],['DELETE /api/brain/admin/:id', REMOVES_RECORD],- ['PUT /api/brain/admin/:id', PRE_GUARD_BASELINE],- ['POST /api/brain/bridge-sync', PRE_GUARD_BASELINE],- ['POST /api/brain/buckets', PRE_GUARD_BASELINE],+ ['PUT /api/brain/admin/:id', RECORDS],+ ['POST /api/brain/bridge-sync', TOOL_FREE_INFERENCE],+ ['POST /api/brain/buckets', RECORDS],['DELETE /api/brain/buckets/:id', REMOVES_RECORD],- ['PUT /api/brain/buckets/:id', PRE_GUARD_BASELINE],- ['POST /api/brain/buckets/reorder', PRE_GUARD_BASELINE],+ ['PUT /api/brain/buckets/:id', RECORDS],+ ['POST /api/brain/buckets/reorder', RECORDS],['DELETE /api/brain/daily-log/:date', REMOVES_RECORD],- ['PUT /api/brain/daily-log/:date', PRE_GUARD_BASELINE],- ['POST /api/brain/daily-log/:date/append', PRE_GUARD_BASELINE],- ['PUT /api/brain/daily-log/settings', PRE_GUARD_BASELINE],- ['POST /api/brain/daily-log/sync-obsidian', PRE_GUARD_BASELINE],- ['POST /api/brain/fix', PRE_GUARD_BASELINE],- ['POST /api/brain/ideas', PRE_GUARD_BASELINE],+ ['PUT /api/brain/daily-log/:date', RECORDS],+ ['POST /api/brain/daily-log/:date/append', RECORDS],+ ['PUT /api/brain/daily-log/settings', RECORDS],+ ['POST /api/brain/daily-log/sync-obsidian', RECORDS],+ ['POST /api/brain/fix', RECORDS],+ ['POST /api/brain/ideas', RECORDS],['DELETE /api/brain/ideas/:id', REMOVES_RECORD],- ['PUT /api/brain/ideas/:id', PRE_GUARD_BASELINE],- ['POST /api/brain/ideas/idealoom/import', PRE_GUARD_BASELINE],- ['POST /api/brain/ideas/idealoom/lists', PRE_GUARD_BASELINE],+ ['PUT /api/brain/ideas/:id', RECORDS],+ ['POST /api/brain/ideas/idealoom/import', RECORDS],+ ['POST /api/brain/ideas/idealoom/lists', RECORDS],['DELETE /api/brain/ideas/idealoom/lists/:id', REMOVES_RECORD],- ['PUT /api/brain/ideas/idealoom/lists/:id', PRE_GUARD_BASELINE],- ['PUT /api/brain/ideas/idealoom/settings', PRE_GUARD_BASELINE],- ['POST /api/brain/ideas/idealoom/sync', PRE_GUARD_BASELINE],+ ['PUT /api/brain/ideas/idealoom/lists/:id', RECORDS],+ ['PUT /api/brain/ideas/idealoom/settings', RECORDS],+ ['POST /api/brain/ideas/idealoom/sync', RECORDS],['DELETE /api/brain/inbox/:id', REMOVES_RECORD],- ['PUT /api/brain/inbox/:id', PRE_GUARD_BASELINE],- ['POST /api/brain/inbox/:id/done', PRE_GUARD_BASELINE],- ['POST /api/brain/inbox/sent-to-catalog', PRE_GUARD_BASELINE],+ ['PUT /api/brain/inbox/:id', RECORDS],+ ['POST /api/brain/inbox/:id/done', RECORDS],+ ['POST /api/brain/inbox/sent-to-catalog', RECORDS],['POST /api/brain/links', HANDLER_GATED],['DELETE /api/brain/links/:id', REMOVES_RECORD],- ['PUT /api/brain/links/:id', PRE_GUARD_BASELINE],- ['POST /api/brain/links/reorder', PRE_GUARD_BASELINE],- ['POST /api/brain/memories', PRE_GUARD_BASELINE],+ ['PUT /api/brain/links/:id', RECORDS],+ ['POST /api/brain/links/reorder', RECORDS],+ ['POST /api/brain/memories', RECORDS],['DELETE /api/brain/memories/:id', REMOVES_RECORD],- ['PUT /api/brain/memories/:id', PRE_GUARD_BASELINE],- ['POST /api/brain/people', PRE_GUARD_BASELINE],+ ['PUT /api/brain/memories/:id', RECORDS],+ ['POST /api/brain/people', RECORDS],['DELETE /api/brain/people/:id', REMOVES_RECORD],- ['PUT /api/brain/people/:id', PRE_GUARD_BASELINE],- ['POST /api/brain/projects', PRE_GUARD_BASELINE],+ ['PUT /api/brain/people/:id', RECORDS],+ ['POST /api/brain/projects', RECORDS],['DELETE /api/brain/projects/:id', REMOVES_RECORD],- ['PUT /api/brain/projects/:id', PRE_GUARD_BASELINE],- ['POST /api/brain/reconcile/parity', PRE_GUARD_BASELINE],- ['POST /api/brain/review/resolve', PRE_GUARD_BASELINE],- ['PUT /api/brain/settings', PRE_GUARD_BASELINE],- ['POST /api/brain/songbook', PRE_GUARD_BASELINE],+ ['PUT /api/brain/projects/:id', RECORDS],+ ['POST /api/brain/reconcile/parity', READ_ONLY_EXTERNAL],+ ['POST /api/brain/review/resolve', RECORDS],+ ['PUT /api/brain/settings', HANDLER_GATED],+ ['POST /api/brain/songbook', RECORDS],['DELETE /api/brain/songbook/:id', REMOVES_RECORD],- ['PATCH /api/brain/songbook/:id', PRE_GUARD_BASELINE],- ['POST /api/brain/songbook/:id/attachments', PRE_GUARD_BASELINE],+ ['PATCH /api/brain/songbook/:id', RECORDS],+ ['POST /api/brain/songbook/:id/attachments', RECORDS],['DELETE /api/brain/songbook/:id/attachments/:filename', REMOVES_RECORD],- ['POST /api/brain/songbook/:id/practice', PRE_GUARD_BASELINE],- ['POST /api/brain/songbook/import/url', PRE_GUARD_BASELINE],- ['POST /api/brain/sync', PRE_GUARD_BASELINE],- ['POST /api/brain/threads', PRE_GUARD_BASELINE],+ ['POST /api/brain/songbook/:id/practice', RECORDS],+ ['POST /api/brain/songbook/import/url', PUBLIC_FETCH],+ ['POST /api/brain/sync', RECORDS],+ ['POST /api/brain/threads', RECORDS],['DELETE /api/brain/threads/:id', REMOVES_RECORD],- ['PUT /api/brain/threads/:id', PRE_GUARD_BASELINE],- ['POST /api/brain/threads/:id/refs', PRE_GUARD_BASELINE],+ ['PUT /api/brain/threads/:id', RECORDS],+ ['POST /api/brain/threads/:id/refs', RECORDS],['DELETE /api/brain/threads/:id/refs/:kind/:refId', REMOVES_RECORD],- ['POST /api/brain/threads/attach', PRE_GUARD_BASELINE],- ['POST /api/brain/threads/sync', PRE_GUARD_BASELINE],+ ['POST /api/brain/threads/attach', RECORDS],+ ['POST /api/brain/threads/sync', READ_ONLY_EXTERNAL],['POST /api/brain/youtube/ingest/:jobId/cancel', REDUCES_EXECUTION],['DELETE /api/brain/youtube/ingests/:videoId', REMOVES_RECORD],- ['PUT /api/brain/youtube/settings', PRE_GUARD_BASELINE],+ ['PUT /api/brain/youtube/settings', RECORDS],// /api/brain/import- ['POST /api/brain/import/chatgpt', PRE_GUARD_BASELINE],- ['POST /api/brain/import/chatgpt/preview', PRE_GUARD_BASELINE],- ['POST /api/brain/import/chatgpt/zip', PRE_GUARD_BASELINE],+ ['POST /api/brain/import/chatgpt', RECORDS],+ ['POST /api/brain/import/chatgpt/preview', READ_OVER_POST],+ ['POST /api/brain/import/chatgpt/zip', RECORDS],// /api/browser['DELETE /api/browser/downloads/:name', REMOVES_RECORD],// /api/calendar- ['POST /api/calendar/accounts', PRE_GUARD_BASELINE],+ ['POST /api/calendar/accounts', RECORDS],['DELETE /api/calendar/accounts/:id', REMOVES_RECORD],- ['PUT /api/calendar/accounts/:id', PRE_GUARD_BASELINE],- ['PUT /api/calendar/accounts/:id/subcalendars', PRE_GUARD_BASELINE],- ['POST /api/calendar/debug/clear-token', PRE_GUARD_BASELINE],- ['POST /api/calendar/google/auth/clear', PRE_GUARD_BASELINE],- ['POST /api/calendar/google/auth/credentials', PRE_GUARD_BASELINE],- ['POST /api/calendar/review/:date/confirm', PRE_GUARD_BASELINE],- ['POST /api/calendar/sync/:accountId', PRE_GUARD_BASELINE],- ['POST /api/calendar/sync/:accountId/api', PRE_GUARD_BASELINE],- ['POST /api/calendar/sync/:accountId/discover-api', PRE_GUARD_BASELINE],- ['POST /api/calendar/sync/:accountId/push', PRE_GUARD_BASELINE],+ ['PUT /api/calendar/accounts/:id', RECORDS],+ ['PUT /api/calendar/accounts/:id/subcalendars', RECORDS],+ ['POST /api/calendar/debug/clear-token', REMOVES_RECORD],+ ['POST /api/calendar/google/auth/clear', REMOVES_RECORD],+ ['POST /api/calendar/google/auth/credentials', CONNECTOR_CREDENTIAL],+ ['POST /api/calendar/review/:date/confirm', RECORDS],+ ['POST /api/calendar/sync/:accountId/api', EXTERNAL_SYNC],+ ['POST /api/calendar/sync/:accountId/discover-api', EXTERNAL_SYNC],+ ['POST /api/calendar/sync/:accountId/push', RECORDS],// /api/catalog- ['POST /api/catalog/bulk-import', PRE_GUARD_BASELINE],- ['POST /api/catalog/embeddings/backfill', PRE_GUARD_BASELINE],+ ['POST /api/catalog/bulk-import', RECORDS],+ ['POST /api/catalog/embeddings/backfill', TOOL_FREE_INFERENCE],['POST /api/catalog/identity/:id/abort', HANDLER_GATED],['POST /api/catalog/identity/:id/accept', HANDLER_GATED],['POST /api/catalog/identity/:id/advance', HANDLER_GATED],@@ -216,75 +227,71 @@ const REVIEWED_OPEN_MUTATIONS = [['POST /api/catalog/identity/create', HANDLER_GATED],['POST /api/catalog/identity/import', HANDLER_GATED],['POST /api/catalog/identity/preview', HANDLER_GATED],- ['POST /api/catalog/import/music-videos', PRE_GUARD_BASELINE],- ['POST /api/catalog/ingredient-merges/:id/recover', PRE_GUARD_BASELINE],- ['POST /api/catalog/ingredients', PRE_GUARD_BASELINE],+ ['POST /api/catalog/import/music-videos', RECORDS],+ ['POST /api/catalog/ingredient-merges/:id/recover', RECORDS],+ ['POST /api/catalog/ingredients', RECORDS],['DELETE /api/catalog/ingredients/:id', REMOVES_RECORD],- ['PATCH /api/catalog/ingredients/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/catalog/ingredients/:id', RECORDS],['DELETE /api/catalog/ingredients/:id/link', REMOVES_RECORD],- ['POST /api/catalog/ingredients/:id/link', PRE_GUARD_BASELINE],+ ['POST /api/catalog/ingredients/:id/link', RECORDS],['DELETE /api/catalog/ingredients/:id/media', REMOVES_RECORD],- ['POST /api/catalog/ingredients/:id/media', PRE_GUARD_BASELINE],- ['POST /api/catalog/ingredients/:id/media/from-mood-board', PRE_GUARD_BASELINE],- ['PATCH /api/catalog/ingredients/:id/media/library', PRE_GUARD_BASELINE],- ['POST /api/catalog/ingredients/:id/media/portrait', PRE_GUARD_BASELINE],- ['POST /api/catalog/ingredients/:id/media/upload', PRE_GUARD_BASELINE],- ['POST /api/catalog/ingredients/:id/media/voice', PRE_GUARD_BASELINE],+ ['POST /api/catalog/ingredients/:id/media', RECORDS],+ ['POST /api/catalog/ingredients/:id/media/from-mood-board', RECORDS],+ ['PATCH /api/catalog/ingredients/:id/media/library', RECORDS],+ ['POST /api/catalog/ingredients/:id/media/portrait', RECORDS],+ ['POST /api/catalog/ingredients/:id/media/upload', RECORDS],+ ['POST /api/catalog/ingredients/:id/media/voice', TOOL_FREE_INFERENCE],['DELETE /api/catalog/ingredients/:id/relations', REMOVES_RECORD],- ['POST /api/catalog/ingredients/:id/relations', PRE_GUARD_BASELINE],- ['POST /api/catalog/ingredients/:id/revisions/:revisionId/restore', PRE_GUARD_BASELINE],- ['POST /api/catalog/ingredients/:id/sheets/preview', PRE_GUARD_BASELINE],- ['POST /api/catalog/ingredients/merge', PRE_GUARD_BASELINE],- ['POST /api/catalog/migration/rerun', PRE_GUARD_BASELINE],- ['POST /api/catalog/scraps', PRE_GUARD_BASELINE],+ ['POST /api/catalog/ingredients/:id/relations', RECORDS],+ ['POST /api/catalog/ingredients/:id/revisions/:revisionId/restore', RECORDS],+ ['POST /api/catalog/ingredients/:id/sheets/preview', READ_OVER_POST],+ ['POST /api/catalog/ingredients/merge', RECORDS],+ ['POST /api/catalog/migration/rerun', RECORDS],+ ['POST /api/catalog/scraps', RECORDS],['DELETE /api/catalog/scraps/:id', REMOVES_RECORD],- ['PATCH /api/catalog/scraps/:id', PRE_GUARD_BASELINE],- ['POST /api/catalog/scraps/:id/commit', PRE_GUARD_BASELINE],- ['POST /api/catalog/sync/apply', PRE_GUARD_BASELINE],- ['POST /api/catalog/types', PRE_GUARD_BASELINE],+ ['PATCH /api/catalog/scraps/:id', RECORDS],+ ['POST /api/catalog/scraps/:id/commit', RECORDS],+ ['POST /api/catalog/sync/apply', RECORDS],+ ['POST /api/catalog/types', RECORDS],['DELETE /api/catalog/types/:id', REMOVES_RECORD],- ['PATCH /api/catalog/types/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/catalog/types/:id', RECORDS],// /api/character- ['PUT /api/character', PRE_GUARD_BASELINE],- ['POST /api/character/damage', PRE_GUARD_BASELINE],- ['POST /api/character/event', PRE_GUARD_BASELINE],- ['POST /api/character/reset', PRE_GUARD_BASELINE],- ['POST /api/character/rest', PRE_GUARD_BASELINE],- ['POST /api/character/sync/jira', PRE_GUARD_BASELINE],- ['POST /api/character/sync/tasks', PRE_GUARD_BASELINE],- ['POST /api/character/xp', PRE_GUARD_BASELINE],+ ['PUT /api/character', RECORDS],+ ['POST /api/character/damage', RECORDS],+ ['POST /api/character/event', RECORDS],+ ['POST /api/character/reset', REMOVES_RECORD],+ ['POST /api/character/rest', RECORDS],+ ['POST /api/character/sync/jira', EXTERNAL_SYNC],+ ['POST /api/character/sync/tasks', RECORDS],+ ['POST /api/character/xp', RECORDS],// /api/client-errors- ['POST /api/client-errors', PRE_GUARD_BASELINE],+ ['POST /api/client-errors', CLIENT_TELEMETRY],// /api/code-animation- ['POST /api/code-animation/:id/export', PRE_GUARD_BASELINE],- ['POST /api/code-animation/:id/soundtrack/track', PRE_GUARD_BASELINE],+ ['POST /api/code-animation/:id/soundtrack/track', RECORDS],['DELETE /api/code-animation/jobs/:id', REMOVES_RECORD],- ['POST /api/code-animation/jobs/:id/poster', PRE_GUARD_BASELINE],- ['POST /api/code-animation/packages/validate', PRE_GUARD_BASELINE],- ['POST /api/code-animation/projects', PRE_GUARD_BASELINE],- ['PATCH /api/code-animation/projects/:id', PRE_GUARD_BASELINE],- ['POST /api/code-animation/projects/:id/accept', PRE_GUARD_BASELINE],- ['POST /api/code-animation/projects/:id/accepted-output', PRE_GUARD_BASELINE],- ['POST /api/code-animation/projects/:id/import', PRE_GUARD_BASELINE],- ['POST /api/code-animation/projects/:id/sound-assets', PRE_GUARD_BASELINE],+ ['POST /api/code-animation/packages/validate', READ_OVER_POST],+ ['POST /api/code-animation/projects', RECORDS],+ ['PATCH /api/code-animation/projects/:id', RECORDS],+ ['POST /api/code-animation/projects/:id/accept', RECORDS],+ ['POST /api/code-animation/projects/:id/accepted-output', RECORDS],+ ['POST /api/code-animation/projects/:id/import', RECORDS],+ ['POST /api/code-animation/projects/:id/sound-assets', RECORDS],['POST /api/code-animation/projects/:id/stage-runs/:runId/cancel', REDUCES_EXECUTION],// /api/code-review['POST /api/code-review/cli-outcome', RECORDS],- ['POST /api/code-review/report-failure', PRE_GUARD_BASELINE],+ ['POST /api/code-review/report-failure', RECORDS],// /api/commands['POST /api/commands/:id/stop', HANDLER_GATED],['POST /api/commands/execute', HANDLER_GATED],['POST /api/commands/processes/:name/action', HANDLER_GATED],// /api/conflict-journal['DELETE /api/conflict-journal/:id', REMOVES_RECORD],- ['POST /api/conflict-journal/:id/resolve', PRE_GUARD_BASELINE],// /api/contacts- ['POST /api/contacts/enrich-tribe', PRE_GUARD_BASELINE],- ['POST /api/contacts/import-to-tribe', PRE_GUARD_BASELINE],- ['POST /api/contacts/sync', PRE_GUARD_BASELINE],+ ['POST /api/contacts/enrich-tribe', RECORDS],+ ['POST /api/contacts/import-to-tribe', RECORDS],+ ['POST /api/contacts/sync', LOCAL_SOURCE_SYNC],// /api/continuous-video- ['POST /api/continuous-video', PRE_GUARD_BASELINE],- ['POST /api/continuous-video/lint', PRE_GUARD_BASELINE],+ ['POST /api/continuous-video/lint', READ_OVER_POST],// /api/cos['DELETE /api/cos/agents/:id', REMOVES_RECORD],['POST /api/cos/agents/:id/feedback', RECORDS],@@ -292,38 +299,33 @@ const REVIEWED_OPEN_MUTATIONS = [['POST /api/cos/agents/:id/pause', REDUCES_EXECUTION],['POST /api/cos/agents/:id/terminate', REDUCES_EXECUTION],['DELETE /api/cos/agents/completed', REMOVES_RECORD],- ['POST /api/cos/app-activity/:appId/clear-cooldown', PRE_GUARD_BASELINE],['POST /api/cos/digest/generate', DERIVED_REPORT],- ['POST /api/cos/health/check', PRE_GUARD_BASELINE],['DELETE /api/cos/jobs/:id', REMOVES_RECORD],- ['POST /api/cos/jobs/:id/gate-check', PRE_GUARD_BASELINE],- ['POST /api/cos/learning/backfill', PRE_GUARD_BASELINE],+ ['POST /api/cos/jobs/:id/gate-check', READ_OVER_POST],['POST /api/cos/learning/insights', RECORDS],- ['POST /api/cos/learning/recalculate-durations', PRE_GUARD_BASELINE],- ['POST /api/cos/learning/recommendations/clear-dismissed', PRE_GUARD_BASELINE],- ['POST /api/cos/learning/recommendations/dismiss', PRE_GUARD_BASELINE],- ['POST /api/cos/learning/recommendations/restore', PRE_GUARD_BASELINE],- ['POST /api/cos/learning/reset/:taskType', PRE_GUARD_BASELINE],+ ['POST /api/cos/learning/recalculate-durations', IN_PROCESS_COMPUTE],+ ['POST /api/cos/learning/recommendations/clear-dismissed', RECORDS],+ ['POST /api/cos/learning/recommendations/dismiss', RECORDS],+ ['POST /api/cos/learning/recommendations/restore', RECORDS],['DELETE /api/cos/mind/attachments/:attachmentId', REMOVES_RECORD],- ['POST /api/cos/mind/bundle/export', PRE_GUARD_BASELINE],- ['POST /api/cos/mind/bundle/preview', PRE_GUARD_BASELINE],- ['POST /api/cos/mind/cleanup', PRE_GUARD_BASELINE],- ['POST /api/cos/mind/events/:eventId/acknowledge', PRE_GUARD_BASELINE],- ['POST /api/cos/mind/events/:eventId/promote', PRE_GUARD_BASELINE],- ['POST /api/cos/mind/memories', PRE_GUARD_BASELINE],- ['PUT /api/cos/mind/memories/:memoryId', PRE_GUARD_BASELINE],+ ['POST /api/cos/mind/bundle/export', READ_OVER_POST],+ ['POST /api/cos/mind/bundle/preview', READ_OVER_POST],+ ['POST /api/cos/mind/cleanup', REMOVES_RECORD],+ ['POST /api/cos/mind/events/:eventId/acknowledge', RECORDS],+ ['POST /api/cos/mind/events/:eventId/promote', RECORDS],+ ['POST /api/cos/mind/memories', RECORDS],+ ['PUT /api/cos/mind/memories/:memoryId', RECORDS],['POST /api/cos/mind/pause', REDUCES_EXECUTION],- ['POST /api/cos/mind/recipes/:recipeId/archive', PRE_GUARD_BASELINE],- ['POST /api/cos/mind/recipes/validate', PRE_GUARD_BASELINE],+ ['POST /api/cos/mind/recipes/:recipeId/archive', REMOVES_RECORD],+ ['POST /api/cos/mind/recipes/validate', READ_OVER_POST],['POST /api/cos/mind/stop', REDUCES_EXECUTION],['DELETE /api/cos/mind/thinking-request', REMOVES_RECORD],['POST /api/cos/pause', REDUCES_EXECUTION],['POST /api/cos/reports/generate', DERIVED_REPORT],- ['PATCH /api/cos/schedule/maintenance-runs/:id/archive', PRE_GUARD_BASELINE],+ ['PATCH /api/cos/schedule/maintenance-runs/:id/archive', RECORDS],['POST /api/cos/schedule/maintenance-runs/:id/stop', REDUCES_EXECUTION],['DELETE /api/cos/schedule/on-demand/:requestId', REMOVES_RECORD],- ['POST /api/cos/schedule/reset', PRE_GUARD_BASELINE],- ['POST /api/cos/schedule/templates', PRE_GUARD_BASELINE],+ ['POST /api/cos/schedule/templates', RECORDS],['DELETE /api/cos/schedule/templates/:templateId', REMOVES_RECORD],['POST /api/cos/stop', REDUCES_EXECUTION],['DELETE /api/cos/tasks/:id', REMOVES_RECORD],@@ -343,152 +345,141 @@ const REVIEWED_OPEN_MUTATIONS = [['POST /api/creative-director/:id/stop', REDUCES_EXECUTION],['POST /api/creative-director/auto-cast/suggest', RECORDS],// /api/daily-driver- ['POST /api/daily-driver/handled', PRE_GUARD_BASELINE],+ ['POST /api/daily-driver/handled', RECORDS],// /api/dashboard/layouts['DELETE /api/dashboard/layouts/:id', REMOVES_RECORD],- ['PUT /api/dashboard/layouts/:id', PRE_GUARD_BASELINE],- ['PUT /api/dashboard/layouts/active', PRE_GUARD_BASELINE],+ ['PUT /api/dashboard/layouts/:id', RECORDS],+ ['PUT /api/dashboard/layouts/active', RECORDS],// /api/data['DELETE /api/data/:category', REMOVES_RECORD],- ['POST /api/data/:category/archive', PRE_GUARD_BASELINE],['DELETE /api/data/backups/:filename', REMOVES_RECORD],['POST /api/data/cos/storage/cancel', REDUCES_EXECUTION],- ['PUT /api/data/cos/storage/pin', PRE_GUARD_BASELINE],- ['PUT /api/data/cos/storage/policy', PRE_GUARD_BASELINE],- ['POST /api/data/cos/storage/preview', PRE_GUARD_BASELINE],- ['POST /api/data/cos/storage/run', PRE_GUARD_BASELINE],+ ['PUT /api/data/cos/storage/pin', RECORDS],+ ['PUT /api/data/cos/storage/policy', RECORDS],+ ['POST /api/data/cos/storage/preview', READ_OVER_POST],+ ['POST /api/data/cos/storage/run', REMOVES_RECORD],// /api/database- ['POST /api/database/maintenance/preflight', PRE_GUARD_BASELINE],+ ['POST /api/database/maintenance/preflight', READ_ONLY_PROBE],// /api/datadog['DELETE /api/datadog/instances/:id', REMOVES_RECORD],- ['POST /api/datadog/instances/:id/search-errors', PRE_GUARD_BASELINE],- ['POST /api/datadog/instances/:id/test', PRE_GUARD_BASELINE],+ ['POST /api/datadog/instances/:id/search-errors', READ_ONLY_EXTERNAL],+ ['POST /api/datadog/instances/:id/test', READ_ONLY_EXTERNAL],// /api/decks- ['POST /api/decks', PRE_GUARD_BASELINE],+ ['POST /api/decks', RECORDS],['DELETE /api/decks/:id', REMOVES_RECORD],- ['PATCH /api/decks/:id', PRE_GUARD_BASELINE],- ['PATCH /api/decks/:id/cards/:cardId', PRE_GUARD_BASELINE],- ['POST /api/decks/:id/samples', PRE_GUARD_BASELINE],+ ['PATCH /api/decks/:id', RECORDS],+ ['PATCH /api/decks/:id/cards/:cardId', RECORDS],+ ['POST /api/decks/:id/samples', RECORDS],['DELETE /api/decks/:id/samples/:sampleId', REMOVES_RECORD],// /api/detect['POST /api/detect/ai', HANDLER_GATED],- ['POST /api/detect/pm2', PRE_GUARD_BASELINE],- ['POST /api/detect/port', PRE_GUARD_BASELINE],- ['POST /api/detect/repo', PRE_GUARD_BASELINE],+ ['POST /api/detect/pm2', READ_OVER_POST],+ ['POST /api/detect/port', READ_ONLY_PROBE],// /api/devtools/video-download['POST /api/devtools/video-download/:jobId/cancel', REDUCES_EXECUTION],['DELETE /api/devtools/video-download/downloads/:id', REMOVES_RECORD],// /api/digital-twin- ['POST /api/digital-twin/documents', PRE_GUARD_BASELINE],+ ['POST /api/digital-twin/documents', RECORDS],['DELETE /api/digital-twin/documents/:id', REMOVES_RECORD],- ['PUT /api/digital-twin/documents/:id', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/enrich/save-list', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/export', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/feedback', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/feedback/recalculate', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/identity/image', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/identity/image/save', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/import/save', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/import/spotify/browser/open', PRE_GUARD_BASELINE],+ ['PUT /api/digital-twin/documents/:id', RECORDS],+ ['POST /api/digital-twin/enrich/save-list', RECORDS],+ ['POST /api/digital-twin/export', READ_OVER_POST],+ ['POST /api/digital-twin/feedback', RECORDS],+ ['POST /api/digital-twin/feedback/recalculate', DERIVED_REPORT],+ ['POST /api/digital-twin/identity/image', TOOL_FREE_INFERENCE],+ ['POST /api/digital-twin/identity/image/save', RECORDS],+ ['POST /api/digital-twin/import/save', RECORDS],['DELETE /api/digital-twin/personas/:id', REMOVES_RECORD],['PUT /api/digital-twin/settings', HANDLER_GATED],- ['POST /api/digital-twin/snapshots', PRE_GUARD_BASELINE],+ ['POST /api/digital-twin/snapshots', RECORDS],['DELETE /api/digital-twin/snapshots/:id', REMOVES_RECORD],- ['POST /api/digital-twin/snapshots/compare', PRE_GUARD_BASELINE],+ ['POST /api/digital-twin/snapshots/compare', READ_OVER_POST],['DELETE /api/digital-twin/taste/:section', REMOVES_RECORD],- ['POST /api/digital-twin/taste/:section/personalized-question', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/taste/answer', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/taste/summary', PRE_GUARD_BASELINE],- ['PUT /api/digital-twin/traits', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/twin-evidence/recompute', PRE_GUARD_BASELINE],+ ['POST /api/digital-twin/taste/:section/personalized-question', TOOL_FREE_INFERENCE],+ ['POST /api/digital-twin/taste/answer', RECORDS],+ ['POST /api/digital-twin/taste/summary', TOOL_FREE_INFERENCE],+ ['PUT /api/digital-twin/traits', RECORDS],+ ['POST /api/digital-twin/twin-evidence/recompute', DERIVED_REPORT],// /api/digital-twin/autobiography- ['PUT /api/digital-twin/autobiography/config', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/autobiography/stories', PRE_GUARD_BASELINE],+ ['PUT /api/digital-twin/autobiography/config', RECORDS],+ ['POST /api/digital-twin/autobiography/stories', RECORDS],['DELETE /api/digital-twin/autobiography/stories/:id', REMOVES_RECORD],- ['PUT /api/digital-twin/autobiography/stories/:id', PRE_GUARD_BASELINE],+ ['PUT /api/digital-twin/autobiography/stories/:id', RECORDS],['POST /api/digital-twin/autobiography/stories/:id/evaluate', TOOL_FREE_INFERENCE],['POST /api/digital-twin/autobiography/stories/:id/follow-ups', TOOL_FREE_INFERENCE],['POST /api/digital-twin/autobiography/stories/:id/weave', TOOL_FREE_INFERENCE],- ['POST /api/digital-twin/autobiography/trigger', PRE_GUARD_BASELINE],+ ['POST /api/digital-twin/autobiography/trigger', RECORDS],// /api/digital-twin/identity- ['PUT /api/digital-twin/identity/chronotype', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/identity/chronotype/derive', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/identity/goals', PRE_GUARD_BASELINE],+ ['PUT /api/digital-twin/identity/chronotype', RECORDS],+ ['POST /api/digital-twin/identity/chronotype/derive', DERIVED_REPORT],+ ['POST /api/digital-twin/identity/goals', RECORDS],['DELETE /api/digital-twin/identity/goals/:id', REMOVES_RECORD],- ['PUT /api/digital-twin/identity/goals/:id', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/identity/goals/:id/accept-decomposition', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/identity/goals/:id/accept-phases', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/identity/goals/:id/activities', PRE_GUARD_BASELINE],+ ['PUT /api/digital-twin/identity/goals/:id', RECORDS],+ ['POST /api/digital-twin/identity/goals/:id/accept-decomposition', RECORDS],+ ['POST /api/digital-twin/identity/goals/:id/accept-phases', RECORDS],+ ['POST /api/digital-twin/identity/goals/:id/activities', RECORDS],['DELETE /api/digital-twin/identity/goals/:id/activities/:activityName', REMOVES_RECORD],- ['POST /api/digital-twin/identity/goals/:id/calendars', PRE_GUARD_BASELINE],+ ['POST /api/digital-twin/identity/goals/:id/calendars', RECORDS],['DELETE /api/digital-twin/identity/goals/:id/calendars/:subcalendarId', REMOVES_RECORD],['POST /api/digital-twin/identity/goals/:id/check-in', TOOL_FREE_INFERENCE],['POST /api/digital-twin/identity/goals/:id/decompose', TOOL_FREE_INFERENCE],['POST /api/digital-twin/identity/goals/:id/generate-phases', TOOL_FREE_INFERENCE],- ['POST /api/digital-twin/identity/goals/:id/milestones', PRE_GUARD_BASELINE],- ['PUT /api/digital-twin/identity/goals/:id/milestones/:milestoneId/complete', PRE_GUARD_BASELINE],- ['PUT /api/digital-twin/identity/goals/:id/milestones/:milestoneId/tasks/:taskId/complete', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/identity/goals/:id/progress', PRE_GUARD_BASELINE],- ['PUT /api/digital-twin/identity/goals/:id/progress', PRE_GUARD_BASELINE],+ ['POST /api/digital-twin/identity/goals/:id/milestones', RECORDS],+ ['PUT /api/digital-twin/identity/goals/:id/milestones/:milestoneId/complete', RECORDS],+ ['PUT /api/digital-twin/identity/goals/:id/milestones/:milestoneId/tasks/:taskId/complete', RECORDS],+ ['POST /api/digital-twin/identity/goals/:id/progress', RECORDS],+ ['PUT /api/digital-twin/identity/goals/:id/progress', RECORDS],['DELETE /api/digital-twin/identity/goals/:id/progress/:entryId', REMOVES_RECORD],- ['POST /api/digital-twin/identity/goals/:id/reschedule', PRE_GUARD_BASELINE],['DELETE /api/digital-twin/identity/goals/:id/schedule', REMOVES_RECORD],- ['POST /api/digital-twin/identity/goals/:id/schedule', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/identity/goals/:id/todos', PRE_GUARD_BASELINE],+ ['POST /api/digital-twin/identity/goals/:id/todos', RECORDS],['DELETE /api/digital-twin/identity/goals/:id/todos/:todoId', REMOVES_RECORD],- ['PUT /api/digital-twin/identity/goals/:id/todos/:todoId', PRE_GUARD_BASELINE],- ['PUT /api/digital-twin/identity/goals/birth-date', PRE_GUARD_BASELINE],+ ['PUT /api/digital-twin/identity/goals/:id/todos/:todoId', RECORDS],+ ['PUT /api/digital-twin/identity/goals/birth-date', RECORDS],['POST /api/digital-twin/identity/goals/organize', TOOL_FREE_INFERENCE],- ['POST /api/digital-twin/identity/goals/organize/apply', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/identity/longevity/derive', PRE_GUARD_BASELINE],+ ['POST /api/digital-twin/identity/goals/organize/apply', RECORDS],+ ['POST /api/digital-twin/identity/longevity/derive', DERIVED_REPORT],// /api/digital-twin/social-accounts- ['POST /api/digital-twin/social-accounts', PRE_GUARD_BASELINE],+ ['POST /api/digital-twin/social-accounts', RECORDS],['DELETE /api/digital-twin/social-accounts/:id', REMOVES_RECORD],- ['PUT /api/digital-twin/social-accounts/:id', PRE_GUARD_BASELINE],- ['POST /api/digital-twin/social-accounts/bulk', PRE_GUARD_BASELINE],+ ['PUT /api/digital-twin/social-accounts/:id', RECORDS],+ ['POST /api/digital-twin/social-accounts/bulk', RECORDS],// /api/eidoverse/travel- ['POST /api/eidoverse/travel/depart', PRE_GUARD_BASELINE],['POST /api/eidoverse/travel/federation/chat', PEER_SURFACE],['POST /api/eidoverse/travel/federation/leave', PEER_SURFACE],['POST /api/eidoverse/travel/federation/visit', PEER_SURFACE],// /api/eidoverse/world- ['PUT /api/eidoverse/world/config', PRE_GUARD_BASELINE],- ['POST /api/eidoverse/world/controllers', PRE_GUARD_BASELINE],['DELETE /api/eidoverse/world/controllers/:id', REMOVES_RECORD],- ['PATCH /api/eidoverse/world/controllers/:id', PRE_GUARD_BASELINE],- ['PATCH /api/eidoverse/world/controllers/:id/config', PRE_GUARD_BASELINE],- ['POST /api/eidoverse/world/foundations', PRE_GUARD_BASELINE],+ ['POST /api/eidoverse/world/foundations', RECORDS],['DELETE /api/eidoverse/world/foundations/:id', REMOVES_RECORD],- ['POST /api/eidoverse/world/foundations/:id/adopt', PRE_GUARD_BASELINE],- ['POST /api/eidoverse/world/foundations/:id/candidate', PRE_GUARD_BASELINE],- ['POST /api/eidoverse/world/foundations/:id/promote', PRE_GUARD_BASELINE],- ['POST /api/eidoverse/world/foundations/:id/withdraw', PRE_GUARD_BASELINE],- ['POST /api/eidoverse/world/presence', PRE_GUARD_BASELINE],- ['POST /api/eidoverse/world/project', PRE_GUARD_BASELINE],+ ['POST /api/eidoverse/world/foundations/:id/adopt', RECORDS],+ ['POST /api/eidoverse/world/foundations/:id/candidate', IN_PROCESS_COMPUTE],+ ['POST /api/eidoverse/world/foundations/:id/promote', PEER_SYNC],+ ['POST /api/eidoverse/world/foundations/:id/withdraw', REMOVES_RECORD],+ ['POST /api/eidoverse/world/presence', CONFIGURED_WORLD_SYNC],+ ['POST /api/eidoverse/world/project', CONFIGURED_WORLD_SYNC],// /api/fableloom- ['POST /api/fableloom', PRE_GUARD_BASELINE],+ ['POST /api/fableloom', RECORDS],['DELETE /api/fableloom/:id', REMOVES_RECORD],- ['PATCH /api/fableloom/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/fableloom/:id', RECORDS],['POST /api/fableloom/:id/editorial/autopilot/:runId/cancel', REDUCES_EXECUTION],- ['POST /api/fableloom/:id/episodes', PRE_GUARD_BASELINE],+ ['POST /api/fableloom/:id/episodes', RECORDS],['DELETE /api/fableloom/:id/episodes/:episodeId', REMOVES_RECORD],- ['PATCH /api/fableloom/:id/episodes/:episodeId', PRE_GUARD_BASELINE],- ['POST /api/fableloom/:id/episodes/:episodeId/continuity/review', PRE_GUARD_BASELINE],- ['POST /api/fableloom/:id/episodes/:episodeId/nodes', PRE_GUARD_BASELINE],+ ['PATCH /api/fableloom/:id/episodes/:episodeId', RECORDS],+ ['POST /api/fableloom/:id/episodes/:episodeId/continuity/review', READ_OVER_POST],+ ['POST /api/fableloom/:id/episodes/:episodeId/nodes', RECORDS],['DELETE /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId', REMOVES_RECORD],- ['PATCH /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId', PRE_GUARD_BASELINE],- ['POST /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/fal-video', PRE_GUARD_BASELINE],- ['POST /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/transitions', PRE_GUARD_BASELINE],+ ['PATCH /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId', RECORDS],+ ['POST /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/transitions', RECORDS],['DELETE /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/transitions/:transitionId', REMOVES_RECORD],- ['PATCH /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/transitions/:transitionId', PRE_GUARD_BASELINE],- ['POST /api/fableloom/:id/episodes/:episodeId/outline/validate', PRE_GUARD_BASELINE],+ ['PATCH /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/transitions/:transitionId', RECORDS],+ ['POST /api/fableloom/:id/episodes/:episodeId/outline/validate', DERIVED_REPORT],['POST /api/fableloom/:id/episodes/:episodeId/production/batch/:runId/cancel', REDUCES_EXECUTION],- ['POST /api/fableloom/:id/episodes/:episodeId/production/plan', PRE_GUARD_BASELINE],- ['POST /api/fableloom/:id/episodes/:episodeId/sessions/host', PRE_GUARD_BASELINE],- ['POST /api/fableloom/:id/episodes/:episodeId/sessions/preflight', PRE_GUARD_BASELINE],- ['POST /api/fableloom/:id/episodes/:episodeId/shots/apply', PRE_GUARD_BASELINE],+ ['POST /api/fableloom/:id/episodes/:episodeId/production/plan', READ_OVER_POST],+ ['POST /api/fableloom/:id/episodes/:episodeId/sessions/host', TOOL_FREE_INFERENCE],+ ['POST /api/fableloom/:id/episodes/:episodeId/sessions/preflight', READ_OVER_POST],+ ['POST /api/fableloom/:id/episodes/:episodeId/shots/apply', RECORDS],['DELETE /api/fableloom/sessions/:sessionId', REMOVES_RECORD],- ['PATCH /api/fableloom/sessions/:sessionId', PRE_GUARD_BASELINE],+ ['PATCH /api/fableloom/sessions/:sessionId', RECORDS],// /api/feature-agents['DELETE /api/feature-agents/:id', REMOVES_RECORD],['POST /api/feature-agents/:id/pause', REDUCES_EXECUTION],@@ -506,26 +497,24 @@ const REVIEWED_OPEN_MUTATIONS = [['POST /api/federation/media/v1/jobs', PEER_SURFACE],['POST /api/federation/media/v1/jobs/:id/cancel', PEER_SURFACE],// /api/feeds- ['POST /api/feeds', PRE_GUARD_BASELINE],+ ['POST /api/feeds', READ_ONLY_EXTERNAL],['DELETE /api/feeds/:id', REMOVES_RECORD],- ['POST /api/feeds/:id/refresh', PRE_GUARD_BASELINE],- ['POST /api/feeds/items/:id/read', PRE_GUARD_BASELINE],- ['POST /api/feeds/items/read-all', PRE_GUARD_BASELINE],- ['POST /api/feeds/refresh-all', PRE_GUARD_BASELINE],+ ['POST /api/feeds/:id/refresh', READ_ONLY_EXTERNAL],+ ['POST /api/feeds/items/:id/read', RECORDS],+ ['POST /api/feeds/items/read-all', RECORDS],+ ['POST /api/feeds/refresh-all', READ_ONLY_EXTERNAL],// /api/games- ['POST /api/games', PRE_GUARD_BASELINE],+ ['POST /api/games', RECORDS],['DELETE /api/games/:id', REMOVES_RECORD],- ['PATCH /api/games/:id', PRE_GUARD_BASELINE],- ['POST /api/games/:id/artwork', PRE_GUARD_BASELINE],+ ['PATCH /api/games/:id', RECORDS],+ ['POST /api/games/:id/artwork', RECORDS],['DELETE /api/games/:id/artwork/:bindingId', REMOVES_RECORD],- ['PATCH /api/games/:id/artwork/:bindingId', PRE_GUARD_BASELINE],- ['POST /api/games/:id/artwork/:bindingId/publish', PRE_GUARD_BASELINE],- ['POST /api/games/:id/compile', PRE_GUARD_BASELINE],- ['POST /api/games/:id/music', PRE_GUARD_BASELINE],+ ['PATCH /api/games/:id/artwork/:bindingId', RECORDS],+ ['POST /api/games/:id/compile', IN_PROCESS_COMPUTE],+ ['POST /api/games/:id/music', RECORDS],['DELETE /api/games/:id/music/:bindingId', REMOVES_RECORD],- ['PATCH /api/games/:id/music/:bindingId', PRE_GUARD_BASELINE],- ['POST /api/games/:id/music/:bindingId/publish', PRE_GUARD_BASELINE],- ['POST /api/games/:id/sprites', PRE_GUARD_BASELINE],+ ['PATCH /api/games/:id/music/:bindingId', RECORDS],+ ['POST /api/games/:id/sprites', RECORDS],['DELETE /api/games/:id/sprites/:spriteId', REMOVES_RECORD],// /api/github['DELETE /api/github/accounts/:id', REMOVES_RECORD],@@ -536,19 +525,18 @@ const REVIEWED_OPEN_MUTATIONS = [// /api/harnesses['POST /api/harnesses/models/refresh', CONFIGURED_INFERENCE],// /api/health- ['POST /api/health/import/xml', PRE_GUARD_BASELINE],- ['POST /api/health/ingest', PRE_GUARD_BASELINE],+ ['POST /api/health/import/xml', RECORDS],+ ['POST /api/health/ingest', RECORDS],// /api/history['DELETE /api/history', REMOVES_RECORD],['DELETE /api/history/:id', REMOVES_RECORD],// /api/html-composition['POST /api/html-composition/:jobId/cancel', REDUCES_EXECUTION],- ['POST /api/html-composition/render', PRE_GUARD_BASELINE],// /api/human-actions- ['POST /api/human-actions/plans', PRE_GUARD_BASELINE],+ ['POST /api/human-actions/plans', RECORDS],// /api/image-clean- ['POST /api/image-clean', PRE_GUARD_BASELINE],- ['POST /api/image-clean/result/:jobId/save', PRE_GUARD_BASELINE],+ ['POST /api/image-clean', HANDLER_GATED],+ ['POST /api/image-clean/result/:jobId/save', RECORDS],// /api/image-gen['DELETE /api/image-gen/:filename', REMOVES_RECORD],['POST /api/image-gen/:filename/clean', IN_PROCESS_MEDIA],@@ -564,63 +552,63 @@ const REVIEWED_OPEN_MUTATIONS = [['POST /api/image-gen/setup/create-venv', HANDLER_GATED],['POST /api/image-gen/setup/flux2-install', MANAGED_INSTALL],['DELETE /api/image-gen/setup/hf-token', REMOVES_RECORD],- ['POST /api/image-gen/setup/hf-token', PRE_GUARD_BASELINE],+ ['POST /api/image-gen/setup/hf-token', CONNECTOR_CREDENTIAL],['POST /api/image-gen/setup/install', HANDLER_GATED],['POST /api/image-gen/setup/moss-install', HANDLER_GATED],['POST /api/image-gen/setup/moss-weights', HANDLER_GATED],- ['POST /api/image-gen/upload', PRE_GUARD_BASELINE],+ ['POST /api/image-gen/upload', RECORDS],// /api/image-to-3d['DELETE /api/image-to-3d/models/:id', REMOVES_RECORD],- ['POST /api/image-to-3d/models/:id/usdz', PRE_GUARD_BASELINE],+ ['POST /api/image-to-3d/models/:id/usdz', RECORDS],// /api/image-video/models['DELETE /api/image-video/models/custom/:id', REMOVES_RECORD],- ['PATCH /api/image-video/models/custom/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/image-video/models/custom/:id', RECORDS],['DELETE /api/image-video/models/hf/:dirName', REMOVES_RECORD],['POST /api/image-video/models/install/huggingface', MODEL_DATA],['DELETE /api/image-video/models/lora/:filename', REMOVES_RECORD],- ['PATCH /api/image-video/models/registry/:id/availability', PRE_GUARD_BASELINE],+ ['PATCH /api/image-video/models/registry/:id/availability', RECORDS],['DELETE /api/image-video/models/store/:backend/:key', REMOVES_RECORD],// /api/imessage- ['POST /api/imessage/blocklist', PRE_GUARD_BASELINE],- ['PUT /api/imessage/blocklist', PRE_GUARD_BASELINE],+ ['POST /api/imessage/blocklist', RECORDS],+ ['PUT /api/imessage/blocklist', RECORDS],['DELETE /api/imessage/blocklist/:handle', REMOVES_RECORD],['DELETE /api/imessage/conversations/:chatKey', REMOVES_RECORD],['DELETE /api/imessage/events/:id', REMOVES_RECORD],- ['POST /api/imessage/sync', PRE_GUARD_BASELINE],+ ['POST /api/imessage/sync', LOCAL_SOURCE_SYNC],// /api/insights- ['POST /api/insights/goal-scorecard/compute', PRE_GUARD_BASELINE],- ['PUT /api/insights/goal-scorecard/rules', PRE_GUARD_BASELINE],- ['PUT /api/insights/goal-scorecard/settings', PRE_GUARD_BASELINE],+ ['POST /api/insights/goal-scorecard/compute', DERIVED_REPORT],+ ['PUT /api/insights/goal-scorecard/rules', RECORDS],+ ['PUT /api/insights/goal-scorecard/settings', RECORDS],['POST /api/insights/narrative/refresh', TOOL_FREE_INFERENCE],['POST /api/insights/themes/refresh', TOOL_FREE_INFERENCE],// /api/instances- ['POST /api/instances/peers', PRE_GUARD_BASELINE],+ ['POST /api/instances/peers', HANDLER_GATED],['DELETE /api/instances/peers/:id', REMOVES_RECORD],- ['PUT /api/instances/peers/:id', PRE_GUARD_BASELINE],- ['POST /api/instances/peers/:id/connect', PRE_GUARD_BASELINE],- ['POST /api/instances/peers/:id/pair-secret', PRE_GUARD_BASELINE],- ['POST /api/instances/peers/:id/probe', PRE_GUARD_BASELINE],- ['POST /api/instances/peers/:id/reciprocate', PRE_GUARD_BASELINE],- ['POST /api/instances/peers/:id/sync', PRE_GUARD_BASELINE],+ ['PUT /api/instances/peers/:id', HANDLER_GATED],+ ['POST /api/instances/peers/:id/connect', HANDLER_GATED],+ ['POST /api/instances/peers/:id/pair-secret', HANDLER_GATED],+ ['POST /api/instances/peers/:id/probe', HANDLER_GATED],+ ['POST /api/instances/peers/:id/reciprocate', HANDLER_GATED],+ ['POST /api/instances/peers/:id/sync', HANDLER_GATED],['POST /api/instances/peers/announce', PEER_SURFACE],['POST /api/instances/peers/pair-secret', PEER_SURFACE],['POST /api/instances/peers/sync-categories', PEER_SURFACE],['DELETE /api/instances/peers/tailcat/forwards/:id', REMOVES_RECORD],['DELETE /api/instances/peers/tailcat/serve', REMOVES_RECORD],- ['PUT /api/instances/self', PRE_GUARD_BASELINE],+ ['PUT /api/instances/self', RECORDS],// /api/jira['DELETE /api/jira/instances/:id', REMOVES_RECORD],- ['POST /api/jira/instances/:id/test', PRE_GUARD_BASELINE],- ['POST /api/jira/reports/generate', PRE_GUARD_BASELINE],+ ['POST /api/jira/instances/:id/test', READ_ONLY_EXTERNAL],+ ['POST /api/jira/reports/generate', TOOL_FREE_INFERENCE],// /api/legacy-export- ['POST /api/legacy-export', PRE_GUARD_BASELINE],+ ['POST /api/legacy-export', READ_OVER_POST],// /api/lmstudio- ['POST /api/lmstudio/analyze-task', PRE_GUARD_BASELINE],- ['POST /api/lmstudio/classify-memory', PRE_GUARD_BASELINE],- ['POST /api/lmstudio/completion', PRE_GUARD_BASELINE],+ ['POST /api/lmstudio/analyze-task', TOOL_FREE_INFERENCE],+ ['POST /api/lmstudio/classify-memory', TOOL_FREE_INFERENCE],+ ['POST /api/lmstudio/completion', TOOL_FREE_INFERENCE],['POST /api/lmstudio/download', MODEL_DATA],- ['POST /api/lmstudio/embeddings', PRE_GUARD_BASELINE],- ['POST /api/lmstudio/load', PRE_GUARD_BASELINE],+ ['POST /api/lmstudio/embeddings', TOOL_FREE_INFERENCE],+ ['POST /api/lmstudio/load', MODEL_DATA],['POST /api/lmstudio/unload', REDUCES_EXECUTION],// /api/local-llm['POST /api/local-llm/assessments/delete', MODEL_DATA],@@ -653,305 +641,263 @@ const REVIEWED_OPEN_MUTATIONS = [['DELETE /api/loops/:id', REMOVES_RECORD],['POST /api/loops/:id/stop', REDUCES_EXECUTION],// /api/lora-datasets- ['POST /api/lora-datasets', PRE_GUARD_BASELINE],+ ['POST /api/lora-datasets', RECORDS],['DELETE /api/lora-datasets/:id', REMOVES_RECORD],- ['PATCH /api/lora-datasets/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/lora-datasets/:id', RECORDS],['POST /api/lora-datasets/:id/caption-runs/:runId/cancel', REDUCES_EXECUTION],- ['POST /api/lora-datasets/:id/images', PRE_GUARD_BASELINE],+ ['POST /api/lora-datasets/:id/images', RECORDS],['DELETE /api/lora-datasets/:id/images/:imageId', REMOVES_RECORD],- ['PATCH /api/lora-datasets/:id/images/:imageId', PRE_GUARD_BASELINE],- ['POST /api/lora-datasets/:id/import-gallery', PRE_GUARD_BASELINE],- ['POST /api/lora-datasets/:id/strip-shared-fragments', PRE_GUARD_BASELINE],+ ['PATCH /api/lora-datasets/:id/images/:imageId', RECORDS],+ ['POST /api/lora-datasets/:id/import-gallery', IN_PROCESS_MEDIA],+ ['POST /api/lora-datasets/:id/strip-shared-fragments', RECORDS],// /api/lora-training['DELETE /api/lora-training/runs/:id', REMOVES_RECORD],['POST /api/lora-training/runs/:id/cancel', REDUCES_EXECUTION],- ['POST /api/lora-training/runs/:id/promote-checkpoint', PRE_GUARD_BASELINE],// /api/loras['DELETE /api/loras/:filename', REMOVES_RECORD],- ['PATCH /api/loras/:filename', PRE_GUARD_BASELINE],+ ['PATCH /api/loras/:filename', RECORDS],['DELETE /api/loras/auth/civitai', REMOVES_RECORD],- ['POST /api/loras/auth/civitai', PRE_GUARD_BASELINE],+ ['POST /api/loras/auth/civitai', CONNECTOR_CREDENTIAL],['POST /api/loras/install', MODEL_DATA],['POST /api/loras/install/huggingface', MODEL_DATA],['POST /api/loras/install/huggingface/stream', MODEL_DATA],['POST /api/loras/install/preflight', MODEL_DATA],// /api/managed-visitor-admin['DELETE /api/managed-visitor-admin/:appId/credential', REMOVES_RECORD],- ['POST /api/managed-visitor-admin/:appId/credential', PRE_GUARD_BASELINE],- ['POST /api/managed-visitor-admin/admissions', PRE_GUARD_BASELINE],- ['POST /api/managed-visitor-admin/admissions/cancel', REDUCES_EXECUTION],- ['POST /api/managed-visitor-admin/sessions/:id/actions', PRE_GUARD_BASELINE],- ['POST /api/managed-visitor-admin/sessions/:id/leave', REDUCES_EXECUTION],- ['POST /api/managed-visitor-admin/sessions/:id/observations', PRE_GUARD_BASELINE],+ ['POST /api/managed-visitor-admin/:appId/credential', MANAGED_VISITOR_BROKER],// /api/managed-visitors/v1- ['DELETE /api/managed-visitors/v1/:appId/credential', REMOVES_RECORD],- ['POST /api/managed-visitors/v1/:appId/credential', PRE_GUARD_BASELINE],- ['POST /api/managed-visitors/v1/admissions', PRE_GUARD_BASELINE],+ ['POST /api/managed-visitors/v1/admissions', MANAGED_VISITOR_BROKER],['POST /api/managed-visitors/v1/admissions/cancel', REDUCES_EXECUTION],- ['POST /api/managed-visitors/v1/sessions/:id/actions', PRE_GUARD_BASELINE],+ ['POST /api/managed-visitors/v1/sessions/:id/actions', MANAGED_VISITOR_BROKER],['POST /api/managed-visitors/v1/sessions/:id/leave', REDUCES_EXECUTION],- ['POST /api/managed-visitors/v1/sessions/:id/observations', PRE_GUARD_BASELINE],+ ['POST /api/managed-visitors/v1/sessions/:id/observations', MANAGED_VISITOR_BROKER],// /api/meatspace- ['POST /api/meatspace/activities', PRE_GUARD_BASELINE],+ ['POST /api/meatspace/activities', RECORDS],['DELETE /api/meatspace/activities/:index', REMOVES_RECORD],- ['PUT /api/meatspace/activities/:index', PRE_GUARD_BASELINE],- ['POST /api/meatspace/alcohol/custom-drinks', PRE_GUARD_BASELINE],+ ['PUT /api/meatspace/activities/:index', RECORDS],+ ['POST /api/meatspace/alcohol/custom-drinks', RECORDS],['DELETE /api/meatspace/alcohol/custom-drinks/:index', REMOVES_RECORD],- ['PUT /api/meatspace/alcohol/custom-drinks/:index', PRE_GUARD_BASELINE],- ['POST /api/meatspace/alcohol/log', PRE_GUARD_BASELINE],+ ['PUT /api/meatspace/alcohol/custom-drinks/:index', RECORDS],+ ['POST /api/meatspace/alcohol/log', RECORDS],['DELETE /api/meatspace/alcohol/log/:date/:index', REMOVES_RECORD],- ['PUT /api/meatspace/alcohol/log/:date/:index', PRE_GUARD_BASELINE],- ['PUT /api/meatspace/birth-date', PRE_GUARD_BASELINE],- ['POST /api/meatspace/blood', PRE_GUARD_BASELINE],- ['POST /api/meatspace/blood-pressure', PRE_GUARD_BASELINE],- ['POST /api/meatspace/body', PRE_GUARD_BASELINE],- ['PUT /api/meatspace/config', PRE_GUARD_BASELINE],- ['POST /api/meatspace/epigenetic', PRE_GUARD_BASELINE],- ['POST /api/meatspace/eyes', PRE_GUARD_BASELINE],+ ['PUT /api/meatspace/alcohol/log/:date/:index', RECORDS],+ ['PUT /api/meatspace/birth-date', RECORDS],+ ['POST /api/meatspace/blood', RECORDS],+ ['POST /api/meatspace/blood-pressure', RECORDS],+ ['POST /api/meatspace/body', RECORDS],+ ['PUT /api/meatspace/config', RECORDS],+ ['POST /api/meatspace/epigenetic', RECORDS],+ ['POST /api/meatspace/eyes', RECORDS],['DELETE /api/meatspace/eyes/:id', REMOVES_RECORD],- ['PUT /api/meatspace/eyes/:id', PRE_GUARD_BASELINE],- ['POST /api/meatspace/life-events', PRE_GUARD_BASELINE],+ ['PUT /api/meatspace/eyes/:id', RECORDS],+ ['POST /api/meatspace/life-events', RECORDS],['DELETE /api/meatspace/life-events/:id', REMOVES_RECORD],- ['PUT /api/meatspace/life-events/:id', PRE_GUARD_BASELINE],- ['PUT /api/meatspace/lifestyle', PRE_GUARD_BASELINE],- ['POST /api/meatspace/nicotine/custom-products', PRE_GUARD_BASELINE],+ ['PUT /api/meatspace/life-events/:id', RECORDS],+ ['PUT /api/meatspace/lifestyle', RECORDS],+ ['POST /api/meatspace/nicotine/custom-products', RECORDS],['DELETE /api/meatspace/nicotine/custom-products/:index', REMOVES_RECORD],- ['PUT /api/meatspace/nicotine/custom-products/:index', PRE_GUARD_BASELINE],- ['POST /api/meatspace/nicotine/log', PRE_GUARD_BASELINE],+ ['PUT /api/meatspace/nicotine/custom-products/:index', RECORDS],+ ['POST /api/meatspace/nicotine/log', RECORDS],['DELETE /api/meatspace/nicotine/log/:date/:index', REMOVES_RECORD],- ['PUT /api/meatspace/nicotine/log/:date/:index', PRE_GUARD_BASELINE],- ['PUT /api/meatspace/post/config', PRE_GUARD_BASELINE],- ['POST /api/meatspace/post/memory-drill', PRE_GUARD_BASELINE],- ['POST /api/meatspace/post/memory-items', PRE_GUARD_BASELINE],+ ['PUT /api/meatspace/nicotine/log/:date/:index', RECORDS],+ ['PUT /api/meatspace/post/config', RECORDS],+ ['POST /api/meatspace/post/memory-drill', READ_OVER_POST],+ ['POST /api/meatspace/post/memory-items', RECORDS],['DELETE /api/meatspace/post/memory-items/:id', REMOVES_RECORD],- ['PUT /api/meatspace/post/memory-items/:id', PRE_GUARD_BASELINE],- ['POST /api/meatspace/post/memory-items/:id/attest-mastery', PRE_GUARD_BASELINE],- ['POST /api/meatspace/post/memory-items/:id/practice', PRE_GUARD_BASELINE],- ['PUT /api/meatspace/post/morse/level', PRE_GUARD_BASELINE],- ['POST /api/meatspace/post/morse/rounds', PRE_GUARD_BASELINE],- ['POST /api/meatspace/post/sessions', PRE_GUARD_BASELINE],- ['POST /api/meatspace/post/training', PRE_GUARD_BASELINE],- ['POST /api/meatspace/post/training/runs', PRE_GUARD_BASELINE],- ['POST /api/meatspace/workouts', PRE_GUARD_BASELINE],+ ['PUT /api/meatspace/post/memory-items/:id', RECORDS],+ ['POST /api/meatspace/post/memory-items/:id/attest-mastery', RECORDS],+ ['POST /api/meatspace/post/memory-items/:id/practice', RECORDS],+ ['PUT /api/meatspace/post/morse/level', RECORDS],+ ['POST /api/meatspace/post/morse/rounds', RECORDS],+ ['POST /api/meatspace/post/sessions', RECORDS],+ ['POST /api/meatspace/post/training', RECORDS],+ ['POST /api/meatspace/post/training/runs', RECORDS],+ ['POST /api/meatspace/workouts', RECORDS],// /api/meatspace/genome['DELETE /api/meatspace/genome', REMOVES_RECORD],['DELETE /api/meatspace/genome/clinvar', REMOVES_RECORD],- ['POST /api/meatspace/genome/clinvar/scan', PRE_GUARD_BASELINE],- ['POST /api/meatspace/genome/clinvar/sync', PRE_GUARD_BASELINE],- ['POST /api/meatspace/genome/epigenetic', PRE_GUARD_BASELINE],+ ['POST /api/meatspace/genome/clinvar/scan', READ_OVER_POST],+ ['POST /api/meatspace/genome/clinvar/sync', REFERENCE_DATASET],+ ['POST /api/meatspace/genome/epigenetic', RECORDS],['DELETE /api/meatspace/genome/epigenetic/:id', REMOVES_RECORD],- ['PUT /api/meatspace/genome/epigenetic/:id', PRE_GUARD_BASELINE],- ['POST /api/meatspace/genome/epigenetic/:id/log', PRE_GUARD_BASELINE],- ['POST /api/meatspace/genome/markers', PRE_GUARD_BASELINE],+ ['PUT /api/meatspace/genome/epigenetic/:id', RECORDS],+ ['POST /api/meatspace/genome/epigenetic/:id/log', RECORDS],+ ['POST /api/meatspace/genome/markers', RECORDS],['DELETE /api/meatspace/genome/markers/:id', REMOVES_RECORD],- ['PUT /api/meatspace/genome/markers/:id/notes', PRE_GUARD_BASELINE],- ['POST /api/meatspace/genome/scan', PRE_GUARD_BASELINE],- ['POST /api/meatspace/genome/search', PRE_GUARD_BASELINE],- ['POST /api/meatspace/genome/upload', PRE_GUARD_BASELINE],+ ['PUT /api/meatspace/genome/markers/:id/notes', RECORDS],+ ['POST /api/meatspace/genome/scan', DERIVED_REPORT],+ ['POST /api/meatspace/genome/search', READ_OVER_POST],+ ['POST /api/meatspace/genome/upload', RECORDS],// /api/media['POST /api/media/stop', REDUCES_EXECUTION],// /api/media-jobs['DELETE /api/media-jobs/:id', REMOVES_RECORD],['POST /api/media-jobs/:id/cancel', REDUCES_EXECUTION],['POST /api/media-jobs/cancel-queued', REDUCES_EXECUTION],- ['POST /api/media-jobs/holds/:holdId/resume', PRE_GUARD_BASELINE],// /api/media/annotations- ['PATCH /api/media/annotations/:key', PRE_GUARD_BASELINE],+ ['PATCH /api/media/annotations/:key', RECORDS],// /api/media/collections- ['POST /api/media/collections', PRE_GUARD_BASELINE],+ ['POST /api/media/collections', RECORDS],['DELETE /api/media/collections/:id', REMOVES_RECORD],- ['PATCH /api/media/collections/:id', PRE_GUARD_BASELINE],- ['POST /api/media/collections/:id/items', PRE_GUARD_BASELINE],+ ['PATCH /api/media/collections/:id', RECORDS],+ ['POST /api/media/collections/:id/items', RECORDS],['DELETE /api/media/collections/:id/items/:key', REMOVES_RECORD],- ['POST /api/media/collections/:id/items/bulk', PRE_GUARD_BASELINE],- ['POST /api/media/collections/:id/localize', PRE_GUARD_BASELINE],+ ['POST /api/media/collections/:id/items/bulk', RECORDS],// /api/media/sketches- ['POST /api/media/sketches', PRE_GUARD_BASELINE],- ['PUT /api/media/sketches/:key', PRE_GUARD_BASELINE],+ ['POST /api/media/sketches', RECORDS],+ ['PUT /api/media/sketches/:key', RECORDS],// /api/memory- ['POST /api/memory', PRE_GUARD_BASELINE],+ ['POST /api/memory', RECORDS],['DELETE /api/memory/:id', REMOVES_RECORD],- ['PUT /api/memory/:id', PRE_GUARD_BASELINE],- ['POST /api/memory/:id/approve', PRE_GUARD_BASELINE],- ['POST /api/memory/:id/reject', PRE_GUARD_BASELINE],- ['POST /api/memory/consolidate', PRE_GUARD_BASELINE],- ['POST /api/memory/decay', PRE_GUARD_BASELINE],+ ['PUT /api/memory/:id', RECORDS],+ ['POST /api/memory/:id/approve', RECORDS],+ ['POST /api/memory/:id/reject', RECORDS],+ ['POST /api/memory/consolidate', RECORDS],+ ['POST /api/memory/decay', RECORDS],['DELETE /api/memory/expired', REMOVES_RECORD],- ['POST /api/memory/link', PRE_GUARD_BASELINE],- ['POST /api/memory/search', PRE_GUARD_BASELINE],- ['POST /api/memory/sync', PRE_GUARD_BASELINE],+ ['POST /api/memory/link', RECORDS],+ ['POST /api/memory/search', READ_OVER_POST],+ ['POST /api/memory/sync', RECORDS],// /api/messages- ['POST /api/messages/:accountId/:messageId/refresh', PRE_GUARD_BASELINE],- ['POST /api/messages/accounts', PRE_GUARD_BASELINE],+ ['POST /api/messages/accounts', RECORDS],['DELETE /api/messages/accounts/:id', REMOVES_RECORD],- ['PUT /api/messages/accounts/:id', PRE_GUARD_BASELINE],- ['POST /api/messages/accounts/:id/cache/clear', PRE_GUARD_BASELINE],- ['POST /api/messages/debug/clear-token', PRE_GUARD_BASELINE],- ['POST /api/messages/drafts', PRE_GUARD_BASELINE],+ ['PUT /api/messages/accounts/:id', RECORDS],+ ['POST /api/messages/accounts/:id/cache/clear', REMOVES_RECORD],+ ['POST /api/messages/debug/clear-token', REMOVES_RECORD],+ ['POST /api/messages/drafts', RECORDS],['DELETE /api/messages/drafts/:id', REMOVES_RECORD],- ['PUT /api/messages/drafts/:id', PRE_GUARD_BASELINE],- ['POST /api/messages/drafts/:id/approve', PRE_GUARD_BASELINE],- ['POST /api/messages/drafts/:id/reconcile', PRE_GUARD_BASELINE],+ ['POST /api/messages/drafts/:id/reconcile', RECORDS],['POST /api/messages/drafts/generate', TOOL_FREE_INFERENCE],['POST /api/messages/evaluate', TOOL_FREE_INFERENCE],- ['POST /api/messages/fetch-full/:accountId', PRE_GUARD_BASELINE],- ['POST /api/messages/sync/:accountId', PRE_GUARD_BASELINE],['DELETE /api/messages/triage-rules/:index', REMOVES_RECORD],// /api/model-personality['DELETE /api/model-personality/history/:runId', REMOVES_RECORD],- ['PUT /api/model-personality/settings', PRE_GUARD_BASELINE],+ ['PUT /api/model-personality/settings', CONFIGURED_SELECTION],// /api/models/performance/task-benchmark- ['POST /api/models/performance/task-benchmark/discover', PRE_GUARD_BASELINE],- ['POST /api/models/performance/task-benchmark/run', PRE_GUARD_BASELINE],+ ['POST /api/models/performance/task-benchmark/discover', CONFIGURED_INFERENCE],+ ['POST /api/models/performance/task-benchmark/run', CONFIGURED_INFERENCE],// /api/mood-boards- ['POST /api/mood-boards', PRE_GUARD_BASELINE],+ ['POST /api/mood-boards', RECORDS],['DELETE /api/mood-boards/:id', REMOVES_RECORD],- ['PATCH /api/mood-boards/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/mood-boards/:id', RECORDS],['POST /api/mood-boards/:id/backfill-prompts', RECORDS],- ['POST /api/mood-boards/:id/collage', PRE_GUARD_BASELINE],- ['POST /api/mood-boards/:id/items', PRE_GUARD_BASELINE],+ ['POST /api/mood-boards/:id/items', RECORDS],['DELETE /api/mood-boards/:id/items/:itemId', REMOVES_RECORD],- ['PATCH /api/mood-boards/:id/items/:itemId', PRE_GUARD_BASELINE],- ['POST /api/mood-boards/:id/items/:itemId/extract-frames', PRE_GUARD_BASELINE],- ['POST /api/mood-boards/:id/localize-media', PRE_GUARD_BASELINE],+ ['PATCH /api/mood-boards/:id/items/:itemId', RECORDS],+ ['POST /api/mood-boards/:id/localize-media', PUBLIC_FETCH],['DELETE /api/mood-boards/:id/pinterest', REMOVES_RECORD],- ['PUT /api/mood-boards/:id/pinterest', PRE_GUARD_BASELINE],- ['POST /api/mood-boards/:id/pinterest/import', PRE_GUARD_BASELINE],- ['POST /api/mood-boards/:id/pinterest/sync', PRE_GUARD_BASELINE],- ['POST /api/mood-boards/:id/x-post', PRE_GUARD_BASELINE],+ ['PUT /api/mood-boards/:id/pinterest', RECORDS],+ ['POST /api/mood-boards/:id/pinterest/sync', PUBLIC_FETCH],+ ['POST /api/mood-boards/:id/x-post', PUBLIC_FETCH],// /api/mortalloom- ['POST /api/mortalloom/import', PRE_GUARD_BASELINE],+ ['POST /api/mortalloom/import', RECORDS],// /api/music- ['POST /api/music/code/preview', PRE_GUARD_BASELINE],- ['POST /api/music/models', PRE_GUARD_BASELINE],+ ['POST /api/music/code/preview', READ_OVER_POST],+ ['POST /api/music/models', MODEL_DATA],['DELETE /api/music/models/:engine/*id', REMOVES_RECORD],- ['POST /api/music/prompt-preview', PRE_GUARD_BASELINE],+ ['POST /api/music/prompt-preview', READ_OVER_POST],// /api/music-video- ['POST /api/music-video', PRE_GUARD_BASELINE],['DELETE /api/music-video/:id', REMOVES_RECORD],- ['PATCH /api/music-video/:id', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/analyze', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/analyze/manual', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/audio-timing/apply', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/audio-timing/preview', PRE_GUARD_BASELINE],['POST /api/music-video/:id/auto-reviews/:runId/cancel', REDUCES_EXECUTION],['POST /api/music-video/:id/auto-reviews/:runId/stop', REDUCES_EXECUTION],['POST /api/music-video/:id/autonomous/cancel', REDUCES_EXECUTION],['POST /api/music-video/:id/autonomous/stop', REDUCES_EXECUTION],- ['POST /api/music-video/:id/cast-and-sets/approve', PRE_GUARD_BASELINE],['DELETE /api/music-video/:id/cast-and-sets/feedback/:feedbackId', REMOVES_RECORD],- ['POST /api/music-video/:id/cast-and-sets/reconfirm', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/cast-and-sets/skip', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/clone', PRE_GUARD_BASELINE],+ ['POST /api/music-video/:id/cast-and-sets/reconfirm', RECORDS],+ ['POST /api/music-video/:id/clone', RECORDS],['DELETE /api/music-video/:id/composition/document', REMOVES_RECORD],- ['POST /api/music-video/:id/composition/document/accept', PRE_GUARD_BASELINE],+ ['POST /api/music-video/:id/composition/document/accept', HANDLER_GATED],['DELETE /api/music-video/:id/composition/document/candidate', REMOVES_RECORD],- ['POST /api/music-video/:id/composition/document/engine/upgrade', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/composition/document/template', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/composition/document/zip', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/dependency-repairs', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/dev-artifacts', PRE_GUARD_BASELINE],+ ['POST /api/music-video/:id/composition/document/engine/upgrade', RECORDS],+ ['POST /api/music-video/:id/composition/document/template', RECORDS],+ ['POST /api/music-video/:id/composition/document/zip', HANDLER_GATED],+ ['POST /api/music-video/:id/dev-artifacts', RECORDS],['DELETE /api/music-video/:id/dev-artifacts/:artifactId', REMOVES_RECORD],- ['POST /api/music-video/:id/dev-artifacts/:artifactId/notes', PRE_GUARD_BASELINE],- ['PATCH /api/music-video/:id/dev-artifacts/:artifactId/notes/:noteId', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/dev-artifacts/:artifactId/review', PRE_GUARD_BASELINE],+ ['POST /api/music-video/:id/dev-artifacts/:artifactId/notes', RECORDS],+ ['PATCH /api/music-video/:id/dev-artifacts/:artifactId/notes/:noteId', RECORDS],['DELETE /api/music-video/:id/excerpt/:excerptId', REMOVES_RECORD],- ['POST /api/music-video/:id/excerpt/:excerptId/notes', PRE_GUARD_BASELINE],+ ['POST /api/music-video/:id/excerpt/:excerptId/notes', RECORDS],['DELETE /api/music-video/:id/excerpt/:excerptId/notes/:noteId', REMOVES_RECORD],- ['PATCH /api/music-video/:id/excerpt/:excerptId/notes/:noteId', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/excerpt/:excerptId/revisions', PRE_GUARD_BASELINE],+ ['PATCH /api/music-video/:id/excerpt/:excerptId/notes/:noteId', RECORDS],+ ['POST /api/music-video/:id/excerpt/:excerptId/revisions', RECORDS],['DELETE /api/music-video/:id/film-looks/:lookId', REMOVES_RECORD],- ['PUT /api/music-video/:id/finished-outside', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/handoff/import', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/lyrics/import', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/lyrics/import-track', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/media-pool/add', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/media-pool/delete', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/media-pool/import', PRE_GUARD_BASELINE],- ['PATCH /api/music-video/:id/media-pool/marks', PRE_GUARD_BASELINE],- ['PUT /api/music-video/:id/production-review', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/production-review/alignment', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/production-review/approve', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/production-review/document-shots', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/production-review/feedback', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/production-review/feedback/resolve', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/production-review/import', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/production-review/lyric-anchors', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/production-review/prepare', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/production-review/proof', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/production-review/revert', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/production-review/shots', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/production-review/shots/:shotId/bind', PRE_GUARD_BASELINE],+ ['PUT /api/music-video/:id/finished-outside', RECORDS],+ ['POST /api/music-video/:id/handoff/import', RECORDS],+ ['POST /api/music-video/:id/lyrics/import', RECORDS],+ ['POST /api/music-video/:id/lyrics/import-track', RECORDS],+ ['POST /api/music-video/:id/media-pool/add', RECORDS],+ ['POST /api/music-video/:id/media-pool/delete', REMOVES_RECORD],+ ['POST /api/music-video/:id/media-pool/import', RECORDS],+ ['PATCH /api/music-video/:id/media-pool/marks', RECORDS],+ ['PUT /api/music-video/:id/production-review', RECORDS],+ ['POST /api/music-video/:id/production-review/alignment', HANDLER_GATED],+ ['POST /api/music-video/:id/production-review/approve', HANDLER_GATED],+ ['POST /api/music-video/:id/production-review/document-shots', RECORDS],+ ['POST /api/music-video/:id/production-review/feedback', RECORDS],+ ['POST /api/music-video/:id/production-review/feedback/resolve', HANDLER_GATED],+ ['POST /api/music-video/:id/production-review/import', RECORDS],+ ['POST /api/music-video/:id/production-review/lyric-anchors', RECORDS],+ ['POST /api/music-video/:id/production-review/revert', RECORDS],+ ['POST /api/music-video/:id/production-review/shots', HANDLER_GATED],+ ['POST /api/music-video/:id/production-review/shots/:shotId/bind', RECORDS],['DELETE /api/music-video/:id/production-review/stale-rows', REMOVES_RECORD],- ['POST /api/music-video/:id/production-review/text-check', PRE_GUARD_BASELINE],['POST /api/music-video/:id/production-runs/:runId/cancel', REDUCES_EXECUTION],['POST /api/music-video/:id/production-runs/:runId/stop', REDUCES_EXECUTION],- ['PATCH /api/music-video/:id/publish-kit/copy', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/publish-kit/cover-art', PRE_GUARD_BASELINE],- ['PUT /api/music-video/:id/publish-kit/cover-art/design', PRE_GUARD_BASELINE],- ['PUT /api/music-video/:id/publish-kit/thumbnail', PRE_GUARD_BASELINE],+ ['PATCH /api/music-video/:id/publish-kit/copy', RECORDS],+ ['POST /api/music-video/:id/publish-kit/cover-art', IN_PROCESS_MEDIA],+ ['PUT /api/music-video/:id/publish-kit/cover-art/design', RECORDS],+ ['PUT /api/music-video/:id/publish-kit/thumbnail', RECORDS],['DELETE /api/music-video/:id/publish-kit/youtube-thumbnail', REMOVES_RECORD],- ['POST /api/music-video/:id/publish-kit/youtube-thumbnail', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/publish-kit/youtube-thumbnail/paint', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/publish-kit/youtube-thumbnail/paint/preview', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/publish-kit/youtube-thumbnail/tests', PRE_GUARD_BASELINE],+ ['POST /api/music-video/:id/publish-kit/youtube-thumbnail', IN_PROCESS_MEDIA],+ ['POST /api/music-video/:id/publish-kit/youtube-thumbnail/paint/preview', READ_OVER_POST],+ ['POST /api/music-video/:id/publish-kit/youtube-thumbnail/tests', RECORDS],['DELETE /api/music-video/:id/publish-kit/youtube-thumbnail/tests/:filename', REMOVES_RECORD],- ['POST /api/music-video/:id/publish/:target/cross-links', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/publish/:target/prepare', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/publish/:target/preview', PRE_GUARD_BASELINE],- ['PUT /api/music-video/:id/publish/cross-links', PRE_GUARD_BASELINE],+ ['POST /api/music-video/:id/publish/:target/cross-links', HANDLER_GATED],+ ['POST /api/music-video/:id/publish/:target/prepare', HANDLER_GATED],+ ['POST /api/music-video/:id/publish/:target/preview', READ_OVER_POST],+ ['PUT /api/music-video/:id/publish/cross-links', RECORDS],['DELETE /api/music-video/:id/publish/drafts/:draftId', REMOVES_RECORD],['DELETE /api/music-video/:id/publish/posts/:target', REMOVES_RECORD],- ['PUT /api/music-video/:id/publish/posts/:target', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/render-cleanup', PRE_GUARD_BASELINE],+ ['PUT /api/music-video/:id/publish/posts/:target', RECORDS],+ ['POST /api/music-video/:id/render-cleanup', REMOVES_RECORD],['POST /api/music-video/:id/revisions/:revisionId/cancel', REDUCES_EXECUTION],- ['POST /api/music-video/:id/revisions/:revisionId/release', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/revisions/:revisionId/resume', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/scenes', PRE_GUARD_BASELINE],+ ['POST /api/music-video/:id/revisions/:revisionId/release', RECORDS],+ ['POST /api/music-video/:id/scenes', RECORDS],['DELETE /api/music-video/:id/scenes/:sceneId', REMOVES_RECORD],- ['PATCH /api/music-video/:id/scenes/:sceneId', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/scenes/:sceneId/continue-from-previous', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/scenes/:sceneId/merge-next', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/scenes/:sceneId/merge-previous', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/scenes/:sceneId/performance-repair', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/scenes/:sceneId/split', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/scenes/:sceneId/start', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/scenes/:sceneId/swap-frames', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/scenes/:sceneId/takes', PRE_GUARD_BASELINE],- ['PATCH /api/music-video/:id/scenes/:sceneId/takes/:takeId', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/scenes/:sceneId/takes/:takeId/select', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/scenes/:sceneId/takes/reject-unused', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/scenes/:sceneId/takes/use', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/scenes/reorder', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/sharing-copy', PRE_GUARD_BASELINE],+ ['PATCH /api/music-video/:id/scenes/:sceneId', RECORDS],+ ['POST /api/music-video/:id/scenes/:sceneId/merge-next', RECORDS],+ ['POST /api/music-video/:id/scenes/:sceneId/merge-previous', RECORDS],+ ['POST /api/music-video/:id/scenes/:sceneId/split', RECORDS],+ ['POST /api/music-video/:id/scenes/:sceneId/start', RECORDS],+ ['POST /api/music-video/:id/scenes/:sceneId/swap-frames', RECORDS],+ ['POST /api/music-video/:id/scenes/:sceneId/takes', RECORDS],+ ['PATCH /api/music-video/:id/scenes/:sceneId/takes/:takeId', RECORDS],+ ['POST /api/music-video/:id/scenes/:sceneId/takes/:takeId/select', RECORDS],+ ['POST /api/music-video/:id/scenes/:sceneId/takes/reject-unused', RECORDS],+ ['POST /api/music-video/:id/scenes/:sceneId/takes/use', RECORDS],+ ['POST /api/music-video/:id/scenes/reorder', RECORDS],['POST /api/music-video/:id/shots/:sceneId/render/cancel', REDUCES_EXECUTION],- ['POST /api/music-video/:id/song-revision', PRE_GUARD_BASELINE],+ ['POST /api/music-video/:id/song-revision', RECORDS],['POST /api/music-video/:id/song-revision/cancel', REDUCES_EXECUTION],- ['POST /api/music-video/:id/song-revision/select', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/song-revision/track', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/song-style/suno', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/song/prepare', PRE_GUARD_BASELINE],- ['PATCH /api/music-video/:id/treatment', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/treatment/apply', PRE_GUARD_BASELINE],- ['POST /api/music-video/:id/treatment/proofs/:proofId/review', PRE_GUARD_BASELINE],+ ['PATCH /api/music-video/:id/treatment', RECORDS],+ ['POST /api/music-video/:id/treatment/apply', RECORDS],+ ['POST /api/music-video/:id/treatment/proofs/:proofId/review', RECORDS],['DELETE /api/music-video/:id/vocal-stem', REMOVES_RECORD],- ['POST /api/music-video/:id/vocal-stem', PRE_GUARD_BASELINE],['POST /api/music-video/excerpt/:jobId/cancel', REDUCES_EXECUTION],['POST /api/music-video/lyrics/align/:jobId/cancel', REDUCES_EXECUTION],- ['POST /api/music-video/making-of/export', PRE_GUARD_BASELINE],- ['POST /api/music-video/making-of/preview', PRE_GUARD_BASELINE],+ ['POST /api/music-video/making-of/export', READ_OVER_POST],+ ['POST /api/music-video/making-of/preview', READ_OVER_POST],['POST /api/music-video/publish-kit/:jobId/cancel', REDUCES_EXECUTION],['DELETE /api/music-video/publish/artist-styles', REMOVES_RECORD],- ['PUT /api/music-video/publish/artist-styles', PRE_GUARD_BASELINE],+ ['PUT /api/music-video/publish/artist-styles', RECORDS],['DELETE /api/music-video/publish/cover-fonts/:fontId', REMOVES_RECORD],- ['PUT /api/music-video/publish/platforms', PRE_GUARD_BASELINE],+ ['PUT /api/music-video/publish/platforms', RECORDS],['POST /api/music-video/render/:jobId/cancel', REDUCES_EXECUTION],['POST /api/music-video/transcribe-midi/:jobId/cancel', REDUCES_EXECUTION],['POST /api/music-video/vocal-stem/separate/:jobId/cancel', REDUCES_EXECUTION],// /api/music-video/character-styles- ['PUT /api/music-video/character-styles/:id/reference', PRE_GUARD_BASELINE],+ ['PUT /api/music-video/character-styles/:id/reference', RECORDS],// /api/music/supercollider- ['POST /api/music/supercollider/render', PRE_GUARD_BASELINE],['POST /api/music/supercollider/renders/:jobId/cancel', REDUCES_EXECUTION],// /api/notes['DELETE /api/notes/vaults/:id', REMOVES_RECORD],@@ -961,8 +907,8 @@ const REVIEWED_OPEN_MUTATIONS = [// /api/notifications['DELETE /api/notifications', REMOVES_RECORD],['DELETE /api/notifications/:id', REMOVES_RECORD],- ['POST /api/notifications/:id/read', PRE_GUARD_BASELINE],- ['POST /api/notifications/read-all', PRE_GUARD_BASELINE],+ ['POST /api/notifications/:id/read', RECORDS],+ ['POST /api/notifications/read-all', RECORDS],// /api/palette['POST /api/palette/action/:id', HANDLER_GATED],// /api/peer-administration@@ -974,63 +920,61 @@ const REVIEWED_OPEN_MUTATIONS = [['POST /api/peer-administration/grants', HANDLER_GATED],['POST /api/peer-administration/preview', HANDLER_GATED],// /api/peer-sync- ['POST /api/peer-sync/pull-metadata', PRE_GUARD_BASELINE],- ['POST /api/peer-sync/pull-record', PRE_GUARD_BASELINE],+ ['POST /api/peer-sync/pull-metadata', PEER_SYNC],+ ['POST /api/peer-sync/pull-record', PEER_SYNC],['POST /api/peer-sync/push', PEER_SURFACE],- ['POST /api/peer-sync/subscriptions', PRE_GUARD_BASELINE],+ ['POST /api/peer-sync/subscriptions', PEER_SYNC],['DELETE /api/peer-sync/subscriptions/:id', REMOVES_RECORD],- ['POST /api/peer-sync/sync-now', PRE_GUARD_BASELINE],- ['POST /api/peer-sync/sync-record', PRE_GUARD_BASELINE],+ ['POST /api/peer-sync/sync-now', PEER_SYNC],+ ['POST /api/peer-sync/sync-record', PEER_SYNC],// /api/pipeline['DELETE /api/pipeline/audio/music-library/:filename', REMOVES_RECORD],- ['PATCH /api/pipeline/editorial/checks/:id', PRE_GUARD_BASELINE],- ['POST /api/pipeline/editorial/custom-checks', PRE_GUARD_BASELINE],+ ['PATCH /api/pipeline/editorial/checks/:id', RECORDS],['DELETE /api/pipeline/editorial/custom-checks/:id', REMOVES_RECORD],- ['PATCH /api/pipeline/editorial/custom-checks/:id', PRE_GUARD_BASELINE],- ['PATCH /api/pipeline/editorial/readiness-gate', PRE_GUARD_BASELINE],+ ['PATCH /api/pipeline/editorial/readiness-gate', RECORDS],['DELETE /api/pipeline/issues/:id', REMOVES_RECORD],- ['PATCH /api/pipeline/issues/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/pipeline/issues/:id', RECORDS],['POST /api/pipeline/issues/:id/auto-run-text/cancel', REDUCES_EXECUTION],['DELETE /api/pipeline/issues/:id/pov-rewrites/:rewriteId', REMOVES_RECORD],- ['POST /api/pipeline/issues/:id/stages/:stageId/recover', PRE_GUARD_BASELINE],- ['POST /api/pipeline/issues/:id/stages/:stageId/restore', PRE_GUARD_BASELINE],+ ['POST /api/pipeline/issues/:id/stages/:stageId/recover', RECORDS],+ ['POST /api/pipeline/issues/:id/stages/:stageId/restore', RECORDS],['POST /api/pipeline/issues/:id/stages/audio/cues/:cueIdx/render', PIPELINE_DETERMINISTIC],['POST /api/pipeline/issues/:id/stages/audio/extract-lines', PIPELINE_DETERMINISTIC],- ['PATCH /api/pipeline/issues/:id/stages/audio/lines/:lineIdx', PRE_GUARD_BASELINE],+ ['PATCH /api/pipeline/issues/:id/stages/audio/lines/:lineIdx', RECORDS],['POST /api/pipeline/issues/:id/stages/audio/lines/:lineIdx/render', PIPELINE_DETERMINISTIC],['DELETE /api/pipeline/issues/:id/stages/audio/music', REMOVES_RECORD],- ['POST /api/pipeline/issues/:id/stages/audio/music/attach', PRE_GUARD_BASELINE],+ ['POST /api/pipeline/issues/:id/stages/audio/music/attach', RECORDS],['POST /api/pipeline/issues/:id/stages/audio/music/generate', PIPELINE_DETERMINISTIC],- ['POST /api/pipeline/issues/:id/stages/audio/music/upload', PRE_GUARD_BASELINE],+ ['POST /api/pipeline/issues/:id/stages/audio/music/upload', RECORDS],['POST /api/pipeline/issues/:id/stages/comicPages/extract-pages', PIPELINE_DETERMINISTIC],- ['PATCH /api/pipeline/issues/:id/stages/comicPages/pages/:pageIndex', PRE_GUARD_BASELINE],+ ['PATCH /api/pipeline/issues/:id/stages/comicPages/pages/:pageIndex', RECORDS],['POST /api/pipeline/issues/:id/stages/storyboards/scenes/:index/video', PIPELINE_DETERMINISTIC],- ['POST /api/pipeline/series', PRE_GUARD_BASELINE],+ ['POST /api/pipeline/series', RECORDS],['DELETE /api/pipeline/series/:id', REMOVES_RECORD],- ['PATCH /api/pipeline/series/:id', PRE_GUARD_BASELINE],- ['PATCH /api/pipeline/series/:id/arc-fields/:field/lock', PRE_GUARD_BASELINE],+ ['PATCH /api/pipeline/series/:id', RECORDS],+ ['PATCH /api/pipeline/series/:id/arc-fields/:field/lock', RECORDS],['POST /api/pipeline/series/:id/arc/derive-from-manuscript/commit', PIPELINE_DETERMINISTIC],['POST /api/pipeline/series/:id/autopilot/cancel', REDUCES_EXECUTION],- ['POST /api/pipeline/series/:id/autopilot/model-outcomes', PRE_GUARD_BASELINE],+ ['POST /api/pipeline/series/:id/autopilot/model-outcomes', RECORDS],['POST /api/pipeline/series/:id/autopilot/pause', REDUCES_EXECUTION],['POST /api/pipeline/series/:id/continuity-bible/generate/cancel', REDUCES_EXECUTION],['POST /api/pipeline/series/:id/editorial/analyze/cancel', REDUCES_EXECUTION],['POST /api/pipeline/series/:id/editorial/checks/run/cancel', REDUCES_EXECUTION],['POST /api/pipeline/series/:id/editorial/panel/run/cancel', REDUCES_EXECUTION],- ['POST /api/pipeline/series/:id/issues', PRE_GUARD_BASELINE],+ ['POST /api/pipeline/series/:id/issues', RECORDS],['POST /api/pipeline/series/:id/manuscript/completeness/cancel', REDUCES_EXECUTION],['POST /api/pipeline/series/:id/manuscript/cuts/apply', PIPELINE_DETERMINISTIC],['POST /api/pipeline/series/:id/manuscript/cuts/preview', PIPELINE_DETERMINISTIC],- ['PATCH /api/pipeline/series/:id/manuscript/review/comments/:commentId', PRE_GUARD_BASELINE],- ['POST /api/pipeline/series/:id/manuscript/review/comments/:commentId/accept', PRE_GUARD_BASELINE],- ['POST /api/pipeline/series/:id/manuscript/review/comments/:commentId/undo', PRE_GUARD_BASELINE],- ['PUT /api/pipeline/series/:id/manuscript/sections/:issueId', PRE_GUARD_BASELINE],+ ['PATCH /api/pipeline/series/:id/manuscript/review/comments/:commentId', RECORDS],+ ['POST /api/pipeline/series/:id/manuscript/review/comments/:commentId/accept', RECORDS],+ ['POST /api/pipeline/series/:id/manuscript/review/comments/:commentId/undo', RECORDS],+ ['PUT /api/pipeline/series/:id/manuscript/sections/:issueId', RECORDS],['POST /api/pipeline/series/:id/reverse-outline/generate/cancel', REDUCES_EXECUTION],['POST /api/pipeline/series/:id/review/cancel', REDUCES_EXECUTION],['POST /api/pipeline/series/:id/review/fix/cancel', REDUCES_EXECUTION],- ['POST /api/pipeline/series/:id/seasons', PRE_GUARD_BASELINE],+ ['POST /api/pipeline/series/:id/seasons', RECORDS],['DELETE /api/pipeline/series/:id/seasons/:seasonId', REMOVES_RECORD],- ['PATCH /api/pipeline/series/:id/seasons/:seasonId', PRE_GUARD_BASELINE],+ ['PATCH /api/pipeline/series/:id/seasons/:seasonId', RECORDS],['POST /api/pipeline/series/:id/seasons/:seasonId/generate-beats/cancel', REDUCES_EXECUTION],['POST /api/pipeline/series/merge', PIPELINE_DETERMINISTIC],['POST /api/pipeline/series/merge/preview', PIPELINE_DETERMINISTIC],@@ -1040,42 +984,37 @@ const REVIEWED_OPEN_MUTATIONS = [['POST /api/pipeline/tts/preview', PIPELINE_DETERMINISTIC],['POST /api/pipeline/tts/synthesize', PIPELINE_DETERMINISTIC],// /api/ports- ['POST /api/ports/allocate', PRE_GUARD_BASELINE],- ['POST /api/ports/check', PRE_GUARD_BASELINE],+ ['POST /api/ports/allocate', READ_ONLY_PROBE],+ ['POST /api/ports/check', READ_ONLY_PROBE],// /api/privacy['DELETE /api/privacy/broker-cases/:id/evidence', REMOVES_RECORD],- ['POST /api/privacy/broker-cases/:id/recheck', PRE_GUARD_BASELINE],- ['POST /api/privacy/broker-cases/:id/transition', PRE_GUARD_BASELINE],- ['PUT /api/privacy/brokers/:id', PRE_GUARD_BASELINE],- ['POST /api/privacy/brokers/refresh', PRE_GUARD_BASELINE],- ['POST /api/privacy/changes', PRE_GUARD_BASELINE],+ ['POST /api/privacy/broker-cases/:id/recheck', RECORDS],+ ['POST /api/privacy/broker-cases/:id/transition', RECORDS],+ ['PUT /api/privacy/brokers/:id', RECORDS],+ ['POST /api/privacy/brokers/refresh', READ_ONLY_EXTERNAL],+ ['POST /api/privacy/changes', RECORDS],['POST /api/privacy/changes/:id/orgs/:orgId/draft-email', RECORDS],- ['POST /api/privacy/changes/:id/orgs/:orgId/removed', PRE_GUARD_BASELINE],- ['POST /api/privacy/changes/:id/orgs/:orgId/updated', PRE_GUARD_BASELINE],- ['POST /api/privacy/optout', PRE_GUARD_BASELINE],- ['PUT /api/privacy/optout/schedule', PRE_GUARD_BASELINE],- ['POST /api/privacy/optout/verify', PRE_GUARD_BASELINE],- ['POST /api/privacy/orgs', PRE_GUARD_BASELINE],+ ['POST /api/privacy/changes/:id/orgs/:orgId/removed', RECORDS],+ ['POST /api/privacy/changes/:id/orgs/:orgId/updated', RECORDS],+ ['POST /api/privacy/orgs', RECORDS],['DELETE /api/privacy/orgs/:id', REMOVES_RECORD],- ['PUT /api/privacy/orgs/:id', PRE_GUARD_BASELINE],- ['PUT /api/privacy/orgs/:id/holdings', PRE_GUARD_BASELINE],- ['POST /api/privacy/scan', PRE_GUARD_BASELINE],- ['POST /api/privacy/subjects', PRE_GUARD_BASELINE],+ ['PUT /api/privacy/orgs/:id', RECORDS],+ ['PUT /api/privacy/orgs/:id/holdings', RECORDS],+ ['POST /api/privacy/subjects', RECORDS],['DELETE /api/privacy/subjects/:id', REMOVES_RECORD],- ['PUT /api/privacy/subjects/:id', PRE_GUARD_BASELINE],- ['POST /api/privacy/subjects/:id/consents', PRE_GUARD_BASELINE],- ['POST /api/privacy/subjects/:id/consents/revoke', PRE_GUARD_BASELINE],- ['POST /api/privacy/vault', PRE_GUARD_BASELINE],+ ['PUT /api/privacy/subjects/:id', RECORDS],+ ['POST /api/privacy/subjects/:id/consents/revoke', REDUCES_EXECUTION],+ ['POST /api/privacy/vault', RECORDS],['DELETE /api/privacy/vault/:id', REMOVES_RECORD],- ['PUT /api/privacy/vault/:id', PRE_GUARD_BASELINE],- ['POST /api/privacy/vault/:id/reveal', PRE_GUARD_BASELINE],+ ['PUT /api/privacy/vault/:id', RECORDS],+ ['POST /api/privacy/vault/:id/reveal', READ_OVER_POST],// /api/prompts['DELETE /api/prompts/:stage', REMOVES_RECORD],- ['POST /api/prompts/:stage/preview', PRE_GUARD_BASELINE],- ['POST /api/prompts/reload', PRE_GUARD_BASELINE],+ ['POST /api/prompts/:stage/preview', READ_OVER_POST],+ ['POST /api/prompts/reload', READ_OVER_POST],['DELETE /api/prompts/variables/:key', REMOVES_RECORD],// /api/provider-fallbacks- ['PUT /api/provider-fallbacks', PRE_GUARD_BASELINE],+ ['PUT /api/provider-fallbacks', CONFIGURED_SELECTION],// /api/providers['DELETE /api/providers/:id', REMOVES_RECORD],['POST /api/providers/:id/derive', RECORDS],@@ -1101,23 +1040,23 @@ const REVIEWED_OPEN_MUTATIONS = [// /api/providers/comparison['POST /api/providers/comparison/import', RECORDS],// /api/rapid-reader- ['POST /api/rapid-reader/library', PRE_GUARD_BASELINE],+ ['POST /api/rapid-reader/library', RECORDS],['DELETE /api/rapid-reader/library/:id', REMOVES_RECORD],- ['POST /api/rapid-reader/library/fetch', PRE_GUARD_BASELINE],+ ['POST /api/rapid-reader/library/fetch', PUBLIC_FETCH],// /api/review['DELETE /api/review/items/:id', REMOVES_RECORD],- ['PATCH /api/review/items/:id', PRE_GUARD_BASELINE],- ['POST /api/review/items/:id/complete', PRE_GUARD_BASELINE],- ['POST /api/review/items/:id/dismiss', PRE_GUARD_BASELINE],- ['POST /api/review/items/bulk-status', PRE_GUARD_BASELINE],- ['POST /api/review/queue/delivery', PRE_GUARD_BASELINE],- ['POST /api/review/queue/triage', PRE_GUARD_BASELINE],- ['POST /api/review/todo', PRE_GUARD_BASELINE],+ ['PATCH /api/review/items/:id', RECORDS],+ ['POST /api/review/items/:id/complete', RECORDS],+ ['POST /api/review/items/:id/dismiss', RECORDS],+ ['POST /api/review/items/bulk-status', RECORDS],+ ['POST /api/review/queue/delivery', RECORDS],+ ['POST /api/review/queue/triage', RECORDS],+ ['POST /api/review/todo', RECORDS],// /api/rounds- ['POST /api/rounds', PRE_GUARD_BASELINE],+ ['POST /api/rounds', RECORDS],['DELETE /api/rounds/:id', REMOVES_RECORD],- ['PATCH /api/rounds/:id', PRE_GUARD_BASELINE],- ['POST /api/rounds/:id/refresh-template', PRE_GUARD_BASELINE],+ ['PATCH /api/rounds/:id', RECORDS],+ ['POST /api/rounds/:id/refresh-template', RECORDS],['POST /api/rounds/reference-audio/import/:jobId/cancel', REDUCES_EXECUTION],['POST /api/rounds/reference-audio/transcribe-midi/:jobId/cancel', REDUCES_EXECUTION],// /api/runs@@ -1125,60 +1064,55 @@ const REVIEWED_OPEN_MUTATIONS = [['DELETE /api/runs/:id', REMOVES_RECORD],['POST /api/runs/:id/stop', REDUCES_EXECUTION],// /api/screenshots- ['POST /api/screenshots', PRE_GUARD_BASELINE],+ ['POST /api/screenshots', RECORDS],// /api/settings['PUT /api/settings/ai-assignments/:id', HANDLER_GATED],- ['PUT /api/settings/credentials/:id', PRE_GUARD_BASELINE],- ['PUT /api/settings/features/:featureId', PRE_GUARD_BASELINE],- ['POST /api/settings/features/eidoverse/host', PRE_GUARD_BASELINE],- ['PUT /api/settings/features/groups/:groupId', PRE_GUARD_BASELINE],- ['POST /api/settings/orchestration-profiles', PRE_GUARD_BASELINE],+ ['PUT /api/settings/credentials/:id', CONNECTOR_CREDENTIAL],+ ['PUT /api/settings/features/:featureId', FEATURE_TOGGLE],+ ['POST /api/settings/features/eidoverse/host', LOCAL_BRIDGE],+ ['PUT /api/settings/features/groups/:groupId', FEATURE_TOGGLE],+ ['POST /api/settings/orchestration-profiles', RECORDS],['DELETE /api/settings/orchestration-profiles/:id', REMOVES_RECORD],- ['PUT /api/settings/orchestration-profiles/:id', PRE_GUARD_BASELINE],+ ['PUT /api/settings/orchestration-profiles/:id', RECORDS],// /api/sharing['DELETE /api/sharing/buckets/:id', REMOVES_RECORD],- ['PUT /api/sharing/buckets/:id', PRE_GUARD_BASELINE],- ['POST /api/sharing/buckets/:id/export', PRE_GUARD_BASELINE],- ['POST /api/sharing/buckets/:id/inbox/:manifestId/dismiss', PRE_GUARD_BASELINE],- ['POST /api/sharing/buckets/:id/inbox/:manifestId/promote', PRE_GUARD_BASELINE],- ['POST /api/sharing/subscriptions', PRE_GUARD_BASELINE],+ ['PUT /api/sharing/buckets/:id', RECORDS],+ ['POST /api/sharing/buckets/:id/export', RECORDS],+ ['POST /api/sharing/buckets/:id/inbox/:manifestId/dismiss', REMOVES_RECORD],+ ['POST /api/sharing/buckets/:id/inbox/:manifestId/promote', RECORDS],+ ['POST /api/sharing/subscriptions', RECORDS],['DELETE /api/sharing/subscriptions/:id', REMOVES_RECORD],- // /api/signal- ['POST /api/signal/sync', PRE_GUARD_BASELINE],// /api/spotify- ['POST /api/spotify/auth/clear', PRE_GUARD_BASELINE],- ['POST /api/spotify/auth/credentials', PRE_GUARD_BASELINE],- ['POST /api/spotify/playlists/sync', PRE_GUARD_BASELINE],- ['POST /api/spotify/sync', PRE_GUARD_BASELINE],+ ['POST /api/spotify/auth/clear', REMOVES_RECORD],+ ['POST /api/spotify/auth/credentials', RECORDS],+ ['POST /api/spotify/playlists/sync', EXTERNAL_SYNC],+ ['POST /api/spotify/sync', EXTERNAL_SYNC],// /api/sprites- ['POST /api/sprites', PRE_GUARD_BASELINE],+ ['POST /api/sprites', RECORDS],['DELETE /api/sprites/:id', REMOVES_RECORD],- ['PATCH /api/sprites/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/sprites/:id', RECORDS],['DELETE /api/sprites/:id/assets', REMOVES_RECORD],- ['POST /api/sprites/:id/atlas/compile', PRE_GUARD_BASELINE],- ['POST /api/sprites/:id/reference/lock', PRE_GUARD_BASELINE],- ['POST /api/sprites/:id/reference/main/unlock', PRE_GUARD_BASELINE],- ['POST /api/sprites/:id/reference/turnaround/unlock', PRE_GUARD_BASELINE],- ['POST /api/sprites/:id/reference/unlock', PRE_GUARD_BASELINE],- ['POST /api/sprites/:id/tracks/:trackId/approve', PRE_GUARD_BASELINE],- ['POST /api/sprites/:id/tracks/:trackId/reopen', PRE_GUARD_BASELINE],- ['POST /api/sprites/:id/walk/approve', PRE_GUARD_BASELINE],- ['POST /api/sprites/:id/walk/postprocess', PRE_GUARD_BASELINE],- ['POST /api/sprites/:id/walk/reopen', PRE_GUARD_BASELINE],- ['POST /api/sprites/:id/walk/runs/:runId/source-frames/extract', PRE_GUARD_BASELINE],- ['PUT /api/sprites/:id/walk/target', PRE_GUARD_BASELINE],- ['POST /api/sprites/:id/walk/trim', PRE_GUARD_BASELINE],- ['POST /api/sprites/:id/walk/unlock', PRE_GUARD_BASELINE],- ['POST /api/sprites/animation-tracks', PRE_GUARD_BASELINE],+ ['POST /api/sprites/:id/atlas/compile', IN_PROCESS_MEDIA],+ ['POST /api/sprites/:id/reference/lock', IN_PROCESS_MEDIA],+ ['POST /api/sprites/:id/reference/main/unlock', RECORDS],+ ['POST /api/sprites/:id/reference/turnaround/unlock', RECORDS],+ ['POST /api/sprites/:id/reference/unlock', RECORDS],+ ['POST /api/sprites/:id/tracks/:trackId/approve', RECORDS],+ ['POST /api/sprites/:id/tracks/:trackId/reopen', RECORDS],+ ['POST /api/sprites/:id/walk/approve', RECORDS],+ ['POST /api/sprites/:id/walk/reopen', RECORDS],+ ['PUT /api/sprites/:id/walk/target', RECORDS],+ ['POST /api/sprites/:id/walk/unlock', RECORDS],+ ['POST /api/sprites/animation-tracks', RECORDS],['DELETE /api/sprites/animation-tracks/:trackId', REMOVES_RECORD],- ['PUT /api/sprites/animation-tracks/:trackId', PRE_GUARD_BASELINE],+ ['PUT /api/sprites/animation-tracks/:trackId', RECORDS],// /api/stacker-news['POST /api/stacker-news/accounts', HANDLER_GATED],['DELETE /api/stacker-news/accounts/:id', REMOVES_RECORD],['PATCH /api/stacker-news/accounts/:id', HANDLER_GATED],- ['POST /api/stacker-news/actions', PRE_GUARD_BASELINE],- ['POST /api/stacker-news/analyses/:id/feedback', PRE_GUARD_BASELINE],- ['POST /api/stacker-news/items', PRE_GUARD_BASELINE],+ ['POST /api/stacker-news/actions', RECORDS],+ ['POST /api/stacker-news/analyses/:id/feedback', RECORDS],+ ['POST /api/stacker-news/items', RECORDS],['POST /api/stacker-news/items/:id/analyze', TOOL_FREE_INFERENCE],['POST /api/stacker-news/territories', HANDLER_GATED],['DELETE /api/stacker-news/territories/:id', REMOVES_RECORD],@@ -1186,15 +1120,15 @@ const REVIEWED_OPEN_MUTATIONS = [// /api/standardize['POST /api/standardize/analyze', READ_ONLY_EXTERNAL],// /api/story-builder- ['POST /api/story-builder', PRE_GUARD_BASELINE],+ ['POST /api/story-builder', RECORDS],['DELETE /api/story-builder/:id', REMOVES_RECORD],- ['PATCH /api/story-builder/:id', PRE_GUARD_BASELINE],- ['POST /api/story-builder/:id/current-step/:stepId', PRE_GUARD_BASELINE],- ['POST /api/story-builder/:id/issues/:issueId/lock', PRE_GUARD_BASELINE],- ['POST /api/story-builder/:id/reconcile', PRE_GUARD_BASELINE],- ['POST /api/story-builder/:id/steps/:stepId/lock', PRE_GUARD_BASELINE],- ['POST /api/story-builder/:id/steps/:stepId/unlock', PRE_GUARD_BASELINE],- ['POST /api/story-builder/:id/sync', PRE_GUARD_BASELINE],+ ['PATCH /api/story-builder/:id', RECORDS],+ ['POST /api/story-builder/:id/current-step/:stepId', RECORDS],+ ['POST /api/story-builder/:id/issues/:issueId/lock', RECORDS],+ ['POST /api/story-builder/:id/reconcile', RECORDS],+ ['POST /api/story-builder/:id/steps/:stepId/lock', RECORDS],+ ['POST /api/story-builder/:id/steps/:stepId/unlock', RECORDS],+ ['POST /api/story-builder/:id/sync', RECORDS],// /api/storyboards['POST /api/storyboards', RECORDS],['DELETE /api/storyboards/:id', REMOVES_RECORD],@@ -1218,177 +1152,163 @@ const REVIEWED_OPEN_MUTATIONS = [['POST /api/storyboards/recipes', RECORDS],['DELETE /api/storyboards/recipes/:recipeId', REMOVES_RECORD],// /api/sync- ['POST /api/sync/:category/apply', PRE_GUARD_BASELINE],- ['POST /api/sync/tombstones/sweep', PRE_GUARD_BASELINE],+ ['POST /api/sync/tombstones/sweep', REMOVES_RECORD],// /api/system- ['PUT /api/system/health/thresholds', PRE_GUARD_BASELINE],+ ['PUT /api/system/health/thresholds', RECORDS],['DELETE /api/system/health/warnings/:type/dismiss', REMOVES_RECORD],- ['POST /api/system/health/warnings/:type/dismiss', PRE_GUARD_BASELINE],+ ['POST /api/system/health/warnings/:type/dismiss', RECORDS],// /api/system-resources- ['POST /api/system-resources/duplicates/rectify', PRE_GUARD_BASELINE],- ['POST /api/system-resources/report', PRE_GUARD_BASELINE],+ ['POST /api/system-resources/duplicates/rectify', MODEL_DATA],+ ['POST /api/system-resources/report', READ_ONLY_PROBE],// /api/threejs-models['DELETE /api/threejs-models/:id', REMOVES_RECORD],// /api/timeline- ['POST /api/timeline/import/browser', PRE_GUARD_BASELINE],- ['POST /api/timeline/import/discord', PRE_GUARD_BASELINE],- ['POST /api/timeline/import/spotify', PRE_GUARD_BASELINE],- ['POST /api/timeline/import/takeout-location', PRE_GUARD_BASELINE],- ['POST /api/timeline/import/whatsapp', PRE_GUARD_BASELINE],- ['POST /api/timeline/import/youtube', PRE_GUARD_BASELINE],+ ['POST /api/timeline/import/browser', RECORDS],+ ['POST /api/timeline/import/discord', RECORDS],+ ['POST /api/timeline/import/spotify', RECORDS],+ ['POST /api/timeline/import/takeout-location', RECORDS],+ ['POST /api/timeline/import/whatsapp', RECORDS],+ ['POST /api/timeline/import/youtube', RECORDS],// /api/tools['DELETE /api/tools/:id', REMOVES_RECORD],// /api/tracks- ['POST /api/tracks', PRE_GUARD_BASELINE],+ ['POST /api/tracks', RECORDS],['DELETE /api/tracks/:id', REMOVES_RECORD],- ['PATCH /api/tracks/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/tracks/:id', RECORDS],['DELETE /api/tracks/:id/audio', REMOVES_RECORD],- ['POST /api/tracks/:id/audio/attach', PRE_GUARD_BASELINE],- ['POST /api/tracks/:id/audio/upload', PRE_GUARD_BASELINE],- ['POST /api/tracks/:id/chiptune/render', PRE_GUARD_BASELINE],- ['POST /api/tracks/:id/code/render', PRE_GUARD_BASELINE],+ ['POST /api/tracks/:id/audio/attach', RECORDS],+ ['POST /api/tracks/:id/chiptune/render', FIXED_ENCODE],['DELETE /api/tracks/:id/renders/:renderId', REMOVES_RECORD],- ['POST /api/tracks/:id/renders/:renderId/select', PRE_GUARD_BASELINE],- ['POST /api/tracks/:id/supercollider/take', PRE_GUARD_BASELINE],- ['POST /api/tracks/:id/waveform/render', PRE_GUARD_BASELINE],+ ['POST /api/tracks/:id/renders/:renderId/select', RECORDS],+ ['POST /api/tracks/:id/waveform/render', FIXED_ENCODE],['POST /api/tracks/import/:jobId/cancel', REDUCES_EXECUTION],- ['POST /api/tracks/import/suno', PRE_GUARD_BASELINE],// /api/tribe['DELETE /api/tribe/beeper/identities/:identityId', REMOVES_RECORD],['DELETE /api/tribe/beeper/link', REMOVES_RECORD],- ['POST /api/tribe/beeper/link', PRE_GUARD_BASELINE],- ['POST /api/tribe/beeper/link-new', PRE_GUARD_BASELINE],+ ['POST /api/tribe/beeper/link', RECORDS],+ ['POST /api/tribe/beeper/link-new', RECORDS],['POST /api/tribe/outreach/draft', TOOL_FREE_INFERENCE],- ['POST /api/tribe/people', PRE_GUARD_BASELINE],+ ['POST /api/tribe/people', RECORDS],['DELETE /api/tribe/people/:id', REMOVES_RECORD],- ['PUT /api/tribe/people/:id', PRE_GUARD_BASELINE],- ['POST /api/tribe/people/:id/memories', PRE_GUARD_BASELINE],+ ['PUT /api/tribe/people/:id', RECORDS],+ ['POST /api/tribe/people/:id/memories', RECORDS],['DELETE /api/tribe/people/:id/memories/:memoryId', REMOVES_RECORD],- ['POST /api/tribe/people/:id/touchpoints', PRE_GUARD_BASELINE],- ['POST /api/tribe/people/:id/touchpoints/calendar', PRE_GUARD_BASELINE],+ ['POST /api/tribe/people/:id/touchpoints', RECORDS],+ ['POST /api/tribe/people/:id/touchpoints/calendar', RECORDS],// /api/universe-builder- ['POST /api/universe-builder', PRE_GUARD_BASELINE],+ ['POST /api/universe-builder', RECORDS],['DELETE /api/universe-builder/:id', REMOVES_RECORD],- ['PATCH /api/universe-builder/:id', PRE_GUARD_BASELINE],- ['POST /api/universe-builder/:id/adopt-style', PRE_GUARD_BASELINE],+ ['PATCH /api/universe-builder/:id', RECORDS],+ ['POST /api/universe-builder/:id/adopt-style', RECORDS],['DELETE /api/universe-builder/:id/canon/:kind/:entryId', REMOVES_RECORD],- ['POST /api/universe-builder/:id/canon/:kind/:entryId/apply-image-correction', PRE_GUARD_BASELINE],- ['PATCH /api/universe-builder/:id/canon/:kind/:entryId/lock', PRE_GUARD_BASELINE],- ['PATCH /api/universe-builder/:id/canon/:kind/lock-all', PRE_GUARD_BASELINE],- ['POST /api/universe-builder/:id/canon/backfill-descriptions', PRE_GUARD_BASELINE],- ['POST /api/universe-builder/:id/characters/:entryId/augment/apply', PRE_GUARD_BASELINE],+ ['POST /api/universe-builder/:id/canon/:kind/:entryId/apply-image-correction', RECORDS],+ ['PATCH /api/universe-builder/:id/canon/:kind/:entryId/lock', RECORDS],+ ['PATCH /api/universe-builder/:id/canon/:kind/lock-all', RECORDS],+ ['POST /api/universe-builder/:id/canon/backfill-descriptions', RECORDS],+ ['POST /api/universe-builder/:id/characters/:entryId/augment/apply', RECORDS],['DELETE /api/universe-builder/:id/characters/:entryId/reference-sheet', REMOVES_RECORD],- ['POST /api/universe-builder/:id/import/markdown', PRE_GUARD_BASELINE],- ['POST /api/universe-builder/:id/style-references', PRE_GUARD_BASELINE],+ ['POST /api/universe-builder/:id/import/markdown', RECORDS],+ ['POST /api/universe-builder/:id/style-references', RECORDS],['DELETE /api/universe-builder/:id/style-references/:referenceId', REMOVES_RECORD],- ['PATCH /api/universe-builder/:id/variations/lock-all', PRE_GUARD_BASELINE],- ['POST /api/universe-builder/merge', PRE_GUARD_BASELINE],- ['POST /api/universe-builder/merge/preview', PRE_GUARD_BASELINE],+ ['PATCH /api/universe-builder/:id/variations/lock-all', RECORDS],+ ['POST /api/universe-builder/merge', RECORDS],+ ['POST /api/universe-builder/merge/preview', READ_OVER_POST],// /api/update- ['POST /api/update/check', PRE_GUARD_BASELINE],+ ['POST /api/update/check', READ_ONLY_EXTERNAL],['DELETE /api/update/ignore', REMOVES_RECORD],- ['POST /api/update/ignore', PRE_GUARD_BASELINE],+ ['POST /api/update/ignore', RECORDS],// /api/uploads['DELETE /api/uploads', REMOVES_RECORD],- ['POST /api/uploads', PRE_GUARD_BASELINE],+ ['POST /api/uploads', RECORDS],['DELETE /api/uploads/:filename', REMOVES_RECORD],// /api/usage['DELETE /api/usage', REMOVES_RECORD],- ['POST /api/usage/backfill', PRE_GUARD_BASELINE],- ['PUT /api/usage/fleet-billing', PRE_GUARD_BASELINE],- ['POST /api/usage/messages', PRE_GUARD_BASELINE],- ['POST /api/usage/session', PRE_GUARD_BASELINE],- ['PUT /api/usage/subscriptions', PRE_GUARD_BASELINE],- ['PUT /api/usage/subscriptions/enabled', PRE_GUARD_BASELINE],- ['POST /api/usage/tokens', PRE_GUARD_BASELINE],+ ['POST /api/usage/backfill', IN_PROCESS_COMPUTE],+ ['PUT /api/usage/fleet-billing', RECORDS],+ ['POST /api/usage/messages', CLIENT_TELEMETRY],+ ['POST /api/usage/session', CLIENT_TELEMETRY],+ ['PUT /api/usage/subscriptions', RECORDS],+ ['POST /api/usage/tokens', CLIENT_TELEMETRY],// /api/video-gen['POST /api/video-gen/cancel', REDUCES_EXECUTION],['DELETE /api/video-gen/history/:id', REMOVES_RECORD],- ['PATCH /api/video-gen/history/:id/poster', PRE_GUARD_BASELINE],- ['PATCH /api/video-gen/history/:id/prompt', PRE_GUARD_BASELINE],- ['POST /api/video-gen/history/:id/visibility', PRE_GUARD_BASELINE],+ ['PATCH /api/video-gen/history/:id/prompt', RECORDS],+ ['POST /api/video-gen/history/:id/visibility', RECORDS],['POST /api/video-gen/ic-loras/:mode/download', MODEL_DATA],['POST /api/video-gen/ic-loras/:mode/repair', MODEL_DATA],- ['POST /api/video-gen/model-terms', PRE_GUARD_BASELINE],+ ['POST /api/video-gen/model-terms', RECORDS],['POST /api/video-gen/models/:modelId/download', MODEL_DATA],['POST /api/video-gen/models/:modelId/repair', MODEL_DATA],['POST /api/video-gen/models/verify', MODEL_DATA],- ['POST /api/video-gen/prompt-preview', PRE_GUARD_BASELINE],+ ['POST /api/video-gen/prompt-preview', READ_OVER_POST],['POST /api/video-gen/text-encoder/download', MODEL_DATA],['POST /api/video-gen/text-encoder/repair', MODEL_DATA],['POST /api/video-gen/text-encoders/:id/download', MODEL_DATA],['POST /api/video-gen/text-encoders/:id/repair', MODEL_DATA],- ['POST /api/video-gen/upload', PRE_GUARD_BASELINE],// /api/video-timeline['POST /api/video-timeline/:jobId/cancel', REDUCES_EXECUTION],- ['POST /api/video-timeline/projects', PRE_GUARD_BASELINE],+ ['POST /api/video-timeline/projects', RECORDS],['DELETE /api/video-timeline/projects/:id', REMOVES_RECORD],- ['PATCH /api/video-timeline/projects/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/video-timeline/projects/:id', RECORDS],// /api/voice- ['PUT /api/voice/config', PRE_GUARD_BASELINE],- ['POST /api/voice/piper/fetch', MODEL_DATA],- ['POST /api/voice/profiles/:id/assign', PRE_GUARD_BASELINE],- ['POST /api/voice/profiles/:id/benchmark', PRE_GUARD_BASELINE],- ['POST /api/voice/profiles/:id/benchmark-interactive', PRE_GUARD_BASELINE],- ['POST /api/voice/profiles/:id/benchmark-interactive/complete', PRE_GUARD_BASELINE],+ ['PUT /api/voice/config', HANDLER_GATED],+ ['POST /api/voice/profiles/:id/assign', RECORDS],+ ['POST /api/voice/profiles/:id/benchmark', LOCAL_TTS],+ ['POST /api/voice/profiles/:id/benchmark-interactive', LOCAL_TTS],+ ['POST /api/voice/profiles/:id/benchmark-interactive/complete', RECORDS],['POST /api/voice/profiles/:id/fine-tune/:jobId/cancel', REDUCES_EXECUTION],- ['POST /api/voice/profiles/:id/fine-tune/:jobId/promote', PRE_GUARD_BASELINE],- ['POST /api/voice/profiles/:id/promote', PRE_GUARD_BASELINE],- ['POST /api/voice/profiles/clone', PRE_GUARD_BASELINE],- ['POST /api/voice/profiles/design', PRE_GUARD_BASELINE],- ['POST /api/voice/profiles/preset', PRE_GUARD_BASELINE],+ ['POST /api/voice/profiles/:id/fine-tune/:jobId/promote', RECORDS],+ ['POST /api/voice/profiles/:id/promote', RECORDS],+ ['POST /api/voice/profiles/clone', RECORDS],+ ['POST /api/voice/profiles/design', RECORDS],+ ['POST /api/voice/profiles/preset', RECORDS],['POST /api/voice/qwen3/download-model', MODEL_DATA],- ['POST /api/voice/speak', PRE_GUARD_BASELINE],- ['POST /api/voice/studio/design', PRE_GUARD_BASELINE],+ ['POST /api/voice/speak', LOCAL_TTS],+ ['POST /api/voice/studio/design', LOCAL_TTS],['POST /api/voice/studio/unload', REDUCES_EXECUTION],- ['POST /api/voice/test', PRE_GUARD_BASELINE],+ ['POST /api/voice/test', LOCAL_TTS],['POST /api/voice/tts/unload', REDUCES_EXECUTION],- ['POST /api/voice/whisper', PRE_GUARD_BASELINE],// /api/voice/public- ['POST /api/voice/public/synthesize', PRE_GUARD_BASELINE],+ ['POST /api/voice/public/synthesize', EXPOSED_API],// /api/workspace-contexts['DELETE /api/workspace-contexts/:appId', REMOVES_RECORD],- ['POST /api/workspace-contexts/:appId/restore', PRE_GUARD_BASELINE],- ['POST /api/workspace-contexts/:appId/save', PRE_GUARD_BASELINE],+ ['POST /api/workspace-contexts/:appId/restore', READ_OVER_POST],+ ['POST /api/workspace-contexts/:appId/save', RECORDS],// /api/writers-room- ['POST /api/writers-room/exercises', PRE_GUARD_BASELINE],- ['POST /api/writers-room/exercises/:id/discard', PRE_GUARD_BASELINE],- ['POST /api/writers-room/exercises/:id/finish', PRE_GUARD_BASELINE],- ['POST /api/writers-room/exercises/:id/promote', PRE_GUARD_BASELINE],- ['POST /api/writers-room/folders', PRE_GUARD_BASELINE],+ ['POST /api/writers-room/exercises', RECORDS],+ ['POST /api/writers-room/exercises/:id/discard', RECORDS],+ ['POST /api/writers-room/exercises/:id/finish', RECORDS],+ ['POST /api/writers-room/exercises/:id/promote', RECORDS],+ ['POST /api/writers-room/folders', RECORDS],['DELETE /api/writers-room/folders/:id', REMOVES_RECORD],- ['POST /api/writers-room/works', PRE_GUARD_BASELINE],+ ['POST /api/writers-room/works', RECORDS],['DELETE /api/writers-room/works/:id', REMOVES_RECORD],- ['PATCH /api/writers-room/works/:id', PRE_GUARD_BASELINE],+ ['PATCH /api/writers-room/works/:id', RECORDS],['POST /api/writers-room/works/:id/analysis/:analysisId/scene-image', RECORDS],- ['POST /api/writers-room/works/:id/cd-bridge/send', PRE_GUARD_BASELINE],- ['POST /api/writers-room/works/:id/characters', PRE_GUARD_BASELINE],+ ['POST /api/writers-room/works/:id/characters', RECORDS],['DELETE /api/writers-room/works/:id/characters/:characterId', REMOVES_RECORD],- ['PATCH /api/writers-room/works/:id/characters/:characterId', PRE_GUARD_BASELINE],- ['POST /api/writers-room/works/:id/characters/:characterId/augment/apply', PRE_GUARD_BASELINE],- ['PUT /api/writers-room/works/:id/draft', PRE_GUARD_BASELINE],- ['POST /api/writers-room/works/:id/live-render-preview', PRE_GUARD_BASELINE],- ['POST /api/writers-room/works/:id/objects', PRE_GUARD_BASELINE],+ ['PATCH /api/writers-room/works/:id/characters/:characterId', RECORDS],+ ['POST /api/writers-room/works/:id/characters/:characterId/augment/apply', RECORDS],+ ['PUT /api/writers-room/works/:id/draft', RECORDS],+ ['POST /api/writers-room/works/:id/live-render-preview', RECORDS],+ ['POST /api/writers-room/works/:id/objects', RECORDS],['DELETE /api/writers-room/works/:id/objects/:objectId', REMOVES_RECORD],- ['PATCH /api/writers-room/works/:id/objects/:objectId', PRE_GUARD_BASELINE],- ['POST /api/writers-room/works/:id/places', PRE_GUARD_BASELINE],+ ['PATCH /api/writers-room/works/:id/objects/:objectId', RECORDS],+ ['POST /api/writers-room/works/:id/places', RECORDS],['DELETE /api/writers-room/works/:id/places/:placeId', REMOVES_RECORD],- ['PATCH /api/writers-room/works/:id/places/:placeId', PRE_GUARD_BASELINE],+ ['PATCH /api/writers-room/works/:id/places/:placeId', RECORDS],['POST /api/writers-room/works/:id/polish/cancel', REDUCES_EXECUTION],- ['POST /api/writers-room/works/:id/polish/revert', PRE_GUARD_BASELINE],- ['POST /api/writers-room/works/:id/promote-to-pipeline', PRE_GUARD_BASELINE],- ['POST /api/writers-room/works/:id/versions', PRE_GUARD_BASELINE],- ['PATCH /api/writers-room/works/:id/versions/:draftId', PRE_GUARD_BASELINE],+ ['POST /api/writers-room/works/:id/polish/revert', RECORDS],+ ['POST /api/writers-room/works/:id/promote-to-pipeline', RECORDS],+ ['POST /api/writers-room/works/:id/versions', RECORDS],+ ['PATCH /api/writers-room/works/:id/versions/:draftId', RECORDS],// /api/x- ['POST /api/x/accounts', PRE_GUARD_BASELINE],+ ['POST /api/x/accounts', RECORDS],['DELETE /api/x/accounts/:id', REMOVES_RECORD],- ['PATCH /api/x/accounts/:id', PRE_GUARD_BASELINE],- ['POST /api/x/drafts', PRE_GUARD_BASELINE],- // /api/youtube- ['POST /api/youtube/playlists/sync', PRE_GUARD_BASELINE],- ['POST /api/youtube/sync', PRE_GUARD_BASELINE],+ ['PATCH /api/x/accounts/:id', RECORDS],+ ['POST /api/x/drafts', RECORDS],// /sdapi/v1- ['POST /sdapi/v1/options', PRE_GUARD_BASELINE],+ ['POST /sdapi/v1/options', READ_OVER_POST],['POST /sdapi/v1/txt2img', HANDLER_GATED],];diff --git a/server/index.js b/server/index.jsindex 0a19cbc6c6..8fccaa84f2 100644--- a/server/index.js+++ b/server/index.js@@ -101,7 +101,8 @@ import backupRoutes from './routes/backup.js';import legacyExportRoutes from './routes/legacyExport.js';import eidoverseWorldRoutes from './routes/eidoverseWorldRoutes.js';import eidoverseTravelRoutes from './routes/eidoverseTravelRoutes.js';-import { createManagedVisitorRoutes, createManagedVisitorAdminRoutes } from './routes/managedVisitors.js';+import { createManagedVisitorRoutes } from './routes/managedVisitors.js';+import { createManagedVisitorAdminRoutes } from './routes/managedVisitorAdmin.js';import databaseRoutes from './routes/database.js';import localLlmRoutes from './routes/localLlm.js';import codeReviewRoutes from './routes/codeReview.js';diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex 65dcba0cb3..83262d1a7e 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -87,10 +87,27 @@* song-revision generation (signed-in browser) and Eidoverse augment/say* (acting as the CoS world identity) are gated whole. SynthID regenerate is* gated unless `method` is `light`, and the code-animation prompt only when- * it names a `referenceVideo`. Left open: image clean and watermark- * removal (in-process sharp), and the Messages, Tribe outreach,+ * it names a `referenceVideo`. Left open: gallery image clean and+ * watermark removal (in-process sharp), and the Messages, Tribe outreach,* autobiography, identity-goal and insights AI routes, whose transports* are tool-free (an HTTP chat completion or the sandboxed Codex text turn).+ * The remainder of the audit gated the routes listed under "Pre-guard+ * audit, remainder" below: ffmpeg/ffprobe over caller-supplied, uploaded,+ * gallery or peer-pulled media, the headless composition browser, local+ * Python/Docker/PM2 work, host data and secrets, the operator's signed-in+ * browser, external account writes, agent and LLM work, resets that put+ * held agent work back in rotation, and Eidoverse identity and controller+ * configuration. Per request: the standalone image clean in GPU mode (the+ * handler checks its query), Brain settings that arm or retarget the+ * scheduled digest (the handler compares the stored value), Music Video+ * document import and accept (the handler starts the browser overlay check+ * only with host control), voice config (the runtime reconcile likewise),+ * and the body splits in COMPILED_BODY_ROUTES. Left open with a specific+ * reason in REVIEWED_OPEN_MUTATIONS (server/hostControlCoverage.test.js):+ * fixed read-only probes (`ps`, `du`, `lsof`), the chiptune and waveform+ * renders (a fixed ffmpeg encode of audio PortOS synthesized), TTS+ * synthesis on an installed runtime (configured inference), and selection+ * among already-configured providers that arms nothing.* - Importer, Brain and analytics AI (#11036): classify/analyze/retry-issues,* model-personality run, goal-scorecard narrative, Brain capture (it can* dispatch classification or repository intake), inbox retry, digest/review@@ -158,7 +175,9 @@* require operator authority. Head training reads git/forge history;* adoption/discard changes the classifier admitting agent work.* - settings: other feature toggles and the Eidoverse host bridge (they arm- * PortOS's own integrations or open a listener), orchestration profiles,+ * PortOS's own integrations or open a listener; the eidoverse and+ * docker-containment toggles launch or tear down host executables and are+ * gated by path), orchestration profiles,* AI assignments and credentials (they choose among configured providers* or store a key). The `PUT /api/settings` and `PUT /api/cos/config`* slices that change execution policy are gated per request body — see@@ -188,9 +207,12 @@* `llm.tools.enabled` and `llm.codeAgent` are the voice agent's* instructions or the switch that arms its coding-agent tool, and* `stt.endpoint` receives microphone audio and returns the transcript- * the agent acts on. `PUT /api/voice/config` is gated only when one of those values would- * change (`HOST_CONTROL_VOICE_CONFIG_PATHS`); a whole-config resend and- * every other voice setting stay open on that dedicated endpoint.+ * the agent acts on. `enabled`, the STT/TTS engines, Core ML and the+ * host model/voice paths are what the runtime reconcile starts, installs or+ * reads (#13055). `PUT /api/voice/config` is gated only when one of those+ * values would change (`HOST_CONTROL_VOICE_CONFIG_PATHS`), and it runs the+ * reconcile (PM2, setup script) only for a caller with host control; a+ * whole-config resend and every other voice setting stay open.* Generic settings replaces the entire voice root, so even an empty* replacement can reset protected policy and requires operator authority.*@@ -713,7 +735,8 @@ export const HOST_CONTROL_ROUTES = Object.freeze([// provider that may fall back to a CLI/TUI, or enqueue an agent-backed image// job; chiptune publication writes into a managed app repo (#10893). Gate the// whole operation, API-first variants included. Deck/track CRUD, progress- // reads and the deterministic chiptune library render stay open.+ // reads and the deterministic chiptune library render stay open (its fixed+ // ffmpeg encode only reads audio PortOS synthesized, #13055).'POST /api/decks/:id/analyze-sample','POST /api/decks/:id/generate-prompts','POST /api/decks/:id/render',@@ -972,8 +995,9 @@ export const HOST_CONTROL_ROUTES = Object.freeze([// FableLoom authoring and production (#10668) can dispatch CLI/TUI agents,// including API-first fallback and deferred batch resume. Authorize before// service reads/writes, run creation or queues. Deterministic CRUD, validation,- // shot application, continuity/production planning, cancellation and contained- // fal.ai browser automation remain open under their existing contracts.+ // shot application, continuity/production planning and cancellation remain+ // open under their existing contracts. fal.ai scene video drives the signed-in+ // browser and is gated with the pre-guard audit remainder (#13055).'POST /api/fableloom/:id/plan/generate','POST /api/fableloom/:id/plan/review','POST /api/fableloom/:id/plan/feedback',@@ -1140,6 +1164,130 @@ export const HOST_CONTROL_ROUTES = Object.freeze(['POST /api/cos/mind/start','POST /api/cos/mind/wake','POST /api/cos/mind/resume',++ // Pre-guard audit, remainder (#13055): routes that were open when the+ // coverage guard landed and turned out to run host work when traced.+ //+ // ffmpeg/ffprobe over caller-supplied, uploaded, gallery or peer-pulled+ // media (the parser surface), like video last-frame and upscale/stitch.+ 'POST /api/music-video/:id/analyze',+ 'POST /api/music-video/:id/analyze/manual',+ 'POST /api/music-video/:id/audio-timing/preview',+ 'POST /api/music-video/:id/audio-timing/apply',+ 'POST /api/music-video/:id/dependency-repairs',+ 'POST /api/music-video/:id/production-review/proof',+ 'POST /api/music-video/:id/revisions/:revisionId/resume',+ 'POST /api/music-video/:id/scenes/:sceneId/continue-from-previous',+ 'POST /api/music-video/:id/scenes/:sceneId/performance-repair',+ 'POST /api/music-video/:id/sharing-copy',+ 'POST /api/music-video/:id/vocal-stem',+ // Song prepare and choosing a revised song also run Demucs separation and+ // lyric alignment in Python.+ 'POST /api/music-video/:id/song/prepare',+ 'POST /api/music-video/:id/song-revision/select',+ 'POST /api/music-video/:id/song-revision/track',+ 'POST /api/tracks/:id/audio/upload',+ 'POST /api/tracks/:id/code/render',+ // The take's WAV comes from a container running caller SuperCollider code;+ // the chiptune and waveform renders encode audio PortOS synthesized itself.+ 'POST /api/tracks/:id/supercollider/take',+ 'POST /api/media/collections/:id/localize',+ 'POST /api/mood-boards/:id/collage',+ 'POST /api/mood-boards/:id/items/:itemId/extract-frames',+ 'POST /api/sprites/:id/walk/postprocess',+ 'POST /api/sprites/:id/walk/runs/:runId/source-frames/extract',+ 'POST /api/sprites/:id/walk/trim',+ 'PATCH /api/video-gen/history/:id/poster',+ 'POST /api/video-gen/upload',+ // Headless composition browser (and ffmpeg encode), like the film-look bake.+ // Document zip import and accept stay open; their handler starts the+ // background overlay check only for a caller with host control.+ 'POST /api/music-video/:id/production-review/text-check',+ 'POST /api/code-animation/:id/export',+ 'POST /api/code-animation/jobs/:id/poster',+ 'POST /api/html-composition/render',+ // Local Python, Docker or PM2 work: a continuous-video episode's clip+ // renders and stitching, a checkpoint preview render, caller SuperCollider+ // source in a container, re-armed local video dispatch, the piper setup+ // script (it can brew install), and the PM2 health sweep, which restarts+ // errored processes. TTS synthesis on an installed runtime stays open as+ // configured inference, like local-llm test and Pipeline TTS.+ 'POST /api/continuous-video',+ 'POST /api/lora-training/runs/:id/promote-checkpoint',+ 'POST /api/music/supercollider/render',+ 'POST /api/media-jobs/holds/:holdId/resume',+ 'POST /api/voice/piper/fetch',+ 'POST /api/cos/health/check',+ // Host data and secrets: `tar` over the data directory (removing the archived+ // day files), the Signal Safe Storage keychain secret and the database it+ // decrypts (the GET setup check reads them too), and project files under a+ // caller-named directory.+ 'POST /api/data/:category/archive',+ 'POST /api/signal/sync',+ 'GET /api/signal/setup-check',+ 'POST /api/detect/repo',+ // Game publication writes asset bytes into the bound managed app's repo,+ // like chiptune and sprite atlas publication.+ 'POST /api/games/:id/artwork/:bindingId/publish',+ 'POST /api/games/:id/music/:bindingId/publish',+ // The operator's signed-in browser (#12488 rule): Suno, Pinterest, YouTube,+ // Spotify, fal.ai, Outlook/Teams token capture and scraping, and the broker+ // probes that put a privacy subject's details into broker pages.+ 'POST /api/music-video/:id/song-style/suno',+ 'POST /api/tracks/import/suno',+ 'POST /api/mood-boards/:id/pinterest/import',+ 'POST /api/youtube/sync',+ 'POST /api/youtube/playlists/sync',+ 'POST /api/digital-twin/import/spotify/browser/open',+ 'POST /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/fal-video',+ 'POST /api/calendar/sync/:accountId',+ 'POST /api/messages/sync/:accountId',+ 'POST /api/messages/:accountId/:messageId/refresh',+ 'POST /api/messages/fetch-full/:accountId',+ 'POST /api/privacy/scan',+ 'POST /api/privacy/optout',+ 'POST /api/privacy/optout/verify',+ // External account writes as the operator: Beeper chats, Google Calendar+ // goal time blocks, and approving a mail draft (the send intent the gated+ // send checks, like Beeper outbox create and X/Stacker News review).+ 'POST /api/beeper/conversations',+ 'POST /api/beeper/conversations/:id/archive',+ 'POST /api/beeper/conversations/:id/low-priority',+ 'POST /api/digital-twin/identity/goals/:id/schedule',+ 'POST /api/digital-twin/identity/goals/:id/reschedule',+ 'POST /api/messages/drafts/:id/approve',+ // Agent and LLM work: granted agent-context MCP tools (their HTTP twins are+ // gated), the Cast & Sets check-in that releases a waiting production run,+ // review prepare (direction and the shot planner), thumbnail paint (an image+ // job), custom editorial check instructions sent to a CLI/TUI-capable+ // runner, and the Writers Room handoff, which writes a Creative Director+ // project and treatment.+ 'POST /api/agent-context/mcp',+ 'POST /api/music-video/:id/cast-and-sets/approve',+ 'POST /api/music-video/:id/cast-and-sets/skip',+ 'POST /api/music-video/:id/production-review/prepare',+ 'POST /api/music-video/:id/publish-kit/youtube-thumbnail/paint',+ 'POST /api/pipeline/editorial/custom-checks',+ 'PATCH /api/pipeline/editorial/custom-checks/:id',+ 'POST /api/writers-room/works/:id/cd-bridge/send',+ // Execution policy: a social persona and its provider pins (its PUT twin is+ // gated), and resets that put held agent work back into rotation — the review+ // cooldown, task-type learning (reset returns a type to the auto-approved+ // tier, backfill re-records every run) and schedule failure/drain parks.+ // A manual sync snapshot apply can replace Digital Twin personas.+ 'POST /api/agents/personalities',+ 'POST /api/cos/app-activity/:appId/clear-cooldown',+ 'POST /api/cos/learning/reset/:taskType',+ 'POST /api/cos/learning/backfill',+ 'POST /api/cos/schedule/reset',+ 'POST /api/sync/:category/apply',+ // Eidoverse: travel spends this install's pair credential to admit the+ // owner as a guest elsewhere; world config chooses who the CoS presence+ // grants ownership to and what it publishes; controller config is what an+ // armed controller says or builds unattended, as the CoS identity.+ 'POST /api/eidoverse/travel/depart',+ 'PUT /api/eidoverse/world/config',+ 'PATCH /api/eidoverse/world/controllers/:id/config',]);/**@@ -1151,6 +1299,9 @@ export const HOST_CONTROL_ROUTES = Object.freeze([* polymorphic, so its other slices stay open.*/export const HOST_CONTROL_SETTINGS_SLICES = Object.freeze([+ // The semantic actions (Brain capture, Eidoverse augment/say, tool+ // recipes) the agent-context MCP may run for local agents (#13055).+ 'agentContext','autoUpdate',// Deferred repair policy: verifyCommand runs a shell and autoPromote can// apply the repair to the live checkout. Provider pins also select its agent.@@ -1164,6 +1315,9 @@ export const HOST_CONTROL_SETTINGS_SLICES = Object.freeze([// Image overrides pick what untrusted code runs in; extra hosts widen install egress.'dockerContainment','harnesses',+ // `privacy.recheck` arms the scheduled broker passes and their autonomy,+ // the same change as the gated PUT /api/privacy/optout/schedule (#13055).+ 'privacy','seriesAutopilot','telegram','untrustedContent',@@ -1210,6 +1364,16 @@ export const HOST_CONTROL_VOICE_CONFIG_PATHS = Object.freeze(['llm.tools.enabled','llm.codeAgent','stt.endpoint',+ // What the voice runtime reconcile starts, installs or reads (#13055): the+ // PM2 whisper-server and its engine, the setup script's Core ML and piper+ // installs, and the host model and voice paths. The handler reconciles only+ // for a caller with host control, so every other key stays a record.+ 'enabled',+ 'stt.engine',+ 'stt.coreml',+ 'stt.modelPath',+ 'tts.engine',+ 'tts.piper.voicePath',]);/**@@ -1262,7 +1426,8 @@ const COMPILED_BODY_ROUTES = [// operation spelling, including the omitted legacy default; Ask promotion to// `task` queues a user task. Both match their gated direct routes. Other// sources, triage and Brain/Goal promotion stay data-only and open.- ['POST /api/review/queue/resolve', (body) => /^\s*cos:/i.test(body?.id) ? ['id'] : []],+ // A `drafts:` row approves a message draft, the gated draft approve (#13055).+ ['POST /api/review/queue/resolve', (body) => /^\s*(cos|drafts):/i.test(body?.id) ? ['id'] : []],['POST /api/review/queue/promote-ask', (body) => body?.target === 'task' ? ['target'] : []],// LLM drill types reach a caller-chosen provider (#10989). Math, memory and// cognitive types stay open, including a missing or unknown type.@@ -1280,6 +1445,41 @@ const COMPILED_BODY_ROUTES = [// A code-animation prompt that studies a reference video runs ffmpeg over// it (#13055); a prompt without one only reads records.['POST /api/code-animation/prompt', (body) => body?.referenceVideo ? ['referenceVideo'] : []],+ // Pre-guard audit, remainder (#13055). Each opens or retargets unattended+ // work only for the named value; the rest of the body is records, and+ // disarming or disabling stays open.+ // Toggling Docker containment runs the docker CLI and removes containers,+ // networks and volumes, like the eidoverse toggle above.+ ['PUT /api/settings/features/docker-containment', (body) => bodyKeys(body)],+ // Enabling a subscription family re-enables its provider records, the gated+ // provider-edit change.+ ['PUT /api/usage/subscriptions/enabled', (body) => body?.enabled === true ? ['enabled'] : []],+ // The automation brief (agent guidance, LLM pins, image tools, Cast & Sets+ // auto-approval) steers unattended Music Video runs.+ ['POST /api/music-video', (body) => body?.automation != null ? ['automation'] : []],+ ['PATCH /api/music-video/:id', (body) => body?.automation != null ? ['automation'] : []],+ // Approving the Cast & Sets sheet is the check-in's Approve & continue.+ ['POST /api/music-video/:id/dev-artifacts/:artifactId/review', (body) => body?.status === 'approved' ? ['status'] : []],+ // A restore re-applies archived Creative Director instructions and provider+ // pins, or a commission whose kept schedule re-arms its runs; discard only+ // removes the snapshot.+ ['POST /api/conflict-journal/:id/resolve', (body) => body?.action === 'discard' ? [] : ['action']],+ // Whisper start launches whisper-server under PM2.+ ['POST /api/voice/whisper', (body) => body?.action === 'start' ? ['action'] : []],+ // Approval records send intent for the gated send; content edits drop it.+ ['PUT /api/messages/drafts/:id', (body) => body?.status === 'approved' ? ['status'] : []],+ // Arming the privacy recheck, changing its cron, or turning on autonomous+ // opt-out email approval or web-form submission.+ ['PUT /api/privacy/optout/schedule', (body) => ['enabled', 'autoApproveOptOutEmails', 'autoSubmitWebForms']+ .filter((key) => body?.[key] === true)+ .concat(typeof body?.cronExpression === 'string' ? ['cronExpression'] : [])],+ // A broker scan or opt-out purpose adds the subject to the armed broker+ // passes and authorizes disclosing their details to brokers.+ ['POST /api/privacy/subjects/:id/consents', (body) => ['broker_scan', 'broker_optout'].includes(body?.scope) ? ['scope'] : []],+ // A delivering controller speaks or builds in the private world as the CoS+ // identity on its own schedule, like say/augment; re-arming resumes that.+ ['POST /api/eidoverse/world/controllers', (body) => body?.deliverEffects === true ? ['deliverEffects'] : []],+ ['PATCH /api/eidoverse/world/controllers/:id', (body) => body?.armed === true ? ['armed'] : []],].map(([route, pick]) => ({ ...compileRoute(route), pick }));const bodyRouteEntry = (method, path) => (diff --git a/server/lib/hostControlRoutes.test.js b/server/lib/hostControlRoutes.test.jsindex 9420718b96..353669844a 100644--- a/server/lib/hostControlRoutes.test.js+++ b/server/lib/hostControlRoutes.test.js@@ -139,7 +139,8 @@ describe('HOST_CONTROL_ROUTES (#8716)', () => {expect(isHostControlRoute('post', '/API/Apps/example-app/START/')).toBe(true);expect(hostControlRouteFor('post', '/API/HTML-COMPOSITION/TOOLKIT/SKILLS/INSTALL/')).toBe('POST /api/html-composition/toolkit/skills/install');expect(isHostControlRoute('GET', '/api/html-composition/toolkit')).toBe(false);- expect(isHostControlRoute('POST', '/api/html-composition/render')).toBe(false);+ // Render runs the headless composition browser and ffmpeg (#13055).+ expect(isHostControlRoute('POST', '/api/html-composition/render')).toBe(true);expect(isHostControlRoute('POST', '/api/git/status')).toBe(true);for (const suffix of ['//', '////']) {expect(hostControlRouteFor('post', '/API/Runs' + suffix)).toBe('POST /api/runs');@@ -174,7 +175,17 @@ describe('outbound mail host-control policy (#11273)', () => {expect(mounted.has(route)).toBe(true);expect(hostControlRouteFor('POST', '/api/messages/drafts/33333333-3333-3333-3333-333333333333/send')).toBe(route);expect(isHostControlRoute('POST', '/api/messages/drafts')).toBe(false);- expect(isHostControlRoute('POST', '/api/messages/drafts/33333333-3333-3333-3333-333333333333/approve')).toBe(false);+ // Approval is the send intent the gated send checks (#13055); a PUT that+ // approves is gated per body, and other draft edits stay open.+ expect(isHostControlRoute('POST', '/api/messages/drafts/33333333-3333-3333-3333-333333333333/approve')).toBe(true);+ const draft = '/api/messages/drafts/33333333-3333-3333-3333-333333333333';+ expect(isHostControlRoute('PUT', draft)).toBe(false);+ expect(hostControlBodyKeys('PUT', draft, { status: 'approved' })).toEqual(['status']);+ for (const body of [{ body: 'Example' }, { status: 'draft' }, { status: 'pending_review' }, null]) {+ expect(hostControlBodyKeys('PUT', draft, body), JSON.stringify(body)).toEqual([]);+ }+ expect(hostControlBodyKeys('POST', '/api/review/queue/resolve', { id: 'drafts:example' })).toEqual(['id']);+ expect(hostControlBodyKeys('POST', '/api/review/queue/resolve', { id: 'memory:example' })).toEqual([]);});it('gates external archive/delete actions while keeping message reads open (#11434)', () => {@@ -310,8 +321,6 @@ describe('prompt-feeding store and Digital Twin mutation inventory (#9040, #1067"POST /api/digital-twin/identity/goals/:id/generate-phases","POST /api/digital-twin/identity/goals/:id/milestones","POST /api/digital-twin/identity/goals/:id/progress",- "POST /api/digital-twin/identity/goals/:id/reschedule",- "POST /api/digital-twin/identity/goals/:id/schedule","POST /api/digital-twin/identity/goals/:id/todos","POST /api/digital-twin/identity/goals/organize","POST /api/digital-twin/identity/goals/organize/apply",@@ -319,7 +328,6 @@ describe('prompt-feeding store and Digital Twin mutation inventory (#9040, #1067"POST /api/digital-twin/identity/image/save","POST /api/digital-twin/identity/longevity/derive","POST /api/digital-twin/import/save",- "POST /api/digital-twin/import/spotify/browser/open","POST /api/digital-twin/snapshots","POST /api/digital-twin/snapshots/compare","POST /api/digital-twin/social-accounts",@@ -394,7 +402,6 @@ describe('media generation and source publication policy (#9667)', () => {['POST', '/api/image-gen/cancel'],['POST', '/api/video-gen/cancel'],['POST', '/api/sprites/:id/atlas/compile'],- ['POST', '/api/html-composition/render'],]) expect(isHostControlRoute(method, path), path).toBe(false);});});@@ -415,7 +422,6 @@ describe('auxiliary media mutation inventory (#9672)', () => {'POST /api/lora-datasets/:id/strip-shared-fragments','POST /api/media-jobs/:id/cancel','POST /api/media-jobs/cancel-queued',- 'POST /api/media-jobs/holds/:holdId/resume',];it('gates every agent-dispatching mutation and keeps reviewed record operations open', () => {@@ -515,7 +521,6 @@ describe('Pipeline authoring remainder policy (#10907)', () => {'DELETE /api/pipeline/series/:id/seasons/:seasonId','DELETE /api/pipeline/editorial/custom-checks/:id','PATCH /api/pipeline/editorial/checks/:id',- 'PATCH /api/pipeline/editorial/custom-checks/:id','PATCH /api/pipeline/editorial/readiness-gate','PATCH /api/pipeline/issues/:id','PATCH /api/pipeline/issues/:id/stages/audio/lines/:lineIdx',@@ -525,7 +530,6 @@ describe('Pipeline authoring remainder policy (#10907)', () => {'PATCH /api/pipeline/series/:id/manuscript/review/comments/:commentId','PATCH /api/pipeline/series/:id/seasons/:seasonId','PATCH /api/pipeline/tts/narrate/segment',- 'POST /api/pipeline/editorial/custom-checks','POST /api/pipeline/issues/:id/auto-run-text/cancel',// Recovery only resets persisted state; generating again uses the gated route.'POST /api/pipeline/issues/:id/stages/:stageId/recover',@@ -666,7 +670,6 @@ describe('FableLoom mutation inventory (#10668)', () => {'POST /api/fableloom/:id/episodes/:episodeId/nodes','PATCH /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId','DELETE /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId',- 'POST /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/fal-video','POST /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/transitions','PATCH /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/transitions/:transitionId','DELETE /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/transitions/:transitionId',@@ -941,8 +944,10 @@ describe('Calendar MCP execution policy (#11051)', () => {expect(hostControlRouteFor('POST', path)).toBe(`POST ${path}`);expect(hostControlRouteFor('post', path.toUpperCase() + '/')).toBe(`POST ${path}`);}+ // Generic sync captures an Outlook bearer token through the signed-in+ // browser (#13055); the direct API sync and push ingestion do not.+ expect(hostControlRouteFor('POST', '/api/calendar/sync/:accountId')).toBe('POST /api/calendar/sync/:accountId');for (const route of [- 'POST /api/calendar/sync/:accountId','POST /api/calendar/sync/:accountId/push','POST /api/calendar/sync/:accountId/api','POST /api/calendar/sync/:accountId/discover-api',diff --git a/server/routes/brainSettings.js b/server/routes/brainSettings.jsindex 8eb3f5bf28..8d6b27a3fd 100644--- a/server/routes/brainSettings.js+++ b/server/routes/brainSettings.js@@ -11,6 +11,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { settingsUpdateInputSchema } from '../lib/brainValidation.js';import { modelPinIsOffered } from '../lib/localProviderRuntime.js';+import { assertHostControl } from '../services/authGate.js';const router = Router();@@ -29,14 +30,24 @@ router.get('/settings', asyncHandler(async (req, res) => {*/router.put('/settings', asyncHandler(async (req, res) => {const data = validateRequest(settingsUpdateInputSchema, req.body);+ const currentSettings = await brainService.loadMeta();++ // The scheduled digest and weekly review run Brain records, which open+ // routes write, through this provider on a runner that is not tool-free.+ // Turning them on or retargeting them needs host control, like the gated+ // daily-log digest settings (#13055); an unchanged resend stays open.+ const changes = (key) => data[key] !== undefined && data[key] !== currentSettings[key];+ if ((data.scheduledReviewsEnabled === true && changes('scheduledReviewsEnabled'))+ || changes('defaultProvider') || changes('defaultModel')) {+ assertHostControl(req);+ }// Validate provider and model if providedif (data.defaultProvider || data.defaultModel) {const providerId = data.defaultProvider;const modelId = data.defaultModel;- // Get current settings to use existing provider if only model is being updated- const currentSettings = await brainService.loadMeta();+ // Use the existing provider if only the model is being updatedconst effectiveProviderId = providerId || currentSettings.defaultProvider;// Validate provider existsdiff --git a/server/routes/brainSettings.test.js b/server/routes/brainSettings.test.jsindex b926e95bdc..d2d226b618 100644--- a/server/routes/brainSettings.test.js+++ b/server/routes/brainSettings.test.js@@ -21,6 +21,9 @@ vi.mock('../services/providers.js', () => ({const settingsRoutes = (await import('./brainSettings.js')).default;const app = express();+// A local password-free caller holds host control, which retargeting the+// scheduled digest needs (#13055); hostControlPreGuardOps.test.js covers refusal.+app.use((req, _res, next) => { req.portosAuthContext = { enabled: false }; next(); });app.use(express.json());app.use('/api/brain', settingsRoutes);app.use(errorMiddleware);diff --git a/server/routes/hostControlCalendarMcp.test.js b/server/routes/hostControlCalendarMcp.test.jsindex cafa543008..4a36f7dc49 100644--- a/server/routes/hostControlCalendarMcp.test.js+++ b/server/routes/hostControlCalendarMcp.test.js@@ -87,6 +87,11 @@ vi.mock('../services/googleOAuthAutoConfig.js', () => ({vi.mock('../services/messageTokenExtractor.js', () => ({getToken: vi.fn(async () => ({ token: 'example-token', fresh: true, decoded: {} })), getTokenStatus: vi.fn(), clearTokenCache: vi.fn(),}));+// Outlook generic sync: token capture in the signed-in tab, then the Graph fetch.+// null is its "no token" answer, which syncAccount reports as skipped.+vi.mock('../services/calendarApiSync.js', async (importOriginal) => ({+ ...await importOriginal(), syncOutlookCalendarApi: vi.fn(async () => null),+}));import { authGate, hostControlRouteGate, hostControlBodyGate } from '../services/authGate.js';import { createSession } from '../services/auth.js';@@ -97,6 +102,7 @@ import { mutateCache } from '../services/calendarSync.js';import { apiSyncAccount, apiDiscoverCalendars } from '../services/calendarGoogleApiSync.js';import { startAutoConfig, captureCredentials, runAutomatedSetup } from '../services/googleOAuthAutoConfig.js';import { getToken } from '../services/messageTokenExtractor.js';+import { syncOutlookCalendarApi } from '../services/calendarApiSync.js';import calendarRoutes from './calendar.js';const appFor = (address = '192.0.2.10') => {@@ -189,7 +195,7 @@ describe('Calendar MCP operator authority (#11051)', () => {}});- it('allows remote reference-data edits, push ingestion, direct API operations and generic Google push-only sync without a CLI', async () => {+ it('allows remote reference-data edits, push ingestion and direct API operations without a CLI', async () => {const app = appFor();const edited = await request(app).put(`/api/calendar/accounts/${fixture.id}/subcalendars`).send({subcalendars: [{ calendarId: fixture.calendarId, name: fixture.marker, enabled: true }],@@ -205,8 +211,6 @@ describe('Calendar MCP operator authority (#11051)', () => {for (const action of ['api', 'discover-api']) expect((await post(app, action)).status).toBe(200);expect(apiSyncAccount).toHaveBeenCalledWith(fixture.id, undefined);expect(apiDiscoverCalendars).toHaveBeenCalledWith(fixture.id);- const generic = await request(app).post(`/api/calendar/sync/${fixture.id}`).send({});- expect([generic.status, generic.body.status]).toEqual([200, 'push-only']);// The stored marker remains data: neither MCP entry point may consume it// when this same remote caller tries to start the agent.@@ -258,3 +262,69 @@ describe('Calendar host-browser automation operator authority (#12952)', () => {for (const [path, effect] of browserActions) expect(effect, path).toHaveBeenCalledTimes(3);});});++describe('Calendar generic sync operator authority (#13055)', () => {+ // An Outlook account's generic sync captures a bearer token from the+ // operator's signed-in browser tab on a cache miss, so the route is gated+ // whole; its /api, /push and /discover-api siblings stay open (above).+ const path = `/api/calendar/sync/${fixture.id}`;+ const sync = (app, headers = {}, target = path) => {+ const pending = request(app).post(target);+ for (const [name, value] of Object.entries(headers)) pending.set(name, value);+ return pending.send({});+ };+ const expectNotSynced = () => {+ for (const effect of [getAccount, syncOutlookCalendarApi, getToken]) expect(effect).not.toHaveBeenCalled();+ };+ beforeEach(() => {+ fixture.account = { ...fixture.account, type: 'outlook-calendar' };+ });++ it('refuses remote, spoofed-proxy and URL-variant callers before the account is read', async () => {+ for (const [address, headers] of [+ ['192.0.2.10', {}],+ ['127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }],+ ['192.0.2.10', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '127.0.0.1' }],+ ]) {+ for (const target of [path, path.toUpperCase() + '/']) {+ const response = await sync(appFor(address), headers, target);+ expect([response.status, response.body.code], target).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ }+ expectNotSynced();+ });++ it('requires authentication with a password and denies legacy Basic and scoped-peer credentials', async () => {+ auth.enabled = true;+ for (const [headers, status, code] of [+ [{}, 401, 'AUTH_REQUIRED'],+ [{ Authorization: 'Basic ' + Buffer.from(':example-password').toString('base64') }, 403, 'HOST_CONTROL_FORBIDDEN'],+ [{+ [PEER_AUTH_HEADER]: derivePeerAuthToken('a'.repeat(32), 'example-instance'),+ [PEER_INSTANCE_HEADER]: 'example-instance',+ }, 403, 'PEER_SCOPE_FORBIDDEN'],+ ]) {+ const response = await sync(appFor(), headers);+ expect([response.status, response.body.code]).toEqual([status, code]);+ }+ expectNotSynced();+ });++ it('keeps local, operator-session and delegated-agent callers able to sync', async () => {+ const operator = await createSession();+ const agent = await createSession({ label: 'agent' });+ for (const [enabled, address, headers] of [+ [false, '127.0.0.1', {}],+ [true, '192.0.2.10', { Cookie: `portos_auth=${operator.token}` }],+ [true, '192.0.2.10', { Authorization: `Bearer ${agent.token}` }],+ ]) {+ auth.enabled = enabled;+ const response = await sync(appFor(address), headers);+ expect([response.status, response.body.status], JSON.stringify(response.body)).toEqual([200, 'skipped']);+ }+ expect(syncOutlookCalendarApi).toHaveBeenCalledTimes(3);+ expect(syncOutlookCalendarApi).toHaveBeenLastCalledWith(+ expect.objectContaining({ id: fixture.id, type: 'outlook-calendar' }), expect.anything(), undefined, {},+ );+ });+});diff --git a/server/routes/hostControlDigitalTwin.test.js b/server/routes/hostControlDigitalTwin.test.jsindex 5127716d55..721f554fd7 100644--- a/server/routes/hostControlDigitalTwin.test.js+++ b/server/routes/hostControlDigitalTwin.test.js@@ -81,6 +81,8 @@ const operations = [['avatar-bio/polish', picker, effects.polishAvatarBio],['import/analyze', { source: 'goodreads', data: 'Example import data', ...picker }, effects.analyzeImportedData],['import/spotify/browser/import', picker, spotify.importSpotifyFromBrowser],+ // Opens a tab in the operator's signed-in managed browser (#13055).+ ['import/spotify/browser/open', {}, spotify.openSpotifyBrowser],['twin-evidence/interpret', picker, evidence.interpretConsumption],];const appFor = (address = '192.0.2.10') => {diff --git a/server/routes/hostControlMediaAuthoring.test.js b/server/routes/hostControlMediaAuthoring.test.jsindex 586ebd03a2..8fc9fe530a 100644--- a/server/routes/hostControlMediaAuthoring.test.js+++ b/server/routes/hostControlMediaAuthoring.test.js@@ -407,7 +407,6 @@ describe('media authoring operator authority (#9512, #9869)', () => {for (const [path, body, status] of [['/api/code-animation/prompt', { concept: 'Example scene' }, 200],[`/api/code-animation/projects/${id}/stage-runs/${id}/cancel`, {}, 200],- [`/api/code-animation/${id}/export`, {}, 202],[`/api/tracks/${id}/waveform/render`, {}, 200],[`/api/music-video/${id}/autonomous/stop`, {}, 200],[`/api/music-video/${id}/autonomous/cancel`, {}, 200],diff --git a/server/routes/hostControlMediaInstallers.test.js b/server/routes/hostControlMediaInstallers.test.jsindex 1d92319622..9ad543960c 100644--- a/server/routes/hostControlMediaInstallers.test.js+++ b/server/routes/hostControlMediaInstallers.test.js@@ -231,7 +231,9 @@ describe('media installer operator authority (#9513)', () => {expect(response.status, path).toBe(200);expect(response.headers['content-type']).toMatch(/^application\/json/);}- const render = await request(app).post('/api/music/supercollider/render')+ // Render runs caller SuperCollider source in a container, so it needs host+ // control (#13055); a local caller still renders without setup.+ const render = await request(appFor('127.0.0.1')).post('/api/music/supercollider/render').send({ code: 'Pbind()', durationSec: 4, seed: 1 });expect(render.status).toBe(202);expect(enqueueJob).toHaveBeenCalledWith({ kind: 'supercollider', params: {diff --git a/server/routes/hostControlMusicVideoPreGuard.test.js b/server/routes/hostControlMusicVideoPreGuard.test.jsnew file mode 100644index 0000000000..f217c869c5--- /dev/null+++ b/server/routes/hostControlMusicVideoPreGuard.test.js@@ -0,0 +1,326 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';+import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-mv-pre-guard-') }));+afterAll(cleanupTempDataRoots);++// Music Video routes the pre-guard audit moved behind operator authority+// (#13055): ffmpeg/ffprobe decodes, the headless-browser text check, Suno browser+// reads, retime/alignment jobs, image jobs and Cast & Sets releases, plus the+// automation brief and the sheet approval that steer unattended runs. Real+// router behind the real gates; each service sink is a spy, so a refused+// caller that reached one is visible, and an open body must still reach it.+const auth = vi.hoisted(() => ({ enabled: false }));+const effects = vi.hoisted(() => {+ const resolves = (value) => vi.fn(async () => value);+ const project = { id: 'example-project' };+ return {+ createProject: resolves(project),+ updateProject: resolves(project),+ analyzeProjectSong: resolves(project),+ analyzeAudioFileManual: resolves({ bpm: 120, sections: [], durationSec: 10 }),+ applyAudioTiming: resolves({ project }),+ previewAudioTiming: resolves({ preview: [] }),+ approveCastAndSets: resolves({ status: 'approved' }),+ skipCastAndSets: resolves({ status: 'skipped' }),+ acceptMixedMediaDocument: resolves({ project }),+ importDocumentZip: resolves({ project }),+ checkOverlayTextInBackground: vi.fn(),+ startDependencyRepair: resolves({ project }),+ reviewArtifact: resolves({ project }),+ prepareProductionReview: resolves({ project }),+ renderProductionProof: resolves({ jobId: 'example-job' }),+ startOverlayTextCheck: resolves({ project: {}, readiness: {} }),+ paintYoutubeThumbnail: resolves({ project: {} }),+ resumeRevision: resolves({ project }),+ continueFromPreviousShot: resolves({ project }),+ startPerformanceRepair: resolves({ project }),+ prepareSharingCopy: resolves({ jobId: 'example-job' }),+ selectSongRevision: resolves({ project }),+ reviseSongFromTrack: resolves({ project }),+ refreshSongStyleFromSuno: resolves({ project }),+ autoPrepareSong: resolves({ project }),+ // The real parser streams the stem to a temp file the service would adopt.+ attachVocalStem: vi.fn(async (_id, { tempPath }) => {+ const { rm } = await import('node:fs/promises');+ await rm(tempPath, { force: true });+ return project;+ }),+ };+});++vi.mock('../services/auth.js', async (importOriginal) => ({+ ...await importOriginal(),+ isAuthEnabled: vi.fn(async () => auth.enabled),+ verifyPassword: vi.fn(async () => true),+}));+vi.mock('../services/settings.js', () => ({+ settingsEvents: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ getSettings: vi.fn(async () => ({})),+ updateSettingsWith: vi.fn(async (mutate) => mutate({})),+}));+vi.mock('../services/instanceIdentity.js', () => ({+ ensureInstanceId: vi.fn(async () => 'example-self'),+ loadData: vi.fn(async () => ({ peers: [{+ id: 'example-peer', instanceId: 'example-instance', enabled: true, syncSecret: 'a'.repeat(32),+ }] })),+}));+vi.mock('../services/musicVideo/projects.js', async (importOriginal) => ({+ ...await importOriginal(),+ createProject: effects.createProject,+ updateProject: effects.updateProject,+ refreshSongStyleFromSuno: effects.refreshSongStyleFromSuno,+ setProjectAnalysis: vi.fn(async () => ({ id: 'example-project' })),+}));+vi.mock('../services/musicVideo/requireProject.js', async (importOriginal) => ({+ ...await importOriginal(),+ // No cached analysis, so manual analysis takes the ffmpeg decode path.+ requireProject: vi.fn(async (id) => ({ id, audioAnalysis: null })),+}));+vi.mock('../services/musicVideo/projectAudio.js', async (importOriginal) => ({+ ...await importOriginal(),+ analyzeProjectSong: effects.analyzeProjectSong,+ resolveProjectAudioPath: vi.fn(async () => 'example.mp3'),+}));+vi.mock('../services/musicVideo/audioAnalysis.js', async (importOriginal) => ({+ ...await importOriginal(),+ analyzeAudioFileManual: effects.analyzeAudioFileManual,+}));+vi.mock('../services/musicVideo/audioTiming.js', async (importOriginal) => ({+ ...await importOriginal(),+ applyAudioTiming: effects.applyAudioTiming,+ previewAudioTiming: effects.previewAudioTiming,+}));+vi.mock('../services/musicVideo/castAndSetsService.js', async (importOriginal) => ({+ ...await importOriginal(),+ approveCastAndSets: effects.approveCastAndSets,+ skipCastAndSets: effects.skipCastAndSets,+}));+vi.mock('../services/musicVideo/documentGeneration.js', async (importOriginal) => ({+ ...await importOriginal(),+ acceptMixedMediaDocument: effects.acceptMixedMediaDocument,+}));+vi.mock('../services/musicVideo/compositionDocument.js', async (importOriginal) => ({+ ...await importOriginal(),+ importDocumentZip: effects.importDocumentZip,+}));+vi.mock('../services/musicVideo/overlayTextService.js', async (importOriginal) => ({+ ...await importOriginal(),+ checkOverlayTextInBackground: effects.checkOverlayTextInBackground,+ startOverlayTextCheck: effects.startOverlayTextCheck,+}));+vi.mock('../services/musicVideo/revisionService.js', async (importOriginal) => ({+ ...await importOriginal(),+ startDependencyRepair: effects.startDependencyRepair,+ resumeRevision: effects.resumeRevision,+}));+vi.mock('../services/musicVideo/devArtifactService.js', async (importOriginal) => ({+ ...await importOriginal(),+ reviewArtifact: effects.reviewArtifact,+}));+vi.mock('../services/musicVideo/productionReviewService.js', async (importOriginal) => ({+ ...await importOriginal(),+ prepareProductionReview: effects.prepareProductionReview,+ renderProductionProof: effects.renderProductionProof,+}));+vi.mock('../services/musicVideo/youtubeThumbnail.js', async (importOriginal) => ({+ ...await importOriginal(),+ paintYoutubeThumbnail: effects.paintYoutubeThumbnail,+}));+vi.mock('../services/musicVideo/continueShot.js', async (importOriginal) => ({+ ...await importOriginal(),+ continueFromPreviousShot: effects.continueFromPreviousShot,+}));+vi.mock('../services/musicVideo/performanceRepair.js', async (importOriginal) => ({+ ...await importOriginal(),+ startPerformanceRepair: effects.startPerformanceRepair,+}));+vi.mock('../services/musicVideo/sharingCopy.js', async (importOriginal) => ({+ ...await importOriginal(),+ prepareSharingCopy: effects.prepareSharingCopy,+}));+vi.mock('../services/musicVideo/songRevision.js', async (importOriginal) => ({+ ...await importOriginal(),+ selectSongRevision: effects.selectSongRevision,+ reviseSongFromTrack: effects.reviseSongFromTrack,+}));+vi.mock('../services/musicVideo/songAutoPrepare.js', async (importOriginal) => ({+ ...await importOriginal(),+ autoPrepareSong: effects.autoPrepareSong,+}));+vi.mock('../services/musicVideo/vocalStem.js', async (importOriginal) => ({+ ...await importOriginal(),+ attachVocalStem: effects.attachVocalStem,+}));++import { authGate, hostControlBodyGate, hostControlRouteGate } from '../services/authGate.js';+import { createSession } from '../services/auth.js';+import musicVideoRoutes from './musicVideo.js';++const BOUNDARY = 'example-boundary';+const upload = (field, filename, type) => ({+ raw: Buffer.from([+ `--${BOUNDARY}`,+ `Content-Disposition: form-data; name="${field}"; filename="${filename}"`,+ `Content-Type: ${type}`,+ '',+ 'example',+ `--${BOUNDARY}--`,+ '',+ ].join('\r\n')),+});++const PROJECT = '/api/music-video/example-project';+// [method, path, body, sink, authorized status, open body (body-gated rows only)]+const operations = [+ ['post', '/api/music-video', { name: 'Example video', automation: { guidance: 'Example guidance', checkins: { castAndSets: 'auto' } } },+ effects.createProject, 201, { name: 'Example video' }],+ ['patch', PROJECT, { automation: { checkins: { castAndSets: 'auto' } } }, effects.updateProject, 200, { name: 'Example video' }],+ ['post', `${PROJECT}/dev-artifacts/mvda-example/review`, { status: 'approved' }, effects.reviewArtifact, 200,+ { status: 'changes-requested', note: 'Example note' }],+ ['post', `${PROJECT}/analyze`, {}, effects.analyzeProjectSong, 200],+ ['post', `${PROJECT}/analyze/manual`, { bpm: 120, offsetSec: 0 }, effects.analyzeAudioFileManual, 200],+ ['post', `${PROJECT}/audio-timing/apply`, {+ targetTrackId: 'example-track', intervals: [{ oldStartSec: 0, oldEndSec: 10, newStartSec: 0 }], basis: '0123456789abcdef0123456789abcdef',+ }, effects.applyAudioTiming, 200],+ ['post', `${PROJECT}/audio-timing/preview`, {+ targetTrackId: 'example-track', intervals: [{ oldStartSec: 0, oldEndSec: 10, newStartSec: 0 }],+ }, effects.previewAudioTiming, 200],+ ['post', `${PROJECT}/cast-and-sets/approve`, {}, effects.approveCastAndSets, 200],+ ['post', `${PROJECT}/cast-and-sets/skip`, {}, effects.skipCastAndSets, 200],+ ['post', `${PROJECT}/dependency-repairs`, { basis: 'example-basis' }, effects.startDependencyRepair, 201],+ ['post', `${PROJECT}/production-review/prepare`, { providerId: 'example-provider', model: 'example-model' }, effects.prepareProductionReview, 200],+ ['post', `${PROJECT}/production-review/proof`, { startSec: 0, endSec: 12 }, effects.renderProductionProof, 202],+ ['post', `${PROJECT}/production-review/text-check`, {}, effects.startOverlayTextCheck, 202],+ ['post', `${PROJECT}/publish-kit/youtube-thumbnail/paint`, { title: 'Example title', source: { kind: 'image', filename: 'example.png' } },+ effects.paintYoutubeThumbnail, 200],+ ['post', `${PROJECT}/revisions/mvrev-example/resume`, {}, effects.resumeRevision, 200],+ ['post', `${PROJECT}/scenes/example-scene/continue-from-previous`, {}, effects.continueFromPreviousShot, 200],+ ['post', `${PROJECT}/scenes/example-scene/performance-repair`, { excerptId: 'example-excerpt', sourceAssetId: 'example-asset', boundarySec: 1 },+ effects.startPerformanceRepair, 201],+ ['post', `${PROJECT}/sharing-copy`, {}, effects.prepareSharingCopy, 202],+ ['post', `${PROJECT}/song-revision/select`, { revisionId: 'example-revision', songId: 'example-song' }, effects.selectSongRevision, 200],+ ['post', `${PROJECT}/song-revision/track`, { trackId: 'example-track' }, effects.reviseSongFromTrack, 201],+ ['post', `${PROJECT}/song-style/suno`, { url: 'https://example.com/song/example' }, effects.refreshSongStyleFromSuno, 200],+ ['post', `${PROJECT}/song/prepare`, {}, effects.autoPrepareSong, 200],+ ['post', `${PROJECT}/vocal-stem`, upload('stem', 'example.mp3', 'audio/mpeg'), effects.attachVocalStem, 200],+];++const appFor = (address = '192.0.2.10') => {+ const app = express();+ app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });+ next();+ });+ app.use(authGate, hostControlRouteGate, express.json(), hostControlBodyGate);+ app.use('/api/music-video', musicVideoRoutes);+ app.use(errorMiddleware);+ return app;+};+const call = (app, [method, path, body], headers = {}) => {+ const pending = request(app)[method](path);+ if (body.raw) pending.set('Content-Type', `multipart/form-data; boundary=${BOUNDARY}`);+ for (const [name, value] of Object.entries(headers)) pending.set(name, value);+ return pending.send(body.raw ?? body);+};+const expectNoEffects = () => {+ for (const effect of Object.values(effects)) expect(effect).not.toHaveBeenCalled();+};++beforeEach(() => {+ vi.clearAllMocks();+ auth.enabled = false;+});++describe('Music Video pre-guard operator authority (#13055)', () => {+ it('imports a composition document for any caller and starts the browser overlay check only with host control', async () => {+ const imports = [+ [['post', `${PROJECT}/composition/document/zip`, upload('file', 'example.zip', 'application/zip')], effects.importDocumentZip, 201],+ [['post', `${PROJECT}/composition/document/accept`, { directory: 'music-video/example-project/composition/doc-example' }],+ effects.acceptMixedMediaDocument, 200],+ ];+ const importAs = async (address) => {+ for (const [operation, , status] of imports) {+ expect((await call(appFor(address), operation)).status, `${address} ${operation[1]}`).toBe(status);+ }+ };+ await importAs('127.0.0.1');+ await vi.waitFor(() => expect(effects.checkOverlayTextInBackground).toHaveBeenCalledTimes(2));+ expect(effects.checkOverlayTextInBackground).toHaveBeenLastCalledWith('example-project');++ // The check starts behind a dynamic import of a now-cached module, so a+ // check the remote imports had started would land before the next local one.+ await importAs('192.0.2.10');+ for (const [, effect] of imports) expect(effect).toHaveBeenCalledTimes(2);+ await importAs('127.0.0.1');+ await vi.waitFor(() => expect(effects.checkOverlayTextInBackground.mock.calls.length).toBeGreaterThanOrEqual(4));+ expect(effects.checkOverlayTextInBackground).toHaveBeenCalledTimes(4);+ });++ it('refuses remote password-free callers, spoofed-proxy and case variants before any service runs', async () => {+ for (const operation of operations) {+ const [method, path, body, , , open] = operation;+ const variants = [+ ['192.0.2.10', {}, path],+ ['127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }, path],+ ['192.0.2.10', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '127.0.0.1' }, path],+ ];+ if (!open) variants.push(['192.0.2.10', {}, path.toUpperCase() + '/']);+ for (const [address, headers, target] of variants) {+ const response = await call(appFor(address), [method, target, body], headers);+ expect([response.status, response.body.code], `${method} ${target}`).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ }+ expectNoEffects();+ });++ it('requires authentication with a password and denies legacy Basic and scoped-peer credentials', async () => {+ auth.enabled = true;+ for (const operation of operations) {+ for (const [headers, status, code] of [+ [{}, 401, 'AUTH_REQUIRED'],+ [{ Authorization: 'Basic ' + Buffer.from(':example-password').toString('base64') }, 403, 'HOST_CONTROL_FORBIDDEN'],+ [{+ [PEER_AUTH_HEADER]: derivePeerAuthToken('a'.repeat(32), 'example-instance'),+ [PEER_INSTANCE_HEADER]: 'example-instance',+ }, 403, 'PEER_SCOPE_FORBIDDEN'],+ ]) {+ const response = await call(appFor(), operation, headers);+ expect([response.status, response.body.code], `${operation[0]} ${operation[1]}`).toEqual([status, code]);+ }+ }+ expectNoEffects();+ });++ it('keeps working for local callers, operator sessions and delegated agent sessions', async () => {+ const operator = await createSession();+ const agent = await createSession({ label: 'agent' });+ for (const [enabled, address, headers] of [+ [false, '127.0.0.1', {}],+ [true, '192.0.2.10', { Authorization: `Bearer ${operator.token}` }],+ [true, '192.0.2.10', { Authorization: `Bearer ${agent.token}` }],+ ]) {+ auth.enabled = enabled;+ for (const operation of operations) {+ const response = await call(appFor(address), operation, headers);+ expect(response.status, `${operation[0]} ${operation[1]}: ${JSON.stringify(response.body)}`).toBe(operation[4]);+ }+ }+ for (const [method, path, , effect] of operations) expect(effect, `${method} ${path}`).toHaveBeenCalledTimes(3);+ expect(effects.createProject).toHaveBeenLastCalledWith(expect.objectContaining({ automation: operations[0][2].automation }));+ });++ it('leaves the open body of each body-gated route available to a remote caller', async () => {+ for (const [method, path, , effect, status, open] of operations.filter((operation) => operation[5])) {+ const response = await call(appFor(), [method, path, open]);+ expect(response.status, `${method} ${path}: ${JSON.stringify(response.body)}`).toBe(status);+ expect(effect, `${method} ${path}`).toHaveBeenCalledTimes(1);+ }+ });+});diff --git a/server/routes/hostControlPreGuardMedia.test.js b/server/routes/hostControlPreGuardMedia.test.jsnew file mode 100644index 0000000000..11b716db0d--- /dev/null+++ b/server/routes/hostControlPreGuardMedia.test.js@@ -0,0 +1,318 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { EventEmitter } from 'node:events';+import express from 'express';+import sharp from 'sharp';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';+import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/paths.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-pre-guard-media-') }));+vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-pre-guard-media-') }));+afterAll(cleanupTempDataRoots);++// ffmpeg/ffprobe over caller or peer media, the headless composition browser,+// re-armed local video dispatch, the signed-in Pinterest browser and the GPU+// image clean need operator authority (#13055). Real routers behind the real+// gates; every host-process service is doubled. The standalone image clean is+// gated in its handler only for the GPU mode, so its in-process sharp passes+// stay open to a remote caller.+const auth = vi.hoisted(() => ({ enabled: false }));+const effects = vi.hoisted(() => ({+ codeExport: vi.fn(async () => ({ status: 'queued' })),+ codePoster: vi.fn(async () => ({ posterVersion: 1 })),+ enqueue: vi.fn(async () => ({ jobId: 'example-job' })),+ resumeHold: vi.fn(async () => true),+ pull: vi.fn(async () => ({})),+ collage: vi.fn(async () => ({ filename: 'example-collage.png' })),+ frames: vi.fn(async () => ({ added: 3 })),+ pinterest: vi.fn(async () => ({ imported: 1 })),+ postprocess: vi.fn(async () => ({ ok: true })),+ sourceFrames: vi.fn(async () => ({ frames: [] })),+ trim: vi.fn(async () => ({ id: 'example-trim' })),+ videoPoster: vi.fn(async () => ({ id: 'example-video' })),+ upload: vi.fn(async () => ({ filename: 'example.mp4' })),+ uploadFile: vi.fn(async () => ({ filename: 'example.mp4' })),+ gpuClean: vi.fn(async () => ({ jobId: '22222222-2222-4222-8222-222222222222', modelId: 'example-model', strength: 0.3 })),+}));+vi.mock('../services/auth.js', async (importOriginal) => ({+ ...await importOriginal(),+ isAuthEnabled: vi.fn(async () => auth.enabled),+ verifyPassword: vi.fn(async () => true),+}));+vi.mock('../services/settings.js', () => ({+ settingsEvents: new EventEmitter(), getSettings: vi.fn(async () => ({})),+}));+vi.mock('../services/instanceIdentity.js', () => ({+ ensureInstanceId: vi.fn(async () => 'example-self'),+ loadData: vi.fn(async () => ({ peers: [{+ id: 'example-peer', instanceId: 'example-instance', enabled: true, syncSecret: 'a'.repeat(32),+ }] })),+}));+vi.mock('../services/codeAnimation/index.js', () => ({ captureCodeAnimationJobPoster: effects.codePoster }));+vi.mock('../services/codeAnimation/export.js', () => ({ startCodeAnimationExport: effects.codeExport }));+vi.mock('../services/mediaJobQueue/index.js', () => ({+ enqueueJob: effects.enqueue, resumeVideoHold: effects.resumeHold,+ attachSseClient: vi.fn(), cancelJob: vi.fn(), listJobs: vi.fn(() => []), listQueueJobs: vi.fn(() => []),+ getJob: vi.fn(() => null), cancelQueuedJobs: vi.fn(), removeArchivedJob: vi.fn(), runJobNow: vi.fn(),+ listVideoHolds: vi.fn(() => []),+ JOB_KINDS: ['image', 'video'], JOB_STATUSES: ['queued', 'running', 'completed', 'failed', 'canceled'],+ MEDIA_QUEUE_SHUTTING_DOWN: 'MEDIA_QUEUE_SHUTTING_DOWN',+}));+vi.mock('../services/mediaCollections.js', async (importOriginal) => ({+ ...await importOriginal(),+ getCollection: vi.fn(async (id) => ({ id, items: [{ kind: 'video', ref: 'example-video' }] })),+}));+vi.mock('../services/peerHostedMedia.js', () => ({+ resolveMediaLocations: vi.fn(async (items) => items.map(() => ({ location: 'remote', hostPeerId: 'example-peer' }))),+ findHostPeer: vi.fn(async (id) => ({ id })),+ unmarkHosted: vi.fn(),+}));+vi.mock('../services/sharing/peerSyncAssets.js', () => ({+ pullMissingAssetsFromPeer: effects.pull,+ collectionVideoRefToFilename: (ref) => `${ref}.mp4`,+}));+vi.mock('../services/moodBoard/index.js', () => ({+ composeBoardCollage: effects.collage,+ extractItemFrames: effects.frames,+ importPrivatePinterestBoard: effects.pinterest,+}));+vi.mock('../services/sprites/walk.js', () => ({+ rerunWalkPostprocess: effects.postprocess, getWalkSourceFrames: effects.sourceFrames,+}));+vi.mock('../services/sprites/walkTrims.js', () => ({ saveLoopTrim: effects.trim }));+vi.mock('../services/videoGen/poster.js', () => ({ updateVideoPoster: effects.videoPoster }));+vi.mock('../services/videoUpload.js', () => ({+ saveUploadedGalleryVideo: effects.upload, saveUploadedGalleryVideoFile: effects.uploadFile,+}));+vi.mock('../services/imageGen/cleanGpu.js', () => ({+ enqueueGpuClean: effects.gpuClean,+ readGpuCleanResult: vi.fn(), getGpuCleanStatus: vi.fn(), saveGpuCleanToGallery: vi.fn(),+}));+// Observed, not doubled: the remote-open image clean runs the real sharp pass.+vi.mock('../lib/imageClean.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, cleanImageBuffer: vi.fn(actual.cleanImageBuffer) };+});+// Unrelated service effects remain unreachable when mounting target handlers.+vi.mock('../services/codeAnimation/stages.js', () => ({}));+vi.mock('../services/codeAnimation/soundtrack.js', () => ({}));+vi.mock('../services/codeAnimation/soundAssets.js', () => ({}));+vi.mock('../services/codeAnimation/preflight.js', () => ({}));+vi.mock('../services/codeAnimation/package.js', () => ({}));+vi.mock('../services/codeAnimation/projects.js', () => ({}));+vi.mock('../services/mediaPromptRefiner.js', () => ({}));+vi.mock('../services/mediaPromptHistory.js', () => ({}));+vi.mock('../services/mediaPromptFromMedia.js', () => ({}));+vi.mock('../services/moodBoardStyleSynthesis.js', () => ({}));+vi.mock('../services/moodBoardCompositeStyle.js', () => ({}));+vi.mock('../services/moodBoard/analyzeJob.js', () => ({}));+vi.mock('../services/moodBoard/generateMore.js', () => ({}));+vi.mock('../services/sprites/records.js', () => ({}));+vi.mock('../services/sprites/importer.js', () => ({}));+vi.mock('../services/sprites/reference.js', () => ({}));+vi.mock('../services/sprites/assetPrompt.js', () => ({}));+vi.mock('../services/sprites/localAnimationRender.js', () => ({}));+vi.mock('../services/sprites/animationTrackWorkflow.js', () => ({}));+vi.mock('../services/sprites/animationTrackCrud.js', () => ({}));+vi.mock('../services/sprites/atlas.js', () => ({}));+vi.mock('../services/sprites/publish.js', () => ({}));+vi.mock('../services/sprites/assets.js', () => ({}));+vi.mock('../services/videoGen/local.js', () => ({ BYOV_RUNTIME_INFO: {}, getHistoryItem: vi.fn() }));+vi.mock('../services/videoGen/batch.js', () => ({ MAX_VIDEO_BATCH_SIZE: 8 }));+vi.mock('../services/videoGen/prepareParams.js', () => ({ cleanupMultipartTemp: vi.fn(), validateVideoRetryParams: vi.fn() }));+vi.mock('../services/videoGen/runtimeInstaller.js', () => ({}));+vi.mock('../services/videoGen/upscaleJob.js', () => ({}));+vi.mock('../services/videoGen/trimStart.js', () => ({}));+vi.mock('../services/videoGen/submitJob.js', () => ({}));+vi.mock('../services/videoGen/reactor.js', () => ({}));+vi.mock('../services/videoGen/modelCache.js', () => ({}));+vi.mock('../services/videoGen/displayPower.js', () => ({}));+vi.mock('../services/hfDownloadStream.js', () => ({}));+vi.mock('../services/userActions.js', () => ({ recordUserAction: vi.fn() }));++import { authGate, hostControlBodyGate, hostControlRouteGate } from '../services/authGate.js';+import { createSession } from '../services/auth.js';+import { cleanImageBuffer } from '../lib/imageClean.js';+import codeAnimationRoutes from './codeAnimation.js';+import htmlCompositionRoutes from './htmlComposition.js';+import imageCleanRoutes from './imageClean.js';+import mediaJobRoutes from './mediaJobs.js';+import mediaCollectionRoutes from './mediaCollections.js';+import moodBoardRoutes from './moodBoard.js';+import spriteRoutes from './sprites.js';+import videoGenRoutes from './videoGen.js';++const id = '00000000-0000-4000-8000-000000000001';+const runId = 'walk-south-0123abcd';+// [method, path, body, effect observed on success, success status]+const operations = [+ ['post', `/api/code-animation/${id}/export`, {}, effects.codeExport, 202],+ ['post', `/api/code-animation/jobs/${id}/poster`, {}, effects.codePoster, 200],+ ['post', '/api/html-composition/render', { directory: 'compositions/example' }, effects.enqueue, 202],+ ['post', `/api/media-jobs/holds/${id}/resume`, {}, effects.resumeHold, 200],+ ['post', '/api/media/collections/example-collection/localize', {}, effects.pull, 202],+ ['post', '/api/mood-boards/example-board/collage', {}, effects.collage, 200],+ ['post', '/api/mood-boards/example-board/items/example-item/extract-frames', { count: 3 }, effects.frames, 200],+ ['post', '/api/mood-boards/example-board/pinterest/import', { url: 'https://www.pinterest.com/example/example-board/' }, effects.pinterest, 200],+ ['post', '/api/sprites/example-sprite/walk/postprocess', { runId }, effects.postprocess, 200],+ ['post', `/api/sprites/example-sprite/walk/runs/${runId}/source-frames/extract`, {}, effects.sourceFrames, 200],+ ['post', '/api/sprites/example-sprite/walk/trim', { runId, enabledColumns: [0, 1] }, effects.trim, 201],+ ['patch', `/api/video-gen/history/${id}/poster`, { atSec: 1.5 }, effects.videoPoster, 200],+ ['post', '/api/video-gen/upload', { data: 'AAAA', filename: 'clip.mp4' }, effects.upload, 200],+];+const peerHeaders = {+ [PEER_AUTH_HEADER]: derivePeerAuthToken('a'.repeat(32), 'example-instance'),+ [PEER_INSTANCE_HEADER]: 'example-instance',+};+const basicHeaders = { Authorization: 'Basic ' + Buffer.from(':example-password').toString('base64') };+const spoofedProxies = [+ ['192.0.2.10', {}],+ ['127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }],+ ['192.0.2.10', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '127.0.0.1' }],+];+const credentialRefusals = [+ [{}, 401, 'AUTH_REQUIRED'],+ [basicHeaders, 403, 'HOST_CONTROL_FORBIDDEN'],+ [peerHeaders, 403, 'PEER_SCOPE_FORBIDDEN'],+];+const authorizedCallers = async () => [+ [false, '127.0.0.1', {}],+ [true, '192.0.2.10', { Authorization: `Bearer ${(await createSession()).token}` }],+ [true, '192.0.2.10', { Authorization: `Bearer ${(await createSession({ label: 'agent' })).token}` }],+];++const appFor = (address = '192.0.2.10') => {+ const app = express();+ app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });+ next();+ });+ app.use(authGate, hostControlRouteGate, express.json(), hostControlBodyGate);+ app.use('/api/code-animation', codeAnimationRoutes);+ app.use('/api/html-composition', htmlCompositionRoutes);+ app.use('/api/image-clean', imageCleanRoutes);+ app.use('/api/media-jobs', mediaJobRoutes);+ app.use('/api/media/collections', mediaCollectionRoutes);+ app.use('/api/mood-boards', moodBoardRoutes);+ app.use('/api/sprites', spriteRoutes);+ app.use('/api/video-gen', videoGenRoutes);+ app.use(errorMiddleware);+ return app;+};+const call = (app, [method, path, body], headers = {}) => {+ const pending = request(app)[method](path);+ for (const [name, value] of Object.entries(headers)) pending.set(name, value);+ return pending.send(body);+};+const expectNoEffects = () => {+ for (const effect of Object.values(effects)) expect(effect).not.toHaveBeenCalled();+};++beforeEach(() => {+ vi.clearAllMocks();+ auth.enabled = false;+});++describe('media pre-guard host-process authority (#13055)', () => {+ it('refuses remote password-free callers, spoofed-proxy and case variants before any host process', async () => {+ for (const operation of operations) {+ for (const [address, headers] of spoofedProxies) {+ for (const path of [operation[1], operation[1].toUpperCase() + '/']) {+ const response = await call(appFor(address), [operation[0], path, operation[2]], headers);+ expect([response.status, response.body.code], path).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ }+ }+ const multipart = await request(appFor()).post('/api/video-gen/upload')+ .set('Content-Type', 'multipart/form-data; boundary=example-boundary')+ .send('--example-boundary--');+ expect([multipart.status, multipart.body.code]).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ expectNoEffects();+ });++ it('requires authentication with a password and denies legacy Basic and scoped-peer credentials', async () => {+ auth.enabled = true;+ for (const operation of operations) {+ for (const [headers, status, code] of credentialRefusals) {+ const response = await call(appFor(), operation, headers);+ expect([response.status, response.body.code], operation[1]).toEqual([status, code]);+ }+ }+ expectNoEffects();+ });++ it('keeps working for local callers, operator sessions and delegated agent sessions', async () => {+ for (const [enabled, address, headers] of await authorizedCallers()) {+ auth.enabled = enabled;+ for (const operation of operations) {+ const effect = operation[3];+ const previousCalls = effect.mock.calls.length;+ const response = await call(appFor(address), operation, headers);+ expect(response.status, `${operation[1]}: ${JSON.stringify(response.body)}`).toBe(operation[4]);+ // Localize answers 202 and pulls in the background.+ await vi.waitFor(() => expect(effect).toHaveBeenCalledTimes(previousCalls + 1));+ }+ }+ expect(effects.enqueue).toHaveBeenLastCalledWith({ kind: 'html-composition', params: { directory: 'compositions/example' } });+ expect(effects.resumeHold).toHaveBeenLastCalledWith(id);+ expect(effects.pull).toHaveBeenLastCalledWith('example-peer', [{ kind: 'video', filename: 'example-video.mp4' }], { includeMismatched: false });+ expect(effects.videoPoster).toHaveBeenLastCalledWith(id, 1.5);+ expect(effects.upload).toHaveBeenLastCalledWith('AAAA', 'clip.mp4');+ });+});++// The mode rides in the query, so the handler (not the route list) gates the+// GPU pass; the in-process sharp passes must stay open to a remote caller.+describe('standalone image clean GPU authority (#13055)', () => {+ let png;+ const clean = (app, query, headers = {}) => {+ const pending = request(app).post(`/api/image-clean${query}`).set('Content-Type', 'application/octet-stream');+ for (const [name, value] of Object.entries(headers)) pending.set(name, value);+ return pending.send(png);+ };++ beforeAll(async () => {+ png = await sharp({ create: { width: 64, height: 64, channels: 3, background: { r: 200, g: 100, b: 50 } } }).png().toBuffer();+ });++ it('refuses a remote GPU clean before any image work or queueing', async () => {+ for (const query of ['?diffusion=gpu', '?diffusion=flux']) {+ for (const [address, headers] of spoofedProxies) {+ const response = await clean(appFor(address), query, headers);+ expect([response.status, response.body.code], query).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ }+ auth.enabled = true;+ for (const [headers, status, code] of credentialRefusals) {+ const response = await clean(appFor(), '?diffusion=gpu', headers);+ expect([response.status, response.body.code]).toEqual([status, code]);+ }+ expect(cleanImageBuffer).not.toHaveBeenCalled();+ expect(effects.gpuClean).not.toHaveBeenCalled();+ });++ it('queues the GPU clean for local callers, operator sessions and delegated agent sessions', async () => {+ for (const [enabled, address, headers] of await authorizedCallers()) {+ auth.enabled = enabled;+ const response = await clean(appFor(address), '?diffusion=gpu', headers);+ expect(response.status, JSON.stringify(response.body)).toBe(202);+ expect(response.body).toMatchObject({ mode: 'gpu', jobId: '22222222-2222-4222-8222-222222222222' });+ }+ expect(effects.gpuClean).toHaveBeenCalledTimes(3);+ });++ it('keeps the in-process sharp clean open to a remote password-free caller', async () => {+ for (const query of ['', '?diffusion=light']) {+ const response = await clean(appFor(), query);+ expect(response.status, `${query}: ${response.text}`).toBe(200);+ expect(response.headers['content-type']).toBe('image/png');+ expect(JSON.parse(response.headers['x-clean-report']).steps.some(({ step }) => step === 'diffusion')).toBe(query !== '');+ }+ expect(cleanImageBuffer).toHaveBeenCalledTimes(2);+ expect(effects.gpuClean).not.toHaveBeenCalled();+ });+});diff --git a/server/routes/hostControlPreGuardMessaging.test.js b/server/routes/hostControlPreGuardMessaging.test.jsnew file mode 100644index 0000000000..62228a4244--- /dev/null+++ b/server/routes/hostControlPreGuardMessaging.test.js@@ -0,0 +1,210 @@+import { EventEmitter } from 'node:events';+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';+import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-messaging-authority-') }));+afterAll(cleanupTempDataRoots);++// Beeper chat writes, Messages sync/refresh/fetch-full (the operator's signed-in+// Outlook/Teams tab) and mail-draft approval, including its PUT and Review-queue+// spellings, need operator authority (#13055). Real routers behind the real+// gates; the Beeper, Messages and Review services are doubled so nothing+// reaches Beeper, a browser tab or the draft store.+const auth = vi.hoisted(() => ({ enabled: false }));+const effects = vi.hoisted(() => ({+ createConversation: vi.fn(async () => ({ id: 'example-conversation' })),+ archive: vi.fn(async () => ({ id: 'example-conversation', isArchived: true })),+ lowPriority: vi.fn(async () => ({ id: 'example-conversation', isLowPriority: true })),+ sync: vi.fn(async () => ({ success: true, newMessages: 0 })),+ getMessage: vi.fn(async () => ({ id: 'example-message' })),+ refresh: vi.fn(async () => ({ success: true })),+ getAccount: vi.fn(async () => ({ id: 'example-account', type: 'outlook', name: 'Example Mail' })),+ getMessages: vi.fn(async () => ({ messages: [{ id: 'example-message', bodyFull: false }] })),+ refreshMany: vi.fn(async () => ({ updated: 1 })),+ updateDraft: vi.fn(async (id, updates) => ({ id, status: 'draft', ...updates })),+ approve: vi.fn(async (id) => ({ id, status: 'approved' })),+ resolveQueueItem: vi.fn(async () => ({ resolved: true })),+}));+vi.mock('../services/auth.js', async (importOriginal) => ({+ ...await importOriginal(),+ isAuthEnabled: vi.fn(async () => auth.enabled),+ verifyPassword: vi.fn(async () => true),+}));+vi.mock('../services/settings.js', () => ({+ settingsEvents: new EventEmitter(), getSettings: vi.fn(async () => ({})), updateSettingsWith: vi.fn(),+}));+vi.mock('../services/instanceIdentity.js', () => ({+ loadData: vi.fn(async () => ({ peers: [{+ id: 'example-peer', instanceId: 'example-instance', enabled: true, syncSecret: 'a'.repeat(32),+ }] })),+}));+vi.mock('../services/beeperSync.js', () => ({+ runBeeperSweep: vi.fn(), createBeeperConversation: effects.createConversation,+}));+vi.mock('../services/beeperConversations.js', () => ({+ listConversations: vi.fn(), getConversation: vi.fn(), listMessages: vi.fn(), listNetworks: vi.fn(),+ markConversationSeen: vi.fn(), purgeConversation: vi.fn(),+ setConversationArchived: effects.archive, setConversationLowPriority: effects.lowPriority,+}));+vi.mock('../services/beeperStatus.js', () => ({ getBeeperStatus: vi.fn(), checkBeeperConnection: vi.fn() }));+vi.mock('../services/beeperOAuth.js', () => ({+ completeBeeperOAuth: vi.fn(), connectWithPastedToken: vi.fn(), disconnectBeeper: vi.fn(), startBeeperOAuth: vi.fn(),+}));+vi.mock('../services/beeperOutbox.js', () => ({+ clearOutboxBreaker: vi.fn(), createOutboxEntry: vi.fn(), discardOutboxEntry: vi.fn(),+ reconcileOutboxEntry: vi.fn(), listOutboxEntries: vi.fn(), sendOutboxEntry: vi.fn(),+}));+vi.mock('../services/beeperAttachments.js', () => ({+ backfillAttachments: vi.fn(), ensureAttachmentBytes: vi.fn(), getAttachment: vi.fn(),+ getAttachmentSummary: vi.fn(), setAttachmentKeep: vi.fn(),+}));+vi.mock('../services/messageSync.js', async (importOriginal) => ({+ ...await importOriginal(),+ syncAccount: effects.sync, getMessage: effects.getMessage, refreshMessage: effects.refresh,+ getMessages: effects.getMessages, refreshMessages: effects.refreshMany,+}));+vi.mock('../services/messageAccounts.js', async (importOriginal) => ({+ ...await importOriginal(), getAccount: effects.getAccount,+}));+vi.mock('../services/messageDrafts.js', async (importOriginal) => ({+ ...await importOriginal(), updateDraft: effects.updateDraft, approveDraft: effects.approve,+}));+vi.mock('../services/review.js', () => ({ reviewEvents: { emit: vi.fn() } }));+vi.mock('../services/reviewQueue.js', () => ({+ buildQueue: vi.fn(), MAX_REVIEW_QUEUE_SNOOZE_MS: 30 * 24 * 60 * 60 * 1000,+ resolveQueueItem: effects.resolveQueueItem, triageQueueItem: vi.fn(), promoteAskQueueItem: vi.fn(),+}));++import { authGate, hostControlBodyGate, hostControlRouteGate } from '../services/authGate.js';+import { createSession } from '../services/auth.js';+import beeperRoutes from './beeper.js';+import messagesRoutes from './messages.js';+import reviewRoutes from './review.js';++const ACCOUNT = '00000000-0000-4000-8000-000000000001';+const DRAFT = '22222222-2222-4222-8222-222222222222';+// Whole-route gates: the case/trailing-slash spelling must be refused too.+const operations = [+ ['post', '/api/beeper/conversations', { accountId: 'example-account', participantId: 'example-participant' }, effects.createConversation, 201],+ ['post', `/api/beeper/conversations/${ACCOUNT}/archive`, { archived: true }, effects.archive, 200],+ ['post', `/api/beeper/conversations/${ACCOUNT}/low-priority`, { lowPriority: true }, effects.lowPriority, 200],+ ['post', `/api/messages/sync/${ACCOUNT}`, {}, effects.sync, 200],+ ['post', `/api/messages/${ACCOUNT}/example-message/refresh`, {}, effects.refresh, 200],+ ['post', `/api/messages/fetch-full/${ACCOUNT}`, { force: false }, effects.refreshMany, 200],+ ['post', `/api/messages/drafts/${DRAFT}/approve`, {}, effects.approve, 200],+];+// Body gates: the same approval reached by a PUT status or a Review-queue row.+const approvals = [+ ['put', `/api/messages/drafts/${DRAFT}`, { status: 'approved' }, effects.updateDraft, 200],+ ['post', '/api/review/queue/resolve', { id: `drafts:${DRAFT}`, operation: 'approve' }, effects.resolveQueueItem, 200],+ ['post', '/api/review/queue/resolve', { id: `DRAFTS:${DRAFT}` }, effects.resolveQueueItem, 200],+];+const gated = [...operations, ...approvals];++const appFor = (address = '192.0.2.10') => {+ const app = express();+ app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });+ next();+ });+ app.use(authGate, hostControlRouteGate, express.json(), hostControlBodyGate);+ app.use('/api/beeper', beeperRoutes);+ app.use('/api/messages', messagesRoutes);+ app.use('/api/review', reviewRoutes);+ app.use(errorMiddleware);+ return app;+};+const send = (app, [method, path, body], headers = {}) => {+ const pending = request(app)[method](path);+ for (const [name, value] of Object.entries(headers)) pending.set(name, value);+ return pending.send(body);+};+const expectNoEffects = () => {+ for (const [name, effect] of Object.entries(effects)) expect(effect, name).not.toHaveBeenCalled();+};++beforeEach(() => {+ vi.clearAllMocks();+ auth.enabled = false;+});++describe('Beeper chat writes, Messages browser sync and draft approval operator authority (#13055)', () => {+ it('refuses remote password-free callers, spoofed-proxy and URL variants before any effect', async () => {+ for (const operation of gated) {+ const [method, path, body] = operation;+ const targets = operations.includes(operation) ? [path, path.toUpperCase() + '/'] : [path];+ for (const [address, headers] of [+ ['192.0.2.10', {}],+ ['127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }],+ ['192.0.2.10', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '127.0.0.1' }],+ ]) {+ for (const target of targets) {+ const response = await send(appFor(address), [method, target, body], headers);+ expect([response.status, response.body.code], `${method} ${target} ${JSON.stringify(body)}`)+ .toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ }+ }+ expectNoEffects();+ });++ it('requires authentication with a password and denies legacy Basic and scoped-peer credentials', async () => {+ auth.enabled = true;+ for (const operation of gated) {+ for (const [headers, status, code] of [+ [{}, 401, 'AUTH_REQUIRED'],+ [{ Authorization: 'Basic ' + Buffer.from(':example-password').toString('base64') }, 403, 'HOST_CONTROL_FORBIDDEN'],+ [{+ [PEER_AUTH_HEADER]: derivePeerAuthToken('a'.repeat(32), 'example-instance'),+ [PEER_INSTANCE_HEADER]: 'example-instance',+ }, 403, 'PEER_SCOPE_FORBIDDEN'],+ ]) {+ const response = await send(appFor(), operation, headers);+ expect([response.status, response.body.code], `${operation[1]} ${JSON.stringify(operation[2])}`).toEqual([status, code]);+ }+ }+ expectNoEffects();+ });++ it('keeps working for local callers, operator sessions and delegated agent sessions', async () => {+ const operator = await createSession();+ const agent = await createSession({ label: 'agent' });+ for (const [enabled, address, headers] of [+ [false, '127.0.0.1', {}],+ [true, '192.0.2.10', { Cookie: `portos_auth=${operator.token}` }],+ [true, '192.0.2.10', { Authorization: `Bearer ${agent.token}` }],+ ]) {+ auth.enabled = enabled;+ for (const operation of gated) {+ const [, path, body, effect, status] = operation;+ const before = effect.mock.calls.length;+ const response = await send(appFor(address), operation, headers);+ expect(response.status, `${path} ${JSON.stringify(body)}: ${JSON.stringify(response.body)}`).toBe(status);+ expect(effect, path).toHaveBeenCalledTimes(before + 1);+ }+ }+ expect(effects.createConversation).toHaveBeenLastCalledWith({ accountId: 'example-account', participantId: 'example-participant' });+ expect(effects.archive).toHaveBeenLastCalledWith(ACCOUNT, true);+ expect(effects.refreshMany).toHaveBeenLastCalledWith(ACCOUNT, ['example-message']);+ expect(effects.updateDraft).toHaveBeenLastCalledWith(DRAFT, { status: 'approved' });+ expect(effects.resolveQueueItem).toHaveBeenLastCalledWith(`DRAFTS:${DRAFT}`);+ });++ it('leaves draft content edits and non-draft Review rows open to a remote caller', async () => {+ for (const [operation, effect, args] of [+ [['put', `/api/messages/drafts/${DRAFT}`, { body: 'Example reply text' }], effects.updateDraft, [DRAFT, { body: 'Example reply text' }]],+ [['post', '/api/review/queue/resolve', { id: 'memory:example-memory', operation: 'approve' }], effects.resolveQueueItem, ['memory:example-memory', 'approve']],+ [['post', '/api/review/queue/resolve', { id: 'threads:example-thread', operation: 'complete' }], effects.resolveQueueItem, ['threads:example-thread', 'complete']],+ ]) {+ const response = await send(appFor(), operation);+ expect(response.status, `${operation[1]} ${JSON.stringify(response.body)}`).toBe(200);+ expect(effect).toHaveBeenLastCalledWith(...args);+ }+ });+});diff --git a/server/routes/hostControlPreGuardOps.test.js b/server/routes/hostControlPreGuardOps.test.jsnew file mode 100644index 0000000000..48f7112990--- /dev/null+++ b/server/routes/hostControlPreGuardOps.test.js@@ -0,0 +1,261 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { EventEmitter } from 'node:events';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';+import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-pre-guard-ops-') }));+afterAll(cleanupTempDataRoots);++// Agent-context MCP tool calls, social persona creation, CoS resets and the+// PM2 health sweep, plus the per-request splits that arm or retarget work+// (enabling a subscription family, Docker containment and agent-context+// settings, the Brain digest provider) require operator authority (#13055).+// Real routers behind the real gates; every effect is doubled at its service.+const auth = vi.hoisted(() => ({ enabled: false }));+const storedBrain = vi.hoisted(() => ({ defaultProvider: 'example-cli', defaultModel: 'example-model', scheduledReviewsEnabled: false }));+const effects = vi.hoisted(() => ({+ mcpTool: vi.fn(async () => ({ content: [{ type: 'text', text: '{}' }] })),+ createAgent: vi.fn(async (data) => ({ id: 'example-agent', ...data })),+ clearCooldown: vi.fn(async () => ({ cooldownUntil: null })),+ healthCheck: vi.fn(async () => ({ healthy: true })),+ backfill: vi.fn(async () => 0),+ resetLearning: vi.fn(async (taskType) => ({ reset: true, taskType })),+ resetSchedule: vi.fn(async () => ({ success: true })),+ setSubscription: vi.fn(async (family, enabled) => ({ applied: true, family, enabled })),+ updateFeature: vi.fn(async (id, enabled) => ({ features: [{ id, enabled }] })),+ reconcileDocker: vi.fn(async () => ({})),+ saveSettings: vi.fn(async (update) => update({})),+ updateAssignment: vi.fn(async (id) => ({ id })),+ updateBrainMeta: vi.fn(async (data) => ({ ...data })),+}));++vi.mock('../services/auth.js', async (importOriginal) => ({+ ...await importOriginal(),+ isAuthEnabled: vi.fn(async () => auth.enabled),+ verifyPassword: vi.fn(async () => true),+}));+vi.mock('../services/settings.js', () => ({+ settingsEvents: new EventEmitter(),+ getSettings: vi.fn(async () => ({})),+ updateSettingsWith: effects.saveSettings,+}));+vi.mock('../services/instanceIdentity.js', () => ({+ ensureInstanceId: vi.fn(async () => 'example-self'),+ loadData: vi.fn(async () => ({ peers: [{+ id: 'example-peer', instanceId: 'example-instance', enabled: true, syncSecret: 'a'.repeat(32),+ }] })),+}));+vi.mock('../services/agentContextMcp.js', () => ({+ getAgentContextManifest: vi.fn(async () => ({+ enabled: true, configurationValid: true, profile: 'minimal', scopes: [], actions: {}, tools: [],+ })),+ callAgentContextTool: effects.mcpTool,+}));+vi.mock('../services/agentPersonalities.js', () => ({ createAgent: effects.createAgent }));+vi.mock('../services/agentPersonalityGenerator.js', () => ({}));+vi.mock('../services/history.js', () => ({ logAction: vi.fn(async () => {}) }));+vi.mock('../services/appActivity.js', () => ({ clearAppCooldown: effects.clearCooldown }));+vi.mock('../services/cosHealthMonitor.js', () => ({ runHealthCheck: effects.healthCheck }));+vi.mock('../services/taskLearning.js', () => ({+ backfillFromHistory: effects.backfill, resetTaskTypeLearning: effects.resetLearning,+}));+vi.mock('../services/reviewQueue.js', () => ({ __resetAlertsCache: vi.fn() }));+vi.mock('../services/taskSchedule.js', () => ({ resetExecutionHistory: effects.resetSchedule }));+vi.mock('../services/subscriptions.js', () => ({+ setSubscriptionEnabled: effects.setSubscription,+ getSubscriptionOverview: vi.fn(async () => ({ subscriptions: [] })),+}));+vi.mock('../services/instanceFeatures.js', () => ({ updateInstanceFeature: effects.updateFeature }));+vi.mock('../services/dockerContainment.js', () => ({ reconcileDockerContainment: effects.reconcileDocker }));+vi.mock('../services/aiAssignments.js', () => ({ updateAiAssignment: effects.updateAssignment }));+vi.mock('../services/brain.js', () => ({+ loadMeta: vi.fn(async () => ({ ...storedBrain })),+ updateMeta: effects.updateBrainMeta,+}));+vi.mock('../services/providers.js', () => ({+ getProviderById: vi.fn(async (id) => ({ id, type: 'api', models: [] })),+}));+vi.mock('../services/mediaJobQueue/index.js', () => ({+ setCodexParallelLimit: vi.fn(), CODEX_PARALLEL_MIN: 1, CODEX_PARALLEL_MAX: 8, CODEX_PARALLEL_DEFAULT: 2,+}));+// Unrelated service graphs the mounted routers import; their handlers are not reached.+vi.mock('../services/cos.js', () => ({}));+vi.mock('../services/cosReports.js', () => ({}));+vi.mock('../services/claudeChangelog.js', () => ({}));+vi.mock('../services/cosAgentLifecycle.js', () => ({}));+vi.mock('../services/cosAgentArchive.js', () => ({}));+vi.mock('../services/cosAgentIndex.js', () => ({}));+vi.mock('../services/cosAgentFeedback.js', () => ({}));+vi.mock('../services/agentOrchestrator.js', () => ({}));+vi.mock('../services/weeklyDigest.js', () => ({}));+vi.mock('../services/cosState.js', () => ({}));+vi.mock('../services/userActionScheduleLog.js', () => ({}));+vi.mock('../services/maintenanceRun.js', () => ({}));+vi.mock('../services/usage.js', () => ({}));+vi.mock('../services/claudeCodeUsage.js', () => ({}));+vi.mock('../services/claudeCodeTranscriptUsage.js', () => ({}));+vi.mock('../services/providerUsage.js', () => ({}));+vi.mock('../services/peerUsage.js', () => ({}));+vi.mock('../services/usageFleetBilling.js', () => ({}));+vi.mock('../services/subscriptionCosts.js', () => ({}));+vi.mock('../services/credentialInventory.js', () => ({}));+vi.mock('../services/eidoverse.js', () => ({}));+vi.mock('../services/eidoverseHost.js', () => ({}));++import { authGate, hostControlBodyGate, hostControlRouteGate } from '../services/authGate.js';+import { createSession } from '../services/auth.js';+import agentContextRoutes from './agentContextMcp.js';+import agentPersonalitiesRoutes from './agentPersonalities.js';+import cosAgentRoutes from './cosAgentRoutes.js';+import cosReportRoutes from './cosReportRoutes.js';+import cosLearningRoutes from './cosLearningRoutes.js';+import cosScheduleRoutes from './cosScheduleRoutes.js';+import usageRoutes from './usage.js';+import settingsRoutes from './settings.js';+import brainSettingsRoutes from './brainSettings.js';++const REMOTE = '192.0.2.10';+const brainPut = (body) => ['put', '/api/brain/settings', body, effects.updateBrainMeta, 200];+// [method, path, gated body, effect, success status, open twin]. A row with an+// open twin is gated per request (body gate or handler) and the twin is the+// same route with a body that stays open; the others are gated whole.+const operations = [+ ['post', '/api/agent-context/mcp', {+ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'brain_capture', arguments: {} },+ }, effects.mcpTool, 200],+ ['post', '/api/agents/personalities', {+ userId: 'example-user', name: 'Example Bot', personality: { style: 'casual' },+ }, effects.createAgent, 201],+ ['post', '/api/cos/app-activity/example-app/clear-cooldown', {}, effects.clearCooldown, 200],+ ['post', '/api/cos/health/check', {}, effects.healthCheck, 200],+ ['post', '/api/cos/learning/backfill', {}, effects.backfill, 200],+ ['post', '/api/cos/learning/reset/task:example', {}, effects.resetLearning, 200],+ ['post', '/api/cos/schedule/reset', { taskType: 'example-task' }, effects.resetSchedule, 200],+ ['put', '/api/usage/subscriptions/enabled', { family: 'claude', enabled: true }, effects.setSubscription, 200,+ ['put', '/api/usage/subscriptions/enabled', { family: 'claude', enabled: false }]],+ // Disabling also tears containment down through the docker CLI.+ ['put', '/api/settings/features/docker-containment', { enabled: false }, effects.updateFeature, 200,+ ['put', '/api/settings/features/post', { enabled: false }]],+ ['put', '/api/settings', { agentContext: { enabled: true } }, effects.saveSettings, 200,+ ['put', '/api/settings', { hideFirstRunCard: true }]],+ ['put', '/api/settings/ai-assignments/brain.default', { providerId: 'example-cli', model: 'example-model' }, effects.updateAssignment, 200,+ ['put', '/api/settings/ai-assignments/settings.creativeDirector.treatment', { providerId: 'example-cli', model: 'example-model' }]],+ [...brainPut({ scheduledReviewsEnabled: true }), ['put', '/api/brain/settings', { confidenceThreshold: 0.7, dailyDigestTime: '07:00' }]],+ [...brainPut({ defaultProvider: 'example-other' }), ['put', '/api/brain/settings', { defaultProvider: 'example-cli', defaultModel: 'example-model' }]],+ [...brainPut({ defaultModel: 'example-other-model' }), ['put', '/api/brain/settings', { defaultModel: 'example-model' }]],+];+const isWholeRoute = (operation) => operation[5] === undefined;+// The agent-context router admits loopback sockets only, so its operator and+// agent sessions arrive locally; a password still makes the session the grant.+const callerAddress = ([, path], address) => (path.startsWith('/api/agent-context/') ? '127.0.0.1' : address);++const appFor = (address = REMOTE) => {+ const app = express();+ app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });+ next();+ });+ app.use(authGate, hostControlRouteGate, express.json(), hostControlBodyGate);+ app.use('/api/agent-context', agentContextRoutes);+ app.use('/api/agents/personalities', agentPersonalitiesRoutes);+ app.use('/api/cos', cosAgentRoutes, cosReportRoutes, cosLearningRoutes, cosScheduleRoutes);+ app.use('/api/usage', usageRoutes);+ app.use('/api/settings', settingsRoutes);+ app.use('/api/brain', brainSettingsRoutes);+ app.use(errorMiddleware);+ return app;+};+// The MCP transport requires this Accept header; the other routes ignore it.+const call = (app, [method, path, body], headers = {}) => {+ const pending = request(app)[method](path).set('Accept', 'application/json, text/event-stream');+ for (const [name, value] of Object.entries(headers)) pending.set(name, value);+ return pending.send(body);+};+const expectNoEffects = () => {+ for (const effect of Object.values(effects)) expect(effect).not.toHaveBeenCalled();+};++beforeEach(() => {+ vi.clearAllMocks();+ auth.enabled = false;+});++describe('pre-guard audit operations and policy splits require operator authority (#13055)', () => {+ it('refuses remote password-free callers, spoofed-proxy and case variants before any effect', async () => {+ for (const operation of operations) {+ const targets = isWholeRoute(operation) ? [operation[1], operation[1].toUpperCase() + '/'] : [operation[1]];+ for (const [address, headers] of [+ [REMOTE, {}],+ ['127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: REMOTE }],+ [REMOTE, { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '127.0.0.1' }],+ ]) {+ for (const target of targets) {+ const response = await call(appFor(address), [operation[0], target, operation[2]], headers);+ expect([response.status, response.body.code], `${target} ${JSON.stringify(operation[2])}`)+ .toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ }+ }+ expectNoEffects();+ });++ it('requires authentication with a password and denies legacy Basic and scoped-peer credentials', async () => {+ auth.enabled = true;+ for (const operation of operations) {+ for (const [headers, status, code] of [+ [{}, 401, 'AUTH_REQUIRED'],+ [{ Authorization: 'Basic ' + Buffer.from(':example-password').toString('base64') }, 403, 'HOST_CONTROL_FORBIDDEN'],+ [{+ [PEER_AUTH_HEADER]: derivePeerAuthToken('a'.repeat(32), 'example-instance'),+ [PEER_INSTANCE_HEADER]: 'example-instance',+ }, 403, 'PEER_SCOPE_FORBIDDEN'],+ ]) {+ const response = await call(appFor(callerAddress(operation, REMOTE)), operation, headers);+ expect([response.status, response.body.code], `${operation[1]} ${JSON.stringify(operation[2])}`)+ .toEqual([status, code]);+ }+ }+ expectNoEffects();+ });++ it('keeps working for local callers, operator sessions and delegated agent sessions', async () => {+ const operator = await createSession();+ const agent = await createSession({ label: 'agent' });+ for (const [enabled, address, headers] of [+ [false, '127.0.0.1', {}],+ [true, REMOTE, { Authorization: `Bearer ${operator.token}` }],+ [true, REMOTE, { Authorization: `Bearer ${agent.token}` }],+ ]) {+ auth.enabled = enabled;+ for (const operation of operations) {+ const previousCalls = operation[3].mock.calls.length;+ const response = await call(appFor(callerAddress(operation, address)), operation, headers);+ expect(response.status, `${operation[1]}: ${JSON.stringify(response.body)}`).toBe(operation[4]);+ expect(operation[3]).toHaveBeenCalledTimes(previousCalls + 1);+ }+ }+ expect(effects.mcpTool).toHaveBeenLastCalledWith('brain_capture', {}, expect.anything(), expect.anything());+ expect(effects.resetLearning).toHaveBeenLastCalledWith('task:example');+ expect(effects.setSubscription).toHaveBeenLastCalledWith('claude', true);+ expect(effects.reconcileDocker).toHaveBeenLastCalledWith({ enabled: false, reason: 'feature-toggle' });+ expect(effects.updateBrainMeta).toHaveBeenLastCalledWith({ defaultModel: 'example-other-model' });+ });++ it('leaves the open body of each split route to a remote password-free caller', async () => {+ for (const operation of operations.filter((row) => !isWholeRoute(row))) {+ const previousCalls = operation[3].mock.calls.length;+ const response = await call(appFor(), operation[5]);+ expect(response.status, `${operation[5][1]}: ${JSON.stringify(response.body)}`).toBe(operation[4]);+ expect(operation[3]).toHaveBeenCalledTimes(previousCalls + 1);+ }+ expect(effects.setSubscription).toHaveBeenCalledWith('claude', false);+ expect(effects.updateFeature).toHaveBeenCalledWith('post', false);+ expect(effects.reconcileDocker).not.toHaveBeenCalled();+ expect(effects.updateBrainMeta).toHaveBeenCalledWith({ defaultProvider: 'example-cli', defaultModel: 'example-model' });+ });+});diff --git a/server/routes/hostControlPreGuardPrivacy.test.js b/server/routes/hostControlPreGuardPrivacy.test.jsnew file mode 100644index 0000000000..9c64bcb96f--- /dev/null+++ b/server/routes/hostControlPreGuardPrivacy.test.js@@ -0,0 +1,184 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { EventEmitter } from 'node:events';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';+import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-privacy-authority-') }));+afterAll(cleanupTempDataRoots);++// Privacy broker scans, opt-out and verification passes, arming the broker+// recheck (route body or the `privacy` settings slice), broker consent grants,+// YouTube scrapes in the managed browser and Google Calendar goal blocks need+// operator authority (#13055). Real routers behind the real gates; the first+// service boundary is doubled so no browser, mail, DB or Google call runs.+const auth = vi.hoisted(() => ({ enabled: false }));+const effects = vi.hoisted(() => ({+ scan: vi.fn(async () => ({ scanned: 0 })),+ optOut: vi.fn(async () => ({ submitted: 0 })),+ verify: vi.fn(async () => ({ verified: 0 })),+ updateSettings: vi.fn(async (mutate) => mutate({})),+ restartRecheck: vi.fn(async () => {}),+ recordConsent: vi.fn(async (grant) => ({ id: 'example-grant', ...grant })),+ youtubeSync: vi.fn(async () => ({ ok: true })),+ playlistSync: vi.fn(async () => ({ ok: true })),+ scheduleGoal: vi.fn(async () => ({ scheduled: 0 })),+ rescheduleGoal: vi.fn(async () => ({ scheduled: 0 })),+ settingsWrite: vi.fn((req, res) => res.json({ saved: Object.keys(req.body) })),+}));+vi.mock('../services/auth.js', async (importOriginal) => ({+ ...await importOriginal(),+ isAuthEnabled: vi.fn(async () => auth.enabled),+ verifyPassword: vi.fn(async () => true),+}));+vi.mock('../services/settings.js', () => ({+ settingsEvents: new EventEmitter(),+ getSettings: vi.fn(async () => ({})),+ updateSettingsWith: effects.updateSettings,+}));+vi.mock('../services/instanceIdentity.js', () => ({+ loadData: vi.fn(async () => ({ peers: [{+ id: 'example-peer', instanceId: 'example-instance', enabled: true, syncSecret: 'a'.repeat(32),+ }] })),+}));+vi.mock('../services/privacyScan.js', () => ({ runScanPass: effects.scan }));+vi.mock('../services/privacyOptOut.js', () => ({ runOptOutPass: effects.optOut, runVerificationPass: effects.verify }));+vi.mock('../services/privacyRecheckScheduler.js', () => ({+ restartPrivacyRecheckScheduler: effects.restartRecheck,+ getPrivacyRecheckStatus: vi.fn(async () => ({ enabled: false })),+}));+vi.mock('../services/privacySubjects.js', () => ({ recordConsent: effects.recordConsent }));+vi.mock('../services/privacyVault.js', () => ({}));+vi.mock('../services/privacyOrgs.js', () => ({}));+vi.mock('../services/privacyBrokers.js', () => ({}));+vi.mock('../services/privacyChanges.js', () => ({}));+vi.mock('../services/youtubeSync.js', () => ({ runSync: effects.youtubeSync }));+vi.mock('../services/youtubePlaylists.js', () => ({ syncYoutubePlaylists: effects.playlistSync }));+vi.mock('../services/goalCalendarScheduler.js', () => ({+ scheduleTimeBlocks: effects.scheduleGoal, rescheduleTimeBlocks: effects.rescheduleGoal,+}));+vi.mock('../services/identity.js', () => ({}));++import { authGate, hostControlBodyGate, hostControlRouteGate } from '../services/authGate.js';+import { createSession } from '../services/auth.js';+import privacyRoutes from './privacy.js';+import youtubeRoutes from './youtube.js';+import identityRoutes from './identity.js';++const subjectId = '22222222-2222-4222-8222-222222222222';+const consents = `/api/privacy/subjects/${subjectId}/consents`;+const schedule = '/api/privacy/optout/schedule';+// [method, path, body, effect, status]; the last six rows are body gates.+const operations = [+ ['post', '/api/privacy/scan', {}, effects.scan, 200],+ ['post', '/api/privacy/optout', {}, effects.optOut, 200],+ ['post', '/api/privacy/optout/verify', {}, effects.verify, 200],+ ['post', '/api/youtube/sync', {}, effects.youtubeSync, 200],+ ['post', '/api/youtube/playlists/sync', {}, effects.playlistSync, 200],+ ['post', '/api/digital-twin/identity/goals/example-goal/schedule', {}, effects.scheduleGoal, 200],+ ['post', '/api/digital-twin/identity/goals/example-goal/reschedule', {}, effects.rescheduleGoal, 200],+ ['put', schedule, { enabled: true }, effects.restartRecheck, 200],+ ['put', schedule, { autoApproveOptOutEmails: true }, effects.restartRecheck, 200],+ ['put', schedule, { autoSubmitWebForms: true }, effects.restartRecheck, 200],+ ['put', schedule, { cronExpression: '0 3 * * 1' }, effects.restartRecheck, 200],+ ['post', consents, { scope: 'broker_scan', method: 'verbal' }, effects.recordConsent, 201],+ ['post', consents, { scope: 'broker_optout', method: 'verbal' }, effects.recordConsent, 201],+ ['put', '/api/settings', { privacy: { recheck: { enabled: true } } }, effects.settingsWrite, 200],+];+const appFor = (address = '192.0.2.10') => {+ const app = express();+ app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });+ next();+ });+ app.use(authGate, hostControlRouteGate, express.json(), hostControlBodyGate);+ app.use('/api/privacy', privacyRoutes);+ app.use('/api/youtube', youtubeRoutes);+ app.use('/api/digital-twin/identity', identityRoutes);+ // Stand-in for the settings store: the body gate, not the store, is under test.+ app.put('/api/settings', effects.settingsWrite);+ app.use(errorMiddleware);+ return app;+};+const call = (app, [method, path, body], headers = {}) => {+ const pending = request(app)[method](path);+ for (const [name, value] of Object.entries(headers)) pending.set(name, value);+ return pending.send(body);+};+const expectNoEffects = () => {+ for (const effect of Object.values(effects)) expect(effect).not.toHaveBeenCalled();+};++beforeEach(() => {+ vi.clearAllMocks();+ auth.enabled = false;+});++describe('privacy broker, YouTube and goal calendar operator authority (#13055)', () => {+ it('refuses remote password-free callers, spoofed-proxy and case variants before any effect', async () => {+ for (const [method, path, body] of operations) {+ for (const [address, headers, target] of [+ ['192.0.2.10', {}, path],+ ['127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }, path],+ ['192.0.2.10', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '127.0.0.1' }, path],+ ['192.0.2.10', {}, path.toUpperCase() + '/'],+ ]) {+ const response = await call(appFor(address), [method, target, body], headers);+ expect([response.status, response.body.code], `${target} ${JSON.stringify(body)}`).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ }+ expectNoEffects();+ });++ it('requires authentication with a password and denies legacy Basic and scoped-peer credentials', async () => {+ auth.enabled = true;+ for (const operation of operations) {+ for (const [headers, status, code] of [+ [{}, 401, 'AUTH_REQUIRED'],+ [{ Authorization: 'Basic ' + Buffer.from(':example-password').toString('base64') }, 403, 'HOST_CONTROL_FORBIDDEN'],+ [{+ [PEER_AUTH_HEADER]: derivePeerAuthToken('a'.repeat(32), 'example-instance'),+ [PEER_INSTANCE_HEADER]: 'example-instance',+ }, 403, 'PEER_SCOPE_FORBIDDEN'],+ ]) {+ const response = await call(appFor(), operation, headers);+ expect([response.status, response.body.code], `${operation[1]} ${JSON.stringify(operation[2])}`).toEqual([status, code]);+ }+ }+ expectNoEffects();+ });++ it('keeps working for local callers, operator sessions and delegated agent sessions', async () => {+ const operator = await createSession();+ const agent = await createSession({ label: 'agent' });+ for (const [enabled, address, headers] of [+ [false, '127.0.0.1', {}],+ [true, '192.0.2.10', { Authorization: `Bearer ${operator.token}` }],+ [true, '192.0.2.10', { Authorization: `Bearer ${agent.token}` }],+ ]) {+ auth.enabled = enabled;+ for (const operation of operations) {+ const [, path, body, effect, status] = operation;+ const before = effect.mock.calls.length;+ const response = await call(appFor(address), operation, headers);+ expect(response.status, `${path}: ${JSON.stringify(response.body)}`).toBe(status);+ expect(effect, `${path} ${JSON.stringify(body)}`).toHaveBeenCalledTimes(before + 1);+ }+ }+ expect(effects.rescheduleGoal).toHaveBeenLastCalledWith('example-goal');+ expect(effects.recordConsent).toHaveBeenLastCalledWith(expect.objectContaining({ subjectId, scope: 'broker_optout' }));+ });++ it('leaves disarming the recheck and a local-vault consent open to a remote caller', async () => {+ const disarm = await call(appFor(), ['put', schedule, { enabled: false, autoApproveOptOutEmails: false, autoSubmitWebForms: false }]);+ expect(disarm.status, JSON.stringify(disarm.body)).toBe(200);+ expect(effects.restartRecheck).toHaveBeenCalledTimes(1);+ const vault = await call(appFor(), ['post', consents, { scope: 'pii_vault', method: 'verbal' }]);+ expect(vault.status, JSON.stringify(vault.body)).toBe(201);+ expect(effects.recordConsent).toHaveBeenCalledWith(expect.objectContaining({ subjectId, scope: 'pii_vault' }));+ });+});diff --git a/server/routes/hostControlPreGuardStoryWorld.test.js b/server/routes/hostControlPreGuardStoryWorld.test.jsnew file mode 100644index 0000000000..29ced37a2f--- /dev/null+++ b/server/routes/hostControlPreGuardStoryWorld.test.js@@ -0,0 +1,216 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { EventEmitter } from 'node:events';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';+import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-story-world-authority-') }));+afterAll(cleanupTempDataRoots);++// Continuous-video renders, fal.ai browser automation, editorial custom-check+// prompts run unattended, Creative Director hand-off, Eidoverse travel and the+// world config/controller surfaces that act as the CoS identity now need+// operator authority (#13055). Real routers behind the real gates; each effect+// is doubled at its service boundary, so an admitted request is a call on it.+const auth = vi.hoisted(() => ({ enabled: false }));+const effects = vi.hoisted(() => ({+ continuousVideo: vi.fn(async () => ({})),+ falVideo: vi.fn(async () => ({ jobId: 'example-job' })),+ saveSettings: vi.fn(),+ cdSend: vi.fn(async () => ({ project: { id: 'example-project' } })),+ depart: vi.fn(async () => ({ url: 'https://example.com/visit' })),+ worldConfig: vi.fn(async () => ({ config: {} })),+ controllerConfig: vi.fn(async () => ({ outcome: 'updated', install: { id: 'example-beacon' } })),+ install: vi.fn(async () => ({ outcome: 'installed', install: { id: 'example-beacon' } })),+ arm: vi.fn(async () => ({ outcome: 'updated', install: { id: 'example-beacon' } })),+}));+const settings = vi.hoisted(() => ({+ pipelineEditorialChecks: { customChecks: [{+ id: 'custom.example-check', label: 'Example check', prompt: 'Flag example problems',+ scope: 'issue', category: 'custom', severityDefault: 'medium',+ }] },+}));+vi.mock('../services/auth.js', async (importOriginal) => ({+ ...await importOriginal(),+ isAuthEnabled: vi.fn(async () => auth.enabled),+ verifyPassword: vi.fn(async () => true),+}));+vi.mock('../services/settings.js', () => ({+ settingsEvents: new EventEmitter(),+ getSettings: vi.fn(async () => settings),+ updateSettingsWith: effects.saveSettings,+}));+vi.mock('../services/instanceIdentity.js', () => ({+ ensureInstanceId: vi.fn(async () => 'example-self'),+ loadData: vi.fn(async () => ({ peers: [{+ id: 'example-peer', instanceId: 'example-instance', enabled: true, syncSecret: 'a'.repeat(32),+ }] })),+}));+vi.mock('../services/videoGen/continuousVideo.js', () => ({+ generateContinuousVideoEpisode: effects.continuousVideo,+ composeEpisodeClips: vi.fn(() => [{ prompt: 'Example clip' }]),+ attachEpisodeSseClient: vi.fn(() => false),+ CONTINUOUS_VIDEO_BACKENDS: ['local', 'reactor', 'fal'],+}));+vi.mock('../lib/videoPromptLinter.js', () => ({ lintClips: vi.fn(() => ({ pass: true })) }));+vi.mock('../services/fableLoom/index.js', () => ({ startFalVideoAutomation: effects.falVideo }));+vi.mock('../services/writersRoom/liveDirector.js', () => ({ sendToCreativeDirector: effects.cdSend }));+vi.mock('../services/writersRoom/local.js', () => ({}));+vi.mock('../services/writersRoom/evaluator.js', () => ({}));+vi.mock('../services/writersRoom/polish.js', () => ({}));+vi.mock('../services/writersRoom/syncedReview.js', () => ({}));+vi.mock('../services/writersRoom/characters.js', () => ({}));+vi.mock('../services/writersRoom/castAugment.js', () => ({}));+vi.mock('../services/writersRoom/places.js', () => ({}));+vi.mock('../services/writersRoom/objects.js', () => ({}));+vi.mock('../services/writersRoom/promoteToPipeline.js', () => ({}));+vi.mock('../services/catalogExtraction.js', () => ({}));+vi.mock('../services/eidoverseTravel.js', () => ({ visitEidoversePeer: effects.depart }));+vi.mock('../services/eidoverseWorld.js', () => ({ updateEidoverseWorldConfig: effects.worldConfig }));+vi.mock('../services/eidoverseControllerRuntime.js', () => ({+ installEidoverseController: effects.install,+ setEidoverseControllerArmed: effects.arm,+ updateEidoverseControllerConfig: effects.controllerConfig,+ summarizeControllerInstall: vi.fn((install) => install),+}));+vi.mock('../services/eidoverseFoundationLedger.js', () => ({}));+vi.mock('../services/eidoverseControllerRegistry.js', () => ({}));++import { authGate, hostControlBodyGate, hostControlRouteGate } from '../services/authGate.js';+import { createSession } from '../services/auth.js';+import continuousVideoRoutes from './continuousVideoEpisode.js';+import fableLoomRoutes from './fableLoom.js';+import pipelineEditorialRoutes from './pipeline/editorial.js';+import writersRoomRoutes from './writersRoom.js';+import travelRoutes from './eidoverseTravelRoutes.js';+import worldRoutes from './eidoverseWorldRoutes.js';++const customCheck = { label: 'Example check', prompt: 'Flag example problems' };+const beaconInstall = { id: 'example-beacon', controllerId: 'ambient-beacon' };+// [method, path, gated body, effect, status, open body (body-gated rows only)]+const operations = [+ ['post', '/api/continuous-video', {+ scenes: [{ lines: [{ type: 'action', text: 'Example action at dusk.' }] }], bible: {},+ }, effects.continuousVideo, 200],+ ['post', '/api/fableloom/example-loom/episodes/example-episode/nodes/example-node/fal-video',+ { prompt: 'Example scene direction, slow push-in.' }, effects.falVideo, 202],+ ['post', '/api/pipeline/editorial/custom-checks', customCheck, effects.saveSettings, 201],+ ['patch', '/api/pipeline/editorial/custom-checks/custom.example-check',+ { ...customCheck, prompt: 'Flag example problems more strictly' }, effects.saveSettings, 200],+ ['post', '/api/writers-room/works/wr-work-example/cd-bridge/send', { proposal: {+ logline: 'Example logline', synopsis: 'Example synopsis.',+ scenes: [{ intent: 'Open on the harbor', prompt: 'Wide shot of an example harbor at dawn', durationSeconds: 5 }],+ } }, effects.cdSend, 201],+ ['post', '/api/eidoverse/travel/depart', { peerId: 'example-peer' }, effects.depart, 200],+ ['put', '/api/eidoverse/world/config', { world: 'example-world', humanName: 'Example Human' }, effects.worldConfig, 200],+ ['patch', '/api/eidoverse/world/controllers/example-beacon/config',+ { config: { label: 'beacon', announce: true } }, effects.controllerConfig, 200],+ ['post', '/api/eidoverse/world/controllers',+ { ...beaconInstall, deliverEffects: true, config: { label: 'beacon', announce: true } },+ effects.install, 200, beaconInstall],+ ['patch', '/api/eidoverse/world/controllers/example-beacon', { armed: true }, effects.arm, 200, { armed: false }],+];++const appFor = (address = '192.0.2.10') => {+ const app = express();+ app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });+ next();+ });+ app.use(authGate, hostControlRouteGate, express.json(), hostControlBodyGate);+ app.use('/api/continuous-video', continuousVideoRoutes);+ app.use('/api/fableloom', fableLoomRoutes);+ app.use('/api/pipeline', pipelineEditorialRoutes);+ app.use('/api/writers-room', writersRoomRoutes);+ app.use('/api/eidoverse/travel', travelRoutes);+ app.use('/api/eidoverse/world', worldRoutes);+ app.use(errorMiddleware);+ return app;+};+const call = (app, [method, path, body], headers = {}) => {+ const pending = request(app)[method](path);+ for (const [name, value] of Object.entries(headers)) pending.set(name, value);+ return pending.send(body);+};+const expectNoEffects = () => {+ for (const effect of Object.values(effects)) expect(effect).not.toHaveBeenCalled();+};++beforeEach(() => {+ vi.clearAllMocks();+ auth.enabled = false;+ effects.saveSettings.mockImplementation(async (mutate) => mutate(settings));+});++describe('story, video and Eidoverse world operator authority (#13055)', () => {+ it('refuses remote password-free callers, spoofed-proxy and case variants before any effect', async () => {+ for (const [method, path, body] of operations) {+ for (const [address, headers, target] of [+ ['192.0.2.10', {}, path],+ ['127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }, path],+ ['192.0.2.10', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '127.0.0.1' }, path],+ ['192.0.2.10', {}, path.toUpperCase() + '/'],+ ]) {+ const response = await call(appFor(address), [method, target, body], headers);+ expect([response.status, response.body.code], `${method} ${target}`).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ }+ expectNoEffects();+ });++ it('requires authentication with a password and denies legacy Basic and scoped-peer credentials', async () => {+ auth.enabled = true;+ for (const operation of operations) {+ for (const [headers, status, code] of [+ [{}, 401, 'AUTH_REQUIRED'],+ [{ Authorization: 'Basic ' + Buffer.from(':example-password').toString('base64') }, 403, 'HOST_CONTROL_FORBIDDEN'],+ [{+ [PEER_AUTH_HEADER]: derivePeerAuthToken('a'.repeat(32), 'example-instance'),+ [PEER_INSTANCE_HEADER]: 'example-instance',+ }, 403, 'PEER_SCOPE_FORBIDDEN'],+ ]) {+ const response = await call(appFor(), operation, headers);+ expect([response.status, response.body.code], `${operation[0]} ${operation[1]}`).toEqual([status, code]);+ }+ }+ expectNoEffects();+ });++ it('keeps working for local callers, operator sessions and delegated agent sessions', async () => {+ const operator = await createSession();+ const agent = await createSession({ label: 'agent' });+ for (const [enabled, address, headers] of [+ [false, '127.0.0.1', {}],+ [true, '192.0.2.10', { Cookie: `portos_auth=${operator.token}` }],+ [true, '192.0.2.10', { Authorization: `Bearer ${agent.token}` }],+ ]) {+ auth.enabled = enabled;+ for (const [method, path, body, effect, status] of operations) {+ const before = effect.mock.calls.length;+ const response = await call(appFor(address), [method, path, body], headers);+ expect(response.status, `${method} ${path}: ${JSON.stringify(response.body)}`).toBe(status);+ expect(effect, `${method} ${path}`).toHaveBeenCalledTimes(before + 1);+ }+ }+ expect(effects.depart).toHaveBeenLastCalledWith({ peerId: 'example-peer', agent: false });+ expect(effects.install).toHaveBeenLastCalledWith(+ expect.objectContaining({ id: 'example-beacon', deliverEffects: true }), { installedBy: 'user' });+ expect(effects.arm).toHaveBeenLastCalledWith('example-beacon', true);+ expect(effects.controllerConfig).toHaveBeenLastCalledWith('example-beacon', { label: 'beacon', announce: true });+ });++ it('leaves a non-delivering install and disarming open to a remote password-free caller', async () => {+ for (const [method, path, , effect, status, openBody] of operations.filter((operation) => operation[5])) {+ const response = await call(appFor(), [method, path, openBody]);+ expect(response.status, `${method} ${path}: ${JSON.stringify(response.body)}`).toBe(status);+ expect(effect).toHaveBeenCalledTimes(1);+ }+ expect(effects.install).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'example-beacon', deliverEffects: false }), { installedBy: 'user' });+ expect(effects.arm).toHaveBeenCalledWith('example-beacon', false);+ });+});diff --git a/server/routes/hostControlPreGuardTracksData.test.js b/server/routes/hostControlPreGuardTracksData.test.jsnew file mode 100644index 0000000000..48fd35fb0a--- /dev/null+++ b/server/routes/hostControlPreGuardTracksData.test.js@@ -0,0 +1,268 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { unlink } from 'node:fs/promises';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';+import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-pre-guard-tracks-data-') }));+afterAll(cleanupTempDataRoots);++// Pre-guard audit remainder (#13055): track uploads and takes, the Suno import,+// SuperCollider renders, game asset publication, a conflict restore, the repo+// probe, data archive, Signal sync and setup check, snapshot apply and LoRA+// checkpoint promotion each run host work. Real routers behind the real gates;+// only the service effect is doubled, and it never runs for a refused caller.+const auth = vi.hoisted(() => ({ enabled: false }));+const effects = vi.hoisted(() => ({+ getTrack: vi.fn(async (id) => ({ id })),+ importUpload: vi.fn(),+ probeDuration: vi.fn(async () => 4),+ attachAudio: vi.fn(async (id) => ({ id })),+ codeTake: vi.fn(async () => ({ filename: 'example.ogg' })),+ superColliderTake: vi.fn(async () => ({ filename: 'example.ogg' })),+ sunoImport: vi.fn(async () => ({ jobId: 'example-suno-job' })),+ chiptuneRender: vi.fn(async () => ({ track: {} })),+ superColliderStatus: vi.fn(async () => ({ ready: true, state: 'ready' })),+ enqueue: vi.fn(async () => ({ jobId: 'example-render', status: 'queued' })),+ resolveConflict: vi.fn(async () => ({ resolved: true })),+ publishArtwork: vi.fn(async () => ({ published: true })),+ publishMusic: vi.fn(async () => ({ published: true })),+ archive: vi.fn(async () => ({ archived: true })),+ getRun: vi.fn(async (id) => ({ id, status: 'completed' })),+ promote: vi.fn(async () => ({ promoted: true })),+ signalSetup: vi.fn(async () => ({ ok: true })),+ signalSync: vi.fn(async () => ({ ok: true })),+ applyRemote: vi.fn(async () => ({ applied: true })),+ probe: vi.fn(() => false),+}));+vi.mock('../services/auth.js', async (importOriginal) => ({+ ...await importOriginal(),+ isAuthEnabled: vi.fn(async () => auth.enabled),+ verifyPassword: vi.fn(async () => true),+}));+vi.mock('../services/settings.js', () => ({+ settingsEvents: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ getSettings: vi.fn(async () => ({})),+}));+vi.mock('../services/instanceIdentity.js', () => ({+ ensureInstanceId: vi.fn(async () => 'example-self'),+ loadData: vi.fn(async () => ({ peers: [{+ id: 'example-peer', instanceId: 'example-instance', enabled: true, syncSecret: 'a'.repeat(32),+ }] })),+}));+// The repo probe's first host read is `existsSync(path)`; every other caller+// keeps the real filesystem.+vi.mock('fs', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, existsSync: (path) => (path === '/example/project' ? effects.probe(path) : actual.existsSync(path)) };+});+vi.mock('../services/tracks/index.js', async () => ({+ ...await import('../services/tracks/logic.js'),+ getTrack: effects.getTrack,+}));+vi.mock('../services/pipeline/musicLibrary.js', () => ({+ MUSIC_UPLOAD_MAX_BYTES: 1024 * 1024,+ isSupportedMusicUpload: () => true,+ assertSafeMusicFilename: vi.fn(),+ importUploadedTrack: effects.importUpload,+}));+vi.mock('../lib/ffmpeg.js', () => ({ probeVideoDuration: effects.probeDuration }));+vi.mock('../services/trackAudioAttach.js', () => ({ attachAudioAsRender: effects.attachAudio }));+vi.mock('../services/trackSunoImport.js', () => ({ startSunoImport: effects.sunoImport }));+vi.mock('../services/chiptune.js', () => ({ renderChiptuneTrack: effects.chiptuneRender }));+vi.mock('../services/musicCode.js', () => ({+ MUSIC_CODE_MAX: 20000,+ saveCodeTakeToTrack: effects.codeTake,+ saveSuperColliderTakeToTrack: effects.superColliderTake,+}));+vi.mock('../services/trackAlbumMembership.js', () => ({}));+vi.mock('../services/trackYoutubeImport.js', () => ({}));+vi.mock('../services/musicWaveform.js', () => ({}));+vi.mock('../services/superColliderRuntime.js', () => ({ getSuperColliderStatus: effects.superColliderStatus }));+vi.mock('../services/superColliderRender.js', () => ({ superColliderSourceHash: () => 'example-source-hash' }));+vi.mock('../services/mediaJobQueue/index.js', () => ({ enqueueJob: effects.enqueue }));+vi.mock('../lib/conflictJournal.js', () => ({ isBaseHashPersistBlocked: vi.fn(async () => false) }));+vi.mock('../services/conflictJournalResolver.js', () => ({+ ERR_NOT_FOUND: 'CONFLICT_JOURNAL_NOT_FOUND',+ ERR_VALIDATION: 'CONFLICT_JOURNAL_VALIDATION',+ ERR_TARGET_GONE: 'CONFLICT_TARGET_GONE',+ resolveConflict: effects.resolveConflict,+}));+vi.mock('../services/games/index.js', () => ({+ publishGameArtwork: effects.publishArtwork,+ publishGameMusic: effects.publishMusic,+}));+vi.mock('../services/dataManager.js', () => ({ archiveCategory: effects.archive }));+vi.mock('../services/loraTraining/index.js', () => ({+ getRunRequired: effects.getRun,+ promoteCheckpoint: effects.promote,+}));+vi.mock('../services/loraTraining/runtimes.js', () => ({ TRAINING_DEFAULTS: {} }));+vi.mock('../lib/pythonSetup.js', () => ({}));+vi.mock('../services/signalSync.js', () => ({ checkSetup: effects.signalSetup, runSync: effects.signalSync }));+vi.mock('../services/dataSync.js', () => ({ applyRemote: effects.applyRemote }));+vi.mock('../services/sharing/tombstoneGc.js', () => ({ TOMBSTONE_GRACE_MS: 24 * 60 * 60 * 1000 }));+vi.mock('../services/sharing/peerPullAuthorization.js', () => ({}));+vi.mock('../services/pm2.js', () => ({}));+vi.mock('../services/aiDetect.js', () => ({}));++import { authGate, hostControlBodyGate, hostControlRouteGate } from '../services/authGate.js';+import { createSession } from '../services/auth.js';+import tracksRoutes from './tracks.js';+import superColliderRoutes from './superCollider.js';+import conflictJournalRoutes from './conflictJournal.js';+import gamesRoutes from './games.js';+import dataManagerRoutes from './dataManager.js';+import loraTrainingRoutes from './loraTraining.js';+import signalRoutes from './signal.js';+import dataSyncRoutes from './dataSync.js';+import detectRoutes from './detect.js';++effects.importUpload.mockImplementation(async (path) => {+ await unlink(path);+ return { filename: 'example.mp3', sizeBytes: 11 };+});++const BOUNDARY = 'example-boundary';+const multipart = (filename, mime, fields = {}) => ({+ contentType: `multipart/form-data; boundary=${BOUNDARY}`,+ bytes: Buffer.concat([+ ...Object.entries(fields).map(([name, value]) =>+ Buffer.from(`--${BOUNDARY}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`)),+ Buffer.from(`--${BOUNDARY}\r\nContent-Disposition: form-data; name="track"; filename="${filename}"\r\nContent-Type: ${mime}\r\n\r\n`),+ Buffer.from('RIFFexample'),+ Buffer.from(`\r\n--${BOUNDARY}--\r\n`),+ ]),+});++const trackId = '11111111-1111-4111-8111-111111111111';+const gameId = 'game-11111111-1111-4111-8111-111111111111';+const restore = ['post', '/api/conflict-journal/example-conflict-1/resolve', { action: 'restore-all' }, effects.resolveConflict, 200];+const operations = [+ ['post', `/api/tracks/${trackId}/audio/upload`, multipart('example.mp3', 'audio/mpeg', { source: 'upload' }), effects.attachAudio, 200],+ ['post', `/api/tracks/${trackId}/code/render`, multipart('example.wav', 'audio/wav', { prompt: 'Example take' }), effects.codeTake, 200],+ ['post', `/api/tracks/${trackId}/supercollider/take`, { jobId: 'example-job-0001' }, effects.superColliderTake, 200],+ ['post', '/api/tracks/import/suno', { url: 'https://suno.com/song/11111111-1111-4111-8111-111111111111' }, effects.sunoImport, 202],+ ['post', '/api/music/supercollider/render', { code: '{ SinOsc.ar(440) * 0.1 }', durationSec: 4 }, effects.enqueue, 202],+ ['post', `/api/games/${gameId}/artwork/artwork-1/publish`, {}, effects.publishArtwork, 200],+ ['post', `/api/games/${gameId}/music/music-1/publish`, {}, effects.publishMusic, 200],+ ['post', '/api/detect/repo', { path: '/example/project' }, effects.probe, 200],+ ['post', '/api/data/health/archive', { daysToKeep: 365 }, effects.archive, 200],+ ['post', '/api/signal/sync', {}, effects.signalSync, 200],+ ['get', '/api/signal/setup-check', undefined, effects.signalSetup, 200],+ ['post', '/api/sync/digitalTwin/apply', { data: {} }, effects.applyRemote, 200],+ ['post', '/api/lora-training/runs/run-example/promote-checkpoint', { step: 300 }, effects.promote, 200],+];++const appFor = (address = '192.0.2.10') => {+ const app = express();+ app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });+ next();+ });+ app.use(authGate, hostControlRouteGate, express.json(), hostControlBodyGate);+ app.use('/api/tracks', tracksRoutes);+ app.use('/api/music/supercollider', superColliderRoutes);+ app.use('/api/conflict-journal', conflictJournalRoutes);+ app.use('/api/games', gamesRoutes);+ app.use('/api/data', dataManagerRoutes);+ app.use('/api/lora-training', loraTrainingRoutes);+ app.use('/api/signal', signalRoutes);+ app.use('/api/sync', dataSyncRoutes);+ app.use('/api/detect', detectRoutes);+ app.use(errorMiddleware);+ return app;+};+const call = (app, [method, path, body], headers = {}) => {+ const pending = request(app)[method](path);+ for (const [name, value] of Object.entries(headers)) pending.set(name, value);+ if (body?.bytes) return pending.set('Content-Type', body.contentType).send(body.bytes);+ return body === undefined ? pending : pending.send(body);+};+const expectNoEffects = () => {+ for (const [name, effect] of Object.entries(effects)) expect(effect, name).not.toHaveBeenCalled();+};++beforeEach(() => {+ vi.clearAllMocks();+ auth.enabled = false;+});++describe('pre-guard audit remainder: tracks, renders, publication and host data (#13055)', () => {+ it('refuses remote password-free callers, spoofed-proxy and case variants before any effect', async () => {+ for (const operation of [...operations, restore]) {+ const [method, path, body] = operation;+ const targets = operation === restore ? [path] : [path, path.toUpperCase() + '/'];+ for (const [address, headers] of [+ ['192.0.2.10', {}],+ ['127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }],+ ['192.0.2.10', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '127.0.0.1' }],+ ]) {+ for (const target of targets) {+ const response = await call(appFor(address), [method, target, body], headers);+ expect([response.status, response.body.code], `${method} ${target}`).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ }+ }+ expectNoEffects();+ });++ it('requires authentication with a password and denies legacy Basic and scoped-peer credentials', async () => {+ auth.enabled = true;+ for (const operation of [...operations, restore]) {+ for (const [headers, status, code] of [+ [{}, 401, 'AUTH_REQUIRED'],+ [{ Authorization: 'Basic ' + Buffer.from(':example-password').toString('base64') }, 403, 'HOST_CONTROL_FORBIDDEN'],+ [{+ [PEER_AUTH_HEADER]: derivePeerAuthToken('a'.repeat(32), 'example-instance'),+ [PEER_INSTANCE_HEADER]: 'example-instance',+ }, 403, 'PEER_SCOPE_FORBIDDEN'],+ ]) {+ const response = await call(appFor(), operation, headers);+ expect([response.status, response.body.code], `${operation[0]} ${operation[1]}`).toEqual([status, code]);+ }+ }+ expectNoEffects();+ });++ it('keeps working for local callers, operator sessions and delegated agent sessions', async () => {+ const operator = await createSession();+ const agent = await createSession({ label: 'agent' });+ for (const [enabled, address, headers] of [+ [false, '127.0.0.1', {}],+ [true, '192.0.2.10', { Authorization: `Bearer ${operator.token}` }],+ [true, '192.0.2.10', { Authorization: `Bearer ${agent.token}` }],+ ]) {+ auth.enabled = enabled;+ for (const operation of [...operations, restore]) {+ const [method, path, , effect, status] = operation;+ const previousCalls = effect.mock.calls.length;+ const response = await call(appFor(address), operation, headers);+ expect(response.status, `${method} ${path}: ${JSON.stringify(response.body)}`).toBe(status);+ expect(effect, `${method} ${path}`).toHaveBeenCalledTimes(previousCalls + 1);+ }+ }+ expect(effects.importUpload).toHaveBeenLastCalledWith(expect.any(String), 'example.mp3');+ expect(effects.codeTake).toHaveBeenLastCalledWith(expect.objectContaining({ trackId, prompt: 'Example take' }));+ expect(effects.enqueue).toHaveBeenLastCalledWith({ kind: 'supercollider', params: expect.objectContaining({+ source: '{ SinOsc.ar(440) * 0.1 }', durationSec: 4,+ }) });+ expect(effects.archive).toHaveBeenLastCalledWith('health', { daysToKeep: 365 });+ expect(effects.applyRemote).toHaveBeenLastCalledWith('digitalTwin', {}, { portosMeta: undefined });+ expect(effects.promote).toHaveBeenLastCalledWith('run-example', 300);+ expect(effects.resolveConflict).toHaveBeenLastCalledWith('example-conflict-1', { action: 'restore-all' });+ });++ it('leaves a conflict discard and the deterministic chiptune render open to a remote caller', async () => {+ const discard = await call(appFor(), ['post', restore[1], { action: 'discard' }]);+ expect(discard.status, JSON.stringify(discard.body)).toBe(200);+ expect(effects.resolveConflict).toHaveBeenCalledExactlyOnceWith('example-conflict-1', { action: 'discard' });+ const chiptune = await call(appFor(), ['post', `/api/tracks/${trackId}/chiptune/render`, {}]);+ expect(chiptune.status, JSON.stringify(chiptune.body)).toBe(200);+ expect(effects.chiptuneRender).toHaveBeenCalledExactlyOnceWith({ trackId });+ });+});diff --git a/server/routes/hostControlPreGuardVoice.test.js b/server/routes/hostControlPreGuardVoice.test.jsnew file mode 100644index 0000000000..04faefb40e--- /dev/null+++ b/server/routes/hostControlPreGuardVoice.test.js@@ -0,0 +1,163 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';+import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-voice-authority-') }));+afterAll(cleanupTempDataRoots);++// The piper voice fetch runs the setup script (which can brew install) and+// whisper start launches whisper-server under PM2, so both need operator+// authority (#13055). Whisper stop and the TTS test, which runs an installed+// runtime on text, stay open. Real router behind the real gates; the voice+// services are doubled so no process starts.+const auth = vi.hoisted(() => ({ enabled: false }));+const storedVoice = vi.hoisted(() => ({ enabled: true, stt: { engine: 'whisper' }, tts: { engine: 'piper' } }));+const effects = vi.hoisted(() => ({+ piperFetch: vi.fn(async () => ({ downloaded: true })),+ startWhisper: vi.fn(async () => ({ started: true })),+}));+const open = vi.hoisted(() => ({+ stopWhisper: vi.fn(async () => {}),+ synthesize: vi.fn(async () => ({ wav: Buffer.from('RIFF'), latencyMs: 1 })),+}));+vi.mock('../services/auth.js', async (importOriginal) => ({+ ...await importOriginal(),+ isAuthEnabled: vi.fn(async () => auth.enabled),+ verifyPassword: vi.fn(async () => true),+}));+vi.mock('../services/settings.js', () => ({+ settingsEvents: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ getSettings: vi.fn(async () => ({})),+}));+vi.mock('../services/instanceIdentity.js', () => ({+ ensureInstanceId: vi.fn(async () => 'example-self'),+ loadData: vi.fn(async () => ({ peers: [{+ id: 'example-peer', instanceId: 'example-instance', enabled: true, syncSecret: 'a'.repeat(32),+ }] })),+}));+vi.mock('../services/voice/config.js', () => ({+ getVoiceConfig: vi.fn(async () => storedVoice),+ updateVoiceConfig: vi.fn(),+}));+vi.mock('../services/voice/bootstrap.js', () => ({+ downloadPiperVoice: effects.piperFetch,+ startWhisper: effects.startWhisper,+ stopWhisper: open.stopWhisper,+}));+vi.mock('../services/voice/tts.js', () => ({ synthesize: open.synthesize, VALID_ENGINES: new Set(['piper']) }));+vi.mock('../services/voice/piper-voices.js', () => ({ findPiperVoice: vi.fn(() => ({ id: 'en_US-example-medium' })) }));+vi.mock('../services/voice/health.js', () => ({ invalidateHealthCache: vi.fn() }));+vi.mock('../services/voice/proactiveSpeech.js', () => ({+ HHMM_RE: /^([01]\d|2[0-3]):[0-5]\d$/,+ MAX_PROACTIVE_TEXT_LEN: 500,+}));+// Unrelated voice services stay unreachable when mounting the router.+vi.mock('../services/voice/facetimeBridge.js', () => ({ probe: vi.fn(), call: vi.fn(), hangup: vi.fn() }));+vi.mock('../services/voice/profiles.js', () => ({}));+vi.mock('../services/voice/profileBenchmarks.js', () => ({}));+vi.mock('../services/voice/qwen3TtsRuntime.js', () => ({}));+vi.mock('../services/voice/fineTuning.js', () => ({}));++import { authGate, hostControlBodyGate, hostControlRouteGate } from '../services/authGate.js';+import { createSession } from '../services/auth.js';+import voiceRoutes from './voice.js';++const operations = [+ ['/api/voice/piper/fetch', { voice: 'en_US-example-medium' }, effects.piperFetch],+ ['/api/voice/whisper', { action: 'start' }, effects.startWhisper],+];++const appFor = (address = '192.0.2.10') => {+ const app = express();+ app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });+ next();+ });+ app.use(authGate, hostControlRouteGate, express.json(), hostControlBodyGate);+ app.use('/api/voice', voiceRoutes);+ app.use(errorMiddleware);+ return app;+};+const post = (app, [path, body], headers = {}) => {+ const pending = request(app).post(path);+ for (const [name, value] of Object.entries(headers)) pending.set(name, value);+ return pending.send(body);+};+const expectNoEffects = () => {+ for (const effect of Object.values(effects)) expect(effect).not.toHaveBeenCalled();+};++beforeEach(() => {+ vi.clearAllMocks();+ auth.enabled = false;+});++describe('voice runtime setup and whisper start operator authority (#13055)', () => {+ it('refuses remote password-free callers, spoofed-proxy and case variants before any runtime work', async () => {+ for (const [path, body] of operations) {+ for (const [address, headers, target] of [+ ['192.0.2.10', {}, path],+ ['127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }, path],+ ['192.0.2.10', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '127.0.0.1' }, path],+ ['192.0.2.10', {}, path.toUpperCase() + '/'],+ ]) {+ const response = await post(appFor(address), [target, body], headers);+ expect([response.status, response.body.code], target).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ }+ expectNoEffects();+ });++ it('requires authentication with a password and denies legacy Basic and scoped-peer credentials', async () => {+ auth.enabled = true;+ for (const operation of operations) {+ for (const [headers, status, code] of [+ [{}, 401, 'AUTH_REQUIRED'],+ [{ Authorization: 'Basic ' + Buffer.from(':example-password').toString('base64') }, 403, 'HOST_CONTROL_FORBIDDEN'],+ [{+ [PEER_AUTH_HEADER]: derivePeerAuthToken('a'.repeat(32), 'example-instance'),+ [PEER_INSTANCE_HEADER]: 'example-instance',+ }, 403, 'PEER_SCOPE_FORBIDDEN'],+ ]) {+ const response = await post(appFor(), operation, headers);+ expect([response.status, response.body.code], operation[0]).toEqual([status, code]);+ }+ }+ expectNoEffects();+ });++ it('keeps working for local callers, operator sessions and delegated agent sessions', async () => {+ const operator = await createSession();+ const agent = await createSession({ label: 'agent' });+ for (const [enabled, address, headers] of [+ [false, '127.0.0.1', {}],+ [true, '192.0.2.10', { Authorization: `Bearer ${operator.token}` }],+ [true, '192.0.2.10', { Authorization: `Bearer ${agent.token}` }],+ ]) {+ auth.enabled = enabled;+ for (const operation of operations) {+ const response = await post(appFor(address), operation, headers);+ expect(response.status, `${operation[0]}: ${JSON.stringify(response.body)}`).toBe(200);+ }+ }+ expect(effects.piperFetch).toHaveBeenCalledTimes(3);+ expect(effects.piperFetch).toHaveBeenLastCalledWith('en_US-example-medium', storedVoice);+ expect(effects.startWhisper).toHaveBeenCalledTimes(3);+ expect(effects.startWhisper).toHaveBeenLastCalledWith(storedVoice);+ });++ it('leaves whisper stop and the TTS test open to a remote password-free caller', async () => {+ const stop = await post(appFor(), ['/api/voice/whisper', { action: 'stop' }]);+ expect([stop.status, stop.body]).toEqual([200, { success: true, action: 'stop' }]);+ expect(open.stopWhisper).toHaveBeenCalledTimes(1);+ const spoken = await post(appFor(), ['/api/voice/test', { text: 'Hello' }]);+ expect(spoken.status).toBe(200);+ expect(open.synthesize).toHaveBeenCalledWith('Hello', { voice: undefined, engine: undefined });+ expectNoEffects();+ });+});diff --git a/server/routes/hostControlVoiceConfig.test.js b/server/routes/hostControlVoiceConfig.test.jsindex c0b86a5ca2..607518596f 100644--- a/server/routes/hostControlVoiceConfig.test.js+++ b/server/routes/hostControlVoiceConfig.test.js@@ -16,6 +16,14 @@ const voiceConfig = vi.hoisted(() => ({getVoiceConfig: vi.fn(),updateVoiceConfig: vi.fn(),}));+const bootstrap = vi.hoisted(() => ({+ reconcile: vi.fn(async () => ({})),+ verifyBinaries: vi.fn(),+ verifyModels: vi.fn(),+ downloadPiperVoice: vi.fn(),+ startWhisper: vi.fn(),+ stopWhisper: vi.fn(),+}));vi.mock('../services/auth.js', () => auth);vi.mock('../services/settings.js', () => ({settingsEvents: new EventEmitter(),@@ -29,14 +37,7 @@ vi.mock('../services/instanceIdentity.js', () => ({}));vi.mock('../services/voice/config.js', () => voiceConfig);vi.mock('../services/voice/health.js', () => ({ checkAll: vi.fn(), invalidateHealthCache: vi.fn() }));-vi.mock('../services/voice/bootstrap.js', () => ({- reconcile: vi.fn(async () => ({})),- verifyBinaries: vi.fn(),- verifyModels: vi.fn(),- downloadPiperVoice: vi.fn(),- startWhisper: vi.fn(),- stopWhisper: vi.fn(),-}));+vi.mock('../services/voice/bootstrap.js', () => bootstrap);vi.mock('../services/voice/tts.js', () => ({synthesize: vi.fn(),listVoices: vi.fn(),@@ -85,7 +86,8 @@ import voiceRoutes from './voice.js';const storedVoice = {enabled: true,- tts: { engine: 'piper', rate: 1 },+ stt: { engine: 'whisper', coreml: false, modelPath: 'example-models/example.bin' },+ tts: { engine: 'piper', rate: 1, piper: { voicePath: 'example-voices/example.onnx' } },llm: {provider: 'ollama',model: 'auto',@@ -132,6 +134,13 @@ const attackBodies = [{ llm: { tools: { enabled: true, maxIterations: 3 } } },{ llm: { codeAgent: { ...storedVoice.llm.codeAgent, enabled: true, provider: 'claude' } } },{ llm: { codeAgent: { ...storedVoice.llm.codeAgent, model: 'example-model' } } },+ // What the runtime reconcile starts, installs or reads (#13055).+ { enabled: false },+ { stt: { engine: 'web-speech' } },+ { stt: { coreml: true } },+ { stt: { modelPath: 'example-models/other.bin' } },+ { tts: { engine: 'qwen3-tts' } },+ { tts: { piper: { voicePath: 'example-voices/other.onnx' } } },];beforeEach(() => {@@ -141,7 +150,7 @@ beforeEach(() => {voiceConfig.updateVoiceConfig.mockImplementation(async patch => ({ ...storedVoice, ...patch, saved: true }));});-describe('voice config instruction authority (#10990)', () => {+describe('voice config instruction and runtime authority (#10990, #13055)', () => {it('refuses a password-free remote change to the prompt, persona, tools or coding agent', async () => {for (const body of attackBodies) {for (const path of ['/api/voice/config', '/API/Voice/Config/', '/api/voice/config//']) {@@ -156,6 +165,7 @@ describe('voice config instruction authority (#10990)', () => {const peerPresented = await putConfig(appFor(), attackBodies[0], '/api/voice/config', peerHeaders);expect([peerPresented.status, peerPresented.body.code]).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);expect(voiceConfig.updateVoiceConfig).not.toHaveBeenCalled();+ expect(bootstrap.reconcile).not.toHaveBeenCalled();});it('refuses legacy Basic when a password is set, and a scoped peer before the config is read', async () => {@@ -171,9 +181,11 @@ describe('voice config instruction authority (#10990)', () => {expect(voiceConfig.updateVoiceConfig).not.toHaveBeenCalled();});- it('lets the same remote caller resend the stored instructions while changing the TTS rate', async () => {+ it('lets the same remote caller resend the stored instructions and runtime keys while changing the TTS rate, without reconciling', async () => {const response = await putConfig(appFor(), {- tts: { rate: 1.25 },+ enabled: true,+ stt: { modelPath: 'example-models/example.bin', coreml: false, engine: 'whisper' },+ tts: { rate: 1.25, engine: 'piper', piper: { voicePath: 'example-voices/example.onnx' } },llm: {provider: 'example-provider',systemPrompt: storedVoice.llm.systemPrompt,@@ -193,9 +205,12 @@ describe('voice config instruction authority (#10990)', () => {expect(response.status, JSON.stringify(response.body)).toBe(200);expect(voiceConfig.updateVoiceConfig).toHaveBeenCalledTimes(1);expect(voiceConfig.getVoiceConfig).toHaveBeenCalledTimes(1);+ // PM2 and the setup script are host work: the record saves, the runtime is left as it was.+ expect(response.body.reconciliation).toEqual({ skipped: 'host-control' });+ expect(bootstrap.reconcile).not.toHaveBeenCalled();});- it('lets a local password-free caller, an operator session and a delegated agent session change every field', async () => {+ it('lets a local password-free caller, an operator session and a delegated agent session change every field and reconcile', async () => {for (const [enabled, address, headers] of [[false, '127.0.0.1', {}],[true, '192.0.2.10', { Cookie: 'portos_auth=example-session' }],@@ -205,9 +220,11 @@ describe('voice config instruction authority (#10990)', () => {for (const body of attackBodies) {const response = await putConfig(appFor(address), body, '/api/voice/config', headers);expect(response.status, JSON.stringify(response.body)).toBe(200);+ expect(response.body.reconciliation).toEqual({});}}expect(voiceConfig.getVoiceConfig).not.toHaveBeenCalled();expect(voiceConfig.updateVoiceConfig).toHaveBeenCalledTimes(attackBodies.length * 3);+ expect(bootstrap.reconcile).toHaveBeenCalledTimes(attackBodies.length * 3);});});diff --git a/server/routes/htmlComposition.test.js b/server/routes/htmlComposition.test.jsindex b2abd47a12..986395771b 100644--- a/server/routes/htmlComposition.test.js+++ b/server/routes/htmlComposition.test.js@@ -184,10 +184,12 @@ describe('motion skills install authority (#9439)', () => {expect(execFile).not.toHaveBeenCalled();});- it('keeps toolkit status and contained rendering available to a remote password-free caller', async () => {+ it('keeps toolkit status available to a remote password-free caller and gates rendering', async () => {const gatedApp = buildApp();expect((await request(gatedApp).get('/api/html-composition/toolkit')).status).toBe(200);- expect((await request(gatedApp).post('/api/html-composition/render').send({ directory: 'compositions/example' })).status).toBe(202);+ // Render runs the headless composition browser and ffmpeg (#13055).+ const render = await request(gatedApp).post('/api/html-composition/render').send({ directory: 'compositions/example' });+ expect([render.status, render.body.code]).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);expect(execFile).not.toHaveBeenCalled();});});diff --git a/server/routes/imageClean.js b/server/routes/imageClean.jsindex 49eeacc9cb..d3de06ba41 100644--- a/server/routes/imageClean.js+++ b/server/routes/imageClean.js@@ -13,6 +13,7 @@ import { z } from 'zod';import sharp from 'sharp';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';+import { assertHostControl } from '../services/authGate.js';import { cleanImageBuffer, CLEAN_LEVELS, compositeIgnoreZone, IGNORE_ZONE_FEATHER_DEFAULT } from '../lib/imageClean.js';import { applyLightRegen, computePixelDelta, REGEN_STRENGTH_MIN, REGEN_STRENGTH_MAX } from '../services/imageGen/regen.js';import { enqueueGpuClean, readGpuCleanResult, getGpuCleanStatus, saveGpuCleanToGallery } from '../services/imageGen/cleanGpu.js';@@ -117,6 +118,10 @@ router.post(raw({ type: RAW_TYPES, limit: RAW_LIMIT }),asyncHandler(async (req, res) => {const { metadata, denoise, diffusion, mask: hasMask, feather, strength, maxMp } = validateRequest(cleanQuerySchema, req.query);+ // The GPU pass queues a local Python FLUX job (#13055); the sync passes are+ // in-process sharp and stay open. The mode rides in the query, which the+ // body gate cannot see, so the handler checks it.+ if (diffusion === 'gpu') assertHostControl(req);const rawBody = Buffer.isBuffer(req.body) ? req.body : null;const { image: buffer, mask: maskBuffer } = splitMaskEnvelope(rawBody, hasMask);diff --git a/server/routes/imageClean.test.js b/server/routes/imageClean.test.jsindex a115d70723..ade6814aa2 100644--- a/server/routes/imageClean.test.js+++ b/server/routes/imageClean.test.js@@ -25,6 +25,9 @@ import imageCleanRoutes from './imageClean.js';// for image/* content-types, so the route's own express.raw() owns the body.const buildApp = () => {const app = express();+ // A local password-free caller holds host control, which the GPU pass needs+ // (#13055); hostControlPreGuardMedia.test.js covers the refusal.+ app.use((req, _res, next) => { req.portosAuthContext = { enabled: false }; next(); });app.use(express.json({ limit: '55mb' }));app.use('/api/image-clean', imageCleanRoutes);app.use(errorMiddleware);diff --git a/server/routes/managedVisitorAdmin.js b/server/routes/managedVisitorAdmin.jsnew file mode 100644index 0000000000..2c34571a21--- /dev/null+++ b/server/routes/managedVisitorAdmin.js@@ -0,0 +1,30 @@+import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { visitorCredentialSchema, visitorIdSchema } from '../lib/managedVisitorValidation.js';+import { getManagedVisitorBroker } from '../services/managedVisitors.js';+import { isCrossOrigin } from '../../lib/portosAuthCore.js';+import { validateRequest } from './managedVisitors.js';++// Owner provisioning lives in its own module so the route-graph scan, which+// keys a module by its router, credits these routes to this mount alone.+export function createManagedVisitorAdminRoutes(getBroker = getManagedVisitorBroker) {+ const router = Router();+ router.use((req, _res, next) => {+ // No app/peer credential acquires owner provisioning authority. Auth-off retains+ // PortOS's documented private-install owner API posture, with explicit CSRF protection.+ if (isCrossOrigin(req) || /^Bearer mv1_/i.test(req.headers.authorization ?? '')+ || req.portosAuthContext?.enabled && req.portosAuthContext.method !== 'session') {+ return next(new ServerError('Visitor credential management requires the owner interface.', { status: 403 }));+ }+ next();+ });+ router.get('/', asyncHandler(async (_req, res) => res.json({ credentials: await getBroker().listCredentials() })));+ router.post('/:appId/credential', asyncHandler(async (req, res) => {+ const id = await validateRequest(visitorIdSchema, req.params.appId), body = await validateRequest(visitorCredentialSchema, req.body);+ res.set('Cache-Control', 'no-store'); res.json(await getBroker().provision(id, body));+ }));+ router.delete('/:appId/credential', asyncHandler(async (req, res) => {+ res.json(await getBroker().revoke(await validateRequest(visitorIdSchema, req.params.appId)));+ }));+ return router;+}diff --git a/server/routes/managedVisitors.js b/server/routes/managedVisitors.jsindex 60bf22111b..fc48d0a700 100644--- a/server/routes/managedVisitors.js+++ b/server/routes/managedVisitors.js@@ -1,11 +1,10 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { visitorCancellationSchema, visitorCredentialSchema, visitorAdmissionSchema, visitorScopeSchema, visitorActionSchema, visitorIdSchema } from '../lib/managedVisitorValidation.js';+import { visitorCancellationSchema, visitorAdmissionSchema, visitorScopeSchema, visitorActionSchema, visitorIdSchema } from '../lib/managedVisitorValidation.js';import { getManagedVisitorBroker } from '../services/managedVisitors.js';-import { isCrossOrigin } from '../../lib/portosAuthCore.js';// Keep the large shared validation barrel off the broker's import-only path.-const validateRequest = async (schema, value) => (await import('../lib/validation.js')).validateRequest(schema, value);+export const validateRequest = async (schema, value) => (await import('../lib/validation.js')).validateRequest(schema, value);export function createManagedVisitorRoutes(getBroker = getManagedVisitorBroker) {const router = Router();@@ -33,25 +32,3 @@ export function createManagedVisitorRoutes(getBroker = getManagedVisitorBroker)}));return router;}--export function createManagedVisitorAdminRoutes(getBroker = getManagedVisitorBroker) {- const router = Router();- router.use((req, _res, next) => {- // No app/peer credential acquires owner provisioning authority. Auth-off retains- // PortOS's documented private-install owner API posture, with explicit CSRF protection.- if (isCrossOrigin(req) || /^Bearer mv1_/i.test(req.headers.authorization ?? '')- || req.portosAuthContext?.enabled && req.portosAuthContext.method !== 'session') {- return next(new ServerError('Visitor credential management requires the owner interface.', { status: 403 }));- }- next();- });- router.get('/', asyncHandler(async (_req, res) => res.json({ credentials: await getBroker().listCredentials() })));- router.post('/:appId/credential', asyncHandler(async (req, res) => {- const id = await validateRequest(visitorIdSchema, req.params.appId), body = await validateRequest(visitorCredentialSchema, req.body);- res.set('Cache-Control', 'no-store'); res.json(await getBroker().provision(id, body));- }));- router.delete('/:appId/credential', asyncHandler(async (req, res) => {- res.json(await getBroker().revoke(await validateRequest(visitorIdSchema, req.params.appId)));- }));- return router;-}diff --git a/server/routes/managedVisitors.test.js b/server/routes/managedVisitors.test.jsindex d036c968e9..86e875342d 100644--- a/server/routes/managedVisitors.test.js+++ b/server/routes/managedVisitors.test.js@@ -19,7 +19,8 @@ vi.mock('../services/managedVisitors.js', async () => {authenticateManagedVisitorRequest: req => actual.authenticateManagedVisitorRequest(req, shared.broker) };});import { authGate } from '../services/authGate.js';-import { createManagedVisitorRoutes, createManagedVisitorAdminRoutes } from './managedVisitors.js';+import { createManagedVisitorRoutes } from './managedVisitors.js';+import { createManagedVisitorAdminRoutes } from './managedVisitorAdmin.js';let directory, app, clock, host, credentials, count, delayed;const appId = 'managed-app', individualId = 'individual-a', individualSessionId = 'runtime-a', worldId = 'quiet-garden';const admission = { individualId, individualSessionId, worldId, body: 'fly-v1', ttlMs: 30000 };diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 7f3485633d..4eadd34f28 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -18,6 +18,7 @@ import { presentMusicVideoDependencies } from '../lib/musicVideoDependencies.js'import { finishedOutsideBlocker } from '../lib/musicVideoFinishedOutside.js';import { getProductionReview, saveProductionDraft, prepareProductionReview, approveProductionReview, lockProductionShots, renderProductionProof, requireProductionReviewer, importProductionPlanning, bindProductionShot, addProductionFeedback, closeProductionFeedback, syncLyricAnchors, removeStaleStoryboardRows, reviseProductionFromFeedback, revertProductionInput } from '../services/musicVideo/productionReviewService.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { requestHasHostControl } from '../services/authGate.js';import {validateRequest,musicVideoAudioTimingPreviewSchema,@@ -894,7 +895,11 @@ router.post('/:id/code/sections/:sectionId/regenerate', asyncHandler(async (req,// install; the record keeps a pointer to the current immutable version.// A new document gets its overlay text checked in the background, so the// findings are waiting at the storyboard approval (local browser work, no provider).-const checkOverlayTextAfterImport = (projectId) => {+// The check renders the document in the headless composition browser, so it+// runs only for a caller with host control (#13055); anyone else gets the+// import alone, and the gated production-review text check runs it later.+const checkOverlayTextAfterImport = (req, projectId) => {+ if (!requestHasHostControl(req)) return;import('../services/musicVideo/overlayTextService.js').then(({ checkOverlayTextInBackground }) => checkOverlayTextInBackground(projectId)).catch((err) => console.error(`❌ Overlay text check did not start: ${err.message}`));@@ -916,7 +921,7 @@ router.post('/:id/composition/document/zip', documentZipUpload, asyncHandler(asyif (!req.file) throw new ServerError('No file uploaded (multipart field "file")', { status: 400, code: 'VALIDATION_ERROR' });try {res.status(201).json(await importDocumentZip(req.params.id, req.file.path, req.file.originalname));- checkOverlayTextAfterImport(req.params.id);+ checkOverlayTextAfterImport(req, req.params.id);} finally {await unlink(req.file.path).catch(() => {});}@@ -925,7 +930,7 @@ router.post('/:id/composition/document/zip', documentZipUpload, asyncHandler(asyrouter.post('/:id/composition/document/directory', asyncHandler(async (req, res) => {const { directory } = validateRequest(musicVideoDocumentDirectoryImportSchema, req.body || {});res.status(201).json(await importDocumentDirectory(req.params.id, directory));- checkOverlayTextAfterImport(req.params.id);+ checkOverlayTextAfterImport(req, req.params.id);}));router.post('/:id/composition/document/template', asyncHandler(async (req, res) => {@@ -961,7 +966,7 @@ router.post('/:id/composition/document/sections/:sectionId/regenerate', asyncHanrouter.post('/:id/composition/document/accept', asyncHandler(async (req, res) => {const { directory } = validateRequest(musicVideoDocumentCandidateSchema, req.body || {});res.json(await acceptMixedMediaDocument(req.params.id, directory));- checkOverlayTextAfterImport(req.params.id);+ checkOverlayTextAfterImport(req, req.params.id);}));router.delete('/:id/composition/document/candidate', asyncHandler(async (req, res) => {diff --git a/server/routes/settings.js b/server/routes/settings.jsindex e1d8b09e8f..fafd2db55e 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -393,9 +393,11 @@ router.put('/features/groups/:groupId', asyncHandler(async (req, res) => {// PUT /api/settings/ai-assignments/:idrouter.put('/ai-assignments/:id', asyncHandler(async (req, res) => {- // These facades replace execution policy or steer scheduled social posts.+ // These facades replace execution policy, steer scheduled social posts, or+ // retarget the scheduled Brain digest (the PUT /api/brain/settings check).// Check the decoded identifier so encoded route params cannot bypass the gate.- if (req.params.id === 'settings.autofixer' || req.params.id.startsWith('socialAgent.')) assertHostControl(req);+ if (req.params.id === 'settings.autofixer' || req.params.id === 'brain.default'+ || req.params.id.startsWith('socialAgent.')) assertHostControl(req);const payload = validateRequest(aiAssignmentUpdateSchema, req.body || {});res.json(await updateAiAssignment(req.params.id, payload));}));diff --git a/server/routes/voice.js b/server/routes/voice.jsindex 019cda2580..9b2edcffea 100644--- a/server/routes/voice.js+++ b/server/routes/voice.js@@ -13,6 +13,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest, voicePiperFetchBodySchema } from '../lib/validation.js';import { MAX_BASE64_UPLOAD_BYTES } from '../lib/uploadLimits.js';import { getVoiceConfig, updateVoiceConfig } from '../services/voice/config.js';+import { requestHasHostControl } from '../services/authGate.js';import { checkAll, invalidateHealthCache } from '../services/voice/health.js';import * as facetimeBridge from '../services/voice/facetimeBridge.js';import { reconcile, verifyBinaries, verifyModels, downloadPiperVoice, startWhisper, stopWhisper } from '../services/voice/bootstrap.js';@@ -153,8 +154,14 @@ router.put('/config', asyncHandler(async (req, res) => {}let next = await updateVoiceConfig(parsed.data);invalidateHealthCache();- const reconciliation = await reconcile(next).catch((err) => ({ error: err.message }));- if (next.enabled && next.tts?.retiredEngine && !reconciliation?.error && !reconciliation?.setupRequired) {+ // Reconcile starts/stops whisper-server under PM2 and can run the setup+ // script, so it is host work (#13055). hostControlBodyGate already refused a+ // caller without host control that changed a runtime key, so skipping it+ // leaves nothing that caller changed un-applied.+ const reconciliation = requestHasHostControl(req)+ ? await reconcile(next).catch((err) => ({ error: err.message }))+ : { skipped: 'host-control' };+ if (next.enabled && next.tts?.retiredEngine && !reconciliation?.skipped && !reconciliation?.error && !reconciliation?.setupRequired) {next = await updateVoiceConfig({ tts: { retiredEngine: null } });}req.app.get('io')?.emit('voice:config:changed', {diff --git a/server/routes/voice.test.js b/server/routes/voice.test.jsindex 95f7dde217..8d69e80af4 100644--- a/server/routes/voice.test.js+++ b/server/routes/voice.test.js@@ -101,6 +101,9 @@ const DEFAULT_CFG = {const buildApp = ({ io = { emit: () => {} } } = {}) => {const app = express();+ // A local caller on a password-free install holds host control, so PUT+ // /config reconciles (#13055); hostControlVoiceConfig.test.js covers the rest.+ app.use((req, _res, next) => { req.portosAuthContext = { enabled: false }; next(); });app.use(express.json());// /speak fails fast when io is missing (a 500 misconfiguration error// rather than a 200 { ok:false, reason:'no-io' } that monitoring woulddiff --git a/server/routes/voicePublic.js b/server/routes/voicePublic.jsindex ed81afa84b..16098842d2 100644--- a/server/routes/voicePublic.js+++ b/server/routes/voicePublic.js@@ -21,6 +21,9 @@ import { voiceSynthesizeBodySchema } from '../lib/apiContractSchemas.js';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 { getSettings } from '../services/settings.js';+import { assertHostControl } from '../services/authGate.js';+import { resolveApiAccess } from '../lib/apiRegistry.js';const router = Router();@@ -37,7 +40,16 @@ export const synthesizeBodySchema = voiceSynthesizeBodySchema;// 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) => {+// Exposure is the operator's opt-in (#13055). authGate applies it only when a+// password is set, so a password-free install checks it here: unexposed,+// synthesis spawns a TTS runtime only for a caller with host control.+const requireExposedOrHostControl = asyncHandler(async (req, _res, next) => {+ const voice = resolveApiAccess(await getSettings()).find((entry) => entry.id === 'voice');+ if (voice?.exposed !== true) assertHostControl(req);+ next();+});++router.post('/synthesize', requireExposedOrHostControl, asyncHandler(async (req, res) => {const parsed = synthesizeBodySchema.safeParse(req.body || {});if (!parsed.success) {throw new ServerError(diff --git a/server/routes/voicePublic.test.js b/server/routes/voicePublic.test.jsindex 60ccd6ec94..5bc3507c99 100644--- a/server/routes/voicePublic.test.js+++ b/server/routes/voicePublic.test.js@@ -13,13 +13,26 @@ vi.mock('../services/voice/config.js', () => ({vi.mock('../services/voice/proactiveSpeech.js', () => ({MAX_PROACTIVE_TEXT_LEN: 2000,}));+const access = vi.hoisted(() => ({ exposed: true }));+vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn(async () => ({ apiAccess: { voice: { exposed: access.exposed } } })),+ settingsEvents: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+}));const tts = await import('../services/voice/tts.js');const config = await import('../services/voice/config.js');const { default: voicePublicRoutes } = await import('./voicePublic.js');-const buildApp = () => {+const buildApp = (authContext) => {const app = express();+ // A remote LAN caller: host control then rests on the auth context alone.+ if (authContext) {+ app.use((req, _res, next) => {+ Object.defineProperty(req.socket, 'remoteAddress', { value: '192.0.2.10' });+ req.portosAuthContext = authContext;+ next();+ });+ }app.use(express.json());app.use('/api/voice/public', voicePublicRoutes);return app;@@ -28,6 +41,7 @@ const buildApp = () => {describe('Public Voice API (/api/voice/public)', () => {beforeEach(() => {vi.clearAllMocks();+ access.exposed = true;config.getVoiceConfig.mockResolvedValue({tts: { engine: 'piper', kokoro: { voice: 'af_heart' }, piper: { voice: 'en_GB-jenny_dioco-medium' } },});@@ -80,6 +94,29 @@ describe('Public Voice API (/api/voice/public)', () => {});});+ describe('exposure (#13055)', () => {+ // authGate applies the exposure toggle only with a password set, so the+ // router enforces it on a password-free install: unexposed synthesis+ // spawns a TTS runtime only for a caller with host control.+ it('refuses unexposed synthesis without host control and keeps it for an operator', async () => {+ access.exposed = false;+ tts.synthesize.mockResolvedValue({ wav: Buffer.from('x'), latencyMs: 1, engine: 'piper' });+ const refused = await request(buildApp({ enabled: false })).post('/api/voice/public/synthesize').send({ text: 'hi' });+ expect([refused.status, refused.body.code]).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ expect(tts.synthesize).not.toHaveBeenCalled();++ const operator = { enabled: true, authenticated: true, method: 'session' };+ expect((await request(buildApp(operator)).post('/api/voice/public/synthesize').send({ text: 'hi' })).status).toBe(200);+ expect(tts.synthesize).toHaveBeenCalledTimes(1);+ });++ it('keeps the voice list readable while unexposed', async () => {+ access.exposed = false;+ tts.listVoices.mockResolvedValue([]);+ expect((await request(buildApp({ enabled: false })).get('/api/voice/public/voices')).status).toBe(200);+ });+ });+describe('GET /voices', () => {it('delegates to listVoices with the requested engine', async () => {tts.listVoices.mockResolvedValue({ engine: 'piper', voices: [{ id: 'af_heart' }] });diff --git a/server/services/messageDrafts.js b/server/services/messageDrafts.jsindex 12609be825..011157e1cb 100644--- a/server/services/messageDrafts.js+++ b/server/services/messageDrafts.js@@ -1,5 +1,6 @@import { join } from 'path';+import { isDeepStrictEqual } from 'util';import { z } from 'zod';import { v4 as uuidv4 } from '../lib/uuid.js';import { atomicWrite, ensureDir, PATHS, readJSONFileStrict } from '../lib/fileUtils.js';@@ -130,10 +131,15 @@ export async function updateDraft(id, updates) {if (['sending', 'delivery_unknown', 'sent'].includes(drafts[idx].status) || ['sending', 'delivery_unknown', 'sent', 'failed'].includes(updates.status)) {throw new ServerError('Draft cannot be edited in its current send state', { status: 409, code: 'DRAFT_STATE_CONFLICT' });}+ // Approval is send intent for the content the approver saw (#13055): an+ // edit to who or what gets sent drops it unless the same update re-approves.+ const contentChanged = ['to', 'cc', 'subject', 'body']+ .some((key) => updates[key] !== undefined && !isDeepStrictEqual(updates[key], drafts[idx][key]));const allowed = ['to', 'cc', 'subject', 'body', 'status'];for (const key of allowed) {if (updates[key] !== undefined) drafts[idx][key] = updates[key];}+ if (contentChanged && drafts[idx].status === 'approved' && updates.status !== 'approved') drafts[idx].status = 'draft';drafts[idx].updatedAt = new Date().toISOString();await saveDrafts(drafts);return drafts[idx];diff --git a/server/services/messageDrafts.test.js b/server/services/messageDrafts.test.jsindex 2485152180..e992cddcb3 100644--- a/server/services/messageDrafts.test.js+++ b/server/services/messageDrafts.test.js@@ -21,7 +21,7 @@ vi.mock('../lib/fileUtils.js', () => ({safeJSONParse: (s, fallback) => { try { return JSON.parse(s); } catch { return fallback; } }}));-const { listDrafts, createDraft } = await import('./messageDrafts.js');+const { listDrafts, createDraft, updateDraft, claimDraftForSend, releaseDraftSend } = await import('./messageDrafts.js');// Seed the file store directly so we control accountId/status without relying on// createDraft (which always stamps status 'draft').@@ -91,3 +91,37 @@ describe('messageDrafts.listDrafts', () => {expect(result.map(d => d.id)).toEqual([draft.id]);});});++// Approval is the send intent claimDraftForSend checks, so it must bind to the+// content that was approved (#13055): an edit to who or what gets sent drops it.+describe('messageDrafts.updateDraft approval binding', () => {+ const approved = {+ id: 'approved-draft', status: 'approved', to: ['[email protected]'], cc: [],+ subject: 'Example subject', body: 'Example reply', createdAt: '2026-01-01T00:00:00.000Z',+ };+ const { id, status: _status, createdAt: _createdAt, ...content } = approved;++ beforeEach(() => {+ fileStore.clear();+ seed([structuredClone(approved)]);+ });++ it.each([+ ['to', ['[email protected]']],+ ['cc', ['[email protected]']],+ ['subject', 'Changed subject'],+ ['body', 'Changed reply'],+ ])('drops approval when %s changes, so the edited draft cannot be claimed for send', async (key, value) => {+ expect(await updateDraft(id, { [key]: value })).toMatchObject({ [key]: value, status: 'draft' });+ await expect(claimDraftForSend(id)).rejects.toMatchObject({ status: 409, code: 'DRAFT_STATE_CONFLICT' });+ });++ it('keeps approval for an unchanged resend and for an edit that re-approves in the same update', async () => {+ expect((await updateDraft(id, structuredClone(content))).status).toBe('approved');+ expect(await updateDraft(id, { body: 'Re-approved reply', status: 'approved' }))+ .toMatchObject({ body: 'Re-approved reply', status: 'approved' });+ const claimed = await claimDraftForSend(id);+ expect(claimed).toMatchObject({ body: 'Re-approved reply', status: 'sending' });+ releaseDraftSend(id, claimed.sendAttemptId);+ });+});