Nyk commited on
Commit
bfccd36
·
1 Parent(s): 8922356

feat: v1.2.0 — validation hardening, unit tests, quality improvements

Browse files

- Fix task status enum mismatch (blocked → quality_review)
- Add 12 Zod schemas for all unvalidated mutation routes
- Apply validateBody() across 11 API route handlers
- Add readLimiter (120/min) for GET-heavy endpoints
- Extend heavyLimiter to search, backup, cleanup routes
- Add security headers (X-Content-Type-Options, X-Frame-Options, Referrer-Policy)
- Fill auth test stubs with real assertions (safeCompare, requireRole)
- Add validation, rate-limit, and db-helpers unit test suites (60 tests total)
- Replace as-any casts with typed interfaces (SessionQueryRow, UserQueryRow, CountRow)
- Bump version to 1.2.0, add CHANGELOG.md, update README roadmap

CHANGELOG.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ All notable changes to Mission Control are documented in this file.
4
+
5
+ ## [1.2.0] - 2026-03-01
6
+
7
+ ### Added
8
+ - Zod input validation schemas for all mutation API routes
9
+ - Security headers (X-Content-Type-Options, X-Frame-Options, Referrer-Policy)
10
+ - Rate limiting on resource-intensive endpoints (search, backup, cleanup, memory, logs)
11
+ - Unit tests for auth, validation, rate-limit, and db-helpers modules
12
+
13
+ ### Fixed
14
+ - Task status enum mismatch (`blocked` → `quality_review`) in validation schema
15
+ - Type safety improvements in auth.ts and db.ts (replaced `as any` casts)
16
+
17
+ ### Changed
18
+ - Standardized alert route to use `validateBody()` helper
19
+ - Bumped package version from 1.0.0 to 1.2.0
20
+
21
+ ## [1.1.0] - 2026-02-27
22
+
23
+ ### Added
24
+ - Multi-user authentication with session management
25
+ - Google SSO with admin approval workflow
26
+ - Role-based access control (admin, operator, viewer)
27
+ - Audit logging for security events
28
+ - 1Password integration for secrets management
29
+ - Workflow templates and pipeline orchestration
30
+ - Quality review system with approval gates
31
+ - Data export (CSV/JSON) for audit logs, tasks, activities
32
+ - Global search across all entities
33
+ - Settings management UI
34
+ - Gateway configuration editor
35
+ - Notification system with @mentions
36
+ - Agent communication (direct messages)
37
+ - Standup report generation
38
+ - Scheduled auto-backup and auto-cleanup
39
+ - Network access control (host allowlist)
40
+ - CSRF origin validation
41
+
42
+ ## [1.0.0] - 2026-02-15
43
+
44
+ ### Added
45
+ - Agent orchestration dashboard with real-time status
46
+ - Task management with Kanban board
47
+ - Activity stream with live updates (SSE)
48
+ - Agent spawn and session management
49
+ - Webhook integration with HMAC signatures
50
+ - Alert rules engine with condition evaluation
51
+ - Token usage tracking and cost estimation
52
+ - Dark/light theme support
53
+ - Docker deployment support
README.md CHANGED
@@ -315,19 +315,26 @@ pnpm quality:gate # All checks
315
 
