Files
proof-of-work/proof-of-work/app/api/exercises/route.ts
T
Keysat 3f22ef7600
CI / proof-of-work (Next.js app) (push) Has been cancelled
CI / start9/0.4 (StartOS package code) (push) Has been cancelled
v1.1.0:9 — P2 hardening: input-validation 400s, auth rate-limit, XFF anti-spoof, non-root container
P2 batch from the 2026-06-13 full-eval (EVALUATION.md / ROADMAP.md), reviewed by the reviewer agent. App-code + packaging only; no schema or data change, existing /data untouched.

Input validation: malformed JSON bodies, invalid date, and out-of-range or non-numeric pagination on /api/workouts now return 400 instead of 500. New lib/http.ts readJsonBody maps a bad body to a ZodError across the 11 CRUD routes whose catch maps ZodError to 400; me/import and admin/signups guard request.json() in an explicit try/catch.

Rate limiting: POST /api/auth now shares the UI login server action's per-IP 10-per-15min cap and returns 429 + Retry-After. clientIpFromHeaders reads the rightmost (trusted-proxy-appended) X-Forwarded-For entry instead of the spoofable leftmost.

Container: drops root. The entrypoint prepares /data as root, chowns it to nextjs, then exec su-exec nextjs:nodejs node server.js (su-exec added to the runner image). The container drop needs live sideload verification.
2026-06-13 00:03:47 -05:00

126 lines
3.3 KiB
TypeScript

import { getCurrentUser } from "@/lib/auth";
import { getExercises, createExercise } from "@/lib/db/exercises";
import { prisma } from "@/lib/prisma";
import { readJsonBody } from "@/lib/http";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
const CreateExerciseSchema = z.object({
name: z.string().min(1, "Exercise name is required"),
type: z.string().min(1),
muscleGroups: z.array(z.string()).default([]),
description: z.string().optional(),
inputFields: z.array(z.string().min(1)).optional(),
defaultWeightUnit: z.string().nullable().optional(),
});
/**
* GET /api/exercises
*/
export async function GET(request: NextRequest) {
try {
const user = await getCurrentUser();
if (!user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const query = searchParams.get("q");
let exercises;
if (query) {
exercises = await prisma.exercise.findMany({
where: {
userId: user.id,
name: { contains: query },
},
orderBy: { name: "asc" },
});
} else {
exercises = await getExercises(user.id);
}
return NextResponse.json(exercises);
} catch (error) {
console.error("GET /api/exercises error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
/**
* POST /api/exercises
*/
export async function POST(request: NextRequest) {
try {
const user = await getCurrentUser();
if (!user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const body = await readJsonBody(request);
const validated = CreateExerciseSchema.parse(body);
const existing = await prisma.exercise.findUnique({
where: {
userId_name: {
userId: user.id,
name: validated.name,
},
},
});
if (existing) {
return NextResponse.json(
{ error: "Exercise already exists" },
{ status: 400 }
);
}
// Determine default inputFields based on type
let inputFields = validated.inputFields;
if (!inputFields) {
if (validated.type === "cardio") {
inputFields = ["sets", "duration", "calories"];
} else {
inputFields = ["sets", "reps", "weight"];
}
}
// Kettlebell defaults to kg
let defaultWeightUnit = validated.defaultWeightUnit;
if (defaultWeightUnit === undefined && validated.type === "kettlebell") {
defaultWeightUnit = "kg";
}
const exercise = await createExercise({
userId: user.id,
name: validated.name,
type: validated.type,
description: validated.description,
muscleGroups: JSON.stringify(validated.muscleGroups),
inputFields: JSON.stringify(inputFields),
defaultWeightUnit: defaultWeightUnit || null,
isCustom: true,
});
return NextResponse.json(exercise, { status: 201 });
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: "Validation error", details: error.errors },
{ status: 400 }
);
}
console.error("POST /api/exercises error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}