From d9533eb71434bd2ab704569714a148bbb38df635 Mon Sep 17 00:00:00 2001 From: Sweets Sweetman Date: Tue, 1 Sep 2026 10:42:13 -0500 Subject: [PATCH 1/2] feat(projects): task create, update and delete (app#2048) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit POST /api/projects/{projectId}/tasks, plus PATCH and DELETE on a single task. This is what makes a project seedable at all: with no project-creation endpoint, tasks are authored over the API from Claude Code. Completion moves only through PATCH's `completed` boolean. toTaskUpdates stamps completed_at from the server clock and completed_by from the authenticated account, and the validator does not accept either field from the caller — so who closed an item, and when, is never the client's word for it. An empty PATCH body is a 400 rather than a no-op 200: silently succeeding on a body that changes nothing hides a broken client. Both ids are matched on every write, so a task id from another project cannot be updated or deleted through a project the caller does collaborate on. Contract: recoupable/docs#326. Tables: recoupable/database#68. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01BTaK5sDuryYsQG5W56mR5n --- .../[projectId]/tasks/[taskId]/route.ts | 40 +++++++++++++++ app/api/projects/[projectId]/tasks/route.ts | 33 ++++++++++++ lib/projects/__tests__/toTaskUpdates.test.ts | 27 ++++++++++ .../validateUpdateProjectTaskBody.test.ts | 36 +++++++++++++ lib/projects/createProjectTaskHandler.ts | 48 ++++++++++++++++++ lib/projects/deleteProjectTaskHandler.ts | 36 +++++++++++++ lib/projects/toTaskUpdates.ts | 38 ++++++++++++++ lib/projects/updateProjectTaskHandler.ts | 43 ++++++++++++++++ lib/projects/validateCreateProjectTaskBody.ts | 39 +++++++++++++++ lib/projects/validateUpdateProjectTaskBody.ts | 50 +++++++++++++++++++ .../project_tasks/deleteProjectTask.ts | 20 ++++++++ .../project_tasks/insertProjectTask.ts | 12 +++++ .../project_tasks/updateProjectTask.ts | 25 ++++++++++ 13 files changed, 447 insertions(+) create mode 100644 app/api/projects/[projectId]/tasks/route.ts create mode 100644 lib/projects/__tests__/toTaskUpdates.test.ts create mode 100644 lib/projects/__tests__/validateUpdateProjectTaskBody.test.ts create mode 100644 lib/projects/createProjectTaskHandler.ts create mode 100644 lib/projects/deleteProjectTaskHandler.ts create mode 100644 lib/projects/toTaskUpdates.ts create mode 100644 lib/projects/updateProjectTaskHandler.ts create mode 100644 lib/projects/validateCreateProjectTaskBody.ts create mode 100644 lib/projects/validateUpdateProjectTaskBody.ts create mode 100644 lib/supabase/project_tasks/deleteProjectTask.ts create mode 100644 lib/supabase/project_tasks/insertProjectTask.ts create mode 100644 lib/supabase/project_tasks/updateProjectTask.ts diff --git a/app/api/projects/[projectId]/tasks/[taskId]/route.ts b/app/api/projects/[projectId]/tasks/[taskId]/route.ts index 70b2d2c24..ac1082952 100644 --- a/app/api/projects/[projectId]/tasks/[taskId]/route.ts +++ b/app/api/projects/[projectId]/tasks/[taskId]/route.ts @@ -1,6 +1,8 @@ import { NextRequest, NextResponse } from "next/server"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { getProjectTaskHandler } from "@/lib/projects/getProjectTaskHandler"; +import { updateProjectTaskHandler } from "@/lib/projects/updateProjectTaskHandler"; +import { deleteProjectTaskHandler } from "@/lib/projects/deleteProjectTaskHandler"; /** * OPTIONS handler for CORS preflight requests. @@ -31,4 +33,42 @@ export async function GET( return getProjectTaskHandler(request, projectId, taskId); } +/** + * PATCH /api/projects/{projectId}/tasks/{taskId} + * + * Update a task, including the completion toggle (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 200 with the updated task; 400 on a bad body; 401 unauthenticated; + * 404 when the caller is not a collaborator or no such task exists; 500. + */ +export async function PATCH( + request: NextRequest, + { params }: { params: Promise<{ projectId: string; taskId: string }> }, +): Promise { + const { projectId, taskId } = await params; + return updateProjectTaskHandler(request, projectId, taskId); +} + +/** + * DELETE /api/projects/{projectId}/tasks/{taskId} + * + * Delete a task and its comments (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 200 with the deleted id; 401 unauthenticated; 404 when the caller is + * not a collaborator or no such task exists; 500 on a database failure. + */ +export async function DELETE( + request: NextRequest, + { params }: { params: Promise<{ projectId: string; taskId: string }> }, +): Promise { + const { projectId, taskId } = await params; + return deleteProjectTaskHandler(request, projectId, taskId); +} + export const dynamic = "force-dynamic"; diff --git a/app/api/projects/[projectId]/tasks/route.ts b/app/api/projects/[projectId]/tasks/route.ts new file mode 100644 index 000000000..628a10fea --- /dev/null +++ b/app/api/projects/[projectId]/tasks/route.ts @@ -0,0 +1,33 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { createProjectTaskHandler } from "@/lib/projects/createProjectTaskHandler"; + +/** + * 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() }); +} + +/** + * POST /api/projects/{projectId}/tasks + * + * Add a task to a client project (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` path parameter. + * @returns 201 with the created task; 400 on a bad body; 401 unauthenticated; + * 404 when the caller is not a collaborator; 500 on a database failure. + */ +export async function POST( + request: NextRequest, + { params }: { params: Promise<{ projectId: string }> }, +): Promise { + const { projectId } = await params; + return createProjectTaskHandler(request, projectId); +} + +export const dynamic = "force-dynamic"; diff --git a/lib/projects/__tests__/toTaskUpdates.test.ts b/lib/projects/__tests__/toTaskUpdates.test.ts new file mode 100644 index 000000000..1756e6d3c --- /dev/null +++ b/lib/projects/__tests__/toTaskUpdates.test.ts @@ -0,0 +1,27 @@ +import { describe, it, expect } from "vitest"; +import { toTaskUpdates } from "@/lib/projects/toTaskUpdates"; + +describe("toTaskUpdates", () => { + it("stamps completion from the server clock and the acting account", () => { + const updates = toTaskUpdates({ completed: true }, "acct-1"); + expect(updates.completed_by).toBe("acct-1"); + expect(typeof updates.completed_at).toBe("string"); + }); + + it("clears both fields when reopening", () => { + expect(toTaskUpdates({ completed: false }, "acct-1")).toEqual({ + completed_at: null, + completed_by: null, + }); + }); + + it("leaves completion alone when the body does not mention it", () => { + const updates = toTaskUpdates({ title: "Renamed" }, "acct-1"); + expect(updates).toEqual({ title: "Renamed" }); + }); + + it("maps an explicit null through instead of dropping the field", () => { + // Clearing a due date has to be distinguishable from not touching it. + expect(toTaskUpdates({ due_date: null }, "acct-1")).toEqual({ due_date: null }); + }); +}); diff --git a/lib/projects/__tests__/validateUpdateProjectTaskBody.test.ts b/lib/projects/__tests__/validateUpdateProjectTaskBody.test.ts new file mode 100644 index 000000000..3603adf8a --- /dev/null +++ b/lib/projects/__tests__/validateUpdateProjectTaskBody.test.ts @@ -0,0 +1,36 @@ +import { describe, it, expect } from "vitest"; +import { NextResponse } from "next/server"; +import { validateUpdateProjectTaskBody } from "@/lib/projects/validateUpdateProjectTaskBody"; + +describe("validateUpdateProjectTaskBody", () => { + it("accepts a single field", () => { + expect(validateUpdateProjectTaskBody({ completed: true })).toEqual({ + completed: true, + }); + }); + + it("rejects an empty body rather than treating it as a no-op success", () => { + expect(validateUpdateProjectTaskBody({})).toBeInstanceOf(NextResponse); + }); + + it("rejects a due_date that is not a calendar date", () => { + expect(validateUpdateProjectTaskBody({ due_date: "2026-09-12T00:00:00Z" })).toBeInstanceOf( + NextResponse, + ); + }); + + it("rejects a non-UUID assignee", () => { + expect(validateUpdateProjectTaskBody({ assignee_account_id: "nope" })).toBeInstanceOf( + NextResponse, + ); + }); + + it("does not accept completed_at or completed_by from the caller", () => { + const result = validateUpdateProjectTaskBody({ + completed: true, + completed_at: "1999-01-01T00:00:00Z", + completed_by: "11111111-1111-1111-1111-111111111111", + }); + expect(result).toEqual({ completed: true }); + }); +}); diff --git a/lib/projects/createProjectTaskHandler.ts b/lib/projects/createProjectTaskHandler.ts new file mode 100644 index 000000000..c221fd360 --- /dev/null +++ b/lib/projects/createProjectTaskHandler.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 { validateCreateProjectTaskBody } from "@/lib/projects/validateCreateProjectTaskBody"; +import { insertProjectTask } from "@/lib/supabase/project_tasks/insertProjectTask"; + +/** + * POST /api/projects/{projectId}/tasks + * + * Create a task. New tasks are always incomplete; completion moves through the + * PATCH endpoint so the server owns the timestamp and the actor. + * Contract: recoupable/docs#326. + * + * @param request - The incoming request. + * @param projectId - The project to add the task to. + * @returns 201 with the created task, 400, 401, 404 or 500. + */ +export async function createProjectTaskHandler( + request: NextRequest, + projectId: string, +): Promise { + const access = await requireProjectAccess(request, projectId); + if (access instanceof NextResponse) return access; + + const body = await request.json().catch(() => null); + const validated = validateCreateProjectTaskBody(body); + if (validated instanceof NextResponse) return validated; + + try { + const task = await insertProjectTask({ + project_id: projectId, + title: validated.title, + description: validated.description ?? null, + due_date: validated.due_date ?? null, + assignee_account_id: validated.assignee_account_id ?? null, + }); + + return NextResponse.json( + { status: "success", task }, + { status: 201, headers: getCorsHeaders() }, + ); + } catch (error) { + console.error("Error creating project task:", error); + return errorResponse("Internal server error", 500); + } +} diff --git a/lib/projects/deleteProjectTaskHandler.ts b/lib/projects/deleteProjectTaskHandler.ts new file mode 100644 index 000000000..9c1e75acc --- /dev/null +++ b/lib/projects/deleteProjectTaskHandler.ts @@ -0,0 +1,36 @@ +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 { deleteProjectTask } from "@/lib/supabase/project_tasks/deleteProjectTask"; + +/** + * DELETE /api/projects/{projectId}/tasks/{taskId} + * + * Permanently delete a task and, by cascade, its comments. No soft delete. + * Contract: recoupable/docs#326. + * + * @param request - The incoming request. + * @param projectId - The project the task belongs to. + * @param taskId - The task to delete. + * @returns 200 with the deleted id, 401, 404 or 500. + */ +export async function deleteProjectTaskHandler( + request: NextRequest, + projectId: string, + taskId: string, +): Promise { + const access = await requireProjectAccess(request, projectId); + if (access instanceof NextResponse) return access; + + try { + const deleted = await deleteProjectTask(projectId, taskId); + if (!deleted) return errorResponse("Task not found", 404); + + return successResponse({ id: taskId }); + } catch (error) { + console.error("Error deleting project task:", error); + return errorResponse("Internal server error", 500); + } +} diff --git a/lib/projects/toTaskUpdates.ts b/lib/projects/toTaskUpdates.ts new file mode 100644 index 000000000..caab36e13 --- /dev/null +++ b/lib/projects/toTaskUpdates.ts @@ -0,0 +1,38 @@ +import { TablesUpdate } from "@/types/database.types"; +import type { UpdateProjectTaskBody } from "@/lib/projects/validateUpdateProjectTaskBody"; + +/** + * Turn a validated PATCH body into a row update (app#2048). + * + * `completed` is the only way completion moves: true stamps `completed_at` from + * the server clock and records the acting account, false clears both. The + * caller never supplies either, so who closed an item and when is never the + * client's word for it. + * + * @param body - The validated request body. + * @param accountId - The authenticated account, recorded as `completed_by`. + * @returns The columns to write. + */ +export function toTaskUpdates( + body: UpdateProjectTaskBody, + accountId: string, +): TablesUpdate<"project_tasks"> { + const updates: TablesUpdate<"project_tasks"> = {}; + + if (body.title !== undefined) updates.title = body.title; + if (body.description !== undefined) updates.description = body.description ?? null; + if (body.due_date !== undefined) updates.due_date = body.due_date ?? null; + if (body.assignee_account_id !== undefined) { + updates.assignee_account_id = body.assignee_account_id ?? null; + } + + if (body.completed === true) { + updates.completed_at = new Date().toISOString(); + updates.completed_by = accountId; + } else if (body.completed === false) { + updates.completed_at = null; + updates.completed_by = null; + } + + return updates; +} diff --git a/lib/projects/updateProjectTaskHandler.ts b/lib/projects/updateProjectTaskHandler.ts new file mode 100644 index 000000000..d09506766 --- /dev/null +++ b/lib/projects/updateProjectTaskHandler.ts @@ -0,0 +1,43 @@ +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 { validateUpdateProjectTaskBody } from "@/lib/projects/validateUpdateProjectTaskBody"; +import { toTaskUpdates } from "@/lib/projects/toTaskUpdates"; +import { updateProjectTask } from "@/lib/supabase/project_tasks/updateProjectTask"; + +/** + * PATCH /api/projects/{projectId}/tasks/{taskId} + * + * Update a task, including the completion toggle. Any collaborator may close or + * reopen any task, the client included; the row records which one did. + * Contract: recoupable/docs#326. + * + * @param request - The incoming request. + * @param projectId - The project the task belongs to. + * @param taskId - The task to update. + * @returns 200 with the updated task, 400, 401, 404 or 500. + */ +export async function updateProjectTaskHandler( + 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 = validateUpdateProjectTaskBody(body); + if (validated instanceof NextResponse) return validated; + + try { + const task = await updateProjectTask(projectId, taskId, toTaskUpdates(validated, access)); + if (!task) return errorResponse("Task not found", 404); + + return successResponse({ task }); + } catch (error) { + console.error("Error updating project task:", error); + return errorResponse("Internal server error", 500); + } +} diff --git a/lib/projects/validateCreateProjectTaskBody.ts b/lib/projects/validateCreateProjectTaskBody.ts new file mode 100644 index 000000000..5665f3e95 --- /dev/null +++ b/lib/projects/validateCreateProjectTaskBody.ts @@ -0,0 +1,39 @@ +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { z } from "zod"; + +export const createProjectTaskBodySchema = z.object({ + title: z.string({ message: "title is required" }).trim().min(1, "title cannot be empty"), + description: z.string().trim().nullish(), + due_date: z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/, "due_date must be a YYYY-MM-DD date") + .nullish(), + assignee_account_id: z.string().uuid("assignee_account_id must be a valid UUID").nullish(), +}); + +export type CreateProjectTaskBody = z.infer; + +/** + * Validates the body for POST /api/projects/{projectId}/tasks. + * + * @param body - The request body. + * @returns The validated body, or a 400 NextResponse naming the first problem. + */ +export function validateCreateProjectTaskBody(body: unknown): NextResponse | CreateProjectTaskBody { + const result = createProjectTaskBodySchema.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/projects/validateUpdateProjectTaskBody.ts b/lib/projects/validateUpdateProjectTaskBody.ts new file mode 100644 index 000000000..c2bd3ac44 --- /dev/null +++ b/lib/projects/validateUpdateProjectTaskBody.ts @@ -0,0 +1,50 @@ +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { z } from "zod"; + +export const updateProjectTaskBodySchema = z + .object({ + title: z.string().trim().min(1, "title cannot be empty").optional(), + description: z.string().trim().nullish(), + due_date: z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/, "due_date must be a YYYY-MM-DD date") + .nullish(), + assignee_account_id: z.string().uuid("assignee_account_id must be a valid UUID").nullish(), + completed: z.boolean().optional(), + }) + // An empty PATCH is a caller mistake, not a no-op success: silently + // returning 200 for a body that changes nothing hides a broken client. + .refine(body => Object.keys(body).length > 0, { + message: "at least one field is required", + }); + +export type UpdateProjectTaskBody = z.infer; + +/** + * Validates the body for PATCH /api/projects/{projectId}/tasks/{taskId}. + * + * `completed_at` and `completed_by` are deliberately not accepted: completion + * is toggled with `completed` so the server, not the caller, decides when it + * happened and who did it. + * + * @param body - The request body. + * @returns The validated body, or a 400 NextResponse naming the first problem. + */ +export function validateUpdateProjectTaskBody(body: unknown): NextResponse | UpdateProjectTaskBody { + const result = updateProjectTaskBodySchema.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_tasks/deleteProjectTask.ts b/lib/supabase/project_tasks/deleteProjectTask.ts new file mode 100644 index 000000000..5de9dea06 --- /dev/null +++ b/lib/supabase/project_tasks/deleteProjectTask.ts @@ -0,0 +1,20 @@ +import supabase from "../serverClient"; + +/** + * Delete a task and, by cascade, its comments. Scoped to the project for the + * same reason as the update. + * + * @returns Whether a row was deleted. + */ +export async function deleteProjectTask(projectId: string, taskId: string): Promise { + const { data, error } = await supabase + .from("project_tasks") + .delete() + .eq("project_id", projectId) + .eq("id", taskId) + .select("id") + .maybeSingle(); + + if (error) throw new Error(`Failed to delete project_tasks: ${error.message}`); + return Boolean(data); +} diff --git a/lib/supabase/project_tasks/insertProjectTask.ts b/lib/supabase/project_tasks/insertProjectTask.ts new file mode 100644 index 000000000..7c0315321 --- /dev/null +++ b/lib/supabase/project_tasks/insertProjectTask.ts @@ -0,0 +1,12 @@ +import supabase from "../serverClient"; +import { Tables, TablesInsert } from "@/types/database.types"; + +/** Create a task on a project. */ +export async function insertProjectTask( + task: TablesInsert<"project_tasks">, +): Promise> { + const { data, error } = await supabase.from("project_tasks").insert(task).select("*").single(); + + if (error) throw new Error(`Failed to insert project_tasks: ${error.message}`); + return data; +} diff --git a/lib/supabase/project_tasks/updateProjectTask.ts b/lib/supabase/project_tasks/updateProjectTask.ts new file mode 100644 index 000000000..ee2ad3a90 --- /dev/null +++ b/lib/supabase/project_tasks/updateProjectTask.ts @@ -0,0 +1,25 @@ +import supabase from "../serverClient"; +import { Tables, TablesUpdate } from "@/types/database.types"; + +/** + * Update a task, scoped to its project. + * + * Both ids are matched so a task id from another project cannot be written + * through a project the caller does collaborate on. Null when no row matched. + */ +export async function updateProjectTask( + projectId: string, + taskId: string, + updates: TablesUpdate<"project_tasks">, +): Promise | null> { + const { data, error } = await supabase + .from("project_tasks") + .update(updates) + .eq("project_id", projectId) + .eq("id", taskId) + .select("*") + .maybeSingle(); + + if (error) throw new Error(`Failed to update project_tasks: ${error.message}`); + return data; +} From a43bf0de7eb1be4250bb20bd07829950fb167ebe Mon Sep 17 00:00:00 2001 From: Sweets Sweetman Date: Tue, 1 Sep 2026 13:25:46 -0500 Subject: [PATCH 2/2] refactor(projects): one validate call per CRUD handler, and 400 not 500 on a malformed id MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two things, one change. **SRP (review comment).** All three handlers ran the requirements inline — requireProjectAccess, then a separate body parse and validate. Each now makes one call: validateCreateProjectTaskRequest and validateUpdateProjectTaskRequest resolve access and body together and hand back { accountId, body }; DELETE has no body, so its whole requirement is the shared validateProjectTaskRequest that api#881 already ships. Order inside is access before body, so an unauthorised caller never learns whether their body would have been accepted. The zod body validators stay their own files and keep their tests; the Request functions call them. Named *Request rather than *Body because they now settle more than the body, and a name that says Body while doing an access check would mislead the next reader. **A 500 preview verification caught.** PATCH and DELETE with a non-UUID taskId returned 500, exactly the defect fixed in api#881 — these handlers predated that fix and never picked it up. Routing them through the api#881 validators brings the requireUuidParam guard with it, so both now return the documented 400. POST with a non-UUID projectId was answering 404 by accident, via hasProjectAccess swallowing its lookup error; it is now an explicit 400 too. Tests written red first against the missing modules. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01MpcHy63mJgvXYmwKcgsn9i --- .../validateCreateProjectTaskRequest.test.ts | 28 +++++++++++ .../validateUpdateProjectTaskRequest.test.ts | 49 +++++++++++++++++++ lib/projects/createProjectTaskHandler.ts | 18 +++---- lib/projects/deleteProjectTaskHandler.ts | 4 +- lib/projects/updateProjectTaskHandler.ts | 12 ++--- .../validateCreateProjectTaskRequest.ts | 36 ++++++++++++++ .../validateUpdateProjectTaskRequest.ts | 41 ++++++++++++++++ 7 files changed, 167 insertions(+), 21 deletions(-) create mode 100644 lib/projects/__tests__/validateCreateProjectTaskRequest.test.ts create mode 100644 lib/projects/__tests__/validateUpdateProjectTaskRequest.test.ts create mode 100644 lib/projects/validateCreateProjectTaskRequest.ts create mode 100644 lib/projects/validateUpdateProjectTaskRequest.ts diff --git a/lib/projects/__tests__/validateCreateProjectTaskRequest.test.ts b/lib/projects/__tests__/validateCreateProjectTaskRequest.test.ts new file mode 100644 index 000000000..ec0313cf0 --- /dev/null +++ b/lib/projects/__tests__/validateCreateProjectTaskRequest.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it, vi } from "vitest"; +import { NextRequest } from "next/server"; +import { validateCreateProjectTaskRequest } from "@/lib/projects/validateCreateProjectTaskRequest"; + +vi.mock("@/lib/supabase/serverClient", () => ({ default: {} })); +vi.mock("@/lib/projects/requireProjectAccess", () => ({ + requireProjectAccess: vi.fn(), +})); + +const url = "https://api.recoupable.dev/api/projects/x/tasks"; +const post = (body: unknown) => + new NextRequest(url, { + method: "POST", + body: JSON.stringify(body), + headers: { "content-type": "application/json" }, + }); + +describe("validateCreateProjectTaskRequest", () => { + it("rejects a malformed projectId with 400 before the body is read", async () => { + const result = await validateCreateProjectTaskRequest(post({ title: "x" }), "not-a-uuid"); + + expect(result).toMatchObject({ status: 400 }); + await expect((result as Response).json()).resolves.toEqual({ + status: "error", + error: "projectId must be a valid UUID", + }); + }); +}); diff --git a/lib/projects/__tests__/validateUpdateProjectTaskRequest.test.ts b/lib/projects/__tests__/validateUpdateProjectTaskRequest.test.ts new file mode 100644 index 000000000..c026a2d37 --- /dev/null +++ b/lib/projects/__tests__/validateUpdateProjectTaskRequest.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it, vi } from "vitest"; +import { NextRequest } from "next/server"; +import { validateUpdateProjectTaskRequest } from "@/lib/projects/validateUpdateProjectTaskRequest"; + +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"; +const patch = (body: unknown) => + new NextRequest(url, { + method: "PATCH", + body: JSON.stringify(body), + headers: { "content-type": "application/json" }, + }); + +const body = (result: unknown) => (result as Response).json(); + +describe("validateUpdateProjectTaskRequest", () => { + it("rejects a malformed projectId with 400", async () => { + const result = await validateUpdateProjectTaskRequest( + patch({ title: "x" }), + "not-a-uuid", + PROJECT_ID, + ); + + expect(result).toMatchObject({ status: 400 }); + await expect(body(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 validateUpdateProjectTaskRequest( + patch({ title: "x" }), + PROJECT_ID, + "not-a-uuid", + ); + + expect(result).toMatchObject({ status: 400 }); + await expect(body(result)).resolves.toEqual({ + status: "error", + error: "taskId must be a valid UUID", + }); + }); +}); diff --git a/lib/projects/createProjectTaskHandler.ts b/lib/projects/createProjectTaskHandler.ts index c221fd360..233d2ae9f 100644 --- a/lib/projects/createProjectTaskHandler.ts +++ b/lib/projects/createProjectTaskHandler.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 { validateCreateProjectTaskBody } from "@/lib/projects/validateCreateProjectTaskBody"; +import { validateCreateProjectTaskRequest } from "@/lib/projects/validateCreateProjectTaskRequest"; import { insertProjectTask } from "@/lib/supabase/project_tasks/insertProjectTask"; /** @@ -21,20 +20,17 @@ export async function createProjectTaskHandler( request: NextRequest, projectId: string, ): Promise { - const access = await requireProjectAccess(request, projectId); - if (access instanceof NextResponse) return access; - - const body = await request.json().catch(() => null); - const validated = validateCreateProjectTaskBody(body); + const validated = await validateCreateProjectTaskRequest(request, projectId); if (validated instanceof NextResponse) return validated; + const { body } = validated; try { const task = await insertProjectTask({ project_id: projectId, - title: validated.title, - description: validated.description ?? null, - due_date: validated.due_date ?? null, - assignee_account_id: validated.assignee_account_id ?? null, + title: body.title, + description: body.description ?? null, + due_date: body.due_date ?? null, + assignee_account_id: body.assignee_account_id ?? null, }); return NextResponse.json( diff --git a/lib/projects/deleteProjectTaskHandler.ts b/lib/projects/deleteProjectTaskHandler.ts index 9c1e75acc..5bba86ad3 100644 --- a/lib/projects/deleteProjectTaskHandler.ts +++ b/lib/projects/deleteProjectTaskHandler.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 { deleteProjectTask } from "@/lib/supabase/project_tasks/deleteProjectTask"; /** @@ -21,7 +21,7 @@ export async function deleteProjectTaskHandler( 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 { diff --git a/lib/projects/updateProjectTaskHandler.ts b/lib/projects/updateProjectTaskHandler.ts index d09506766..b419051a2 100644 --- a/lib/projects/updateProjectTaskHandler.ts +++ b/lib/projects/updateProjectTaskHandler.ts @@ -2,8 +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 { validateUpdateProjectTaskBody } from "@/lib/projects/validateUpdateProjectTaskBody"; +import { validateUpdateProjectTaskRequest } from "@/lib/projects/validateUpdateProjectTaskRequest"; import { toTaskUpdates } from "@/lib/projects/toTaskUpdates"; import { updateProjectTask } from "@/lib/supabase/project_tasks/updateProjectTask"; @@ -24,15 +23,12 @@ export async function updateProjectTaskHandler( 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 = validateUpdateProjectTaskBody(body); + const validated = await validateUpdateProjectTaskRequest(request, projectId, taskId); if (validated instanceof NextResponse) return validated; + const { accountId, body } = validated; try { - const task = await updateProjectTask(projectId, taskId, toTaskUpdates(validated, access)); + const task = await updateProjectTask(projectId, taskId, toTaskUpdates(body, accountId)); if (!task) return errorResponse("Task not found", 404); return successResponse({ task }); diff --git a/lib/projects/validateCreateProjectTaskRequest.ts b/lib/projects/validateCreateProjectTaskRequest.ts new file mode 100644 index 000000000..d58bea2c9 --- /dev/null +++ b/lib/projects/validateCreateProjectTaskRequest.ts @@ -0,0 +1,36 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; +import { validateProjectRequest } from "@/lib/projects/validateProjectRequest"; +import { + validateCreateProjectTaskBody, + type CreateProjectTaskBody, +} from "@/lib/projects/validateCreateProjectTaskBody"; + +export interface CreateProjectTaskRequest { + accountId: string; + body: CreateProjectTaskBody; +} + +/** + * Everything `POST /api/projects/{projectId}/tasks` requires of a request: a + * well-formed `projectId`, a caller with a collaborator row on it, and a valid + * body — in that order, so an unauthorised caller never learns whether their + * body would have been accepted. + * + * @param request - The incoming request, carrying the Bearer credential. + * @param projectId - The `projectId` path segment, unvalidated. + * @returns The authenticated account and validated body, or the response to + * return instead. + */ +export async function validateCreateProjectTaskRequest( + request: NextRequest, + projectId: string, +): Promise { + const access = await validateProjectRequest(request, projectId); + if (access instanceof NextResponse) return access; + + const body = validateCreateProjectTaskBody(await request.json().catch(() => null)); + if (body instanceof NextResponse) return body; + + return { accountId: access, body }; +} diff --git a/lib/projects/validateUpdateProjectTaskRequest.ts b/lib/projects/validateUpdateProjectTaskRequest.ts new file mode 100644 index 000000000..833b1cbf2 --- /dev/null +++ b/lib/projects/validateUpdateProjectTaskRequest.ts @@ -0,0 +1,41 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; +import { validateProjectTaskRequest } from "@/lib/projects/validateProjectTaskRequest"; +import { + validateUpdateProjectTaskBody, + type UpdateProjectTaskBody, +} from "@/lib/projects/validateUpdateProjectTaskBody"; + +export interface UpdateProjectTaskRequest { + accountId: string; + body: UpdateProjectTaskBody; +} + +/** + * Everything `PATCH /api/projects/{projectId}/tasks/{taskId}` requires: both + * path ids well formed, a caller with a collaborator row on the project, and a + * valid body — in that order. + * + * The id checks matter beyond 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 validateUpdateProjectTaskRequest( + request: NextRequest, + projectId: string, + taskId: string, +): Promise { + const access = await validateProjectTaskRequest(request, projectId, taskId); + if (access instanceof NextResponse) return access; + + const body = validateUpdateProjectTaskBody(await request.json().catch(() => null)); + if (body instanceof NextResponse) return body; + + return { accountId: access, body }; +}