From 55c94f72cbae7bae07a5c64a6ff2142ddb466b73 Mon Sep 17 00:00:00 2001 From: Sweets Sweetman Date: Tue, 1 Sep 2026 10:43:41 -0500 Subject: [PATCH 1/2] feat(projects): task comments, read and post (app#2048) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET and POST /api/projects/{projectId}/tasks/{taskId}/comments. This is the thread that replaces the email chain: a client comments on the task itself and we answer in the same place. Comments are append-only plain text. No edit, no delete, no markdown, no mentions, no attachments — each is a real feature with real edge cases and none is needed to replace an email thread. The author is the authenticated account, never a field in the body, so a comment cannot be posted as someone else. Both handlers confirm the task belongs to the project before touching its comments, so a task id from elsewhere cannot be read or written through a project the caller does collaborate on. The validator mirrors the column's 4000-character CHECK rather than trusting it: a 400 naming the field beats a 500 from a constraint violation. Contract: recoupable/docs#326. Tables: recoupable/database#68. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01BTaK5sDuryYsQG5W56mR5n --- .../tasks/[taskId]/comments/route.ts | 53 +++++++++++++++++++ .../validateCreateProjectCommentBody.test.ts | 32 +++++++++++ lib/projects/createProjectCommentHandler.ts | 48 +++++++++++++++++ lib/projects/getProjectCommentsHandler.ts | 41 ++++++++++++++ .../validateCreateProjectCommentBody.ts | 45 ++++++++++++++++ .../insertProjectTaskComment.ts | 24 +++++++++ 6 files changed, 243 insertions(+) create mode 100644 app/api/projects/[projectId]/tasks/[taskId]/comments/route.ts create mode 100644 lib/projects/__tests__/validateCreateProjectCommentBody.test.ts create mode 100644 lib/projects/createProjectCommentHandler.ts create mode 100644 lib/projects/getProjectCommentsHandler.ts create mode 100644 lib/projects/validateCreateProjectCommentBody.ts create mode 100644 lib/supabase/project_task_comments/insertProjectTaskComment.ts diff --git a/app/api/projects/[projectId]/tasks/[taskId]/comments/route.ts b/app/api/projects/[projectId]/tasks/[taskId]/comments/route.ts new file mode 100644 index 000000000..47c2e5bd5 --- /dev/null +++ b/app/api/projects/[projectId]/tasks/[taskId]/comments/route.ts @@ -0,0 +1,53 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { getProjectCommentsHandler } from "@/lib/projects/getProjectCommentsHandler"; +import { createProjectCommentHandler } from "@/lib/projects/createProjectCommentHandler"; + +/** + * OPTIONS handler for CORS preflight requests. + * + * @returns A 204 NextResponse carrying the CORS headers. + */ +export async function OPTIONS() { + return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); +} + +/** + * GET /api/projects/{projectId}/tasks/{taskId}/comments + * + * A task's comments, oldest first (app#2048, contract: recoupable/docs#326). + * + * @param request - The incoming request, carrying the Bearer credential. + * @param root0 - The route context. + * @param root0.params - The resolved `projectId` and `taskId` parameters. + * @returns 200 with the comments; 401 unauthenticated; 404 when the caller is + * not a collaborator or no such task exists; 500 on a database failure. + */ +export async function GET( + request: NextRequest, + { params }: { params: Promise<{ projectId: string; taskId: string }> }, +): Promise { + const { projectId, taskId } = await params; + return getProjectCommentsHandler(request, projectId, taskId); +} + +/** + * POST /api/projects/{projectId}/tasks/{taskId}/comments + * + * Post a comment attributed to the caller (app#2048). + * + * @param request - The incoming request, carrying the Bearer credential. + * @param root0 - The route context. + * @param root0.params - The resolved `projectId` and `taskId` parameters. + * @returns 201 with the comment; 400 on a bad body; 401 unauthenticated; 404 + * when the caller is not a collaborator or no such task exists; 500. + */ +export async function POST( + request: NextRequest, + { params }: { params: Promise<{ projectId: string; taskId: string }> }, +): Promise { + const { projectId, taskId } = await params; + return createProjectCommentHandler(request, projectId, taskId); +} + +export const dynamic = "force-dynamic"; diff --git a/lib/projects/__tests__/validateCreateProjectCommentBody.test.ts b/lib/projects/__tests__/validateCreateProjectCommentBody.test.ts new file mode 100644 index 000000000..5489ceff6 --- /dev/null +++ b/lib/projects/__tests__/validateCreateProjectCommentBody.test.ts @@ -0,0 +1,32 @@ +import { describe, it, expect } from "vitest"; +import { NextResponse } from "next/server"; +import { + validateCreateProjectCommentBody, + COMMENT_MAX_LENGTH, +} from "@/lib/projects/validateCreateProjectCommentBody"; + +describe("validateCreateProjectCommentBody", () => { + it("accepts and trims a comment", () => { + expect(validateCreateProjectCommentBody({ body: " hello " })).toEqual({ + body: "hello", + }); + }); + + it("rejects whitespace only, which the database CHECK would also reject", () => { + expect(validateCreateProjectCommentBody({ body: " " })).toBeInstanceOf(NextResponse); + }); + + it("rejects a missing body", () => { + expect(validateCreateProjectCommentBody({})).toBeInstanceOf(NextResponse); + }); + + it("rejects a comment past the column's length cap", () => { + const tooLong = { body: "x".repeat(COMMENT_MAX_LENGTH + 1) }; + expect(validateCreateProjectCommentBody(tooLong)).toBeInstanceOf(NextResponse); + }); + + it("accepts a comment exactly at the cap", () => { + const atCap = { body: "x".repeat(COMMENT_MAX_LENGTH) }; + expect(validateCreateProjectCommentBody(atCap)).toEqual(atCap); + }); +}); diff --git a/lib/projects/createProjectCommentHandler.ts b/lib/projects/createProjectCommentHandler.ts new file mode 100644 index 000000000..8900478ba --- /dev/null +++ b/lib/projects/createProjectCommentHandler.ts @@ -0,0 +1,48 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; +import { errorResponse } from "@/lib/networking/errorResponse"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { requireProjectAccess } from "@/lib/projects/requireProjectAccess"; +import { validateCreateProjectCommentBody } from "@/lib/projects/validateCreateProjectCommentBody"; +import { selectProjectTask } from "@/lib/supabase/project_tasks/selectProjectTask"; +import { insertProjectTaskComment } from "@/lib/supabase/project_task_comments/insertProjectTaskComment"; +import { toProjectComment } from "@/lib/projects/toProjectComment"; + +/** + * POST /api/projects/{projectId}/tasks/{taskId}/comments + * + * Post a comment, attributed to the authenticated account. Append-only: there + * is no edit and no delete. Contract: recoupable/docs#326. + * + * @param request - The incoming request. + * @param projectId - The project the task belongs to. + * @param taskId - The task to comment on. + * @returns 201 with the comment, 400, 401, 404 or 500. + */ +export async function createProjectCommentHandler( + request: NextRequest, + projectId: string, + taskId: string, +): Promise { + const access = await requireProjectAccess(request, projectId); + if (access instanceof NextResponse) return access; + + const body = await request.json().catch(() => null); + const validated = validateCreateProjectCommentBody(body); + if (validated instanceof NextResponse) return validated; + + try { + const task = await selectProjectTask(projectId, taskId); + if (!task) return errorResponse("Task not found", 404); + + const comment = await insertProjectTaskComment(taskId, access, validated.body); + + return NextResponse.json( + { status: "success", comment: toProjectComment(comment) }, + { status: 201, headers: getCorsHeaders() }, + ); + } catch (error) { + console.error("Error creating project task comment:", error); + return errorResponse("Internal server error", 500); + } +} diff --git a/lib/projects/getProjectCommentsHandler.ts b/lib/projects/getProjectCommentsHandler.ts new file mode 100644 index 000000000..18c82e8f5 --- /dev/null +++ b/lib/projects/getProjectCommentsHandler.ts @@ -0,0 +1,41 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; +import { errorResponse } from "@/lib/networking/errorResponse"; +import { successResponse } from "@/lib/networking/successResponse"; +import { requireProjectAccess } from "@/lib/projects/requireProjectAccess"; +import { selectProjectTask } from "@/lib/supabase/project_tasks/selectProjectTask"; +import { selectProjectTaskComments } from "@/lib/supabase/project_task_comments/selectProjectTaskComments"; +import { toProjectComment } from "@/lib/projects/toProjectComment"; + +/** + * GET /api/projects/{projectId}/tasks/{taskId}/comments + * + * A task's comments, oldest first. Contract: recoupable/docs#326. + * + * @param request - The incoming request. + * @param projectId - The project the task belongs to. + * @param taskId - The task whose comments to read. + * @returns 200 with the comments, 401, 404 or 500. + */ +export async function getProjectCommentsHandler( + request: NextRequest, + projectId: string, + taskId: string, +): Promise { + const access = await requireProjectAccess(request, projectId); + if (access instanceof NextResponse) return access; + + try { + // Confirms the task belongs to this project before reading its comments, + // so a task id from elsewhere cannot be read through a project the caller + // does collaborate on. + const task = await selectProjectTask(projectId, taskId); + if (!task) return errorResponse("Task not found", 404); + + const comments = await selectProjectTaskComments(taskId); + return successResponse({ comments: comments.map(toProjectComment) }); + } catch (error) { + console.error("Error fetching project task comments:", error); + return errorResponse("Internal server error", 500); + } +} diff --git a/lib/projects/validateCreateProjectCommentBody.ts b/lib/projects/validateCreateProjectCommentBody.ts new file mode 100644 index 000000000..cd0f89fa4 --- /dev/null +++ b/lib/projects/validateCreateProjectCommentBody.ts @@ -0,0 +1,45 @@ +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { z } from "zod"; + +/** Matches the `length(body) <= 4000` CHECK on project_task_comments. */ +export const COMMENT_MAX_LENGTH = 4000; + +export const createProjectCommentBodySchema = z.object({ + body: z + .string({ message: "body is required" }) + .trim() + .min(1, "body cannot be empty") + .max(COMMENT_MAX_LENGTH, `body cannot exceed ${COMMENT_MAX_LENGTH} characters`), +}); + +export type CreateProjectCommentBody = z.infer; + +/** + * Validates the body for POST /api/projects/{projectId}/tasks/{taskId}/comments. + * + * The length cap mirrors the database CHECK rather than trusting it: a 400 + * naming the field beats a 500 from a constraint violation. + * + * @param body - The request body. + * @returns The validated body, or a 400 NextResponse naming the first problem. + */ +export function validateCreateProjectCommentBody( + body: unknown, +): NextResponse | CreateProjectCommentBody { + const result = createProjectCommentBodySchema.safeParse(body); + + if (!result.success) { + const firstError = result.error.issues[0]; + return NextResponse.json( + { + status: "error", + missing_fields: firstError.path, + error: firstError.message, + }, + { status: 400, headers: getCorsHeaders() }, + ); + } + + return result.data; +} diff --git a/lib/supabase/project_task_comments/insertProjectTaskComment.ts b/lib/supabase/project_task_comments/insertProjectTaskComment.ts new file mode 100644 index 000000000..c6fa54379 --- /dev/null +++ b/lib/supabase/project_task_comments/insertProjectTaskComment.ts @@ -0,0 +1,24 @@ +import supabase from "../serverClient"; +import type { ProjectTaskCommentRow } from "./selectProjectTaskComments"; + +/** + * Post a comment on a task, returning it with its author's account name so the + * caller can render the new row without a second read. + */ +export async function insertProjectTaskComment( + taskId: string, + accountId: string, + body: string, +): Promise { + const { data, error } = await supabase + .from("project_task_comments") + .insert({ task_id: taskId, account_id: accountId, body }) + .select("id, task_id, account_id, body, created_at, accounts(name)") + .single(); + + if (error) { + throw new Error(`Failed to insert project_task_comments: ${error.message}`); + } + + return data as unknown as ProjectTaskCommentRow; +} From c57ae77164d41a5d724e8885f8cc1070e8067ff6 Mon Sep 17 00:00:00 2001 From: Sweets Sweetman Date: Tue, 1 Sep 2026 13:36:18 -0500 Subject: [PATCH 2/2] fix(projects): repair the semantic merge break, one validate call per handler MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The `main` merge into this branch was clean textually and broken semantically: git had no conflict to report, but api#881 changed the API underneath these files and the branch kept calling the old one. Two failures, both caught by `tsc` and both red on the Vercel build: 1. `insertProjectTaskComment` imported `ProjectTaskCommentRow` from `selectProjectTaskComments`. api#881 deleted that hand-written type in favour of the inferred one — `TS2305: Module has no exported member`. 2. `getProjectCommentsHandler` called `selectProjectTaskComments(taskId)`. api#883 collapsed that function to take a list — `TS2345: Argument of type 'string' is not assignable to parameter of type 'string[]'`. Worse than a type error if it had compiled: a bare string reaching `.in()` does not filter the way a caller would expect. Both now follow main: the insert returns the inferred row, and the read passes `[taskId]`. **SRP (review comment).** Both handlers ran `requireProjectAccess` inline. `POST` now makes one call to `validateCreateProjectCommentRequest`, which returns `{ accountId, body }`; `GET` has no body, so its whole requirement is the shared `validateProjectTaskRequest` from api#881. Access resolves before the body, so an unauthorised caller never learns whether their body would have been accepted. That also fixes a 500 this PR would have shipped: a non-UUID `taskId` reached Postgres, the same defect api#881 and api#882 each had to fix. Routing through those validators brings the `requireUuidParam` guard with it. Test written red first against the missing module. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01MpcHy63mJgvXYmwKcgsn9i --- ...alidateCreateProjectCommentRequest.test.ts | 49 +++++++++++++++++++ lib/projects/createProjectCommentHandler.ts | 12 ++--- lib/projects/getProjectCommentsHandler.ts | 6 +-- .../validateCreateProjectCommentRequest.ts | 42 ++++++++++++++++ .../insertProjectTaskComment.ts | 9 +--- 5 files changed, 100 insertions(+), 18 deletions(-) create mode 100644 lib/projects/__tests__/validateCreateProjectCommentRequest.test.ts create mode 100644 lib/projects/validateCreateProjectCommentRequest.ts diff --git a/lib/projects/__tests__/validateCreateProjectCommentRequest.test.ts b/lib/projects/__tests__/validateCreateProjectCommentRequest.test.ts new file mode 100644 index 000000000..d0d56ccdb --- /dev/null +++ b/lib/projects/__tests__/validateCreateProjectCommentRequest.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it, vi } from "vitest"; +import { NextRequest } from "next/server"; +import { validateCreateProjectCommentRequest } from "@/lib/projects/validateCreateProjectCommentRequest"; + +vi.mock("@/lib/supabase/serverClient", () => ({ default: {} })); +vi.mock("@/lib/projects/requireProjectAccess", () => ({ + requireProjectAccess: vi.fn(), +})); + +const PROJECT_ID = "60a9a3e7-b7b2-466f-91d3-59b96e875bf6"; +const url = "https://api.recoupable.dev/api/projects/x/tasks/y/comments"; +const post = (body: unknown) => + new NextRequest(url, { + method: "POST", + body: JSON.stringify(body), + headers: { "content-type": "application/json" }, + }); + +const read = (result: unknown) => (result as Response).json(); + +describe("validateCreateProjectCommentRequest", () => { + it("rejects a malformed projectId with 400", async () => { + const result = await validateCreateProjectCommentRequest( + post({ body: "hi" }), + "not-a-uuid", + PROJECT_ID, + ); + + expect(result).toMatchObject({ status: 400 }); + await expect(read(result)).resolves.toEqual({ + status: "error", + error: "projectId must be a valid UUID", + }); + }); + + it("rejects a malformed taskId with 400 rather than letting it reach Postgres", async () => { + const result = await validateCreateProjectCommentRequest( + post({ body: "hi" }), + PROJECT_ID, + "not-a-uuid", + ); + + expect(result).toMatchObject({ status: 400 }); + await expect(read(result)).resolves.toEqual({ + status: "error", + error: "taskId must be a valid UUID", + }); + }); +}); diff --git a/lib/projects/createProjectCommentHandler.ts b/lib/projects/createProjectCommentHandler.ts index 8900478ba..575b0421e 100644 --- a/lib/projects/createProjectCommentHandler.ts +++ b/lib/projects/createProjectCommentHandler.ts @@ -2,8 +2,7 @@ import type { NextRequest } from "next/server"; import { NextResponse } from "next/server"; import { errorResponse } from "@/lib/networking/errorResponse"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; -import { requireProjectAccess } from "@/lib/projects/requireProjectAccess"; -import { validateCreateProjectCommentBody } from "@/lib/projects/validateCreateProjectCommentBody"; +import { validateCreateProjectCommentRequest } from "@/lib/projects/validateCreateProjectCommentRequest"; import { selectProjectTask } from "@/lib/supabase/project_tasks/selectProjectTask"; import { insertProjectTaskComment } from "@/lib/supabase/project_task_comments/insertProjectTaskComment"; import { toProjectComment } from "@/lib/projects/toProjectComment"; @@ -24,18 +23,15 @@ export async function createProjectCommentHandler( projectId: string, taskId: string, ): Promise { - const access = await requireProjectAccess(request, projectId); - if (access instanceof NextResponse) return access; - - const body = await request.json().catch(() => null); - const validated = validateCreateProjectCommentBody(body); + const validated = await validateCreateProjectCommentRequest(request, projectId, taskId); if (validated instanceof NextResponse) return validated; + const { accountId, body } = validated; try { const task = await selectProjectTask(projectId, taskId); if (!task) return errorResponse("Task not found", 404); - const comment = await insertProjectTaskComment(taskId, access, validated.body); + const comment = await insertProjectTaskComment(taskId, accountId, body.body); return NextResponse.json( { status: "success", comment: toProjectComment(comment) }, diff --git a/lib/projects/getProjectCommentsHandler.ts b/lib/projects/getProjectCommentsHandler.ts index 18c82e8f5..60b6ae028 100644 --- a/lib/projects/getProjectCommentsHandler.ts +++ b/lib/projects/getProjectCommentsHandler.ts @@ -2,7 +2,7 @@ import type { NextRequest } from "next/server"; import { NextResponse } from "next/server"; import { errorResponse } from "@/lib/networking/errorResponse"; import { successResponse } from "@/lib/networking/successResponse"; -import { requireProjectAccess } from "@/lib/projects/requireProjectAccess"; +import { validateProjectTaskRequest } from "@/lib/projects/validateProjectTaskRequest"; import { selectProjectTask } from "@/lib/supabase/project_tasks/selectProjectTask"; import { selectProjectTaskComments } from "@/lib/supabase/project_task_comments/selectProjectTaskComments"; import { toProjectComment } from "@/lib/projects/toProjectComment"; @@ -22,7 +22,7 @@ export async function getProjectCommentsHandler( projectId: string, taskId: string, ): Promise { - const access = await requireProjectAccess(request, projectId); + const access = await validateProjectTaskRequest(request, projectId, taskId); if (access instanceof NextResponse) return access; try { @@ -32,7 +32,7 @@ export async function getProjectCommentsHandler( const task = await selectProjectTask(projectId, taskId); if (!task) return errorResponse("Task not found", 404); - const comments = await selectProjectTaskComments(taskId); + const comments = await selectProjectTaskComments([taskId]); return successResponse({ comments: comments.map(toProjectComment) }); } catch (error) { console.error("Error fetching project task comments:", error); diff --git a/lib/projects/validateCreateProjectCommentRequest.ts b/lib/projects/validateCreateProjectCommentRequest.ts new file mode 100644 index 000000000..e4ec20a76 --- /dev/null +++ b/lib/projects/validateCreateProjectCommentRequest.ts @@ -0,0 +1,42 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; +import { validateProjectTaskRequest } from "@/lib/projects/validateProjectTaskRequest"; +import { + validateCreateProjectCommentBody, + type CreateProjectCommentBody, +} from "@/lib/projects/validateCreateProjectCommentBody"; + +export interface CreateProjectCommentRequest { + accountId: string; + body: CreateProjectCommentBody; +} + +/** + * Everything `POST /api/projects/{projectId}/tasks/{taskId}/comments` requires: + * both path ids well formed, a caller with a collaborator row on the project, + * and a valid body — in that order, so an unauthorised caller never learns + * whether their body would have been accepted. + * + * The id checks are not tidiness: an unguarded `taskId` reaches Postgres as + * `invalid input syntax for type uuid` and surfaces as a 500 rather than the + * 400 the contract documents. + * + * @param request - The incoming request, carrying the Bearer credential. + * @param projectId - The `projectId` path segment, unvalidated. + * @param taskId - The `taskId` path segment, unvalidated. + * @returns The authenticated account and validated body, or the response to + * return instead. + */ +export async function validateCreateProjectCommentRequest( + request: NextRequest, + projectId: string, + taskId: string, +): Promise { + const access = await validateProjectTaskRequest(request, projectId, taskId); + if (access instanceof NextResponse) return access; + + const body = validateCreateProjectCommentBody(await request.json().catch(() => null)); + if (body instanceof NextResponse) return body; + + return { accountId: access, body }; +} diff --git a/lib/supabase/project_task_comments/insertProjectTaskComment.ts b/lib/supabase/project_task_comments/insertProjectTaskComment.ts index c6fa54379..2c2d5ecfd 100644 --- a/lib/supabase/project_task_comments/insertProjectTaskComment.ts +++ b/lib/supabase/project_task_comments/insertProjectTaskComment.ts @@ -1,15 +1,10 @@ import supabase from "../serverClient"; -import type { ProjectTaskCommentRow } from "./selectProjectTaskComments"; /** * Post a comment on a task, returning it with its author's account name so the * caller can render the new row without a second read. */ -export async function insertProjectTaskComment( - taskId: string, - accountId: string, - body: string, -): Promise { +export async function insertProjectTaskComment(taskId: string, accountId: string, body: string) { const { data, error } = await supabase .from("project_task_comments") .insert({ task_id: taskId, account_id: accountId, body }) @@ -20,5 +15,5 @@ export async function insertProjectTaskComment( throw new Error(`Failed to insert project_task_comments: ${error.message}`); } - return data as unknown as ProjectTaskCommentRow; + return data; }