trails/apps/journal/app/routes/api.routes.$id.edit-in-planner.ts
Ullrich Schäfer 4de6c86d41
fix(journal): architectural audit omnibus
Addresses 8 issues from the Journal architecture audit:

1. DB indexes on routes.ownerId + activities.ownerId. Listing queries on
   these tables were full table scans; adds composite indexes matching
   the order-by columns (updatedAt/startedAt/createdAt).
2. Zod validation on /api/auth/register body. Previously the action
   destructured request.json() with zero schema validation.
3. N+1 GeoJSON batch fetch collapsed to a single ANY($1::text[]) query
   in both routes.server and activities.server.
4. Webhook envelope validation in /api/sync/webhook/:provider.
5. AbortSignal.timeout(30s) on all external fetches (Komoot, Wahoo) via
   a new fetchWithTimeout helper in lib/http.server.ts.
6. .limit(100) on listPublicRoutesForOwner / listPublicActivitiesForOwner.
9. Welcome email moved off fire-and-forget onto a pg-boss job with
   retryLimit: 3 (send-welcome-email).
10. process.env.ORIGIN ?? "http://localhost:3000" centralized into
    lib/config.server.ts::getOrigin() across 14 call sites.

Issues 7 (centralized apiError/auth guards across 60+ route files) and
8 (split .server.ts boundaries across 20+ route files) intentionally
deferred — both are pure refactors that would balloon this PR past
reviewability and warrant their own focused PRs.

Tests added:
- lib/config.server.test.ts (2 cases)
- lib/http.server.test.ts (3 cases — timeout abort, success passthrough,
  caller-signal composition)
- routes/api.sync.webhook.$provider.test.ts (6 cases)
- routes/api.auth.register.test.ts (7 cases — schema rejection paths +
  the new welcome-email enqueue assertion)

Full repo: pnpm typecheck, pnpm lint, pnpm test all green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 10:28:33 +02:00

59 lines
2.2 KiB
TypeScript

import { data } from "react-router";
import { getOrigin } from "~/lib/config.server";
import type { Route } from "./+types/api.routes.$id.edit-in-planner";
import { getSessionUser } from "~/lib/auth/session.server";
import { getRouteWithVersions } from "~/lib/routes.server";
import { createRouteToken } from "~/lib/jwt.server";
export async function action({ params, request }: Route.ActionArgs) {
const user = await getSessionUser(request);
if (!user) return data({ error: "Not authenticated" }, { status: 401 });
const route = await getRouteWithVersions(params.id);
if (!route) return data({ error: "Route not found" }, { status: 404 });
if (route.ownerId !== user.id) return data({ error: "Not authorized" }, { status: 403 });
const token = await createRouteToken(params.id);
const origin = getOrigin();
const callbackUrl = `${origin}/api/routes/${params.id}/callback`;
const plannerUrl = process.env.PLANNER_URL ?? "http://localhost:3001";
const returnUrl = `${origin}/routes/${params.id}`;
// Create Planner session via API (POST body, not URL params)
const sessionResp = await fetch(`${plannerUrl}/api/sessions`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
callbackUrl,
callbackToken: token,
gpx: route.gpx ?? undefined,
}),
});
if (!sessionResp.ok) {
return data({ error: "Failed to create Planner session" }, { status: 502 });
}
const session = (await sessionResp.json()) as {
url: string;
initialWaypoints?: Array<{ lat: number; lon: number; name?: string; isDayBreak?: boolean; note?: string; osmId?: number; poiTags?: Record<string, string> }>;
initialNoGoAreas?: Array<{ points: Array<{ lat: number; lon: number }> }>;
initialNotes?: string;
};
// Encode planning data in URL params
const urlParams = new URLSearchParams({ returnUrl });
if (session.initialWaypoints?.length) {
urlParams.set("waypoints", JSON.stringify(session.initialWaypoints));
}
if (session.initialNoGoAreas?.length) {
urlParams.set("noGoAreas", JSON.stringify(session.initialNoGoAreas));
}
if (session.initialNotes) {
urlParams.set("notes", session.initialNotes);
}
return data({
url: `${plannerUrl}${session.url}?${urlParams}`,
});
}