Skip to content

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

Route contract tests for the mounted routers no test reached, plus a guard

[._.]/ Adam Eivyaba507c34f00
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.js
index 83c7c2cbd6..76d5b280e4 100644
--- a/scripts/ci-test-plan.js
+++ b/scripts/ci-test-plan.js
@@ -369,6 +369,9 @@ export const ALWAYS_RUN_TESTS = [
// Base-relative retired history guard: JSON edits have no import edge here.
// Pregate and CI forward the planner's exact CI_BASE_SHA.
'server/services/taskPromptDefaults/integritySnapshot.guard.test.js',
+ // Whole-tree scanner (#12048): server/index.js can mount a new router that no
+ // test imports, with no import edge from that router to this guard.
+ 'server/routeTestCoverageConventions.test.js',
'server/routeValidationConventions.test.js',
'server/timerCallbackConventions.test.js',
];
diff --git a/server/lib/meatspaceValidation.js b/server/lib/meatspaceValidation.js
index db6871492a..e5cf3d522a 100644
--- a/server/lib/meatspaceValidation.js
+++ b/server/lib/meatspaceValidation.js
@@ -1,6 +1,11 @@
import { z } from 'zod';
import { partialWithoutDefaults } from './zodCompat.js';
+// GET /alcohol/daily and /nicotine/daily: entries compare these against their
+// YYYY-MM-DD date keys as strings, so any other shape silently filters wrong.
+const dayKey = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Expected YYYY-MM-DD');
+export const dailyRangeQuerySchema = z.object({ from: dayKey.optional(), to: dayKey.optional() });
+
// =============================================================================
// LIFE CALENDAR ACTIVITIES
// =============================================================================
diff --git a/server/routeTestCoverageConventions.test.js b/server/routeTestCoverageConventions.test.js
new file mode 100644
index 0000000000..775720362e
--- /dev/null
+++ b/server/routeTestCoverageConventions.test.js
@@ -0,0 +1,85 @@
+/**
+ * Repo-wide guard: every route module `server/index.js` mounts is imported by
+ * at least one test (#12048).
+ *
+ * A router no test imports ships green with a handler that returns the wrong
+ * shape or 500s on an edge path, and the CI planner's related-test selection has
+ * nothing to select when the file changes. The fix is a contract test at the
+ * HTTP boundary (`request(app)` from `lib/testHelper.js`, success path plus the
+ * materially different failure path), not an entry here.
+ *
+ * `UNTESTED_ALLOWLIST` is the burn-down of mounted modules that no test imports
+ * yet. It only SHRINKS: a module that gains a test must leave the list (the
+ * stale-entry assertion fails otherwise), and a newly mounted untested module
+ * fails outright.
+ *
+ * "Imported" means a relative specifier in a tracked test file (a static or
+ * dynamic import, or a `vi.mock` path) resolves to the module. A route reached
+ * only through another module (a sub-router mounted by a barrel) is covered by
+ * the barrel's test and is not itself listed.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { dirname, join, relative, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = fileURLToPath(new URL('..', import.meta.url));
+
+/** Mounted route modules no test imports yet, each with why it can wait. */
+const UNTESTED_ALLOWLIST = new Map([
+ ['server/routes/alerts.js', 'read-only pass-through over proactiveAlerts, which its own suite covers'],
+ ['server/routes/autoFixMetrics.js', 'read-only pass-through over autoFixMetrics, which its own suite covers'],
+ ['server/routes/iterm.js', 'read-only capability probe over itermBridge, which its own suite covers'],
+ ['server/routes/runs.js', 'returns the toolkit runs router unchanged; the toolkit route suite owns the contract'],
+]);
+
+/** `server/routes/...` paths imported by `server/index.js`, repo-relative. */
+function mountedRouteModules(indexSource) {
+ return [...indexSource.matchAll(/from\s+['"](\.\/routes\/[^'"]+)['"]/g)]
+ .map((m) => `server/${m[1].slice(2)}`);
+}
+
+/** Every relative module a test file names, resolved repo-relative. */
+function importedModules(testFile, source) {
+ return [...source.matchAll(/['"](\.{1,2}\/[^'"\n]+\.[cm]?js)['"]/g)]
+ .map((m) => relative(ROOT, resolve(ROOT, dirname(testFile), m[1])).split('\\').join('/'));
+}
+
+function trackedTests() {
+ return execFileSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard', 'server', 'scripts', 'lib', 'autofixer'], { cwd: ROOT, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
+ .split('\0').filter((f) => /\.test\.[cm]?js$/.test(f));
+}
+
+function untestedMounted() {
+ const mounted = mountedRouteModules(readFileSync(join(ROOT, 'server/index.js'), 'utf8'));
+ const imported = new Set(trackedTests().flatMap((f) => importedModules(f, readFileSync(join(ROOT, f), 'utf8'))));
+ return { mounted, untested: mounted.filter((m) => !imported.has(m)) };
+}
+
+describe('mounted route modules are reached by a test (#12048)', () => {
+ it('reads the mounts and resolves test imports the way the scan relies on', () => {
+ expect(mountedRouteModules("import a from './routes/apps/index.js';\nimport { b } from \"./routes/x.js\";"))
+ .toEqual(['server/routes/apps/index.js', 'server/routes/x.js']);
+ expect(importedModules('server/routes/foo.test.js', "vi.mock('../services/a.js');\nconst { default: r } = await import('./foo.js');"))
+ .toEqual(['server/services/a.js', 'server/routes/foo.js']);
+ });
+
+ it('has no untested mounted route module outside the burn-down list', () => {
+ const { mounted, untested } = untestedMounted();
+ expect(mounted.length).toBeGreaterThan(100);
+ const offenders = untested.filter((m) => !UNTESTED_ALLOWLIST.has(m));
+ expect(
+ offenders,
+ 'add a route contract test (request(app) at the mounted path: success plus the materially different failure). Do NOT add to UNTESTED_ALLOWLIST — it only shrinks.',
+ ).toEqual([]);
+ });
+
+ it('drops allowlist entries once their module is tested or unmounted', () => {
+ const { untested } = untestedMounted();
+ const stale = [...UNTESTED_ALLOWLIST.keys()].filter((m) => !untested.includes(m));
+ expect(stale, 'these modules are now imported by a test or no longer mounted — remove them from UNTESTED_ALLOWLIST').toEqual([]);
+ for (const reason of UNTESTED_ALLOWLIST.values()) expect(reason.length).toBeGreaterThan(10);
+ });
+});
diff --git a/server/routeValidationConventions.test.js b/server/routeValidationConventions.test.js
index 6f791761a6..c9e72004b8 100644
--- a/server/routeValidationConventions.test.js
+++ b/server/routeValidationConventions.test.js
@@ -196,8 +196,6 @@ const UNVALIDATED_QUERY_BASELINE = [
'routes/apps/viteTls.js GET /:id/vite-host-check',
'routes/artists.js GET /',
'routes/authors.js GET /',
- 'routes/autobiography.js GET /prompt',
- 'routes/autobiography.js GET /stories',
'routes/automationSchedules.js GET /',
'routes/avatar.js GET /model.glb',
'routes/brainCrud.js GET /admin',
@@ -237,13 +235,10 @@ const UNVALIDATED_QUERY_BASELINE = [
'routes/eidoverseWorldRoutes.js GET /foundations/:id',
'routes/eidoverseWorldRoutes.js POST /foundations/:id/adopt',
'routes/featureAgents.js GET /:id/runs',
- 'routes/feeds.js GET /items',
- 'routes/feeds.js POST /items/read-all',
'routes/games.js GET /',
'routes/harnesses.js GET /',
'routes/harnesses.js POST /action',
'routes/harnesses.js POST /models/refresh',
- 'routes/identity.js GET /goals/:id/calendar-events',
'routes/imageGen.js GET /regen/availability',
'routes/imageGen.js GET /status',
'routes/imageGenSetup.js POST /install',
@@ -254,8 +249,6 @@ const UNVALIDATED_QUERY_BASELINE = [
'routes/localLlm.js GET /loaded',
'routes/loras.js GET /',
'routes/loras.js GET /suggestions',
- 'routes/meatspaceAlcoholRoutes.js GET /alcohol/daily',
- 'routes/meatspaceNicotineRoutes.js GET /nicotine/daily',
'routes/meatspacePostRoutes.js GET /post/morse/progress',
'routes/meatspacePostRoutes.js GET /post/recommendations',
'routes/meatspacePostRoutes.js GET /post/review/reps',
@@ -267,9 +260,6 @@ const UNVALIDATED_QUERY_BASELINE = [
'routes/memory.js GET /:id/related',
'routes/messages.js GET /drafts',
'routes/messages.js POST /debug/test-token',
- 'routes/moltworldTools.js GET /balance',
- 'routes/moltworldTools.js GET /rate-limits',
- 'routes/moltworldTools.js GET /status',
'routes/moodBoard.js GET /',
'routes/music.js POST /setup/runtime-install',
'routes/openclaw.js GET /sessions/:id/messages',
@@ -293,11 +283,9 @@ const UNVALIDATED_QUERY_BASELINE = [
'routes/providers.js POST /readiness/setup',
'routes/providers.js POST /runtimes/install',
'routes/quotaBurn.js GET /',
- 'routes/remoteDesktopViewer.js GET /',
'routes/review.js GET /items',
'routes/scaffold.js GET /directories',
'routes/sharing.js GET /subscriptions',
- 'routes/socialAccounts.js GET /',
'routes/spotify.js GET /oauth/callback',
'routes/sprites.js GET /',
'routes/storyBuilder.js GET /',
diff --git a/server/routes/autobiography.js b/server/routes/autobiography.js
index 2585a3788a..43194b7d17 100644
--- a/server/routes/autobiography.js
+++ b/server/routes/autobiography.js
@@ -46,6 +46,9 @@ const evaluateStorySchema = z.object({
providerId: z.string().optional()
});
+const nextPromptQuerySchema = z.object({ exclude: z.string().min(1).max(200).optional() });
+const storiesQuerySchema = z.object({ theme: z.string().min(1).max(100).optional() });
+
const updateConfigSchema = z.object({
enabled: z.boolean().optional(),
intervalHours: z.number().min(1).max(168).optional(),
@@ -107,7 +110,8 @@ router.get('/themes', asyncHandler(async (req, res) => {
* Get the next prompt
*/
router.get('/prompt', asyncHandler(async (req, res) => {
- const prompt = await autobiographyService.getNextPrompt(req.query.exclude || undefined);
+ const { exclude } = validateRequest(nextPromptQuerySchema, req.query);
+ const prompt = await autobiographyService.getNextPrompt(exclude);
res.json(prompt);
}));
@@ -141,7 +145,8 @@ router.get('/prompt/:id', asyncHandler(async (req, res) => {
* Get all stories, optionally filtered by theme
*/
router.get('/stories', asyncHandler(async (req, res) => {
- const stories = await autobiographyService.getStories(req.query.theme || null);
+ const { theme } = validateRequest(storiesQuerySchema, req.query);
+ const stories = await autobiographyService.getStories(theme ?? null);
res.json(stories);
}));
diff --git a/server/routes/autobiography.test.js b/server/routes/autobiography.test.js
new file mode 100644
index 0000000000..c519d9a451
--- /dev/null
+++ b/server/routes/autobiography.test.js
@@ -0,0 +1,65 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/autobiography.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ updateConfig: vi.fn(),
+ getNextPrompt: vi.fn(),
+ getPromptById: vi.fn(),
+ getStories: vi.fn(),
+ saveStory: vi.fn(),
+ updateStory: vi.fn(),
+}));
+
+import * as autobiography from '../services/autobiography.js';
+import autobiographyRoutes from './autobiography.js';
+
+const app = express();
+app.use(express.json());
+app.use('/api/digital-twin/autobiography', autobiographyRoutes);
+app.use(errorMiddleware);
+const BASE = '/api/digital-twin/autobiography';
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('/api/digital-twin/autobiography', () => {
+ it('saves a story to a custom question only when the question text is present', async () => {
+ autobiography.saveStory.mockResolvedValue({ id: 's1' });
+ const missing = await request(app).post(`${BASE}/stories`).send({ promptId: 'custom', content: 'Once' });
+ expect(missing.status).toBe(400);
+ expect(autobiography.saveStory).not.toHaveBeenCalled();
+
+ const ok = await request(app).post(`${BASE}/stories`).send({ promptId: 'custom', content: 'Once', customPromptText: 'What was your first job?' });
+ expect(ok.status).toBe(200);
+ expect(autobiography.saveStory).toHaveBeenCalledWith({
+ promptId: 'custom', content: 'Once', parentStoryId: undefined, customPromptText: 'What was your first job?',
+ });
+ });
+
+ it('refuses a reminder time the scheduler could not register', async () => {
+ const res = await request(app).put(`${BASE}/config`).send({ reminder: { enabled: true, time: '9am' } });
+ expect(res.status).toBe(400);
+ expect(autobiography.updateConfig).not.toHaveBeenCalled();
+ });
+
+ it('answers 404 for an unknown prompt or story', async () => {
+ autobiography.getPromptById.mockReturnValue(null);
+ autobiography.updateStory.mockResolvedValue(null);
+ expect((await request(app).get(`${BASE}/prompt/nope`)).status).toBe(404);
+ expect((await request(app).put(`${BASE}/stories/nope`).send({ content: 'x' })).status).toBe(404);
+ });
+
+ it('passes the theme filter and the excluded prompt from the query string', async () => {
+ autobiography.getStories.mockResolvedValue([]);
+ autobiography.getNextPrompt.mockResolvedValue({ id: 'p2' });
+ await request(app).get(`${BASE}/stories?theme=childhood`);
+ expect(autobiography.getStories).toHaveBeenCalledWith('childhood');
+ await request(app).get(`${BASE}/stories`);
+ expect(autobiography.getStories).toHaveBeenLastCalledWith(null);
+ await request(app).get(`${BASE}/prompt?exclude=p1`);
+ expect(autobiography.getNextPrompt).toHaveBeenCalledWith('p1');
+ expect((await request(app).get(`${BASE}/stories?theme=a&theme=b`)).status).toBe(400);
+ });
+});
diff --git a/server/routes/dailyDriver.test.js b/server/routes/dailyDriver.test.js
new file mode 100644
index 0000000000..34a0925015
--- /dev/null
+++ b/server/routes/dailyDriver.test.js
@@ -0,0 +1,36 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/dailyDriver.js', () => ({
+ getAndRecordVisit: vi.fn(), getDriverState: vi.fn(), markDriverHandled: vi.fn(),
+}));
+
+import * as dailyDriver from '../services/dailyDriver.js';
+import dailyDriverRoutes from './dailyDriver.js';
+
+const app = express();
+app.use(express.json());
+app.use('/api/daily-driver', dailyDriverRoutes);
+app.use(errorMiddleware);
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('/api/daily-driver', () => {
+ it('records the visit on read, so the next read of the day is no longer the first', async () => {
+ dailyDriver.getAndRecordVisit.mockResolvedValue({ today: '2026-01-02', firstVisitToday: true, handledToday: false });
+ const res = await request(app).get('/api/daily-driver');
+ expect(res.body).toEqual({ today: '2026-01-02', firstVisitToday: true, handledToday: false });
+ expect(dailyDriver.getAndRecordVisit).toHaveBeenCalledTimes(1);
+ expect(dailyDriver.getDriverState).not.toHaveBeenCalled();
+ });
+
+ it('marks the day handled on POST /handled and surfaces a store failure', async () => {
+ dailyDriver.markDriverHandled.mockResolvedValue({ today: '2026-01-02', firstVisitToday: false, handledToday: true });
+ expect((await request(app).post('/api/daily-driver/handled')).body.handledToday).toBe(true);
+
+ dailyDriver.markDriverHandled.mockRejectedValue(new Error('write failed'));
+ expect((await request(app).post('/api/daily-driver/handled')).status).toBe(500);
+ });
+});
diff --git a/server/routes/feeds.js b/server/routes/feeds.js
index 2d2a701e1a..a06cefc12e 100644
--- a/server/routes/feeds.js
+++ b/server/routes/feeds.js
@@ -25,6 +25,16 @@ const addFeedSchema = z.object({
url: z.string().url()
});
+const feedIdQuery = { feedId: z.string().min(1).max(200).optional() };
+const itemsQuerySchema = z.object({
+ ...feedIdQuery,
+ unreadOnly: z.enum(['true', 'false']).optional(),
+ // parsePagination clamps these; the schema only refuses non-scalar values.
+ limit: z.string().max(20).optional(),
+ offset: z.string().max(20).optional(),
+});
+const readAllQuerySchema = z.object(feedIdQuery);
+
// GET /api/feeds — list all feeds with unread counts
router.get('/', asyncHandler(async (req, res) => {
const feeds = await feedsService.getFeeds();
@@ -39,8 +49,9 @@ router.get('/stats', asyncHandler(async (req, res) => {
// GET /api/feeds/items — get feed items (supports limit/offset pagination, default limit 100)
router.get('/items', asyncHandler(async (req, res) => {
- const { feedId, unreadOnly } = req.query;
- const { limit, offset } = parsePagination(req.query, { defaultLimit: 100, maxLimit: 500 });
+ const query = validateRequest(itemsQuerySchema, req.query);
+ const { feedId, unreadOnly } = query;
+ const { limit, offset } = parsePagination(query, { defaultLimit: 100, maxLimit: 500 });
const items = await feedsService.getItems({
feedId: feedId || undefined,
unreadOnly: unreadOnly === 'true',
@@ -68,7 +79,7 @@ router.post('/refresh-all', asyncHandler(async (req, res) => {
// POST /api/feeds/items/read-all — mark all items as read
router.post('/items/read-all', asyncHandler(async (req, res) => {
- const { feedId } = req.query;
+ const { feedId } = validateRequest(readAllQuerySchema, req.query);
const result = await feedsService.markAllRead(feedId || undefined);
res.json(result);
}));
diff --git a/server/routes/feeds.test.js b/server/routes/feeds.test.js
new file mode 100644
index 0000000000..eaa733a95b
--- /dev/null
+++ b/server/routes/feeds.test.js
@@ -0,0 +1,74 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/feeds.js', () => ({
+ getFeeds: vi.fn(),
+ addFeed: vi.fn(),
+ removeFeed: vi.fn(),
+ refreshFeed: vi.fn(),
+ refreshAllFeeds: vi.fn(),
+ getItems: vi.fn(),
+ markItemRead: vi.fn(),
+ markAllRead: vi.fn(),
+ getFeedStats: vi.fn(),
+}));
+
+import * as feeds from '../services/feeds.js';
+import feedsRoutes from './feeds.js';
+
+const app = express();
+app.use(express.json());
+app.use('/api/feeds', feedsRoutes);
+app.use(errorMiddleware);
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('/api/feeds', () => {
+ it('subscribes to a feed URL, and maps a service refusal or a non-URL to 400', async () => {
+ feeds.addFeed.mockResolvedValue({ feed: { id: 'f1', url: 'https://example.com/rss' } });
+ const ok = await request(app).post('/api/feeds').send({ url: 'https://example.com/rss' });
+ expect(ok.status).toBe(201);
+ expect(ok.body).toEqual({ id: 'f1', url: 'https://example.com/rss' });
+
+ feeds.addFeed.mockResolvedValue({ error: 'Feed already subscribed' });
+ const dup = await request(app).post('/api/feeds').send({ url: 'https://example.com/rss' });
+ expect(dup.status).toBe(400);
+ expect(dup.body.error).toBe('Feed already subscribed');
+
+ feeds.addFeed.mockClear();
+ const bad = await request(app).post('/api/feeds').send({ url: 'not a url' });
+ expect(bad.status).toBe(400);
+ expect(feeds.addFeed).not.toHaveBeenCalled();
+ });
+
+ it('reads items with the filters the client sends and clamps pagination', async () => {
+ feeds.getItems.mockResolvedValue([]);
+ await request(app).get('/api/feeds/items?feedId=f1&unreadOnly=true&limit=9999&offset=5');
+ expect(feeds.getItems).toHaveBeenCalledWith({ feedId: 'f1', unreadOnly: true, limit: 500, offset: 5 });
+
+ await request(app).get('/api/feeds/items');
+ expect(feeds.getItems).toHaveBeenLastCalledWith({ feedId: undefined, unreadOnly: false, limit: 100, offset: 0 });
+
+ const bad = await request(app).get('/api/feeds/items?unreadOnly=yes');
+ expect(bad.status).toBe(400);
+ });
+
+ it('marks all items read for one feed or every feed', async () => {
+ feeds.markAllRead.mockResolvedValue({ marked: 2 });
+ await request(app).post('/api/feeds/items/read-all?feedId=f1');
+ expect(feeds.markAllRead).toHaveBeenCalledWith('f1');
+ await request(app).post('/api/feeds/items/read-all');
+ expect(feeds.markAllRead).toHaveBeenLastCalledWith(undefined);
+ });
+
+ it('answers 404 when the item or feed a mutation names does not exist', async () => {
+ feeds.markItemRead.mockResolvedValue({ error: 'Item not found' });
+ feeds.refreshFeed.mockResolvedValue({ error: 'Feed not found' });
+ feeds.removeFeed.mockResolvedValue({ error: 'Feed not found' });
+ expect((await request(app).post('/api/feeds/items/i9/read')).status).toBe(404);
+ expect((await request(app).post('/api/feeds/f9/refresh')).status).toBe(404);
+ expect((await request(app).delete('/api/feeds/f9')).status).toBe(404);
+ });
+});
diff --git a/server/routes/identity.js b/server/routes/identity.js
index e8e2624163..f0c1431b18 100644
--- a/server/routes/identity.js
+++ b/server/routes/identity.js
@@ -1,4 +1,5 @@
import { Router } from 'express';
+import { z } from 'zod';
import * as identityService from '../services/identity.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
@@ -26,6 +27,12 @@ import * as goalCalendarScheduler from '../services/goalCalendarScheduler.js';
const router = Router();
+// Passed through to the calendar sync's own date filter.
+const calendarWindowQuerySchema = z.object({
+ startDate: z.string().max(40).optional(),
+ endDate: z.string().max(40).optional(),
+});
+
// =============================================================================
// IDENTITY STATUS
// =============================================================================
@@ -218,7 +225,7 @@ router.delete('/goals/:id/calendars/:subcalendarId', asyncHandler(async (req, re
// GET /api/digital-twin/identity/goals/:id/calendar-events — Get matching events
router.get('/goals/:id/calendar-events', asyncHandler(async (req, res) => {
- const { startDate, endDate } = req.query;
+ const { startDate, endDate } = validateRequest(calendarWindowQuerySchema, req.query);
const events = await identityService.getGoalCalendarEvents(req.params.id, startDate, endDate);
res.json(events);
}));
diff --git a/server/routes/identity.test.js b/server/routes/identity.test.js
new file mode 100644
index 0000000000..5e42344f1f
--- /dev/null
+++ b/server/routes/identity.test.js
@@ -0,0 +1,66 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/identity.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ setBirthDate: vi.fn(),
+ createGoal: vi.fn(),
+ deleteGoal: vi.fn(),
+ getGoalCalendarEvents: vi.fn(),
+}));
+vi.mock('../services/goalCalendarScheduler.js', () => ({
+ scheduleTimeBlocks: vi.fn(), removeScheduledEvents: vi.fn(), rescheduleTimeBlocks: vi.fn(),
+}));
+
+import * as identityService from '../services/identity.js';
+import identityRoutes from './identity.js';
+
+const app = express();
+app.use(express.json());
+app.use('/api/digital-twin/identity', identityRoutes);
+app.use(errorMiddleware);
+const BASE = '/api/digital-twin/identity';
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('/api/digital-twin/identity goals', () => {
+ it('creates a goal with the schema defaults filled in', async () => {
+ identityService.createGoal.mockImplementation(async (data) => ({ id: 'g1', ...data }));
+ const res = await request(app).post(`${BASE}/goals`).send({ title: 'Run a marathon' });
+ expect(res.status).toBe(201);
+ expect(identityService.createGoal).toHaveBeenCalledWith(expect.objectContaining({
+ title: 'Run a marathon', horizon: '5-year', category: 'mastery', goalType: 'standard', parentId: null, tags: [],
+ }));
+ });
+
+ it('refuses a goal without a title and a birth date in the future', async () => {
+ expect((await request(app).post(`${BASE}/goals`).send({ description: 'x' })).status).toBe(400);
+ expect(identityService.createGoal).not.toHaveBeenCalled();
+
+ const future = await request(app).put(`${BASE}/goals/birth-date`).send({ birthDate: '2999-01-01' });
+ expect(future.status).toBe(400);
+ expect(identityService.setBirthDate).not.toHaveBeenCalled();
+
+ identityService.setBirthDate.mockResolvedValue({ goals: [] });
+ expect((await request(app).put(`${BASE}/goals/birth-date`).send({ birthDate: '1980-02-03' })).status).toBe(200);
+ expect(identityService.setBirthDate).toHaveBeenCalledWith('1980-02-03');
+ });
+
+ it('answers 404 deleting a goal that does not exist and 204 for one that does', async () => {
+ identityService.deleteGoal.mockResolvedValue(false);
+ expect((await request(app).delete(`${BASE}/goals/missing`)).status).toBe(404);
+ identityService.deleteGoal.mockResolvedValue(true);
+ expect((await request(app).delete(`${BASE}/goals/g1`)).status).toBe(204);
+ });
+
+ it('passes the calendar window through and refuses a repeated bound', async () => {
+ identityService.getGoalCalendarEvents.mockResolvedValue([]);
+ await request(app).get(`${BASE}/goals/g1/calendar-events?startDate=2026-01-01&endDate=2026-01-31`);
+ expect(identityService.getGoalCalendarEvents).toHaveBeenCalledWith('g1', '2026-01-01', '2026-01-31');
+
+ const bad = await request(app).get(`${BASE}/goals/g1/calendar-events?startDate=a&startDate=b`);
+ expect(bad.status).toBe(400);
+ });
+});
diff --git a/server/routes/meatspace.test.js b/server/routes/meatspace.test.js
new file mode 100644
index 0000000000..c0fc88cc60
--- /dev/null
+++ b/server/routes/meatspace.test.js
@@ -0,0 +1,61 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+// Only the services these cases reach are stubbed; the barrel's other
+// sub-routers import their real services, as their own suites do.
+vi.mock('../services/meatspace.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ getOverview: vi.fn(),
+ updateBirthDate: vi.fn(),
+}));
+vi.mock('../services/meatspaceAlcohol.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ getDailyAlcohol: vi.fn(),
+}));
+vi.mock('../services/meatspaceNicotine.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ getDailyNicotine: vi.fn(),
+}));
+
+import * as meatspace from '../services/meatspace.js';
+import * as alcohol from '../services/meatspaceAlcohol.js';
+import * as nicotine from '../services/meatspaceNicotine.js';
+import meatspaceRoutes from './meatspace.js';
+
+const app = express();
+app.use(express.json());
+app.use('/api/meatspace', meatspaceRoutes);
+app.use(errorMiddleware);
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('/api/meatspace (barrel over the per-domain routers)', () => {
+ it('serves the overview from the core router', async () => {
+ meatspace.getOverview.mockResolvedValue({ deathClock: null });
+ expect((await request(app).get('/api/meatspace')).body).toEqual({ deathClock: null });
+ });
+
+ it('sets a past birth date and refuses a malformed one', async () => {
+ meatspace.updateBirthDate.mockResolvedValue({ birthDate: '1980-02-03' });
+ expect((await request(app).put('/api/meatspace/birth-date').send({ birthDate: '1980-02-03' })).status).toBe(200);
+ expect(meatspace.updateBirthDate).toHaveBeenCalledWith('1980-02-03');
+
+ meatspace.updateBirthDate.mockClear();
+ expect((await request(app).put('/api/meatspace/birth-date').send({ birthDate: 'Feb 3' })).status).toBe(400);
+ expect(meatspace.updateBirthDate).not.toHaveBeenCalled();
+ });
+
+ it('reads daily substance entries for a date window and refuses a non-date bound', async () => {
+ alcohol.getDailyAlcohol.mockResolvedValue([]);
+ nicotine.getDailyNicotine.mockResolvedValue([]);
+ await request(app).get('/api/meatspace/alcohol/daily?from=2026-01-01&to=2026-01-31');
+ expect(alcohol.getDailyAlcohol).toHaveBeenCalledWith('2026-01-01', '2026-01-31');
+ await request(app).get('/api/meatspace/nicotine/daily');
+ expect(nicotine.getDailyNicotine).toHaveBeenCalledWith(undefined, undefined);
+
+ expect((await request(app).get('/api/meatspace/alcohol/daily?from=yesterday')).status).toBe(400);
+ expect((await request(app).get('/api/meatspace/nicotine/daily?to=2026-1-5')).status).toBe(400);
+ });
+});
diff --git a/server/routes/meatspaceAlcoholRoutes.js b/server/routes/meatspaceAlcoholRoutes.js
index 4df098cc2f..9c5d28e4f1 100644
--- a/server/routes/meatspaceAlcoholRoutes.js
+++ b/server/routes/meatspaceAlcoholRoutes.js
@@ -12,6 +12,7 @@ import {
drinkUpdateSchema,
customDrinkSchema,
customDrinkUpdateSchema,
+ dailyRangeQuerySchema,
} from '../lib/meatspaceValidation.js';
import * as alcoholService from '../services/meatspaceAlcohol.js';
@@ -35,7 +36,8 @@ router.get('/alcohol', asyncHandler(async (req, res) => {
* Daily alcohol entries with optional date range
*/
router.get('/alcohol/daily', asyncHandler(async (req, res) => {
- const entries = await alcoholService.getDailyAlcohol(req.query.from, req.query.to);
+ const { from, to } = validateRequest(dailyRangeQuerySchema, req.query);
+ const entries = await alcoholService.getDailyAlcohol(from, to);
res.json(entries);
}));
diff --git a/server/routes/meatspaceNicotineRoutes.js b/server/routes/meatspaceNicotineRoutes.js
index 148c8e6a5c..256dbac640 100644
--- a/server/routes/meatspaceNicotineRoutes.js
+++ b/server/routes/meatspaceNicotineRoutes.js
@@ -12,6 +12,7 @@ import {
nicotineUpdateSchema,
customNicotineProductSchema,
customNicotineProductUpdateSchema,
+ dailyRangeQuerySchema,
} from '../lib/meatspaceValidation.js';
import * as nicotineService from '../services/meatspaceNicotine.js';
@@ -35,7 +36,8 @@ router.get('/nicotine', asyncHandler(async (req, res) => {
* Daily nicotine entries with optional date range
*/
router.get('/nicotine/daily', asyncHandler(async (req, res) => {
- const entries = await nicotineService.getDailyNicotine(req.query.from, req.query.to);
+ const { from, to } = validateRequest(dailyRangeQuerySchema, req.query);
+ const entries = await nicotineService.getDailyNicotine(from, to);
res.json(entries);
}));
diff --git a/server/routes/mediaAnnotations.test.js b/server/routes/mediaAnnotations.test.js
new file mode 100644
index 0000000000..90e28a01be
--- /dev/null
+++ b/server/routes/mediaAnnotations.test.js
@@ -0,0 +1,53 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorEvents, errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/mediaAnnotations.js', () => ({
+ ERR_VALIDATION: 'VALIDATION_ERROR',
+ NOTE_MAX_LENGTH: 2000,
+ listAnnotations: vi.fn(),
+ setAnnotation: vi.fn(),
+}));
+
+import * as svc from '../services/mediaAnnotations.js';
+import mediaAnnotationsRoutes from './mediaAnnotations.js';
+
+// With an io on the app, the error middleware also raises errorEvents 'error',
+// which throws on an EventEmitter with no listener; the server registers one at boot.
+errorEvents.on('error', () => {});
+const io = { emit: vi.fn() };
+const notBroadcast = () => expect(io.emit).not.toHaveBeenCalledWith('media:annotation:updated', expect.anything());
+const app = express();
+app.set('io', io);
+app.use(express.json());
+app.use('/api/media/annotations', mediaAnnotationsRoutes);
+app.use(errorMiddleware);
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('/api/media/annotations', () => {
+ it('writes the local entry and broadcasts it so other open views update', async () => {
+ const entry = { own: { starred: true, note: '' }, others: [] };
+ svc.setAnnotation.mockResolvedValue(entry);
+ const res = await request(app).patch('/api/media/annotations/image:a.png').send({ starred: true });
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ key: 'image:a.png', entry });
+ expect(svc.setAnnotation).toHaveBeenCalledWith('image:a.png', { starred: true });
+ expect(io.emit).toHaveBeenCalledWith('media:annotation:updated', { key: 'image:a.png', entry });
+ });
+
+ it('refuses an empty or over-long patch before touching the store', async () => {
+ expect((await request(app).patch('/api/media/annotations/image:a.png').send({})).status).toBe(400);
+ expect((await request(app).patch('/api/media/annotations/image:a.png').send({ note: 'x'.repeat(2001) })).status).toBe(400);
+ expect(svc.setAnnotation).not.toHaveBeenCalled();
+ notBroadcast();
+ });
+
+ it('maps a service validation refusal (bad key) to 400 and broadcasts nothing', async () => {
+ svc.setAnnotation.mockRejectedValue(Object.assign(new Error('Invalid key: nope'), { code: 'VALIDATION_ERROR' }));
+ const res = await request(app).patch('/api/media/annotations/nope').send({ starred: false });
+ expect(res.status).toBe(400);
+ notBroadcast();
+ });
+});
diff --git a/server/routes/moltworldTools.js b/server/routes/moltworldTools.js
index 88870d2b9f..f939e556c9 100644
--- a/server/routes/moltworldTools.js
+++ b/server/routes/moltworldTools.js
@@ -6,6 +6,7 @@
*/
import { Router } from 'express';
+import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest, moltworldJoinSchema, moltworldBuildSchema, moltworldExploreSchema, moltworldThinkSchema, moltworldSaySchema, moltworldQueueAddSchema, moltworldQueueFailBodySchema } from '../lib/validation.js';
import * as platformAccounts from '../services/platformAccounts.js';
@@ -16,6 +17,8 @@ import * as moltworldQueue from '../services/moltworldQueue.js';
const router = Router();
+const accountQuerySchema = z.object({ accountId: z.string().min(1).max(200) });
+
/**
* Get an authenticated Moltworld client for an account
*/
@@ -193,10 +196,7 @@ router.post('/say', asyncHandler(async (req, res) => {
// GET /status — Agent position, balance, nearby agents
router.get('/status', asyncHandler(async (req, res) => {
- const { accountId } = req.query;
- if (!accountId) {
- throw new ServerError('accountId required', { status: 400, code: 'VALIDATION_ERROR' });
- }
+ const { accountId } = validateRequest(accountQuerySchema, req.query);
console.log(`🌍 GET /api/agents/tools/moltworld/status account=${accountId}`);
@@ -211,10 +211,7 @@ router.get('/status', asyncHandler(async (req, res) => {
// GET /balance — SIM token balance
router.get('/balance', asyncHandler(async (req, res) => {
- const { accountId } = req.query;
- if (!accountId) {
- throw new ServerError('accountId required', { status: 400, code: 'VALIDATION_ERROR' });
- }
+ const { accountId } = validateRequest(accountQuerySchema, req.query);
console.log(`💰 GET /api/agents/tools/moltworld/balance account=${accountId}`);
@@ -225,10 +222,7 @@ router.get('/balance', asyncHandler(async (req, res) => {
// GET /rate-limits — Rate limit status
router.get('/rate-limits', asyncHandler(async (req, res) => {
- const { accountId } = req.query;
- if (!accountId) {
- throw new ServerError('accountId required', { status: 400, code: 'VALIDATION_ERROR' });
- }
+ const { accountId } = validateRequest(accountQuerySchema, req.query);
console.log(`⏱️ GET /api/agents/tools/moltworld/rate-limits account=${accountId}`);
diff --git a/server/routes/moltworldTools.test.js b/server/routes/moltworldTools.test.js
new file mode 100644
index 0000000000..dbe1077a55
--- /dev/null
+++ b/server/routes/moltworldTools.test.js
@@ -0,0 +1,91 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const client = vi.hoisted(() => ({
+ joinWorld: vi.fn(), build: vi.fn(), think: vi.fn(),
+ getProfile: vi.fn(), getBalance: vi.fn(), getRateLimitStatus: vi.fn(),
+}));
+vi.mock('../services/platformAccounts.js', () => ({ getAccountWithCredentials: vi.fn(), recordActivity: vi.fn() }));
+vi.mock('../services/agentPersonalities.js', () => ({ getAgentById: vi.fn() }));
+vi.mock('../services/agentActivity.js', () => ({ logActivity: vi.fn() }));
+vi.mock('../services/moltworldQueue.js', () => ({
+ getQueue: vi.fn(), addAction: vi.fn(), removeAction: vi.fn(), markCompleted: vi.fn(), markFailed: vi.fn(),
+}));
+vi.mock('../integrations/moltworld/index.js', () => ({ createMoltworldClient: vi.fn(() => client) }));
+
+import * as platformAccounts from '../services/platformAccounts.js';
+import * as agentActivity from '../services/agentActivity.js';
+import * as moltworldQueue from '../services/moltworldQueue.js';
+import { createMoltworldClient } from '../integrations/moltworld/index.js';
+import moltworldToolsRoutes from './moltworldTools.js';
+
+const app = express();
+app.use(express.json());
+app.use('/api/agents/tools/moltworld', moltworldToolsRoutes);
+app.use(errorMiddleware);
+const BASE = '/api/agents/tools/moltworld';
+
+const account = (over = {}) => ({
+ id: 'acct-1', status: 'active', platform: 'moltworld',
+ credentials: { apiKey: 'key-example', agentId: 'mw-agent', username: 'example-agent' }, ...over,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ platformAccounts.getAccountWithCredentials.mockResolvedValue(account());
+});
+
+describe('/api/agents/tools/moltworld', () => {
+ it('acts in the world with the account credentials and logs the action for the agent', async () => {
+ client.think.mockResolvedValue({ ok: true });
+ const res = await request(app).post(`${BASE}/think`).send({ accountId: 'acct-1', agentId: 'agent-1', thought: 'hello' });
+ expect(res.status).toBe(200);
+ expect(createMoltworldClient).toHaveBeenCalledWith('key-example', 'mw-agent');
+ expect(client.think).toHaveBeenCalledWith('hello');
+ expect(platformAccounts.recordActivity).toHaveBeenCalledWith('acct-1');
+ expect(agentActivity.logActivity).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'agent-1', action: 'mw_think' }));
+ });
+
+ it('refuses a missing, inactive, or non-Moltworld account before calling the world', async () => {
+ const body = { accountId: 'acct-1', thought: 'hello' };
+ platformAccounts.getAccountWithCredentials.mockResolvedValueOnce(null);
+ expect((await request(app).post(`${BASE}/think`).send(body)).status).toBe(404);
+ platformAccounts.getAccountWithCredentials.mockResolvedValueOnce(account({ status: 'suspended' }));
+ const inactive = await request(app).post(`${BASE}/think`).send(body);
+ expect(inactive.status).toBe(400);
+ expect(inactive.body.code).toBe('ACCOUNT_INACTIVE');
+ platformAccounts.getAccountWithCredentials.mockResolvedValueOnce(account({ platform: 'moltbook' }));
+ const wrong = await request(app).post(`${BASE}/think`).send(body);
+ expect(wrong.body.code).toBe('WRONG_PLATFORM');
+ expect(client.think).not.toHaveBeenCalled();
+ });
+
+ it('rejects a build outside the world bounds', async () => {
+ const res = await request(app).post(`${BASE}/build`).send({ accountId: 'acct-1', x: 9999, y: 0, z: 0 });
+ expect(res.status).toBe(400);
+ expect(client.build).not.toHaveBeenCalled();
+ });
+
+ it('reads status for an account and requires the account id', async () => {
+ client.getProfile.mockResolvedValue({ x: 1, y: 2 });
+ client.getBalance.mockResolvedValue({ sim: 10 });
+ const res = await request(app).get(`${BASE}/status?accountId=acct-1`);
+ expect(res.body).toEqual({ profile: { x: 1, y: 2 }, balance: { sim: 10 } });
+
+ for (const path of ['status', 'balance', 'rate-limits']) {
+ const missing = await request(app).get(`${BASE}/${path}`);
+ expect(missing.status, path).toBe(400);
+ expect(missing.body.code).toBe('VALIDATION_ERROR');
+ }
+ });
+
+ it('answers 404 when a queue item cannot be removed or settled', async () => {
+ moltworldQueue.removeAction.mockReturnValue(null);
+ moltworldQueue.markFailed.mockReturnValue(null);
+ expect((await request(app).delete(`${BASE}/queue/q9`)).status).toBe(404);
+ expect((await request(app).post(`${BASE}/queue/q9/fail`).send({ error: 'boom' })).status).toBe(404);
+ expect(moltworldQueue.markFailed).toHaveBeenCalledWith('q9', 'boom');
+ });
+});
diff --git a/server/routes/moltworldWs.test.js b/server/routes/moltworldWs.test.js
new file mode 100644
index 0000000000..01e8ad4ed0
--- /dev/null
+++ b/server/routes/moltworldWs.test.js
@@ -0,0 +1,52 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/moltworldWs.js', () => ({
+ connect: vi.fn(), disconnect: vi.fn(), getStatus: vi.fn(),
+ sendMove: vi.fn(), sendThink: vi.fn(), sendNearby: vi.fn(), sendInteract: vi.fn(),
+}));
+
+import * as moltworldWs from '../services/moltworldWs.js';
+import moltworldWsRoutes from './moltworldWs.js';
+
+const app = express();
+app.use(express.json());
+app.use('/api/agents/tools/moltworld/ws', moltworldWsRoutes);
+app.use(errorMiddleware);
+const BASE = '/api/agents/tools/moltworld/ws';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ moltworldWs.getStatus.mockReturnValue({ status: 'connected' });
+});
+
+describe('/api/agents/tools/moltworld/ws', () => {
+ it('connects the relay for an account and reports the resulting state', async () => {
+ const res = await request(app).post(`${BASE}/connect`).send({ accountId: 'acct-1' });
+ expect(res.body).toEqual({ status: 'connected' });
+ expect(moltworldWs.connect).toHaveBeenCalledWith('acct-1');
+ });
+
+ it('surfaces a failed connect as an error, not a connected status', async () => {
+ moltworldWs.connect.mockRejectedValue(new Error('Account not found'));
+ const res = await request(app).post(`${BASE}/connect`).send({ accountId: 'acct-1' });
+ expect(res.status).toBe(500);
+ });
+
+ it('relays a move inside the world bounds and refuses one outside them', async () => {
+ const ok = await request(app).post(`${BASE}/move`).send({ x: 10, y: -10, thought: 'walking' });
+ expect(ok.body).toEqual({ sent: true });
+ expect(moltworldWs.sendMove).toHaveBeenCalledWith(10, -10, 'walking');
+
+ moltworldWs.sendMove.mockClear();
+ expect((await request(app).post(`${BASE}/move`).send({ x: 241, y: 0 })).status).toBe(400);
+ expect(moltworldWs.sendMove).not.toHaveBeenCalled();
+ });
+
+ it('defaults an interaction payload to an empty object', async () => {
+ await request(app).post(`${BASE}/interact`).send({ to: 'agent-2' });
+ expect(moltworldWs.sendInteract).toHaveBeenCalledWith('agent-2', {});
+ });
+});
diff --git a/server/routes/mortalloom.test.js b/server/routes/mortalloom.test.js
new file mode 100644
index 0000000000..447f362747
--- /dev/null
+++ b/server/routes/mortalloom.test.js
@@ -0,0 +1,43 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/mortalLoomStore.js', () => ({
+ getStatus: vi.fn(),
+ importToPortOS: vi.fn(),
+ MORTALLOOM_APP_STORE_URL: 'https://apps.apple.com/app/id0000000000',
+}));
+
+import { getStatus, importToPortOS } from '../services/mortalLoomStore.js';
+import mortalloomRoutes from './mortalloom.js';
+
+const app = express();
+app.use(express.json());
+app.use('/api/mortalloom', mortalloomRoutes);
+app.use(errorMiddleware);
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('/api/mortalloom', () => {
+ it('imports the MortalLoom store into PortOS on POST /import', async () => {
+ importToPortOS.mockResolvedValue({ imported: { alcohol: 2 } });
+ const res = await request(app).post('/api/mortalloom/import');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ imported: { alcohol: 2 } });
+ });
+
+ it('reports a failed import through the error envelope', async () => {
+ importToPortOS.mockRejectedValue(new Error('iCloud store unreadable'));
+ const res = await request(app).post('/api/mortalloom/import');
+ expect(res.status).toBe(500);
+ expect(res.body.error).toEqual(expect.any(String));
+ });
+
+ it('serves status and the App Store link without importing', async () => {
+ getStatus.mockResolvedValue({ available: false });
+ expect((await request(app).get('/api/mortalloom/status')).body).toEqual({ available: false });
+ expect((await request(app).get('/api/mortalloom/app-store')).body).toEqual({ url: 'https://apps.apple.com/app/id0000000000' });
+ expect(importToPortOS).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/routes/remoteDesktopViewer.js b/server/routes/remoteDesktopViewer.js
index 392cd3081a..7d371ffcd4 100644
--- a/server/routes/remoteDesktopViewer.js
+++ b/server/routes/remoteDesktopViewer.js
@@ -2,12 +2,17 @@ import express from 'express';
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { z } from 'zod';
+import { failValidation } from '../lib/errorHandler.js';
import { remoteDesktopBroker } from '../services/remoteDesktop.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const viewerTemplate = readFileSync(join(__dirname, '..', 'views', 'remote-desktop.html'), 'utf8');
const vendorRoot = join(__dirname, '..', 'node_modules', '@novnc', 'novnc');
const router = express.Router();
+// A repeated `token` parameter arrives as an array; refuse it rather than let
+// the broker see a non-string.
+const viewerQuerySchema = z.object({ token: z.string().max(512).optional() });
router.use('/vendor', express.static(vendorRoot, {
index: false,
@@ -16,7 +21,9 @@ router.use('/vendor', express.static(vendorRoot, {
}));
router.get('/', (req, res) => {
- const token = req.query.token;
+ const parsed = viewerQuerySchema.safeParse(req.query);
+ if (!parsed.success) failValidation(parsed);
+ const { token } = parsed.data;
if (!remoteDesktopBroker.hasSession(token)) {
res.status(401).type('text/plain').send('This remote desktop link is invalid or expired. Return to PortDeck and start a new session.');
return;
diff --git a/server/routes/remoteDesktopViewer.test.js b/server/routes/remoteDesktopViewer.test.js
new file mode 100644
index 0000000000..231bc59589
--- /dev/null
+++ b/server/routes/remoteDesktopViewer.test.js
@@ -0,0 +1,49 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const broker = vi.hoisted(() => ({ hasSession: vi.fn() }));
+vi.mock('../services/remoteDesktop.js', () => ({ remoteDesktopBroker: broker }));
+
+const { default: viewerRoutes } = await import('./remoteDesktopViewer.js');
+
+const app = express();
+app.use('/remote-desktop', viewerRoutes);
+app.use(errorMiddleware);
+
+const TOKEN = 'a'.repeat(43);
+
+beforeEach(() => { broker.hasSession.mockReset(); });
+
+// The viewer page is served before any API auth: the broker-issued token is the
+// only thing standing between a LAN caller and the VNC bridge page.
+describe('GET /remote-desktop', () => {
+ it('serves the viewer bound to a live session token, uncached and without a referrer', async () => {
+ broker.hasSession.mockReturnValue(true);
+ const res = await request(app).get(`/remote-desktop?token=${TOKEN}`);
+ expect(res.status).toBe(200);
+ expect(res.headers['content-type']).toMatch(/text\/html/);
+ expect(res.headers['cache-control']).toBe('no-store');
+ expect(res.headers['referrer-policy']).toBe('no-referrer');
+ expect(res.text).toContain(TOKEN);
+ expect(res.text).not.toContain('__REMOTE_DESKTOP_TOKEN__');
+ expect(broker.hasSession).toHaveBeenCalledWith(TOKEN);
+ });
+
+ it('refuses an unknown or missing token without echoing it into a page', async () => {
+ broker.hasSession.mockReturnValue(false);
+ for (const path of [`/remote-desktop?token=${TOKEN}`, '/remote-desktop']) {
+ const res = await request(app).get(path);
+ expect(res.status).toBe(401);
+ expect(res.headers['content-type']).toMatch(/text\/plain/);
+ expect(res.text).not.toContain(TOKEN);
+ }
+ });
+
+ it('rejects a repeated token parameter before consulting the broker', async () => {
+ const res = await request(app).get(`/remote-desktop?token=${TOKEN}&token=${TOKEN}`);
+ expect(res.status).toBe(400);
+ expect(broker.hasSession).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/routes/search.test.js b/server/routes/search.test.js
new file mode 100644
index 0000000000..73ef22cae5
--- /dev/null
+++ b/server/routes/search.test.js
@@ -0,0 +1,31 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/search.js', () => ({ fanOutSearch: vi.fn() }));
+
+import { fanOutSearch } from '../services/search.js';
+import searchRoutes from './search.js';
+
+const app = express();
+app.use('/api/search', searchRoutes);
+app.use(errorMiddleware);
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('GET /api/search', () => {
+ it('searches with the trimmed query and echoes it beside the grouped sources', async () => {
+ fanOutSearch.mockResolvedValue([{ id: 'brain', results: [] }]);
+ const res = await request(app).get('/api/search?q=%20%20garden%20%20');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ query: 'garden', sources: [{ id: 'brain', results: [] }] });
+ expect(fanOutSearch).toHaveBeenCalledWith('garden');
+ });
+
+ it('refuses a missing or one-character query without fanning out', async () => {
+ expect((await request(app).get('/api/search')).status).toBe(400);
+ expect((await request(app).get('/api/search?q=a')).status).toBe(400);
+ expect(fanOutSearch).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/routes/signal.test.js b/server/routes/signal.test.js
new file mode 100644
index 0000000000..0c79f0893e
--- /dev/null
+++ b/server/routes/signal.test.js
@@ -0,0 +1,49 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/signalSync.js', () => ({ checkSetup: vi.fn(), getStatus: vi.fn(), runSync: vi.fn() }));
+
+import * as signalSync from '../services/signalSync.js';
+import signalRoutes from './signal.js';
+
+const app = express();
+app.use(express.json());
+app.use('/api/signal', signalRoutes);
+app.use(errorMiddleware);
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('/api/signal', () => {
+ it('runs one sync pass on POST /sync and returns its summary', async () => {
+ signalSync.runSync.mockResolvedValue({ ok: true, imported: 3 });
+ const res = await request(app).post('/api/signal/sync');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ ok: true, imported: 3 });
+ expect(signalSync.runSync).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns a blocked setup report as data rather than an error', async () => {
+ const report = { ok: false, error: 'Signal database key could not be read', code: 'KEY_UNAVAILABLE' };
+ signalSync.checkSetup.mockResolvedValue(report);
+ const res = await request(app).get('/api/signal/setup-check');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual(report);
+ });
+
+ it('turns an unexpected sync failure into the standard error envelope', async () => {
+ signalSync.runSync.mockRejectedValue(new Error('snapshot copy failed'));
+ const res = await request(app).post('/api/signal/sync');
+ expect(res.status).toBe(500);
+ expect(res.body).toMatchObject({ error: expect.any(String) });
+ });
+
+ it('reports status without opening the database', async () => {
+ signalSync.getStatus.mockResolvedValue({ enabled: true, intervalMinutes: 15 });
+ const res = await request(app).get('/api/signal/status');
+ expect(res.body).toEqual({ enabled: true, intervalMinutes: 15 });
+ expect(signalSync.checkSetup).not.toHaveBeenCalled();
+ expect(signalSync.runSync).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/routes/socialAccounts.js b/server/routes/socialAccounts.js
index 68d3213772..14cea83fe1 100644
--- a/server/routes/socialAccounts.js
+++ b/server/routes/socialAccounts.js
@@ -6,15 +6,21 @@
*/
import { Router } from 'express';
+import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validate, validateRequest, socialAccountSchema, socialAccountBulkBodySchema, socialAccountUpdateSchema } from '../lib/validation.js';
import * as socialAccounts from '../services/socialAccounts.js';
const router = Router();
+const listQuerySchema = z.object({
+ platform: z.string().min(1).max(50).optional(),
+ category: z.string().min(1).max(50).optional(),
+});
+
// GET / - List all social accounts
router.get('/', asyncHandler(async (req, res) => {
- const { platform, category } = req.query;
+ const { platform, category } = validateRequest(listQuerySchema, req.query);
let accounts;
if (platform) {
diff --git a/server/routes/socialAccounts.test.js b/server/routes/socialAccounts.test.js
new file mode 100644
index 0000000000..a7b10a69c4
--- /dev/null
+++ b/server/routes/socialAccounts.test.js
@@ -0,0 +1,83 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/socialAccounts.js', () => ({
+ getAllAccounts: vi.fn(),
+ getAccountsByPlatform: vi.fn(),
+ getAccountsByCategory: vi.fn(),
+ getAccountById: vi.fn(),
+ createAccount: vi.fn(),
+ updateAccount: vi.fn(),
+ deleteAccount: vi.fn(),
+ getSupportedPlatforms: vi.fn(),
+ getAccountStats: vi.fn(),
+}));
+
+import * as socialAccounts from '../services/socialAccounts.js';
+import socialAccountsRoutes from './socialAccounts.js';
+
+const app = express();
+app.use(express.json());
+app.use('/api/digital-twin/social-accounts', socialAccountsRoutes);
+app.use(errorMiddleware);
+const BASE = '/api/digital-twin/social-accounts';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ socialAccounts.createAccount.mockImplementation(async (data) => ({ id: 'acct-1', ...data }));
+});
+
+describe('/api/digital-twin/social-accounts', () => {
+ it('creates a valid account with schema defaults and refuses an unknown platform', async () => {
+ const ok = await request(app).post(BASE).send({ platform: 'github', username: 'example-user' });
+ expect(ok.status).toBe(201);
+ expect(socialAccounts.createAccount).toHaveBeenCalledWith(expect.objectContaining({
+ platform: 'github', username: 'example-user', bio: '', contentTypes: [], ingestionEnabled: false,
+ }));
+
+ socialAccounts.createAccount.mockClear();
+ const bad = await request(app).post(BASE).send({ platform: 'myspace', username: 'example-user' });
+ expect(bad.status).toBe(400);
+ expect(bad.body.code).toBe('VALIDATION_ERROR');
+ expect(socialAccounts.createAccount).not.toHaveBeenCalled();
+ });
+
+ it('creates the valid rows of a bulk import and reports the invalid ones', async () => {
+ const res = await request(app).post(`${BASE}/bulk`).send({ accounts: [
+ { platform: 'x', username: 'example-user' },
+ { platform: 'x' },
+ ] });
+ expect(res.status).toBe(201);
+ expect(res.body.summary).toEqual({ created: 1, failed: 1 });
+ expect(res.body.results[1]).toMatchObject({ success: false, input: { platform: 'x' } });
+ expect(socialAccounts.createAccount).toHaveBeenCalledTimes(1);
+ });
+
+ it('filters the list by platform or category from the query string', async () => {
+ socialAccounts.getAccountsByPlatform.mockResolvedValue([{ id: 'a' }]);
+ const res = await request(app).get(`${BASE}?platform=github`);
+ expect(res.body).toEqual({ accounts: [{ id: 'a' }] });
+ expect(socialAccounts.getAccountsByPlatform).toHaveBeenCalledWith('github');
+
+ socialAccounts.getAccountsByCategory.mockResolvedValue([]);
+ await request(app).get(`${BASE}?category=professional`);
+ expect(socialAccounts.getAccountsByCategory).toHaveBeenCalledWith('professional');
+
+ const repeated = await request(app).get(`${BASE}?platform=x&platform=github`);
+ expect(repeated.status).toBe(400);
+ });
+
+ it('answers 404 for a missing account on read, update and delete, and 204 on a real delete', async () => {
+ socialAccounts.getAccountById.mockResolvedValue(null);
+ socialAccounts.updateAccount.mockResolvedValue(null);
+ socialAccounts.deleteAccount.mockResolvedValue(false);
+ expect((await request(app).get(`${BASE}/missing`)).status).toBe(404);
+ expect((await request(app).put(`${BASE}/missing`).send({ bio: 'x' })).status).toBe(404);
+ expect((await request(app).delete(`${BASE}/missing`)).status).toBe(404);
+
+ socialAccounts.deleteAccount.mockResolvedValue(true);
+ expect((await request(app).delete(`${BASE}/acct-1`)).status).toBe(204);
+ });
+});