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

fix: validate agent-activity route inputs and floor the cleanup retention window (#5714)

[._.]/ Adam Eivy1d72e483690f
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 8216ff9118..35ec11d240 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -8,7 +8,7 @@ import { MAX_MONTHLY_COST } from './subscriptionSavings.js';
import { QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from './generationModes.js';
import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';
import {
- grokVideoDurationSchema, cloudModelIdString, recordRenderPinFields, isSafeSubdirFilter,
+ grokVideoDurationSchema, cloudModelIdString, recordRenderPinFields, isSafeSubdirFilter, csvIdsParam,
} from './sharedSchemas.js';
import { PR_COMPLETION_VALUES } from './prDisposition.js';
import { EFFORT_LEVELS } from './providerModels.js';
@@ -1367,6 +1367,72 @@ export const userActionsListQuerySchema = z.object({
offset: z.coerce.number().int().optional(),
});
+// =============================================================================
+// AGENT ACTIVITY LOG (server/routes/agentActivity.js)
+// =============================================================================
+
+// The activity log is a per-agent, per-day tree of JSON files under
+// `data/agents/activity/<agentId>/<YYYY-MM-DD>.json`. Two things follow:
+// `agentId` is interpolated into a filesystem path, so it is held to a bare
+// filename segment (`isSafeRecordId` on top of the charset, so `..` can't turn
+// a read into a traversal); and the read limits are CLAMPED here rather than in
+// the service, because every handler slices an already-loaded array — an
+// unbounded `limit` is a memory/response-size problem, not a query cost.
+const AGENT_ACTIVITY_MAX_LIMIT = 500;
+const agentActivityLimit = (defaultLimit) =>
+ z.coerce.number().int().min(1).max(AGENT_ACTIVITY_MAX_LIMIT).default(defaultLimit);
+// A blank query value (`?action=` from an unset form field) reads as absent
+// rather than as a 400 — it was `action || null` before this schema existed.
+const agentActivityAction = z.preprocess(emptyToUndefined, z.string().trim().min(1).max(64).optional());
+const agentActivityIds = csvIdsParam({ max: 50, maxIdLength: 128 });
+
+// GET /api/agents/activity
+export const agentActivityQuerySchema = z.object({
+ limit: agentActivityLimit(50),
+ agentIds: agentActivityIds,
+ action: agentActivityAction,
+}).strict();
+
+// GET /api/agents/activity/timeline — `before` is an infinite-scroll cursor the
+// client echoes back from a row's `timestamp`, so it is a full ISO instant.
+export const agentActivityTimelineQuerySchema = z.object({
+ limit: agentActivityLimit(50),
+ agentIds: agentActivityIds,
+ before: z.preprocess(emptyToUndefined, z.string().datetime().optional()),
+}).strict();
+
+export const agentActivityAgentParamsSchema = z.object({
+ agentId: z.string().trim().min(1).max(128)
+ .regex(/^[A-Za-z0-9._-]+$/, 'agentId must be alphanumeric with . _ -')
+ .refine(isSafeRecordId, 'agentId must be a bare filename segment'),
+}).strict();
+
+// GET /api/agents/activity/agent/:agentId — `date` stays a `YYYY-MM-DD` STRING
+// all the way to `getActivityFilePath`, which takes that form directly. Parsing
+// it to a Date first would re-derive the day in local time from a UTC midnight
+// and read the neighbouring file for anyone west of UTC.
+export const agentActivityAgentQuerySchema = z.object({
+ date: z.preprocess(emptyToUndefined, z.string().date().optional()),
+ limit: agentActivityLimit(100),
+ offset: z.coerce.number().int().min(0).default(0),
+ action: agentActivityAction,
+}).strict();
+
+// GET /api/agents/activity/agent/:agentId/stats — one file read per day, so the
+// window is capped at a year rather than left open.
+export const agentActivityStatsQuerySchema = z.object({
+ days: z.coerce.number().int().min(1).max(365).default(7),
+}).strict();
+
+// POST /api/agents/activity/cleanup — unlinks every activity file older than the
+// window. The floor is 1 day, NOT 0: `daysToKeep: 0` puts the cutoff at now and
+// deletes the whole archive, and a negative value reaches into future-dated
+// files. "Delete everything" is not a retention window; if it is ever wanted it
+// gets its own explicitly-named endpoint rather than riding this number.
+export const agentActivityCleanupSchema = z.object({
+ daysToKeep: z.coerce.number().int().min(1).max(3650).default(30),
+}).strict();
+
// =============================================================================
// CLIENT ERROR REPORT
// =============================================================================
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index 73cccab8d4..ef318b8fb4 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest';
import {
+ agentActivityAgentParamsSchema,
processSchema,
appSchema,
appUpdateSchema,
@@ -2296,4 +2297,17 @@ describe('ad-hoc route schemas (#2521)', () => {
expect(eidoverseWorldConfigPatchSchema.safeParse({ notAField: 1 }).success).toBe(false);
});
});
+
+ // The activity log builds a file path out of this id, so the schema — not the
+ // URL layer — is what has to refuse a non-segment (#5714).
+ describe('agentActivityAgentParamsSchema', () => {
+ it('accepts a bare filename segment', () => {
+ expect(agentActivityAgentParamsSchema.safeParse({ agentId: 'agent_a-1.v2' }).success).toBe(true);
+ });
+ it('refuses a dot segment or a path separator', () => {
+ for (const agentId of ['.', '..', '../etc', 'a/b', 'a\\b', 'a b', '']) {
+ expect(agentActivityAgentParamsSchema.safeParse({ agentId }).success).toBe(false);
+ }
+ });
+ });
});
diff --git a/server/routes/agentActivity.js b/server/routes/agentActivity.js
index 09e5926bfc..787ee1a35f 100644
--- a/server/routes/agentActivity.js
+++ b/server/routes/agentActivity.js
@@ -6,7 +6,15 @@
import { Router } from 'express';
import { asyncHandler } from '../lib/errorHandler.js';
-import { validateRequest } from '../lib/validation.js';
+import {
+ validateRequest,
+ agentActivityQuerySchema,
+ agentActivityTimelineQuerySchema,
+ agentActivityAgentParamsSchema,
+ agentActivityAgentQuerySchema,
+ agentActivityStatsQuerySchema,
+ agentActivityCleanupSchema,
+} from '../lib/validation.js';
import { runEventsQuerySchema, runEventProjectionsQuerySchema, runEventProjectionIdSchema, runEventReconcileSchema } from '../lib/cosValidation.js';
import * as agentActivity from '../services/agentActivity.js';
import * as runEventLog from '../services/agentRunEventLog.js';
@@ -16,57 +24,53 @@ const router = Router();
// GET / - Get recent activity across all agents
router.get('/', asyncHandler(async (req, res) => {
- const { limit = 50, agentIds, action } = req.query;
+ const { limit, agentIds, action } = validateRequest(agentActivityQuerySchema, req.query);
- const activities = await agentActivity.getRecentActivities({
- limit: parseInt(limit, 10),
- agentIds: agentIds ? agentIds.split(',') : null,
- action: action || null
- });
-
- res.json(activities);
+ res.json(await agentActivity.getRecentActivities({
+ limit,
+ agentIds: agentIds ?? null,
+ action: action ?? null
+ }));
}));
// GET /timeline - Get activity timeline (for infinite scroll)
router.get('/timeline', asyncHandler(async (req, res) => {
- const { limit = 50, agentIds, before } = req.query;
-
- const activities = await agentActivity.getActivityTimeline({
- limit: parseInt(limit, 10),
- agentIds: agentIds ? agentIds.split(',') : null,
- beforeTimestamp: before || null
- });
+ const { limit, agentIds, before } = validateRequest(agentActivityTimelineQuerySchema, req.query);
- res.json(activities);
+ res.json(await agentActivity.getActivityTimeline({
+ limit,
+ agentIds: agentIds ?? null,
+ beforeTimestamp: before ?? null
+ }));
}));
// GET /agent/:agentId - Get activities for specific agent
router.get('/agent/:agentId', asyncHandler(async (req, res) => {
- const { agentId } = req.params;
- const { date, limit = 100, offset = 0, action } = req.query;
-
- const activities = await agentActivity.getActivities(agentId, {
- date: date ? new Date(date) : new Date(),
- limit: parseInt(limit, 10),
- offset: parseInt(offset, 10),
- action: action || null
- });
-
- res.json(activities);
+ const { agentId } = validateRequest(agentActivityAgentParamsSchema, req.params);
+ const { date, limit, offset, action } = validateRequest(agentActivityAgentQuerySchema, req.query);
+
+ res.json(await agentActivity.getActivities(agentId, {
+ // A `YYYY-MM-DD` string, which getActivityFilePath consumes as-is.
+ date: date ?? null,
+ limit,
+ offset,
+ action: action ?? null
+ }));
}));
// GET /agent/:agentId/stats - Get activity stats for agent
router.get('/agent/:agentId/stats', asyncHandler(async (req, res) => {
- const { agentId } = req.params;
- const { days = 7 } = req.query;
+ const { agentId } = validateRequest(agentActivityAgentParamsSchema, req.params);
+ const { days } = validateRequest(agentActivityStatsQuerySchema, req.query);
- const stats = await agentActivity.getAgentStats(agentId, parseInt(days, 10));
- res.json(stats);
+ res.json(await agentActivity.getAgentStats(agentId, days));
}));
-// POST /cleanup - Clean up old activity files
+// POST /cleanup - Clean up old activity files. Destructive: it unlinks every
+// day file older than the window, so the schema's 1-day floor is what stands
+// between a mistyped client call and the whole archive.
router.post('/cleanup', asyncHandler(async (req, res) => {
- const { daysToKeep = 30 } = req.body;
+ const { daysToKeep } = validateRequest(agentActivityCleanupSchema, req.body ?? {});
const deletedCount = await agentActivity.cleanupOldActivity(daysToKeep);
res.json({ success: true, deletedCount });
diff --git a/server/routes/agentActivity.test.js b/server/routes/agentActivity.test.js
index 0de335f403..b9dfca5ff4 100644
--- a/server/routes/agentActivity.test.js
+++ b/server/routes/agentActivity.test.js
@@ -14,7 +14,7 @@ const mocks = vi.hoisted(() => ({
vi.mock('../services/agentRunEventLog.js', () => mocks);
vi.mock('../services/agentRunReconciler.js', () => mocks);
-vi.mock('../services/agentActivity.js', () => ({
+const activityMocks = vi.hoisted(() => ({
getRecentActivities: vi.fn(async () => []),
getActivityTimeline: vi.fn(async () => []),
getActivities: vi.fn(async () => []),
@@ -22,6 +22,8 @@ vi.mock('../services/agentActivity.js', () => ({
cleanupOldActivity: vi.fn(async () => 0),
}));
+vi.mock('../services/agentActivity.js', () => activityMocks);
+
import agentActivityRoutes from './agentActivity.js';
const app = () => {
@@ -171,3 +173,153 @@ describe('/run-events/reconcile', () => {
expect((await post('/run-events/reconcile', { force: true })).status).toBe(400);
});
});
+
+// ---------------------------------------------------------------------------
+// Activity-log input validation (#5714). Before this, `limit` was a bare
+// parseInt, `agentIds` an uncapped split(','), `date` went straight to
+// `new Date()`, and `daysToKeep` reached a function that unlinks files.
+// ---------------------------------------------------------------------------
+
+describe('activity route validation', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('POST /cleanup', () => {
+ it('refuses a zero-day window instead of wiping the archive', async () => {
+ const res = await post('/cleanup', { daysToKeep: 0 });
+ expect(res.status).toBe(400);
+ expect(activityMocks.cleanupOldActivity).not.toHaveBeenCalled();
+ });
+
+ it('refuses a negative window, which would reach future-dated files', async () => {
+ expect((await post('/cleanup', { daysToKeep: -5 })).status).toBe(400);
+ expect(activityMocks.cleanupOldActivity).not.toHaveBeenCalled();
+ });
+
+ it('refuses a non-numeric window', async () => {
+ expect((await post('/cleanup', { daysToKeep: 'abc' })).status).toBe(400);
+ expect(activityMocks.cleanupOldActivity).not.toHaveBeenCalled();
+ });
+
+ it('defaults an empty body to the 30-day window', async () => {
+ const res = await post('/cleanup', {});
+ expect(res.status).toBe(200);
+ expect(activityMocks.cleanupOldActivity).toHaveBeenCalledWith(30);
+ });
+
+ it('passes a valid window through as a number', async () => {
+ await post('/cleanup', { daysToKeep: '7' });
+ expect(activityMocks.cleanupOldActivity).toHaveBeenCalledWith(7);
+ });
+
+ it('rejects an unknown body field rather than ignoring it', async () => {
+ expect((await post('/cleanup', { daysToKeep: 30, force: true })).status).toBe(400);
+ });
+ });
+
+ describe('GET /', () => {
+ it('clamps the list limit server-side', async () => {
+ expect((await get('/?limit=999999')).status).toBe(400);
+ expect((await get('/?limit=0')).status).toBe(400);
+ expect(activityMocks.getRecentActivities).not.toHaveBeenCalled();
+ });
+
+ it('parses agentIds into a capped array, not a raw split', async () => {
+ const res = await get('/?limit=10&agentIds=a-1,%20a-2%20');
+ expect(res.status).toBe(200);
+ expect(activityMocks.getRecentActivities).toHaveBeenCalledWith({
+ limit: 10,
+ agentIds: ['a-1', 'a-2'],
+ action: null,
+ });
+ });
+
+ it('treats a blank filter value as absent, not as a 400', async () => {
+ const res = await get('/?action=&agentIds=');
+ expect(res.status).toBe(200);
+ expect(activityMocks.getRecentActivities).toHaveBeenCalledWith({
+ limit: 50,
+ agentIds: null,
+ action: null,
+ });
+ });
+
+ it('rejects an agentIds batch past the cap', async () => {
+ const tooMany = Array.from({ length: 51 }, (_, i) => `a${i}`).join(',');
+ expect((await get(`/?agentIds=${tooMany}`)).status).toBe(400);
+ });
+
+ it('defaults limit and passes absent filters as null', async () => {
+ await get('/');
+ expect(activityMocks.getRecentActivities).toHaveBeenCalledWith({
+ limit: 50,
+ agentIds: null,
+ action: null,
+ });
+ });
+ });
+
+ describe('GET /timeline', () => {
+ it('requires a full ISO instant for the scroll cursor', async () => {
+ expect((await get('/timeline?before=not-a-date')).status).toBe(400);
+ expect(activityMocks.getActivityTimeline).not.toHaveBeenCalled();
+ });
+
+ it('forwards a valid cursor and coerced limit', async () => {
+ const res = await get('/timeline?limit=25&before=2026-08-23T00:00:05.000Z');
+ expect(res.status).toBe(200);
+ expect(activityMocks.getActivityTimeline).toHaveBeenCalledWith({
+ limit: 25,
+ agentIds: null,
+ beforeTimestamp: '2026-08-23T00:00:05.000Z',
+ });
+ });
+ });
+
+ describe('GET /agent/:agentId', () => {
+ it('rejects a traversal segment in the agent id', async () => {
+ // The separator is percent-encoded so the path survives URL normalization
+ // and arrives as one decoded param — `agentId` is interpolated straight
+ // into `data/agents/activity/<agentId>/<date>.json`.
+ expect((await get('/agent/..%2fetc')).status).toBe(400);
+ expect((await get('/agent/%2e%2e%2fetc')).status).toBe(400);
+ expect((await get('/agent/a b')).status).toBe(400);
+ expect(activityMocks.getActivities).not.toHaveBeenCalled();
+ });
+
+ it('hands the date through as a YYYY-MM-DD string, never a Date', async () => {
+ const res = await get('/agent/agent-a?date=2026-08-22&limit=10&offset=5');
+ expect(res.status).toBe(200);
+ expect(activityMocks.getActivities).toHaveBeenCalledWith('agent-a', {
+ date: '2026-08-22',
+ limit: 10,
+ offset: 5,
+ action: null,
+ });
+ });
+
+ it('rejects a free-form date string', async () => {
+ expect((await get('/agent/agent-a?date=yesterday')).status).toBe(400);
+ expect(activityMocks.getActivities).not.toHaveBeenCalled();
+ });
+
+ it('clamps the limit and refuses a negative offset', async () => {
+ expect((await get('/agent/agent-a?limit=999999')).status).toBe(400);
+ expect((await get('/agent/agent-a?offset=-1')).status).toBe(400);
+ });
+ });
+
+ describe('GET /agent/:agentId/stats', () => {
+ it('bounds the stats window, which is one file read per day', async () => {
+ expect((await get('/agent/agent-a/stats?days=100000')).status).toBe(400);
+ expect((await get('/agent/agent-a/stats?days=0')).status).toBe(400);
+ expect(activityMocks.getAgentStats).not.toHaveBeenCalled();
+ });
+
+ it('defaults to a 7-day window as a number', async () => {
+ await get('/agent/agent-a/stats');
+ expect(activityMocks.getAgentStats).toHaveBeenCalledWith('agent-a', 7);
+ });
+ });
+});
diff --git a/server/services/agentActivity.js b/server/services/agentActivity.js
index c4ea19555e..e9d074f6c7 100644
--- a/server/services/agentActivity.js
+++ b/server/services/agentActivity.js
@@ -310,12 +310,29 @@ export async function getActivityTimeline(options = {}) {
return activities.slice(0, limit);
}
+// Smallest retention window this function will honour. A caller asking for 0
+// puts the cutoff at now and unlinks the ENTIRE archive; a negative value walks
+// the cutoff into the future and takes today's file with it. Neither is a
+// retention window, so both fall back to the default rather than deleting.
+const MIN_DAYS_TO_KEEP = 1;
+const DEFAULT_DAYS_TO_KEEP = 30;
+
/**
- * Clean up old activity files (older than N days)
+ * Clean up old activity files (older than N days).
+ *
+ * The floor lives here and not only at the HTTP boundary because schedulers
+ * call this directly.
*/
-export async function cleanupOldActivity(daysToKeep = 30) {
+export async function cleanupOldActivity(daysToKeep = DEFAULT_DAYS_TO_KEEP) {
+ const days = Number.isInteger(daysToKeep) && daysToKeep >= MIN_DAYS_TO_KEEP
+ ? daysToKeep
+ : DEFAULT_DAYS_TO_KEEP;
+ if (days !== daysToKeep) {
+ console.warn(`⚠️ Ignoring unusable activity retention window ${daysToKeep}; keeping ${days} days`);
+ }
+
const cutoffDate = new Date();
- cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);
+ cutoffDate.setDate(cutoffDate.getDate() - days);
let deletedCount = 0;
diff --git a/server/services/agentActivity.test.js b/server/services/agentActivity.test.js
index d8263909e3..7308dc1c45 100644
--- a/server/services/agentActivity.test.js
+++ b/server/services/agentActivity.test.js
@@ -1,5 +1,5 @@
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
-import { mkdir, rm, writeFile } from 'fs/promises';
+import { mkdir, readdir, rm, writeFile } from 'fs/promises';
import { join } from 'path';
import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
@@ -10,7 +10,7 @@ vi.mock('../lib/fileUtils.js', async () => {
return makeProxy(actual);
});
-const { getActivityTimeline } = await import('./agentActivity.js');
+const { cleanupOldActivity, getActivityTimeline } = await import('./agentActivity.js');
const activityRoot = join(tempRoot, 'agents', 'activity');
@@ -73,3 +73,41 @@ describe('getActivityTimeline', () => {
]);
});
});
+
+// A destructive-action guard: `cleanupOldActivity` unlinks day files, and the
+// service is called from schedulers as well as the HTTP route, so the floor
+// cannot live only at the request boundary (#5714).
+describe('cleanupOldActivity', () => {
+ beforeEach(async () => {
+ await rm(activityRoot, { recursive: true, force: true });
+ vi.restoreAllMocks();
+ });
+
+ const seedTodayAndOld = async () => {
+ const today = new Date();
+ const iso = (d) => d.toISOString().slice(0, 10);
+ const old = new Date(today);
+ old.setDate(old.getDate() - 400);
+ await writeDay('agent-a', iso(today), [entry('today', today.toISOString())]);
+ await writeDay('agent-a', iso(old), [entry('ancient', old.toISOString())]);
+ return { today: iso(today), old: iso(old) };
+ };
+
+ const dayFiles = async () => (await readdir(join(activityRoot, 'agent-a'))).sort();
+
+ it.each([0, -5, 1.5, 'abc', null])('falls back to 30 days for %s', async (bad) => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const { today } = await seedTodayAndOld();
+
+ await expect(cleanupOldActivity(bad)).resolves.toBe(1);
+ // The ancient file goes; today's survives — the whole archive does not.
+ await expect(dayFiles()).resolves.toEqual([`${today}.json`]);
+ });
+
+ it('honours a real retention window', async () => {
+ const { today, old } = await seedTodayAndOld();
+
+ await expect(cleanupOldActivity(3650)).resolves.toBe(0);
+ await expect(dayFiles()).resolves.toEqual([`${old}.json`, `${today}.json`].sort());
+ });
+});