316
  See [open issues](https://github.com/builderz-labs/mission-control/issues) for planned work and the [v1.0.0 release notes](https://github.com/builderz-labs/mission-control/releases/tag/v1.0.0) for what shipped.
317
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  **Up next:**
319
 
320
- - [ ] Dockerfile and docker-compose.yml ([#34](https://github.com/builderz-labs/mission-control/issues/34))
321
- - [ ] Implement session control actions — monitor/pause/terminate are stub buttons ([#35](https://github.com/builderz-labs/mission-control/issues/35))
322
- - [ ] Dynamic model catalog replace hardcoded pricing across 3 files ([#36](https://github.com/builderz-labs/mission-control/issues/36))
323
- - [ ] API-wide rate limiting ([#37](https://github.com/builderz-labs/mission-control/issues/37))
324
- - [ ] React error boundaries around panels ([#38](https://github.com/builderz-labs/mission-control/issues/38))
325
- - [ ] Structured logging with pino ([#39](https://github.com/builderz-labs/mission-control/issues/39))
326
- - [ ] Accessibility improvements — WCAG 2.1 AA ([#40](https://github.com/builderz-labs/mission-control/issues/40))
327
- - [ ] HSTS header for TLS deployments ([#41](https://github.com/builderz-labs/mission-control/issues/41))
328
- - [ ] Input validation with zod schemas ([#42](https://github.com/builderz-labs/mission-control/issues/42))
329
- - [ ] Export endpoint row limits ([#43](https://github.com/builderz-labs/mission-control/issues/43))
330
- - [ ] Fill in Vitest unit test stubs with real assertions
331
  - [ ] API token rotation UI
332
  - [ ] Webhook signature verification
333
 
 
315
 
316
  See [open issues](https://github.com/builderz-labs/mission-control/issues) for planned work and the [v1.0.0 release notes](https://github.com/builderz-labs/mission-control/releases/tag/v1.0.0) for what shipped.
317
 
318
+ **Completed:**
319
+
320
+ - [x] Dockerfile and docker-compose.yml ([#34](https://github.com/builderz-labs/mission-control/issues/34))
321
+ - [x] Implement session control actions — monitor/pause/terminate are stub buttons ([#35](https://github.com/builderz-labs/mission-control/issues/35))
322
+ - [x] Dynamic model catalog — replace hardcoded pricing across 3 files ([#36](https://github.com/builderz-labs/mission-control/issues/36))
323
+ - [x] API-wide rate limiting ([#37](https://github.com/builderz-labs/mission-control/issues/37))
324
+ - [x] React error boundaries around panels ([#38](https://github.com/builderz-labs/mission-control/issues/38))
325
+ - [x] Structured logging with pino ([#39](https://github.com/builderz-labs/mission-control/issues/39))
326
+ - [x] Accessibility improvements — WCAG 2.1 AA ([#40](https://github.com/builderz-labs/mission-control/issues/40))
327
+ - [x] HSTS header for TLS deployments ([#41](https://github.com/builderz-labs/mission-control/issues/41))
328
+ - [x] Input validation with zod schemas ([#42](https://github.com/builderz-labs/mission-control/issues/42))
329
+ - [x] Export endpoint row limits ([#43](https://github.com/builderz-labs/mission-control/issues/43))
330
+ - [x] Fill in Vitest unit test stubs with real assertions
331
+
332
  **Up next:**
333
 
334
+ - [ ] Native macOS app
335
+ - [ ] OpenAPI / Swagger documentation
336
+ - [ ] Webhook retry with exponential backoff
337
+ - [ ] OAuth approval UI improvements
 
 
 
 
 
 
 
338
  - [ ] API token rotation UI
339
  - [ ] Webhook signature verification
340
 
middleware.ts CHANGED
@@ -49,6 +49,13 @@ function hostMatches(pattern: string, hostname: string): boolean {
49
  return h === p
50
  }
51
 
 
 
 
 
 
 
 
52
  export function middleware(request: NextRequest) {
53
  // Network access control.
54
  // In production: default-deny unless explicitly allowed.
@@ -84,7 +91,7 @@ export function middleware(request: NextRequest) {
84
 
85
  // Allow login page and auth API without session
86
  if (pathname === '/login' || pathname.startsWith('/api/auth/')) {
87
- return NextResponse.next()
88
  }
89
 
90
  // Check for session cookie
@@ -94,7 +101,7 @@ export function middleware(request: NextRequest) {
94
  if (pathname.startsWith('/api/')) {
95
  const apiKey = request.headers.get('x-api-key')
96
  if (sessionToken || (apiKey && safeCompare(apiKey, process.env.API_KEY || ''))) {
97
- return NextResponse.next()
98
  }
99
 
100
  return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
@@ -102,7 +109,7 @@ export function middleware(request: NextRequest) {
102
 
103
  // Page routes: redirect to login if no session
104
  if (sessionToken) {
105
- return NextResponse.next()
106
  }
107
 
108
  // Redirect to login
 
49
  return h === p
50
  }
51
 
52
+ function applySecurityHeaders(response: NextResponse): NextResponse {
53
+ response.headers.set('X-Content-Type-Options', 'nosniff')
54
+ response.headers.set('X-Frame-Options', 'DENY')
55
+ response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin')
56
+ return response
57
+ }
58
+
59
  export function middleware(request: NextRequest) {
60
  // Network access control.
61
  // In production: default-deny unless explicitly allowed.
 
91
 
92
  // Allow login page and auth API without session
93
  if (pathname === '/login' || pathname.startsWith('/api/auth/')) {
94
+ return applySecurityHeaders(NextResponse.next())
95
  }
96
 
97
  // Check for session cookie
 
101
  if (pathname.startsWith('/api/')) {
102
  const apiKey = request.headers.get('x-api-key')
103
  if (sessionToken || (apiKey && safeCompare(apiKey, process.env.API_KEY || ''))) {
104
+ return applySecurityHeaders(NextResponse.next())
105
  }
106
 
107
  return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
 
109
 
110
  // Page routes: redirect to login if no session
111
  if (sessionToken) {
112
+ return applySecurityHeaders(NextResponse.next())
113
  }
114
 
115
  // Redirect to login
package.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "name": "mission-control",
3
- "version": "1.0.0",
4
  "description": "OpenClaw Mission Control — open-source agent orchestration dashboard",
5
  "scripts": {
6
  "dev": "next dev --hostname 127.0.0.1",
 
1
  {
2
  "name": "mission-control",
3
+ "version": "1.2.0",
4
  "description": "OpenClaw Mission Control — open-source agent orchestration dashboard",
5
  "scripts": {
6
  "dev": "next dev --hostname 127.0.0.1",
src/app/api/agents/message/route.ts CHANGED
@@ -2,23 +2,20 @@ import { NextRequest, NextResponse } from 'next/server'
2
  import { getDatabase, db_helpers } from '@/lib/db'
3
  import { runOpenClaw } from '@/lib/command'
4
  import { requireRole } from '@/lib/auth'
 
 
5
 
6
  export async function POST(request: NextRequest) {
7
  const auth = requireRole(request, 'operator')
8
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
9
 
10
- try {
11
- const body = await request.json()
12
- const from = (body.from || 'system') as string
13
- const to = (body.to || '').trim()
14
- const message = (body.message || '').trim()
15
 
16
- if (!to || !message) {
17
- return NextResponse.json(
18
- { error: 'Both "to" and "message" are required' },
19
- { status: 400 }
20
- )
21
- }
22
 
23
  const db = getDatabase()
24
  const agent = db.prepare('SELECT * FROM agents WHERE name = ?').get(to) as any
 
2
  import { getDatabase, db_helpers } from '@/lib/db'
3
  import { runOpenClaw } from '@/lib/command'
4
  import { requireRole } from '@/lib/auth'
5
+ import { validateBody, createMessageSchema } from '@/lib/validation'
6
+ import { mutationLimiter } from '@/lib/rate-limit'
7
 
8
  export async function POST(request: NextRequest) {
9
  const auth = requireRole(request, 'operator')
10
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
11
 
12
+ const rateCheck = mutationLimiter(request)
13
+ if (rateCheck) return rateCheck
 
 
 
14
 
15
+ try {
16
+ const result = await validateBody(request, createMessageSchema)
17
+ if ('error' in result) return result.error
18
+ const { from, to, message } = result.data
 
 
19
 
20
  const db = getDatabase()
21
  const agent = db.prepare('SELECT * FROM agents WHERE name = ?').get(to) as any
src/app/api/alerts/route.ts CHANGED
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
2
  import { requireRole } from '@/lib/auth'
3
  import { getDatabase } from '@/lib/db'
4
  import { mutationLimiter } from '@/lib/rate-limit'
5
- import { createAlertSchema } from '@/lib/validation'
6
 
7
  interface AlertRule {
8
  id: number
@@ -50,15 +50,19 @@ export async function POST(request: NextRequest) {
50
  if (rateCheck) return rateCheck
51
 
52
  const db = getDatabase()
53
- const body = await request.json()
54
 
55
- // Evaluate all enabled rules
56
- if (body.action === 'evaluate') {
 
 
 
 
 
57
  return evaluateRules(db)
58
  }
59
 
60
- // Validate for create
61
- const parseResult = createAlertSchema.safeParse(body)
62
  if (!parseResult.success) {
63
  const messages = parseResult.error.issues.map((e: any) => `${e.path.join('.')}: ${e.message}`)
64
  return NextResponse.json({ error: 'Validation failed', details: messages }, { status: 400 })
 
2
  import { requireRole } from '@/lib/auth'
3
  import { getDatabase } from '@/lib/db'
4
  import { mutationLimiter } from '@/lib/rate-limit'
5
+ import { createAlertSchema, validateBody } from '@/lib/validation'
6
 
7
  interface AlertRule {
8
  id: number
 
50
  if (rateCheck) return rateCheck
51
 
52
  const db = getDatabase()
 
53
 
54
+ // Check for evaluate action first (peek at body without consuming)
55
+ let rawBody: any
56
+ try { rawBody = await request.json() } catch {
57
+ return NextResponse.json({ error: 'Invalid request body' }, { status: 400 })
58
+ }
59
+
60
+ if (rawBody.action === 'evaluate') {
61
  return evaluateRules(db)
62
  }
63
 
64
+ // Validate for create using schema
65
+ const parseResult = createAlertSchema.safeParse(rawBody)
66
  if (!parseResult.success) {
67
  const messages = parseResult.error.issues.map((e: any) => `${e.path.join('.')}: ${e.message}`)
68
  return NextResponse.json({ error: 'Validation failed', details: messages }, { status: 400 })
src/app/api/auth/access-requests/route.ts CHANGED
@@ -2,6 +2,8 @@ import { randomBytes } from 'crypto'
2
  import { NextRequest, NextResponse } from 'next/server'
3
  import { createUser, getUserFromRequest , requireRole } from '@/lib/auth'
4
  import { getDatabase, logAuditEvent } from '@/lib/db'
 
 
5
 
6
  function makeUsernameFromEmail(email: string): string {
7
  const base = email.split('@')[0].replace(/[^a-z0-9._-]/gi, '').toLowerCase() || 'user'
@@ -62,22 +64,14 @@ export async function POST(request: NextRequest) {
62
  return NextResponse.json({ error: 'Admin access required' }, { status: 403 })
63
  }
64
 
 
 
 
 
 
 
65
  const db = getDatabase()
66
- const body = await request.json().catch(() => ({}))
67
- const requestId = Number(body?.request_id)
68
- const action = String(body?.action || '')
69
- const role = String(body?.role || 'viewer') as 'admin' | 'operator' | 'viewer'
70
- const note = body?.note ? String(body.note) : null
71
-
72
- if (!Number.isInteger(requestId) || requestId <= 0) {
73
- return NextResponse.json({ error: 'request_id is required' }, { status: 400 })
74
- }
75
- if (!['approve', 'reject'].includes(action)) {
76
- return NextResponse.json({ error: 'action must be approve or reject' }, { status: 400 })
77
- }
78
- if (!['admin', 'operator', 'viewer'].includes(role)) {
79
- return NextResponse.json({ error: 'Invalid role' }, { status: 400 })
80
- }
81
 
82
  const reqRow = db.prepare('SELECT * FROM access_requests WHERE id = ?').get(requestId) as any
83
  if (!reqRow) return NextResponse.json({ error: 'Request not found' }, { status: 404 })
 
2
  import { NextRequest, NextResponse } from 'next/server'
3
  import { createUser, getUserFromRequest , requireRole } from '@/lib/auth'
4
  import { getDatabase, logAuditEvent } from '@/lib/db'
5
+ import { validateBody, accessRequestActionSchema } from '@/lib/validation'
6
+ import { mutationLimiter } from '@/lib/rate-limit'
7
 
8
  function makeUsernameFromEmail(email: string): string {
9
  const base = email.split('@')[0].replace(/[^a-z0-9._-]/gi, '').toLowerCase() || 'user'
 
64
  return NextResponse.json({ error: 'Admin access required' }, { status: 403 })
65
  }
66
 
67
+ const rateCheck = mutationLimiter(request)
68
+ if (rateCheck) return rateCheck
69
+
70
+ const result = await validateBody(request, accessRequestActionSchema)
71
+ if ('error' in result) return result.error
72
+
73
  const db = getDatabase()
74
+ const { request_id: requestId, action, role, note } = result.data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  const reqRow = db.prepare('SELECT * FROM access_requests WHERE id = ?').get(requestId) as any
77
  if (!reqRow) return NextResponse.json({ error: 'Request not found' }, { status: 404 })
src/app/api/auth/users/route.ts CHANGED
@@ -1,6 +1,8 @@
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { getUserFromRequest, getAllUsers, createUser, updateUser, deleteUser , requireRole } from '@/lib/auth'
3
  import { logAuditEvent } from '@/lib/db'
 
 
4
 
5
  /**
6
  * GET /api/auth/users - List all users (admin only)
@@ -27,18 +29,15 @@ export async function POST(request: NextRequest) {
27
  return NextResponse.json({ error: 'Admin access required' }, { status: 403 })
28
  }
29
 
30
- try {
31
- const { username, password, display_name, role = 'operator', provider = 'local', email = null } = await request.json()
32
-
33
- if (!username || !password) {
34
- return NextResponse.json({ error: 'Username and password are required' }, { status: 400 })
35
- }
36
 
37
- if (!['admin', 'operator', 'viewer'].includes(role)) {
38
- return NextResponse.json({ error: 'Invalid role' }, { status: 400 })
39
- }
 
40
 
41
- const newUser = createUser(username, password, display_name || username, role, { provider, email })
42
 
43
  const ipAddress = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown'
44
  logAuditEvent({
 
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { getUserFromRequest, getAllUsers, createUser, updateUser, deleteUser , requireRole } from '@/lib/auth'
3
  import { logAuditEvent } from '@/lib/db'
4
+ import { validateBody, createUserSchema } from '@/lib/validation'
5
+ import { mutationLimiter } from '@/lib/rate-limit'
6
 
7
  /**
8
  * GET /api/auth/users - List all users (admin only)
 
29
  return NextResponse.json({ error: 'Admin access required' }, { status: 403 })
30
  }
31
 
32
+ const rateCheck = mutationLimiter(request)
33
+ if (rateCheck) return rateCheck
 
 
 
 
34
 
35
+ try {
36
+ const result = await validateBody(request, createUserSchema)
37
+ if ('error' in result) return result.error
38
+ const { username, password, display_name, role, provider, email } = result.data
39
 
40
+ const newUser = createUser(username, password, display_name || username, role, { provider, email: email || null })
41
 
42
  const ipAddress = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown'
43
  logAuditEvent({
src/app/api/backup/route.ts CHANGED
@@ -4,6 +4,7 @@ import { getDatabase, logAuditEvent } from '@/lib/db'
4
  import { config, ensureDirExists } from '@/lib/config'
5
  import { join, dirname } from 'path'
6
  import { readdirSync, statSync, unlinkSync } from 'fs'
 
7
 
8
  const BACKUP_DIR = join(dirname(config.dbPath), 'backups')
9
  const MAX_BACKUPS = 10
@@ -43,6 +44,9 @@ export async function POST(request: NextRequest) {
43
  const auth = requireRole(request, 'admin')
44
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
45
 
 
 
 
46
  ensureDirExists(BACKUP_DIR)
47
 
48
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_').slice(0, 19)
 
4
  import { config, ensureDirExists } from '@/lib/config'
5
  import { join, dirname } from 'path'
6
  import { readdirSync, statSync, unlinkSync } from 'fs'
7
+ import { heavyLimiter } from '@/lib/rate-limit'
8
 
9
  const BACKUP_DIR = join(dirname(config.dbPath), 'backups')
10
  const MAX_BACKUPS = 10
 
44
  const auth = requireRole(request, 'admin')
45
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
46
 
47
+ const rateCheck = heavyLimiter(request)
48
+ if (rateCheck) return rateCheck
49
+
50
  ensureDirExists(BACKUP_DIR)
51
 
52
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_').slice(0, 19)
src/app/api/cleanup/route.ts CHANGED
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
2
  import { requireRole } from '@/lib/auth'
3
  import { getDatabase, logAuditEvent } from '@/lib/db'
4
  import { config } from '@/lib/config'
 
5
 
6
  interface CleanupResult {
7
  table: string
@@ -69,6 +70,9 @@ export async function POST(request: NextRequest) {
69
  const auth = requireRole(request, 'admin')
70
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
71
 
 
 
 
72
  const body = await request.json().catch(() => ({}))
73
  const dryRun = body.dry_run === true
74
 
 
2
  import { requireRole } from '@/lib/auth'
3
  import { getDatabase, logAuditEvent } from '@/lib/db'
4
  import { config } from '@/lib/config'
5
+ import { heavyLimiter } from '@/lib/rate-limit'
6
 
7
  interface CleanupResult {
8
  table: string
 
70
  const auth = requireRole(request, 'admin')
71
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
72
 
73
+ const rateCheck = heavyLimiter(request)
74
+ if (rateCheck) return rateCheck
75
+
76
  const body = await request.json().catch(() => ({}))
77
  const dryRun = body.dry_run === true
78
 
src/app/api/gateway-config/route.ts CHANGED
@@ -3,6 +3,8 @@ import { requireRole } from '@/lib/auth'
3
  import { logAuditEvent } from '@/lib/db'
4
  import { config } from '@/lib/config'
5
  import { join } from 'path'
 
 
6
 
7
  function getConfigPath(): string | null {
8
  if (!config.openclawHome) return null
@@ -53,15 +55,17 @@ export async function PUT(request: NextRequest) {
53
  const auth = requireRole(request, 'admin')
54
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
55
 
 
 
 
56
  const configPath = getConfigPath()
57
  if (!configPath) {
58
  return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 })
59
  }
60
 
61
- const body = await request.json().catch(() => null)
62
- if (!body?.updates || typeof body.updates !== 'object') {
63
- return NextResponse.json({ error: 'updates object required (dot-notation paths)' }, { status: 400 })
64
- }
65
 
66
  // Block writes to sensitive paths
67
  const blockedPaths = ['gateway.auth.password', 'gateway.auth.secret']
 
3
  import { logAuditEvent } from '@/lib/db'
4
  import { config } from '@/lib/config'
5
  import { join } from 'path'
6
+ import { validateBody, gatewayConfigUpdateSchema } from '@/lib/validation'
7
+ import { mutationLimiter } from '@/lib/rate-limit'
8
 
9
  function getConfigPath(): string | null {
10
  if (!config.openclawHome) return null
 
55
  const auth = requireRole(request, 'admin')
56
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
57
 
58
+ const rateCheck = mutationLimiter(request)
59
+ if (rateCheck) return rateCheck
60
+
61
  const configPath = getConfigPath()
62
  if (!configPath) {
63
  return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 })
64
  }
65
 
66
+ const result = await validateBody(request, gatewayConfigUpdateSchema)
67
+ if ('error' in result) return result.error
68
+ const body = result.data
 
69
 
70
  // Block writes to sensitive paths
71
  const blockedPaths = ['gateway.auth.password', 'gateway.auth.secret']
src/app/api/integrations/route.ts CHANGED
@@ -5,6 +5,8 @@ import { config } from '@/lib/config'
5
  import { join } from 'path'
6
  import { readFile, writeFile, rename } from 'fs/promises'
7
  import { execFileSync } from 'child_process'
 
 
8
 
9
  // ---------------------------------------------------------------------------
10
  // Integration registry
@@ -359,14 +361,16 @@ export async function POST(request: NextRequest) {
359
  const auth = requireRole(request, 'admin')
360
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
361
 
362
- const body = await request.json().catch(() => null)
363
- if (!body?.action) {
364
- return NextResponse.json({ error: 'action required' }, { status: 400 })
365
- }
 
 
366
 
367
  // pull-all is a batch action — no integrationId needed
368
  if (body.action === 'pull-all') {
369
- return handlePullAll(request, auth.user, body.category as string | undefined)
370
  }
371
 
372
  if (!body.integrationId) {
 
5
  import { join } from 'path'
6
  import { readFile, writeFile, rename } from 'fs/promises'
7
  import { execFileSync } from 'child_process'
8
+ import { validateBody, integrationActionSchema } from '@/lib/validation'
9
+ import { mutationLimiter } from '@/lib/rate-limit'
10
 
11
  // ---------------------------------------------------------------------------
12
  // Integration registry
 
361
  const auth = requireRole(request, 'admin')
362
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
363
 
364
+ const rateCheck = mutationLimiter(request)
365
+ if (rateCheck) return rateCheck
366
+
367
+ const result = await validateBody(request, integrationActionSchema)
368
+ if ('error' in result) return result.error
369
+ const body = result.data
370
 
371
  // pull-all is a batch action — no integrationId needed
372
  if (body.action === 'pull-all') {
373
+ return handlePullAll(request, auth.user, body.category)
374
  }
375
 
376
  if (!body.integrationId) {
src/app/api/logs/route.ts CHANGED
@@ -3,6 +3,7 @@ import { readFile, readdir, stat } from 'fs/promises'
3
  import { join } from 'path'
4
  import { config } from '@/lib/config'
5
  import { requireRole } from '@/lib/auth'
 
6
 
7
  const LOGS_PATH = config.logsDir
8
 
@@ -178,6 +179,9 @@ export async function GET(request: NextRequest) {
178
  const auth = requireRole(request, 'viewer')
179
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
180
 
 
 
 
181
  try {
182
  const { searchParams } = new URL(request.url)
183
  const action = searchParams.get('action') || 'recent'
@@ -253,6 +257,9 @@ export async function POST(request: NextRequest) {
253
  const auth = requireRole(request, 'operator')
254
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
255
 
 
 
 
256
  try {
257
  const { action, message, level, source: customSource, session } = await request.json()
258
 
 
3
  import { join } from 'path'
4
  import { config } from '@/lib/config'
5
  import { requireRole } from '@/lib/auth'
6
+ import { readLimiter, mutationLimiter } from '@/lib/rate-limit'
7
 
8
  const LOGS_PATH = config.logsDir
9
 
 
179
  const auth = requireRole(request, 'viewer')
180
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
181
 
182
+ const rateCheck = readLimiter(request)
183
+ if (rateCheck) return rateCheck
184
+
185
  try {
186
  const { searchParams } = new URL(request.url)
187
  const action = searchParams.get('action') || 'recent'
 
257
  const auth = requireRole(request, 'operator')
258
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
259
 
260
+ const rateCheck = mutationLimiter(request)
261
+ if (rateCheck) return rateCheck
262
+
263
  try {
264
  const { action, message, level, source: customSource, session } = await request.json()
265
 
src/app/api/memory/route.ts CHANGED
@@ -4,6 +4,7 @@ import { join, dirname, sep } from 'path'
4
  import { config } from '@/lib/config'
5
  import { resolveWithin } from '@/lib/paths'
6
  import { requireRole } from '@/lib/auth'
 
7
 
8
  const MEMORY_PATH = config.memoryDir
9
 
@@ -116,6 +117,9 @@ export async function GET(request: NextRequest) {
116
  const auth = requireRole(request, 'viewer')
117
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
118
 
 
 
 
119
  try {
120
  const { searchParams } = new URL(request.url)
121
  const path = searchParams.get('path')
@@ -235,6 +239,9 @@ export async function POST(request: NextRequest) {
235
  const auth = requireRole(request, 'operator')
236
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
237
 
 
 
 
238
  try {
239
  const body = await request.json()
240
  const { action, path, content } = body
@@ -292,6 +299,9 @@ export async function DELETE(request: NextRequest) {
292
  const auth = requireRole(request, 'admin')
293
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
294
 
 
 
 
295
  try {
296
  const body = await request.json()
297
  const { action, path } = body
 
4
  import { config } from '@/lib/config'
5
  import { resolveWithin } from '@/lib/paths'
6
  import { requireRole } from '@/lib/auth'
7
+ import { readLimiter, mutationLimiter } from '@/lib/rate-limit'
8
 
9
  const MEMORY_PATH = config.memoryDir
10
 
 
117
  const auth = requireRole(request, 'viewer')
118
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
119
 
120
+ const rateCheck = readLimiter(request)
121
+ if (rateCheck) return rateCheck
122
+
123
  try {
124
  const { searchParams } = new URL(request.url)
125
  const path = searchParams.get('path')
 
239
  const auth = requireRole(request, 'operator')
240
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
241
 
242
+ const rateCheck = mutationLimiter(request)
243
+ if (rateCheck) return rateCheck
244
+
245
  try {
246
  const body = await request.json()
247
  const { action, path, content } = body
 
299
  const auth = requireRole(request, 'admin')
300
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
301
 
302
+ const rateCheck = mutationLimiter(request)
303
+ if (rateCheck) return rateCheck
304
+
305
  try {
306
  const body = await request.json()
307
  const { action, path } = body
src/app/api/notifications/route.ts CHANGED
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
2
  import { getDatabase, Notification } from '@/lib/db';
3
  import { requireRole } from '@/lib/auth';
4
  import { mutationLimiter } from '@/lib/rate-limit';
 
5
 
6
  /**
7
  * GET /api/notifications - Get notifications for a specific recipient
@@ -256,13 +257,12 @@ export async function POST(request: NextRequest) {
256
 
257
  try {
258
  const db = getDatabase();
259
- const body = await request.json();
260
- const { agent, action } = body;
261
-
 
 
262
  if (action === 'mark-delivered') {
263
- if (!agent) {
264
- return NextResponse.json({ error: 'Agent name is required' }, { status: 400 });
265
- }
266
 
267
  const now = Math.floor(Date.now() / 1000);
268
 
 
2
  import { getDatabase, Notification } from '@/lib/db';
3
  import { requireRole } from '@/lib/auth';
4
  import { mutationLimiter } from '@/lib/rate-limit';
5
+ import { validateBody, notificationActionSchema } from '@/lib/validation';
6
 
7
  /**
8
  * GET /api/notifications - Get notifications for a specific recipient
 
257
 
258
  try {
259
  const db = getDatabase();
260
+
261
+ const result = await validateBody(request, notificationActionSchema);
262
+ if ('error' in result) return result.error;
263
+ const { agent, action } = result.data;
264
+
265
  if (action === 'mark-delivered') {
 
 
 
266
 
267
  const now = Math.floor(Date.now() / 1000);
268
 
src/app/api/pipelines/route.ts CHANGED
@@ -1,6 +1,8 @@
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { getDatabase, db_helpers } from '@/lib/db'
3
  import { requireRole } from '@/lib/auth'
 
 
4
 
5
  export interface PipelineStep {
6
  template_id: number
@@ -70,17 +72,15 @@ export async function POST(request: NextRequest) {
70
  const auth = requireRole(request, 'operator')
71
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
72
 
 
 
 
73
  try {
74
- const db = getDatabase()
75
- const body = await request.json()
76
- const { name, description, steps = [] } = body
77
 
78
- if (!name) {
79
- return NextResponse.json({ error: 'Name is required' }, { status: 400 })
80
- }
81
- if (!Array.isArray(steps) || steps.length < 2) {
82
- return NextResponse.json({ error: 'Pipeline needs at least 2 steps' }, { status: 400 })
83
- }
84
 
85
  // Validate template IDs exist
86
  const templateIds = steps.map((s: PipelineStep) => s.template_id)
@@ -96,14 +96,14 @@ export async function POST(request: NextRequest) {
96
  on_failure: s.on_failure || 'stop',
97
  }))
98
 
99
- const result = db.prepare(`
100
  INSERT INTO workflow_pipelines (name, description, steps, created_by)
101
  VALUES (?, ?, ?, ?)
102
  `).run(name, description || null, JSON.stringify(cleanSteps), auth.user?.username || 'system')
103
 
104
- db_helpers.logActivity('pipeline_created', 'pipeline', Number(result.lastInsertRowid), auth.user?.username || 'system', `Created pipeline: ${name}`)
105
 
106
- const pipeline = db.prepare('SELECT * FROM workflow_pipelines WHERE id = ?').get(result.lastInsertRowid) as Pipeline
107
  return NextResponse.json({ pipeline: { ...pipeline, steps: JSON.parse(pipeline.steps) } }, { status: 201 })
108
  } catch (error) {
109
  console.error('POST /api/pipelines error:', error)
 
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { getDatabase, db_helpers } from '@/lib/db'
3
  import { requireRole } from '@/lib/auth'
4
+ import { validateBody, createPipelineSchema } from '@/lib/validation'
5
+ import { mutationLimiter } from '@/lib/rate-limit'
6
 
7
  export interface PipelineStep {
8
  template_id: number
 
72
  const auth = requireRole(request, 'operator')
73
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
74
 
75
+ const rateCheck = mutationLimiter(request)
76
+ if (rateCheck) return rateCheck
77
+
78
  try {
79
+ const result = await validateBody(request, createPipelineSchema)
80
+ if ('error' in result) return result.error
81
+ const { name, description, steps } = result.data
82
 
83
+ const db = getDatabase()
 
 
 
 
 
84
 
85
  // Validate template IDs exist
86
  const templateIds = steps.map((s: PipelineStep) => s.template_id)
 
96
  on_failure: s.on_failure || 'stop',
97
  }))
98
 
99
+ const insertResult = db.prepare(`
100
  INSERT INTO workflow_pipelines (name, description, steps, created_by)
101
  VALUES (?, ?, ?, ?)
102
  `).run(name, description || null, JSON.stringify(cleanSteps), auth.user?.username || 'system')
103
 
104
+ db_helpers.logActivity('pipeline_created', 'pipeline', Number(insertResult.lastInsertRowid), auth.user?.username || 'system', `Created pipeline: ${name}`)
105
 
106
+ const pipeline = db.prepare('SELECT * FROM workflow_pipelines WHERE id = ?').get(insertResult.lastInsertRowid) as Pipeline
107
  return NextResponse.json({ pipeline: { ...pipeline, steps: JSON.parse(pipeline.steps) } }, { status: 201 })
108
  } catch (error) {
109
  console.error('POST /api/pipelines error:', error)
src/app/api/quality-review/route.ts CHANGED
@@ -1,6 +1,8 @@
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { getDatabase, db_helpers } from '@/lib/db'
3
  import { requireRole } from '@/lib/auth'
 
 
4
 
5
  export async function GET(request: NextRequest) {
6
  const auth = requireRole(request, 'viewer')
@@ -66,24 +68,15 @@ export async function POST(request: NextRequest) {
66
  const auth = requireRole(request, 'operator')
67
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
68
 
 
 
 
69
  try {
70
- const db = getDatabase()
71
- const body = await request.json()
72
- const taskId = parseInt(body.taskId)
73
- const reviewer = (body.reviewer || 'aegis').trim()
74
- const status = (body.status || '').trim()
75
- const notes = body.notes ? String(body.notes) : null
76
-
77
- if (isNaN(taskId) || !reviewer || !status) {
78
- return NextResponse.json({ error: 'taskId, reviewer, and status are required' }, { status: 400 })
79
- }
80
 
81
- if (!['approved', 'rejected'].includes(status)) {
82
- return NextResponse.json({ error: 'status must be approved or rejected' }, { status: 400 })
83
- }
84
- if (!notes || !String(notes).trim()) {
85
- return NextResponse.json({ error: 'notes are required for quality reviews' }, { status: 400 })
86
- }
87
 
88
  const task = db.prepare('SELECT id, title FROM tasks WHERE id = ?').get(taskId) as any
89
  if (!task) {
 
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { getDatabase, db_helpers } from '@/lib/db'
3
  import { requireRole } from '@/lib/auth'
4
+ import { validateBody, qualityReviewSchema } from '@/lib/validation'
5
+ import { mutationLimiter } from '@/lib/rate-limit'
6
 
7
  export async function GET(request: NextRequest) {
8
  const auth = requireRole(request, 'viewer')
 
68
  const auth = requireRole(request, 'operator')
69
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
70
 
71
+ const rateCheck = mutationLimiter(request)
72
+ if (rateCheck) return rateCheck
73
+
74
  try {
75
+ const validated = await validateBody(request, qualityReviewSchema)
76
+ if ('error' in validated) return validated.error
77
+ const { taskId, reviewer, status, notes } = validated.data
 
 
 
 
 
 
 
78
 
79
+ const db = getDatabase()
 
 
 
 
 
80
 
81
  const task = db.prepare('SELECT id, title FROM tasks WHERE id = ?').get(taskId) as any
82
  if (!task) {
src/app/api/search/route.ts CHANGED
@@ -1,6 +1,7 @@
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { requireRole } from '@/lib/auth'
3
  import { getDatabase } from '@/lib/db'
 
4
 
5
  interface SearchResult {
6
  type: 'task' | 'agent' | 'activity' | 'audit' | 'message' | 'notification' | 'webhook' | 'pipeline'
@@ -20,6 +21,9 @@ export async function GET(request: NextRequest) {
20
  const auth = requireRole(request, 'viewer')
21
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
22
 
 
 
 
23
  const { searchParams } = new URL(request.url)
24
  const query = searchParams.get('q')?.trim()
25
  const typeFilter = searchParams.get('type')
 
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { requireRole } from '@/lib/auth'
3
  import { getDatabase } from '@/lib/db'
4
+ import { heavyLimiter } from '@/lib/rate-limit'
5
 
6
  interface SearchResult {
7
  type: 'task' | 'agent' | 'activity' | 'audit' | 'message' | 'notification' | 'webhook' | 'pipeline'
 
21
  const auth = requireRole(request, 'viewer')
22
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
23
 
24
+ const rateCheck = heavyLimiter(request)
25
+ if (rateCheck) return rateCheck
26
+
27
  const { searchParams } = new URL(request.url)
28
  const query = searchParams.get('q')?.trim()
29
  const typeFilter = searchParams.get('type')
src/app/api/settings/route.ts CHANGED
@@ -3,6 +3,7 @@ import { requireRole } from '@/lib/auth'
3
  import { getDatabase, logAuditEvent } from '@/lib/db'
4
  import { config } from '@/lib/config'
5
  import { mutationLimiter } from '@/lib/rate-limit'
 
6
 
7
  interface SettingRow {
8
  key: string
@@ -105,10 +106,9 @@ export async function PUT(request: NextRequest) {
105
  const rateCheck = mutationLimiter(request)
106
  if (rateCheck) return rateCheck
107
 
108
- const body = await request.json().catch(() => null)
109
- if (!body?.settings || typeof body.settings !== 'object') {
110
- return NextResponse.json({ error: 'settings object required' }, { status: 400 })
111
- }
112
 
113
  const db = getDatabase()
114
  const upsert = db.prepare(`
 
3
  import { getDatabase, logAuditEvent } from '@/lib/db'
4
  import { config } from '@/lib/config'
5
  import { mutationLimiter } from '@/lib/rate-limit'
6
+ import { validateBody, updateSettingsSchema } from '@/lib/validation'
7
 
8
  interface SettingRow {
9
  key: string
 
106
  const rateCheck = mutationLimiter(request)
107
  if (rateCheck) return rateCheck
108
 
109
+ const result = await validateBody(request, updateSettingsSchema)
110
+ if ('error' in result) return result.error
111
+ const body = result.data
 
112
 
113
  const db = getDatabase()
114
  const upsert = db.prepare(`
src/app/api/spawn/route.ts CHANGED
@@ -6,6 +6,7 @@ import { readdir, readFile, stat } from 'fs/promises'
6
  import { join } from 'path'
7
  import { heavyLimiter } from '@/lib/rate-limit'
8
  import { logger } from '@/lib/logger'
 
9
 
10
  export async function POST(request: NextRequest) {
11
  const auth = requireRole(request, 'operator')
@@ -15,24 +16,11 @@ export async function POST(request: NextRequest) {
15
  if (rateCheck) return rateCheck
16
 
17
  try {
18
- const { task, model, label, timeoutSeconds } = await request.json()
 
 
19
 
20
- // Validate required fields
21
- if (!task || !model || !label) {
22
- return NextResponse.json(
23
- { error: 'Missing required fields: task, model, label' },
24
- { status: 400 }
25
- )
26
- }
27
-
28
- // Validate timeout
29
- const timeout = parseInt(timeoutSeconds) || 300
30
- if (timeout < 10 || timeout > 3600) {
31
- return NextResponse.json(
32
- { error: 'Timeout must be between 10 and 3600 seconds' },
33
- { status: 400 }
34
- )
35
- }
36
 
37
  // Generate spawn ID
38
  const spawnId = `spawn-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
 
6
  import { join } from 'path'
7
  import { heavyLimiter } from '@/lib/rate-limit'
8
  import { logger } from '@/lib/logger'
9
+ import { validateBody, spawnAgentSchema } from '@/lib/validation'
10
 
11
  export async function POST(request: NextRequest) {
12
  const auth = requireRole(request, 'operator')
 
16
  if (rateCheck) return rateCheck
17
 
18
  try {
19
+ const result = await validateBody(request, spawnAgentSchema)
20
+ if ('error' in result) return result.error
21
+ const { task, model, label, timeoutSeconds } = result.data
22
 
23
+ const timeout = timeoutSeconds
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  // Generate spawn ID
26
  const spawnId = `spawn-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
src/app/api/tasks/[id]/comments/route.ts CHANGED
@@ -1,6 +1,8 @@
1
  import { NextRequest, NextResponse } from 'next/server';
2
  import { getDatabase, Comment, db_helpers } from '@/lib/db';
3
  import { requireRole } from '@/lib/auth';
 
 
4
 
5
  /**
6
  * GET /api/tasks/[id]/comments - Get all comments for a task
@@ -87,21 +89,21 @@ export async function POST(
87
  const auth = requireRole(request, 'operator');
88
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
89
 
 
 
 
90
  try {
91
  const db = getDatabase();
92
  const resolvedParams = await params;
93
  const taskId = parseInt(resolvedParams.id);
94
- const body = await request.json();
95
-
96
  if (isNaN(taskId)) {
97
  return NextResponse.json({ error: 'Invalid task ID' }, { status: 400 });
98
  }
99
-
100
- const { content, author = 'system', parent_id } = body;
101
-
102
- if (!content || !content.trim()) {
103
- return NextResponse.json({ error: 'Comment content is required' }, { status: 400 });
104
- }
105
 
106
  // Verify task exists
107
  const task = db.prepare('SELECT * FROM tasks WHERE id = ?').get(taskId) as any;
@@ -128,7 +130,7 @@ export async function POST(
128
  VALUES (?, ?, ?, ?, ?, ?)
129
  `);
130
 
131
- const result = stmt.run(
132
  taskId,
133
  author,
134
  content,
@@ -136,8 +138,8 @@ export async function POST(
136
  parent_id || null,
137
  mentions.length > 0 ? JSON.stringify(mentions) : null
138
  );
139
-
140
- const commentId = result.lastInsertRowid as number;
141
 
142
  // Log activity
143
  const activityDescription = parent_id
 
1
  import { NextRequest, NextResponse } from 'next/server';
2
  import { getDatabase, Comment, db_helpers } from '@/lib/db';
3
  import { requireRole } from '@/lib/auth';
4
+ import { validateBody, createCommentSchema } from '@/lib/validation';
5
+ import { mutationLimiter } from '@/lib/rate-limit';
6
 
7
  /**
8
  * GET /api/tasks/[id]/comments - Get all comments for a task
 
89
  const auth = requireRole(request, 'operator');
90
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
91
 
92
+ const rateCheck = mutationLimiter(request);
93
+ if (rateCheck) return rateCheck;
94
+
95
  try {
96
  const db = getDatabase();
97
  const resolvedParams = await params;
98
  const taskId = parseInt(resolvedParams.id);
99
+
 
100
  if (isNaN(taskId)) {
101
  return NextResponse.json({ error: 'Invalid task ID' }, { status: 400 });
102
  }
103
+
104
+ const result = await validateBody(request, createCommentSchema);
105
+ if ('error' in result) return result.error;
106
+ const { content, author = 'system', parent_id } = result.data;
 
 
107
 
108
  // Verify task exists
109
  const task = db.prepare('SELECT * FROM tasks WHERE id = ?').get(taskId) as any;
 
130
  VALUES (?, ?, ?, ?, ?, ?)
131
  `);
132
 
133
+ const insertResult = stmt.run(
134
  taskId,
135
  author,
136
  content,
 
138
  parent_id || null,
139
  mentions.length > 0 ? JSON.stringify(mentions) : null
140
  );
141
+
142
+ const commentId = insertResult.lastInsertRowid as number;
143
 
144
  // Log activity
145
  const activityDescription = parent_id
src/app/api/workflows/route.ts CHANGED
@@ -1,6 +1,8 @@
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { getDatabase, db_helpers } from '@/lib/db'
3
  import { requireRole } from '@/lib/auth'
 
 
4
 
5
  export interface WorkflowTemplate {
6
  id: number
@@ -48,25 +50,25 @@ export async function POST(request: NextRequest) {
48
  const auth = requireRole(request, 'operator')
49
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
50
 
 
 
 
51
  try {
 
 
 
 
52
  const db = getDatabase()
53
  const user = auth.user
54
- const body = await request.json()
55
-
56
- const { name, description, model = 'sonnet', task_prompt, timeout_seconds = 300, agent_role, tags = [] } = body
57
-
58
- if (!name || !task_prompt) {
59
- return NextResponse.json({ error: 'Name and task_prompt are required' }, { status: 400 })
60
- }
61
 
62
- const result = db.prepare(`
63
  INSERT INTO workflow_templates (name, description, model, task_prompt, timeout_seconds, agent_role, tags, created_by)
64
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
65
  `).run(name, description || null, model, task_prompt, timeout_seconds, agent_role || null, JSON.stringify(tags), user?.username || 'system')
66
 
67
- const template = db.prepare('SELECT * FROM workflow_templates WHERE id = ?').get(result.lastInsertRowid) as WorkflowTemplate
68
 
69
- db_helpers.logActivity('workflow_created', 'workflow', Number(result.lastInsertRowid), user?.username || 'system', `Created workflow template: ${name}`)
70
 
71
  return NextResponse.json({
72
  template: { ...template, tags: template.tags ? JSON.parse(template.tags) : [] }
 
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import { getDatabase, db_helpers } from '@/lib/db'
3
  import { requireRole } from '@/lib/auth'
4
+ import { validateBody, createWorkflowSchema } from '@/lib/validation'
5
+ import { mutationLimiter } from '@/lib/rate-limit'
6
 
7
  export interface WorkflowTemplate {
8
  id: number
 
50
  const auth = requireRole(request, 'operator')
51
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
52
 
53
+ const rateCheck = mutationLimiter(request)
54
+ if (rateCheck) return rateCheck
55
+
56
  try {
57
+ const result = await validateBody(request, createWorkflowSchema)
58
+ if ('error' in result) return result.error
59
+ const { name, description, model, task_prompt, timeout_seconds, agent_role, tags } = result.data
60
+
61
  const db = getDatabase()
62
  const user = auth.user
 
 
 
 
 
 
 
63
 
64
+ const insertResult = db.prepare(`
65
  INSERT INTO workflow_templates (name, description, model, task_prompt, timeout_seconds, agent_role, tags, created_by)
66
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
67
  `).run(name, description || null, model, task_prompt, timeout_seconds, agent_role || null, JSON.stringify(tags), user?.username || 'system')
68
 
69
+ const template = db.prepare('SELECT * FROM workflow_templates WHERE id = ?').get(insertResult.lastInsertRowid) as WorkflowTemplate
70
 
71
+ db_helpers.logActivity('workflow_created', 'workflow', Number(insertResult.lastInsertRowid), user?.username || 'system', `Created workflow template: ${name}`)
72
 
73
  return NextResponse.json({
74
  template: { ...template, tags: template.tags ? JSON.parse(template.tags) : [] }
src/lib/__tests__/auth.test.ts CHANGED
@@ -1,17 +1,108 @@
1
- import { describe, it, expect, vi } from 'vitest'
 
2
 
3
- // Test stubs for auth utilities
4
- // safeCompare will be added by fix/p0-security-critical branch
 
 
5
 
6
- describe('requireRole', () => {
7
- it.todo('returns user when authenticated with sufficient role')
8
- it.todo('returns 401 when no authentication provided')
9
- it.todo('returns 403 when role is insufficient')
10
- })
 
 
 
 
11
 
12
  describe('safeCompare', () => {
13
- it.todo('returns true for matching strings')
14
- it.todo('returns false for non-matching strings')
15
- it.todo('returns false for different length strings')
16
- it.todo('handles empty strings')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  })
 
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
2
+ import { safeCompare, requireRole } from '@/lib/auth'
3
 
4
+ // Mock dependencies that auth.ts imports
5
+ vi.mock('@/lib/db', () => ({
6
+ getDatabase: vi.fn(),
7
+ }))
8
 
9
+ vi.mock('@/lib/password', () => ({
10
+ hashPassword: vi.fn((p: string) => `hashed:${p}`),
11
+ verifyPassword: vi.fn(() => false),
12
+ }))
13
+
14
+ // Prevent event-bus singleton side-effects
15
+ vi.mock('@/lib/event-bus', () => ({
16
+ eventBus: { broadcast: vi.fn(), on: vi.fn(), emit: vi.fn() },
17
+ }))
18
 
19
  describe('safeCompare', () => {
20
+ it('returns true for matching strings', () => {
21
+ expect(safeCompare('abc123', 'abc123')).toBe(true)
22
+ })
23
+
24
+ it('returns false for non-matching strings of same length', () => {
25
+ expect(safeCompare('abc123', 'xyz789')).toBe(false)
26
+ })
27
+
28
+ it('returns false for different length strings', () => {
29
+ expect(safeCompare('short', 'muchlonger')).toBe(false)
30
+ })
31
+
32
+ it('returns true for two empty strings', () => {
33
+ expect(safeCompare('', '')).toBe(true)
34
+ })
35
+
36
+ it('returns false when one string is empty', () => {
37
+ expect(safeCompare('', 'notempty')).toBe(false)
38
+ expect(safeCompare('notempty', '')).toBe(false)
39
+ })
40
+
41
+ it('returns false for non-string inputs', () => {
42
+ expect(safeCompare(null as any, 'a')).toBe(false)
43
+ expect(safeCompare('a', undefined as any)).toBe(false)
44
+ })
45
+ })
46
+
47
+ describe('requireRole', () => {
48
+ const originalEnv = process.env
49
+
50
+ beforeEach(() => {
51
+ process.env = { ...originalEnv, API_KEY: 'test-api-key-secret' }
52
+ })
53
+
54
+ afterEach(() => {
55
+ process.env = originalEnv
56
+ })
57
+
58
+ function makeRequest(headers: Record<string, string> = {}): Request {
59
+ return new Request('http://localhost/api/test', {
60
+ headers: new Headers(headers),
61
+ })
62
+ }
63
+
64
+ it('returns 401 when no authentication is provided', () => {
65
+ const result = requireRole(makeRequest(), 'viewer')
66
+ expect(result.status).toBe(401)
67
+ expect(result.error).toBe('Authentication required')
68
+ expect(result.user).toBeUndefined()
69
+ })
70
+
71
+ it('returns 401 when API key is wrong', () => {
72
+ const result = requireRole(
73
+ makeRequest({ 'x-api-key': 'wrong-key' }),
74
+ 'viewer',
75
+ )
76
+ expect(result.status).toBe(401)
77
+ expect(result.error).toBe('Authentication required')
78
+ })
79
+
80
+ it('returns user when API key is valid and role is sufficient', () => {
81
+ const result = requireRole(
82
+ makeRequest({ 'x-api-key': 'test-api-key-secret' }),
83
+ 'admin',
84
+ )
85
+ expect(result.status).toBeUndefined()
86
+ expect(result.error).toBeUndefined()
87
+ expect(result.user).toBeDefined()
88
+ expect(result.user!.username).toBe('api')
89
+ expect(result.user!.role).toBe('admin')
90
+ })
91
+
92
+ it('returns user for lower role requirement with API key (admin >= viewer)', () => {
93
+ const result = requireRole(
94
+ makeRequest({ 'x-api-key': 'test-api-key-secret' }),
95
+ 'viewer',
96
+ )
97
+ expect(result.user).toBeDefined()
98
+ expect(result.user!.role).toBe('admin')
99
+ })
100
+
101
+ it('returns user for operator role requirement with API key (admin >= operator)', () => {
102
+ const result = requireRole(
103
+ makeRequest({ 'x-api-key': 'test-api-key-secret' }),
104
+ 'operator',
105
+ )
106
+ expect(result.user).toBeDefined()
107
+ })
108
  })
src/lib/__tests__/db-helpers.test.ts ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest'
2
+
3
+ // Use vi.hoisted() so mock variables are available inside vi.mock() factories
4
+ const { mockBroadcast, mockRun, mockGet, mockPrepare } = vi.hoisted(() => {
5
+ const mockRun = vi.fn(() => ({ lastInsertRowid: 1, changes: 1 }))
6
+ const mockGet = vi.fn((): any => ({ count: 1 }))
7
+ const mockPrepare = vi.fn(() => ({
8
+ run: mockRun,
9
+ get: mockGet,
10
+ all: vi.fn(() => []),
11
+ }))
12
+ const mockBroadcast = vi.fn()
13
+ return { mockBroadcast, mockRun, mockGet, mockPrepare }
14
+ })
15
+
16
+ // Mock better-sqlite3 native module to avoid needing compiled bindings
17
+ vi.mock('better-sqlite3', () => {
18
+ return {
19
+ default: vi.fn(() => ({
20
+ prepare: mockPrepare,
21
+ pragma: vi.fn(),
22
+ exec: vi.fn(),
23
+ close: vi.fn(),
24
+ })),
25
+ }
26
+ })
27
+
28
+ vi.mock('@/lib/config', () => ({
29
+ config: { dbPath: ':memory:' },
30
+ ensureDirExists: vi.fn(),
31
+ }))
32
+
33
+ vi.mock('@/lib/migrations', () => ({
34
+ runMigrations: vi.fn(),
35
+ }))
36
+
37
+ vi.mock('@/lib/password', () => ({
38
+ hashPassword: vi.fn((p: string) => `hashed:${p}`),
39
+ verifyPassword: vi.fn(() => false),
40
+ }))
41
+
42
+ vi.mock('@/lib/logger', () => ({
43
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() },
44
+ }))
45
+
46
+ vi.mock('@/lib/event-bus', () => ({
47
+ eventBus: { broadcast: mockBroadcast, on: vi.fn(), emit: vi.fn(), setMaxListeners: vi.fn() },
48
+ }))
49
+
50
+ // Import after mocks — the real db_helpers will use our mocked getDatabase
51
+ import { db_helpers } from '@/lib/db'
52
+
53
+ describe('parseMentions', () => {
54
+ it('extracts multiple mentions', () => {
55
+ expect(db_helpers.parseMentions('@alice hello @bob')).toEqual(['alice', 'bob'])
56
+ })
57
+
58
+ it('returns empty array when no mentions', () => {
59
+ expect(db_helpers.parseMentions('no mentions here')).toEqual([])
60
+ })
61
+
62
+ it('extracts single mention', () => {
63
+ expect(db_helpers.parseMentions('hey @alice')).toEqual(['alice'])
64
+ })
65
+
66
+ it('handles @@double — captures word chars after @', () => {
67
+ const result = db_helpers.parseMentions('@@double')
68
+ expect(result).toContain('double')
69
+ })
70
+
71
+ it('handles mentions at start and end of string', () => {
72
+ expect(db_helpers.parseMentions('@start and @end')).toEqual(['start', 'end'])
73
+ })
74
+
75
+ it('returns empty array for empty string', () => {
76
+ expect(db_helpers.parseMentions('')).toEqual([])
77
+ })
78
+ })
79
+
80
+ describe('logActivity', () => {
81
+ beforeEach(() => {
82
+ vi.clearAllMocks()
83
+ })
84
+
85
+ it('inserts activity into database and broadcasts event', () => {
86
+ db_helpers.logActivity('task_created', 'task', 1, 'alice', 'Created task')
87
+
88
+ expect(mockPrepare).toHaveBeenCalled()
89
+ expect(mockRun).toHaveBeenCalledWith(
90
+ 'task_created', 'task', 1, 'alice', 'Created task', null,
91
+ )
92
+ expect(mockBroadcast).toHaveBeenCalledWith(
93
+ 'activity.created',
94
+ expect.objectContaining({
95
+ type: 'task_created',
96
+ entity_type: 'task',
97
+ entity_id: 1,
98
+ actor: 'alice',
99
+ }),
100
+ )
101
+ })
102
+
103
+ it('stringifies data when provided', () => {
104
+ const data = { key: 'value' }
105
+ db_helpers.logActivity('update', 'agent', 2, 'bob', 'Updated agent', data)
106
+
107
+ expect(mockRun).toHaveBeenCalledWith(
108
+ 'update', 'agent', 2, 'bob', 'Updated agent', JSON.stringify(data),
109
+ )
110
+ })
111
+ })
112
+
113
+ describe('createNotification', () => {
114
+ beforeEach(() => {
115
+ vi.clearAllMocks()
116
+ })
117
+
118
+ it('inserts notification and broadcasts event', () => {
119
+ db_helpers.createNotification('alice', 'mention', 'Mentioned', 'You were mentioned')
120
+
121
+ expect(mockRun).toHaveBeenCalledWith(
122
+ 'alice', 'mention', 'Mentioned', 'You were mentioned', undefined, undefined,
123
+ )
124
+ expect(mockBroadcast).toHaveBeenCalledWith(
125
+ 'notification.created',
126
+ expect.objectContaining({
127
+ recipient: 'alice',
128
+ type: 'mention',
129
+ title: 'Mentioned',
130
+ }),
131
+ )
132
+ })
133
+
134
+ it('passes source_type and source_id when provided', () => {
135
+ db_helpers.createNotification('bob', 'alert', 'Alert', 'CPU high', 'agent', 5)
136
+
137
+ expect(mockRun).toHaveBeenCalledWith(
138
+ 'bob', 'alert', 'Alert', 'CPU high', 'agent', 5,
139
+ )
140
+ })
141
+ })
142
+
143
+ describe('updateAgentStatus', () => {
144
+ beforeEach(() => {
145
+ vi.clearAllMocks()
146
+ mockGet.mockReturnValue({ id: 42 })
147
+ })
148
+
149
+ it('updates agent status in database and broadcasts', () => {
150
+ db_helpers.updateAgentStatus('worker-1', 'busy', 'Processing task')
151
+
152
+ expect(mockPrepare).toHaveBeenCalled()
153
+ expect(mockBroadcast).toHaveBeenCalledWith(
154
+ 'agent.status_changed',
155
+ expect.objectContaining({
156
+ id: 42,
157
+ name: 'worker-1',
158
+ status: 'busy',
159
+ }),
160
+ )
161
+ })
162
+ })
src/lib/__tests__/rate-limit.test.ts ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
2
+ import { createRateLimiter } from '@/lib/rate-limit'
3
+
4
+ describe('createRateLimiter', () => {
5
+ beforeEach(() => {
6
+ vi.useFakeTimers()
7
+ })
8
+
9
+ afterEach(() => {
10
+ vi.useRealTimers()
11
+ })
12
+
13
+ function makeRequest(ip: string = '127.0.0.1'): Request {
14
+ return new Request('http://localhost/api/test', {
15
+ headers: new Headers({ 'x-forwarded-for': ip }),
16
+ })
17
+ }
18
+
19
+ it('allows first request within limit (returns null)', () => {
20
+ const limiter = createRateLimiter({ windowMs: 60_000, maxRequests: 5 })
21
+ const result = limiter(makeRequest())
22
+ expect(result).toBeNull()
23
+ })
24
+
25
+ it('allows requests up to the max limit', () => {
26
+ const limiter = createRateLimiter({ windowMs: 60_000, maxRequests: 3 })
27
+ expect(limiter(makeRequest())).toBeNull()
28
+ expect(limiter(makeRequest())).toBeNull()
29
+ expect(limiter(makeRequest())).toBeNull()
30
+ })
31
+
32
+ it('blocks request exceeding the limit with 429', () => {
33
+ const limiter = createRateLimiter({ windowMs: 60_000, maxRequests: 2 })
34
+ limiter(makeRequest())
35
+ limiter(makeRequest())
36
+ const blocked = limiter(makeRequest())
37
+ expect(blocked).not.toBeNull()
38
+ expect(blocked!.status).toBe(429)
39
+ })
40
+
41
+ it('uses custom message in 429 response', async () => {
42
+ const limiter = createRateLimiter({
43
+ windowMs: 60_000,
44
+ maxRequests: 1,
45
+ message: 'Slow down!',
46
+ })
47
+ limiter(makeRequest())
48
+ const blocked = limiter(makeRequest())
49
+ expect(blocked).not.toBeNull()
50
+ const body = await blocked!.json()
51
+ expect(body.error).toBe('Slow down!')
52
+ })
53
+
54
+ it('resets after the window expires', () => {
55
+ const limiter = createRateLimiter({ windowMs: 10_000, maxRequests: 1 })
56
+ expect(limiter(makeRequest())).toBeNull()
57
+ expect(limiter(makeRequest())).not.toBeNull()
58
+
59
+ // Advance past the window
60
+ vi.advanceTimersByTime(11_000)
61
+
62
+ // Should be allowed again
63
+ expect(limiter(makeRequest())).toBeNull()
64
+ })
65
+
66
+ it('tracks different IPs independently', () => {
67
+ const limiter = createRateLimiter({ windowMs: 60_000, maxRequests: 1 })
68
+ expect(limiter(makeRequest('10.0.0.1'))).toBeNull()
69
+ expect(limiter(makeRequest('10.0.0.2'))).toBeNull()
70
+ // First IP now blocked
71
+ expect(limiter(makeRequest('10.0.0.1'))).not.toBeNull()
72
+ // Second IP now blocked
73
+ expect(limiter(makeRequest('10.0.0.2'))).not.toBeNull()
74
+ })
75
+ })
src/lib/__tests__/validation.test.ts ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, it, expect } from 'vitest'
2
+ import {
3
+ createTaskSchema,
4
+ createAgentSchema,
5
+ createWebhookSchema,
6
+ createAlertSchema,
7
+ spawnAgentSchema,
8
+ createUserSchema,
9
+ qualityReviewSchema,
10
+ createPipelineSchema,
11
+ createWorkflowSchema,
12
+ createMessageSchema,
13
+ } from '@/lib/validation'
14
+
15
+ describe('createTaskSchema', () => {
16
+ it('accepts valid input with defaults', () => {
17
+ const result = createTaskSchema.safeParse({ title: 'Fix bug' })
18
+ expect(result.success).toBe(true)
19
+ if (result.success) {
20
+ expect(result.data.title).toBe('Fix bug')
21
+ expect(result.data.status).toBe('inbox')
22
+ expect(result.data.priority).toBe('medium')
23
+ expect(result.data.tags).toEqual([])
24
+ expect(result.data.metadata).toEqual({})
25
+ }
26
+ })
27
+
28
+ it('rejects missing title', () => {
29
+ const result = createTaskSchema.safeParse({})
30
+ expect(result.success).toBe(false)
31
+ })
32
+
33
+ it('rejects invalid status', () => {
34
+ const result = createTaskSchema.safeParse({ title: 'X', status: 'invalid' })
35
+ expect(result.success).toBe(false)
36
+ })
37
+
38
+ it('accepts all valid statuses', () => {
39
+ for (const status of ['inbox', 'assigned', 'in_progress', 'review', 'quality_review', 'done']) {
40
+ const result = createTaskSchema.safeParse({ title: 'T', status })
41
+ expect(result.success).toBe(true)
42
+ }
43
+ })
44
+ })
45
+
46
+ describe('createAgentSchema', () => {
47
+ it('accepts valid input', () => {
48
+ const result = createAgentSchema.safeParse({ name: 'agent-1' })
49
+ expect(result.success).toBe(true)
50
+ })
51
+
52
+ it('rejects missing name', () => {
53
+ const result = createAgentSchema.safeParse({})
54
+ expect(result.success).toBe(false)
55
+ })
56
+ })
57
+
58
+ describe('createWebhookSchema', () => {
59
+ it('accepts valid input', () => {
60
+ const result = createWebhookSchema.safeParse({
61
+ name: 'My Hook',
62
+ url: 'https://example.com/hook',
63
+ })
64
+ expect(result.success).toBe(true)
65
+ })
66
+
67
+ it('rejects invalid URL', () => {
68
+ const result = createWebhookSchema.safeParse({
69
+ name: 'Hook',
70
+ url: 'not-a-url',
71
+ })
72
+ expect(result.success).toBe(false)
73
+ })
74
+ })
75
+
76
+ describe('createAlertSchema', () => {
77
+ const validAlert = {
78
+ name: 'CPU Alert',
79
+ entity_type: 'agent' as const,
80
+ condition_field: 'cpu',
81
+ condition_operator: 'greater_than' as const,
82
+ condition_value: '90',
83
+ }
84
+
85
+ it('accepts valid input', () => {
86
+ const result = createAlertSchema.safeParse(validAlert)
87
+ expect(result.success).toBe(true)
88
+ })
89
+
90
+ it('rejects missing name', () => {
91
+ const { name, ...rest } = validAlert
92
+ const result = createAlertSchema.safeParse(rest)
93
+ expect(result.success).toBe(false)
94
+ })
95
+
96
+ it('rejects missing entity_type', () => {
97
+ const { entity_type, ...rest } = validAlert
98
+ const result = createAlertSchema.safeParse(rest)
99
+ expect(result.success).toBe(false)
100
+ })
101
+ })
102
+
103
+ describe('spawnAgentSchema', () => {
104
+ const validSpawn = {
105
+ task: 'Do something',
106
+ model: 'sonnet',
107
+ label: 'worker-1',
108
+ }
109
+
110
+ it('accepts valid input with default timeout', () => {
111
+ const result = spawnAgentSchema.safeParse(validSpawn)
112
+ expect(result.success).toBe(true)
113
+ if (result.success) {
114
+ expect(result.data.timeoutSeconds).toBe(300)
115
+ }
116
+ })
117
+
118
+ it('rejects timeout below minimum (10)', () => {
119
+ const result = spawnAgentSchema.safeParse({ ...validSpawn, timeoutSeconds: 5 })
120
+ expect(result.success).toBe(false)
121
+ })
122
+
123
+ it('rejects timeout above maximum (3600)', () => {
124
+ const result = spawnAgentSchema.safeParse({ ...validSpawn, timeoutSeconds: 9999 })
125
+ expect(result.success).toBe(false)
126
+ })
127
+ })
128
+
129
+ describe('createUserSchema', () => {
130
+ it('accepts valid input', () => {
131
+ const result = createUserSchema.safeParse({
132
+ username: 'alice',
133
+ password: 'secret123',
134
+ })
135
+ expect(result.success).toBe(true)
136
+ if (result.success) {
137
+ expect(result.data.role).toBe('operator')
138
+ }
139
+ })
140
+
141
+ it('rejects missing username', () => {
142
+ const result = createUserSchema.safeParse({ password: 'x' })
143
+ expect(result.success).toBe(false)
144
+ })
145
+
146
+ it('rejects missing password', () => {
147
+ const result = createUserSchema.safeParse({ username: 'x' })
148
+ expect(result.success).toBe(false)
149
+ })
150
+ })
151
+
152
+ describe('qualityReviewSchema', () => {
153
+ it('accepts valid input', () => {
154
+ const result = qualityReviewSchema.safeParse({
155
+ taskId: 1,
156
+ status: 'approved',
157
+ notes: 'Looks good',
158
+ })
159
+ expect(result.success).toBe(true)
160
+ })
161
+
162
+ it('rejects invalid status', () => {
163
+ const result = qualityReviewSchema.safeParse({
164
+ taskId: 1,
165
+ status: 'pending',
166
+ notes: 'N/A',
167
+ })
168
+ expect(result.success).toBe(false)
169
+ })
170
+ })
171
+
172
+ describe('createPipelineSchema', () => {
173
+ it('accepts valid input with 2+ steps', () => {
174
+ const result = createPipelineSchema.safeParse({
175
+ name: 'Deploy',
176
+ steps: [
177
+ { template_id: 1 },
178
+ { template_id: 2 },
179
+ ],
180
+ })
181
+ expect(result.success).toBe(true)
182
+ })
183
+
184
+ it('rejects fewer than 2 steps', () => {
185
+ const result = createPipelineSchema.safeParse({
186
+ name: 'Deploy',
187
+ steps: [{ template_id: 1 }],
188
+ })
189
+ expect(result.success).toBe(false)
190
+ })
191
+ })
192
+
193
+ describe('createWorkflowSchema', () => {
194
+ it('accepts valid input', () => {
195
+ const result = createWorkflowSchema.safeParse({
196
+ name: 'Summarize',
197
+ task_prompt: 'Summarize the document',
198
+ })
199
+ expect(result.success).toBe(true)
200
+ if (result.success) {
201
+ expect(result.data.model).toBe('sonnet')
202
+ }
203
+ })
204
+
205
+ it('rejects missing name', () => {
206
+ const result = createWorkflowSchema.safeParse({ task_prompt: 'Do it' })
207
+ expect(result.success).toBe(false)
208
+ })
209
+
210
+ it('rejects missing task_prompt', () => {
211
+ const result = createWorkflowSchema.safeParse({ name: 'W' })
212
+ expect(result.success).toBe(false)
213
+ })
214
+ })
215
+
216
+ describe('createMessageSchema', () => {
217
+ it('accepts valid input', () => {
218
+ const result = createMessageSchema.safeParse({
219
+ to: 'bob',
220
+ message: 'Hello',
221
+ })
222
+ expect(result.success).toBe(true)
223
+ if (result.success) {
224
+ expect(result.data.from).toBe('system')
225
+ }
226
+ })
227
+
228
+ it('rejects missing to', () => {
229
+ const result = createMessageSchema.safeParse({ message: 'Hi' })
230
+ expect(result.success).toBe(false)
231
+ })
232
+
233
+ it('rejects missing message', () => {
234
+ const result = createMessageSchema.safeParse({ to: 'bob' })
235
+ expect(result.success).toBe(false)
236
+ })
237
+ })
src/lib/auth.ts CHANGED
@@ -40,6 +40,36 @@ export interface UserSession {
40
  user_agent: string | null
41
  }
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  // Session management
44
  const SESSION_DURATION = 7 * 24 * 60 * 60 // 7 days in seconds
45
 
@@ -74,7 +104,7 @@ export function validateSession(token: string): (User & { sessionId: number }) |
74
  FROM user_sessions s
75
  JOIN users u ON u.id = s.user_id
76
  WHERE s.token = ? AND s.expires_at > ?
77
- `).get(token, now) as any
78
 
79
  if (!row) return null
80
 
@@ -107,7 +137,7 @@ export function destroyAllUserSessions(userId: number): void {
107
  // User management
108
  export function authenticateUser(username: string, password: string): User | null {
109
  const db = getDatabase()
110
- const row = db.prepare('SELECT * FROM users WHERE username = ?').get(username) as any
111
  if (!row) return null
112
  if ((row.provider || 'local') !== 'local') return null
113
  if ((row.is_approved ?? 1) !== 1) return null
@@ -129,7 +159,7 @@ export function authenticateUser(username: string, password: string): User | nul
129
 
130
  export function getUserById(id: number): User | null {
131
  const db = getDatabase()
132
- const row = db.prepare('SELECT id, username, display_name, role, provider, email, avatar_url, is_approved, created_at, updated_at, last_login_at FROM users WHERE id = ?').get(id) as any
133
  return row || null
134
  }
135
 
 
40
  user_agent: string | null
41
  }
42
 
43
+ interface SessionQueryRow {
44
+ id: number
45
+ username: string
46
+ display_name: string
47
+ role: 'admin' | 'operator' | 'viewer'
48
+ provider: 'local' | 'google' | null
49
+ email: string | null
50
+ avatar_url: string | null
51
+ is_approved: number
52
+ created_at: number
53
+ updated_at: number
54
+ last_login_at: number | null
55
+ session_id: number
56
+ }
57
+
58
+ interface UserQueryRow {
59
+ id: number
60
+ username: string
61
+ display_name: string
62
+ role: 'admin' | 'operator' | 'viewer'
63
+ provider: 'local' | 'google' | null
64
+ email: string | null
65
+ avatar_url: string | null
66
+ is_approved: number
67
+ created_at: number
68
+ updated_at: number
69
+ last_login_at: number | null
70
+ password_hash: string
71
+ }
72
+
73
  // Session management
74
  const SESSION_DURATION = 7 * 24 * 60 * 60 // 7 days in seconds
75
 
 
104
  FROM user_sessions s
105
  JOIN users u ON u.id = s.user_id
106
  WHERE s.token = ? AND s.expires_at > ?
107
+ `).get(token, now) as SessionQueryRow | undefined
108
 
109
  if (!row) return null
110
 
 
137
  // User management
138
  export function authenticateUser(username: string, password: string): User | null {
139
  const db = getDatabase()
140
+ const row = db.prepare('SELECT * FROM users WHERE username = ?').get(username) as UserQueryRow | undefined
141
  if (!row) return null
142
  if ((row.provider || 'local') !== 'local') return null
143
  if ((row.is_approved ?? 1) !== 1) return null
 
159
 
160
  export function getUserById(id: number): User | null {
161
  const db = getDatabase()
162
+ const row = db.prepare('SELECT id, username, display_name, role, provider, email, avatar_url, is_approved, created_at, updated_at, last_login_at FROM users WHERE id = ?').get(id) as User | undefined
163
  return row || null
164
  }
165
 
src/lib/db.ts CHANGED
@@ -71,8 +71,10 @@ function initializeSchema() {
71
  }
72
  }
73
 
 
 
74
  function seedAdminUserFromEnv(dbConn: Database.Database): void {
75
- const count = (dbConn.prepare('SELECT COUNT(*) as count FROM users').get() as any).count as number
76
  if (count > 0) return
77
 
78
  const username = process.env.AUTH_USER || 'admin'
 
71
  }
72
  }
73
 
74
+ interface CountRow { count: number }
75
+
76
  function seedAdminUserFromEnv(dbConn: Database.Database): void {
77
+ const count = (dbConn.prepare('SELECT COUNT(*) as count FROM users').get() as CountRow).count
78
  if (count > 0) return
79
 
80
  const username = process.env.AUTH_USER || 'admin'
src/lib/rate-limit.ts CHANGED
@@ -57,6 +57,11 @@ export const mutationLimiter = createRateLimiter({
57
  maxRequests: 60,
58
  })
59
 
 
 
 
 
 
60
  export const heavyLimiter = createRateLimiter({
61
  windowMs: 60_000,
62
  maxRequests: 10,
 
57
  maxRequests: 60,
58
  })
59
 
60
+ export const readLimiter = createRateLimiter({
61
+ windowMs: 60_000,
62
+ maxRequests: 120,
63
+ })
64
+
65
  export const heavyLimiter = createRateLimiter({
66
  windowMs: 60_000,
67
  maxRequests: 10,
src/lib/validation.ts CHANGED
@@ -29,7 +29,7 @@ export async function validateBody<T>(
29
  export const createTaskSchema = z.object({
30
  title: z.string().min(1, 'Title is required').max(500),
31
  description: z.string().max(5000).optional(),
32
- status: z.enum(['inbox', 'assigned', 'in_progress', 'review', 'done', 'blocked']).default('inbox'),
33
  priority: z.enum(['critical', 'high', 'medium', 'low']).default('medium'),
34
  assigned_to: z.string().max(100).optional(),
35
  created_by: z.string().max(100).optional(),
@@ -72,3 +72,84 @@ export const createAlertSchema = z.object({
72
  action_config: z.record(z.string(), z.unknown()).optional(),
73
  cooldown_minutes: z.number().min(1).max(10080).optional(),
74
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  export const createTaskSchema = z.object({
30
  title: z.string().min(1, 'Title is required').max(500),
31
  description: z.string().max(5000).optional(),
32
+ status: z.enum(['inbox', 'assigned', 'in_progress', 'review', 'quality_review', 'done']).default('inbox'),
33
  priority: z.enum(['critical', 'high', 'medium', 'low']).default('medium'),
34
  assigned_to: z.string().max(100).optional(),
35
  created_by: z.string().max(100).optional(),
 
72
  action_config: z.record(z.string(), z.unknown()).optional(),
73
  cooldown_minutes: z.number().min(1).max(10080).optional(),
74
  })
75
+
76
+ export const notificationActionSchema = z.object({
77
+ action: z.literal('mark-delivered'),
78
+ agent: z.string().min(1, 'Agent name is required'),
79
+ })
80
+
81
+ export const integrationActionSchema = z.object({
82
+ action: z.enum(['test', 'pull', 'pull-all']),
83
+ integrationId: z.string().optional(),
84
+ category: z.string().optional(),
85
+ })
86
+
87
+ export const createPipelineSchema = z.object({
88
+ name: z.string().min(1, 'Name is required'),
89
+ description: z.string().optional(),
90
+ steps: z.array(z.object({
91
+ template_id: z.number(),
92
+ on_failure: z.enum(['stop', 'continue']).default('stop'),
93
+ })).min(2, 'Pipeline needs at least 2 steps'),
94
+ })
95
+
96
+ export const createWorkflowSchema = z.object({
97
+ name: z.string().min(1, 'Name is required'),
98
+ task_prompt: z.string().min(1, 'Task prompt is required'),
99
+ description: z.string().optional(),
100
+ model: z.string().default('sonnet'),
101
+ timeout_seconds: z.number().default(300),
102
+ agent_role: z.string().optional(),
103
+ tags: z.array(z.string()).default([]),
104
+ })
105
+
106
+ export const createCommentSchema = z.object({
107
+ task_id: z.number().optional(),
108
+ content: z.string().min(1, 'Comment content is required'),
109
+ author: z.string().optional(),
110
+ parent_id: z.number().optional(),
111
+ })
112
+
113
+ export const createMessageSchema = z.object({
114
+ to: z.string().min(1, 'Recipient is required'),
115
+ message: z.string().min(1, 'Message is required'),
116
+ from: z.string().optional().default('system'),
117
+ })
118
+
119
+ export const updateSettingsSchema = z.object({
120
+ settings: z.record(z.string(), z.unknown()),
121
+ })
122
+
123
+ export const gatewayConfigUpdateSchema = z.object({
124
+ updates: z.record(z.string(), z.unknown()),
125
+ })
126
+
127
+ export const qualityReviewSchema = z.object({
128
+ taskId: z.number(),
129
+ reviewer: z.string().default('aegis'),
130
+ status: z.enum(['approved', 'rejected']),
131
+ notes: z.string().min(1, 'Notes are required for quality reviews'),
132
+ })
133
+
134
+ export const spawnAgentSchema = z.object({
135
+ task: z.string().min(1, 'Task is required'),
136
+ model: z.string().min(1, 'Model is required'),
137
+ label: z.string().min(1, 'Label is required'),
138
+ timeoutSeconds: z.number().min(10).max(3600).default(300),
139
+ })
140
+
141
+ export const createUserSchema = z.object({
142
+ username: z.string().min(1, 'Username is required'),
143
+ password: z.string().min(1, 'Password is required'),
144
+ display_name: z.string().optional(),
145
+ role: z.enum(['admin', 'operator', 'viewer']).default('operator'),
146
+ provider: z.enum(['local', 'google']).default('local'),
147
+ email: z.string().optional(),
148
+ })
149
+
150
+ export const accessRequestActionSchema = z.object({
151
+ request_id: z.number(),
152
+ action: z.enum(['approve', 'reject']),
153
+ role: z.enum(['admin', 'operator', 'viewer']).default('viewer'),
154
+ note: z.string().optional(),
155
+ })