mirror of
https://github.com/BradGroux/veritas-kanban.git
synced 2026-12-02 10:47:17 +00:00
## Summary - adds task/comment/workflow revision metadata, ETag headers, and stale-write 409 conflict responses - records actors on task, comment, activity, audit, and workflow API mutations - sends cached revisions from web task/comment mutations and reloads the current task on conflicts - documents the conflict contract and adds route/API regression coverage ## Verification - `VERITAS_DISABLE_WATCHERS=1 node_modules/.bin/vitest run server/src/__tests__/routes/tasks-coverage.test.ts server/src/__tests__/routes/optimistic-concurrency.test.ts` - `node_modules/.bin/prettier --check server/src/__tests__/routes/tasks-coverage.test.ts` - `pnpm --filter @veritas-kanban/server typecheck` - `git diff --check` - PR checks: Build, Lint & Type Check, Security Audit, Workspace Unit Tests
202 lines
6.1 KiB
TypeScript
202 lines
6.1 KiB
TypeScript
import { Router, type Router as RouterType } from 'express';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { z } from 'zod';
|
|
import { getTaskService } from '../services/task-service.js';
|
|
import { activityService } from '../services/activity-service.js';
|
|
import { getGitHubSyncService } from '../services/github-sync-service.js';
|
|
import { asyncHandler } from '../middleware/async-handler.js';
|
|
import { NotFoundError, ValidationError } from '../middleware/error-handler.js';
|
|
import { sanitizeCommentText, sanitizeAuthor } from '../utils/sanitize.js';
|
|
import { broadcastTaskChange } from '../services/broadcast-service.js';
|
|
import type { AuthenticatedRequest } from '../middleware/auth.js';
|
|
import { actorFromRequest, assertFreshRevision, setRevisionHeaders } from '../utils/concurrency.js';
|
|
|
|
const router: RouterType = Router();
|
|
const taskService = getTaskService();
|
|
|
|
// Validation schemas
|
|
const addCommentSchema = z.object({
|
|
author: z.string().min(1).max(100),
|
|
text: z.string().min(1).max(2000),
|
|
});
|
|
|
|
// POST /api/tasks/:id/comments - Add comment
|
|
router.post(
|
|
'/:id/comments',
|
|
asyncHandler(async (req, res) => {
|
|
let author: string, text: string;
|
|
try {
|
|
({ author, text } = addCommentSchema.parse(req.body));
|
|
} catch (error) {
|
|
if (error instanceof z.ZodError) {
|
|
throw new ValidationError('Validation failed', error.issues);
|
|
}
|
|
throw error;
|
|
}
|
|
// Sanitize user-provided text fields to prevent stored XSS
|
|
author = sanitizeAuthor(author);
|
|
text = sanitizeCommentText(text);
|
|
|
|
const task = await taskService.getTask(req.params.id as string);
|
|
if (!task) {
|
|
throw new NotFoundError('Task not found');
|
|
}
|
|
assertFreshRevision(req, 'task', task.id, task);
|
|
const actor = actorFromRequest(req as AuthenticatedRequest);
|
|
|
|
const comment = {
|
|
id: `comment_${randomUUID()}`,
|
|
author,
|
|
text,
|
|
timestamp: new Date().toISOString(),
|
|
revision: 1,
|
|
createdBy: actor,
|
|
updatedBy: actor,
|
|
};
|
|
|
|
const comments = [...(task.comments || []), comment];
|
|
const updatedTask = await taskService.updateTask(req.params.id as string, {
|
|
comments,
|
|
updatedBy: actor,
|
|
});
|
|
if (!updatedTask) {
|
|
throw new NotFoundError('Task not found');
|
|
}
|
|
|
|
// Log activity
|
|
await activityService.logActivity(
|
|
'comment_added',
|
|
task.id,
|
|
task.title,
|
|
{
|
|
author,
|
|
preview: text.slice(0, 50) + (text.length > 50 ? '...' : ''),
|
|
actor,
|
|
},
|
|
task.agent,
|
|
actor
|
|
);
|
|
|
|
// Broadcast update to all connected WebSocket clients
|
|
broadcastTaskChange('updated', task.id);
|
|
|
|
// Outbound sync: post comment to linked GitHub issue (fire-and-forget)
|
|
if (task.github) {
|
|
getGitHubSyncService()
|
|
.syncCommentToGitHub(task, `**${author}:** ${text}`)
|
|
.catch(() => {
|
|
/* intentionally silent — don't fail the API call */
|
|
});
|
|
}
|
|
|
|
setRevisionHeaders(res, 'task', updatedTask.id, updatedTask);
|
|
res.status(201).json(updatedTask);
|
|
})
|
|
);
|
|
|
|
// PATCH /api/tasks/:id/comments/:commentId - Edit comment
|
|
router.patch(
|
|
'/:id/comments/:commentId',
|
|
asyncHandler(async (req, res) => {
|
|
let text: string;
|
|
try {
|
|
({ text } = z.object({ text: z.string().min(1) }).parse(req.body));
|
|
} catch (error) {
|
|
if (error instanceof z.ZodError) {
|
|
throw new ValidationError('Validation failed', error.issues);
|
|
}
|
|
throw error;
|
|
}
|
|
// Sanitize user-provided text to prevent stored XSS
|
|
text = sanitizeCommentText(text);
|
|
|
|
const task = await taskService.getTask(req.params.id as string);
|
|
if (!task) {
|
|
throw new NotFoundError('Task not found');
|
|
}
|
|
assertFreshRevision(req, 'task', task.id, task);
|
|
const actor = actorFromRequest(req as AuthenticatedRequest);
|
|
|
|
const comments = [...(task.comments || [])];
|
|
const commentIndex = comments.findIndex(
|
|
(c: { id: string; author: string; text: string; timestamp: string }) =>
|
|
c.id === (req.params.commentId as string)
|
|
);
|
|
if (commentIndex === -1) {
|
|
throw new NotFoundError('Comment not found');
|
|
}
|
|
|
|
comments[commentIndex] = {
|
|
...comments[commentIndex],
|
|
text,
|
|
timestamp: comments[commentIndex].timestamp, // preserve original timestamp
|
|
updated: new Date().toISOString(),
|
|
updatedBy: actor,
|
|
revision: (comments[commentIndex]?.revision ?? 1) + 1,
|
|
};
|
|
|
|
const updatedTask = await taskService.updateTask(req.params.id as string, {
|
|
comments,
|
|
updatedBy: actor,
|
|
});
|
|
if (!updatedTask) {
|
|
throw new NotFoundError('Task not found');
|
|
}
|
|
|
|
// Broadcast update to all connected WebSocket clients
|
|
broadcastTaskChange('updated', req.params.id as string);
|
|
|
|
setRevisionHeaders(res, 'task', updatedTask.id, updatedTask);
|
|
res.json(updatedTask);
|
|
})
|
|
);
|
|
|
|
// DELETE /api/tasks/:id/comments/:commentId - Delete comment
|
|
router.delete(
|
|
'/:id/comments/:commentId',
|
|
asyncHandler(async (req, res) => {
|
|
const task = await taskService.getTask(req.params.id as string);
|
|
if (!task) {
|
|
throw new NotFoundError('Task not found');
|
|
}
|
|
assertFreshRevision(req, 'task', task.id, task);
|
|
const actor = actorFromRequest(req as AuthenticatedRequest);
|
|
|
|
const comments = task.comments || [];
|
|
const filtered = comments.filter(
|
|
(c: { id: string; author: string; text: string; timestamp: string }) =>
|
|
c.id !== (req.params.commentId as string)
|
|
);
|
|
if (filtered.length === comments.length) {
|
|
throw new NotFoundError('Comment not found');
|
|
}
|
|
|
|
const updatedTask = await taskService.updateTask(req.params.id as string, {
|
|
comments: filtered,
|
|
updatedBy: actor,
|
|
});
|
|
if (!updatedTask) {
|
|
throw new NotFoundError('Task not found');
|
|
}
|
|
|
|
await activityService.logActivity(
|
|
'comment_deleted',
|
|
task.id,
|
|
task.title,
|
|
{
|
|
commentId: req.params.commentId as string,
|
|
actor,
|
|
},
|
|
task.agent,
|
|
actor
|
|
);
|
|
|
|
// Broadcast update to all connected WebSocket clients
|
|
broadcastTaskChange('updated', task.id);
|
|
|
|
setRevisionHeaders(res, 'task', updatedTask.id, updatedTask);
|
|
res.json(updatedTask);
|
|
})
|
|
);
|
|
|
|
export { router as taskCommentRoutes };
|