trails/apps/journal/app/routes/api.v1.routes.$id.ts
Ullrich Schäfer 7a1dca378f
journal: branded ownership loading for routes and activities
Ownership was checked ad hoc: some handlers loaded-and-compared
ownerId, some lib mutators enforced it in WHERE clauses and silently
no-op'd for non-owners, and nothing tied the two together. Two real
authorization bugs hid in the gaps: linkActivityToRoute ignored its
ownerId parameter entirely (any logged-in user could relink any
activity), and createRouteFromActivity loaded any activity without an
ownership check (a non-owner could copy a private activity's GPX into
their own route). PUT /api/v1/routes/:id also returned ok:true for
non-owners without updating anything.

ownership.server.ts is now the single enforcement point:

- loadOwnedRoute / loadOwnedActivity (non-throwing, for callers with
  their own error vocabulary) and requireOwnedRoute /
  requireOwnedActivity (throwing data() 404/403 for web handlers; 404
  by default so guessed ids don't leak existence)
- the returned entities carry an Owned<> brand; mutators (updateRoute,
  deleteRoute, deleteActivity, updateActivityVisibility,
  linkActivityToRoute, createRouteFromActivity) now require an
  OwnedRef, so skipping the check is a compile error
- vouchOwnership is the explicit, greppable escape hatch for the one
  non-session authorization path (the Planner JWT callback)
- WHERE ownerId clauses stay in the mutators as defense in depth

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 02:35:00 +02:00

70 lines
2.4 KiB
TypeScript

import type { Route } from "./+types/api.v1.routes.$id";
import { requireApiUser, apiError } from "~/lib/api-guard.server";
import { getRouteWithVersions, updateRoute, deleteRoute } from "~/lib/routes.server";
import { loadOwnedRoute } from "~/lib/ownership.server";
import { UpdateRouteRequestSchema, ERROR_CODES, zodIssuesToFieldErrors } from "@trails-cool/api";
/** GET /api/v1/routes/:id — full route detail */
export async function loader({ request, params }: Route.LoaderArgs) {
const user = await requireApiUser(request);
const route = await getRouteWithVersions(params.id);
if (!route || route.ownerId !== user.id) {
return apiError(404, ERROR_CODES.NOT_FOUND, "Route not found");
}
return Response.json({
id: route.id,
name: route.name,
description: route.description,
distance: route.distance,
elevationGain: route.elevationGain,
elevationLoss: route.elevationLoss,
routingProfile: route.routingProfile,
dayBreaks: route.dayBreaks ?? [],
gpx: route.gpx,
geojson: null, // TODO: fetch geojson
versions: route.versions.map((v) => ({
id: v.id,
version: v.version,
createdBy: v.createdBy,
changeDescription: v.changeDescription,
createdAt: v.createdAt.toISOString(),
})),
createdAt: route.createdAt.toISOString(),
updatedAt: route.updatedAt.toISOString(),
});
}
/** PUT /api/v1/routes/:id — update a route */
/** DELETE /api/v1/routes/:id — delete a route */
export async function action({ request, params }: Route.ActionArgs) {
const user = await requireApiUser(request);
if (request.method === "PUT") {
const body = await request.json().catch(() => null);
const parsed = UpdateRouteRequestSchema.safeParse(body);
if (!parsed.success) {
return apiError(400, ERROR_CODES.VALIDATION_ERROR, "Validation failed",
zodIssuesToFieldErrors(parsed.error));
}
const result = await loadOwnedRoute(params.id, user.id);
if (!result.ok) {
return apiError(404, ERROR_CODES.NOT_FOUND, "Route not found");
}
await updateRoute(result.entity, parsed.data);
return Response.json({ ok: true });
}
if (request.method === "DELETE") {
const result = await loadOwnedRoute(params.id, user.id);
if (!result.ok) {
return apiError(404, ERROR_CODES.NOT_FOUND, "Route not found");
}
await deleteRoute(result.entity);
return new Response(null, { status: 204 });
}
return new Response(null, { status: 405 });
}