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 limit and feed query parameters in notifications and agent tools routes (#11769)

[._.]/ Adam Eivy11d7972fa5e5
diff --git a/server/lib/validation.js b/server/lib/validation.js
index baffdaa305..ee73383467 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -4,6 +4,7 @@ export { MAX_IMAGE_EDGE, MAX_IMAGE_PIXELS } from './imageLimits.js';
import { CREDENTIALS } from './credentialRegistry.js';
import { DEFAULT_BACKUP_CRON, MIN_RETENTION_COUNT, MAX_RETENTION_COUNT } from './backupConfig.js';
import { z } from 'zod';
+import { NOTIFICATION_TYPES } from './notificationTypes.js';
import { POLLUTING_KEYS } from './objects.js';
import { pipelineEditorialChecksSettingsSchema } from './pipelineValidation.js';
import { ServerError } from './errorHandler.js';
@@ -1739,6 +1740,26 @@ export const appIconQuerySchema = z.object({
size: z.enum(['64', '128', '256']).default('128').transform(Number),
});
+// Read-route query contracts: a malformed limit is a 400, never a silent
+// negative slice or an ignored NaN.
+export const listNotificationsQuerySchema = z.object({
+ type: z.enum(Object.values(NOTIFICATION_TYPES)).optional(),
+ unreadOnly: z.enum(['true', 'false']).optional(),
+ limit: z.coerce.number().int().min(1).max(1000).optional(),
+});
+
+export const agentToolsFeedQuerySchema = z.object({
+ accountId: z.string().min(1),
+ sort: z.enum(['hot', 'new', 'top', 'rising']).default('hot'),
+ limit: z.coerce.number().int().min(1).max(100).default(25),
+});
+
+export const agentToolsRelevantPostsQuerySchema = z.object({
+ agentId: z.string().min(1),
+ accountId: z.string().min(1),
+ maxResults: z.coerce.number().int().min(1).max(100).default(10),
+});
+
/**
* Validate data against a Zod schema, throwing on failure.
* Returns parsed data on success, throws ServerError on failure.
diff --git a/server/routes/agentTools.js b/server/routes/agentTools.js
index 83ef481542..1483cc906d 100644
--- a/server/routes/agentTools.js
+++ b/server/routes/agentTools.js
@@ -16,7 +16,9 @@ import {
engageSchema,
checkPostsSchema,
createDraftSchema,
- updateDraftSchema
+ updateDraftSchema,
+ agentToolsFeedQuerySchema,
+ agentToolsRelevantPostsQuerySchema
} from '../lib/validation.js';
import * as platformAccounts from '../services/platformAccounts.js';
import * as agentPersonalities from '../services/agentPersonalities.js';
@@ -233,11 +235,7 @@ router.post('/engage', asyncHandler(async (req, res) => {
// GET /feed - Browse Moltbook feed for an account
router.get('/feed', asyncHandler(async (req, res) => {
- const { accountId, sort = 'hot', limit = 25 } = req.query;
-
- if (!accountId) {
- throw new ServerError('accountId required', { status: 400, code: 'VALIDATION_ERROR' });
- }
+ const { accountId, sort, limit } = validateRequest(agentToolsFeedQuerySchema, req.query);
console.log(`🛠️ GET /api/agents/tools/feed account=${accountId} sort=${sort}`);
@@ -247,22 +245,18 @@ router.get('/feed', asyncHandler(async (req, res) => {
}
const client = createMoltbookClient(account.credentials.apiKey);
- const feed = await client.getFeed(sort, parseInt(limit, 10));
+ const feed = await client.getFeed(sort, limit);
res.json(feed);
}));
// GET /relevant-posts - Relevance-scored feed for an agent
router.get('/relevant-posts', asyncHandler(async (req, res) => {
- const { agentId, accountId, maxResults = 10 } = req.query;
-
- if (!agentId || !accountId) {
- throw new ServerError('agentId and accountId required', { status: 400, code: 'VALIDATION_ERROR' });
- }
+ const { agentId, accountId, maxResults } = validateRequest(agentToolsRelevantPostsQuerySchema, req.query);
console.log(`🛠️ GET /api/agents/tools/relevant-posts agent=${agentId}`);
const { client, agent } = await getClientAndAgent(accountId, agentId);
- const posts = await findRelevantPosts(client, agent, { maxResults: parseInt(maxResults, 10) });
+ const posts = await findRelevantPosts(client, agent, { maxResults });
res.json(posts);
}));
diff --git a/server/routes/agentTools.test.js b/server/routes/agentTools.test.js
index 1ead0a77bb..abdcc7b0df 100644
--- a/server/routes/agentTools.test.js
+++ b/server/routes/agentTools.test.js
@@ -107,6 +107,35 @@ describe('Agent Tools Routes', () => {
});
});
+ describe('GET /feed and /relevant-posts query validation', () => {
+ it.each([
+ '/feed?accountId=acc-1&limit=-1',
+ '/feed?accountId=acc-1&limit=0',
+ '/feed?accountId=acc-1&limit=abc',
+ '/feed?accountId=acc-1&limit=101',
+ '/feed?accountId=acc-1&sort=bogus',
+ '/feed?accountId=a&accountId=b',
+ '/feed',
+ '/relevant-posts?agentId=agent-1&accountId=acc-1&maxResults=-1',
+ '/relevant-posts?agentId=agent-1&accountId=acc-1&maxResults=0',
+ '/relevant-posts?agentId=agent-1&accountId=acc-1&maxResults=abc',
+ '/relevant-posts?accountId=acc-1',
+ ])('400s %s before any lookup', async (path) => {
+ const res = await request(app).get(`/api/agents/tools${path}`);
+ expect(res.status).toBe(400);
+ expect(platformAccounts.getAccountWithCredentials).not.toHaveBeenCalled();
+ expect(findRelevantPosts).not.toHaveBeenCalled();
+ });
+
+ it('passes coerced numeric limit and default sort to the client', async () => {
+ platformAccounts.getAccountWithCredentials.mockResolvedValue(ACTIVE_ACCOUNT);
+ moltbookClient.getFeed = vi.fn().mockResolvedValue({ posts: [] });
+ const res = await request(app).get('/api/agents/tools/feed?accountId=acc-1&limit=5');
+ expect(res.status).toBe(200);
+ expect(moltbookClient.getFeed).toHaveBeenCalledWith('hot', 5);
+ });
+ });
+
describe('POST /engage', () => {
it('returns ACCOUNT_INACTIVE (400) for a non-active account', async () => {
platformAccounts.getAccountWithCredentials.mockResolvedValue({ ...ACTIVE_ACCOUNT, status: 'suspended' });
diff --git a/server/routes/notifications.js b/server/routes/notifications.js
index 1641976759..a069daaa05 100644
--- a/server/routes/notifications.js
+++ b/server/routes/notifications.js
@@ -4,19 +4,19 @@
import { Router } from 'express';
import * as notifications from '../services/notifications.js';
+import { validateRequest, listNotificationsQuerySchema } from '../lib/validation.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
const router = Router();
// GET /api/notifications - List all notifications
router.get('/', asyncHandler(async (req, res) => {
- const options = {
- type: req.query.type,
- unreadOnly: req.query.unreadOnly === 'true',
- limit: req.query.limit ? parseInt(req.query.limit, 10) : undefined
- };
-
- const result = await notifications.getNotifications(options);
+ const query = validateRequest(listNotificationsQuerySchema, req.query);
+ const result = await notifications.getNotifications({
+ type: query.type,
+ unreadOnly: query.unreadOnly === 'true',
+ limit: query.limit
+ });
res.json(result);
}));
diff --git a/server/routes/notifications.test.js b/server/routes/notifications.test.js
index 9d97363a91..ca91210282 100644
--- a/server/routes/notifications.test.js
+++ b/server/routes/notifications.test.js
@@ -114,6 +114,17 @@ describe('notifications routes', () => {
});
});
+ describe('GET /api/notifications query validation', () => {
+ it.each(['limit=-1', 'limit=0', 'limit=1001', 'limit=abc', 'limit=1.5', 'type=invalid', 'type=a&type=b', 'unreadOnly=yes'])(
+ 'rejects %s with VALIDATION_ERROR',
+ async (qs) => {
+ const res = await request(buildApp()).get(`/api/notifications?${qs}`);
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ }
+ );
+ });
+
describe('GET /api/notifications/count', () => {
it('returns the unread count', async () => {
notifications.getUnreadCount.mockResolvedValue(7);