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: require operator authority for social actions and folder imports (#12563)
[._.]/ Adam Eivyccb23bb34062
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex 641114cc72..bac7ad04a4 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -199,6 +199,10 @@ export const HOST_CONTROL_ROUTES = Object.freeze([// handoff; both the decision and execution require operator authority.'POST /api/stacker-news/actions/:id/review','POST /api/stacker-news/actions/:id/execute',+ // Signed-in browser reads, including caller-selected verification transport.+ 'POST /api/stacker-news/accounts/:id/sync',+ 'POST /api/stacker-news/accounts/:id/browser-identity',+ 'POST /api/stacker-news/accounts/:id/verify',// X (Twitter) draft review authorizes a later browser compose handoff, and// opening approved drafts, opening account destinations or syncing accounts@@ -835,6 +839,17 @@ export const HOST_CONTROL_ROUTES = Object.freeze([// direct writes and the stores that arm or steer later scheduled writes.// Accounts/schedules are shared with Moltworld. Reads, private drafts and// deletions stay open; dedicated toggles gate only re-enabling in-handler.+ 'POST /api/agents/tools/moltworld/join',+ 'POST /api/agents/tools/moltworld/build',+ 'POST /api/agents/tools/moltworld/explore',+ 'POST /api/agents/tools/moltworld/think',+ 'POST /api/agents/tools/moltworld/say',+ 'POST /api/agents/tools/moltworld/queue',+ 'POST /api/agents/tools/moltworld/ws/connect',+ 'POST /api/agents/tools/moltworld/ws/move',+ 'POST /api/agents/tools/moltworld/ws/think',+ 'POST /api/agents/tools/moltworld/ws/nearby',+ 'POST /api/agents/tools/moltworld/ws/interact','POST /api/agents/tools/publish-post','POST /api/agents/tools/publish-comment','POST /api/agents/tools/engage',@@ -1030,6 +1045,7 @@ export const HOST_CONTROL_ROUTES = Object.freeze([// neighbours stay open.'POST /api/sharing/buckets','POST /api/sprites/import',+ 'POST /api/music-video/:id/composition/document/directory','POST /api/timeline/import/gmail',// Persistent Mind lifecycle (#8742): starting/waking/resuming the mind armsdiff --git a/server/lib/hostControlRoutes.test.js b/server/lib/hostControlRoutes.test.jsindex fa9da9f6bb..0c18a95ae2 100644--- a/server/lib/hostControlRoutes.test.js+++ b/server/lib/hostControlRoutes.test.js@@ -621,6 +621,7 @@ describe('Music Video agent workflow policy (#9869)', () => {'POST /api/music-video/:id/production-runs/:runId/resume','POST /api/music-video/:id/auto-reviews','POST /api/music-video/:id/auto-reviews/:runId/resume',+ 'POST /api/music-video/:id/composition/document/directory','POST /api/music-video/:id/render','POST /api/music-video/:id/shots/:sceneId/render','POST /api/music-video/:id/shot-renders/preview',@@ -640,7 +641,6 @@ describe('Music Video agent workflow policy (#9869)', () => {'POST /api/music-video/:id/production-runs/:runId/cancel','POST /api/music-video/:id/auto-reviews/:runId/stop','POST /api/music-video/:id/auto-reviews/:runId/cancel',- 'POST /api/music-video/:id/composition/document/directory','GET /api/music-video/:id/composition/document','POST /api/music-video/:id/publish/:target/prepare',]) {diff --git a/server/routes/hostControlMoltworld.test.js b/server/routes/hostControlMoltworld.test.jsnew file mode 100644index 0000000000..8ea8a77a76--- /dev/null+++ b/server/routes/hostControlMoltworld.test.js@@ -0,0 +1,109 @@+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 { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';++vi.mock('../lib/fileUtils.js', async (original) => makePathsProxy(await original(), {+ dataRoot: () => lazyTempDataRoot('portos-moltworld-authority-'),+}));+afterAll(cleanupTempDataRoots);+const auth = vi.hoisted(() => ({ enabled: false }));+vi.mock('../services/auth.js', async (original) => ({+ ...await original(), isAuthEnabled: vi.fn(async () => auth.enabled),+}));+vi.mock('../services/settings.js', () => ({ settingsEvents: new EventEmitter(), getSettings: async () => ({}) }));+const effects = vi.hoisted(() => ({+ getAccountWithCredentials: vi.fn(async () => ({ status: 'active', platform: 'moltworld', credentials: { apiKey: 'example-key' } })),+ recordActivity: vi.fn(), joinWorld: vi.fn(async () => ({})), build: vi.fn(async () => ({})), think: vi.fn(async () => ({})),+ getProfile: vi.fn(async () => ({})), getBalance: vi.fn(async () => ({})), getRateLimitStatus: vi.fn(() => ({})),+ connect: vi.fn(), disconnect: vi.fn(), getStatus: vi.fn(() => ({})),+ sendMove: vi.fn(), sendThink: vi.fn(), sendNearby: vi.fn(), sendInteract: vi.fn(),+ addAction: vi.fn(() => ({})), removeAction: vi.fn(() => ({})), markCompleted: vi.fn(() => ({})), markFailed: vi.fn(() => ({})), getQueue: vi.fn(() => []),+}));+vi.mock('../services/platformAccounts.js', () => effects);+vi.mock('../services/agentPersonalities.js', () => ({ getAgentById: vi.fn() }));+vi.mock('../services/agentActivity.js', () => ({ logActivity: vi.fn() }));+vi.mock('../integrations/moltworld/index.js', () => ({ createMoltworldClient: () => effects }));+vi.mock('../services/moltworldWs.js', () => effects);+vi.mock('../services/moltworldQueue.js', () => effects);++import { authGate, hostControlRouteGate } from '../services/authGate.js';+import { createSession } from '../services/auth.js';+import tools from './moltworldTools.js';+import ws from './moltworldWs.js';+const base = '/api/agents/tools/moltworld';+const operations = [+ ['join', { accountId: 'example-account' }, 'joinWorld'],+ ['build', { accountId: 'example-account', x: 0, y: 0, z: 0 }, 'build'],+ ['explore', { accountId: 'example-account', x: 0, y: 0 }, 'joinWorld'],+ ['think', { accountId: 'example-account', thought: 'Example thought' }, 'think'],+ ['say', { accountId: 'example-account', message: 'Example message' }, 'joinWorld'],+ ['queue', { agentId: 'example-agent', actionType: 'mw_think' }, 'addAction'],+ ['ws/connect', { accountId: 'example-account' }, 'connect'],+ ['ws/move', { x: 0, y: 0 }, 'sendMove'],+ ['ws/think', { thought: 'Example thought' }, 'sendThink'],+ ['ws/nearby', {}, 'sendNearby'],+ ['ws/interact', { to: 'example-agent' }, 'sendInteract'],+];+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());+ app.use(base + '/ws', ws);+ app.use(base, tools);+ app.use(errorMiddleware);+ return app;+};+const call = (app, path, body, headers = {}) => {+ const pending = request(app).post(`${base}/${path}`);+ for (const [key, value] of Object.entries(headers)) pending.set(key, value);+ return pending.send(body);+};+beforeEach(() => { vi.clearAllMocks(); auth.enabled = false; });++describe('Moltworld host authority', () => {+ it('refuses remote and forwarded callers before credentials, queue or socket effects', async () => {+ for (const [path, body] of operations) {+ for (const [address, headers] of [['192.0.2.10', {}], ['127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }]]) {+ const res = await call(appFor(address), path.toUpperCase() + '/', body, headers);+ expect([res.status, res.body.code], path).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ }+ for (const effect of Object.values(effects)) expect(effect).not.toHaveBeenCalled();+ });++ it('preserves local, operator and delegated-agent execution on every protected action', 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, '127.0.0.1', { Authorization: `Bearer ${agent.token}` }],+ ]) {+ auth.enabled = enabled;+ for (const [path, body, effect] of operations) {+ effects[effect].mockClear();+ const res = await call(appFor(address), path, body, headers);+ expect(res.status, `${path}: ${JSON.stringify(res.body)}`).toBe(200);+ expect(effects[effect]).toHaveBeenCalledOnce();+ }+ }+ });++ it('leaves reads, disconnect and queue cancellation/annotations reachable remotely', async () => {+ const app = appFor();+ for (const path of ['status?accountId=example-account', 'balance?accountId=example-account', 'rate-limits?accountId=example-account', 'queue/example-agent', 'ws/status']) {+ expect((await request(app).get(`${base}/${path}`)).status, path).toBe(200);+ }+ for (const path of ['ws/disconnect', 'queue/example-item/complete', 'queue/example-item/fail']) {+ expect((await call(app, path, {})).status, path).toBe(200);+ }+ expect((await request(app).delete(`${base}/queue/example-item`)).status).toBe(200);+ for (const name of ['joinWorld', 'build', 'think', 'connect', 'sendMove', 'sendThink', 'sendNearby', 'sendInteract', 'addAction']) {+ expect(effects[name]).not.toHaveBeenCalled();+ }+ });+});diff --git a/server/routes/hostControlStackerNewsMonitoring.test.js b/server/routes/hostControlStackerNewsMonitoring.test.jsnew file mode 100644index 0000000000..fdb8de832f--- /dev/null+++ b/server/routes/hostControlStackerNewsMonitoring.test.js@@ -0,0 +1,147 @@+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 { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async (original) => makePathsProxy(await original(), {+ dataRoot: () => lazyTempDataRoot('portos-stacker-monitoring-authority-'),+}));+afterAll(cleanupTempDataRoots);+const auth = vi.hoisted(() => ({ enabled: false }));+vi.mock('../services/auth.js', async (original) => ({+ ...await original(), isAuthEnabled: vi.fn(async () => auth.enabled),+}));+vi.mock('../services/settings.js', () => ({ settingsEvents: new EventEmitter(), getSettings: async () => ({}) }));+const state = vi.hoisted(() => ({ account: {}, territory: {} }));+const effects = vi.hoisted(() => ({+ createAccount: vi.fn(async data => ({ ...state.account, ...data })),+ updateAccount: vi.fn(async (_id, data) => ({ ...state.account, ...data })),+ createTerritory: vi.fn(async data => ({ ...state.territory, ...data })),+ updateTerritory: vi.fn(async (_id, data) => ({ ...state.territory, ...data })),+ syncAccount: vi.fn(async () => ({ synced: true })),+ verifyConnection: vi.fn(async () => ({ connected: true })),+ getBrowserIdentity: vi.fn(async () => ({ connected: true })),+ reconcileStackerNewsSchedulers: vi.fn(),+ deleteAccount: vi.fn(async () => true), deleteTerritory: vi.fn(async () => state.account.id),+}));+vi.mock('../services/stackerNews.js', () => ({+ ...effects, getAccount: async () => state.account, getTerritory: async () => state.territory,+ listTerritories: async () => [state.territory],+}));+vi.mock('../services/stackerNewsScheduler.js', () => effects);+import { authGate, hostControlRouteGate } from '../services/authGate.js';+import { createSession } from '../services/auth.js';+import routes from './stackerNews.js';+const accountId = '00000000-0000-4000-8000-000000000001';+const territoryId = '00000000-0000-4000-8000-000000000002';+const base = '/api/stacker-news';+const mutations = [+ ['post', '/accounts', { label: 'Example account', username: 'example_user' }, 'createAccount'],+ ['patch', `/accounts/${accountId}`, {}, 'updateAccount'],+ ['post', '/territories', { accountId, slug: 'example' }, 'createTerritory'],+ ['patch', `/territories/${territoryId}`, {}, 'updateTerritory'],+];+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());+ app.use(base, routes); app.use(errorMiddleware);+ return app;+};+const call = (app, [method, path, body], headers = {}) => {+ const pending = request(app)[method](base + path);+ for (const [key, value] of Object.entries(headers)) pending.set(key, value);+ return pending.send(body);+};+beforeEach(() => {+ vi.clearAllMocks(); auth.enabled = false;+ state.account = { id: accountId, enabled: true, monitoringEnabled: false };+ state.territory = { id: territoryId, accountId, monitoringEnabled: false };+});++describe('Stacker News browser and monitoring authority', () => {+ it('refuses remote browser operations and explicit monitoring opt-ins before effects', async () => {+ for (const suffix of ['sync', 'browser-identity', 'verify']) {+ const res = await call(appFor(), ['post', `/accounts/${accountId}/${suffix}`, {}]);+ expect([res.status, res.body.code], suffix).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ for (const [method, path, body] of mutations) {+ const res = await call(appFor(), [method, path, { ...body, monitoringEnabled: true }]);+ expect([res.status, res.body.code], path).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ for (const effect of Object.values(effects)) expect(effect).not.toHaveBeenCalled();+ });++ it('preserves local, operator-session and delegated-agent browser operations and monitoring opt-ins', 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, '127.0.0.1', { Authorization: `Bearer ${agent.token}` }],+ ]) {+ auth.enabled = enabled;+ for (const suffix of ['sync', 'browser-identity', 'verify']) {+ const res = await call(appFor(address), ['post', `/accounts/${accountId}/${suffix}`, {}], headers);+ expect(res.status, suffix).toBe(200);+ }+ for (const [method, path, body, effect] of mutations) {+ effects[effect].mockClear();+ const res = await call(appFor(address), [method, path, { ...body, monitoringEnabled: true }], headers);+ expect(res.status, path).toBe(method === 'post' ? 201 : 200);+ expect(effects[effect]).toHaveBeenCalledOnce();+ }+ }+ expect(effects.syncAccount).toHaveBeenCalledTimes(3);+ expect(effects.verifyConnection).toHaveBeenCalledTimes(3);+ expect(effects.getBrowserIdentity).toHaveBeenCalledTimes(3);+ expect(effects.reconcileStackerNewsSchedulers).toHaveBeenCalledTimes(12);+ });++ it('keeps unchanged monitoring, labels, disabling and deletes open', async () => {+ state.account.monitoringEnabled = true;+ state.territory.monitoringEnabled = true;+ for (const [method, path, body] of mutations) {+ for (const addition of [{ monitoringEnabled: false }, { label: 'Changed label' }]) {+ // Creating an inherited territory under an enabled account is an opt-in.+ if (path === '/territories' && addition.monitoringEnabled === undefined) continue;+ const res = await call(appFor(), [method, path, { ...body, ...addition }]);+ expect(res.status, path).toBe(method === 'post' ? 201 : 200);+ }+ }+ for (const path of [`/accounts/${accountId}`, `/territories/${territoryId}`]) {+ expect((await call(appFor(), ['delete', path, {}])).status).toBe(204);+ }+ });++ it('refuses inherited monitoring and re-enabling a disabled monitored account', async () => {+ state.account.monitoringEnabled = true;+ for (const data of [{}, { monitoringEnabled: null }]) {+ const res = await call(appFor(), ['post', '/territories', { accountId, slug: 'example', ...data }]);+ expect([res.status, res.body.code]).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ const inherited = await call(appFor(), ['patch', `/territories/${territoryId}`, { monitoringEnabled: null }]);+ expect([inherited.status, inherited.body.code]).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ state.account.enabled = false;+ for (const monitoringEnabled of [null, true]) {+ state.territory.monitoringEnabled = monitoringEnabled;+ const res = await call(appFor(), ['patch', `/accounts/${accountId}`, { enabled: true }]);+ expect([res.status, res.body.code]).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ for (const effect of Object.values(effects)) expect(effect).not.toHaveBeenCalled();+ });++ it('allows dormant inheritance and re-enabling with all monitoring disabled', async () => {+ for (const operation of [+ ['post', '/territories', { accountId, slug: 'example' }],+ ['patch', `/territories/${territoryId}`, { monitoringEnabled: null }],+ ]) expect((await call(appFor(), operation)).status).toBe(operation[0] === 'post' ? 201 : 200);+ state.account.enabled = false;+ expect((await call(appFor(), ['patch', `/accounts/${accountId}`, { enabled: true, monitoringEnabled: false }])).status).toBe(200);+ // Re-saving an already inherited opt-in does not arm anything new.+ state.account.enabled = true; state.account.monitoringEnabled = true; state.territory.monitoringEnabled = null;+ expect((await call(appFor(), ['patch', `/territories/${territoryId}`, { monitoringEnabled: null }])).status).toBe(200);+ });+});diff --git a/server/routes/musicVideoCompositionDocument.test.js b/server/routes/musicVideoCompositionDocument.test.jsindex fd794ecd45..ff91e527cd 100644--- a/server/routes/musicVideoCompositionDocument.test.js+++ b/server/routes/musicVideoCompositionDocument.test.js@@ -7,6 +7,7 @@import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';import express from 'express';+import { EventEmitter } from 'node:events';import { existsSync, readdirSync, rmSync } from 'node:fs';import { mkdir, readFile, symlink, writeFile } from 'node:fs/promises';import { join } from 'node:path';@@ -18,16 +19,27 @@ import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mconst ROOT = () => lazyTempDataRoot('mv-composition-document-route-test-');vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));-vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));+vi.mock('../services/settings.js', () => ({ settingsEvents: new EventEmitter(), getSettings: vi.fn(async () => ({})) }));+const auth = vi.hoisted(() => ({ enabled: false }));+vi.mock('../services/auth.js', async (original) => ({+ ...await original(), isAuthEnabled: vi.fn(async () => auth.enabled),+}));+const { authGate, hostControlRouteGate } = await import('../services/authGate.js');+const { createSession } = await import('../services/auth.js');const { default: musicVideoRoutes } = await import('./musicVideo.js');const projects = await import('../services/musicVideo/projects.js');const { captureMusicVideoEvidence, musicVideoDependencyChanges } = await import('../lib/musicVideoDependencies.js');-const app = express();-app.use(express.json());-app.use('/api/music-video', musicVideoRoutes);-app.use(errorMiddleware);+const appFor = (address = '127.0.0.1') => {+ const app = express();+ app.use((req, _res, next) => { Object.defineProperty(req.socket, 'remoteAddress', { value: address }); next(); });+ app.use(authGate, hostControlRouteGate, express.json());+ app.use('/api/music-video', musicVideoRoutes);+ app.use(errorMiddleware);+ return app;+};+const app = appFor();const PAGE = '<!doctype html><html><head><link rel="stylesheet" href="style.css"></head><body><script src="portos-mv.js"></script><script src="app.js"></script></body></html>';const FILES = { 'index.html': PAGE, 'app.js': 'globalThis.portosComposition = { durationSec: 1, fps: 12, width: 1280, height: 720, seek() {} };', 'style.css': 'body { background: url(bg.png); }', 'bg.png': Buffer.from([137, 80, 78, 71]) };@@ -45,11 +57,11 @@ function withSymlinkMember(zip, name) {return buf;}-async function uploadZip(projectId, zip, name = 'doc.zip') {+async function uploadZip(projectId, zip, name = 'doc.zip', target = app) {const form = new FormData();form.append('file', new Blob([zip], { type: 'application/zip' }), name);const encoded = new Request('http://localhost/', { method: 'POST', body: form });- return request(app).post(`/api/music-video/${projectId}/composition/document/zip`)+ return request(target).post(`/api/music-video/${projectId}/composition/document/zip`).set('content-type', encoded.headers.get('content-type')).send(Buffer.from(await encoded.arrayBuffer()));}@@ -69,6 +81,7 @@ const versionsOf = (projectId) => {let project;beforeEach(async () => {+ auth.enabled = false;rmSync(join(ROOT(), 'music-video-projects.json'), { force: true });rmSync(join(ROOT(), 'music-video'), { recursive: true, force: true });rmSync(join(ROOT(), 'compositions'), { recursive: true, force: true });@@ -77,6 +90,39 @@ beforeEach(async () => {afterAll(cleanupTempDataRoots);describe('music-video composition documents', () => {+ it('requires host authority before copying a caller-named folder and preserves authorized imports', async () => {+ const source = join(ROOT(), 'compositions', 'example-source');+ await mkdir(source, { recursive: true });+ await writeFile(join(source, 'index.html'), PAGE);+ const path = `/api/music-video/${project.id}/composition/document/directory`;+ const body = { directory: 'compositions/example-source' };+ const before = versionsOf(project.id);+ const denied = await request(appFor('192.0.2.10')).post(path).send(body);+ expect([denied.status, denied.body.code]).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ expect(versionsOf(project.id)).toEqual(before);+ 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, '127.0.0.1', { Authorization: `Bearer ${agent.token}` }],+ ]) {+ auth.enabled = enabled;+ const pending = request(appFor(address)).post(path);+ for (const [key, value] of Object.entries(headers)) pending.set(key, value);+ const imported = await pending.send(body);+ expect(imported.status, JSON.stringify(imported.body)).toBe(201);+ expect(await readFile(join(ROOT(), imported.body.document.directory, 'index.html'), 'utf8')).toBe(PAGE);+ }+ });++ it('keeps uploaded archives and shipped templates reachable for remote callers', async () => {+ const remote = appFor('192.0.2.10');+ const uploaded = await uploadZip(project.id, createZip(Object.entries(FILES).map(([name, data]) => ({ name, data }))), 'doc.zip', remote);+ expect(uploaded.status).toBe(201);+ expect((await request(remote).post(`/api/music-video/${project.id}/composition/document/template`).send({})).status).toBe(201);+ });+it('upgrades a recognized legacy engine without rewriting authored files or validating an old review', async () => {// Historical shipped bytes pin recognition independently of today's engine.const legacy = await readFile(new URL('./fixtures/musicVideoLayeredEngine.txt', import.meta.url));diff --git a/server/routes/stackerNews.js b/server/routes/stackerNews.jsindex b12c8c47ec..b3bf9cff6d 100644--- a/server/routes/stackerNews.js+++ b/server/routes/stackerNews.js@@ -1,6 +1,7 @@import { Router } from 'express';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { assertHostControl } from '../services/authGate.js';import { validateRequest } from '../lib/validation.js';import * as stackerNews from '../services/stackerNews.js';import { reconcileStackerNewsSchedulers } from '../services/stackerNewsScheduler.js';@@ -90,7 +91,9 @@ router.get('/capabilities', (_req, res) => res.json(stackerNews.stackerNewsCapabrouter.get('/accounts', asyncHandler(async (_req, res) => res.json({ accounts: await stackerNews.listAccounts() })));router.post('/accounts', asyncHandler(async (req, res) => {- const account = await stackerNews.createAccount(validateRequest(accountSchema, req.body));+ const data = validateRequest(accountSchema, req.body);+ if (data.monitoringEnabled === true) assertHostControl(req);+ const account = await stackerNews.createAccount(data);await reconcileStackerNewsSchedulers();emitChanged(req, account.id);res.status(201).json(account);@@ -105,7 +108,19 @@ router.get('/accounts/:id', asyncHandler(async (req, res) => {router.patch('/accounts/:id', asyncHandler(async (req, res) => {requireId(req.params.id, 'account ID');- const account = await stackerNews.updateAccount(req.params.id, validateRequest(accountUpdateSchema, req.body));+ const data = validateRequest(accountUpdateSchema, req.body);+ if (data.monitoringEnabled === true) assertHostControl(req);+ // Re-enabling an account also re-arms saved territory monitoring.+ if (data.enabled === true && data.monitoringEnabled !== true) {+ const current = await stackerNews.getAccount(req.params.id);+ if (current && !current.enabled) {+ const territories = await stackerNews.listTerritories(current.id);+ if (territories.some(territory => territory.monitoringEnabled ?? (data.monitoringEnabled ?? current.monitoringEnabled))) {+ assertHostControl(req);+ }+ }+ }+ const account = await stackerNews.updateAccount(req.params.id, data);if (!account) throw new ServerError('Stacker News account not found', { status: 404 });await reconcileStackerNewsSchedulers();emitChanged(req, account.id);@@ -148,7 +163,14 @@ router.get('/accounts/:id/territories', asyncHandler(async (req, res) => {}));router.post('/territories', asyncHandler(async (req, res) => {- const territory = await stackerNews.createTerritory(validateRequest(territorySchema, req.body));+ const data = validateRequest(territorySchema, req.body);+ if (data.monitoringEnabled === true) assertHostControl(req);+ // Omitted/null territory monitoring inherits the account's opt-in.+ if (data.monitoringEnabled == null) {+ const account = await stackerNews.getAccount(data.accountId);+ if (account?.enabled && account.monitoringEnabled) assertHostControl(req);+ }+ const territory = await stackerNews.createTerritory(data);await reconcileStackerNewsSchedulers();emitChanged(req, territory.accountId);res.status(201).json(territory);@@ -157,6 +179,14 @@ router.post('/territories', asyncHandler(async (req, res) => {router.patch('/territories/:id', asyncHandler(async (req, res) => {requireId(req.params.id, 'territory ID');const data = validateRequest(territorySchema.omit({ accountId: true }).partial().strict(), req.body);+ if (data.monitoringEnabled === true) assertHostControl(req);+ if (data.monitoringEnabled === null) {+ const current = await stackerNews.getTerritory(req.params.id);+ if (current && current.monitoringEnabled === false) {+ const account = await stackerNews.getAccount(current.accountId);+ if (account?.enabled && account.monitoringEnabled) assertHostControl(req);+ }+ }const territory = await stackerNews.updateTerritory(req.params.id, data);if (!territory) throw new ServerError('Stacker News territory not found', { status: 404 });await reconcileStackerNewsSchedulers();diff --git a/server/services/stackerNews.js b/server/services/stackerNews.jsindex bcbd376e47..254436b073 100644--- a/server/services/stackerNews.js+++ b/server/services/stackerNews.js@@ -277,6 +277,11 @@ export async function listTerritories(accountId) {return result.rows.map(territoryView);}+export async function getTerritory(id) {+ const result = await query('SELECT * FROM stacker_news_territories WHERE id=$1', [id]);+ return result.rows[0] ? territoryView(result.rows[0]) : null;+}+export async function createTerritory({ accountId, slug, label = '', isOwned = false, monitoringEnabled = null, inheritAccountRules = true, rules = {} }) {const result = await query(`INSERT INTO stacker_news_territories (id,account_id,slug,label,is_owned,monitoring_enabled,inherit_account_rules,rules)