push to maple-street
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
import { z } from "zod";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { rotateCalendarFeedToken } from "@/db/volunteer";
|
||||
import { requestOrigin } from "@/auth/magic-link";
|
||||
import { jsonResponse, errorResponse } from "@/lib/http";
|
||||
|
||||
const bodySchema = z.object({ action: z.literal("rotate") });
|
||||
|
||||
/** POST /api/account/calendar-feed { action: "rotate" } */
|
||||
export async function POST(req: Request) {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const parsed = bodySchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) return errorResponse(400, "invalid action");
|
||||
|
||||
const token = await rotateCalendarFeedToken(gate.id);
|
||||
const origin = requestOrigin(req as Request & { headers: Headers });
|
||||
return jsonResponse({ token, url: `${origin}/api/calendar/${token}` });
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import {
|
||||
hashPassword,
|
||||
normalizeUsername,
|
||||
validatePassword,
|
||||
validateUsername,
|
||||
verifyPassword,
|
||||
} from "@/auth/password";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import {
|
||||
credentialTaken,
|
||||
getUserSecurity,
|
||||
updateUserCredentials,
|
||||
} from "@/db/users";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
const json = (payload: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS });
|
||||
const bad = (message: string) => json({ error: message }, 400);
|
||||
const conflict = (message: string) => json({ error: message }, 409);
|
||||
|
||||
const bodySchema = z.object({
|
||||
username: z.string().min(1).max(100).optional(),
|
||||
currentPassword: z.string().max(200).optional(),
|
||||
newPassword: z.string().min(1).max(200),
|
||||
});
|
||||
|
||||
/**
|
||||
* Set or change the signed-in person's password.
|
||||
*
|
||||
* A magic-link session is enough for the first-time setup, where no password
|
||||
* exists yet. Once one exists, the current password is required so a borrowed
|
||||
* browser session cannot silently lock the owner out.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return bad("A JSON body is required.");
|
||||
}
|
||||
const parsed = bodySchema.safeParse(body);
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
|
||||
const account = await getUserSecurity(gate.id);
|
||||
if (!account) return json({ error: "unknown user" }, 404);
|
||||
|
||||
if (account.passwordHash) {
|
||||
if (!parsed.data.currentPassword) {
|
||||
return bad("Enter your current password.");
|
||||
}
|
||||
if (!(await verifyPassword(parsed.data.currentPassword, account.passwordHash))) {
|
||||
return bad("Your current password is incorrect.");
|
||||
}
|
||||
}
|
||||
|
||||
const passwordError = validatePassword(parsed.data.newPassword);
|
||||
if (passwordError) return bad(passwordError);
|
||||
|
||||
const nextUsername = parsed.data.username
|
||||
? normalizeUsername(parsed.data.username)
|
||||
: account.username;
|
||||
if (parsed.data.username) {
|
||||
const usernameError = validateUsername(nextUsername);
|
||||
if (usernameError) return bad(usernameError);
|
||||
if (await credentialTaken(nextUsername, gate.id)) {
|
||||
return conflict("That username is already in use.");
|
||||
}
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(parsed.data.newPassword);
|
||||
const updated = await updateUserCredentials(gate.id, {
|
||||
username: nextUsername,
|
||||
passwordHash,
|
||||
});
|
||||
if (!updated) return json({ error: "unknown user" }, 404);
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: account.passwordHash
|
||||
? "user.password_changed"
|
||||
: "user.password_set",
|
||||
entityType: "user",
|
||||
entityId: gate.id,
|
||||
after: { username: updated.username, passwordSet: true },
|
||||
});
|
||||
|
||||
return json({ ok: true, username: updated.username, passwordSet: true });
|
||||
};
|
||||
@@ -0,0 +1,90 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser, gateSession } from "@/auth/api";
|
||||
import { hasPermission } from "@/auth/permissions";
|
||||
import {
|
||||
createAnnouncement,
|
||||
deleteAnnouncement,
|
||||
listAnnouncements,
|
||||
updateAnnouncement,
|
||||
} from "@/db/announcements";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
|
||||
const createSchema = z.object({
|
||||
title: z.string().trim().min(1).max(200),
|
||||
body: z.string().max(20_000).optional(),
|
||||
published: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const patchSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
title: z.string().trim().min(1).max(200).optional(),
|
||||
body: z.string().max(20_000).optional(),
|
||||
published: z.boolean().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Announcements. Any signed-in user reads published posts; authors
|
||||
* (`content.author` = admin/coordinator) also see drafts and can write.
|
||||
*
|
||||
* GET -> { announcements }
|
||||
* POST -> { announcement }
|
||||
* PATCH -> { announcement } edit or publish/unpublish
|
||||
* DELETE ?id= -> { ok }
|
||||
*/
|
||||
export const GET = async () => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const canAuthor = hasPermission(gate.systemRole, "content.author");
|
||||
return jsonResponse({
|
||||
announcements: await listAnnouncements({
|
||||
includeUnpublished: canAuthor,
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("content.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const parsed = createSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid post");
|
||||
}
|
||||
|
||||
const announcement = await createAnnouncement({
|
||||
title: parsed.data.title,
|
||||
body: parsed.data.body ?? "",
|
||||
published: parsed.data.published ?? false,
|
||||
createdBy: gate.id,
|
||||
});
|
||||
return jsonResponse({ announcement }, 201);
|
||||
};
|
||||
|
||||
export const PATCH = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("content.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const parsed = patchSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid post");
|
||||
}
|
||||
|
||||
const { id, ...patch } = parsed.data;
|
||||
const announcement = await updateAnnouncement(id, patch);
|
||||
if (!announcement) return errorResponse(404, "unknown announcement");
|
||||
return jsonResponse({ announcement });
|
||||
};
|
||||
|
||||
export const DELETE = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("content.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const id = req.nextUrl.searchParams.get("id");
|
||||
if (!id) return errorResponse(400, "an id is required");
|
||||
|
||||
const deleted = await deleteAnnouncement(id);
|
||||
if (!deleted) return errorResponse(404, "unknown announcement");
|
||||
return jsonResponse({ ok: true });
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
import { z } from "zod";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { RespondError, respondToAssignment } from "@/db/respond";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
|
||||
const bodySchema = z.object({ action: z.enum(["confirm", "decline"]) });
|
||||
|
||||
function errorStatus(code: RespondError["code"]): number {
|
||||
switch (code) {
|
||||
case "unknown_assignment":
|
||||
return 404;
|
||||
case "wrong_volunteer":
|
||||
return 403;
|
||||
case "not_actionable":
|
||||
case "already_used":
|
||||
return 409;
|
||||
}
|
||||
}
|
||||
|
||||
/** POST /api/assignments/:id/respond { action: "confirm" | "decline" } */
|
||||
export async function POST(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const parsed = bodySchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) return errorResponse(400, "invalid action");
|
||||
|
||||
const { id } = await params;
|
||||
try {
|
||||
const result = await respondToAssignment({
|
||||
assignmentId: id,
|
||||
userId: gate.id,
|
||||
action: parsed.data.action,
|
||||
via: "app",
|
||||
});
|
||||
return jsonResponse({ ok: true, ...result });
|
||||
} catch (error) {
|
||||
if (error instanceof RespondError) {
|
||||
return errorResponse(errorStatus(error.code), error.message, error.code);
|
||||
}
|
||||
console.error("[assignment-respond] ERROR", error);
|
||||
return errorResponse(500, "failed to update the assignment");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { rankedCandidatesForSlot } from "@/db/rankedCandidates";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
|
||||
/** GET /api/assignments/candidates?slotId=... — ranked eligible/excluded list. */
|
||||
export async function GET(req: Request) {
|
||||
const gate = await gateOrUser("schedule.publish");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const slotId = new URL(req.url).searchParams.get("slotId")?.trim();
|
||||
if (!slotId) return errorResponse(400, "a slotId is required");
|
||||
|
||||
const result = await rankedCandidatesForSlot(slotId);
|
||||
if (!result) return errorResponse(404, "slot not found");
|
||||
return jsonResponse(result);
|
||||
}
|
||||
@@ -1,14 +1,25 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { auth } from "@/auth/config";
|
||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import { db } from "@/db";
|
||||
import { assignments, slots } from "@/db/schema";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import { activeAssignmentInInstance } from "@/db/assignments";
|
||||
import { assignHardConflicts } from "@/domain/assign";
|
||||
import {
|
||||
assignments,
|
||||
auditLog,
|
||||
serviceInstances,
|
||||
slots,
|
||||
} from "@/db/schema";
|
||||
import { auditRow } from "@/db/audit";
|
||||
import {
|
||||
AssignFactError,
|
||||
resolveAssignFacts,
|
||||
} from "@/db/assignments";
|
||||
import { cancelAssignmentNotifications } from "@/db/outbox";
|
||||
import { enqueuePublishNotifications } from "@/db/outbox";
|
||||
import { enqueueRemindersForInstance } from "@/db/reminders";
|
||||
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
@@ -19,6 +30,8 @@ const bodySchema = z.object({
|
||||
userId: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
const ACTIVE_STATUSES = ["proposed", "confirmed", "completed"] as const;
|
||||
|
||||
/** Walk an error's cause chain to its SQLSTATE (23505 = unique, 23503 = FK). */
|
||||
function sqlStateCode(err: unknown): string | undefined {
|
||||
let node = err as { code?: string; cause?: unknown } | null;
|
||||
@@ -30,18 +43,21 @@ function sqlStateCode(err: unknown): string | undefined {
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign / clear an assignment (unit D8).
|
||||
* Assign / clear an assignment (units D8 + D5/D9 integration).
|
||||
*
|
||||
* POST { action: "assign"|"clear", slotId, userId? }
|
||||
*
|
||||
* - assign -> creates a `proposed`/`manual` assignment after the rule-1
|
||||
* duplicate-in-instance gate; writes an `assignment.created`
|
||||
* audit row.
|
||||
* - clear -> deletes the active assignment on the slot; writes an
|
||||
* `assignment.cleared` audit row.
|
||||
* - assign -> runs the full conflict engine (roster, one-per-instance,
|
||||
* core-skill level, shadow pairing, blackout, cap, back-to-back)
|
||||
* and rejects on any HARD conflict. Soft conflicts are returned
|
||||
* as warnings. Creates `proposed`/`manual`, syncs the slot
|
||||
* status, audits, and re-enqueues mail when the week is already
|
||||
* published.
|
||||
* - clear -> cancels that assignment's pending mail BEFORE deleting it (so
|
||||
* a removed seat cannot still send "you're serving"), reopens the
|
||||
* slot, audits.
|
||||
*
|
||||
* Guarded by `schedule.publish` (coordinator + admin). Hard conflicts reject
|
||||
* 409; a DB unique violation on the slot rejects 409 (rule 2).
|
||||
* Guarded by `schedule.publish` (coordinator + admin).
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
let action: string | undefined;
|
||||
@@ -70,7 +86,10 @@ export const POST = async (req: NextRequest) => {
|
||||
|
||||
try {
|
||||
const session = await auth();
|
||||
const user = (session?.user as { id: string; systemRole: SystemRole } | null | undefined);
|
||||
const user = session?.user as
|
||||
| { id: string; systemRole: SystemRole }
|
||||
| null
|
||||
| undefined;
|
||||
if (!user) {
|
||||
return new Response(JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), {
|
||||
status: 401,
|
||||
@@ -81,32 +100,45 @@ export const POST = async (req: NextRequest) => {
|
||||
const actorId = user.id;
|
||||
|
||||
if (parsed.data.action === "clear") {
|
||||
const active = await db
|
||||
.select({ id: assignments.id })
|
||||
const [active] = await db
|
||||
.select({
|
||||
id: assignments.id,
|
||||
slotId: assignments.slotId,
|
||||
})
|
||||
.from(assignments)
|
||||
.where(
|
||||
and(
|
||||
eq(assignments.slotId, parsed.data.slotId),
|
||||
sql`${assignments.status} IN ('proposed','confirmed','completed')`,
|
||||
inArray(assignments.status, [...ACTIVE_STATUSES]),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (active.length === 0) {
|
||||
if (!active) {
|
||||
return new Response(JSON.stringify({ error: "no active assignment on this slot" }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
await db.delete(assignments).where(eq(assignments.id, active[0].id));
|
||||
await writeAudit(db, {
|
||||
actorId,
|
||||
action: "assignment.cleared",
|
||||
entityType: "assignment",
|
||||
entityId: active[0].id,
|
||||
after: { slotId: parsed.data.slotId },
|
||||
await db.transaction(async (tx) => {
|
||||
await cancelAssignmentNotifications(active.id, new Date(), tx);
|
||||
await tx.delete(assignments).where(eq(assignments.id, active.id));
|
||||
await tx
|
||||
.update(slots)
|
||||
.set({ status: "open" })
|
||||
.where(eq(slots.id, active.slotId));
|
||||
await tx.insert(auditLog).values(
|
||||
auditRow({
|
||||
actorId,
|
||||
action: "assignment.cleared",
|
||||
entityType: "assignment",
|
||||
entityId: active.id,
|
||||
after: { slotId: parsed.data.slotId },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return new Response(JSON.stringify({ ok: true }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
@@ -114,70 +146,102 @@ export const POST = async (req: NextRequest) => {
|
||||
}
|
||||
|
||||
// assign
|
||||
if (!parsed.data.userId) {
|
||||
const assignUserId = parsed.data.userId;
|
||||
if (!assignUserId) {
|
||||
return new Response(JSON.stringify({ error: "a userId is required to assign" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
const slotRows = await db
|
||||
.select({ id: slots.id, serviceInstanceId: slots.serviceInstanceId })
|
||||
let facts;
|
||||
try {
|
||||
facts = await resolveAssignFacts({
|
||||
userId: assignUserId,
|
||||
slotId: parsed.data.slotId,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AssignFactError) {
|
||||
const status = e.code === "unknown_slot" || e.code === "unknown_user" ? 404 : 400;
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
const conflicts = classifyConflicts(facts);
|
||||
const hard = hardConflicts(conflicts);
|
||||
if (hard.length > 0) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: hard.map((conflict) => conflict.message).join(" "),
|
||||
code: hard[0].code,
|
||||
conflicts: hard,
|
||||
}),
|
||||
{ status: 409, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
|
||||
const [instance] = await db
|
||||
.select({
|
||||
id: serviceInstances.id,
|
||||
status: serviceInstances.status,
|
||||
})
|
||||
.from(slots)
|
||||
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.where(eq(slots.id, parsed.data.slotId))
|
||||
.limit(1);
|
||||
if (slotRows.length === 0) {
|
||||
return new Response(JSON.stringify({ error: "unknown slot" }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const instanceId = slotRows[0].serviceInstanceId;
|
||||
if (!instanceId) {
|
||||
return new Response(JSON.stringify({ error: "slot is not attached to a service instance" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
const existing = await activeAssignmentInInstance(db, {
|
||||
userId: parsed.data.userId,
|
||||
instanceId,
|
||||
});
|
||||
const conflicts = assignHardConflicts({ alreadyAssignedInInstance: existing != null });
|
||||
if (conflicts.length > 0) {
|
||||
return new Response(JSON.stringify({ error: conflicts[0].message, code: conflicts[0].code }), {
|
||||
status: 409,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
const result = await db
|
||||
.insert(assignments)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
const assignmentId = uuidv7();
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.insert(assignments).values({
|
||||
id: assignmentId,
|
||||
slotId: parsed.data.slotId,
|
||||
userId: parsed.data.userId,
|
||||
userId: assignUserId,
|
||||
status: "proposed",
|
||||
source: "manual",
|
||||
assignedBy: actorId,
|
||||
assignedAt: new Date(),
|
||||
})
|
||||
.returning({ id: assignments.id, status: assignments.status });
|
||||
});
|
||||
await tx
|
||||
.update(slots)
|
||||
.set({ status: "proposed" })
|
||||
.where(eq(slots.id, parsed.data.slotId));
|
||||
await tx.insert(auditLog).values(
|
||||
auditRow({
|
||||
actorId,
|
||||
action: "assignment.created",
|
||||
entityType: "assignment",
|
||||
entityId: assignmentId,
|
||||
before: { slotId: parsed.data.slotId },
|
||||
after: {
|
||||
slotId: parsed.data.slotId,
|
||||
userId: assignUserId,
|
||||
status: "proposed",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId,
|
||||
action: "assignment.created",
|
||||
entityType: "assignment",
|
||||
entityId: result[0].id,
|
||||
before: { slotId: parsed.data.slotId },
|
||||
after: { slotId: parsed.data.slotId, userId: parsed.data.userId, status: "proposed" },
|
||||
// A published week's mail is written at publish time; a seat added later
|
||||
// would otherwise never be announced. Both enqueues are idempotent on
|
||||
// dedupe_key, so existing rows are untouched.
|
||||
if (instance?.status === "published") {
|
||||
await enqueuePublishNotifications(tx, instance.id, { now: new Date() });
|
||||
await enqueueRemindersForInstance(tx, instance.id, { now: new Date() });
|
||||
}
|
||||
});
|
||||
|
||||
return new Response(JSON.stringify({ ok: true, id: result[0].id, status: result[0].status }), {
|
||||
status: 201,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
ok: true,
|
||||
id: assignmentId,
|
||||
status: "proposed",
|
||||
warnings: conflicts.filter((conflict) => conflict.severity === "soft"),
|
||||
}),
|
||||
{ status: 201, headers: JSON_HEADERS },
|
||||
);
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
@@ -191,6 +255,7 @@ export const POST = async (req: NextRequest) => {
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
console.error("[assignments] ERROR", e);
|
||||
return new Response(JSON.stringify({ error: "failed to assign" }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
consumeMagicToken,
|
||||
getUser,
|
||||
verifyPasswordResetToken,
|
||||
} from "@/auth/magic-link";
|
||||
import { hashPassword, validatePassword } from "@/auth/password";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import { updateUserCredentials } from "@/db/users";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
const json = (payload: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS });
|
||||
|
||||
const bodySchema = z.object({
|
||||
token: z.string().min(1),
|
||||
newPassword: z.string().min(1).max(200),
|
||||
});
|
||||
|
||||
/**
|
||||
* Complete an admin-issued password reset. The token is single-use and is
|
||||
* consumed before the new hash is written, so replaying the same link cannot
|
||||
* reset the account twice.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return json({ error: "A JSON body is required." }, 400);
|
||||
}
|
||||
const parsed = bodySchema.safeParse(body);
|
||||
if (!parsed.success) return json({ error: parsed.error.message }, 400);
|
||||
|
||||
const passwordError = validatePassword(parsed.data.newPassword);
|
||||
if (passwordError) return json({ error: passwordError }, 400);
|
||||
|
||||
const payload = await verifyPasswordResetToken(parsed.data.token);
|
||||
if (!payload) {
|
||||
return json({ error: "This reset link is invalid or has expired." }, 400);
|
||||
}
|
||||
|
||||
const user = await getUser(payload.email);
|
||||
if (!user || user.status !== "active" || user.deactivatedAt) {
|
||||
return json({ error: "This account cannot reset its password." }, 400);
|
||||
}
|
||||
|
||||
const consumed = await consumeMagicToken(payload);
|
||||
if (!consumed) {
|
||||
return json({ error: "This reset link has already been used." }, 409);
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(parsed.data.newPassword);
|
||||
const updated = await updateUserCredentials(user.id, { passwordHash });
|
||||
if (!updated) return json({ error: "unknown user" }, 404);
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId: user.id,
|
||||
action: "user.password_reset",
|
||||
entityType: "user",
|
||||
entityId: user.id,
|
||||
after: { passwordSet: true },
|
||||
});
|
||||
|
||||
return json({ ok: true });
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import {
|
||||
calendarFeedForUser,
|
||||
getCalendarFeedOwner,
|
||||
} from "@/db/volunteer";
|
||||
import { buildCalendar } from "@/lib/ics";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Public, bearer-by-URL calendar feed. The token is long and random; it is not
|
||||
* an account session and grants read-only access to that person's assignments.
|
||||
*/
|
||||
export async function GET(
|
||||
_req: Request,
|
||||
{ params }: { params: Promise<{ token: string }> },
|
||||
) {
|
||||
const { token } = await params;
|
||||
if (!token || token.length < 20 || token.length > 128) {
|
||||
return new Response("Calendar not found", { status: 404 });
|
||||
}
|
||||
|
||||
const owner = await getCalendarFeedOwner(token);
|
||||
if (!owner) return new Response("Calendar not found", { status: 404 });
|
||||
|
||||
const events = await calendarFeedForUser(owner.id);
|
||||
const body = buildCalendar({
|
||||
calendarName: `${owner.displayName} — Media Team`,
|
||||
events,
|
||||
});
|
||||
|
||||
return new Response(body, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "text/calendar; charset=utf-8",
|
||||
"content-disposition": 'inline; filename="media-team.ics"',
|
||||
"cache-control": "private, no-store, max-age=0",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { clientIp, gateOrUser } from "@/auth/api";
|
||||
import { rateLimit } from "@/lib/rate-limit";
|
||||
import {
|
||||
IntakeError,
|
||||
createCoverageIntake,
|
||||
declineCoverageIntake,
|
||||
scheduleCoverageIntake,
|
||||
} from "@/db/intake";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
const json = (body: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(body), { status, headers: JSON_HEADERS });
|
||||
|
||||
const intakeSchema = z.object({
|
||||
requesterName: z.string().min(2).max(120),
|
||||
requesterEmail: z.string().email().max(200),
|
||||
requesterPhone: z.string().max(40).nullable().optional(),
|
||||
ministry: z.string().max(120).nullable().optional(),
|
||||
title: z.string().min(3).max(200),
|
||||
eventType: z.string().max(60).optional(),
|
||||
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||
startTime: z.string().regex(/^\d{2}:\d{2}$/),
|
||||
endTime: z.string().regex(/^\d{2}:\d{2}$/).nullable().optional(),
|
||||
location: z.string().max(200).nullable().optional(),
|
||||
description: z.string().max(2000).nullable().optional(),
|
||||
});
|
||||
|
||||
const reviewSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
action: z.enum(["schedule", "decline"]),
|
||||
});
|
||||
|
||||
async function body(req: NextRequest): Promise<unknown> {
|
||||
try {
|
||||
return await req.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Public submission endpoint. Rate-limited per IP; the response never reveals
|
||||
* whether an identical request already exists.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const limit = rateLimit(`coverage-intake:${clientIp(req)}`, 5, 60 * 60 * 1000);
|
||||
if (!limit.ok) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Too many requests. Please try again later." }),
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
...JSON_HEADERS,
|
||||
"retry-after": String(limit.retryAfterSeconds),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const parsed = intakeSchema.safeParse(await body(req));
|
||||
if (!parsed.success) {
|
||||
return json({ error: parsed.error.issues[0]?.message ?? "Invalid request" }, 400);
|
||||
}
|
||||
|
||||
try {
|
||||
await createCoverageIntake(parsed.data);
|
||||
return json({ ok: true }, 201);
|
||||
} catch (err) {
|
||||
if (err instanceof IntakeError) return json({ error: err.message }, err.status);
|
||||
console.error("[coverage-intake] submit failed", err);
|
||||
return json({ error: "Could not submit the request." }, 500);
|
||||
}
|
||||
};
|
||||
|
||||
/** Coordinator review: turn an accepted request into an event, or decline it. */
|
||||
export const PATCH = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("schedule.publish");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const parsed = reviewSchema.safeParse(await body(req));
|
||||
if (!parsed.success) return json({ error: parsed.error.message }, 400);
|
||||
|
||||
try {
|
||||
if (parsed.data.action === "schedule") {
|
||||
const row = await scheduleCoverageIntake({
|
||||
id: parsed.data.id,
|
||||
actorId: gate.id,
|
||||
});
|
||||
return json({ ok: true, ...row });
|
||||
}
|
||||
await declineCoverageIntake({ id: parsed.data.id, actorId: gate.id });
|
||||
return json({ ok: true });
|
||||
} catch (err) {
|
||||
if (err instanceof IntakeError) return json({ error: err.message }, err.status);
|
||||
console.error("[coverage-intake] review failed", err);
|
||||
return json({ error: "Could not review the request." }, 500);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser, gateSession } from "@/auth/api";
|
||||
import {
|
||||
CoverageError,
|
||||
createCoverageRequest,
|
||||
resolveCoverageRequest,
|
||||
} from "@/db/coverage";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
const json = (body: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(body), { status, headers: JSON_HEADERS });
|
||||
|
||||
const createSchema = z.object({
|
||||
assignmentId: z.string().min(1),
|
||||
reason: z.string().max(500).nullable().optional(),
|
||||
});
|
||||
|
||||
const resolveSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
action: z.enum(["approve", "decline", "cancel"]),
|
||||
replacementUserId: z.string().min(1).nullable().optional(),
|
||||
});
|
||||
|
||||
async function body(req: NextRequest): Promise<unknown> {
|
||||
try {
|
||||
return await req.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** A volunteer asks for coverage on their own assignment. */
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const parsed = createSchema.safeParse(await body(req));
|
||||
if (!parsed.success) return json({ error: parsed.error.message }, 400);
|
||||
|
||||
try {
|
||||
const row = await createCoverageRequest({
|
||||
assignmentId: parsed.data.assignmentId,
|
||||
userId: gate.id,
|
||||
reason: parsed.data.reason ?? null,
|
||||
});
|
||||
return json({ ok: true, ...row }, 201);
|
||||
} catch (err) {
|
||||
if (err instanceof CoverageError) {
|
||||
return json({ error: err.message }, err.status);
|
||||
}
|
||||
console.error("[coverage] create failed", err);
|
||||
return json({ error: "could not create the coverage request" }, 500);
|
||||
}
|
||||
};
|
||||
|
||||
/** A coordinator approves (with or without a replacement) or declines. */
|
||||
export const PATCH = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("schedule.publish");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const parsed = resolveSchema.safeParse(await body(req));
|
||||
if (!parsed.success) return json({ error: parsed.error.message }, 400);
|
||||
|
||||
try {
|
||||
const result = await resolveCoverageRequest({
|
||||
requestId: parsed.data.id,
|
||||
actorId: gate.id,
|
||||
action: parsed.data.action,
|
||||
replacementUserId: parsed.data.replacementUserId ?? null,
|
||||
});
|
||||
return json({ ok: true, ...result });
|
||||
} catch (err) {
|
||||
if (err instanceof CoverageError) {
|
||||
return json({ error: err.message }, err.status);
|
||||
}
|
||||
console.error("[coverage] resolve failed", err);
|
||||
return json({ error: "could not update the coverage request" }, 500);
|
||||
}
|
||||
};
|
||||
@@ -1,6 +1,10 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { approveUser } from "@/auth/invites";
|
||||
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link";
|
||||
import { getUserById } from "@/db/users";
|
||||
import { sendWelcomeEmail } from "@/lib/welcome-email";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
const bodySchema = z.object({
|
||||
@@ -12,6 +16,9 @@ const bodySchema = z.object({
|
||||
* Approve a pending user -> active. POST { userId, approvedBy? }.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("users.manage");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
let userId: string | undefined;
|
||||
let approvedBy: string | undefined;
|
||||
try {
|
||||
@@ -33,12 +40,26 @@ export const POST = async (req: NextRequest) => {
|
||||
try {
|
||||
const user = await approveUser({
|
||||
userId: parsed.data.userId,
|
||||
approvedBy: parsed.data.approvedBy ?? "admin",
|
||||
});
|
||||
return new Response(JSON.stringify({ ok: true, id: user.id, status: user.status }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
// Server-owned: a caller cannot attribute the approval to someone else.
|
||||
approvedBy: gate.id,
|
||||
});
|
||||
|
||||
// The account can now sign in, so this is the moment to send its details.
|
||||
const approved = await getUserById(user.id);
|
||||
let welcome: { delivered: boolean; transport: string | null } | null = null;
|
||||
if (approved) {
|
||||
const token = await signMagicToken(approved.email);
|
||||
const origin = requestOrigin(req) || APP_ORIGIN;
|
||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||
token,
|
||||
)}&email=${encodeURIComponent(approved.email)}`;
|
||||
welcome = await sendWelcomeEmail(approved, url);
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ ok: true, id: user.id, status: user.status, welcome }),
|
||||
{ status: 200, headers: JSON_HEADERS },
|
||||
);
|
||||
} catch {
|
||||
return new Response(JSON.stringify({ error: "failed to approve user" }), {
|
||||
status: 500,
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { constants } from "node:fs";
|
||||
import {
|
||||
access,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
rm,
|
||||
stat,
|
||||
} from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import { getStorageSettings } from "@/db/storage-settings";
|
||||
import {
|
||||
BACKUP_DATABASE_FILE,
|
||||
BACKUP_MANIFEST_FILE,
|
||||
assertRegularFile,
|
||||
type BackupManifest,
|
||||
backupManifestSchema,
|
||||
backupTempRoot,
|
||||
extractZip,
|
||||
listZipEntries,
|
||||
replaceDirectoryContents,
|
||||
restoreDatabaseFromFile,
|
||||
sha256File,
|
||||
validateBackupEntries,
|
||||
writeRequestBodyToFile,
|
||||
} from "@/lib/backup";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
import { UPLOAD_DIR } from "@/lib/uploads";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* POST /api/dev/backup/restore
|
||||
*
|
||||
* Body: the backup ZIP bytes. Header: `x-restore-confirm: RESTORE`.
|
||||
*
|
||||
* The ZIP is validated before anything is changed. The database is loaded with
|
||||
* `psql --single-transaction`, so a bad dump rolls back. Uploads and the archive
|
||||
* are only replaced when the manifest says they were included. The signed-in
|
||||
* admin should keep the same NEXTAUTH_SECRET if they need to retain encrypted
|
||||
* settings such as the Gmail app password.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("admin.settings");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
if (req.headers.get("x-restore-confirm") !== "RESTORE") {
|
||||
return errorResponse(
|
||||
400,
|
||||
'Type "RESTORE" in the confirmation field before restoring.',
|
||||
);
|
||||
}
|
||||
if (!req.body) return errorResponse(400, "A backup ZIP is required.");
|
||||
|
||||
const temp = await mkdtemp(path.join(backupTempRoot(), "glenloch-restore-"));
|
||||
const zipPath = path.join(temp, "backup.zip");
|
||||
const extractDir = path.join(temp, "unpacked");
|
||||
let databaseRestored = false;
|
||||
|
||||
try {
|
||||
await writeRequestBodyToFile(req.body, zipPath);
|
||||
const zipInfo = await stat(zipPath);
|
||||
if (!zipInfo.isFile() || zipInfo.size === 0) {
|
||||
return errorResponse(400, "The uploaded backup is empty.");
|
||||
}
|
||||
|
||||
const entries = await listZipEntries(zipPath);
|
||||
const entriesCheck = validateBackupEntries(entries);
|
||||
if (!entriesCheck.ok) {
|
||||
return errorResponse(400, entriesCheck.error);
|
||||
}
|
||||
|
||||
await mkdir(extractDir, { recursive: true });
|
||||
await extractZip(zipPath, extractDir);
|
||||
|
||||
const manifestPath = path.join(extractDir, BACKUP_MANIFEST_FILE);
|
||||
const dumpPath = path.join(extractDir, BACKUP_DATABASE_FILE);
|
||||
await assertRegularFile(manifestPath);
|
||||
await assertRegularFile(dumpPath);
|
||||
|
||||
let manifest: BackupManifest;
|
||||
try {
|
||||
manifest = backupManifestSchema.parse(
|
||||
JSON.parse(await readFile(manifestPath, "utf8")),
|
||||
);
|
||||
} catch (error) {
|
||||
const detail =
|
||||
error instanceof z.ZodError
|
||||
? error.issues[0]?.message ?? "invalid manifest"
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: "invalid manifest";
|
||||
return errorResponse(400, `Invalid backup manifest: ${detail}`);
|
||||
}
|
||||
|
||||
const dumpInfo = await stat(dumpPath);
|
||||
if (dumpInfo.size !== manifest.database.bytes) {
|
||||
return errorResponse(
|
||||
400,
|
||||
"The database dump size does not match the backup manifest.",
|
||||
);
|
||||
}
|
||||
const checksum = await sha256File(dumpPath);
|
||||
if (checksum !== manifest.database.sha256) {
|
||||
return errorResponse(
|
||||
400,
|
||||
"The database dump checksum does not match the backup manifest.",
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the current archive destination before the database is replaced;
|
||||
// the restored app_settings may point at a path that is not mounted here.
|
||||
const storage = await getStorageSettings();
|
||||
if (manifest.includes.archive) {
|
||||
const archiveRoot = path.parse(storage.archivePath).root;
|
||||
if (
|
||||
!path.isAbsolute(storage.archivePath) ||
|
||||
path.resolve(storage.archivePath) === archiveRoot
|
||||
) {
|
||||
return errorResponse(
|
||||
400,
|
||||
"This backup contains an archive, but the current archive path is not safe. Fix it in Settings first.",
|
||||
);
|
||||
}
|
||||
await mkdir(storage.archivePath, { recursive: true });
|
||||
await access(storage.archivePath, constants.W_OK);
|
||||
}
|
||||
if (manifest.includes.uploads) {
|
||||
await mkdir(UPLOAD_DIR, { recursive: true });
|
||||
await access(UPLOAD_DIR, constants.W_OK);
|
||||
}
|
||||
|
||||
await restoreDatabaseFromFile(dumpPath);
|
||||
databaseRestored = true;
|
||||
|
||||
if (manifest.includes.uploads) {
|
||||
const source = path.join(extractDir, "uploads");
|
||||
await mkdir(source, { recursive: true });
|
||||
await replaceDirectoryContents(source, UPLOAD_DIR);
|
||||
}
|
||||
if (manifest.includes.archive) {
|
||||
const source = path.join(extractDir, "archive");
|
||||
await mkdir(source, { recursive: true });
|
||||
await replaceDirectoryContents(source, storage.archivePath);
|
||||
}
|
||||
|
||||
try {
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: "backup.restored",
|
||||
entityType: "backup",
|
||||
after: {
|
||||
manifestCreatedAt: manifest.createdAt,
|
||||
appVersion: manifest.appVersion,
|
||||
databaseBytes: manifest.database.bytes,
|
||||
includes: manifest.includes,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
// The restore already succeeded; do not turn an audit failure into one.
|
||||
console.error("backup restore: could not write audit row", error);
|
||||
}
|
||||
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
restored: {
|
||||
createdAt: manifest.createdAt,
|
||||
appVersion: manifest.appVersion,
|
||||
databaseBytes: manifest.database.bytes,
|
||||
uploads: manifest.includes.uploads,
|
||||
archive: manifest.includes.archive,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("backup restore failed", error);
|
||||
const detail =
|
||||
error instanceof Error ? error.message : "restore could not be completed";
|
||||
return errorResponse(
|
||||
500,
|
||||
databaseRestored
|
||||
? `The database was restored, but the files could not be replaced: ${detail}`
|
||||
: detail,
|
||||
);
|
||||
} finally {
|
||||
await rm(temp, { recursive: true, force: true }).catch(() => undefined);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,143 @@
|
||||
import { ZipArchive } from "archiver";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { PassThrough, Readable } from "node:stream";
|
||||
import path from "node:path";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import { getStorageSettings } from "@/db/storage-settings";
|
||||
import {
|
||||
BACKUP_FORMAT,
|
||||
BACKUP_FORMAT_VERSION,
|
||||
BACKUP_DATABASE_FILE,
|
||||
BACKUP_MANIFEST_FILE,
|
||||
backupFilename,
|
||||
backupManifestSchema,
|
||||
backupTempRoot,
|
||||
directoryExists,
|
||||
dumpDatabaseToFile,
|
||||
} from "@/lib/backup";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { UPLOAD_DIR } from "@/lib/uploads";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* GET /api/dev/backup
|
||||
*
|
||||
* Streams one complete ZIP: manifest, full Postgres dump, uploads volume, and
|
||||
* the mounted photo archive. Admin-only. The dump is written to a private temp
|
||||
* folder first so the archive can include a checksum of the exact SQL bytes.
|
||||
*/
|
||||
export const GET = async () => {
|
||||
const gate = await gateOrUser("admin.settings");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const temp = await mkdtemp(path.join(backupTempRoot(), "glenloch-backup-"));
|
||||
const dumpPath = path.join(temp, BACKUP_DATABASE_FILE);
|
||||
let keepTemp = true;
|
||||
|
||||
try {
|
||||
const dump = await dumpDatabaseToFile(dumpPath);
|
||||
const storage = await getStorageSettings();
|
||||
const uploadsIncluded = await directoryExists(UPLOAD_DIR);
|
||||
const archivePath = storage.archivePath;
|
||||
const archiveIncluded =
|
||||
(await directoryExists(archivePath)) &&
|
||||
path.resolve(archivePath) !== path.resolve(UPLOAD_DIR) &&
|
||||
!isInside(path.resolve(UPLOAD_DIR), path.resolve(archivePath));
|
||||
|
||||
const manifest = backupManifestSchema.parse({
|
||||
format: BACKUP_FORMAT,
|
||||
formatVersion: BACKUP_FORMAT_VERSION,
|
||||
createdAt: new Date().toISOString(),
|
||||
appVersion: process.env.npm_package_version ?? "unknown",
|
||||
database: {
|
||||
file: BACKUP_DATABASE_FILE,
|
||||
bytes: dump.bytes,
|
||||
sha256: dump.sha256,
|
||||
},
|
||||
includes: {
|
||||
uploads: uploadsIncluded,
|
||||
archive: archiveIncluded,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: "backup.created",
|
||||
entityType: "backup",
|
||||
after: {
|
||||
databaseBytes: dump.bytes,
|
||||
uploads: uploadsIncluded,
|
||||
archive: archiveIncluded,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
// A failed audit row must not stop an otherwise valid backup.
|
||||
console.error("backup: could not write audit row", error);
|
||||
}
|
||||
|
||||
const output = new PassThrough();
|
||||
const archive = new ZipArchive({ zlib: { level: 6 } });
|
||||
const cleanup = () => {
|
||||
if (!keepTemp) return;
|
||||
keepTemp = false;
|
||||
void rm(temp, { recursive: true, force: true }).catch(() => undefined);
|
||||
};
|
||||
|
||||
output.on("close", cleanup);
|
||||
output.on("error", cleanup);
|
||||
archive.on("warning", (error) => {
|
||||
console.warn("backup: zip warning", error);
|
||||
});
|
||||
archive.on("error", (error) => {
|
||||
console.error("backup: zip failed", error);
|
||||
output.destroy(error);
|
||||
});
|
||||
archive.pipe(output);
|
||||
|
||||
archive.append(JSON.stringify(manifest, null, 2), {
|
||||
name: BACKUP_MANIFEST_FILE,
|
||||
});
|
||||
archive.file(dumpPath, { name: BACKUP_DATABASE_FILE });
|
||||
if (uploadsIncluded) archive.directory(UPLOAD_DIR, "uploads");
|
||||
if (archiveIncluded) archive.directory(archivePath, "archive");
|
||||
void archive.finalize().catch((error) => output.destroy(error));
|
||||
|
||||
const filename = backupFilename();
|
||||
return new Response(
|
||||
Readable.toWeb(output) as unknown as ReadableStream<Uint8Array>,
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "application/zip",
|
||||
"content-disposition": `attachment; filename="${filename}"`,
|
||||
"cache-control": "private, no-store",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
if (keepTemp) {
|
||||
keepTemp = false;
|
||||
await rm(temp, { recursive: true, force: true }).catch(() => undefined);
|
||||
}
|
||||
const detail =
|
||||
error instanceof Error ? error.message : "backup could not be created";
|
||||
console.error("backup: creation failed", error);
|
||||
return errorResponse(500, detail);
|
||||
}
|
||||
};
|
||||
|
||||
function isInside(parent: string, candidate: string): boolean {
|
||||
const relative = path.relative(parent, candidate);
|
||||
return (
|
||||
relative !== "" &&
|
||||
!relative.startsWith("..") &&
|
||||
!path.isAbsolute(relative)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import {
|
||||
listCatalog,
|
||||
deactivateCatalog,
|
||||
@@ -158,6 +159,9 @@ const dbError = (err: unknown) => {
|
||||
|
||||
/** GET /api/dev/catalog?type=categories&active=true — list pickers rows. */
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const type = typeSchema.safeParse(req.nextUrl.searchParams.get("type"));
|
||||
if (!type.success) {
|
||||
return new Response(JSON.stringify({ error: "invalid type" }), {
|
||||
@@ -175,6 +179,9 @@ export const GET = async (req: NextRequest) => {
|
||||
|
||||
/** POST /api/dev/catalog { type, ...createFields } — create (slug generated). */
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") {
|
||||
return new Response(JSON.stringify({ error: "invalid body" }), {
|
||||
@@ -223,6 +230,9 @@ export const POST = async (req: NextRequest) => {
|
||||
* `slug` is never accepted here: it freezes after creation.
|
||||
*/
|
||||
export const PATCH = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") {
|
||||
return new Response(JSON.stringify({ error: "invalid body" }), {
|
||||
|
||||
@@ -1,36 +1,48 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { signIn } from "@/auth/config";
|
||||
import { verifyMagicToken } from "@/auth/magic-link";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
import {
|
||||
consumeMagicToken,
|
||||
getUser,
|
||||
requestOrigin,
|
||||
verifyMagicToken,
|
||||
} from "@/auth/magic-link";
|
||||
|
||||
/**
|
||||
* Completes a magic-link sign-in. GET /api/dev/complete?token=... verifies the
|
||||
* one-time token and establishes the Auth.js session.
|
||||
* one-time token, establishes the Auth.js session, and redirects into the app.
|
||||
*
|
||||
* This is a browser endpoint (the link in the dev console transport / invite
|
||||
* email is clicked), so it must answer with a redirect rather than JSON: the
|
||||
* session cookie is set on the redirect response and the follow-up request
|
||||
* arrives signed in.
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const token = new URL(req.url, "http://localhost").searchParams.get(
|
||||
"token",
|
||||
) ?? undefined;
|
||||
const origin = requestOrigin(req);
|
||||
const token = new URL(req.url, origin).searchParams.get("token") ?? undefined;
|
||||
const payload = await verifyMagicToken(token);
|
||||
if (!payload) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "invalid or expired link" }),
|
||||
{ status: 400, headers: JSON_HEADERS },
|
||||
);
|
||||
// Expired or tampered link: send the person back to sign-in rather than
|
||||
// dumping an error object in the browser.
|
||||
return NextResponse.redirect(new URL("/login?error=invalid_link", origin));
|
||||
}
|
||||
|
||||
// Single use: the jti is consumed before a session is created, so a link
|
||||
// forwarded or leaked after first use cannot sign anyone in again.
|
||||
const consumed = await consumeMagicToken(payload);
|
||||
if (!consumed) {
|
||||
return NextResponse.redirect(new URL("/login?error=link_used", origin));
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await signIn("magic-link", { token, redirect: false });
|
||||
return new Response(JSON.stringify({ ok: true, url: result.url }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
await signIn("magic-link", { token, redirect: false });
|
||||
// The first successful link opens credential setup; returning users go
|
||||
// straight into the app.
|
||||
const user = await getUser(payload.email);
|
||||
return NextResponse.redirect(
|
||||
new URL(user?.passwordHash ? "/schedule" : "/welcome", origin),
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[complete] signIn failed:", (err as Error).message, (err as Error).stack);
|
||||
return new Response(JSON.stringify({ error: "failed to sign in" }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
return NextResponse.redirect(new URL("/login", origin));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { gateCron } from "@/auth/api";
|
||||
import { completePastAssignments } from "@/db/complete";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
/**
|
||||
* GET /api/dev/cron/complete — close assignments for services that have ended.
|
||||
*
|
||||
* Marks past published assignments `completed` and updates the volunteer's
|
||||
* `last_served_on` / `last_served_at`, which drive staleness and fairness.
|
||||
* Idempotent: a second run has nothing left to complete.
|
||||
*
|
||||
* Auth: `Authorization: Bearer $CRON_SECRET` (or `?secret=`) for an external
|
||||
* scheduler, otherwise a session with `schedule.publish`.
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const gate = await gateCron(req);
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
try {
|
||||
const summary = await completePastAssignments();
|
||||
return new Response(JSON.stringify(summary), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : "completion failed";
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,15 +1,39 @@
|
||||
import { auth } from "@/auth/config";
|
||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import { generateInstances } from "@/db/instances";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
/**
|
||||
* Daily instance generator (ARCHITECTURE §5.1). Cron `0 6 * * *` (church-local
|
||||
* 06:00, expressed in UTC) calls this. Idempotent — a re-run creates 0 rows.
|
||||
* Instance generator (ARCHITECTURE §5.1). Idempotent — a re-run creates 0 rows.
|
||||
* Callable from the admin services panel; also safe for an external cron once
|
||||
* it is given a service credential. Here it is guarded by `schedule.publish`.
|
||||
*
|
||||
* GET /api/dev/cron/instances
|
||||
*/
|
||||
export const GET = async () => {
|
||||
const result = await generateInstances();
|
||||
return new Response(JSON.stringify({ result }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
try {
|
||||
const session = await auth();
|
||||
requirePermission(
|
||||
(session?.user as { systemRole: SystemRole } | null | undefined),
|
||||
"schedule.publish",
|
||||
);
|
||||
const result = await generateInstances();
|
||||
return new Response(JSON.stringify({ result }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ error: "failed to generate instances" }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { gateCron } from "@/auth/api";
|
||||
import { dispatchDue } from "@/db/dispatcher";
|
||||
import { enqueueEventReminders } from "@/db/eventReminders";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
/**
|
||||
* GET /api/dev/cron/notifications — the dispatcher tick (cron every 5 min).
|
||||
*
|
||||
* Queues any event reminders that are now inside their lead window, then drains
|
||||
* due outbox rows through the guards (assignment active, volunteer active,
|
||||
* channel consent, quiet hours) and the configured transport. Returns what
|
||||
* happened; running it again with nothing due is a no-op.
|
||||
*
|
||||
* Auth: `Authorization: Bearer $CRON_SECRET` (or `?secret=`) for an external
|
||||
* scheduler, otherwise a session with `schedule.publish`.
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const gate = await gateCron(req);
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
try {
|
||||
const eventRemindersQueued = await enqueueEventReminders();
|
||||
const summary = await dispatchDue();
|
||||
return new Response(JSON.stringify({ ...summary, eventRemindersQueued }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : "dispatch failed";
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,15 +1,32 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { gateCron } from "@/auth/api";
|
||||
import { materializeSlots } from "@/db/slots";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
/**
|
||||
* Slot materialization (ARCHITECTURE §5.2). Drives `materializeSlots()` —
|
||||
* idempotent on (instance, role, seat). Re-runs create 0 rows.
|
||||
*
|
||||
* GET /api/dev/cron/slots
|
||||
* Auth: `Authorization: Bearer $CRON_SECRET` (or `?secret=`) for an external
|
||||
* scheduler, otherwise a session with `schedule.publish`.
|
||||
*/
|
||||
export const GET = async () => {
|
||||
const result = await materializeSlots();
|
||||
return new Response(JSON.stringify({ result }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const gate = await gateCron(req);
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
try {
|
||||
const result = await materializeSlots();
|
||||
return new Response(JSON.stringify({ result }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : "slot materialization failed";
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { denyUser } from "@/auth/invites";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
@@ -12,6 +13,9 @@ const bodySchema = z.object({
|
||||
* Deny a pending user -> denied (cannot sign in). POST { userId, deniedBy? }.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("users.manage");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
let userId: string | undefined;
|
||||
let deniedBy: string | undefined;
|
||||
try {
|
||||
@@ -33,7 +37,7 @@ export const POST = async (req: NextRequest) => {
|
||||
try {
|
||||
const user = await denyUser({
|
||||
userId: parsed.data.userId,
|
||||
deniedBy: parsed.data.deniedBy ?? "admin",
|
||||
deniedBy: gate.id,
|
||||
});
|
||||
return new Response(JSON.stringify({ ok: true, id: user.id, status: user.status }), {
|
||||
status: 200,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { inviteUser } from "@/auth/invites";
|
||||
import { requestOrigin } from "@/auth/magic-link";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
const bodySchema = z.object({
|
||||
@@ -14,6 +16,9 @@ const bodySchema = z.object({
|
||||
* signs a magic-link token, and enqueues an invite to the console outbox.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("users.manage");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
let email: string | undefined;
|
||||
let invitedBy: string | undefined;
|
||||
try {
|
||||
@@ -35,7 +40,9 @@ export const POST = async (req: NextRequest) => {
|
||||
try {
|
||||
const result = await inviteUser({
|
||||
email: parsed.data.email,
|
||||
invitedBy: parsed.data.invitedBy ?? "admin",
|
||||
// Server-owned: the signed-in admin is the inviter.
|
||||
invitedBy: gate.id,
|
||||
appOrigin: requestOrigin(req),
|
||||
});
|
||||
return new Response(JSON.stringify(result), {
|
||||
status: 200,
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requestMagicLink } from "@/auth/magic-link";
|
||||
import { clientIp } from "@/auth/api";
|
||||
import {
|
||||
MAGIC_LINK_DEV_TRANSPORT,
|
||||
requestMagicLink,
|
||||
requestOrigin,
|
||||
} from "@/auth/magic-link";
|
||||
import { rateLimit } from "@/lib/rate-limit";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
const bodySchema = z.object({ email: z.string().email() });
|
||||
@@ -28,8 +34,35 @@ export const POST = async (req: NextRequest) => {
|
||||
});
|
||||
}
|
||||
|
||||
// Production: 5 requests per address and 20 per IP per 10 minutes blunts
|
||||
// link spam and email enumeration. The console transport (local/dev/e2e) is
|
||||
// deliberately not throttled, since the test harness signs in repeatedly.
|
||||
const ip = clientIp(req);
|
||||
const emailKey = parsed.data.email.trim().toLowerCase();
|
||||
const byAddress = MAGIC_LINK_DEV_TRANSPORT
|
||||
? { ok: true, retryAfterSeconds: 0 }
|
||||
: rateLimit(`magic:${ip}:${emailKey}`, 5, 10 * 60_000);
|
||||
const byIp = MAGIC_LINK_DEV_TRANSPORT
|
||||
? { ok: true, retryAfterSeconds: 0 }
|
||||
: rateLimit(`magic-ip:${ip}`, 20, 10 * 60_000);
|
||||
if (!byAddress.ok || !byIp.ok) {
|
||||
const retry = Math.max(byAddress.retryAfterSeconds, byIp.retryAfterSeconds);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: "too many sign-in requests; try again later",
|
||||
code: "RATE_LIMITED",
|
||||
}),
|
||||
{
|
||||
status: 429,
|
||||
headers: { ...JSON_HEADERS, "retry-after": String(retry) },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await requestMagicLink(parsed.data.email);
|
||||
const result = await requestMagicLink(parsed.data.email, {
|
||||
origin: requestOrigin(req),
|
||||
});
|
||||
return new Response(JSON.stringify(result), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { auth } from "@/auth/config";
|
||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import { createRule, listRules, updateRule } from "@/db/reminders";
|
||||
import { NOTIFICATION_RULE_EVENTS } from "@/db/schema";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
const createSchema = z.object({
|
||||
key: z.string().min(1),
|
||||
event: z.enum(NOTIFICATION_RULE_EVENTS).optional(),
|
||||
offsetDays: z.number().int().min(-30).max(30),
|
||||
sendAtLocalTime: z.string().regex(/^\d{2}:\d{2}$/),
|
||||
channelSet: z.enum(["email", "sms", "email+sms"]),
|
||||
appliesToServiceId: z.string().nullable().optional(),
|
||||
active: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const patchSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
offsetDays: z.number().int().min(-30).max(30).optional(),
|
||||
sendAtLocalTime: z.string().regex(/^\d{2}:\d{2}$/).optional(),
|
||||
channelSet: z.enum(["email", "sms", "email+sms"]).optional(),
|
||||
appliesToServiceId: z.string().nullable().optional(),
|
||||
active: z.boolean().optional(),
|
||||
});
|
||||
|
||||
async function requireActor() {
|
||||
const session = await auth();
|
||||
const user = session?.user as
|
||||
| { id: string; systemRole: SystemRole }
|
||||
| null
|
||||
| undefined;
|
||||
if (!user) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }),
|
||||
{ status: 401, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
requirePermission(user, "schedule.publish");
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reminder rules CRUD — unit E7 (ARCHITECTURE §6.2).
|
||||
*
|
||||
* GET -> all rules
|
||||
* POST -> create a rule ({ key, offsetDays, sendAtLocalTime, channelSet })
|
||||
* PATCH -> edit a rule (partial)
|
||||
*
|
||||
* Guarded by `schedule.publish`. Reminder sends are computed from these rows at
|
||||
* publish time, so changing an offset changes `scheduled_for` with no deploy.
|
||||
*/
|
||||
export const GET = async () => {
|
||||
try {
|
||||
const actor = await requireActor();
|
||||
if (actor instanceof Response) return actor;
|
||||
return new Response(JSON.stringify({ rules: await listRules() }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ error: "failed to list rules" }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest) => {
|
||||
try {
|
||||
const actor = await requireActor();
|
||||
if (actor instanceof Response) return actor;
|
||||
const body = await req.json().catch(() => null);
|
||||
const parsed = createSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return new Response(JSON.stringify({ error: parsed.error.message }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const rule = await createRule({
|
||||
key: parsed.data.key,
|
||||
event: parsed.data.event ?? "assignment.created",
|
||||
offsetDays: parsed.data.offsetDays,
|
||||
sendAtLocalTime: parsed.data.sendAtLocalTime,
|
||||
channelSet: parsed.data.channelSet,
|
||||
appliesToServiceId: parsed.data.appliesToServiceId ?? null,
|
||||
active: parsed.data.active ?? true,
|
||||
});
|
||||
return new Response(JSON.stringify({ rule }), {
|
||||
status: 201,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ error: "failed to create rule" }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const PATCH = async (req: NextRequest) => {
|
||||
try {
|
||||
const actor = await requireActor();
|
||||
if (actor instanceof Response) return actor;
|
||||
const body = await req.json().catch(() => null);
|
||||
const parsed = patchSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return new Response(JSON.stringify({ error: parsed.error.message }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const { id, ...patch } = parsed.data;
|
||||
const rule = await updateRule(id, patch);
|
||||
if (!rule) {
|
||||
return new Response(JSON.stringify({ error: "unknown rule" }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ rule }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ error: "failed to update rule" }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,170 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { auth } from "@/auth/config";
|
||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import { listNotifications, retryNotification } from "@/db/outbox";
|
||||
import { db } from "@/db";
|
||||
import { users } from "@/db/schema";
|
||||
import { resolveEmailTransport } from "@/lib/email";
|
||||
import { getEmailTransportSettings } from "@/db/settings";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { NOTIFICATION_STATUSES, type NotificationStatus } from "@/db/schema";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
function isStatus(value: string | null): value is NotificationStatus {
|
||||
return (
|
||||
value !== null &&
|
||||
(NOTIFICATION_STATUSES as readonly string[]).includes(value)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/dev/notifications?status=&limit= — the admin notification log
|
||||
* (newest first), read straight from the outbox table (ARCHITECTURE §4/§6.1).
|
||||
* Guarded by `schedule.publish`.
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
try {
|
||||
const session = await auth();
|
||||
const user = session?.user as
|
||||
| { id: string; systemRole: SystemRole }
|
||||
| null
|
||||
| undefined;
|
||||
if (!user) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: "Authentication required",
|
||||
code: "UNAUTHORIZED",
|
||||
}),
|
||||
{ status: 401, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
requirePermission(user, "schedule.publish");
|
||||
|
||||
const statusParam = req.nextUrl.searchParams.get("status");
|
||||
if (statusParam !== null && !isStatus(statusParam)) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: `unknown status: ${statusParam}` }),
|
||||
{ status: 400, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
const limitParam = Number(req.nextUrl.searchParams.get("limit") ?? "50");
|
||||
const notifications = await listNotifications({
|
||||
status: isStatus(statusParam) ? statusParam : undefined,
|
||||
limit: Number.isFinite(limitParam) ? limitParam : 50,
|
||||
});
|
||||
|
||||
return new Response(JSON.stringify({ notifications }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const message = e instanceof Error ? e.message : "internal error";
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const actionSchema = z.object({
|
||||
action: z.enum(["retry", "send_test"]),
|
||||
id: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/dev/notifications — the admin log's actions (E6).
|
||||
* { action: "retry", id } -> requeue a failed/suppressed row for the next tick
|
||||
* { action: "send_test" } -> send a test email to the signed-in admin
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
try {
|
||||
const session = await auth();
|
||||
const user = session?.user as
|
||||
| { id: string; systemRole: SystemRole }
|
||||
| null
|
||||
| undefined;
|
||||
if (!user) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }),
|
||||
{ status: 401, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
requirePermission(user, "schedule.publish");
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
const parsed = actionSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return new Response(JSON.stringify({ error: parsed.error.message }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
if (parsed.data.action === "retry") {
|
||||
if (!parsed.data.id) {
|
||||
return new Response(JSON.stringify({ error: "an id is required" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const row = await retryNotification(parsed.data.id);
|
||||
if (!row) {
|
||||
return new Response(JSON.stringify({ error: "unknown notification" }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ ok: true, notification: row }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
const [actor] = await db
|
||||
.select({ email: users.email, firstName: users.firstName })
|
||||
.from(users)
|
||||
.where(eq(users.id, user.id))
|
||||
.limit(1);
|
||||
if (!actor) {
|
||||
return new Response(JSON.stringify({ error: "unknown user" }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const settings = await getEmailTransportSettings();
|
||||
const transport = resolveEmailTransport(settings);
|
||||
const result = await transport.send({
|
||||
to: settings.notificationEmail || actor.email,
|
||||
subject: "Media Team Hub — test message",
|
||||
html: `<p>${actor.firstName}, this is a test from Media Team Hub.</p><p>If you can read this, ${transport.name} delivery works.</p>`,
|
||||
text: `${actor.firstName}, this is a test from Media Team Hub. If you can read this, ${transport.name} delivery works.`,
|
||||
templateKey: "admin.send_test",
|
||||
dedupeKey: `admin.send_test:${user.id}:${Date.now()}`,
|
||||
});
|
||||
return new Response(JSON.stringify({ ok: true, transport: transport.name, ...result }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const message = e instanceof Error ? e.message : "internal error";
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -2,6 +2,7 @@ import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { getPositionSkills, setPositionSkills } from "@/db/positions";
|
||||
import { validateRequirements } from "@/domain/positions";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
@@ -44,6 +45,9 @@ const ok = (row: unknown) =>
|
||||
* core flag).
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const positionId = req.nextUrl.searchParams.get("positionId");
|
||||
if (!positionId) return bad("missing positionId");
|
||||
const row = await getPositionSkills(positionId);
|
||||
@@ -61,6 +65,9 @@ export const GET = async (req: NextRequest) => {
|
||||
* "weight": 3, "requiredLevel": "qualified" } ], "published": true }
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") return bad("invalid body");
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
updatePosition,
|
||||
deactivatePosition,
|
||||
} from "@/db/positions";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
@@ -85,6 +86,9 @@ const dbError = (err: unknown) => {
|
||||
|
||||
/** GET /api/dev/positions?active=true — list picker rows. */
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const active = req.nextUrl.searchParams.get("active") !== "false";
|
||||
const rows = await listPositions({ active });
|
||||
return new Response(JSON.stringify({ rows }), {
|
||||
@@ -95,6 +99,9 @@ export const GET = async (req: NextRequest) => {
|
||||
|
||||
/** POST /api/dev/positions { ...createFields } — create (slug generated). */
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") {
|
||||
return bad("invalid body");
|
||||
@@ -114,6 +121,9 @@ export const POST = async (req: NextRequest) => {
|
||||
* `slug` is never accepted here: it freezes after creation.
|
||||
*/
|
||||
export const PATCH = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") {
|
||||
return bad("invalid body");
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { updateProfile, setSmsConsent } from "@/db/profile";
|
||||
import type { ProfilePatch } from "@/db/profile";
|
||||
import { clientIp, gateSelfOr } from "@/auth/api";
|
||||
import {
|
||||
updateProfile,
|
||||
setSmsConsent,
|
||||
updateNotificationPreferences,
|
||||
} from "@/db/profile";
|
||||
import type { ProfilePatch, NotificationPreferencePatch } from "@/db/profile";
|
||||
import type { SmsConsentSource } from "@/db/schema";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
@@ -14,6 +19,11 @@ const profileSchema = z.object({
|
||||
phoneE164: z.string().nullable().optional(),
|
||||
emergencyContact: z.string().nullable().optional(),
|
||||
timezone: z.string().optional(),
|
||||
emailEnabled: z.boolean().optional(),
|
||||
reminderLeadDays: z.number().int().min(1).max(14).optional(),
|
||||
digestOnly: z.boolean().optional(),
|
||||
quietHoursStart: z.string().regex(/^\d{2}:\d{2}$/).optional(),
|
||||
quietHoursEnd: z.string().regex(/^\d{2}:\d{2}$/).optional(),
|
||||
});
|
||||
|
||||
const consentSchema = z.object({
|
||||
@@ -45,6 +55,9 @@ export const PATCH = async (req: NextRequest) => {
|
||||
});
|
||||
}
|
||||
|
||||
const gate = await gateSelfOr("users.manage", parsed.data.userId);
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
try {
|
||||
// Only update fields actually present in the body — a PATCH must not null
|
||||
// out unspecified fields (e.g. omitting phoneE164 must not wipe the phone).
|
||||
@@ -56,7 +69,25 @@ export const PATCH = async (req: NextRequest) => {
|
||||
if (parsed.data.emergencyContact !== undefined) patch.emergencyContact = parsed.data.emergencyContact;
|
||||
if (parsed.data.timezone !== undefined) patch.timezone = parsed.data.timezone;
|
||||
|
||||
const prefPatch: NotificationPreferencePatch = {};
|
||||
if (parsed.data.emailEnabled !== undefined)
|
||||
prefPatch.emailEnabled = parsed.data.emailEnabled;
|
||||
if (parsed.data.reminderLeadDays !== undefined)
|
||||
prefPatch.reminderLeadDays = parsed.data.reminderLeadDays;
|
||||
if (parsed.data.digestOnly !== undefined)
|
||||
prefPatch.digestOnly = parsed.data.digestOnly;
|
||||
if (parsed.data.quietHoursStart !== undefined)
|
||||
prefPatch.quietHoursStart = parsed.data.quietHoursStart;
|
||||
if (parsed.data.quietHoursEnd !== undefined)
|
||||
prefPatch.quietHoursEnd = parsed.data.quietHoursEnd;
|
||||
|
||||
const result = await updateProfile(parsed.data.userId, patch);
|
||||
if (Object.keys(prefPatch).length > 0) {
|
||||
result.preferences = await updateNotificationPreferences(
|
||||
parsed.data.userId,
|
||||
prefPatch,
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify(result), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
@@ -91,12 +122,16 @@ export const POST = async (req: NextRequest) => {
|
||||
});
|
||||
}
|
||||
|
||||
const gate = await gateSelfOr("users.manage", parsed.data.userId);
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
try {
|
||||
const preferences = await setSmsConsent(
|
||||
parsed.data.userId,
|
||||
{
|
||||
source: parsed.data.source as SmsConsentSource,
|
||||
ip: parsed.data.ip ?? null,
|
||||
// TCPA evidence is recorded from the request, never from the client body.
|
||||
ip: clientIp(req),
|
||||
},
|
||||
);
|
||||
return new Response(JSON.stringify({ ok: true, preferences }), {
|
||||
|
||||
@@ -1,35 +1,44 @@
|
||||
import { auth } from "@/auth/config";
|
||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { resetAndSeed } from "@/db/seed";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
/**
|
||||
* Dev console reset. Admin-only (admin.settings): truncates the seed-owned
|
||||
* tables and repopulates them, so E2E tests start from a known-clean state on
|
||||
* every run instead of accumulating the mutations of prior runs. Not wired into
|
||||
* any UI — it exists only for test harnesses.
|
||||
* Test-only database reset.
|
||||
*
|
||||
* Two gates, both required:
|
||||
* 1. `ALLOW_DEV_RESET=true` must be set explicitly. This keeps a destructive
|
||||
* truncate + reseed out of any deployment that did not ask for it.
|
||||
* 2. The caller must be a signed-in admin (`admin.settings`).
|
||||
*
|
||||
* E2E sets `ALLOW_DEV_RESET=true` in `playwright.config.ts`; production
|
||||
* compose does not.
|
||||
*/
|
||||
export const POST = async () => {
|
||||
try {
|
||||
const session = await auth();
|
||||
requirePermission(
|
||||
(session?.user as { systemRole: SystemRole } | null | undefined),
|
||||
"admin.settings",
|
||||
if (process.env.ALLOW_DEV_RESET !== "true") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: "database reset is disabled in this environment",
|
||||
code: "RESET_DISABLED",
|
||||
}),
|
||||
{ status: 403, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
|
||||
const gate = await gateOrUser("admin.settings");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
try {
|
||||
await resetAndSeed();
|
||||
return new Response(JSON.stringify({ ok: true }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
throw e;
|
||||
const message = e instanceof Error ? e.message : "reset failed";
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { auth } from "@/auth/config";
|
||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import { db } from "@/db";
|
||||
import { applyAutoFill, computeAutoFill } from "@/db/autoFill";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
const bodySchema = z
|
||||
.object({
|
||||
maxServicesPerMonth: z.number().int().positive().optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
/**
|
||||
* Auto-fill proposals for one service instance (unit D9).
|
||||
*
|
||||
* GET /api/dev/schedule/:instanceId/auto-fill
|
||||
* -> { proposals, unfilled } computed from the instance's open seats and
|
||||
* the active volunteer pool. Nothing is written.
|
||||
*
|
||||
* POST /api/dev/schedule/:instanceId/auto-fill
|
||||
* { maxServicesPerMonth? }
|
||||
* -> writes one `proposed`/`auto` assignment per still-free proposal and
|
||||
* an audit row. Idempotent: a re-run finds every seat already filled
|
||||
* and writes 0 rows.
|
||||
*
|
||||
* Guarded by `schedule.publish` (coordinator + admin).
|
||||
*/
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ instanceId: string }> },
|
||||
) => {
|
||||
try {
|
||||
const session = await auth();
|
||||
const user = (session?.user as { id: string; systemRole: SystemRole } | null | undefined);
|
||||
if (!user) {
|
||||
return new Response(JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), {
|
||||
status: 401,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
requirePermission(user, "schedule.publish");
|
||||
|
||||
const { instanceId } = await params;
|
||||
const result = await computeAutoFill(instanceId);
|
||||
return new Response(JSON.stringify(result), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const message = e instanceof Error ? e.message : "internal error";
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ instanceId: string }> },
|
||||
) => {
|
||||
let maxServicesPerMonth: number | undefined;
|
||||
try {
|
||||
const body = await req.json().catch(() => null);
|
||||
const parsed = bodySchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return new Response(JSON.stringify({ error: parsed.error.message }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
maxServicesPerMonth = parsed.data?.maxServicesPerMonth;
|
||||
} catch {
|
||||
return new Response(JSON.stringify({ error: "invalid body" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const session = await auth();
|
||||
const user = (session?.user as { id: string; systemRole: SystemRole } | null | undefined);
|
||||
if (!user) {
|
||||
return new Response(JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), {
|
||||
status: 401,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
requirePermission(user, "schedule.publish");
|
||||
const actorId = user.id;
|
||||
|
||||
const { instanceId } = await params;
|
||||
const result = await applyAutoFill(instanceId, {
|
||||
actorId,
|
||||
maxServicesPerMonth,
|
||||
});
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId,
|
||||
action: "schedule.autofill",
|
||||
entityType: "service_instance",
|
||||
entityId: instanceId,
|
||||
after: {
|
||||
proposals: result.proposals.length,
|
||||
written: result.written,
|
||||
unfilled: result.unfilled.length,
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(JSON.stringify(result), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const message = e instanceof Error ? e.message : "internal error";
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,147 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { auth } from "@/auth/config";
|
||||
import { requestOrigin } from "@/auth/magic-link";
|
||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import { PublishError, publishInstance, unpublishInstance } from "@/db/publish";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
const bodySchema = z.object({
|
||||
allowGaps: z.boolean().optional(),
|
||||
});
|
||||
|
||||
/** Map a refused publish/unpublish to its HTTP status. */
|
||||
function errorStatus(code: PublishError["code"]): number {
|
||||
switch (code) {
|
||||
case "unknown_instance":
|
||||
return 404;
|
||||
case "instance_cancelled":
|
||||
case "open_slots":
|
||||
case "unpublish_blocked":
|
||||
return 409;
|
||||
}
|
||||
}
|
||||
|
||||
function jsonError(e: PublishError): Response {
|
||||
return new Response(
|
||||
JSON.stringify({ error: e.message, code: e.code, gaps: e.gaps }),
|
||||
{ status: errorStatus(e.code), headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
|
||||
function authFailure(e: AuthError): Response {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve the session user or return the 401 response. */
|
||||
async function requireActor(): Promise<
|
||||
{ id: string; systemRole: SystemRole } | Response
|
||||
> {
|
||||
const session = await auth();
|
||||
const user = session?.user as
|
||||
| { id: string; systemRole: SystemRole }
|
||||
| null
|
||||
| undefined;
|
||||
if (!user) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }),
|
||||
{ status: 401, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
requirePermission(user, "schedule.publish");
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish / unpublish one service instance (unit D10, ARCHITECTURE §5.5).
|
||||
*
|
||||
* POST /api/dev/schedule/:instanceId/publish { allowGaps? }
|
||||
* -> one transaction: validate coverage, set `status='published'` +
|
||||
* `published_at`/`published_by`, write the `week.published` audit
|
||||
* row. Blocked 409 with `gaps` when a covering seat is empty and
|
||||
* `allowGaps` is false. Re-publishing is an idempotent no-op.
|
||||
*
|
||||
* DELETE /api/dev/schedule/:instanceId/publish
|
||||
* -> back to draft, `week.unpublished` audit row. Refused 409 while a
|
||||
* volunteer has confirmed.
|
||||
*
|
||||
* D10 sends nothing — notification wiring is E1.
|
||||
*/
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ instanceId: string }> },
|
||||
) => {
|
||||
let allowGaps: boolean | undefined;
|
||||
try {
|
||||
const body = await req.json().catch(() => null);
|
||||
const parsed = bodySchema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
return new Response(JSON.stringify({ error: parsed.error.message }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
allowGaps = parsed.data.allowGaps;
|
||||
} catch {
|
||||
return new Response(JSON.stringify({ error: "invalid body" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const actor = await requireActor();
|
||||
if (actor instanceof Response) return actor;
|
||||
|
||||
const { instanceId } = await params;
|
||||
const result = await publishInstance(instanceId, {
|
||||
actorId: actor.id,
|
||||
allowGaps,
|
||||
// Confirmation links in the publish/reminder emails must point at the
|
||||
// origin the schedule is being managed from (LAN IP or public domain).
|
||||
appOrigin: requestOrigin(req),
|
||||
});
|
||||
return new Response(JSON.stringify({ ok: true, ...result }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) return authFailure(e);
|
||||
if (e instanceof PublishError) return jsonError(e);
|
||||
const message = e instanceof Error ? e.message : "internal error";
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const DELETE = async (
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ instanceId: string }> },
|
||||
) => {
|
||||
try {
|
||||
const actor = await requireActor();
|
||||
if (actor instanceof Response) return actor;
|
||||
|
||||
const { instanceId } = await params;
|
||||
const result = await unpublishInstance(instanceId, { actorId: actor.id });
|
||||
return new Response(JSON.stringify({ ok: true, ...result }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) return authFailure(e);
|
||||
if (e instanceof PublishError) return jsonError(e);
|
||||
const message = e instanceof Error ? e.message : "internal error";
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { serviceInstances, services } from "@/db/schema";
|
||||
import { gateCron } from "@/auth/api";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
/**
|
||||
* GET /api/dev/schedule/instances — the list of service instances (id,
|
||||
* occursOn, serviceName) for the admin helper routes. Guarded by
|
||||
* `schedule.publish` (coordinator + admin).
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const gate = await gateCron(req);
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
try {
|
||||
|
||||
// `serviceName` is the instance's title override when set, else the service
|
||||
// template's name. Ordering includes `startsAt` so two instances on the same
|
||||
// date (both Sunday services) always come back in the same order.
|
||||
const rows = await db
|
||||
.select({
|
||||
id: serviceInstances.id,
|
||||
occursOn: serviceInstances.occursOn,
|
||||
titleOverride: serviceInstances.titleOverride,
|
||||
name: services.name,
|
||||
status: serviceInstances.status,
|
||||
})
|
||||
.from(serviceInstances)
|
||||
.innerJoin(services, eq(services.id, serviceInstances.serviceId))
|
||||
.orderBy(serviceInstances.occursOn, serviceInstances.startsAt);
|
||||
const instances = rows.map((r) => ({
|
||||
id: r.id,
|
||||
occursOn: r.occursOn,
|
||||
serviceName: r.titleOverride ?? r.name,
|
||||
status: r.status,
|
||||
}));
|
||||
return new Response(JSON.stringify({ instances }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : "internal error";
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,14 +1,38 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { auth } from "@/auth/config";
|
||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import {
|
||||
listServices,
|
||||
createService,
|
||||
updateService,
|
||||
deactivateService,
|
||||
deleteService,
|
||||
} from "@/db/services";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
/** Services are schedule data: only `schedule.publish` roles may change them. */
|
||||
async function requireEditor(): Promise<Response | null> {
|
||||
const session = await auth();
|
||||
try {
|
||||
requirePermission(
|
||||
(session?.user as { systemRole: SystemRole } | null | undefined),
|
||||
"schedule.publish",
|
||||
);
|
||||
return null;
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
const idSchema = z.string().min(1);
|
||||
|
||||
const serviceCreateSchema = z.object({
|
||||
@@ -85,6 +109,8 @@ const constraintError = (err: unknown): Response | null => {
|
||||
|
||||
/** GET /api/dev/services?active=true — list service templates. */
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const failure = await requireEditor();
|
||||
if (failure) return failure;
|
||||
const active = req.nextUrl.searchParams.get("active") !== "false";
|
||||
const rows = await listServices({ active });
|
||||
return new Response(JSON.stringify({ rows }), {
|
||||
@@ -95,6 +121,8 @@ export const GET = async (req: NextRequest) => {
|
||||
|
||||
/** POST /api/dev/services { ...fields } — create a service template. */
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const failure = await requireEditor();
|
||||
if (failure) return failure;
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") {
|
||||
return bad("invalid body");
|
||||
@@ -110,12 +138,52 @@ export const POST = async (req: NextRequest) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* DELETE /api/dev/services?id=… — permanently remove a template that never ran.
|
||||
* Refused (409) once an instance has started, been published, or carries an
|
||||
* assignment; those must be deactivated so schedule history survives.
|
||||
*/
|
||||
export const DELETE = async (req: NextRequest) => {
|
||||
const failure = await requireEditor();
|
||||
if (failure) return failure;
|
||||
const id = idSchema.safeParse(req.nextUrl.searchParams.get("id"));
|
||||
if (!id.success) return bad("a valid id is required");
|
||||
|
||||
const result = await deleteService(id.data);
|
||||
if (result.ok) {
|
||||
return new Response(
|
||||
JSON.stringify({ ok: true, removedInstances: result.removedInstances }),
|
||||
{ status: 200, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
if (result.reason === "not_found") {
|
||||
return new Response(JSON.stringify({ error: "unknown service" }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
const history =
|
||||
result.assignments > 0
|
||||
? `${result.instances} instance(s) and ${result.assignments} assignment(s)`
|
||||
: `${result.instances} published or past instance(s)`;
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: `This service has ${history}. Deactivate it instead so the schedule history is preserved.`,
|
||||
code: "HAS_HISTORY",
|
||||
}),
|
||||
{ status: 409, headers: JSON_HEADERS },
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* PATCH /api/dev/services { id, ...fields } — edit.
|
||||
* PATCH { id, active: false } — deactivate (soft delete).
|
||||
* `name` is never accepted here: it freezes after creation.
|
||||
*/
|
||||
export const PATCH = async (req: NextRequest) => {
|
||||
const failure = await requireEditor();
|
||||
if (failure) return failure;
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") {
|
||||
return bad("invalid body");
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import {
|
||||
getEmailSettings,
|
||||
saveEmailSettings,
|
||||
type EmailSettings,
|
||||
} from "@/db/settings";
|
||||
import { normalizeAppPassword } from "@/lib/secret";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
const settingsSchema = z.object({
|
||||
emailFrom: z.string().email(),
|
||||
notificationEmail: z.string().email().or(z.literal("")),
|
||||
/** Empty string disconnects Gmail; omitted leaves the stored credentials. */
|
||||
smtpUser: z.union([z.literal(""), z.string().email()]).optional(),
|
||||
/** Omitted/blank keeps the stored app password. */
|
||||
smtpAppPassword: z.string().max(200).optional(),
|
||||
});
|
||||
|
||||
/** What goes in the audit trail — never the password. */
|
||||
function summary(settings: EmailSettings) {
|
||||
return {
|
||||
emailFrom: settings.emailFrom,
|
||||
notificationEmail: settings.notificationEmail,
|
||||
smtpUser: settings.smtpUser,
|
||||
smtpConfigured: settings.smtpConfigured,
|
||||
};
|
||||
}
|
||||
|
||||
const bad = (message: string, status = 400) =>
|
||||
new Response(JSON.stringify({ error: message }), {
|
||||
status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/dev/settings — email identity, and whether a Gmail account is
|
||||
* connected (the app password itself is never returned).
|
||||
*/
|
||||
export const GET = async () => {
|
||||
const gate = await gateOrUser("admin.settings");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
return new Response(JSON.stringify({ settings: await getEmailSettings() }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* PUT /api/dev/settings
|
||||
* { emailFrom, notificationEmail, smtpUser?, smtpAppPassword? }
|
||||
*
|
||||
* Saves the sender identity and, when given, the Gmail credentials. A blank
|
||||
* app password keeps the stored one; `smtpUser: ""` disconnects Gmail and
|
||||
* deletes both credential rows. Every save writes an audit row with the
|
||||
* address but never the secret.
|
||||
*/
|
||||
export const PUT = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("admin.settings");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
const parsed = settingsSchema.safeParse(body);
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
|
||||
const before = await getEmailSettings();
|
||||
const smtpUser = parsed.data.smtpUser;
|
||||
const password = normalizeAppPassword(parsed.data.smtpAppPassword ?? "");
|
||||
|
||||
if (smtpUser !== undefined && smtpUser !== "") {
|
||||
if (password !== "" && password.length < 8) {
|
||||
return bad(
|
||||
"That does not look like a Google app password — it should be 16 characters.",
|
||||
);
|
||||
}
|
||||
if (password === "" && !before.smtpConfigured) {
|
||||
return bad("Enter the 16-character app password for this Gmail account.");
|
||||
}
|
||||
if (password === "" && smtpUser !== before.smtpUser) {
|
||||
return bad("Enter the app password for the new Gmail account.");
|
||||
}
|
||||
}
|
||||
|
||||
const settings = await saveEmailSettings({
|
||||
emailFrom: parsed.data.emailFrom,
|
||||
notificationEmail: parsed.data.notificationEmail,
|
||||
smtpUser,
|
||||
smtpAppPassword: password,
|
||||
});
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: "settings.email.updated",
|
||||
entityType: "app_settings",
|
||||
entityId: "email",
|
||||
before: summary(before),
|
||||
after: summary(settings),
|
||||
});
|
||||
|
||||
return new Response(JSON.stringify({ ok: true, settings }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { listAssessments } from "@/db/assessments";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
@@ -16,6 +17,9 @@ const bad = (message: string) =>
|
||||
* the verify modal. There is intentionally no update or delete endpoint.
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const params = req.nextUrl.searchParams;
|
||||
const rawLimit = params.get("limit");
|
||||
let limit: number | undefined;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { composeSkillName } from "@/domain/skills";
|
||||
import { dedupeKey } from "@/db/positions";
|
||||
|
||||
@@ -39,6 +40,9 @@ const bad = (message: string) =>
|
||||
* technologyName?, functionId?, functionName? } -> { name, dedupeKey }.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") return bad("invalid body");
|
||||
const parsed = composeSchema.safeParse(body);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { listSkillsMatrix } from "@/db/assessments";
|
||||
import { isSkillLevel, SKILL_LEVELS, type SkillLevel } from "@/domain/assessments";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
@@ -19,6 +20,9 @@ const bad = (message: string) =>
|
||||
* compose, so `?level=qualified` answers "who is currently signed off?".
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const params = req.nextUrl.searchParams;
|
||||
const level = params.get("level");
|
||||
if (level !== null && !isSkillLevel(level)) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
updateSkill,
|
||||
deactivateSkill,
|
||||
} from "@/db/positions";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
@@ -95,6 +96,9 @@ const dbError = (err: unknown) => {
|
||||
|
||||
/** GET /api/dev/skills?active=true — list picker rows. */
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const active = req.nextUrl.searchParams.get("active") !== "false";
|
||||
const rows = await listSkills({ active });
|
||||
return new Response(JSON.stringify({ rows }), {
|
||||
@@ -105,6 +109,9 @@ export const GET = async (req: NextRequest) => {
|
||||
|
||||
/** POST /api/dev/skills { ...createFields } — create (slug + dedupe_key generated). */
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") return bad("invalid body");
|
||||
const parsed = skillCreateSchema.safeParse(body);
|
||||
@@ -122,6 +129,9 @@ export const POST = async (req: NextRequest) => {
|
||||
* `slug` and the composing FKs are never accepted here: they freeze after creation.
|
||||
*/
|
||||
export const PATCH = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") return bad("invalid body");
|
||||
const id = idSchema.safeParse((body as { id?: unknown }).id);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { z } from "zod";
|
||||
import { AssessmentError, verifySkillLevel } from "@/db/assessments";
|
||||
import { ASSESSMENT_KINDS } from "@/db/schema";
|
||||
import { SKILL_LEVELS } from "@/domain/assessments";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
@@ -11,7 +12,6 @@ const verifySchema = z.object({
|
||||
skillId: z.string().min(1),
|
||||
/** The level being signed off — validated again by the domain rule. */
|
||||
level: z.enum(SKILL_LEVELS),
|
||||
assessorId: z.string().min(1).nullable().optional(),
|
||||
kind: z.enum(ASSESSMENT_KINDS).optional(),
|
||||
notes: z.string().nullable().optional(),
|
||||
});
|
||||
@@ -66,20 +66,24 @@ const dbError = (err: unknown) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* POST /api/dev/skills/verify { userId, skillId, level, assessorId?, kind?, notes? }
|
||||
* POST /api/dev/skills/verify { userId, skillId, level, kind?, notes? }
|
||||
*
|
||||
* The verify-level modal's save: appends a `skill_assessments` row and moves
|
||||
* `user_skills.verified_level` in one transaction. The volunteer's
|
||||
* `self_comfort` is untouched (C2's signal is not the gate).
|
||||
* `self_comfort` is untouched (C2's signal is not the gate). The assessor is
|
||||
* the signed-in admin — the client cannot name someone else as the sign-off.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("training.author");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") return bad("invalid body");
|
||||
const parsed = verifySchema.safeParse(body);
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
|
||||
try {
|
||||
const result = await verifySkillLevel(parsed.data);
|
||||
const result = await verifySkillLevel({ ...parsed.data, assessorId: gate.id });
|
||||
return ok(result);
|
||||
} catch (err) {
|
||||
if (err instanceof AssessmentError) return bad(err.problems.join("; "));
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import {
|
||||
checkArchiveDestination,
|
||||
getStorageSettings,
|
||||
saveStorageSettings,
|
||||
type StorageSettings,
|
||||
} from "@/db/storage-settings";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
|
||||
const storageSchema = z.object({
|
||||
nfsShare: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(255)
|
||||
.refine((value) => !/[\r\n]/.test(value), "Invalid NFS share"),
|
||||
archivePath: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(500)
|
||||
.refine((value) => value.startsWith("/"), "Archive path must be absolute"),
|
||||
archiveFolder: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(120)
|
||||
.refine(
|
||||
(value) => !value.includes("/") && !value.includes("\\") && value !== "..",
|
||||
"Archive folder must be one safe folder name",
|
||||
),
|
||||
});
|
||||
|
||||
function publicSettings(settings: StorageSettings) {
|
||||
return {
|
||||
nfsShare: settings.nfsShare,
|
||||
archivePath: settings.archivePath,
|
||||
archiveFolder: settings.archiveFolder,
|
||||
};
|
||||
}
|
||||
|
||||
/** GET /api/dev/storage — NFS/archive destination and mount readiness. */
|
||||
export const GET = async () => {
|
||||
const gate = await gateOrUser("admin.settings");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const settings = await getStorageSettings();
|
||||
return jsonResponse({
|
||||
settings: publicSettings(settings),
|
||||
status: await checkArchiveDestination(settings),
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* PUT /api/dev/storage
|
||||
* { nfsShare, archivePath, archiveFolder }
|
||||
*
|
||||
* The path must already be mounted into the container. Saving does not mount
|
||||
* NFS; it records the operator's chosen export and the visible mount path, then
|
||||
* verifies the path is a writable directory.
|
||||
*/
|
||||
export const PUT = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("admin.settings");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const parsed = storageSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return errorResponse(
|
||||
400,
|
||||
parsed.error.issues[0]?.message ?? "Invalid storage settings",
|
||||
);
|
||||
}
|
||||
|
||||
const before = await getStorageSettings();
|
||||
const settings = await saveStorageSettings(parsed.data);
|
||||
const status = await checkArchiveDestination(settings);
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: "settings.storage.updated",
|
||||
entityType: "app_settings",
|
||||
entityId: "storage",
|
||||
before: publicSettings(before),
|
||||
after: { ...publicSettings(settings), ready: status.ready },
|
||||
});
|
||||
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
settings: publicSettings(settings),
|
||||
status,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,160 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { unlink } from "node:fs/promises";
|
||||
import { auth } from "@/auth/config";
|
||||
import { AuthError, hasPermission, requirePermission } from "@/auth/permissions";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import {
|
||||
createLesson,
|
||||
deleteLesson,
|
||||
listLessons,
|
||||
listResourceStoredNames,
|
||||
updateLesson,
|
||||
} from "@/db/training";
|
||||
import { uploadPath } from "@/lib/uploads";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
const lessonCreateSchema = z.object({
|
||||
title: z.string().min(1).max(200),
|
||||
summary: z.string().max(1000).nullable().optional(),
|
||||
body: z.string().max(100_000).optional(),
|
||||
published: z.boolean().optional(),
|
||||
sortOrder: z.number().int().min(0).max(999).optional(),
|
||||
});
|
||||
|
||||
const lessonPatchSchema = lessonCreateSchema.partial().extend({
|
||||
id: z.string().min(1),
|
||||
});
|
||||
|
||||
function authFailure(e: AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
async function sessionUser() {
|
||||
const session = await auth();
|
||||
return session?.user as
|
||||
| { id: string; systemRole: SystemRole }
|
||||
| null
|
||||
| undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Training lessons (F2 authoring). Reads are for any signed-in volunteer and
|
||||
* hide unpublished drafts unless the caller can author. Writes require
|
||||
* `training.author` (admin).
|
||||
*
|
||||
* GET -> { lessons }
|
||||
* POST -> { lesson } create
|
||||
* PATCH -> { lesson } edit / publish toggle
|
||||
* DELETE ?id= -> { ok } removes the lesson, its rows, and its files
|
||||
*/
|
||||
export const GET = async () => {
|
||||
const user = await sessionUser();
|
||||
if (!user) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }),
|
||||
{ status: 401, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
const canAuthor = hasPermission(user.systemRole, "training.author");
|
||||
return new Response(
|
||||
JSON.stringify({ lessons: await listLessons({ includeUnpublished: canAuthor }) }),
|
||||
{ status: 200, headers: JSON_HEADERS },
|
||||
);
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest) => {
|
||||
try {
|
||||
await requirePermission(await sessionUser(), "training.author");
|
||||
const body = await req.json().catch(() => null);
|
||||
const parsed = lessonCreateSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return new Response(JSON.stringify({ error: parsed.error.message }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const lesson = await createLesson(parsed.data);
|
||||
return new Response(JSON.stringify({ lesson }), {
|
||||
status: 201,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) return authFailure(e);
|
||||
return new Response(JSON.stringify({ error: "failed to create lesson" }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const PATCH = async (req: NextRequest) => {
|
||||
try {
|
||||
await requirePermission(await sessionUser(), "training.author");
|
||||
const body = await req.json().catch(() => null);
|
||||
const parsed = lessonPatchSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return new Response(JSON.stringify({ error: parsed.error.message }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const { id, ...patch } = parsed.data;
|
||||
const lesson = await updateLesson(id, patch);
|
||||
if (!lesson) {
|
||||
return new Response(JSON.stringify({ error: "unknown lesson" }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ lesson }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) return authFailure(e);
|
||||
return new Response(JSON.stringify({ error: "failed to update lesson" }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const DELETE = async (req: NextRequest) => {
|
||||
try {
|
||||
await requirePermission(await sessionUser(), "training.author");
|
||||
const id = req.nextUrl.searchParams.get("id");
|
||||
if (!id) {
|
||||
return new Response(JSON.stringify({ error: "an id is required" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const files = await listResourceStoredNames(id);
|
||||
const deleted = await deleteLesson(id);
|
||||
if (!deleted) {
|
||||
return new Response(JSON.stringify({ error: "unknown lesson" }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
// Metadata cascades; remove the bytes best-effort.
|
||||
for (const storedName of files) {
|
||||
await unlink(uploadPath(storedName)).catch(() => undefined);
|
||||
}
|
||||
return new Response(JSON.stringify({ ok: true }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) return authFailure(e);
|
||||
return new Response(JSON.stringify({ error: "failed to delete lesson" }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,146 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { unlink, writeFile } from "node:fs/promises";
|
||||
import { auth } from "@/auth/config";
|
||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import { addResource, deleteResource, getLesson, getResource } from "@/db/training";
|
||||
import {
|
||||
MAX_UPLOAD_BYTES,
|
||||
ensureUploadDir,
|
||||
isAllowedUpload,
|
||||
storedNameFor,
|
||||
uploadPath,
|
||||
uploadSignatureMatches,
|
||||
} from "@/lib/uploads";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
function authFailure(e: AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
async function requireAuthor() {
|
||||
const session = await auth();
|
||||
return requirePermission(
|
||||
(session?.user as { id: string; systemRole: SystemRole } | null | undefined),
|
||||
"training.author",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Training attachments. Bytes go to `UPLOAD_DIR` (a named volume in the
|
||||
* deployment) and only metadata is stored in Postgres, so the database never
|
||||
* carries binaries.
|
||||
*
|
||||
* POST multipart { lessonId, file } -> { resource }
|
||||
* DELETE ?id= -> { ok }
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
try {
|
||||
const user = await requireAuthor();
|
||||
const form = await req.formData();
|
||||
const lessonId = form.get("lessonId");
|
||||
const file = form.get("file");
|
||||
|
||||
if (typeof lessonId !== "string" || !lessonId) {
|
||||
return new Response(JSON.stringify({ error: "a lessonId is required" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
if (!file || typeof file === "string") {
|
||||
return new Response(JSON.stringify({ error: "a file is required" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
if (!(await getLesson(lessonId))) {
|
||||
return new Response(JSON.stringify({ error: "unknown lesson" }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
if (file.size > MAX_UPLOAD_BYTES) {
|
||||
return new Response(JSON.stringify({ error: "file is larger than 5 MB" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const mimeType = file.type || "application/octet-stream";
|
||||
if (!isAllowedUpload(mimeType)) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: `file type not allowed: ${mimeType}` }),
|
||||
{ status: 400, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
if (!uploadSignatureMatches(mimeType, bytes)) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: `file contents do not match the declared type: ${mimeType}`,
|
||||
}),
|
||||
{ status: 400, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
|
||||
await ensureUploadDir();
|
||||
const storedName = storedNameFor(file.name, uuidv7());
|
||||
await writeFile(uploadPath(storedName), bytes);
|
||||
|
||||
const resource = await addResource({
|
||||
lessonId,
|
||||
filename: file.name || storedName,
|
||||
mimeType,
|
||||
sizeBytes: file.size,
|
||||
storedName,
|
||||
});
|
||||
void user;
|
||||
return new Response(JSON.stringify({ resource }), {
|
||||
status: 201,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) return authFailure(e);
|
||||
return new Response(JSON.stringify({ error: "failed to upload file" }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const DELETE = async (req: NextRequest) => {
|
||||
try {
|
||||
await requireAuthor();
|
||||
const id = req.nextUrl.searchParams.get("id");
|
||||
if (!id) {
|
||||
return new Response(JSON.stringify({ error: "an id is required" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
const resource = await getResource(id);
|
||||
if (!resource) {
|
||||
return new Response(JSON.stringify({ error: "unknown resource" }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
await deleteResource(id);
|
||||
await unlink(uploadPath(resource.storedName)).catch(() => undefined);
|
||||
return new Response(JSON.stringify({ ok: true }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) return authFailure(e);
|
||||
return new Response(JSON.stringify({ error: "failed to delete file" }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,7 +1,10 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateSelfOr, gateSession } from "@/auth/api";
|
||||
import { hasPermission } from "@/auth/permissions";
|
||||
import {
|
||||
listUnavailability,
|
||||
getUnavailability,
|
||||
createUnavailability,
|
||||
updateUnavailability,
|
||||
cancelUnavailability,
|
||||
@@ -87,10 +90,27 @@ const constraintError = (err: unknown): Response | null => {
|
||||
return null;
|
||||
};
|
||||
|
||||
/** GET /api/dev/unavailability?userId=... — list blackouts (one per user). */
|
||||
/**
|
||||
* GET /api/dev/unavailability?userId=... — list blackouts.
|
||||
* A volunteer sees their own; a leader (`schedule.publish`) may see anyone's
|
||||
* or, with no `userId`, the whole team's.
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const userId = req.nextUrl.searchParams.get("userId") ?? undefined;
|
||||
const rows = await listUnavailability({ userId });
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const requested = req.nextUrl.searchParams.get("userId") ?? undefined;
|
||||
const canManage = hasPermission(gate.systemRole, "schedule.publish");
|
||||
if (requested && requested !== gate.id && !canManage) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "not permitted to view another person's blackouts" }),
|
||||
{ status: 403, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
|
||||
const rows = await listUnavailability({
|
||||
userId: requested ?? (canManage ? undefined : gate.id),
|
||||
});
|
||||
return new Response(JSON.stringify({ rows }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
@@ -105,8 +125,14 @@ export const POST = async (req: NextRequest) => {
|
||||
}
|
||||
const parsed = unavailabilityCreateSchema.safeParse(body);
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
|
||||
const gate = await gateSelfOr("schedule.publish", parsed.data.userId);
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
try {
|
||||
return created(await createUnavailability(parsed.data));
|
||||
return created(
|
||||
await createUnavailability({ ...parsed.data, createdBy: gate.id }),
|
||||
);
|
||||
} catch (err) {
|
||||
const constraint = constraintError(err);
|
||||
if (constraint) return constraint;
|
||||
@@ -126,6 +152,12 @@ export const PATCH = async (req: NextRequest) => {
|
||||
const id = idSchema.safeParse((body as { id?: unknown }).id);
|
||||
if (!id.success) return bad("invalid id");
|
||||
|
||||
const existing = await getUnavailability(id.data);
|
||||
if (!existing) return bad("blackout not found");
|
||||
|
||||
const gate = await gateSelfOr("schedule.publish", existing.userId);
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
// Cancel path: explicit status cancelled.
|
||||
if ((body as { status?: unknown }).status === "cancelled") {
|
||||
const row = await cancelUnavailability(id.data);
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { getUserSkills, setSelfComfort } from "@/db/userSkills";
|
||||
import { gateOrUser, gateSelfOr } from "@/auth/api";
|
||||
import { AssessmentError, verifySkillLevel } from "@/db/assessments";
|
||||
import {
|
||||
addUserSkill,
|
||||
deleteUserSkill,
|
||||
getUserSkill,
|
||||
getUserSkills,
|
||||
setMentorApproval,
|
||||
setSelfComfort,
|
||||
} from "@/db/userSkills";
|
||||
import { SKILL_LEVELS } from "@/domain/assessments";
|
||||
import { validateSelfComfort } from "@/domain/userSkills";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
@@ -15,6 +25,19 @@ const selfComfortCreateSchema = z.object({
|
||||
selfComfort: z.number().int().nullable().optional(),
|
||||
});
|
||||
|
||||
/** An admin setting one person's verified level and/or mentor sign-off. */
|
||||
const levelPatchSchema = z
|
||||
.object({
|
||||
userId: z.string().min(1),
|
||||
skillId: z.string().min(1),
|
||||
verifiedLevel: z.enum(SKILL_LEVELS).optional(),
|
||||
mentorApproved: z.boolean().optional(),
|
||||
})
|
||||
.refine(
|
||||
(value) => value.verifiedLevel !== undefined || value.mentorApproved !== undefined,
|
||||
{ message: "nothing to update" },
|
||||
);
|
||||
|
||||
async function readBody(req: NextRequest) {
|
||||
try {
|
||||
return await req.json();
|
||||
@@ -70,8 +93,23 @@ const dbError = (err: unknown) => {
|
||||
});
|
||||
};
|
||||
|
||||
/** GET /api/dev/user-skills?userId=<id> — a volunteer's competency records. */
|
||||
/**
|
||||
* Competency records (`user_skills`).
|
||||
*
|
||||
* GET ?userId= -> { rows } (signed in)
|
||||
* POST { userId, skillId, selfComfort } -> { row } volunteer slider: comfort only
|
||||
* PATCH { userId, skillId, verifiedLevel } -> { row } admin: audited level move
|
||||
* DELETE ?userId= &skillId= -> { row } admin: remove the entry
|
||||
*
|
||||
* The level path never writes `verified_level` directly: an existing record
|
||||
* moves through `verifySkillLevel`, which appends a `skill_assessments` row in
|
||||
* the same transaction. The one exception is adding a skill at `none` — the
|
||||
* bottom of the ladder — which creates the record with nothing to audit.
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("schedule.view");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const userId = idSchema.safeParse(req.nextUrl.searchParams.get("userId"));
|
||||
if (!userId.success) return bad("invalid userId");
|
||||
const rows = await getUserSkills(userId.data);
|
||||
@@ -79,15 +117,22 @@ export const GET = async (req: NextRequest) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* POST /api/dev/user-skills { userId, skillId, selfComfort } — set a
|
||||
* volunteer's self-reported comfort (the profile slider). Only
|
||||
* self_comfort / self_rated_at change; verified_level is never touched.
|
||||
* POST { userId, skillId, selfComfort } — set a volunteer's self-reported
|
||||
* comfort (the profile slider). Only self_comfort / self_rated_at change;
|
||||
* verified_level is never touched.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("schedule.view");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const body = await readBody(req);
|
||||
if (!body || typeof body !== "object") return bad("invalid body");
|
||||
const parsed = selfComfortCreateSchema.safeParse(body);
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
// A volunteer may rate only their own comfort; admins may correct another
|
||||
// person's record through this same path when needed.
|
||||
const selfGate = await gateSelfOr("users.manage", parsed.data.userId);
|
||||
if (selfGate instanceof Response) return selfGate;
|
||||
const selfComfort = parsed.data.selfComfort ?? null;
|
||||
const problems = validateSelfComfort(selfComfort);
|
||||
if (problems.length > 0) return bad(problems[0]);
|
||||
@@ -98,3 +143,86 @@ export const POST = async (req: NextRequest) => {
|
||||
return dbError(err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* PATCH { userId, skillId, verifiedLevel } — the admin's per-person level edit.
|
||||
*
|
||||
* A missing record is created at `none` (the default level) or, when a higher
|
||||
* level is requested, through the audited verify path. An existing record always
|
||||
* moves through the verify path, so demotions are recorded too.
|
||||
*/
|
||||
export const PATCH = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("users.manage");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const parsed = levelPatchSchema.safeParse(await readBody(req));
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
const { userId, skillId, verifiedLevel, mentorApproved } = parsed.data;
|
||||
|
||||
try {
|
||||
const existing = await getUserSkill(userId, skillId);
|
||||
let row = existing;
|
||||
|
||||
if (!existing) {
|
||||
if (!verifiedLevel || verifiedLevel === "none") {
|
||||
row = await addUserSkill(userId, skillId);
|
||||
} else {
|
||||
const result = await verifySkillLevel({
|
||||
userId,
|
||||
skillId,
|
||||
level: verifiedLevel,
|
||||
assessorId: gate.id,
|
||||
kind: "admin",
|
||||
});
|
||||
row = result.userSkill;
|
||||
}
|
||||
} else if (verifiedLevel !== undefined) {
|
||||
if (existing.verifiedLevel === verifiedLevel) {
|
||||
return bad("level is unchanged — nothing to assess");
|
||||
}
|
||||
const result = await verifySkillLevel({
|
||||
userId,
|
||||
skillId,
|
||||
level: verifiedLevel,
|
||||
assessorId: gate.id,
|
||||
kind: "admin",
|
||||
});
|
||||
row = result.userSkill;
|
||||
}
|
||||
|
||||
if (mentorApproved !== undefined) {
|
||||
row = await setMentorApproval(
|
||||
userId,
|
||||
skillId,
|
||||
mentorApproved,
|
||||
gate.id,
|
||||
);
|
||||
}
|
||||
|
||||
return ok(row);
|
||||
} catch (err) {
|
||||
if (err instanceof AssessmentError) return bad(err.problems.join("; "));
|
||||
return dbError(err);
|
||||
}
|
||||
};
|
||||
|
||||
/** DELETE ?userId= &skillId= — remove one competency record. */
|
||||
export const DELETE = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("users.manage");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const userId = idSchema.safeParse(req.nextUrl.searchParams.get("userId"));
|
||||
const skillId = idSchema.safeParse(req.nextUrl.searchParams.get("skillId"));
|
||||
if (!userId.success || !skillId.success) {
|
||||
return bad("userId and skillId are required");
|
||||
}
|
||||
|
||||
const row = await deleteUserSkill(userId.data, skillId.data);
|
||||
if (!row) {
|
||||
return new Response(JSON.stringify({ error: "unknown competency record" }), {
|
||||
status: 404,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
return ok({ ok: true });
|
||||
};
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import {
|
||||
APP_ORIGIN,
|
||||
requestOrigin,
|
||||
sendMagicLinkEmail,
|
||||
signMagicToken,
|
||||
} from "@/auth/magic-link";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import { getUserById } from "@/db/users";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
const json = (payload: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS });
|
||||
|
||||
const bodySchema = z.object({
|
||||
userId: z.string().min(1),
|
||||
deliver: z.boolean().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Admin emergency magic link (`users.manage`).
|
||||
*
|
||||
* { userId, deliver?: false } -> return a fresh 10-minute sign-in URL
|
||||
* { userId, deliver: true } -> also send that URL through the configured
|
||||
* email transport
|
||||
*
|
||||
* The URL is always returned so an admin can copy it when mail delivery is
|
||||
* unavailable. Only active, non-deactivated accounts are eligible; otherwise
|
||||
* the link would be rejected by the sign-in provider anyway.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("users.manage");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return json({ error: "A JSON body is required." }, 400);
|
||||
}
|
||||
const parsed = bodySchema.safeParse(body);
|
||||
if (!parsed.success) return json({ error: parsed.error.message }, 400);
|
||||
|
||||
const user = await getUserById(parsed.data.userId);
|
||||
if (!user) return json({ error: "unknown user" }, 404);
|
||||
if (user.status !== "active" || user.deactivatedAt !== null) {
|
||||
return json(
|
||||
{ error: "This account is not active — activate it first." },
|
||||
409,
|
||||
);
|
||||
}
|
||||
|
||||
const token = await signMagicToken(user.email);
|
||||
const origin = requestOrigin(req) || APP_ORIGIN;
|
||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||
token,
|
||||
)}&email=${encodeURIComponent(user.email)}`;
|
||||
|
||||
const delivery = parsed.data.deliver
|
||||
? await sendMagicLinkEmail(user, url)
|
||||
: null;
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: parsed.data.deliver
|
||||
? "user.magic_link_sent_by_admin"
|
||||
: "user.magic_link_created_by_admin",
|
||||
entityType: "user",
|
||||
entityId: user.id,
|
||||
after: {
|
||||
expiresInMinutes: 10,
|
||||
delivered: delivery?.delivered ?? false,
|
||||
transport: delivery?.transport ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
return json({
|
||||
ok: true,
|
||||
email: user.email,
|
||||
url,
|
||||
expiresInMinutes: 10,
|
||||
delivered: delivery?.delivered ?? false,
|
||||
transport: delivery?.transport ?? null,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import {
|
||||
APP_ORIGIN,
|
||||
requestOrigin,
|
||||
signPasswordResetToken,
|
||||
} from "@/auth/magic-link";
|
||||
import { hashPassword, validatePassword } from "@/auth/password";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import { getUserById, updateUserCredentials } from "@/db/users";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
const json = (payload: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS });
|
||||
|
||||
const bodySchema = z.discriminatedUnion("action", [
|
||||
z.object({
|
||||
action: z.literal("set"),
|
||||
userId: z.string().min(1),
|
||||
password: z.string().min(1).max(200),
|
||||
}),
|
||||
z.object({
|
||||
action: z.literal("reset-link"),
|
||||
userId: z.string().min(1),
|
||||
}),
|
||||
]);
|
||||
|
||||
/**
|
||||
* Admin password controls (`users.manage`).
|
||||
*
|
||||
* { action: "set", userId, password } -> change the password directly
|
||||
* { action: "reset-link", userId } -> mint a one-hour single-use link
|
||||
*
|
||||
* The link is returned to the admin to hand over; it is deliberately not
|
||||
* emailed automatically so an admin can verify the destination first.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("users.manage");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return json({ error: "A JSON body is required." }, 400);
|
||||
}
|
||||
const parsed = bodySchema.safeParse(body);
|
||||
if (!parsed.success) return json({ error: parsed.error.message }, 400);
|
||||
|
||||
const before = await getUserById(parsed.data.userId);
|
||||
if (!before) return json({ error: "unknown user" }, 404);
|
||||
|
||||
if (parsed.data.action === "set") {
|
||||
const passwordError = validatePassword(parsed.data.password);
|
||||
if (passwordError) return json({ error: passwordError }, 400);
|
||||
|
||||
const passwordHash = await hashPassword(parsed.data.password);
|
||||
const updated = await updateUserCredentials(before.id, { passwordHash });
|
||||
if (!updated) return json({ error: "unknown user" }, 404);
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: "user.password_set_by_admin",
|
||||
entityType: "user",
|
||||
entityId: before.id,
|
||||
after: { passwordSet: true },
|
||||
});
|
||||
|
||||
return json({ ok: true });
|
||||
}
|
||||
|
||||
const token = await signPasswordResetToken(before.email);
|
||||
const origin = requestOrigin(req) || APP_ORIGIN;
|
||||
const url = `${origin}/reset-password?token=${encodeURIComponent(token)}`;
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: "user.password_reset_link_created",
|
||||
entityType: "user",
|
||||
entityId: before.id,
|
||||
after: { expiresInMinutes: 60 },
|
||||
});
|
||||
|
||||
return json({ ok: true, url, expiresInMinutes: 60 });
|
||||
};
|
||||
@@ -0,0 +1,276 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link";
|
||||
import { validateUsername } from "@/auth/password";
|
||||
import { SYSTEM_ROLES } from "@/auth/roles";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import { USER_STATUSES } from "@/db/schema";
|
||||
import { hasEventUploads } from "@/db/events";
|
||||
import {
|
||||
countOtherActiveAdmins,
|
||||
createUser,
|
||||
credentialTaken,
|
||||
deleteUser,
|
||||
getUserById,
|
||||
hasAssignmentHistory,
|
||||
listUsersForAdmin,
|
||||
updateUser,
|
||||
} from "@/db/users";
|
||||
import { isActiveAdmin, removalPlan, wouldLeaveNoAdmin } from "@/domain/users";
|
||||
import { sendWelcomeEmail } from "@/lib/welcome-email";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
const json = (payload: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS });
|
||||
|
||||
const bad = (message: string) => json({ error: message }, 400);
|
||||
const conflict = (message: string) => json({ error: message }, 409);
|
||||
|
||||
const userCreateSchema = z.object({
|
||||
email: z.string().email(),
|
||||
username: z.string().min(1).max(100).optional(),
|
||||
firstName: z.string().min(1).max(80),
|
||||
lastName: z.string().max(80).optional(),
|
||||
displayName: z.string().max(120).nullable().optional(),
|
||||
phoneE164: z.string().max(32).nullable().optional(),
|
||||
systemRole: z.enum(SYSTEM_ROLES),
|
||||
status: z.enum(USER_STATUSES).optional(),
|
||||
timezone: z.string().min(1).max(64).optional(),
|
||||
emergencyContact: z.string().max(200).nullable().optional(),
|
||||
notes: z.string().max(2000).nullable().optional(),
|
||||
});
|
||||
|
||||
const userPatchSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
email: z.string().email().optional(),
|
||||
username: z.string().min(1).max(100).optional(),
|
||||
firstName: z.string().min(1).max(80).optional(),
|
||||
lastName: z.string().max(80).optional(),
|
||||
displayName: z.string().max(120).nullable().optional(),
|
||||
phoneE164: z.string().max(32).nullable().optional(),
|
||||
systemRole: z.enum(SYSTEM_ROLES).optional(),
|
||||
status: z.enum(USER_STATUSES).optional(),
|
||||
timezone: z.string().min(1).max(64).optional(),
|
||||
emergencyContact: z.string().max(200).nullable().optional(),
|
||||
notes: z.string().max(2000).nullable().optional(),
|
||||
/** Convenience flag: true sets `deactivated_at`, false clears it. */
|
||||
deactivated: z.boolean().optional(),
|
||||
});
|
||||
|
||||
async function readBody(req: NextRequest) {
|
||||
try {
|
||||
return await req.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Walk the cause chain for a Postgres SQLSTATE (pg nests it under `cause`). */
|
||||
function pgCode(err: unknown): string | undefined {
|
||||
let node = err as { code?: string; cause?: unknown } | null;
|
||||
while (node) {
|
||||
if (typeof node.code === "string") return node.code;
|
||||
node = (node.cause as { code?: string; cause?: unknown } | null) ?? null;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* User administration (admin-only, `users.manage`).
|
||||
*
|
||||
* GET -> { users } every account, full editable record
|
||||
* POST -> { user, url, welcome } create (active, or pending approval)
|
||||
* PATCH -> { user } edit any field / deactivate
|
||||
* DELETE ?id= -> { ok } hard delete when the person has no
|
||||
* scheduling history
|
||||
*
|
||||
* Every mutation writes an audit row. Two safety rules live in
|
||||
* `src/domain/users.ts` and are enforced here: the last active admin can never
|
||||
* be demoted, deactivated or deleted, and someone who has served is
|
||||
* deactivated rather than deleted so past weeks stay readable.
|
||||
*/
|
||||
export const GET = async () => {
|
||||
const gate = await gateOrUser("users.manage");
|
||||
if (gate instanceof Response) return gate;
|
||||
return json({ users: await listUsersForAdmin() });
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("users.manage");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const parsed = userCreateSchema.safeParse(await readBody(req));
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
|
||||
if (parsed.data.username) {
|
||||
const usernameError = validateUsername(parsed.data.username);
|
||||
if (usernameError) return bad(usernameError);
|
||||
if (await credentialTaken(parsed.data.username)) {
|
||||
return conflict("that username is already in use");
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await createUser(parsed.data);
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: "user.created",
|
||||
entityType: "user",
|
||||
entityId: user.id,
|
||||
after: {
|
||||
email: user.email,
|
||||
systemRole: user.systemRole,
|
||||
status: user.status,
|
||||
},
|
||||
});
|
||||
|
||||
// Hand the admin a sign-in link, exactly like the invite flow does. The
|
||||
// link only works once the account is active.
|
||||
const token = await signMagicToken(user.email);
|
||||
const origin = requestOrigin(req) || APP_ORIGIN;
|
||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||
token,
|
||||
)}&email=${encodeURIComponent(user.email)}`;
|
||||
|
||||
// A new active account gets its sign-in details by email. Pending accounts
|
||||
// are mailed when they are approved, when the link can actually work.
|
||||
const welcome =
|
||||
user.status === "active" && user.deactivatedAt === null
|
||||
? await sendWelcomeEmail(user, url)
|
||||
: null;
|
||||
|
||||
return json({ user, url, welcome }, 201);
|
||||
} catch (err) {
|
||||
if (pgCode(err) === "23505") {
|
||||
return conflict("a user with this email already exists");
|
||||
}
|
||||
return json({ error: "failed to create user" }, 500);
|
||||
}
|
||||
};
|
||||
|
||||
export const PATCH = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("users.manage");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const parsed = userPatchSchema.safeParse(await readBody(req));
|
||||
if (!parsed.success) return bad(parsed.error.message);
|
||||
|
||||
const { id, deactivated, ...fields } = parsed.data;
|
||||
const before = await getUserById(id);
|
||||
if (!before) return json({ error: "unknown user" }, 404);
|
||||
|
||||
if (fields.username !== undefined) {
|
||||
const usernameError = validateUsername(fields.username);
|
||||
if (usernameError) return bad(usernameError);
|
||||
if (await credentialTaken(fields.username, id)) {
|
||||
return conflict("that username is already in use");
|
||||
}
|
||||
}
|
||||
if (fields.email !== undefined && fields.email !== before.email) {
|
||||
if (await credentialTaken(fields.email, id)) {
|
||||
return conflict("that email is already used as a username or email");
|
||||
}
|
||||
}
|
||||
|
||||
const nextRole = fields.systemRole ?? before.systemRole;
|
||||
const nextStatus = fields.status ?? before.status;
|
||||
const nextDeactivated =
|
||||
deactivated === undefined ? before.deactivatedAt !== null : deactivated;
|
||||
const nextEligible = nextStatus === "active" && !nextDeactivated;
|
||||
|
||||
const otherActiveAdmins = await countOtherActiveAdmins(id);
|
||||
if (
|
||||
wouldLeaveNoAdmin({
|
||||
targetIsActiveAdmin: isActiveAdmin(before),
|
||||
nextRole,
|
||||
nextEligible,
|
||||
otherActiveAdmins,
|
||||
})
|
||||
) {
|
||||
return conflict("the last active admin cannot be demoted or deactivated");
|
||||
}
|
||||
|
||||
const patch = {
|
||||
...fields,
|
||||
...(deactivated === undefined
|
||||
? {}
|
||||
: { deactivatedAt: deactivated ? new Date() : null }),
|
||||
};
|
||||
|
||||
try {
|
||||
const user = await updateUser(id, patch);
|
||||
if (!user) return json({ error: "unknown user" }, 404);
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: "user.updated",
|
||||
entityType: "user",
|
||||
entityId: id,
|
||||
before: {
|
||||
email: before.email,
|
||||
systemRole: before.systemRole,
|
||||
status: before.status,
|
||||
deactivated: before.deactivatedAt !== null,
|
||||
},
|
||||
after: {
|
||||
email: user.email,
|
||||
systemRole: user.systemRole,
|
||||
status: user.status,
|
||||
deactivated: user.deactivatedAt !== null,
|
||||
},
|
||||
});
|
||||
|
||||
return json({ user });
|
||||
} catch (err) { if (pgCode(err) === "23505") {
|
||||
return conflict("a user with this email or username already exists");
|
||||
}
|
||||
return json({ error: "failed to update user" }, 500);
|
||||
}
|
||||
};
|
||||
|
||||
export const DELETE = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("users.manage");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const id = req.nextUrl.searchParams.get("id");
|
||||
if (!id) return bad("an id is required");
|
||||
|
||||
const before = await getUserById(id);
|
||||
if (!before) return json({ error: "unknown user" }, 404);
|
||||
|
||||
if (isActiveAdmin(before) && (await countOtherActiveAdmins(id)) === 0) {
|
||||
return conflict("the last active admin cannot be deleted");
|
||||
}
|
||||
|
||||
const plan = removalPlan({
|
||||
hasAssignmentHistory: await hasAssignmentHistory(id),
|
||||
hasEventUploads: await hasEventUploads(id),
|
||||
});
|
||||
if (!plan.allowed) return conflict(plan.reason);
|
||||
|
||||
try {
|
||||
await deleteUser(id);
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: "user.deleted",
|
||||
entityType: "user",
|
||||
entityId: id,
|
||||
before: {
|
||||
email: before.email,
|
||||
systemRole: before.systemRole,
|
||||
status: before.status,
|
||||
},
|
||||
});
|
||||
return json({ ok: true });
|
||||
} catch (err) {
|
||||
// Assignment/upload rows are ON DELETE RESTRICT; the checks above should
|
||||
// have caught this, but the database is the last word.
|
||||
if (pgCode(err) === "23503") {
|
||||
return conflict("this person has history and cannot be deleted — deactivate them instead");
|
||||
}
|
||||
return json({ error: "failed to delete user" }, 500);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,120 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import {
|
||||
deleteEvent,
|
||||
getEventAccess,
|
||||
listEventPhotosForArchive,
|
||||
} from "@/db/events";
|
||||
import { listEventVideos } from "@/db/videos";
|
||||
import { eventVideoUploadDir } from "@/lib/event-videos";
|
||||
import {
|
||||
checkArchiveDestination,
|
||||
getStorageSettings,
|
||||
} from "@/db/storage-settings";
|
||||
import {
|
||||
archiveEventPhotos,
|
||||
EventArchiveError,
|
||||
} from "@/lib/event-nfs-archive";
|
||||
import { eventPhotoDir } from "@/lib/event-photos";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
|
||||
/**
|
||||
* POST /api/events/:id/archive
|
||||
*
|
||||
* Manager-only. Copies every original and saved edit to the configured NFS
|
||||
* mount, writes a manifest, then deletes the database rows and the live upload
|
||||
* directory. The event is only removed after the archive rename succeeds.
|
||||
*/
|
||||
export const POST = async (
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const gate = await gateOrUser("schedule.publish");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id } = await params;
|
||||
const access = await getEventAccess(id, gate.id, gate.systemRole);
|
||||
if (!access) return errorResponse(404, "unknown event");
|
||||
if (!access.canManage) {
|
||||
return errorResponse(403, "only an event manager may archive this event");
|
||||
}
|
||||
|
||||
const storage = await getStorageSettings();
|
||||
const status = await checkArchiveDestination(storage);
|
||||
if (!status.ready) {
|
||||
return errorResponse(
|
||||
409,
|
||||
`${status.message} Configure the NFS archive in Settings first.`,
|
||||
);
|
||||
}
|
||||
|
||||
const photos = await listEventPhotosForArchive(id);
|
||||
const videos = await listEventVideos(id);
|
||||
let archived;
|
||||
try {
|
||||
archived = await archiveEventPhotos({
|
||||
eventId: id,
|
||||
title: access.event.title,
|
||||
startsAt: access.event.startsAt,
|
||||
endsAt: access.event.endsAt,
|
||||
location: access.event.location,
|
||||
description: access.event.description,
|
||||
archivePath: storage.archivePath,
|
||||
archiveFolder: storage.archiveFolder,
|
||||
nfsShare: storage.nfsShare,
|
||||
photos,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof EventArchiveError) {
|
||||
return errorResponse(409, error.message);
|
||||
}
|
||||
console.error(`event ${id}: archive failed`, error);
|
||||
return errorResponse(500, "the event could not be archived");
|
||||
}
|
||||
|
||||
const deleted = await deleteEvent(id);
|
||||
if (!deleted) {
|
||||
return errorResponse(
|
||||
500,
|
||||
"the archive was written, but the event rows could not be removed",
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await rm(eventPhotoDir(id), { recursive: true, force: true });
|
||||
await rm(eventVideoUploadDir(id), { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
console.error(`event ${id}: archived but live files remain`, error);
|
||||
}
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: "event.archived",
|
||||
entityType: "event",
|
||||
entityId: id,
|
||||
before: {
|
||||
title: deleted.event.title,
|
||||
startsAt: deleted.event.startsAt.toISOString(),
|
||||
photoCount: deleted.photoCount,
|
||||
videoCount: videos.length,
|
||||
},
|
||||
after: {
|
||||
archivePath: archived.archivePath,
|
||||
nfsShare: storage.nfsShare || null,
|
||||
files: archived.files,
|
||||
bytes: archived.bytes,
|
||||
deleted: true,
|
||||
videoOriginalsKeptOnNfs: videos.length,
|
||||
},
|
||||
});
|
||||
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
archivePath: archived.archivePath,
|
||||
files: archived.files,
|
||||
bytes: archived.bytes,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,122 @@
|
||||
import { ZipArchive } from "archiver";
|
||||
import { NextRequest } from "next/server";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { PassThrough, Readable } from "node:stream";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getEventAccess, listEventPhotosForArchive } from "@/db/events";
|
||||
import { assignArchivePaths, eventArchiveFilename } from "@/lib/event-archive";
|
||||
import {
|
||||
editedPhotoFilename,
|
||||
eventPhotoPath,
|
||||
photoContentDisposition,
|
||||
} from "@/lib/event-photos";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
/**
|
||||
* GET /api/events/:id/download
|
||||
*
|
||||
* Streams every photo on the event as one ZIP, preserving folder names. Saved
|
||||
* edits are included beside their originals as `<name>-edited.jpg`. The
|
||||
* archive is store-only: JPEGs and camera RAW files are already compressed, so
|
||||
* deflating them would add CPU and latency without shrinking the download.
|
||||
* Anyone assigned to the event (or a manager) can download it.
|
||||
*/
|
||||
export const GET = async (
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id } = await params;
|
||||
const access = await getEventAccess(id, gate.id, gate.systemRole);
|
||||
if (!access) return errorResponse(404, "unknown event");
|
||||
|
||||
const photos = await listEventPhotosForArchive(id);
|
||||
if (photos.length === 0) {
|
||||
return errorResponse(404, "this event has no photos");
|
||||
}
|
||||
|
||||
// Originals claim their names first, then generated edits join the same
|
||||
// folder. A real upload named `photo-edited.jpg` therefore keeps its name and
|
||||
// the generated version is numbered instead.
|
||||
const entries: {
|
||||
key: string;
|
||||
folderName: string;
|
||||
filename: string;
|
||||
storedName: string;
|
||||
}[] = [];
|
||||
for (const photo of photos) {
|
||||
entries.push({
|
||||
key: `${photo.id}:original`,
|
||||
folderName: photo.folderName,
|
||||
filename: photo.filename,
|
||||
storedName: photo.storedName,
|
||||
});
|
||||
}
|
||||
for (const photo of photos) {
|
||||
if (!photo.editedStoredName) continue;
|
||||
entries.push({
|
||||
key: `${photo.id}:edited`,
|
||||
folderName: photo.folderName,
|
||||
filename: editedPhotoFilename(photo.filename),
|
||||
storedName: photo.editedStoredName,
|
||||
});
|
||||
}
|
||||
|
||||
const names = assignArchivePaths(
|
||||
entries.map((entry) => ({
|
||||
id: entry.key,
|
||||
folderName: entry.folderName,
|
||||
filename: entry.filename,
|
||||
})),
|
||||
);
|
||||
const available: { path: string; name: string }[] = [];
|
||||
for (const entry of entries) {
|
||||
const filePath = eventPhotoPath(entry.storedName);
|
||||
try {
|
||||
const info = await stat(filePath);
|
||||
if (!info.isFile()) continue;
|
||||
available.push({ path: filePath, name: names.get(entry.key)! });
|
||||
} catch {
|
||||
console.warn(`event ${id}: skipping missing archive entry ${entry.key}`);
|
||||
}
|
||||
}
|
||||
if (available.length === 0) {
|
||||
return errorResponse(404, "the event photos are missing from storage");
|
||||
}
|
||||
|
||||
// archiver uses readable-stream, so bridge through a core PassThrough before
|
||||
// handing the response to the Web Streams API.
|
||||
const output = new PassThrough();
|
||||
const archive = new ZipArchive({ store: true });
|
||||
archive.on("warning", (error) => {
|
||||
console.warn(`event ${id}: zip warning`, error);
|
||||
});
|
||||
archive.on("error", (error) => {
|
||||
console.error(`event ${id}: zip failed`, error);
|
||||
output.destroy(error);
|
||||
});
|
||||
archive.pipe(output);
|
||||
|
||||
for (const file of available) {
|
||||
archive.file(file.path, { name: file.name });
|
||||
}
|
||||
void archive.finalize().catch((error) => output.destroy(error));
|
||||
|
||||
return new Response(
|
||||
Readable.toWeb(output) as unknown as ReadableStream<Uint8Array>,
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "application/zip",
|
||||
"content-disposition": photoContentDisposition(
|
||||
eventArchiveFilename(access.event.title),
|
||||
false,
|
||||
),
|
||||
"cache-control": "private, no-store",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,130 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, rename, stat, unlink, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getEventPhotoAccess, updateEventPhotoEdit } from "@/db/events";
|
||||
import {
|
||||
editedPhotoFilename,
|
||||
editedStoredNameForEventPhoto,
|
||||
eventPhotoPath,
|
||||
isEditableEventPhoto,
|
||||
} from "@/lib/event-photos";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
import { normalizePhotoAdjustments } from "@/lib/photo-adjustments";
|
||||
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
|
||||
|
||||
const MAX_EDIT_BODY_BYTES = 32 * 1024;
|
||||
|
||||
/**
|
||||
* POST /api/events/:id/folders/:folderId/photos/:photoId/edit
|
||||
* Body: { adjustments: PhotoAdjustments }
|
||||
*
|
||||
* Saves the recipe and renders a fresh full-resolution JPEG beside the
|
||||
* original. The original file is never changed, so an edit can always be
|
||||
* reopened and adjusted again.
|
||||
*/
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
{
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string; folderId: string; photoId: string }>;
|
||||
},
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
if (Number(req.headers.get("content-length") ?? 0) > MAX_EDIT_BODY_BYTES) {
|
||||
return errorResponse(413, "the edit settings are too large");
|
||||
}
|
||||
|
||||
const { id, folderId, photoId } = await params;
|
||||
const access = await getEventPhotoAccess(photoId, gate.id, gate.systemRole);
|
||||
if (
|
||||
!access ||
|
||||
access.photo.folderId !== folderId ||
|
||||
access.eventId !== id
|
||||
) {
|
||||
return errorResponse(404, "unknown photo");
|
||||
}
|
||||
if (!isEditableEventPhoto(access.photo.filename)) {
|
||||
return errorResponse(415, "this photo format cannot be edited");
|
||||
}
|
||||
|
||||
const body = (await req.json().catch(() => null)) as
|
||||
| { adjustments?: unknown }
|
||||
| null;
|
||||
const adjustments = normalizePhotoAdjustments(body?.adjustments);
|
||||
if (!adjustments) {
|
||||
return errorResponse(400, "invalid photo adjustments");
|
||||
}
|
||||
|
||||
const sourcePath = eventPhotoPath(access.photo.storedName);
|
||||
try {
|
||||
const source = await stat(sourcePath);
|
||||
if (!source.isFile()) return errorResponse(404, "the file is missing from storage");
|
||||
} catch {
|
||||
return errorResponse(404, "the file is missing from storage");
|
||||
}
|
||||
|
||||
const editedStoredName = editedStoredNameForEventPhoto(
|
||||
access.eventId,
|
||||
access.photo.id,
|
||||
);
|
||||
const editedPath = eventPhotoPath(editedStoredName);
|
||||
|
||||
let rendered: Awaited<ReturnType<typeof renderPhotoJpeg>>;
|
||||
try {
|
||||
rendered = await renderPhotoJpeg({
|
||||
filePath: sourcePath,
|
||||
kind: access.photo.kind,
|
||||
adjustments,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof PhotoRenderError) {
|
||||
return errorResponse(422, error.message);
|
||||
}
|
||||
console.error("photo edit render failed", error);
|
||||
return errorResponse(500, "the edited JPEG could not be generated");
|
||||
}
|
||||
|
||||
await mkdir(path.dirname(editedPath), { recursive: true });
|
||||
const temporary = `${editedPath}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
await writeFile(temporary, rendered.data);
|
||||
await rename(temporary, editedPath);
|
||||
} catch (error) {
|
||||
await unlink(temporary).catch(() => undefined);
|
||||
console.error("photo edit write failed", error);
|
||||
return errorResponse(500, "the edited JPEG could not be saved");
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await updateEventPhotoEdit({
|
||||
photoId: access.photo.id,
|
||||
editJson: JSON.stringify(adjustments),
|
||||
editedStoredName,
|
||||
editedSizeBytes: rendered.data.byteLength,
|
||||
editedBy: gate.id,
|
||||
});
|
||||
if (!updated) {
|
||||
await unlink(editedPath).catch(() => undefined);
|
||||
return errorResponse(404, "unknown photo");
|
||||
}
|
||||
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
adjustments,
|
||||
editedFilename: editedPhotoFilename(access.photo.filename),
|
||||
editedSizeBytes: rendered.data.byteLength,
|
||||
editedAt: updated.editedAt,
|
||||
width: rendered.width,
|
||||
height: rendered.height,
|
||||
});
|
||||
} catch (error) {
|
||||
await unlink(editedPath).catch(() => undefined);
|
||||
console.error("photo edit metadata failed", error);
|
||||
return errorResponse(500, "the edit was rendered but could not be recorded");
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,99 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { stat } from "node:fs/promises";
|
||||
import sharp from "sharp";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getEventPhotoAccess } from "@/db/events";
|
||||
import {
|
||||
eventPhotoPath,
|
||||
photoContentDisposition,
|
||||
} from "@/lib/event-photos";
|
||||
import {
|
||||
photoExportFilename,
|
||||
photoExportPresetFor,
|
||||
} from "@/lib/photo-exports";
|
||||
import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments";
|
||||
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
/**
|
||||
* GET /api/events/:id/folders/:folderId/photos/:photoId/export?size=2048
|
||||
*
|
||||
* Renders a delivery-sized JPEG from the saved edit. The saved full-resolution
|
||||
* JPEG is resized rather than re-decoded from RAW; if it is missing, the
|
||||
* original is rendered from the stored recipe as a fallback. Only the four
|
||||
* delivery sizes advertised by the editor are accepted.
|
||||
*/
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
{
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string; folderId: string; photoId: string }>;
|
||||
},
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id, folderId, photoId } = await params;
|
||||
const access = await getEventPhotoAccess(photoId, gate.id, gate.systemRole);
|
||||
if (!access || access.photo.folderId !== folderId || access.eventId !== id) {
|
||||
return errorResponse(404, "unknown photo");
|
||||
}
|
||||
|
||||
const preset = photoExportPresetFor(req.nextUrl.searchParams.get("size"));
|
||||
if (!preset) {
|
||||
return errorResponse(400, "unknown export size");
|
||||
}
|
||||
|
||||
let data: Buffer;
|
||||
try {
|
||||
if (access.photo.editedStoredName) {
|
||||
const editedPath = eventPhotoPath(access.photo.editedStoredName);
|
||||
const info = await stat(editedPath);
|
||||
if (!info.isFile()) throw new Error("missing edit");
|
||||
data = await sharp(editedPath)
|
||||
.resize({
|
||||
width: preset.maxDimension,
|
||||
height: preset.maxDimension,
|
||||
fit: "inside",
|
||||
withoutEnlargement: true,
|
||||
})
|
||||
.jpeg({ quality: 90, mozjpeg: true, chromaSubsampling: "4:4:4" })
|
||||
.toBuffer();
|
||||
} else if (access.photo.editJson) {
|
||||
const rendered = await renderPhotoJpeg({
|
||||
filePath: eventPhotoPath(access.photo.storedName),
|
||||
kind: access.photo.kind,
|
||||
adjustments: parseStoredPhotoAdjustments(access.photo.editJson),
|
||||
maxDimension: preset.maxDimension,
|
||||
});
|
||||
data = rendered.data;
|
||||
} else {
|
||||
return errorResponse(
|
||||
409,
|
||||
"Save an edit before exporting a delivery-sized JPEG.",
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof PhotoRenderError) {
|
||||
return errorResponse(422, error.message);
|
||||
}
|
||||
console.error("photo export failed", error);
|
||||
return errorResponse(500, "the exported JPEG could not be generated");
|
||||
}
|
||||
|
||||
return new Response(new Uint8Array(data), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "image/jpeg",
|
||||
"content-length": String(data.byteLength),
|
||||
"content-disposition": photoContentDisposition(
|
||||
photoExportFilename(access.photo.filename, preset),
|
||||
false,
|
||||
),
|
||||
"cache-control": "private, no-store",
|
||||
"x-content-type-options": "nosniff",
|
||||
"content-security-policy": "default-src 'none'; sandbox",
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,102 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getEventPhotoAccess } from "@/db/events";
|
||||
import {
|
||||
eventPhotoPath,
|
||||
isEditableEventPhoto,
|
||||
previewStoredNameForEventPhoto,
|
||||
} from "@/lib/event-photos";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
|
||||
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
|
||||
|
||||
/**
|
||||
* GET /api/events/:id/folders/:folderId/photos/:photoId/preview
|
||||
*
|
||||
* A browser-sized JPEG of the untouched original. RAW files are decoded through
|
||||
* LibRaw; the result is cached on disk because the original never changes.
|
||||
* The client applies the live adjustment LUT to this proxy.
|
||||
*/
|
||||
export const GET = async (
|
||||
_req: NextRequest,
|
||||
{
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string; folderId: string; photoId: string }>;
|
||||
},
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id, folderId, photoId } = await params;
|
||||
const access = await getEventPhotoAccess(photoId, gate.id, gate.systemRole);
|
||||
if (
|
||||
!access ||
|
||||
access.photo.folderId !== folderId ||
|
||||
access.eventId !== id
|
||||
) {
|
||||
return errorResponse(404, "unknown photo");
|
||||
}
|
||||
if (!isEditableEventPhoto(access.photo.filename)) {
|
||||
return errorResponse(415, "this photo format cannot be previewed in the editor");
|
||||
}
|
||||
|
||||
const sourcePath = eventPhotoPath(access.photo.storedName);
|
||||
try {
|
||||
const source = await stat(sourcePath);
|
||||
if (!source.isFile()) return errorResponse(404, "the file is missing from storage");
|
||||
} catch {
|
||||
return errorResponse(404, "the file is missing from storage");
|
||||
}
|
||||
|
||||
const previewPath = eventPhotoPath(
|
||||
previewStoredNameForEventPhoto(access.eventId, access.photo.id),
|
||||
);
|
||||
|
||||
try {
|
||||
const cached = await stat(previewPath);
|
||||
if (cached.isFile() && cached.size > 0) {
|
||||
return imageResponse(await readFile(previewPath));
|
||||
}
|
||||
} catch {
|
||||
// Not generated yet.
|
||||
}
|
||||
|
||||
try {
|
||||
const rendered = await renderPhotoJpeg({
|
||||
filePath: sourcePath,
|
||||
kind: access.photo.kind,
|
||||
adjustments: defaultPhotoAdjustments(),
|
||||
maxDimension: 1800,
|
||||
});
|
||||
|
||||
await mkdir(path.dirname(previewPath), { recursive: true });
|
||||
const temporary = `${previewPath}.${randomUUID()}.tmp`;
|
||||
await writeFile(temporary, rendered.data);
|
||||
await rename(temporary, previewPath);
|
||||
return imageResponse(rendered.data);
|
||||
} catch (error) {
|
||||
if (error instanceof PhotoRenderError) {
|
||||
return errorResponse(422, error.message);
|
||||
}
|
||||
console.error("photo preview failed", error);
|
||||
return errorResponse(500, "the preview could not be generated");
|
||||
}
|
||||
};
|
||||
|
||||
function imageResponse(data: Buffer): Response {
|
||||
return new Response(new Uint8Array(data), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "image/jpeg",
|
||||
"content-length": String(data.byteLength),
|
||||
"content-disposition": "inline",
|
||||
"cache-control": "private, max-age=86400, immutable",
|
||||
"x-content-type-options": "nosniff",
|
||||
"content-security-policy": "default-src 'none'; sandbox",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { stat, unlink } from "node:fs/promises";
|
||||
import { Readable } from "node:stream";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { deleteEventPhoto, getEventPhotoAccess } from "@/db/events";
|
||||
import { canDeleteEventPhoto } from "@/lib/event-access";
|
||||
import {
|
||||
editedPhotoFilename,
|
||||
eventPhotoPath,
|
||||
isBrowserRenderablePhoto,
|
||||
photoContentDisposition,
|
||||
} from "@/lib/event-photos";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
|
||||
/**
|
||||
* GET /api/events/:id/folders/:folderId/photos/:photoId[?download=1|variant=edited]
|
||||
*
|
||||
* Streams the original bytes to anyone assigned to the event (or a manager).
|
||||
* `variant=edited` serves the generated full-resolution JPEG instead, so the
|
||||
* gallery can show the saved look without replacing the original. RAW files
|
||||
* always download; `?download=1` forces an attachment for JPEGs too.
|
||||
*/
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
{
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string; folderId: string; photoId: string }>;
|
||||
},
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id, folderId, photoId } = await params;
|
||||
const access = await getEventPhotoAccess(photoId, gate.id, gate.systemRole);
|
||||
if (
|
||||
!access ||
|
||||
access.photo.folderId !== folderId ||
|
||||
access.eventId !== id
|
||||
) {
|
||||
return errorResponse(404, "unknown photo");
|
||||
}
|
||||
|
||||
const wantsEdited = req.nextUrl.searchParams.get("variant") === "edited";
|
||||
if (wantsEdited && !access.photo.editedStoredName) {
|
||||
return errorResponse(404, "this photo has no saved edit");
|
||||
}
|
||||
|
||||
const filePath = eventPhotoPath(
|
||||
wantsEdited
|
||||
? access.photo.editedStoredName!
|
||||
: access.photo.storedName,
|
||||
);
|
||||
const filename = wantsEdited
|
||||
? editedPhotoFilename(access.photo.filename)
|
||||
: access.photo.filename;
|
||||
let size: number;
|
||||
try {
|
||||
size = (await stat(filePath)).size;
|
||||
} catch {
|
||||
return errorResponse(404, "the file is missing from storage");
|
||||
}
|
||||
|
||||
const inline =
|
||||
req.nextUrl.searchParams.get("download") !== "1" &&
|
||||
(wantsEdited || isBrowserRenderablePhoto(access.photo.filename));
|
||||
|
||||
const stream = createReadStream(filePath);
|
||||
return new Response(
|
||||
Readable.toWeb(stream) as unknown as ReadableStream<Uint8Array>,
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": wantsEdited ? "image/jpeg" : access.photo.mimeType,
|
||||
"content-length": String(size),
|
||||
"content-disposition": photoContentDisposition(filename, inline),
|
||||
"cache-control": "private, max-age=0, must-revalidate",
|
||||
"x-content-type-options": "nosniff",
|
||||
"content-security-policy": "default-src 'none'; sandbox",
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
/** DELETE — the uploader or an event manager can remove a photo. */
|
||||
export const DELETE = async (
|
||||
_req: NextRequest,
|
||||
{
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string; folderId: string; photoId: string }>;
|
||||
},
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id, folderId, photoId } = await params;
|
||||
const access = await getEventPhotoAccess(photoId, gate.id, gate.systemRole);
|
||||
if (
|
||||
!access ||
|
||||
access.photo.folderId !== folderId ||
|
||||
access.eventId !== id
|
||||
) {
|
||||
return errorResponse(404, "unknown photo");
|
||||
}
|
||||
if (
|
||||
!canDeleteEventPhoto({
|
||||
role: gate.systemRole,
|
||||
userId: gate.id,
|
||||
uploaderId: access.photo.uploaderId,
|
||||
})
|
||||
) {
|
||||
return errorResponse(403, "only the uploader or a coordinator may delete this photo");
|
||||
}
|
||||
|
||||
await deleteEventPhoto(photoId);
|
||||
await unlink(eventPhotoPath(access.photo.storedName)).catch(() => undefined);
|
||||
if (access.photo.editedStoredName) {
|
||||
await unlink(eventPhotoPath(access.photo.editedStoredName)).catch(
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
return jsonResponse({ ok: true });
|
||||
};
|
||||
@@ -0,0 +1,156 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { createHash } from "node:crypto";
|
||||
import { createWriteStream } from "node:fs";
|
||||
import { mkdir, unlink } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { Readable, Transform } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import {
|
||||
addEventPhoto,
|
||||
findEventPhotoByChecksum,
|
||||
getEventFolderAccess,
|
||||
isUniqueViolation,
|
||||
} from "@/db/events";
|
||||
import {
|
||||
MAX_EVENT_PHOTO_BYTES,
|
||||
eventPhotoKindFor,
|
||||
eventPhotoMimeFor,
|
||||
eventPhotoPath,
|
||||
sanitizePhotoFilename,
|
||||
storedNameForEventPhoto,
|
||||
} from "@/lib/event-photos";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
class PhotoTooLarge extends Error {}
|
||||
|
||||
function publicPhoto(photo: {
|
||||
id: string;
|
||||
folderId: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
kind: "raw" | "image";
|
||||
createdAt: Date;
|
||||
}) {
|
||||
return {
|
||||
id: photo.id,
|
||||
folderId: photo.folderId,
|
||||
filename: photo.filename,
|
||||
mimeType: photo.mimeType,
|
||||
sizeBytes: photo.sizeBytes,
|
||||
kind: photo.kind,
|
||||
createdAt: photo.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/events/:id/folders/:folderId/photos?name=IMG_0001.CR3
|
||||
*
|
||||
* A single photo is the raw request body (not multipart), so a 100 MB RAW file
|
||||
* streams straight to disk instead of being buffered in memory. The filename is
|
||||
* passed as a query parameter because headers cannot carry arbitrary Unicode.
|
||||
* The SHA-256 is computed while streaming and dedupes a re-upload per folder.
|
||||
*/
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string; folderId: string }> },
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id, folderId } = await params;
|
||||
const access = await getEventFolderAccess(folderId, gate.id, gate.systemRole);
|
||||
if (!access || access.eventId !== id) {
|
||||
return errorResponse(404, "unknown folder");
|
||||
}
|
||||
if (!access.canContribute) {
|
||||
return errorResponse(403, "you are not assigned to this event");
|
||||
}
|
||||
|
||||
const suppliedName = req.nextUrl.searchParams.get("name");
|
||||
if (!suppliedName) return errorResponse(400, "a filename is required");
|
||||
const filename = sanitizePhotoFilename(suppliedName);
|
||||
const kind = eventPhotoKindFor(filename);
|
||||
if (!kind) {
|
||||
return errorResponse(
|
||||
415,
|
||||
"only photo files are accepted (JPEG, PNG, WebP, HEIC, TIFF, PSD or camera RAW)",
|
||||
);
|
||||
}
|
||||
|
||||
const declaredLength = Number(req.headers.get("content-length") ?? 0);
|
||||
if (declaredLength > MAX_EVENT_PHOTO_BYTES) {
|
||||
return errorResponse(413, "that photo is larger than 200 MB");
|
||||
}
|
||||
if (!req.body) return errorResponse(400, "a file body is required");
|
||||
|
||||
const photoId = uuidv7();
|
||||
const storedName = storedNameForEventPhoto(id, photoId, filename);
|
||||
const destination = eventPhotoPath(storedName);
|
||||
await mkdir(path.dirname(destination), { recursive: true });
|
||||
|
||||
const hash = createHash("sha256");
|
||||
let size = 0;
|
||||
const meter = new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
size += chunk.length;
|
||||
if (size > MAX_EVENT_PHOTO_BYTES) {
|
||||
callback(new PhotoTooLarge());
|
||||
return;
|
||||
}
|
||||
hash.update(chunk);
|
||||
callback(null, chunk);
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await pipeline(
|
||||
Readable.from(req.body as unknown as AsyncIterable<Uint8Array>),
|
||||
meter,
|
||||
createWriteStream(destination, { flags: "wx" }),
|
||||
);
|
||||
} catch (error) {
|
||||
await unlink(destination).catch(() => undefined);
|
||||
if (error instanceof PhotoTooLarge) {
|
||||
return errorResponse(413, "that photo is larger than 200 MB");
|
||||
}
|
||||
return errorResponse(500, "the upload did not complete");
|
||||
}
|
||||
|
||||
if (size === 0) {
|
||||
await unlink(destination).catch(() => undefined);
|
||||
return errorResponse(400, "the uploaded file was empty");
|
||||
}
|
||||
|
||||
const checksumSha256 = hash.digest("hex");
|
||||
const existing = await findEventPhotoByChecksum(folderId, checksumSha256);
|
||||
if (existing) {
|
||||
await unlink(destination).catch(() => undefined);
|
||||
return jsonResponse({ photo: publicPhoto(existing), duplicate: true });
|
||||
}
|
||||
|
||||
try {
|
||||
const photo = await addEventPhoto({
|
||||
folderId,
|
||||
uploaderId: gate.id,
|
||||
filename,
|
||||
mimeType: eventPhotoMimeFor(filename),
|
||||
sizeBytes: size,
|
||||
storedName,
|
||||
checksumSha256,
|
||||
kind,
|
||||
});
|
||||
return jsonResponse({ photo: publicPhoto(photo) }, 201);
|
||||
} catch (error) {
|
||||
await unlink(destination).catch(() => undefined);
|
||||
if (isUniqueViolation(error)) {
|
||||
const raced = await findEventPhotoByChecksum(folderId, checksumSha256);
|
||||
if (raced) {
|
||||
return jsonResponse({ photo: publicPhoto(raced), duplicate: true });
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import {
|
||||
createEventFolder,
|
||||
getEventAccess,
|
||||
isUniqueViolation,
|
||||
} from "@/db/events";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
|
||||
const folderSchema = z.object({
|
||||
name: z.string().trim().min(1).max(80),
|
||||
kind: z.enum(["originals", "edited", "mixed"]).optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/events/:id/folders — create a folder inside an event.
|
||||
* Any assigned photographer, coordinator or admin may create one.
|
||||
*/
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id } = await params;
|
||||
const access = await getEventAccess(id, gate.id, gate.systemRole);
|
||||
if (!access) return errorResponse(404, "unknown event");
|
||||
if (!access.canContribute) {
|
||||
return errorResponse(403, "you are not assigned to this event");
|
||||
}
|
||||
|
||||
const parsed = folderSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid folder");
|
||||
}
|
||||
|
||||
try {
|
||||
const folder = await createEventFolder({
|
||||
eventId: id,
|
||||
name: parsed.data.name,
|
||||
kind: parsed.data.kind ?? "originals",
|
||||
createdBy: gate.id,
|
||||
});
|
||||
return jsonResponse({ folder }, 201);
|
||||
} catch (error) {
|
||||
if (isUniqueViolation(error)) {
|
||||
return errorResponse(409, "a folder with that name already exists");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import {
|
||||
assignEventPhotographer,
|
||||
getEventAccess,
|
||||
removeEventPhotographer,
|
||||
} from "@/db/events";
|
||||
import { EVENT_PHOTOGRAPHER_ROLES } from "@/db/schema";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
|
||||
const assignmentSchema = z.object({
|
||||
userId: z.string().min(1),
|
||||
role: z.enum(EVENT_PHOTOGRAPHER_ROLES).optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/events/:id/photographers — assign a photographer/editor.
|
||||
* DELETE ?userId= — remove them. Managers only (`schedule.publish`).
|
||||
*/
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const gate = await gateOrUser("schedule.publish");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id } = await params;
|
||||
const access = await getEventAccess(id, gate.id, gate.systemRole);
|
||||
if (!access) return errorResponse(404, "unknown event");
|
||||
|
||||
const parsed = assignmentSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid assignment");
|
||||
}
|
||||
|
||||
const assignment = await assignEventPhotographer({
|
||||
eventId: id,
|
||||
userId: parsed.data.userId,
|
||||
role: parsed.data.role ?? "photographer",
|
||||
assignedBy: gate.id,
|
||||
});
|
||||
if (!assignment) {
|
||||
return errorResponse(400, "that account is not an active team member");
|
||||
}
|
||||
|
||||
return jsonResponse({ assignment }, 201);
|
||||
};
|
||||
|
||||
export const DELETE = async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const gate = await gateOrUser("schedule.publish");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id } = await params;
|
||||
const access = await getEventAccess(id, gate.id, gate.systemRole);
|
||||
if (!access) return errorResponse(404, "unknown event");
|
||||
|
||||
const userId = req.nextUrl.searchParams.get("userId");
|
||||
if (!userId) return errorResponse(400, "a userId is required");
|
||||
|
||||
const removed = await removeEventPhotographer(id, userId);
|
||||
if (!removed) return errorResponse(404, "that person is not assigned");
|
||||
return jsonResponse({ ok: true });
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import { deleteEvent, getEventAccess } from "@/db/events";
|
||||
import { listEventVideos } from "@/db/videos";
|
||||
import { getStorageSettings } from "@/db/storage-settings";
|
||||
import { eventPhotoDir } from "@/lib/event-photos";
|
||||
import {
|
||||
eventVideoArchiveDir,
|
||||
eventVideoUploadDir,
|
||||
} from "@/lib/event-videos";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
|
||||
/**
|
||||
* DELETE /api/events/:id — manager-only. Removes the event, its folders/photos
|
||||
* and the event's directory on the uploads volume. The database cascade commits
|
||||
* first; bytes are then removed best-effort so a storage hiccup cannot leave a
|
||||
* half-deleted event row. Any orphaned bytes are reported in the server log.
|
||||
*/
|
||||
export const DELETE = async (
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const gate = await gateOrUser("schedule.publish");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id } = await params;
|
||||
const access = await getEventAccess(id, gate.id, gate.systemRole);
|
||||
if (!access) return errorResponse(404, "unknown event");
|
||||
const videos = await listEventVideos(id);
|
||||
|
||||
const deleted = await deleteEvent(id);
|
||||
if (!deleted) return errorResponse(404, "unknown event");
|
||||
|
||||
try {
|
||||
await rm(eventPhotoDir(id), { recursive: true, force: true });
|
||||
await rm(eventVideoUploadDir(id), { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
console.error(`event ${id}: database deleted but files remain`, error);
|
||||
}
|
||||
|
||||
// Video originals are the largest files; remove each one from the archive
|
||||
// after the cascade has removed its row, so a deletion cannot orphan GBs.
|
||||
try {
|
||||
const storage = await getStorageSettings();
|
||||
for (const video of videos) {
|
||||
await rm(
|
||||
eventVideoArchiveDir(
|
||||
storage.archivePath,
|
||||
video.archiveFolder,
|
||||
id,
|
||||
video.id,
|
||||
),
|
||||
{ recursive: true, force: true },
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`event ${id}: NFS video originals were not removed`, error);
|
||||
}
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: "event.deleted",
|
||||
entityType: "event",
|
||||
entityId: id,
|
||||
before: {
|
||||
title: deleted.event.title,
|
||||
startsAt: deleted.event.startsAt.toISOString(),
|
||||
photoCount: deleted.photoCount,
|
||||
videoCount: videos.length,
|
||||
},
|
||||
});
|
||||
|
||||
return jsonResponse({ ok: true });
|
||||
};
|
||||
@@ -0,0 +1,152 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import {
|
||||
getEventVideoAccess,
|
||||
updateEventVideo,
|
||||
type EventVideoPatch,
|
||||
} from "@/db/videos";
|
||||
import { EVENT_VIDEO_VISIBILITIES } from "@/db/schema";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
import { processEventVideo } from "@/lib/video-processing";
|
||||
import { videoView } from "@/lib/video-view";
|
||||
|
||||
const MAX_BODY_BYTES = 64 * 1024;
|
||||
|
||||
const editSchema = z.object({
|
||||
title: z.string().trim().min(1).max(200).optional(),
|
||||
description: z.string().max(5000).nullable().optional(),
|
||||
visibility: z.enum(EVENT_VIDEO_VISIBILITIES).optional(),
|
||||
trimStartMs: z.number().int().min(0).optional(),
|
||||
trimEndMs: z.number().int().min(0).nullable().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/events/:id/videos/:videoId/edit
|
||||
*
|
||||
* Metadata is saved immediately. A changed trim marks the video processing and
|
||||
* re-renders the web MP4 with FFmpeg; the NFS original is never altered. Only a
|
||||
* manager may publish a video as unlisted/public.
|
||||
*/
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string; videoId: string }> },
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY_BYTES) {
|
||||
return errorResponse(413, "the video edit is too large");
|
||||
}
|
||||
|
||||
const { id, videoId } = await params;
|
||||
const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole);
|
||||
if (!access || access.video.eventId !== id) {
|
||||
return errorResponse(404, "unknown video");
|
||||
}
|
||||
if (!access.canContribute) {
|
||||
return errorResponse(403, "you are not assigned to this event");
|
||||
}
|
||||
|
||||
const parsed = editSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return errorResponse(
|
||||
400,
|
||||
parsed.error.issues[0]?.message ?? "invalid video edit",
|
||||
);
|
||||
}
|
||||
const body = parsed.data;
|
||||
if (Object.keys(body).length === 0) {
|
||||
return errorResponse(400, "no changes were supplied");
|
||||
}
|
||||
if (
|
||||
body.visibility &&
|
||||
body.visibility !== "team" &&
|
||||
!access.canManage
|
||||
) {
|
||||
return errorResponse(
|
||||
403,
|
||||
"only a coordinator or admin can publish a video publicly",
|
||||
);
|
||||
}
|
||||
|
||||
const video = access.video;
|
||||
const patch: EventVideoPatch = {};
|
||||
if (body.title !== undefined) patch.title = body.title;
|
||||
if (body.description !== undefined) {
|
||||
patch.description = body.description?.trim() || null;
|
||||
}
|
||||
if (body.visibility !== undefined) patch.visibility = body.visibility;
|
||||
|
||||
let trimChanged = false;
|
||||
if (body.trimStartMs !== undefined || body.trimEndMs !== undefined) {
|
||||
if (!video.durationMs || video.durationMs <= 0) {
|
||||
return errorResponse(
|
||||
409,
|
||||
"this video is still being processed; wait until it is ready before trimming",
|
||||
);
|
||||
}
|
||||
const duration = video.durationMs;
|
||||
const minimum = Math.min(1000, duration);
|
||||
const currentEnd = video.trimEndMs ?? duration;
|
||||
const requestedStart = body.trimStartMs ?? video.trimStartMs;
|
||||
const requestedEnd = body.trimEndMs ?? currentEnd;
|
||||
const start = Math.min(
|
||||
Math.max(0, requestedStart),
|
||||
Math.max(0, duration - minimum),
|
||||
);
|
||||
const end = Math.min(
|
||||
Math.max(requestedEnd, start + minimum),
|
||||
duration,
|
||||
);
|
||||
trimChanged = start !== video.trimStartMs || end !== currentEnd;
|
||||
patch.trimStartMs = start;
|
||||
patch.trimEndMs = end;
|
||||
}
|
||||
|
||||
if (trimChanged) {
|
||||
patch.status = "processing";
|
||||
patch.errorMessage = null;
|
||||
}
|
||||
|
||||
const updated = await updateEventVideo(video.id, patch);
|
||||
if (!updated) return errorResponse(404, "unknown video");
|
||||
|
||||
if (trimChanged) {
|
||||
void processEventVideo(updated.id).catch((error) => {
|
||||
console.error(`video ${updated.id}: background trim failed`, error);
|
||||
});
|
||||
}
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: "video.edited",
|
||||
entityType: "event_video",
|
||||
entityId: video.id,
|
||||
before: {
|
||||
title: video.title,
|
||||
visibility: video.visibility,
|
||||
trimStartMs: video.trimStartMs,
|
||||
trimEndMs: video.trimEndMs,
|
||||
},
|
||||
after: {
|
||||
title: updated.title,
|
||||
visibility: updated.visibility,
|
||||
trimStartMs: updated.trimStartMs,
|
||||
trimEndMs: updated.trimEndMs,
|
||||
processing: trimChanged,
|
||||
},
|
||||
});
|
||||
|
||||
return jsonResponse({
|
||||
video: videoView({
|
||||
...updated,
|
||||
eventTitle: access.event.title,
|
||||
eventStartsAt: access.event.startsAt,
|
||||
}),
|
||||
canManage: access.canManage,
|
||||
canContribute: access.canContribute,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { Readable } from "node:stream";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getStorageSettings } from "@/db/storage-settings";
|
||||
import { getEventVideoAccess } from "@/db/videos";
|
||||
import {
|
||||
eventVideoArchivePath,
|
||||
videoContentDisposition,
|
||||
} from "@/lib/event-videos";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { parseByteRange } from "@/lib/range";
|
||||
|
||||
/** Download the untouched camera original from the NFS archive. */
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string; videoId: string }> },
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id, videoId } = await params;
|
||||
const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole);
|
||||
if (!access || access.video.eventId !== id) {
|
||||
return errorResponse(404, "unknown video");
|
||||
}
|
||||
|
||||
let filePath: string;
|
||||
try {
|
||||
const storage = await getStorageSettings();
|
||||
filePath = eventVideoArchivePath(
|
||||
storage.archivePath,
|
||||
access.video.archiveFolder,
|
||||
access.video.originalStoredName,
|
||||
);
|
||||
} catch {
|
||||
return errorResponse(404, "the NFS archive is not configured");
|
||||
}
|
||||
|
||||
const info = await stat(filePath).catch(() => null);
|
||||
if (!info?.isFile()) {
|
||||
return errorResponse(404, "the original video is missing from the NFS archive");
|
||||
}
|
||||
|
||||
const range = parseByteRange(req.headers.get("range"), info.size);
|
||||
if (range === "invalid") {
|
||||
return new Response(null, {
|
||||
status: 416,
|
||||
headers: { "content-range": `bytes */${info.size}` },
|
||||
});
|
||||
}
|
||||
const start = range?.start ?? 0;
|
||||
const end = range?.end ?? info.size - 1;
|
||||
const stream = createReadStream(filePath, { start, end });
|
||||
|
||||
return new Response(
|
||||
Readable.toWeb(stream) as unknown as ReadableStream<Uint8Array>,
|
||||
{
|
||||
status: range ? 206 : 200,
|
||||
headers: {
|
||||
"content-type": access.video.mimeType,
|
||||
"content-length": String(end - start + 1),
|
||||
"accept-ranges": "bytes",
|
||||
...(range
|
||||
? { "content-range": `bytes ${start}-${end}/${info.size}` }
|
||||
: {}),
|
||||
"content-disposition": videoContentDisposition(
|
||||
access.video.filename,
|
||||
false,
|
||||
),
|
||||
"cache-control": "private, no-store",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import {
|
||||
getEventVideoAccess,
|
||||
markVideoProcessing,
|
||||
} from "@/db/videos";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
import { processEventVideo } from "@/lib/video-processing";
|
||||
import { videoView } from "@/lib/video-view";
|
||||
|
||||
/** Retry a failed encode; the NFS original is still intact. */
|
||||
export const POST = async (
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string; videoId: string }> },
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id, videoId } = await params;
|
||||
const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole);
|
||||
if (!access || access.video.eventId !== id) {
|
||||
return errorResponse(404, "unknown video");
|
||||
}
|
||||
if (!access.canContribute) {
|
||||
return errorResponse(403, "you are not assigned to this event");
|
||||
}
|
||||
if (access.video.status === "processing") {
|
||||
return errorResponse(409, "this video is already processing");
|
||||
}
|
||||
if (access.video.status === "ready") {
|
||||
return errorResponse(409, "this video is already ready; save an edit to re-render it");
|
||||
}
|
||||
|
||||
const updated = await markVideoProcessing(videoId);
|
||||
if (!updated) return errorResponse(404, "unknown video");
|
||||
void processEventVideo(videoId).catch((error) => {
|
||||
console.error(`video ${videoId}: retry failed`, error);
|
||||
});
|
||||
|
||||
return jsonResponse({
|
||||
video: videoView({
|
||||
...updated,
|
||||
eventTitle: access.event.title,
|
||||
eventStartsAt: access.event.startsAt,
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,104 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { db } from "@/db";
|
||||
import { writeAudit } from "@/db/audit";
|
||||
import {
|
||||
deleteEventVideo,
|
||||
getEventVideoAccess,
|
||||
} from "@/db/videos";
|
||||
import { getStorageSettings } from "@/db/storage-settings";
|
||||
import {
|
||||
eventVideoArchiveDir,
|
||||
eventVideoUploadPath,
|
||||
webStoredNameForEventVideo,
|
||||
} from "@/lib/event-videos";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
import { videoView } from "@/lib/video-view";
|
||||
|
||||
/** GET /api/events/:id/videos/:videoId — metadata + processing status. */
|
||||
export const GET = async (
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string; videoId: string }> },
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id, videoId } = await params;
|
||||
const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole);
|
||||
if (!access || access.video.eventId !== id) {
|
||||
return errorResponse(404, "unknown video");
|
||||
}
|
||||
|
||||
return jsonResponse({
|
||||
video: videoView({
|
||||
...access.video,
|
||||
eventTitle: access.event.title,
|
||||
eventStartsAt: access.event.startsAt,
|
||||
}),
|
||||
canManage: access.canManage,
|
||||
canContribute: access.canContribute,
|
||||
});
|
||||
};
|
||||
|
||||
/** DELETE — uploader or an event manager; removes NFS original + derivatives. */
|
||||
export const DELETE = async (
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string; videoId: string }> },
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id, videoId } = await params;
|
||||
const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole);
|
||||
if (!access || access.video.eventId !== id) {
|
||||
return errorResponse(404, "unknown video");
|
||||
}
|
||||
if (!access.canManage && access.video.uploaderId !== gate.id) {
|
||||
return errorResponse(403, "only the uploader or a coordinator may delete this video");
|
||||
}
|
||||
|
||||
const removed = await deleteEventVideo(videoId);
|
||||
if (!removed) return errorResponse(404, "unknown video");
|
||||
|
||||
const derivativeDir = path.dirname(
|
||||
eventVideoUploadPath(
|
||||
removed.webStoredName ??
|
||||
webStoredNameForEventVideo(removed.eventId, removed.id),
|
||||
),
|
||||
);
|
||||
await rm(derivativeDir, { recursive: true, force: true }).catch((error) => {
|
||||
console.error(`video ${videoId}: derivatives were not removed`, error);
|
||||
});
|
||||
|
||||
try {
|
||||
const storage = await getStorageSettings();
|
||||
await rm(
|
||||
eventVideoArchiveDir(
|
||||
storage.archivePath,
|
||||
removed.archiveFolder,
|
||||
removed.eventId,
|
||||
removed.id,
|
||||
),
|
||||
{ recursive: true, force: true },
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(`video ${videoId}: NFS original was not removed`, error);
|
||||
}
|
||||
|
||||
await writeAudit(db, {
|
||||
actorId: gate.id,
|
||||
action: "video.deleted",
|
||||
entityType: "event_video",
|
||||
entityId: videoId,
|
||||
before: {
|
||||
eventId: removed.eventId,
|
||||
title: removed.title,
|
||||
filename: removed.filename,
|
||||
sizeBytes: removed.sizeBytes,
|
||||
},
|
||||
});
|
||||
|
||||
return jsonResponse({ ok: true });
|
||||
};
|
||||
@@ -0,0 +1,257 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { createWriteStream } from "node:fs";
|
||||
import { mkdir, stat, truncate, unlink } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getEventAccess } from "@/db/events";
|
||||
import {
|
||||
checkArchiveDestination,
|
||||
getStorageSettings,
|
||||
} from "@/db/storage-settings";
|
||||
import {
|
||||
EVENT_VIDEO_VISIBILITIES,
|
||||
type EventVideoVisibility,
|
||||
} from "@/db/schema";
|
||||
import { finalizeEventVideo, checksumFile } from "@/lib/event-video-finalize";
|
||||
import {
|
||||
eventVideoArchivePath,
|
||||
isAllowedEventVideo,
|
||||
originalStoredNameForEventVideo,
|
||||
sanitizeVideoFilename,
|
||||
} from "@/lib/event-videos";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
import {
|
||||
EVENT_VIDEO_CHUNK_BYTES,
|
||||
MAX_EVENT_VIDEO_BYTES,
|
||||
MAX_EVENT_VIDEO_LABEL,
|
||||
} from "@/lib/video-limits";
|
||||
import { videoView } from "@/lib/video-view";
|
||||
|
||||
const UPLOAD_ID_PATTERN =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
function integerParam(value: string | null): number | null {
|
||||
if (!value || !/^\d+$/.test(value)) return null;
|
||||
const parsed = Number(value);
|
||||
return Number.isSafeInteger(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
function isMissing(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
(error as { code?: string }).code === "ENOENT"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/events/:id/videos/chunk
|
||||
* ?uploadId=<uuid>&offset=<bytes>&size=<total bytes>
|
||||
* &name=...&title=...&visibility=team
|
||||
*
|
||||
* Raw body, one slice of the file at a time. Cloudflare rejects bodies over
|
||||
* 100 MB, so the browser sends 50 MB slices and this route appends them to the
|
||||
* NFS temporary original. The final slice hashes the complete file, inserts the
|
||||
* metadata row, and starts FFmpeg through the same finalizer as the single-shot
|
||||
* upload route.
|
||||
*/
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id } = await params;
|
||||
const access = await getEventAccess(id, gate.id, gate.systemRole);
|
||||
if (!access) return errorResponse(404, "unknown event");
|
||||
if (!access.canContribute) {
|
||||
return errorResponse(403, "you are not assigned to this event");
|
||||
}
|
||||
|
||||
const uploadId = req.nextUrl.searchParams.get("uploadId") ?? "";
|
||||
if (!UPLOAD_ID_PATTERN.test(uploadId)) {
|
||||
return errorResponse(400, "a valid upload id is required");
|
||||
}
|
||||
|
||||
const offset = integerParam(req.nextUrl.searchParams.get("offset"));
|
||||
const total = integerParam(req.nextUrl.searchParams.get("size"));
|
||||
if (offset === null || total === null) {
|
||||
return errorResponse(400, "the upload offset and total size are required");
|
||||
}
|
||||
if (total <= 0 || total > MAX_EVENT_VIDEO_BYTES) {
|
||||
return errorResponse(
|
||||
413,
|
||||
`that video is larger than ${MAX_EVENT_VIDEO_LABEL}`,
|
||||
);
|
||||
}
|
||||
if (offset >= total) {
|
||||
return errorResponse(400, "the upload offset is outside the video");
|
||||
}
|
||||
|
||||
const declaredLength = Number(req.headers.get("content-length") ?? 0);
|
||||
if (!Number.isSafeInteger(declaredLength) || declaredLength <= 0) {
|
||||
return errorResponse(400, "the chunk has no content length");
|
||||
}
|
||||
if (declaredLength > EVENT_VIDEO_CHUNK_BYTES) {
|
||||
return errorResponse(
|
||||
413,
|
||||
"upload chunks must be 50 MB or smaller",
|
||||
);
|
||||
}
|
||||
if (offset + declaredLength > total) {
|
||||
return errorResponse(400, "the chunk extends past the end of the video");
|
||||
}
|
||||
const isFinal = offset + declaredLength === total;
|
||||
|
||||
const suppliedName = req.nextUrl.searchParams.get("name");
|
||||
if (!suppliedName) return errorResponse(400, "a filename is required");
|
||||
const filename = sanitizeVideoFilename(suppliedName);
|
||||
if (!isAllowedEventVideo(filename)) {
|
||||
return errorResponse(
|
||||
415,
|
||||
"unsupported video type; upload MP4, MOV, M4V, WebM, MKV, AVI, MPEG, MTS or 3GP",
|
||||
);
|
||||
}
|
||||
|
||||
const visibilityText =
|
||||
req.nextUrl.searchParams.get("visibility") ?? "team";
|
||||
if (
|
||||
!EVENT_VIDEO_VISIBILITIES.includes(
|
||||
visibilityText as (typeof EVENT_VIDEO_VISIBILITIES)[number],
|
||||
)
|
||||
) {
|
||||
return errorResponse(400, "invalid video visibility");
|
||||
}
|
||||
const visibility = visibilityText as EventVideoVisibility;
|
||||
if (visibility !== "team" && !access.canManage) {
|
||||
return errorResponse(
|
||||
403,
|
||||
"only a coordinator or admin can publish a video publicly",
|
||||
);
|
||||
}
|
||||
|
||||
const title =
|
||||
(req.nextUrl.searchParams.get("title") ?? "").trim().slice(0, 200) ||
|
||||
path.parse(filename).name.slice(0, 200);
|
||||
const description =
|
||||
(req.nextUrl.searchParams.get("description") ?? "").trim().slice(0, 5000) ||
|
||||
null;
|
||||
|
||||
const storage = await getStorageSettings();
|
||||
const archiveStatus = await checkArchiveDestination(storage);
|
||||
if (!archiveStatus.ready) {
|
||||
return errorResponse(
|
||||
409,
|
||||
`${archiveStatus.message} Configure the NFS archive in Settings before uploading video.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Stage under a client-scoped name, never under a final video id. The final
|
||||
// id is generated by the server when the last chunk arrives, so a caller
|
||||
// cannot overwrite another video's original by guessing its id.
|
||||
const stagingDir = eventVideoArchivePath(
|
||||
storage.archivePath,
|
||||
storage.archiveFolder,
|
||||
`videos/${id}/.uploads`,
|
||||
);
|
||||
const temporary = path.join(stagingDir, `${uploadId}.upload`);
|
||||
await mkdir(stagingDir, { recursive: true });
|
||||
|
||||
let existingSize = 0;
|
||||
try {
|
||||
existingSize = (await stat(temporary)).size;
|
||||
} catch (error) {
|
||||
if (!isMissing(error)) throw error;
|
||||
}
|
||||
if (existingSize !== offset) {
|
||||
return errorResponse(
|
||||
409,
|
||||
"the upload offset does not match the bytes already received; restart the upload",
|
||||
"UPLOAD_OFFSET_MISMATCH",
|
||||
);
|
||||
}
|
||||
if (!req.body) return errorResponse(400, "a video body is required");
|
||||
|
||||
const writeStream = createWriteStream(
|
||||
temporary,
|
||||
existingSize === 0
|
||||
? { flags: "w", mode: 0o640 }
|
||||
: { flags: "r+", start: offset, mode: 0o640 },
|
||||
);
|
||||
|
||||
try {
|
||||
await pipeline(
|
||||
Readable.from(req.body as unknown as AsyncIterable<Uint8Array>),
|
||||
writeStream,
|
||||
);
|
||||
} catch (error) {
|
||||
if (existingSize === 0) {
|
||||
await unlink(temporary).catch(() => undefined);
|
||||
} else {
|
||||
await truncate(temporary, offset).catch(() => undefined);
|
||||
}
|
||||
console.error(`event ${id}: video chunk upload failed`, error);
|
||||
return errorResponse(500, "the video chunk did not complete");
|
||||
}
|
||||
|
||||
const written = (await stat(temporary)).size;
|
||||
if (written !== offset + declaredLength) {
|
||||
if (existingSize === 0) {
|
||||
await unlink(temporary).catch(() => undefined);
|
||||
} else {
|
||||
await truncate(temporary, offset).catch(() => undefined);
|
||||
}
|
||||
return errorResponse(
|
||||
400,
|
||||
"the video chunk was incomplete; restart the upload",
|
||||
);
|
||||
}
|
||||
|
||||
if (!isFinal) {
|
||||
return jsonResponse({ complete: false, receivedBytes: written });
|
||||
}
|
||||
|
||||
try {
|
||||
const checksumSha256 = await checksumFile(temporary);
|
||||
const videoId = uuidv7();
|
||||
const storedName = originalStoredNameForEventVideo(id, videoId, filename);
|
||||
const destination = eventVideoArchivePath(
|
||||
storage.archivePath,
|
||||
storage.archiveFolder,
|
||||
storedName,
|
||||
);
|
||||
await mkdir(path.dirname(destination), { recursive: true });
|
||||
const result = await finalizeEventVideo({
|
||||
eventId: id,
|
||||
videoId,
|
||||
temporary,
|
||||
destination,
|
||||
checksumSha256,
|
||||
sizeBytes: total,
|
||||
filename,
|
||||
title,
|
||||
description,
|
||||
originalStoredName: storedName,
|
||||
archiveFolder: storage.archiveFolder,
|
||||
visibility,
|
||||
uploaderId: gate.id,
|
||||
event: access.event,
|
||||
});
|
||||
|
||||
return jsonResponse(
|
||||
result.duplicate
|
||||
? { video: videoView(result.video), duplicate: true }
|
||||
: { video: videoView(result.video) },
|
||||
result.duplicate ? 200 : 201,
|
||||
);
|
||||
} catch (error) {
|
||||
await unlink(temporary).catch(() => undefined);
|
||||
console.error(`event ${id}: video finalization failed`, error);
|
||||
return errorResponse(500, "the video could not be finalized");
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,213 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { createHash } from "node:crypto";
|
||||
import { createWriteStream } from "node:fs";
|
||||
import { mkdir, unlink } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { Readable, Transform } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getEventAccess } from "@/db/events";
|
||||
import { listEventVideos } from "@/db/videos";
|
||||
import { checkArchiveDestination, getStorageSettings } from "@/db/storage-settings";
|
||||
import {
|
||||
MAX_EVENT_VIDEO_BYTES,
|
||||
eventVideoArchivePath,
|
||||
isAllowedEventVideo,
|
||||
originalStoredNameForEventVideo,
|
||||
sanitizeVideoFilename,
|
||||
} from "@/lib/event-videos";
|
||||
import { finalizeEventVideo } from "@/lib/event-video-finalize";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
import { videoView } from "@/lib/video-view";
|
||||
import {
|
||||
EVENT_VIDEO_VISIBILITIES,
|
||||
type EventVideoVisibility,
|
||||
} from "@/db/schema";
|
||||
|
||||
class VideoTooLarge extends Error {}
|
||||
|
||||
/**
|
||||
* POST /api/events/:id/videos?name=service.mp4&title=Sunday&visibility=team
|
||||
*
|
||||
* Raw request body. The camera original streams straight to the NFS archive and
|
||||
* is hashed while it writes, so a 4 GB file never sits in memory. The stored
|
||||
* row starts as `processing`; FFmpeg creates the web MP4/poster in the
|
||||
* background and the browser polls the video endpoint for readiness.
|
||||
*/
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id } = await params;
|
||||
const access = await getEventAccess(id, gate.id, gate.systemRole);
|
||||
if (!access) return errorResponse(404, "unknown event");
|
||||
if (!access.canContribute) {
|
||||
return errorResponse(403, "you are not assigned to this event");
|
||||
}
|
||||
|
||||
const suppliedName = req.nextUrl.searchParams.get("name");
|
||||
if (!suppliedName) return errorResponse(400, "a filename is required");
|
||||
const filename = sanitizeVideoFilename(suppliedName);
|
||||
if (!isAllowedEventVideo(filename)) {
|
||||
return errorResponse(
|
||||
415,
|
||||
"unsupported video type; upload MP4, MOV, M4V, WebM, MKV, AVI, MPEG, MTS or 3GP",
|
||||
);
|
||||
}
|
||||
|
||||
const visibilityText =
|
||||
req.nextUrl.searchParams.get("visibility") ?? "team";
|
||||
if (
|
||||
!EVENT_VIDEO_VISIBILITIES.includes(
|
||||
visibilityText as (typeof EVENT_VIDEO_VISIBILITIES)[number],
|
||||
)
|
||||
) {
|
||||
return errorResponse(400, "invalid video visibility");
|
||||
}
|
||||
const visibility = visibilityText as EventVideoVisibility;
|
||||
if (visibility !== "team" && !access.canManage) {
|
||||
return errorResponse(
|
||||
403,
|
||||
"only a coordinator or admin can publish a video publicly",
|
||||
);
|
||||
}
|
||||
|
||||
const title =
|
||||
(req.nextUrl.searchParams.get("title") ?? "").trim().slice(0, 200) ||
|
||||
path.parse(filename).name.slice(0, 200);
|
||||
const description =
|
||||
(req.nextUrl.searchParams.get("description") ?? "").trim().slice(0, 5000) ||
|
||||
null;
|
||||
|
||||
const declaredLength = Number(req.headers.get("content-length") ?? 0);
|
||||
if (declaredLength > MAX_EVENT_VIDEO_BYTES) {
|
||||
return errorResponse(413, "that video is larger than 4 GB");
|
||||
}
|
||||
if (!req.body) return errorResponse(400, "a video body is required");
|
||||
|
||||
const storage = await getStorageSettings();
|
||||
const archiveStatus = await checkArchiveDestination(storage);
|
||||
if (!archiveStatus.ready) {
|
||||
return errorResponse(
|
||||
409,
|
||||
`${archiveStatus.message} Configure the NFS archive in Settings before uploading video.`,
|
||||
);
|
||||
}
|
||||
|
||||
const videoId = uuidv7();
|
||||
const storedName = originalStoredNameForEventVideo(id, videoId, filename);
|
||||
const destination = eventVideoArchivePath(
|
||||
storage.archivePath,
|
||||
storage.archiveFolder,
|
||||
storedName,
|
||||
);
|
||||
await mkdir(path.dirname(destination), { recursive: true });
|
||||
const temporary = `${destination}.${uuidv7()}.upload`;
|
||||
|
||||
const hash = createHash("sha256");
|
||||
let size = 0;
|
||||
const meter = new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
size += chunk.length;
|
||||
if (size > MAX_EVENT_VIDEO_BYTES) {
|
||||
callback(new VideoTooLarge());
|
||||
return;
|
||||
}
|
||||
hash.update(chunk);
|
||||
callback(null, chunk);
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await pipeline(
|
||||
Readable.from(req.body as unknown as AsyncIterable<Uint8Array>),
|
||||
meter,
|
||||
createWriteStream(temporary, { flags: "wx", mode: 0o640 }),
|
||||
);
|
||||
} catch (error) {
|
||||
await unlink(temporary).catch(() => undefined);
|
||||
if (error instanceof VideoTooLarge) {
|
||||
return errorResponse(413, "that video is larger than 4 GB");
|
||||
}
|
||||
console.error(`event ${id}: video upload failed`, error);
|
||||
return errorResponse(500, "the video upload did not complete");
|
||||
}
|
||||
|
||||
if (size === 0) {
|
||||
await unlink(temporary).catch(() => undefined);
|
||||
return errorResponse(400, "the uploaded video was empty");
|
||||
}
|
||||
|
||||
// Never accept a short body as an original. A proxy or middleware body limit
|
||||
// used to truncate large uploads while still returning 201, which produced a
|
||||
// corrupt NFS file and a video that could not be processed.
|
||||
if (declaredLength > 0 && size !== declaredLength) {
|
||||
await unlink(temporary).catch(() => undefined);
|
||||
return errorResponse(
|
||||
400,
|
||||
"the video upload did not complete; check your connection and try again",
|
||||
);
|
||||
}
|
||||
|
||||
const checksumSha256 = hash.digest("hex");
|
||||
|
||||
try {
|
||||
const result = await finalizeEventVideo({
|
||||
eventId: id,
|
||||
videoId,
|
||||
temporary,
|
||||
destination,
|
||||
checksumSha256,
|
||||
sizeBytes: size,
|
||||
filename,
|
||||
title,
|
||||
description,
|
||||
originalStoredName: storedName,
|
||||
archiveFolder: storage.archiveFolder,
|
||||
visibility,
|
||||
uploaderId: gate.id,
|
||||
event: access.event,
|
||||
});
|
||||
|
||||
return jsonResponse(
|
||||
result.duplicate
|
||||
? { video: videoView(result.video), duplicate: true }
|
||||
: { video: videoView(result.video) },
|
||||
result.duplicate ? 200 : 201,
|
||||
);
|
||||
} catch (error) {
|
||||
await unlink(temporary).catch(() => undefined);
|
||||
console.error(`event ${id}: video finalization failed`, error);
|
||||
return errorResponse(500, "the video could not be finalized");
|
||||
}
|
||||
};
|
||||
|
||||
/** GET /api/events/:id/videos — video list for one event. */
|
||||
export const GET = async (
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const { id } = await params;
|
||||
const access = await getEventAccess(id, gate.id, gate.systemRole);
|
||||
if (!access) return errorResponse(404, "unknown event");
|
||||
|
||||
const videos = await listEventVideos(id);
|
||||
return jsonResponse({
|
||||
videos: videos.map((video) =>
|
||||
videoView({
|
||||
...video,
|
||||
eventTitle: access.event.title,
|
||||
eventStartsAt: access.event.startsAt,
|
||||
}),
|
||||
),
|
||||
canManage: access.canManage,
|
||||
canContribute: access.canContribute,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,72 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser, gateSession } from "@/auth/api";
|
||||
import { createEvent, listEventsForUser } from "@/db/events";
|
||||
import { CHURCH_TIMEZONE, localToUtc } from "@/lib/tz";
|
||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||
|
||||
const LOCAL_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/;
|
||||
|
||||
const createSchema = z.object({
|
||||
title: z.string().trim().min(1).max(200),
|
||||
eventType: z.string().trim().min(1).max(50).optional(),
|
||||
startsAtLocal: z.string().regex(LOCAL_DATE_TIME, "invalid start time"),
|
||||
endsAtLocal: z
|
||||
.string()
|
||||
.regex(LOCAL_DATE_TIME, "invalid end time")
|
||||
.nullable()
|
||||
.optional(),
|
||||
location: z.string().trim().max(300).nullable().optional(),
|
||||
description: z.string().max(5000).nullable().optional(),
|
||||
});
|
||||
|
||||
function localDate(value: string): Date {
|
||||
const [date, time] = value.split("T");
|
||||
return localToUtc(date, time, CHURCH_TIMEZONE);
|
||||
}
|
||||
|
||||
/** GET /api/events — events the signed-in user may open. */
|
||||
export const GET = async () => {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const events = await listEventsForUser(gate.id, gate.systemRole);
|
||||
return jsonResponse({ events });
|
||||
};
|
||||
|
||||
/**
|
||||
* POST /api/events — create an event (coordinator/admin).
|
||||
*
|
||||
* Times are sent as church-local wall clock (`YYYY-MM-DDTHH:mm`), so the server
|
||||
* — not the browser's timezone — decides the UTC instant.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("schedule.publish");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
const parsed = createSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid event");
|
||||
}
|
||||
|
||||
const startsAt = localDate(parsed.data.startsAtLocal);
|
||||
const endsAt = parsed.data.endsAtLocal
|
||||
? localDate(parsed.data.endsAtLocal)
|
||||
: null;
|
||||
if (endsAt && endsAt <= startsAt) {
|
||||
return errorResponse(400, "the end time must be after the start time");
|
||||
}
|
||||
|
||||
const event = await createEvent({
|
||||
title: parsed.data.title,
|
||||
eventType: parsed.data.eventType ?? "photoshoot",
|
||||
startsAt,
|
||||
endsAt,
|
||||
location: parsed.data.location ?? null,
|
||||
description: parsed.data.description ?? null,
|
||||
createdBy: gate.id,
|
||||
});
|
||||
|
||||
return jsonResponse({ event }, 201);
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { servingHistoryCsv } from "@/db/exports";
|
||||
|
||||
/** GET /api/export/history — completed / no-show assignments as CSV. */
|
||||
export const GET = async () => {
|
||||
const gate = await gateOrUser("schedule.publish");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const csv = await servingHistoryCsv();
|
||||
return new Response(csv, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "text/csv; charset=utf-8",
|
||||
"content-disposition": 'attachment; filename="serving-history.csv"',
|
||||
"cache-control": "no-store",
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { gateOrUser } from "@/auth/api";
|
||||
import { scheduleCsv } from "@/db/exports";
|
||||
import { addDaysISO, dateInTimezone, CHURCH_TIMEZONE } from "@/lib/tz";
|
||||
|
||||
/**
|
||||
* GET /api/export/schedule?from=YYYY-MM-DD&to=YYYY-MM-DD
|
||||
* Defaults to the next four weeks. CSV only — printing is a browser action.
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const gate = await gateOrUser("schedule.publish");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
const today = dateInTimezone(new Date(), CHURCH_TIMEZONE);
|
||||
const from = req.nextUrl.searchParams.get("from") ?? today;
|
||||
const to = req.nextUrl.searchParams.get("to") ?? addDaysISO(from, 27);
|
||||
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(from) || !/^\d{4}-\d{2}-\d{2}$/.test(to)) {
|
||||
return new Response(JSON.stringify({ error: "invalid date" }), {
|
||||
status: 400,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
const csv = await scheduleCsv(from, to);
|
||||
return new Response(csv, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "text/csv; charset=utf-8",
|
||||
"content-disposition": `attachment; filename="schedule-${from}-to-${to}.csv"`,
|
||||
"cache-control": "no-store",
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { Readable } from "node:stream";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getEventVideoAccess, getPublicEventVideo } from "@/db/videos";
|
||||
import { eventVideoUploadPath } from "@/lib/event-videos";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
export const GET = async (
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const { id } = await params;
|
||||
let video = await getPublicEventVideo(id);
|
||||
let publicVideo = Boolean(video);
|
||||
|
||||
if (!video) {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
const access = await getEventVideoAccess(id, gate.id, gate.systemRole);
|
||||
if (!access) return errorResponse(404, "unknown video");
|
||||
video = {
|
||||
...access.video,
|
||||
eventTitle: access.event.title,
|
||||
eventStartsAt: access.event.startsAt,
|
||||
};
|
||||
publicVideo = false;
|
||||
}
|
||||
|
||||
if (!video.posterStoredName) {
|
||||
return errorResponse(404, "this video has no poster yet");
|
||||
}
|
||||
let filePath: string;
|
||||
try {
|
||||
filePath = eventVideoUploadPath(video.posterStoredName);
|
||||
} catch {
|
||||
return errorResponse(404, "unknown poster");
|
||||
}
|
||||
const info = await stat(filePath).catch(() => null);
|
||||
if (!info?.isFile()) return errorResponse(404, "the poster is missing");
|
||||
|
||||
const stream = createReadStream(filePath);
|
||||
return new Response(
|
||||
Readable.toWeb(stream) as unknown as ReadableStream<Uint8Array>,
|
||||
{
|
||||
headers: {
|
||||
"content-type": "image/jpeg",
|
||||
"content-length": String(info.size),
|
||||
"cache-control": publicVideo
|
||||
? "public, max-age=86400"
|
||||
: "private, max-age=0, must-revalidate",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,110 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { Readable } from "node:stream";
|
||||
import { gateSession } from "@/auth/api";
|
||||
import { getEventVideoAccess, getPublicEventVideo } from "@/db/videos";
|
||||
import {
|
||||
eventVideoUploadPath,
|
||||
sanitizeVideoFilename,
|
||||
videoContentDisposition,
|
||||
webRenditionStoredNameForEventVideo,
|
||||
} from "@/lib/event-videos";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { parseByteRange } from "@/lib/range";
|
||||
|
||||
/**
|
||||
* GET /api/media/:id/stream
|
||||
*
|
||||
* Serves the processed web MP4 or a lower-resolution rendition via
|
||||
* `?quality=720|480`. Public/unlisted ready videos need no session; team videos
|
||||
* reuse event access. Byte ranges keep browser seeking and mobile social embeds
|
||||
* working.
|
||||
*/
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const { id } = await params;
|
||||
let video = await getPublicEventVideo(id);
|
||||
let publicVideo = Boolean(video);
|
||||
|
||||
if (!video) {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
const access = await getEventVideoAccess(id, gate.id, gate.systemRole);
|
||||
if (!access) return errorResponse(404, "unknown video");
|
||||
video = {
|
||||
...access.video,
|
||||
eventTitle: access.event.title,
|
||||
eventStartsAt: access.event.startsAt,
|
||||
};
|
||||
publicVideo = false;
|
||||
}
|
||||
|
||||
if (video.status !== "ready" || !video.webStoredName) {
|
||||
return errorResponse(409, "this video is still processing");
|
||||
}
|
||||
|
||||
let filePath: string;
|
||||
let info: Awaited<ReturnType<typeof stat>> | null = null;
|
||||
try {
|
||||
filePath = eventVideoUploadPath(video.webStoredName);
|
||||
info = await stat(filePath).catch(() => null);
|
||||
|
||||
const quality = req.nextUrl.searchParams.get("quality");
|
||||
if ((quality === "720" || quality === "480") && info?.isFile()) {
|
||||
const renditionPath = eventVideoUploadPath(
|
||||
webRenditionStoredNameForEventVideo(
|
||||
video.eventId,
|
||||
video.id,
|
||||
Number(quality),
|
||||
),
|
||||
);
|
||||
const renditionInfo = await stat(renditionPath).catch(() => null);
|
||||
if (renditionInfo?.isFile()) {
|
||||
filePath = renditionPath;
|
||||
info = renditionInfo;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return errorResponse(404, "unknown video");
|
||||
}
|
||||
if (!info?.isFile()) {
|
||||
return errorResponse(404, "the processed video is missing");
|
||||
}
|
||||
|
||||
const range = parseByteRange(req.headers.get("range"), info.size);
|
||||
if (range === "invalid") {
|
||||
return new Response(null, {
|
||||
status: 416,
|
||||
headers: { "content-range": `bytes */${info.size}` },
|
||||
});
|
||||
}
|
||||
const start = range?.start ?? 0;
|
||||
const end = range?.end ?? info.size - 1;
|
||||
const stream = createReadStream(filePath, { start, end });
|
||||
|
||||
return new Response(
|
||||
Readable.toWeb(stream) as unknown as ReadableStream<Uint8Array>,
|
||||
{
|
||||
status: range ? 206 : 200,
|
||||
headers: {
|
||||
"content-type": "video/mp4",
|
||||
"content-length": String(end - start + 1),
|
||||
"accept-ranges": "bytes",
|
||||
...(range
|
||||
? { "content-range": `bytes ${start}-${end}/${info.size}` }
|
||||
: {}),
|
||||
"content-disposition": videoContentDisposition(
|
||||
`${sanitizeVideoFilename(video.title).replace(/\.mp4$/i, "")}.mp4`,
|
||||
true,
|
||||
),
|
||||
"cache-control": publicVideo
|
||||
? "public, max-age=3600"
|
||||
: "private, max-age=0, must-revalidate",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { getPublicEventVideo } from "@/db/videos";
|
||||
import { requestOrigin } from "@/auth/magic-link";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { videoView } from "@/lib/video-view";
|
||||
|
||||
/**
|
||||
* GET /api/oembed?url=https://host/watch/:id&format=json
|
||||
*
|
||||
* A standard oEmbed video response for WordPress, LMS pages, and other
|
||||
* consumers that do not read Open Graph tags. Only public/unlisted ready videos
|
||||
* are exposed.
|
||||
*/
|
||||
export const GET = async (req: NextRequest) => {
|
||||
const rawUrl = req.nextUrl.searchParams.get("url");
|
||||
if (!rawUrl) return errorResponse(400, "a url parameter is required");
|
||||
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
return errorResponse(400, "invalid url");
|
||||
}
|
||||
const match = /^\/(?:watch|embed)\/([A-Za-z0-9_-]+)\/?$/.exec(parsed.pathname);
|
||||
if (!match) return errorResponse(404, "no embeddable media at that url");
|
||||
|
||||
const video = await getPublicEventVideo(match[1]);
|
||||
if (!video) return errorResponse(404, "no embeddable media at that url");
|
||||
|
||||
const origin = requestOrigin(req);
|
||||
const view = videoView(video, origin);
|
||||
const payload = {
|
||||
version: "1.0",
|
||||
type: "video",
|
||||
provider_name: "Glenloch Baptist Church",
|
||||
provider_url: origin,
|
||||
title: video.title,
|
||||
author_name: video.eventTitle,
|
||||
url: view.watchUrl,
|
||||
html: view.embedCode,
|
||||
width: view.embedWidth,
|
||||
height: view.embedHeight,
|
||||
thumbnail_url: view.posterUrl,
|
||||
thumbnail_width: Math.min(1280, video.width ?? 1280),
|
||||
thumbnail_height: Math.min(720, video.height ?? 720),
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(payload), {
|
||||
headers: {
|
||||
"content-type": "application/json; charset=utf-8",
|
||||
"access-control-allow-origin": "*",
|
||||
"cache-control": "public, max-age=300",
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,117 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { clientIp } from "@/auth/api";
|
||||
import { RespondError, applyRespond } from "@/db/respond";
|
||||
import { verifyRespondToken } from "@/lib/respond";
|
||||
import { rateLimit } from "@/lib/rate-limit";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
const bodySchema = z.object({
|
||||
token: z.string().min(1),
|
||||
action: z.enum(["confirm", "decline"]),
|
||||
});
|
||||
|
||||
/** Map a refused respond action to its HTTP status. */
|
||||
function errorStatus(code: RespondError["code"]): number {
|
||||
switch (code) {
|
||||
case "already_used":
|
||||
case "not_actionable":
|
||||
return 409;
|
||||
case "unknown_assignment":
|
||||
return 404;
|
||||
case "wrong_volunteer":
|
||||
return 403;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/respond — { token, action: "confirm" | "decline" }
|
||||
*
|
||||
* The no-login confirm/decline endpoint (ARCHITECTURE §5.6). The signed token
|
||||
* carries the assignment, volunteer, action and `jti`; the `jti` is consumed
|
||||
* exactly once. `GET /respond` renders the page and never mutates, so a link
|
||||
* preview cannot accept a shift.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
let parsedBody: z.infer<typeof bodySchema>;
|
||||
try {
|
||||
const body = await req.json().catch(() => null);
|
||||
const parsed = bodySchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "a token and action are required" }),
|
||||
{ status: 400, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
parsedBody = parsed.data;
|
||||
} catch {
|
||||
return new Response(JSON.stringify({ error: "invalid body" }), {
|
||||
status: 400,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
|
||||
// Public endpoint: cap attempts per IP so tokens cannot be brute-forced.
|
||||
const limit = rateLimit(`respond:${clientIp(req)}`, 30, 60_000);
|
||||
if (!limit.ok) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: "too many attempts; try again shortly",
|
||||
code: "RATE_LIMITED",
|
||||
}),
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
...JSON_HEADERS,
|
||||
"retry-after": String(limit.retryAfterSeconds),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const payload = await verifyRespondToken(parsedBody.token);
|
||||
if (!payload) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: "this link is invalid or has expired",
|
||||
code: "invalid_token",
|
||||
}),
|
||||
{ status: 400, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
if (payload.action !== parsedBody.action) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: "this link is for a different action",
|
||||
code: "action_mismatch",
|
||||
}),
|
||||
{ status: 400, headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await applyRespond({
|
||||
assignmentId: payload.assignmentId,
|
||||
userId: payload.userId,
|
||||
action: payload.action,
|
||||
jti: payload.jti,
|
||||
});
|
||||
return new Response(JSON.stringify({ ok: true, ...result }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof RespondError) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: e.message, code: e.code }),
|
||||
{ status: errorStatus(e.code), headers: JSON_HEADERS },
|
||||
);
|
||||
}
|
||||
const message = e instanceof Error ? e.message : "internal error";
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 500,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,165 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { gateOrUser, gateSession } from "@/auth/api";
|
||||
import {
|
||||
addChecklistItem,
|
||||
addRunSheetItem,
|
||||
deleteChecklistItem,
|
||||
deleteRunSheetItem,
|
||||
saveRunSheetHeader,
|
||||
toggleChecklistItem,
|
||||
updateRunSheetItem,
|
||||
} from "@/db/runSheet";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
const json = (body: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(body), { status, headers: JSON_HEADERS });
|
||||
|
||||
const headerSchema = z.object({
|
||||
action: z.literal("save-header"),
|
||||
instanceId: z.string().min(1),
|
||||
speaker: z.string().max(200).nullable().optional(),
|
||||
sermonTitle: z.string().max(300).nullable().optional(),
|
||||
streamUrl: z.string().max(500).nullable().optional(),
|
||||
slidesUrl: z.string().max(500).nullable().optional(),
|
||||
notes: z.string().max(4000).nullable().optional(),
|
||||
});
|
||||
|
||||
const itemAddSchema = z.object({
|
||||
action: z.literal("add-item"),
|
||||
instanceId: z.string().min(1),
|
||||
title: z.string().min(1).max(200),
|
||||
timeLabel: z.string().max(20).nullable().optional(),
|
||||
owner: z.string().max(120).nullable().optional(),
|
||||
notes: z.string().max(1000).nullable().optional(),
|
||||
});
|
||||
|
||||
const itemUpdateSchema = z.object({
|
||||
action: z.literal("update-item"),
|
||||
id: z.string().min(1),
|
||||
title: z.string().min(1).max(200).optional(),
|
||||
timeLabel: z.string().max(20).nullable().optional(),
|
||||
owner: z.string().max(120).nullable().optional(),
|
||||
notes: z.string().max(1000).nullable().optional(),
|
||||
sortOrder: z.number().int().optional(),
|
||||
});
|
||||
|
||||
const itemDeleteSchema = z.object({
|
||||
action: z.literal("delete-item"),
|
||||
id: z.string().min(1),
|
||||
});
|
||||
|
||||
const checkToggleSchema = z.object({
|
||||
action: z.literal("toggle-check"),
|
||||
id: z.string().min(1),
|
||||
done: z.boolean(),
|
||||
});
|
||||
|
||||
const checkAddSchema = z.object({
|
||||
action: z.literal("add-check"),
|
||||
instanceId: z.string().min(1),
|
||||
phase: z.enum(["pre", "post"]),
|
||||
label: z.string().min(1).max(200),
|
||||
});
|
||||
|
||||
const checkDeleteSchema = z.object({
|
||||
action: z.literal("delete-check"),
|
||||
id: z.string().min(1),
|
||||
});
|
||||
|
||||
const bodySchema = z.discriminatedUnion("action", [
|
||||
headerSchema,
|
||||
itemAddSchema,
|
||||
itemUpdateSchema,
|
||||
itemDeleteSchema,
|
||||
checkToggleSchema,
|
||||
checkAddSchema,
|
||||
checkDeleteSchema,
|
||||
]);
|
||||
|
||||
async function body(req: NextRequest): Promise<unknown> {
|
||||
try {
|
||||
return await req.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run-sheet mutations. Anyone signed in can tick a checklist item (the team
|
||||
* shares the Sunday checklist); editing the sheet, adding or deleting rows is a
|
||||
* coordinator action.
|
||||
*/
|
||||
export const POST = async (req: NextRequest) => {
|
||||
const parsed = bodySchema.safeParse(await body(req));
|
||||
if (!parsed.success) return json({ error: parsed.error.message }, 400);
|
||||
|
||||
if (parsed.data.action === "toggle-check") {
|
||||
const gate = await gateSession();
|
||||
if (gate instanceof Response) return gate;
|
||||
const row = await toggleChecklistItem(
|
||||
parsed.data.id,
|
||||
gate.id,
|
||||
parsed.data.done,
|
||||
);
|
||||
if (!row) return json({ error: "checklist item not found" }, 404);
|
||||
return json({ ok: true, row });
|
||||
}
|
||||
|
||||
const gate = await gateOrUser("schedule.publish");
|
||||
if (gate instanceof Response) return gate;
|
||||
|
||||
switch (parsed.data.action) {
|
||||
case "save-header": {
|
||||
const data = parsed.data;
|
||||
await saveRunSheetHeader(data.instanceId, gate.id, {
|
||||
speaker: data.speaker,
|
||||
sermonTitle: data.sermonTitle,
|
||||
streamUrl: data.streamUrl,
|
||||
slidesUrl: data.slidesUrl,
|
||||
notes: data.notes,
|
||||
});
|
||||
return json({ ok: true });
|
||||
}
|
||||
case "add-item": {
|
||||
const data = parsed.data;
|
||||
const row = await addRunSheetItem(data.instanceId, {
|
||||
title: data.title,
|
||||
timeLabel: data.timeLabel,
|
||||
owner: data.owner,
|
||||
notes: data.notes,
|
||||
});
|
||||
return json({ ok: true, row }, 201);
|
||||
}
|
||||
case "update-item": {
|
||||
const data = parsed.data;
|
||||
const row = await updateRunSheetItem(data.id, {
|
||||
title: data.title,
|
||||
timeLabel: data.timeLabel,
|
||||
owner: data.owner,
|
||||
notes: data.notes,
|
||||
sortOrder: data.sortOrder,
|
||||
});
|
||||
if (!row) return json({ error: "run sheet item not found" }, 404);
|
||||
return json({ ok: true, row });
|
||||
}
|
||||
case "delete-item": {
|
||||
const deleted = await deleteRunSheetItem(parsed.data.id);
|
||||
if (!deleted) return json({ error: "run sheet item not found" }, 404);
|
||||
return json({ ok: true });
|
||||
}
|
||||
case "add-check": {
|
||||
const row = await addChecklistItem(
|
||||
parsed.data.instanceId,
|
||||
parsed.data.phase,
|
||||
parsed.data.label,
|
||||
);
|
||||
return json({ ok: true, row }, 201);
|
||||
}
|
||||
case "delete-check": {
|
||||
const deleted = await deleteChecklistItem(parsed.data.id);
|
||||
if (!deleted) return json({ error: "checklist item not found" }, 404);
|
||||
return json({ ok: true });
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { auth } from "@/auth/config";
|
||||
import { getResource } from "@/db/training";
|
||||
import { uploadPath } from "@/lib/uploads";
|
||||
|
||||
/**
|
||||
* Serve a training attachment to a signed-in team member.
|
||||
*
|
||||
* GET /api/training/files/:id
|
||||
*
|
||||
* Files are private (no public/ directory), so authoring uploads cannot be
|
||||
* fetched without a session. Content is served inline; the original filename is
|
||||
* preserved for downloads.
|
||||
*/
|
||||
export const GET = async (
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) => {
|
||||
const session = await auth();
|
||||
if (!session?.user) {
|
||||
return new Response("Authentication required", { status: 401 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const resource = await getResource(id);
|
||||
if (!resource) {
|
||||
return new Response("Not found", { status: 404 });
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await readFile(uploadPath(resource.storedName));
|
||||
const safeName = resource.filename.replaceAll('"', "");
|
||||
return new Response(new Uint8Array(data), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": resource.mimeType,
|
||||
"content-length": String(data.length),
|
||||
// Only images render inline; everything else is a download, so an
|
||||
// uploaded HTML/SVG payload cannot execute in this origin.
|
||||
"content-disposition": `${resource.mimeType.startsWith("image/") ? "inline" : "attachment"}; filename="${safeName}"; filename*=UTF-8''${encodeURIComponent(resource.filename)}`,
|
||||
"cache-control": "private, max-age=0, must-revalidate",
|
||||
"x-content-type-options": "nosniff",
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 });
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user