Session-bind /api/route and /api/overpass
Today both proxies are effectively open to anyone who can set an Origin header for trails.cool — a third party can use us as a free BRouter/Overpass relay. Require a live planner session on every call so abuse traffic costs the scraper a session row (observable, revocable) before they can issue a single query. Server: - New `requireSession(id)` helper — returns the session row or a 401 Response. Reused by both route handlers. - `/api/route`: `sessionId` in body is now required and verified; rate-limit key always falls back to the session id. - `/api/overpass`: new `X-Trails-Session` header, verified. Header keeps the session out of the request body so the body-keyed cache is unaffected. Client plumbing: - `useRouting(yjs, sessionId)` — sessionId goes into the /api/route body. - `usePois(sessionId)` → `queryPois(..., sessionId)` → `X-Trails-Session` on the proxy call. - `PlannerMap` + `YjsDebugPanel` gain a `sessionId` prop from `SessionView`. Journal server-to-server: - Demo-bot and `/api/v1/routes/compute` now POST `/api/sessions` to mint a throwaway planner session, then cite it on the forwarded `/api/route` call. Planner's `expire-sessions` cron cleans these up (7d window) so nothing needs explicit teardown. Tests: - 5 unit tests for `requireSession` covering missing / empty / non-string / unknown-session / valid-session cases. - Two integration E2E tests document the 401 for missing session on each proxy. - Pre-existing `/api/route` integration tests updated to mint a session first. Caveat: existing browser tabs lose their /api/route ability until reload (the old JS doesn't know to send sessionId). Acceptable for an anonymous planner. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
963902514b
commit
ed7f6ce153
13 changed files with 204 additions and 17 deletions
|
|
@ -134,6 +134,7 @@ export function deduplicateById(pois: Poi[]): Poi[] {
|
|||
export async function queryPois(
|
||||
bbox: BBox,
|
||||
categories: PoiCategory[],
|
||||
sessionId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Poi[]> {
|
||||
if (categories.length === 0) return [];
|
||||
|
|
@ -142,7 +143,12 @@ export async function queryPois(
|
|||
|
||||
const response = await fetch(OVERPASS_PROXY, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
// Bind this call to the active planner session so the proxy
|
||||
// isn't anonymously reachable.
|
||||
"X-Trails-Session": sessionId,
|
||||
},
|
||||
body: `data=${encodeURIComponent(query)}`,
|
||||
signal,
|
||||
});
|
||||
|
|
|
|||
51
apps/planner/app/lib/require-session.test.ts
Normal file
51
apps/planner/app/lib/require-session.test.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("./sessions.ts", () => ({
|
||||
getSession: vi.fn(),
|
||||
}));
|
||||
|
||||
import { requireSession } from "./require-session.ts";
|
||||
import { getSession } from "./sessions.ts";
|
||||
|
||||
const mockedGetSession = vi.mocked(getSession);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("requireSession", () => {
|
||||
it("returns the session when it exists and is open", async () => {
|
||||
mockedGetSession.mockResolvedValueOnce({ id: "abc" } as never);
|
||||
const result = await requireSession("abc");
|
||||
expect(result).toEqual({ id: "abc" });
|
||||
expect(mockedGetSession).toHaveBeenCalledWith("abc");
|
||||
});
|
||||
|
||||
it("returns 401 when the id is missing", async () => {
|
||||
const result = await requireSession(undefined);
|
||||
expect(result).toBeInstanceOf(Response);
|
||||
expect((result as Response).status).toBe(401);
|
||||
expect(mockedGetSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 401 for empty-string id (doesn't look it up)", async () => {
|
||||
const result = await requireSession("");
|
||||
expect(result).toBeInstanceOf(Response);
|
||||
expect((result as Response).status).toBe(401);
|
||||
expect(mockedGetSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 401 for a non-string id", async () => {
|
||||
const result = await requireSession(null);
|
||||
expect(result).toBeInstanceOf(Response);
|
||||
expect((result as Response).status).toBe(401);
|
||||
expect(mockedGetSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 401 when the session doesn't exist (or is closed)", async () => {
|
||||
mockedGetSession.mockResolvedValueOnce(undefined);
|
||||
const result = await requireSession("nonexistent");
|
||||
expect(result).toBeInstanceOf(Response);
|
||||
expect((result as Response).status).toBe(401);
|
||||
});
|
||||
});
|
||||
25
apps/planner/app/lib/require-session.ts
Normal file
25
apps/planner/app/lib/require-session.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { getSession, type SessionMetadata } from "./sessions.ts";
|
||||
|
||||
/**
|
||||
* Gate a proxy endpoint on the presence of a valid planner session.
|
||||
* Returns the session row if `id` names an open session, or a 401
|
||||
* Response for the caller to return otherwise. Callers:
|
||||
*
|
||||
* const session = await requireSession(sessionId);
|
||||
* if (session instanceof Response) return session;
|
||||
*
|
||||
* The session timeout is handled by the `expire-sessions` cron; a
|
||||
* missing or closed row is treated the same way here.
|
||||
*/
|
||||
export async function requireSession(
|
||||
id: string | null | undefined,
|
||||
): Promise<SessionMetadata | Response> {
|
||||
if (!id || typeof id !== "string") {
|
||||
return new Response("Missing session", { status: 401 });
|
||||
}
|
||||
const session = await getSession(id);
|
||||
if (!session) {
|
||||
return new Response("Unknown or closed session", { status: 401 });
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
|
@ -20,7 +20,7 @@ export interface PoiState {
|
|||
refresh: (bbox: BBox, zoom: number) => void;
|
||||
}
|
||||
|
||||
export function usePois(): PoiState {
|
||||
export function usePois(sessionId: string): PoiState {
|
||||
const [pois, setPois] = useState<Poi[]>([]);
|
||||
const [status, setStatus] = useState<PoiStatus>("idle");
|
||||
const [enabledCategories, setEnabledCategories] = useState<string[]>([]);
|
||||
|
|
@ -76,7 +76,7 @@ export function usePois(): PoiState {
|
|||
lastRequestRef.current = Date.now();
|
||||
|
||||
try {
|
||||
const result = await queryPois(bbox, categories, controller.signal);
|
||||
const result = await queryPois(bbox, categories, sessionId, controller.signal);
|
||||
if (controller.signal.aborted) return;
|
||||
|
||||
setCached(bbox, categoriesKey, result);
|
||||
|
|
@ -98,7 +98,7 @@ export function usePois(): PoiState {
|
|||
}
|
||||
}, delay);
|
||||
},
|
||||
[enabledCategories],
|
||||
[enabledCategories, sessionId],
|
||||
);
|
||||
|
||||
// Cleanup on unmount
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ function restoreWaypoints(yjs: YjsState, snapshot: WaypointData[], restoringRef:
|
|||
|
||||
export type RouteError = "no_route" | "failed" | "rate_limit" | null;
|
||||
|
||||
export function useRouting(yjs: YjsState | null) {
|
||||
export function useRouting(yjs: YjsState | null, sessionId: string) {
|
||||
const [isHost, setIsHost] = useState(false);
|
||||
const [computing, setComputing] = useState(false);
|
||||
const [routeError, setRouteError] = useState<RouteError>(null);
|
||||
|
|
@ -93,6 +93,7 @@ export function useRouting(yjs: YjsState | null) {
|
|||
waypoints,
|
||||
profile: (yjs.routeData.get("profile") as string) ?? "fastbike",
|
||||
noGoAreas: noGoAreas.length > 0 ? noGoAreas : undefined,
|
||||
sessionId,
|
||||
}),
|
||||
});
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue