Merge branch 'main' into package-shims
This commit is contained in:
commit
f684272eb5
37 changed files with 939 additions and 844 deletions
18
.github/dependabot.yml
vendored
18
.github/dependabot.yml
vendored
|
|
@ -20,10 +20,22 @@ updates:
|
|||
update-types: ["version-update:semver-major"]
|
||||
- dependency-name: "@types/node"
|
||||
update-types: ["version-update:semver-major"]
|
||||
# react-native is pinned by the Expo SDK — upgrade it via an Expo
|
||||
# SDK bump, not on its own. Community react-native-* libraries are
|
||||
# intentionally NOT ignored here; they can be bumped independently.
|
||||
# These packages are version-pinned by the Expo SDK (see
|
||||
# expo/bundledNativeModules.json) — upgrade them via an Expo SDK
|
||||
# bump / `npx expo install --fix`, never on their own. Dependabot
|
||||
# bumping them past the SDK's expected version broke the native
|
||||
# build (expo-modules-core macro mismatch, June 2026) because CI
|
||||
# never compiles native code. `react` stays unignored: the web
|
||||
# apps own its version via the workspace catalog, and apps/mobile
|
||||
# excludes it from expo version checks.
|
||||
- dependency-name: "react-native"
|
||||
- dependency-name: "react-native-gesture-handler"
|
||||
- dependency-name: "react-native-reanimated"
|
||||
- dependency-name: "react-native-safe-area-context"
|
||||
- dependency-name: "react-native-screens"
|
||||
- dependency-name: "react-native-worklets"
|
||||
- dependency-name: "@sentry/react-native"
|
||||
- dependency-name: "jest-expo"
|
||||
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ import { unionAll } from "drizzle-orm/pg-core";
|
|||
import { getDb } from "./db.ts";
|
||||
import { activities, routes, syncImports, users, follows, remoteActors } from "@trails-cool/db/schema/journal";
|
||||
import type { Visibility } from "@trails-cool/db/schema/journal";
|
||||
import { validateGpx, writeGeom } from "./gpx-save.server.ts";
|
||||
import type { GpxData } from "./gpx-save.server.ts";
|
||||
import { processGpx, writeGeom } from "./gpx-save.server.ts";
|
||||
import type { ProcessedGpx } from "./gpx-save.server.ts";
|
||||
import { enqueueOptional } from "./boss.server.ts";
|
||||
import type { OwnedRef } from "./ownership.server.ts";
|
||||
import {
|
||||
|
|
@ -70,7 +70,7 @@ export async function createActivity(ownerId: string, input: ActivityInput) {
|
|||
const db = getDb();
|
||||
const id = randomUUID();
|
||||
|
||||
let parsed: GpxData | null = null;
|
||||
let processed: ProcessedGpx | null = null;
|
||||
let distance: number | null = input.distance ?? null;
|
||||
let elevationGain: number | null = null;
|
||||
let elevationLoss: number | null = null;
|
||||
|
|
@ -78,13 +78,12 @@ export async function createActivity(ownerId: string, input: ActivityInput) {
|
|||
const duration: number | null = input.duration ?? null;
|
||||
|
||||
if (input.gpx) {
|
||||
parsed = await validateGpx(input.gpx);
|
||||
distance = parsed.distance || distance;
|
||||
elevationGain = parsed.elevation.gain;
|
||||
elevationLoss = parsed.elevation.loss;
|
||||
if (!startedAt && parsed.tracks[0]?.[0]?.time) {
|
||||
startedAt = new Date(parsed.tracks[0][0].time);
|
||||
}
|
||||
processed = await processGpx(input.gpx);
|
||||
// GPX-derived distance wins unless it is zero; caller input is the fallback
|
||||
distance = processed.stats.distance || distance;
|
||||
elevationGain = processed.stats.elevationGain;
|
||||
elevationLoss = processed.stats.elevationLoss;
|
||||
startedAt = startedAt ?? processed.stats.startTime;
|
||||
}
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
|
|
@ -104,9 +103,8 @@ export async function createActivity(ownerId: string, input: ActivityInput) {
|
|||
...(input.synthetic ? { synthetic: true } : {}),
|
||||
});
|
||||
|
||||
if (input.gpx && parsed) {
|
||||
const coords = parsed.tracks.flat().map((p) => [p.lon, p.lat] as [number, number]);
|
||||
await writeGeom(tx, id, "activities", coords);
|
||||
if (input.gpx && processed) {
|
||||
await writeGeom(tx, id, "activities", processed.coords);
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -332,8 +330,7 @@ export async function createRouteFromActivity(ownedActivity: OwnedRef): Promise<
|
|||
.where(and(eq(activities.id, activityId), eq(activities.ownerId, ownerId)));
|
||||
if (!activity?.gpx) return null;
|
||||
|
||||
const parsed = await validateGpx(activity.gpx);
|
||||
const coords = parsed.tracks.flat().map((p) => [p.lon, p.lat] as [number, number]);
|
||||
const { coords } = await processGpx(activity.gpx);
|
||||
const routeId = randomUUID();
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import type { z } from "zod";
|
||||
import { getAuthenticatedUser } from "./oauth.server.ts";
|
||||
import { TERMS_VERSION } from "./legal.ts";
|
||||
import { ERROR_CODES } from "@trails-cool/api";
|
||||
|
|
@ -36,3 +37,19 @@ export async function requireApiUser(request: Request) {
|
|||
export function apiError(status: number, code: string, message: string, fields?: Array<{ field: string; message: string }>) {
|
||||
return Response.json({ error: message, code, fields }, { status });
|
||||
}
|
||||
|
||||
/**
|
||||
* Respond with a payload validated against its @trails-cool/api
|
||||
* contract. The schema is enforced, not advisory: a handler whose
|
||||
* payload drifts from the contract fails its unit tests / e2e run with
|
||||
* a ZodError instead of silently shipping a different wire shape.
|
||||
* Parsing also strips unknown keys, so the response is exactly the
|
||||
* contract — nothing extra leaks.
|
||||
*/
|
||||
export function apiJson<S extends z.ZodType>(
|
||||
schema: S,
|
||||
payload: z.input<S>,
|
||||
init?: ResponseInit,
|
||||
): Response {
|
||||
return Response.json(schema.parse(payload), init);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,162 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
const link = vi.fn();
|
||||
vi.mock("./manager.ts", () => ({
|
||||
link: (...args: unknown[]) => link(...args),
|
||||
}));
|
||||
vi.mock("../config.server.ts", () => ({
|
||||
getOrigin: () => "https://journal.test",
|
||||
}));
|
||||
|
||||
import { initiateOAuthFlow, completeOAuthFlow } from "./oauth-flow.server.ts";
|
||||
import { decodeOAuthState } from "./oauth-state.server.ts";
|
||||
import type { ProviderManifest } from "./registry.ts";
|
||||
|
||||
function fakeManifest(overrides: Partial<ProviderManifest> = {}): ProviderManifest {
|
||||
return {
|
||||
id: "fakeprov",
|
||||
displayName: "Fake Provider",
|
||||
credentialKind: "oauth",
|
||||
credentialAdapter: { isExpired: () => false, refresh: vi.fn() },
|
||||
buildAuthUrl: vi.fn(
|
||||
(redirectUri: string, state: string, extras?: { codeChallenge?: string }) =>
|
||||
`https://provider.test/authorize?redirect_uri=${encodeURIComponent(redirectUri)}&state=${state}` +
|
||||
(extras?.codeChallenge ? `&code_challenge=${extras.codeChallenge}` : ""),
|
||||
),
|
||||
exchangeCode: vi.fn(),
|
||||
...overrides,
|
||||
} as unknown as ProviderManifest;
|
||||
}
|
||||
|
||||
function callbackRequest(params: Record<string, string>, cookie?: string): Request {
|
||||
const url = new URL("https://journal.test/api/sync/callback/fakeprov");
|
||||
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||
return new Request(url, { headers: cookie ? { Cookie: cookie } : {} });
|
||||
}
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
describe("initiateOAuthFlow", () => {
|
||||
it("redirects to the provider with the intent in the state, no cookie for non-PKCE", () => {
|
||||
const manifest = fakeManifest();
|
||||
const resp = initiateOAuthFlow(manifest, { returnTo: "/settings/connections" });
|
||||
|
||||
expect(resp.status).toBe(302);
|
||||
const location = new URL(resp.headers.get("Location")!);
|
||||
expect(location.origin).toBe("https://provider.test");
|
||||
expect(location.searchParams.get("redirect_uri")).toBe(
|
||||
"https://journal.test/api/sync/callback/fakeprov",
|
||||
);
|
||||
expect(decodeOAuthState(location.searchParams.get("state"))).toEqual({
|
||||
returnTo: "/settings/connections",
|
||||
});
|
||||
expect(resp.headers.get("Set-Cookie")).toBeNull();
|
||||
});
|
||||
|
||||
it("PKCE: sets the verifier cookie and sends its S256 challenge", () => {
|
||||
const manifest = fakeManifest({ pkce: true });
|
||||
const resp = initiateOAuthFlow(manifest, { pushAfter: { routeId: "r-1" }, returnTo: "/r" });
|
||||
|
||||
const cookie = resp.headers.get("Set-Cookie")!;
|
||||
expect(cookie).toContain("__oauth_pkce=");
|
||||
expect(cookie).toContain("HttpOnly");
|
||||
const verifier = cookie.match(/__oauth_pkce=([^;]+)/)![1]!;
|
||||
|
||||
const location = new URL(resp.headers.get("Location")!);
|
||||
const expectedChallenge = createHash("sha256").update(verifier).digest("base64url");
|
||||
expect(location.searchParams.get("code_challenge")).toBe(expectedChallenge);
|
||||
// push intent rides the state even on the PKCE path
|
||||
expect(decodeOAuthState(location.searchParams.get("state"))).toEqual({
|
||||
pushAfter: { routeId: "r-1" },
|
||||
returnTo: "/r",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("completeOAuthFlow", () => {
|
||||
it("maps access_denied to denied with decoded state", async () => {
|
||||
const manifest = fakeManifest();
|
||||
const state = new URL(
|
||||
initiateOAuthFlow(manifest, { returnTo: "/x" }).headers.get("Location")!,
|
||||
).searchParams.get("state")!;
|
||||
|
||||
const result = await completeOAuthFlow(
|
||||
manifest,
|
||||
callbackRequest({ error: "access_denied", state }),
|
||||
"user-1",
|
||||
);
|
||||
expect(result).toEqual({ status: "denied", state: { returnTo: "/x" } });
|
||||
expect(link).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns missing_code when no code param", async () => {
|
||||
const result = await completeOAuthFlow(fakeManifest(), callbackRequest({}), "user-1");
|
||||
expect(result.status).toBe("missing_code");
|
||||
});
|
||||
|
||||
it("PKCE: returns missing_verifier when the cookie is gone", async () => {
|
||||
const result = await completeOAuthFlow(
|
||||
fakeManifest({ pkce: true }),
|
||||
callbackRequest({ code: "abc" }),
|
||||
"user-1",
|
||||
);
|
||||
expect(result.status).toBe("missing_verifier");
|
||||
});
|
||||
|
||||
it("exchanges the code and links the connection", async () => {
|
||||
const manifest = fakeManifest();
|
||||
(manifest.exchangeCode as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
credentials: { accessToken: "t" },
|
||||
providerUserId: "prov-9",
|
||||
grantedScopes: ["routes_write"],
|
||||
});
|
||||
|
||||
const result = await completeOAuthFlow(manifest, callbackRequest({ code: "abc" }), "user-1");
|
||||
|
||||
expect(result.status).toBe("linked");
|
||||
expect(manifest.exchangeCode).toHaveBeenCalledWith(
|
||||
"abc",
|
||||
"https://journal.test/api/sync/callback/fakeprov",
|
||||
undefined,
|
||||
);
|
||||
expect(link).toHaveBeenCalledWith({
|
||||
userId: "user-1",
|
||||
provider: "fakeprov",
|
||||
credentialKind: "oauth",
|
||||
credentials: { accessToken: "t" },
|
||||
providerUserId: "prov-9",
|
||||
grantedScopes: ["routes_write"],
|
||||
});
|
||||
});
|
||||
|
||||
it("PKCE: passes the cookie verifier to exchangeCode", async () => {
|
||||
const manifest = fakeManifest({ pkce: true });
|
||||
(manifest.exchangeCode as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
credentials: {},
|
||||
providerUserId: "p",
|
||||
grantedScopes: [],
|
||||
});
|
||||
|
||||
await completeOAuthFlow(
|
||||
manifest,
|
||||
callbackRequest({ code: "abc" }, "__oauth_pkce=my-verifier"),
|
||||
"user-1",
|
||||
);
|
||||
expect(manifest.exchangeCode).toHaveBeenCalledWith(
|
||||
"abc",
|
||||
expect.any(String),
|
||||
{ codeVerifier: "my-verifier" },
|
||||
);
|
||||
});
|
||||
|
||||
it("maps exchange failures to error with the provider code", async () => {
|
||||
const manifest = fakeManifest();
|
||||
(manifest.exchangeCode as ReturnType<typeof vi.fn>).mockRejectedValue(
|
||||
Object.assign(new Error("nope"), { code: "rate_limited" }),
|
||||
);
|
||||
|
||||
const result = await completeOAuthFlow(manifest, callbackRequest({ code: "x" }), "user-1");
|
||||
expect(result).toMatchObject({ status: "error", code: "rate_limited" });
|
||||
});
|
||||
});
|
||||
122
apps/journal/app/lib/connected-services/oauth-flow.server.ts
Normal file
122
apps/journal/app/lib/connected-services/oauth-flow.server.ts
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
// The OAuth connect → callback lifecycle as one module. Routes stay
|
||||
// thin adapters: they look up the manifest, call initiate/complete,
|
||||
// and map the result to redirects. Everything protocol-shaped —
|
||||
// state encoding, PKCE pair generation, the verifier cookie's
|
||||
// lifecycle, redirect-URI construction, code exchange, linking the
|
||||
// connection — lives here, so the next OAuth provider (Coros, Strava)
|
||||
// reuses the flow instead of the pattern.
|
||||
|
||||
import { redirect } from "react-router";
|
||||
import { getOrigin } from "../config.server.ts";
|
||||
import { link } from "./manager.ts";
|
||||
import type { ProviderManifest } from "./registry.ts";
|
||||
import {
|
||||
clearPkceCookieHeader,
|
||||
decodeOAuthState,
|
||||
encodeOAuthState,
|
||||
generatePkcePair,
|
||||
pkceCookieHeader,
|
||||
readPkceVerifier,
|
||||
type PushOAuthState,
|
||||
} from "./oauth-state.server.ts";
|
||||
|
||||
function callbackUri(manifest: ProviderManifest): string {
|
||||
return `${getOrigin()}/api/sync/callback/${manifest.id}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the provider authorization redirect. Encodes post-callback
|
||||
* intent into the state param and, for PKCE providers, sets the
|
||||
* httpOnly verifier cookie — including when the flow is initiated
|
||||
* from a push-resume (the old inline code only handled PKCE on the
|
||||
* plain connect path).
|
||||
*
|
||||
* Caller must have verified `manifest.buildAuthUrl` exists.
|
||||
*/
|
||||
export function initiateOAuthFlow(
|
||||
manifest: ProviderManifest,
|
||||
intent: PushOAuthState,
|
||||
): Response {
|
||||
if (!manifest.buildAuthUrl) {
|
||||
throw new Error(`Provider ${manifest.id} has no buildAuthUrl`);
|
||||
}
|
||||
const state = encodeOAuthState(intent);
|
||||
const redirectUri = callbackUri(manifest);
|
||||
|
||||
if (manifest.pkce) {
|
||||
const { verifier, challenge } = generatePkcePair();
|
||||
return redirect(manifest.buildAuthUrl(redirectUri, state, { codeChallenge: challenge }), {
|
||||
headers: { "Set-Cookie": pkceCookieHeader(verifier) },
|
||||
});
|
||||
}
|
||||
return redirect(manifest.buildAuthUrl(redirectUri, state));
|
||||
}
|
||||
|
||||
export type OAuthCompletion =
|
||||
/** Provider sent the user back with access_denied. */
|
||||
| { status: "denied"; state: PushOAuthState }
|
||||
/** No authorization code in the callback URL. */
|
||||
| { status: "missing_code"; state: PushOAuthState }
|
||||
/** PKCE provider but the verifier cookie is gone (expired / cleared). */
|
||||
| { status: "missing_verifier"; state: PushOAuthState }
|
||||
/** Code exchange or linking failed; `code` is provider-specific or "sync_failed". */
|
||||
| { status: "error"; code: string; state: PushOAuthState }
|
||||
/** Connection linked. */
|
||||
| { status: "linked"; state: PushOAuthState };
|
||||
|
||||
/**
|
||||
* Consume the provider callback: decode state, recover the PKCE
|
||||
* verifier, exchange the code, and link the connection. Never throws —
|
||||
* every outcome is a variant the route maps to a redirect. The spent
|
||||
* verifier cookie should be cleared on whatever response the route
|
||||
* returns (`clearPkceCookieHeader`).
|
||||
*/
|
||||
export async function completeOAuthFlow(
|
||||
manifest: ProviderManifest,
|
||||
request: Request,
|
||||
userId: string,
|
||||
): Promise<OAuthCompletion> {
|
||||
if (!manifest.exchangeCode) {
|
||||
throw new Error(`Provider ${manifest.id} has no exchangeCode`);
|
||||
}
|
||||
const url = new URL(request.url);
|
||||
const state = decodeOAuthState(url.searchParams.get("state"));
|
||||
|
||||
if (url.searchParams.get("error") === "access_denied") {
|
||||
return { status: "denied", state };
|
||||
}
|
||||
|
||||
const code = url.searchParams.get("code");
|
||||
if (!code) return { status: "missing_code", state };
|
||||
|
||||
const codeVerifier = manifest.pkce ? readPkceVerifier(request) : null;
|
||||
if (manifest.pkce && !codeVerifier) {
|
||||
return { status: "missing_verifier", state };
|
||||
}
|
||||
|
||||
try {
|
||||
const exchange = await manifest.exchangeCode(
|
||||
code,
|
||||
callbackUri(manifest),
|
||||
codeVerifier ? { codeVerifier } : undefined,
|
||||
);
|
||||
await link({
|
||||
userId,
|
||||
provider: manifest.id,
|
||||
credentialKind: manifest.credentialKind,
|
||||
credentials: exchange.credentials as Record<string, unknown>,
|
||||
providerUserId: exchange.providerUserId,
|
||||
grantedScopes: exchange.grantedScopes,
|
||||
});
|
||||
return { status: "linked", state };
|
||||
} catch (e) {
|
||||
console.error(`OAuth callback failed for ${manifest.id}:`, e);
|
||||
const code =
|
||||
typeof (e as { code?: string }).code === "string"
|
||||
? (e as { code: string }).code
|
||||
: "sync_failed";
|
||||
return { status: "error", code, state };
|
||||
}
|
||||
}
|
||||
|
||||
export { clearPkceCookieHeader };
|
||||
|
|
@ -6,7 +6,7 @@ import { getDb } from "./db.ts";
|
|||
import { activities, routes, users } from "@trails-cool/db/schema/journal";
|
||||
import { createRoute } from "./routes.server.ts";
|
||||
import { createActivity } from "./activities.server.ts";
|
||||
import { validateGpx } from "./gpx-save.server.ts";
|
||||
import { processGpx } from "./gpx-save.server.ts";
|
||||
import { TERMS_VERSION } from "./legal.ts";
|
||||
import { logger } from "./logger.server.ts";
|
||||
import {
|
||||
|
|
@ -649,10 +649,8 @@ export async function generateOneWalk(
|
|||
const name = templateName(now, locale, persona);
|
||||
const description = templateDescription(now, locale, persona);
|
||||
|
||||
const parsed = await validateGpx(result.gpx);
|
||||
const distance = parsed.distance;
|
||||
const elevationGain = parsed.elevation.gain;
|
||||
const elevationLoss = parsed.elevation.loss;
|
||||
const { stats } = await processGpx(result.gpx);
|
||||
const { distance, elevationGain, elevationLoss } = stats;
|
||||
|
||||
if (!distance || distance < 500) return null;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import { validateGpx, GpxValidationError } from "./gpx-save.server.ts";
|
||||
import { generateGpx } from "@trails-cool/gpx";
|
||||
import { processGpx, validateGpx, GpxValidationError } from "./gpx-save.server.ts";
|
||||
|
||||
const VALID_GPX = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1">
|
||||
|
|
@ -84,3 +85,68 @@ describe("validateGpx", () => {
|
|||
expect(err.name).toBe("GpxValidationError");
|
||||
});
|
||||
});
|
||||
|
||||
const TIMED_GPX = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1">
|
||||
<metadata><desc>An alpine loop</desc></metadata>
|
||||
<trk>
|
||||
<trkseg>
|
||||
<trkpt lat="47.0" lon="8.0"><ele>500</ele><time>2026-06-01T08:00:00Z</time></trkpt>
|
||||
<trkpt lat="47.1" lon="8.1"><ele>520</ele><time>2026-06-01T09:00:00Z</time></trkpt>
|
||||
</trkseg>
|
||||
</trk>
|
||||
</gpx>`;
|
||||
|
||||
describe("processGpx", () => {
|
||||
it("extracts coords in [lon, lat] PostGIS axis order", async () => {
|
||||
const { coords } = await processGpx(VALID_GPX);
|
||||
expect(coords).toEqual([
|
||||
[8.0, 47.0],
|
||||
[8.1, 47.1],
|
||||
[8.2, 47.2],
|
||||
]);
|
||||
});
|
||||
|
||||
it("derives distance, elevation, description, and start time", async () => {
|
||||
const { stats } = await processGpx(TIMED_GPX);
|
||||
expect(stats.distance).toBeGreaterThan(0);
|
||||
expect(stats.elevationGain).not.toBeNull();
|
||||
expect(stats.elevationLoss).not.toBeNull();
|
||||
expect(stats.description).toBe("An alpine loop");
|
||||
expect(stats.startTime).toEqual(new Date("2026-06-01T08:00:00Z"));
|
||||
});
|
||||
|
||||
it("returns null startTime and empty dayBreaks when absent", async () => {
|
||||
const { stats } = await processGpx(VALID_GPX);
|
||||
expect(stats.startTime).toBeNull();
|
||||
expect(stats.dayBreaks).toEqual([]);
|
||||
});
|
||||
|
||||
it("derives dayBreaks from day-break waypoints (round-trip via generateGpx)", async () => {
|
||||
const gpx = generateGpx({
|
||||
name: "Multi-day",
|
||||
waypoints: [
|
||||
{ lat: 47.0, lon: 8.0, name: "Start" },
|
||||
{ lat: 47.1, lon: 8.1, name: "Hut", isDayBreak: true },
|
||||
{ lat: 47.2, lon: 8.2, name: "End" },
|
||||
],
|
||||
tracks: [[
|
||||
{ lat: 47.0, lon: 8.0 },
|
||||
{ lat: 47.1, lon: 8.1 },
|
||||
{ lat: 47.2, lon: 8.2 },
|
||||
]],
|
||||
});
|
||||
|
||||
const { stats } = await processGpx(gpx);
|
||||
expect(stats.dayBreaks).toEqual([1]);
|
||||
});
|
||||
|
||||
it("propagates GpxValidationError from validation", async () => {
|
||||
await expect(processGpx(ONE_POINT_GPX)).rejects.toThrow(GpxValidationError);
|
||||
});
|
||||
|
||||
it("returns the parsed GpxData so callers never re-parse", async () => {
|
||||
const { parsed } = await processGpx(VALID_GPX);
|
||||
expect(parsed.tracks.flat()).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -45,6 +45,51 @@ export async function validateGpx(gpx: string): Promise<GpxData> {
|
|||
return parsed;
|
||||
}
|
||||
|
||||
export interface GpxStats {
|
||||
distance: number | null;
|
||||
elevationGain: number | null;
|
||||
elevationLoss: number | null;
|
||||
/** Indices of waypoints flagged as day breaks. */
|
||||
dayBreaks: number[];
|
||||
/** GPX-level description, when present. */
|
||||
description?: string;
|
||||
/** Timestamp of the first track point, when present. */
|
||||
startTime: Date | null;
|
||||
}
|
||||
|
||||
export interface ProcessedGpx {
|
||||
parsed: GpxData;
|
||||
/** [lon, lat] pairs in PostGIS axis order, ready for writeGeom. */
|
||||
coords: Array<[number, number]>;
|
||||
stats: GpxStats;
|
||||
}
|
||||
|
||||
/**
|
||||
* The validate-and-derive step every GPX save starts with: parse +
|
||||
* validate (throws GpxValidationError), extract the geometry
|
||||
* coordinates, and derive the stats rows store. Callers own the
|
||||
* precedence between these derived stats and caller-supplied ones —
|
||||
* routes let explicit input win wholesale, activities prefer the GPX
|
||||
* distance unless it is zero.
|
||||
*/
|
||||
export async function processGpx(gpx: string): Promise<ProcessedGpx> {
|
||||
const parsed = await validateGpx(gpx);
|
||||
return {
|
||||
parsed,
|
||||
coords: parsed.tracks.flat().map((p) => [p.lon, p.lat] as [number, number]),
|
||||
stats: {
|
||||
distance: parsed.distance ?? null,
|
||||
elevationGain: parsed.elevation.gain ?? null,
|
||||
elevationLoss: parsed.elevation.loss ?? null,
|
||||
dayBreaks: parsed.waypoints
|
||||
.map((w, i) => (w.isDayBreak ? i : -1))
|
||||
.filter((i) => i >= 0),
|
||||
description: parsed.description,
|
||||
startTime: parsed.tracks[0]?.[0]?.time ? new Date(parsed.tracks[0][0].time) : null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type Tx = Parameters<Parameters<Database["transaction"]>[0]>[0];
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ import { getDb } from "./db.ts";
|
|||
import { routes, routeVersions } from "@trails-cool/db/schema/journal";
|
||||
import type { Visibility } from "@trails-cool/db/schema/journal";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { validateGpx, writeGeom } from "./gpx-save.server.ts";
|
||||
import type { GpxData } from "./gpx-save.server.ts";
|
||||
import { processGpx, writeGeom } from "./gpx-save.server.ts";
|
||||
import type { ProcessedGpx } from "./gpx-save.server.ts";
|
||||
import type { OwnedRef } from "./ownership.server.ts";
|
||||
|
||||
export interface RouteInput {
|
||||
|
|
@ -26,21 +26,17 @@ export async function createRoute(ownerId: string, input: RouteInput) {
|
|||
const db = getDb();
|
||||
const id = randomUUID();
|
||||
|
||||
let parsed: GpxData | null = null;
|
||||
let processed: ProcessedGpx | null = null;
|
||||
let distance: number | null = input.distance ?? null;
|
||||
let elevationGain: number | null = input.elevationGain ?? null;
|
||||
let elevationLoss: number | null = input.elevationLoss ?? null;
|
||||
let dayBreaks: number[] = input.dayBreaks ?? [];
|
||||
|
||||
if (input.gpx) {
|
||||
parsed = await validateGpx(input.gpx);
|
||||
// Only compute stats from GPX if not pre-supplied by caller
|
||||
processed = await processGpx(input.gpx);
|
||||
// Only use GPX-derived stats if not pre-supplied by caller
|
||||
if (input.distance === undefined) {
|
||||
const stats = computeRouteStats(parsed);
|
||||
distance = stats.distance;
|
||||
elevationGain = stats.elevationGain;
|
||||
elevationLoss = stats.elevationLoss;
|
||||
dayBreaks = stats.dayBreaks;
|
||||
({ distance, elevationGain, elevationLoss, dayBreaks } = processed.stats);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -60,9 +56,8 @@ export async function createRoute(ownerId: string, input: RouteInput) {
|
|||
...(input.synthetic ? { synthetic: true } : {}),
|
||||
});
|
||||
|
||||
if (input.gpx && parsed) {
|
||||
const coords = parsed.tracks.flat().map((p) => [p.lon, p.lat] as [number, number]);
|
||||
await writeGeom(tx, id, "routes", coords);
|
||||
if (input.gpx && processed) {
|
||||
await writeGeom(tx, id, "routes", processed.coords);
|
||||
|
||||
await tx.insert(routeVersions).values({
|
||||
id: randomUUID(),
|
||||
|
|
@ -135,9 +130,9 @@ export async function updateRoute(route: OwnedRef, input: Partial<RouteInput>) {
|
|||
const { id, ownerId } = route;
|
||||
const db = getDb();
|
||||
|
||||
let parsed: GpxData | null = null;
|
||||
let processed: ProcessedGpx | null = null;
|
||||
if (input.gpx) {
|
||||
parsed = await validateGpx(input.gpx);
|
||||
processed = await processGpx(input.gpx);
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = { updatedAt: new Date() };
|
||||
|
|
@ -145,8 +140,8 @@ export async function updateRoute(route: OwnedRef, input: Partial<RouteInput>) {
|
|||
if (input.description !== undefined) updateData.description = input.description;
|
||||
if (input.visibility !== undefined) updateData.visibility = input.visibility;
|
||||
|
||||
if (input.gpx && parsed) {
|
||||
const stats = computeRouteStats(parsed);
|
||||
if (input.gpx && processed) {
|
||||
const { stats } = processed;
|
||||
updateData.gpx = input.gpx;
|
||||
updateData.distance = stats.distance;
|
||||
updateData.elevationGain = stats.elevationGain;
|
||||
|
|
@ -163,9 +158,8 @@ export async function updateRoute(route: OwnedRef, input: Partial<RouteInput>) {
|
|||
.set(updateData)
|
||||
.where(and(eq(routes.id, id), eq(routes.ownerId, ownerId)));
|
||||
|
||||
if (input.gpx && parsed) {
|
||||
const coords = parsed.tracks.flat().map((p) => [p.lon, p.lat] as [number, number]);
|
||||
await writeGeom(tx, id, "routes", coords);
|
||||
if (input.gpx && processed) {
|
||||
await writeGeom(tx, id, "routes", processed.coords);
|
||||
|
||||
const existingVersions = await tx
|
||||
.select()
|
||||
|
|
@ -197,19 +191,6 @@ export async function deleteRoute(route: OwnedRef) {
|
|||
return result.length > 0;
|
||||
}
|
||||
|
||||
function computeRouteStats(gpxData: GpxData) {
|
||||
const dayBreaks = gpxData.waypoints
|
||||
.map((w, i) => (w.isDayBreak ? i : -1))
|
||||
.filter((i) => i >= 0);
|
||||
return {
|
||||
distance: gpxData.distance,
|
||||
elevationGain: gpxData.elevation.gain,
|
||||
elevationLoss: gpxData.elevation.loss,
|
||||
dayBreaks,
|
||||
description: gpxData.description,
|
||||
};
|
||||
}
|
||||
|
||||
async function getGeojson(table: "routes" | "activities", id: string): Promise<string | null> {
|
||||
try {
|
||||
const db = getDb();
|
||||
|
|
|
|||
|
|
@ -1,13 +1,11 @@
|
|||
import { redirect, data } from "react-router";
|
||||
import { getOrigin } from "~/lib/config.server";
|
||||
import type { Route } from "./+types/api.sync.callback.$provider";
|
||||
import { requireSessionUser } from "~/lib/auth/session.server";
|
||||
import { getManifest, link } from "~/lib/connected-services";
|
||||
import { getManifest } from "~/lib/connected-services";
|
||||
import {
|
||||
decodeOAuthState,
|
||||
readPkceVerifier,
|
||||
completeOAuthFlow,
|
||||
clearPkceCookieHeader,
|
||||
} from "~/lib/connected-services/oauth-state.server";
|
||||
} from "~/lib/connected-services/oauth-flow.server";
|
||||
import { pushRouteToProvider } from "~/lib/connected-services/push-action.server";
|
||||
|
||||
export async function loader({ params, request }: Route.LoaderArgs) {
|
||||
|
|
@ -18,51 +16,28 @@ export async function loader({ params, request }: Route.LoaderArgs) {
|
|||
return data({ error: "Unknown provider" }, { status: 404 });
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const state = decodeOAuthState(url.searchParams.get("state"));
|
||||
const result = await completeOAuthFlow(manifest, request, user.id);
|
||||
const state = result.state;
|
||||
const fallbackReturn = state.returnTo ?? "/settings";
|
||||
// Spent (or irrelevant) verifier — clear it on every outcome.
|
||||
const headers = { "Set-Cookie": clearPkceCookieHeader() };
|
||||
|
||||
// User denied the new scope at Wahoo. Send them back to the originating
|
||||
// page with a notice instead of looping them through OAuth again.
|
||||
if (url.searchParams.get("error") === "access_denied") {
|
||||
return redirect(`${fallbackReturn}?push=needs_permission`);
|
||||
}
|
||||
|
||||
const code = url.searchParams.get("code");
|
||||
if (!code) return data({ error: "Missing authorization code" }, { status: 400 });
|
||||
|
||||
const origin = getOrigin();
|
||||
const redirectUri = `${origin}/api/sync/callback/${params.provider}`;
|
||||
|
||||
// PKCE providers: recover the verifier from the connect-time cookie.
|
||||
const codeVerifier = manifest.pkce ? readPkceVerifier(request) : null;
|
||||
if (manifest.pkce && !codeVerifier) {
|
||||
return redirect(`${fallbackReturn}?error=sync_failed`);
|
||||
}
|
||||
|
||||
try {
|
||||
const exchange = await manifest.exchangeCode(
|
||||
code,
|
||||
redirectUri,
|
||||
codeVerifier ? { codeVerifier } : undefined,
|
||||
);
|
||||
await link({
|
||||
userId: user.id,
|
||||
provider: manifest.id,
|
||||
credentialKind: manifest.credentialKind,
|
||||
credentials: exchange.credentials as Record<string, unknown>,
|
||||
providerUserId: exchange.providerUserId,
|
||||
grantedScopes: exchange.grantedScopes,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(`OAuth callback failed for ${params.provider}:`, e);
|
||||
const errCode =
|
||||
typeof (e as { code?: string }).code === "string"
|
||||
? (e as { code: string }).code
|
||||
: "sync_failed";
|
||||
return redirect(`${fallbackReturn}?error=${errCode}`);
|
||||
switch (result.status) {
|
||||
case "denied":
|
||||
// User declined at the provider. Back to the originating page
|
||||
// with a notice instead of looping them through OAuth again.
|
||||
return redirect(`${fallbackReturn}?push=needs_permission`, { headers });
|
||||
case "missing_code":
|
||||
return data({ error: "Missing authorization code" }, { status: 400 });
|
||||
case "missing_verifier":
|
||||
return redirect(`${fallbackReturn}?error=sync_failed`, { headers });
|
||||
case "error":
|
||||
return redirect(`${fallbackReturn}?error=${result.code}`, { headers });
|
||||
case "linked":
|
||||
break;
|
||||
}
|
||||
|
||||
// Resume an interrupted push now that the connection has the scope.
|
||||
if (state.pushAfter?.routeId) {
|
||||
const outcome = await pushRouteToProvider({
|
||||
userId: user.id,
|
||||
|
|
@ -70,16 +45,12 @@ export async function loader({ params, request }: Route.LoaderArgs) {
|
|||
routeId: state.pushAfter.routeId,
|
||||
});
|
||||
const target = state.returnTo ?? `/routes/${state.pushAfter.routeId}`;
|
||||
if (outcome.status === "success") return redirect(`${target}?push=success`);
|
||||
if (outcome.status === "scope_missing") return redirect(`${target}?push=needs_permission`);
|
||||
if (outcome.status === "needs_relink") return redirect(`${target}?push=needs_permission`);
|
||||
if (outcome.status === "error") return redirect(`${target}?push=error&code=${outcome.code}`);
|
||||
return redirect(`${target}?push=${outcome.status}`);
|
||||
if (outcome.status === "success") return redirect(`${target}?push=success`, { headers });
|
||||
if (outcome.status === "scope_missing") return redirect(`${target}?push=needs_permission`, { headers });
|
||||
if (outcome.status === "needs_relink") return redirect(`${target}?push=needs_permission`, { headers });
|
||||
if (outcome.status === "error") return redirect(`${target}?push=error&code=${outcome.code}`, { headers });
|
||||
return redirect(`${target}?push=${outcome.status}`, { headers });
|
||||
}
|
||||
|
||||
return redirect(state.returnTo ?? "/settings", {
|
||||
// Spent verifier — clear it regardless of which provider this was
|
||||
// (harmless no-op for non-PKCE providers without the cookie).
|
||||
headers: { "Set-Cookie": clearPkceCookieHeader() },
|
||||
});
|
||||
return redirect(state.returnTo ?? "/settings", { headers });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,8 @@
|
|||
import { redirect, data } from "react-router";
|
||||
import { getOrigin } from "~/lib/config.server";
|
||||
import { data } from "react-router";
|
||||
import type { Route } from "./+types/api.sync.connect.$provider";
|
||||
import { requireSessionUser } from "~/lib/auth/session.server";
|
||||
import { getManifest } from "~/lib/connected-services";
|
||||
import {
|
||||
encodeOAuthState,
|
||||
generatePkcePair,
|
||||
pkceCookieHeader,
|
||||
} from "~/lib/connected-services/oauth-state.server";
|
||||
import { initiateOAuthFlow } from "~/lib/connected-services/oauth-flow.server";
|
||||
|
||||
export async function loader({ params, request }: Route.LoaderArgs) {
|
||||
await requireSessionUser(request);
|
||||
|
|
@ -17,19 +12,5 @@ export async function loader({ params, request }: Route.LoaderArgs) {
|
|||
return data({ error: "Unknown provider" }, { status: 404 });
|
||||
}
|
||||
|
||||
const origin = getOrigin();
|
||||
const redirectUri = `${origin}/api/sync/callback/${params.provider}`;
|
||||
const state = encodeOAuthState({ returnTo: "/settings/connections" });
|
||||
|
||||
// PKCE providers (Garmin): the verifier crosses the redirect in an
|
||||
// httpOnly cookie; only the S256 challenge goes to the provider.
|
||||
if (manifest.pkce) {
|
||||
const { verifier, challenge } = generatePkcePair();
|
||||
return redirect(
|
||||
manifest.buildAuthUrl(redirectUri, state, { codeChallenge: challenge }),
|
||||
{ headers: { "Set-Cookie": pkceCookieHeader(verifier) } },
|
||||
);
|
||||
}
|
||||
|
||||
return redirect(manifest.buildAuthUrl(redirectUri, state));
|
||||
return initiateOAuthFlow(manifest, { returnTo: "/settings/connections" });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
import { redirect, data } from "react-router";
|
||||
import { getOrigin } from "~/lib/config.server";
|
||||
import type { Route } from "./+types/api.sync.push.$provider.$routeId";
|
||||
import { requireSessionUser } from "~/lib/auth/session.server";
|
||||
import { getManifest } from "~/lib/connected-services";
|
||||
import { pushRouteToProvider } from "~/lib/connected-services/push-action.server";
|
||||
import { encodeOAuthState } from "~/lib/connected-services/oauth-state.server";
|
||||
import { initiateOAuthFlow } from "~/lib/connected-services/oauth-flow.server";
|
||||
|
||||
export async function action({ params, request }: Route.ActionArgs) {
|
||||
const user = await requireSessionUser(request);
|
||||
|
|
@ -26,13 +25,12 @@ export async function action({ params, request }: Route.ActionArgs) {
|
|||
if (!manifest.buildAuthUrl) {
|
||||
return redirect(`${returnTo}?push=needs_permission`);
|
||||
}
|
||||
const origin = getOrigin();
|
||||
const redirectUri = `${origin}/api/sync/callback/${manifest.id}`;
|
||||
const state = encodeOAuthState({
|
||||
// Re-authorize with the push intent in the state; the callback
|
||||
// resumes the push once the scope is granted.
|
||||
return initiateOAuthFlow(manifest, {
|
||||
pushAfter: { routeId: params.routeId },
|
||||
returnTo,
|
||||
});
|
||||
return redirect(manifest.buildAuthUrl(redirectUri, state));
|
||||
}
|
||||
case "needs_relink":
|
||||
return redirect(`${returnTo}?push=needs_permission`);
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import type { Route } from "./+types/api.v1.activities.$id";
|
||||
import { requireApiUser, apiError } from "~/lib/api-guard.server";
|
||||
import { requireApiUser, apiError, apiJson } from "~/lib/api-guard.server";
|
||||
import { getActivity, deleteActivity } from "~/lib/activities.server";
|
||||
import { loadOwnedActivity } from "~/lib/ownership.server";
|
||||
import { ERROR_CODES } from "@trails-cool/api";
|
||||
import { ERROR_CODES, ActivityDetailSchema } from "@trails-cool/api";
|
||||
|
||||
/** GET /api/v1/activities/:id — full activity detail */
|
||||
export async function loader({ request, params }: Route.LoaderArgs) {
|
||||
|
|
@ -13,11 +13,14 @@ export async function loader({ request, params }: Route.LoaderArgs) {
|
|||
return apiError(404, ERROR_CODES.NOT_FOUND, "Activity not found");
|
||||
}
|
||||
|
||||
return Response.json({
|
||||
return apiJson(ActivityDetailSchema, {
|
||||
id: activity.id,
|
||||
name: activity.name,
|
||||
description: activity.description,
|
||||
description: activity.description ?? "",
|
||||
routeId: activity.routeId,
|
||||
routeName: null, // TODO: join route name (matches the list endpoint)
|
||||
photos: [], // no photos on this surface yet; contract field
|
||||
|
||||
distance: activity.distance,
|
||||
duration: activity.duration,
|
||||
elevationGain: activity.elevationGain,
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
import type { Route } from "./+types/api.v1.activities._index";
|
||||
import { requireApiUser, apiError } from "~/lib/api-guard.server";
|
||||
import { requireApiUser, apiError, apiJson } from "~/lib/api-guard.server";
|
||||
import { listActivities, createActivity } from "~/lib/activities.server";
|
||||
import {
|
||||
PaginationQuerySchema,
|
||||
CreateActivityRequestSchema,
|
||||
ERROR_CODES,
|
||||
zodIssuesToFieldErrors,
|
||||
ActivityListResponseSchema,
|
||||
CreateActivityResponseSchema,
|
||||
} from "@trails-cool/api";
|
||||
|
||||
/** GET /api/v1/activities — paginated activity list */
|
||||
|
|
@ -32,11 +34,11 @@ export async function loader({ request }: Route.LoaderArgs) {
|
|||
const page = allActivities.slice(startIdx, startIdx + limit);
|
||||
const nextCursor = startIdx + limit < allActivities.length ? page[page.length - 1]?.id ?? null : null;
|
||||
|
||||
return Response.json({
|
||||
return apiJson(ActivityListResponseSchema, {
|
||||
activities: page.map((a) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
description: a.description,
|
||||
description: a.description ?? "",
|
||||
routeId: a.routeId,
|
||||
routeName: null, // TODO: join route name
|
||||
distance: a.distance,
|
||||
|
|
@ -67,5 +69,5 @@ export async function action({ request }: Route.ActionArgs) {
|
|||
...parsed.data,
|
||||
startedAt: parsed.data.startedAt ? new Date(parsed.data.startedAt) : null,
|
||||
});
|
||||
return Response.json({ id }, { status: 201 });
|
||||
return apiJson(CreateActivityResponseSchema, { id }, { status: 201 });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import type { Route } from "./+types/api.v1.routes.$id";
|
||||
import { requireApiUser, apiError } from "~/lib/api-guard.server";
|
||||
import { requireApiUser, apiError, apiJson } 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";
|
||||
import { UpdateRouteRequestSchema, ERROR_CODES, zodIssuesToFieldErrors, RouteDetailSchema } from "@trails-cool/api";
|
||||
|
||||
/** GET /api/v1/routes/:id — full route detail */
|
||||
export async function loader({ request, params }: Route.LoaderArgs) {
|
||||
|
|
@ -13,10 +13,10 @@ export async function loader({ request, params }: Route.LoaderArgs) {
|
|||
return apiError(404, ERROR_CODES.NOT_FOUND, "Route not found");
|
||||
}
|
||||
|
||||
return Response.json({
|
||||
return apiJson(RouteDetailSchema, {
|
||||
id: route.id,
|
||||
name: route.name,
|
||||
description: route.description,
|
||||
description: route.description ?? "",
|
||||
distance: route.distance,
|
||||
elevationGain: route.elevationGain,
|
||||
elevationLoss: route.elevationLoss,
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
import type { Route } from "./+types/api.v1.routes._index";
|
||||
import { requireApiUser, apiError } from "~/lib/api-guard.server";
|
||||
import { requireApiUser, apiError, apiJson } from "~/lib/api-guard.server";
|
||||
import { listRoutes, createRoute } from "~/lib/routes.server";
|
||||
import {
|
||||
PaginationQuerySchema,
|
||||
CreateRouteRequestSchema,
|
||||
ERROR_CODES,
|
||||
zodIssuesToFieldErrors,
|
||||
RouteListResponseSchema,
|
||||
CreateRouteResponseSchema,
|
||||
} from "@trails-cool/api";
|
||||
|
||||
/** GET /api/v1/routes — paginated route list */
|
||||
|
|
@ -32,11 +34,11 @@ export async function loader({ request }: Route.LoaderArgs) {
|
|||
const page = allRoutes.slice(startIdx, startIdx + limit);
|
||||
const nextCursor = startIdx + limit < allRoutes.length ? page[page.length - 1]?.id ?? null : null;
|
||||
|
||||
return Response.json({
|
||||
return apiJson(RouteListResponseSchema, {
|
||||
routes: page.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
description: r.description,
|
||||
description: r.description ?? "",
|
||||
distance: r.distance,
|
||||
elevationGain: r.elevationGain,
|
||||
elevationLoss: r.elevationLoss,
|
||||
|
|
@ -63,5 +65,5 @@ export async function action({ request }: Route.ActionArgs) {
|
|||
}
|
||||
|
||||
const id = await createRoute(user.id, parsed.data);
|
||||
return Response.json({ id }, { status: 201 });
|
||||
return apiJson(CreateRouteResponseSchema, { id }, { status: 201 });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,9 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
|
|||
import { TERMS_VERSION } from "~/lib/legal";
|
||||
|
||||
const mockUser = { id: "user-1", email: "test@test.com", username: "test", domain: "localhost", displayName: null, bio: null, createdAt: new Date(), termsVersion: TERMS_VERSION };
|
||||
const ROUTE_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const VERSION_ID = "22222222-2222-4222-8222-222222222222";
|
||||
const NEW_ID = "33333333-3333-4333-8333-333333333333";
|
||||
const mockGetAuthenticatedUser = vi.fn();
|
||||
const mockListRoutes = vi.fn();
|
||||
const mockCreateRoute = vi.fn();
|
||||
|
|
@ -51,7 +54,7 @@ describe("GET /api/v1/routes", () => {
|
|||
const now = new Date();
|
||||
mockListRoutes.mockResolvedValue([
|
||||
{
|
||||
id: "r1", name: "Tour", description: "", distance: 42000,
|
||||
id: ROUTE_ID, name: "Tour", description: "", distance: 42000,
|
||||
elevationGain: 340, elevationLoss: 320, routingProfile: "fastbike",
|
||||
dayBreaks: [], geojson: null, ownerId: "user-1", gpx: null,
|
||||
tags: null, plannerState: null, createdAt: now, updatedAt: now,
|
||||
|
|
@ -63,7 +66,7 @@ describe("GET /api/v1/routes", () => {
|
|||
const data = await resp.json();
|
||||
|
||||
expect(data.routes).toHaveLength(1);
|
||||
expect(data.routes[0].id).toBe("r1");
|
||||
expect(data.routes[0].id).toBe(ROUTE_ID);
|
||||
expect(data.nextCursor).toBeNull();
|
||||
});
|
||||
|
||||
|
|
@ -83,7 +86,7 @@ describe("GET /api/v1/routes", () => {
|
|||
|
||||
describe("POST /api/v1/routes", () => {
|
||||
it("creates a route with valid body", async () => {
|
||||
mockCreateRoute.mockResolvedValue("new-id");
|
||||
mockCreateRoute.mockResolvedValue(NEW_ID);
|
||||
const { action } = await import("./api.v1.routes._index.ts");
|
||||
|
||||
const resp = await action(routeArgs(
|
||||
|
|
@ -95,7 +98,7 @@ describe("POST /api/v1/routes", () => {
|
|||
|
||||
expect(resp.status).toBe(201);
|
||||
const data = await resp.json();
|
||||
expect(data.id).toBe("new-id");
|
||||
expect(data.id).toBe(NEW_ID);
|
||||
});
|
||||
|
||||
it("returns 400 on validation error", async () => {
|
||||
|
|
@ -117,20 +120,20 @@ describe("GET /api/v1/routes/:id", () => {
|
|||
it("returns route detail", async () => {
|
||||
const now = new Date();
|
||||
mockGetRouteWithVersions.mockResolvedValue({
|
||||
id: "r1", name: "Tour", description: "", distance: 42000,
|
||||
id: ROUTE_ID, name: "Tour", description: "", distance: 42000,
|
||||
elevationGain: 340, elevationLoss: 320, routingProfile: "fastbike",
|
||||
dayBreaks: [], gpx: "<gpx/>", ownerId: "user-1",
|
||||
tags: null, plannerState: null, createdAt: now, updatedAt: now,
|
||||
versions: [{ id: "v1", routeId: "r1", version: 1, gpx: "<gpx/>", createdBy: "user-1", changeDescription: null, createdAt: now }],
|
||||
versions: [{ id: VERSION_ID, routeId: ROUTE_ID, version: 1, gpx: "<gpx/>", createdBy: "user-1", changeDescription: null, createdAt: now }],
|
||||
});
|
||||
|
||||
const { loader } = await import("./api.v1.routes.$id.ts");
|
||||
const resp = await loader(routeArgs(
|
||||
authRequest("/api/v1/routes/r1"), { id: "r1" }, "api/v1/routes/:id",
|
||||
authRequest(`/api/v1/routes/${ROUTE_ID}`), { id: ROUTE_ID }, "api/v1/routes/:id",
|
||||
)) as Response;
|
||||
|
||||
const data = await resp.json();
|
||||
expect(data.id).toBe("r1");
|
||||
expect(data.id).toBe(ROUTE_ID);
|
||||
expect(data.gpx).toBe("<gpx/>");
|
||||
expect(data.versions).toHaveLength(1);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,8 +3,10 @@ import { render, screen } from "@testing-library/react-native";
|
|||
import { Text } from "react-native";
|
||||
|
||||
describe("Jest + React Native Testing Library", () => {
|
||||
it("renders a component", () => {
|
||||
render(<Text testID="hello">Hello</Text>);
|
||||
it("renders a component", async () => {
|
||||
// await is a no-op on RNTL v13 but required on v14, where render()
|
||||
// returns a Promise
|
||||
await render(<Text testID="hello">Hello</Text>);
|
||||
expect(screen.getByTestId("hello")).toBeTruthy();
|
||||
expect(screen.getByText("Hello")).toBeTruthy();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@
|
|||
"@trails-cool/map-core": "workspace:*",
|
||||
"@trails-cool/sentry-config": "workspace:*",
|
||||
"@trails-cool/types": "workspace:*",
|
||||
"expo": "~56.0.4",
|
||||
"expo": "~56.0.9",
|
||||
"expo-constants": "~56.0.17",
|
||||
"expo-crypto": "~56.0.4",
|
||||
"expo-dev-client": "~56.0.19",
|
||||
|
|
@ -62,10 +62,10 @@
|
|||
"react": "catalog:",
|
||||
"react-native": "0.85.3",
|
||||
"react-native-gesture-handler": "^2.31.2",
|
||||
"react-native-reanimated": "^4.4.1",
|
||||
"react-native-safe-area-context": "~5.8.0",
|
||||
"react-native-reanimated": "^4.3.1",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "~4.25.2",
|
||||
"react-native-worklets": "0.9.1",
|
||||
"react-native-worklets": "0.8.3",
|
||||
"use-latest-callback": "^0.3.4",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,50 +1,5 @@
|
|||
import { test, expect, waitForHydration, type CDPSession, type Page } from "./fixtures/test";
|
||||
|
||||
// Virtual authenticator helpers
|
||||
async function setupVirtualAuthenticator(cdp: CDPSession) {
|
||||
await cdp.send("WebAuthn.enable");
|
||||
const { authenticatorId } = await cdp.send("WebAuthn.addVirtualAuthenticator", {
|
||||
options: {
|
||||
protocol: "ctap2",
|
||||
transport: "internal",
|
||||
hasResidentKey: true,
|
||||
hasUserVerification: true,
|
||||
isUserVerified: true,
|
||||
},
|
||||
});
|
||||
return authenticatorId;
|
||||
}
|
||||
|
||||
async function removeVirtualAuthenticator(cdp: CDPSession, authenticatorId: string) {
|
||||
await cdp.send("WebAuthn.removeVirtualAuthenticator", { authenticatorId });
|
||||
await cdp.send("WebAuthn.disable");
|
||||
}
|
||||
|
||||
async function registerUser(page: Page, email: string, username: string) {
|
||||
await page.goto("/auth/register");
|
||||
await expect(page.getByRole("heading", { name: "Register" })).toBeVisible();
|
||||
await waitForHydration(page);
|
||||
await page.getByLabel("Email").click();
|
||||
await page.getByLabel("Email").fill(email);
|
||||
await page.getByLabel("Username").click();
|
||||
await page.getByLabel("Username").fill(username);
|
||||
// Verify both fields retained values before submitting
|
||||
await expect(page.getByLabel("Email")).toHaveValue(email);
|
||||
await expect(page.getByLabel("Username")).toHaveValue(username);
|
||||
// Accept the Terms of Service (required)
|
||||
await page.getByRole("checkbox").check();
|
||||
await page.getByRole("button", { name: /Register with Passkey/ }).click();
|
||||
}
|
||||
|
||||
async function logout(page: Page, accountLabel: string) {
|
||||
// The account cluster lives inside an avatar dropdown now. Click the
|
||||
// avatar (its aria-label is displayName || username), then click the
|
||||
// Log Out menuitem inside the popup.
|
||||
await waitForHydration(page);
|
||||
await page.getByRole("navigation").getByRole("button", { name: accountLabel }).click();
|
||||
await page.getByRole("menuitem", { name: "Log Out" }).click();
|
||||
await expect(page.getByRole("navigation").getByRole("link", { name: "Sign In" })).toBeVisible({ timeout: 5000 });
|
||||
}
|
||||
import { setupVirtualAuthenticator, removeVirtualAuthenticator, submitRegistration, logout } from "./helpers/auth";
|
||||
|
||||
test.describe("Passkey Authentication", () => {
|
||||
test("register with passkey and sign in", async ({ page }) => {
|
||||
|
|
@ -55,7 +10,7 @@ test.describe("Passkey Authentication", () => {
|
|||
const username = `testuser${Date.now()}`;
|
||||
|
||||
// Register
|
||||
await registerUser(page, email, username);
|
||||
await submitRegistration(page, email, username);
|
||||
await expect(page).toHaveURL("/", { timeout: 10000 });
|
||||
// The avatar button's aria-label is the displayName or username;
|
||||
// for a freshly-registered user with no displayName set, that's
|
||||
|
|
@ -95,12 +50,12 @@ test.describe("Passkey Authentication", () => {
|
|||
const firstUsername = `first${Date.now()}`;
|
||||
|
||||
// Register first user
|
||||
await registerUser(page, email, firstUsername);
|
||||
await submitRegistration(page, email, firstUsername);
|
||||
await expect(page).toHaveURL("/", { timeout: 10000 });
|
||||
await logout(page, firstUsername);
|
||||
|
||||
// Try to register with same email
|
||||
await registerUser(page, email, `second${Date.now()}`);
|
||||
await submitRegistration(page, email, `second${Date.now()}`);
|
||||
await expect(page.getByText(/already in use/i)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
await removeVirtualAuthenticator(cdp, authenticatorId);
|
||||
|
|
@ -113,12 +68,12 @@ test.describe("Passkey Authentication", () => {
|
|||
const username = `uniq${Date.now()}`;
|
||||
|
||||
// Register first user
|
||||
await registerUser(page, `first-${Date.now()}@example.com`, username);
|
||||
await submitRegistration(page, `first-${Date.now()}@example.com`, username);
|
||||
await expect(page).toHaveURL("/", { timeout: 10000 });
|
||||
await logout(page, username);
|
||||
|
||||
// Try to register with same username
|
||||
await registerUser(page, `second-${Date.now()}@example.com`, username);
|
||||
await submitRegistration(page, `second-${Date.now()}@example.com`, username);
|
||||
await expect(page.getByText(/already taken/i)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
await removeVirtualAuthenticator(cdp, authenticatorId);
|
||||
|
|
|
|||
|
|
@ -1,29 +1,5 @@
|
|||
import { test, expect, waitForHydration, type CDPSession, type Page } from "./fixtures/test";
|
||||
|
||||
async function setupVirtualAuthenticator(cdp: CDPSession) {
|
||||
await cdp.send("WebAuthn.enable");
|
||||
const { authenticatorId } = await cdp.send("WebAuthn.addVirtualAuthenticator", {
|
||||
options: {
|
||||
protocol: "ctap2",
|
||||
transport: "internal",
|
||||
hasResidentKey: true,
|
||||
hasUserVerification: true,
|
||||
isUserVerified: true,
|
||||
},
|
||||
});
|
||||
return authenticatorId;
|
||||
}
|
||||
|
||||
async function registerUser(page: Page, email: string, username: string) {
|
||||
await page.goto("/auth/register");
|
||||
await expect(page.getByRole("heading", { name: "Register" })).toBeVisible();
|
||||
await waitForHydration(page);
|
||||
await page.getByLabel("Email").fill(email);
|
||||
await page.getByLabel("Username").fill(username);
|
||||
await page.getByRole("checkbox").check();
|
||||
await page.getByRole("button", { name: /Register with Passkey/ }).click();
|
||||
await expect(page).toHaveURL("/", { timeout: 10000 });
|
||||
}
|
||||
import { setupVirtualAuthenticator, registerUser } from "./helpers/auth";
|
||||
|
||||
async function setProfileVisibility(page: Page, value: "public" | "private") {
|
||||
await page.goto("/settings");
|
||||
|
|
|
|||
84
e2e/helpers/auth.ts
Normal file
84
e2e/helpers/auth.ts
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
// Shared auth helpers for journal specs. These were previously
|
||||
// copy-pasted per spec file and had already drifted (the auth spec's
|
||||
// registerUser lost the final URL assertion the other copies had, and
|
||||
// the settings spec's variant skipped hydration and the Terms
|
||||
// checkbox). One canonical copy lives here.
|
||||
|
||||
import { expect, waitForHydration, type CDPSession, type Page } from "../fixtures/test";
|
||||
|
||||
export async function setupVirtualAuthenticator(cdp: CDPSession): Promise<string> {
|
||||
await cdp.send("WebAuthn.enable");
|
||||
const { authenticatorId } = await cdp.send("WebAuthn.addVirtualAuthenticator", {
|
||||
options: {
|
||||
protocol: "ctap2",
|
||||
transport: "internal",
|
||||
hasResidentKey: true,
|
||||
hasUserVerification: true,
|
||||
isUserVerified: true,
|
||||
},
|
||||
});
|
||||
return authenticatorId;
|
||||
}
|
||||
|
||||
export async function removeVirtualAuthenticator(
|
||||
cdp: CDPSession,
|
||||
authenticatorId: string,
|
||||
): Promise<void> {
|
||||
await cdp.send("WebAuthn.removeVirtualAuthenticator", { authenticatorId });
|
||||
await cdp.send("WebAuthn.disable");
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill and submit the registration form (passkey + Terms acceptance).
|
||||
* Makes no assertion about the outcome — use this directly for
|
||||
* expected-failure attempts (duplicate email/username), and
|
||||
* registerUser for the success path.
|
||||
*/
|
||||
export async function submitRegistration(
|
||||
page: Page,
|
||||
email: string,
|
||||
username: string,
|
||||
): Promise<void> {
|
||||
await page.goto("/auth/register");
|
||||
await expect(page.getByRole("heading", { name: "Register" })).toBeVisible();
|
||||
await waitForHydration(page);
|
||||
await page.getByLabel("Email").click();
|
||||
await page.getByLabel("Email").fill(email);
|
||||
await page.getByLabel("Username").click();
|
||||
await page.getByLabel("Username").fill(username);
|
||||
// Verify both fields retained values before submitting
|
||||
await expect(page.getByLabel("Email")).toHaveValue(email);
|
||||
await expect(page.getByLabel("Username")).toHaveValue(username);
|
||||
// Accept the Terms of Service (required)
|
||||
await page.getByRole("checkbox").check();
|
||||
await page.getByRole("button", { name: /Register with Passkey/ }).click();
|
||||
}
|
||||
|
||||
/** Register a user with a passkey and wait for the signed-in redirect. */
|
||||
export async function registerUser(page: Page, email: string, username: string): Promise<void> {
|
||||
await submitRegistration(page, email, username);
|
||||
await expect(page).toHaveURL("/", { timeout: 10000 });
|
||||
}
|
||||
|
||||
/** Register a throwaway user with unique credentials derived from `prefix`. */
|
||||
export async function registerFreshUser(
|
||||
page: Page,
|
||||
prefix: string,
|
||||
): Promise<{ email: string; username: string }> {
|
||||
const email = `${prefix}-${Date.now()}@example.com`;
|
||||
const username = `${prefix}${Date.now()}`;
|
||||
await registerUser(page, email, username);
|
||||
return { email, username };
|
||||
}
|
||||
|
||||
export async function logout(page: Page, accountLabel: string): Promise<void> {
|
||||
// The account cluster lives inside an avatar dropdown. Click the
|
||||
// avatar (its aria-label is displayName || username), then click the
|
||||
// Log Out menuitem inside the popup.
|
||||
await waitForHydration(page);
|
||||
await page.getByRole("navigation").getByRole("button", { name: accountLabel }).click();
|
||||
await page.getByRole("menuitem", { name: "Log Out" }).click();
|
||||
await expect(
|
||||
page.getByRole("navigation").getByRole("link", { name: "Sign In" }),
|
||||
).toBeVisible({ timeout: 5000 });
|
||||
}
|
||||
39
e2e/helpers/journal.ts
Normal file
39
e2e/helpers/journal.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// Shared journal-side constants and seed helpers. The /api/e2e/*
|
||||
// endpoints only exist when the journal runs with E2E=true.
|
||||
|
||||
import type { APIRequestContext } from "@playwright/test";
|
||||
import { expect } from "../fixtures/test";
|
||||
|
||||
export const JOURNAL = "http://localhost:3000";
|
||||
export const PLANNER = "http://localhost:3001";
|
||||
|
||||
/** Mint a route + single-use callback JWT via /api/e2e/seed. */
|
||||
export async function seedRoute(
|
||||
request: APIRequestContext,
|
||||
): Promise<{ routeId: string; token: string }> {
|
||||
const resp = await request.post(`${JOURNAL}/api/e2e/seed`);
|
||||
expect(resp.ok(), "POST /api/e2e/seed failed — is the journal running with E2E=true?").toBeTruthy();
|
||||
return (await resp.json()) as { routeId: string; token: string };
|
||||
}
|
||||
|
||||
/** Whether the route has PostGIS geometry stored (via /api/e2e/route/:id). */
|
||||
export async function routeHasGeom(
|
||||
request: APIRequestContext,
|
||||
routeId: string,
|
||||
): Promise<boolean> {
|
||||
const resp = await request.get(`${JOURNAL}/api/e2e/route/${routeId}`);
|
||||
expect(resp.ok()).toBeTruthy();
|
||||
const { hasGeom } = (await resp.json()) as { hasGeom: boolean };
|
||||
return hasGeom;
|
||||
}
|
||||
|
||||
/** Seeds a Komoot connection for the e2e test user; returns the session cookie. */
|
||||
export async function seedKomootConnection(
|
||||
request: APIRequestContext,
|
||||
mode: "public" | "authenticated" = "public",
|
||||
): Promise<{ cookie: string }> {
|
||||
const resp = await request.post(`${JOURNAL}/api/e2e/komoot`, { data: { mode } });
|
||||
if (!resp.ok()) throw new Error(`komoot seed failed: ${resp.status()}`);
|
||||
const cookie = resp.headers()["set-cookie"];
|
||||
return { cookie };
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import { test, expect } from "./fixtures/test";
|
||||
import { JOURNAL, PLANNER, seedRoute, routeHasGeom } from "./helpers/journal";
|
||||
|
||||
/**
|
||||
* Integration tests that require the full dev stack:
|
||||
|
|
@ -9,8 +10,6 @@ import { test, expect } from "./fixtures/test";
|
|||
* Locally, run `pnpm dev:full` first (with E2E=true for the callback tests).
|
||||
*/
|
||||
|
||||
const JOURNAL = "http://localhost:3000";
|
||||
const PLANNER = "http://localhost:3001";
|
||||
|
||||
const VALID_GPX = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1">
|
||||
|
|
@ -30,9 +29,7 @@ const ONE_POINT_GPX = `<?xml version="1.0" encoding="UTF-8"?>
|
|||
|
||||
test.describe("Integration: Planner callback → geometry stored", () => {
|
||||
test("valid GPX stores geometry atomically", async ({ request }) => {
|
||||
const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
|
||||
expect(seedResp.ok()).toBeTruthy();
|
||||
const { routeId, token } = await seedResp.json() as { routeId: string; token: string };
|
||||
const { routeId, token } = await seedRoute(request);
|
||||
|
||||
const callbackResp = await request.post(`${JOURNAL}/api/routes/${routeId}/callback`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
|
|
@ -40,14 +37,11 @@ test.describe("Integration: Planner callback → geometry stored", () => {
|
|||
});
|
||||
expect(callbackResp.status()).toBe(200);
|
||||
|
||||
const geomResp = await request.get(`${JOURNAL}/api/e2e/route/${routeId}`);
|
||||
const { hasGeom } = await geomResp.json() as { hasGeom: boolean };
|
||||
expect(hasGeom).toBe(true);
|
||||
expect(await routeHasGeom(request, routeId)).toBe(true);
|
||||
});
|
||||
|
||||
test("invalid GPX returns 400 and does not store geometry", async ({ request }) => {
|
||||
const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
|
||||
const { routeId, token } = await seedResp.json() as { routeId: string; token: string };
|
||||
const { routeId, token } = await seedRoute(request);
|
||||
|
||||
const callbackResp = await request.post(`${JOURNAL}/api/routes/${routeId}/callback`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
|
|
@ -57,14 +51,11 @@ test.describe("Integration: Planner callback → geometry stored", () => {
|
|||
const body = await callbackResp.json() as { error: string };
|
||||
expect(body.error).toMatch(/at least 2 track points/);
|
||||
|
||||
const geomResp = await request.get(`${JOURNAL}/api/e2e/route/${routeId}`);
|
||||
const { hasGeom } = await geomResp.json() as { hasGeom: boolean };
|
||||
expect(hasGeom).toBe(false);
|
||||
expect(await routeHasGeom(request, routeId)).toBe(false);
|
||||
});
|
||||
|
||||
test("missing token returns 401", async ({ request }) => {
|
||||
const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
|
||||
const { routeId } = await seedResp.json() as { routeId: string };
|
||||
const { routeId } = await seedRoute(request);
|
||||
|
||||
const resp = await request.post(`${JOURNAL}/api/routes/${routeId}/callback`, {
|
||||
data: { gpx: VALID_GPX },
|
||||
|
|
@ -73,8 +64,7 @@ test.describe("Integration: Planner callback → geometry stored", () => {
|
|||
});
|
||||
|
||||
test("token is single-use — second submit is rejected (Phase B replay guard)", async ({ request }) => {
|
||||
const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
|
||||
const { routeId, token } = await seedResp.json() as { routeId: string; token: string };
|
||||
const { routeId, token } = await seedRoute(request);
|
||||
|
||||
// First save succeeds.
|
||||
const first = await request.post(`${JOURNAL}/api/routes/${routeId}/callback`, {
|
||||
|
|
@ -163,9 +153,7 @@ test.describe("Integration: POI metadata roundtrip", () => {
|
|||
</trkseg></trk>
|
||||
</gpx>`;
|
||||
|
||||
const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
|
||||
expect(seedResp.ok()).toBeTruthy();
|
||||
const { routeId, token } = await seedResp.json() as { routeId: string; token: string };
|
||||
const { routeId, token } = await seedRoute(request);
|
||||
|
||||
const callbackResp = await request.post(`${JOURNAL}/api/routes/${routeId}/callback`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
|
|
@ -182,8 +170,7 @@ test.describe("Integration: POI metadata roundtrip", () => {
|
|||
});
|
||||
|
||||
test("GPX without POI extensions shows no waypoints section", async ({ page, request }) => {
|
||||
const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
|
||||
const { routeId, token } = await seedResp.json() as { routeId: string; token: string };
|
||||
const { routeId, token } = await seedRoute(request);
|
||||
await request.post(`${JOURNAL}/api/routes/${routeId}/callback`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
data: { gpx: VALID_GPX },
|
||||
|
|
|
|||
|
|
@ -17,10 +17,9 @@
|
|||
// computes a route and the Save button has GPX to ship.
|
||||
|
||||
import { test, expect } from "./fixtures/test";
|
||||
import { JOURNAL, PLANNER, seedRoute, routeHasGeom } from "./helpers/journal";
|
||||
import { mockBRouter } from "./fixtures/brouter-mock";
|
||||
|
||||
const JOURNAL = "http://localhost:3000";
|
||||
const PLANNER = "http://localhost:3001";
|
||||
|
||||
// Mock BRouter so the in-browser route compute is deterministic and
|
||||
// fast — same approach as `planner-coloring.test.ts`. Without this the
|
||||
|
|
@ -35,9 +34,7 @@ const WAYPOINTS = encodeURIComponent(JSON.stringify([
|
|||
]));
|
||||
|
||||
async function seedRouteAndPlannerSession(request: import("@playwright/test").APIRequestContext) {
|
||||
const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
|
||||
expect(seedResp.ok()).toBeTruthy();
|
||||
const { routeId, token } = (await seedResp.json()) as { routeId: string; token: string };
|
||||
const { routeId, token } = await seedRoute(request);
|
||||
|
||||
// Create a planner session with the journal callback wired up — no
|
||||
// GPX seeded into the session itself. We pass waypoints via URL
|
||||
|
|
@ -85,9 +82,7 @@ test.describe("Journal ↔ Planner save handoff (Phase A + B)", () => {
|
|||
expect(observed.some((s) => s.includes(token))).toBe(false);
|
||||
|
||||
// Sanity: the journal's route now has geometry.
|
||||
const geomResp = await request.get(`${JOURNAL}/api/e2e/route/${routeId}`);
|
||||
const { hasGeom } = (await geomResp.json()) as { hasGeom: boolean };
|
||||
expect(hasGeom).toBe(true);
|
||||
expect(await routeHasGeom(request, routeId)).toBe(true);
|
||||
});
|
||||
|
||||
test("token is single-use — second save through the planner UI fails", async ({ page, request }) => {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import { test, expect } from "./fixtures/test";
|
||||
import { JOURNAL, seedKomootConnection, seedRoute } from "./helpers/journal";
|
||||
|
||||
// Fixed test data — the e2e seed endpoint creates a stable user + Komoot connection
|
||||
const KOMOOT_USER_ID = "99999999999";
|
||||
const JOURNAL = "http://localhost:3000";
|
||||
|
||||
const SAMPLE_GPX = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gpx version="1.1" creator="komoot" xmlns="http://www.topografix.com/GPX/1/1">
|
||||
|
|
@ -34,19 +34,6 @@ const MOCK_TOURS_RESPONSE = {
|
|||
page: { totalPages: 1, number: 0 },
|
||||
};
|
||||
|
||||
// Seeds a Komoot connection for the e2e test user and returns a session cookie.
|
||||
async function seedKomootConnection(
|
||||
request: import("@playwright/test").APIRequestContext,
|
||||
mode: "public" | "authenticated" = "public",
|
||||
) {
|
||||
const resp = await request.post(`${JOURNAL}/api/e2e/komoot`, {
|
||||
data: { mode },
|
||||
});
|
||||
if (!resp.ok()) throw new Error(`komoot seed failed: ${resp.status()}`);
|
||||
const cookie = resp.headers()["set-cookie"];
|
||||
return { cookie };
|
||||
}
|
||||
|
||||
test.describe("Komoot connection page", () => {
|
||||
test("unauthenticated user is redirected to login", async ({ page }) => {
|
||||
await page.goto("/settings/connections/komoot");
|
||||
|
|
@ -105,10 +92,8 @@ test.describe("Komoot import page", () => {
|
|||
test.setTimeout(60000);
|
||||
|
||||
test("redirects to connect page when not connected", async ({ page, request }) => {
|
||||
// Seed user without Komoot connection (use seed endpoint to just get a session)
|
||||
const seedResp = await request.post(`${JOURNAL}/api/e2e/seed`);
|
||||
const data = await seedResp.json() as { routeId: string; token: string };
|
||||
// We only need the session — navigate to import page unauthenticated redirects to login
|
||||
await seedRoute(request);
|
||||
await page.goto("/sync/import/komoot");
|
||||
await expect(page).toHaveURL(/\/auth\/login|\/settings\/connections\/komoot/, { timeout: 5000 });
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,29 +1,5 @@
|
|||
import { test, expect, waitForHydration, type CDPSession, type Page } from "./fixtures/test";
|
||||
|
||||
async function setupVirtualAuthenticator(cdp: CDPSession) {
|
||||
await cdp.send("WebAuthn.enable");
|
||||
const { authenticatorId } = await cdp.send("WebAuthn.addVirtualAuthenticator", {
|
||||
options: {
|
||||
protocol: "ctap2",
|
||||
transport: "internal",
|
||||
hasResidentKey: true,
|
||||
hasUserVerification: true,
|
||||
isUserVerified: true,
|
||||
},
|
||||
});
|
||||
return authenticatorId;
|
||||
}
|
||||
|
||||
async function registerUser(page: Page, email: string, username: string) {
|
||||
await page.goto("/auth/register");
|
||||
await expect(page.getByRole("heading", { name: "Register" })).toBeVisible();
|
||||
await waitForHydration(page);
|
||||
await page.getByLabel("Email").fill(email);
|
||||
await page.getByLabel("Username").fill(username);
|
||||
await page.getByRole("checkbox").check();
|
||||
await page.getByRole("button", { name: /Register with Passkey/ }).click();
|
||||
await expect(page).toHaveURL("/", { timeout: 10000 });
|
||||
}
|
||||
import { setupVirtualAuthenticator, registerUser } from "./helpers/auth";
|
||||
|
||||
async function setProfileVisibility(page: Page, value: "public" | "private") {
|
||||
await page.goto("/settings");
|
||||
|
|
|
|||
|
|
@ -1,31 +1,5 @@
|
|||
import { test, expect, waitForHydration, type CDPSession, type Page } from "./fixtures/test";
|
||||
|
||||
// Reuses the virtual-authenticator + register helpers from auth.test.ts.
|
||||
// Inlined rather than factored out to keep this file independently runnable.
|
||||
async function setupVirtualAuthenticator(cdp: CDPSession) {
|
||||
await cdp.send("WebAuthn.enable");
|
||||
const { authenticatorId } = await cdp.send("WebAuthn.addVirtualAuthenticator", {
|
||||
options: {
|
||||
protocol: "ctap2",
|
||||
transport: "internal",
|
||||
hasResidentKey: true,
|
||||
hasUserVerification: true,
|
||||
isUserVerified: true,
|
||||
},
|
||||
});
|
||||
return authenticatorId;
|
||||
}
|
||||
|
||||
async function registerUser(page: Page, email: string, username: string) {
|
||||
await page.goto("/auth/register");
|
||||
await expect(page.getByRole("heading", { name: "Register" })).toBeVisible();
|
||||
await waitForHydration(page);
|
||||
await page.getByLabel("Email").fill(email);
|
||||
await page.getByLabel("Username").fill(username);
|
||||
await page.getByRole("checkbox").check();
|
||||
await page.getByRole("button", { name: /Register with Passkey/ }).click();
|
||||
await expect(page).toHaveURL("/", { timeout: 10000 });
|
||||
}
|
||||
import { setupVirtualAuthenticator, registerUser } from "./helpers/auth";
|
||||
|
||||
async function createRoute(page: Page, name: string): Promise<string> {
|
||||
await page.goto("/routes/new");
|
||||
|
|
|
|||
|
|
@ -1,36 +1,5 @@
|
|||
import { test, expect, type CDPSession, type Page } from "./fixtures/test";
|
||||
|
||||
async function setupVirtualAuthenticator(cdp: CDPSession) {
|
||||
await cdp.send("WebAuthn.enable");
|
||||
const { authenticatorId } = await cdp.send("WebAuthn.addVirtualAuthenticator", {
|
||||
options: {
|
||||
protocol: "ctap2",
|
||||
transport: "internal",
|
||||
hasResidentKey: true,
|
||||
hasUserVerification: true,
|
||||
isUserVerified: true,
|
||||
},
|
||||
});
|
||||
return authenticatorId;
|
||||
}
|
||||
|
||||
async function removeVirtualAuthenticator(cdp: CDPSession, authenticatorId: string) {
|
||||
await cdp.send("WebAuthn.removeVirtualAuthenticator", { authenticatorId });
|
||||
await cdp.send("WebAuthn.disable");
|
||||
}
|
||||
|
||||
async function registerAndLogin(page: Page, cdp: CDPSession) {
|
||||
const email = `settings-${Date.now()}@example.com`;
|
||||
const username = `settingsuser${Date.now()}`;
|
||||
|
||||
await page.goto("/auth/register");
|
||||
await page.getByLabel("Email").fill(email);
|
||||
await page.getByLabel("Username").fill(username);
|
||||
await page.getByRole("button", { name: /Register with Passkey/ }).click();
|
||||
await expect(page).toHaveURL("/", { timeout: 10000 });
|
||||
|
||||
return { email, username };
|
||||
}
|
||||
import { setupVirtualAuthenticator, removeVirtualAuthenticator, registerFreshUser } from "./helpers/auth";
|
||||
|
||||
test.describe("Account Settings", () => {
|
||||
test("unauthenticated user is redirected to login", async ({ page }) => {
|
||||
|
|
@ -41,7 +10,7 @@ test.describe("Account Settings", () => {
|
|||
test("settings page loads for authenticated user", async ({ page }) => {
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
const authenticatorId = await setupVirtualAuthenticator(cdp);
|
||||
await registerAndLogin(page, cdp);
|
||||
await registerFreshUser(page, "settings");
|
||||
|
||||
await page.goto("/settings");
|
||||
await expect(page.getByRole("heading", { name: "Settings" })).toBeVisible();
|
||||
|
|
@ -55,7 +24,7 @@ test.describe("Account Settings", () => {
|
|||
test("update display name and bio", async ({ page }) => {
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
const authenticatorId = await setupVirtualAuthenticator(cdp);
|
||||
const { username } = await registerAndLogin(page, cdp);
|
||||
const { username } = await registerFreshUser(page, "settings");
|
||||
|
||||
await page.goto("/settings");
|
||||
|
||||
|
|
@ -79,7 +48,7 @@ test.describe("Account Settings", () => {
|
|||
test("passkey list shows registered passkey", async ({ page }) => {
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
const authenticatorId = await setupVirtualAuthenticator(cdp);
|
||||
await registerAndLogin(page, cdp);
|
||||
await registerFreshUser(page, "settings");
|
||||
|
||||
await page.goto("/settings");
|
||||
// Should show the passkey registered during registration
|
||||
|
|
@ -92,7 +61,7 @@ test.describe("Account Settings", () => {
|
|||
test("add and delete passkey from settings", async ({ page }) => {
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
const authenticatorId = await setupVirtualAuthenticator(cdp);
|
||||
await registerAndLogin(page, cdp);
|
||||
await registerFreshUser(page, "settings");
|
||||
|
||||
await page.goto("/settings");
|
||||
|
||||
|
|
@ -119,7 +88,7 @@ test.describe("Account Settings", () => {
|
|||
test("delete last passkey shows warning", async ({ page }) => {
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
const authenticatorId = await setupVirtualAuthenticator(cdp);
|
||||
await registerAndLogin(page, cdp);
|
||||
await registerFreshUser(page, "settings");
|
||||
|
||||
await page.goto("/settings");
|
||||
|
||||
|
|
@ -142,7 +111,7 @@ test.describe("Account Settings", () => {
|
|||
test("settings link reachable from nav when logged in", async ({ page }) => {
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
const authenticatorId = await setupVirtualAuthenticator(cdp);
|
||||
const { username } = await registerAndLogin(page, cdp);
|
||||
const { username } = await registerFreshUser(page, "settings");
|
||||
|
||||
// Settings now lives inside the avatar dropdown; opening the
|
||||
// dropdown reveals the menuitem.
|
||||
|
|
@ -161,7 +130,7 @@ test.describe("Account Settings", () => {
|
|||
test("account deletion requires correct username", async ({ page }) => {
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
const authenticatorId = await setupVirtualAuthenticator(cdp);
|
||||
const { username } = await registerAndLogin(page, cdp);
|
||||
const { username } = await registerFreshUser(page, "settings");
|
||||
|
||||
await page.goto("/settings");
|
||||
|
||||
|
|
|
|||
|
|
@ -1,31 +1,5 @@
|
|||
import { test, expect, waitForHydration, type CDPSession, type Page } from "./fixtures/test";
|
||||
|
||||
// Inline virtual-authenticator + register helpers, mirroring the pattern
|
||||
// in auth.test.ts / public-content.test.ts so this file runs standalone.
|
||||
async function setupVirtualAuthenticator(cdp: CDPSession) {
|
||||
await cdp.send("WebAuthn.enable");
|
||||
const { authenticatorId } = await cdp.send("WebAuthn.addVirtualAuthenticator", {
|
||||
options: {
|
||||
protocol: "ctap2",
|
||||
transport: "internal",
|
||||
hasResidentKey: true,
|
||||
hasUserVerification: true,
|
||||
isUserVerified: true,
|
||||
},
|
||||
});
|
||||
return authenticatorId;
|
||||
}
|
||||
|
||||
async function registerUser(page: Page, email: string, username: string) {
|
||||
await page.goto("/auth/register");
|
||||
await expect(page.getByRole("heading", { name: "Register" })).toBeVisible();
|
||||
await waitForHydration(page);
|
||||
await page.getByLabel("Email").fill(email);
|
||||
await page.getByLabel("Username").fill(username);
|
||||
await page.getByRole("checkbox").check();
|
||||
await page.getByRole("button", { name: /Register with Passkey/ }).click();
|
||||
await expect(page).toHaveURL("/", { timeout: 10000 });
|
||||
}
|
||||
import { setupVirtualAuthenticator, registerUser } from "./helpers/auth";
|
||||
|
||||
async function setProfileVisibility(page: Page, value: "public" | "private") {
|
||||
await page.goto("/settings");
|
||||
|
|
|
|||
|
|
@ -39,7 +39,11 @@ export const CreateActivityRequestSchema = z.object({
|
|||
distance: z.number().optional(),
|
||||
});
|
||||
|
||||
/** Response to POST /api/v1/activities */
|
||||
export const CreateActivityResponseSchema = z.object({ id: z.uuid() });
|
||||
|
||||
export type ActivitySummary = z.infer<typeof ActivitySummarySchema>;
|
||||
export type CreateActivityResponse = z.infer<typeof CreateActivityResponseSchema>;
|
||||
export type ActivityDetail = z.infer<typeof ActivityDetailSchema>;
|
||||
export type ActivityListResponse = z.infer<typeof ActivityListResponseSchema>;
|
||||
export type CreateActivityRequest = z.infer<typeof CreateActivityRequestSchema>;
|
||||
|
|
|
|||
|
|
@ -33,10 +33,12 @@ export {
|
|||
RouteSummarySchema, RouteDetailSchema, RouteVersionSchema,
|
||||
RouteListResponseSchema,
|
||||
CreateRouteRequestSchema, UpdateRouteRequestSchema,
|
||||
CreateRouteResponseSchema,
|
||||
ComputeRouteRequestSchema,
|
||||
type RouteSummary, type RouteDetail, type RouteVersion,
|
||||
type RouteListResponse,
|
||||
type CreateRouteRequest, type UpdateRouteRequest,
|
||||
type CreateRouteResponse,
|
||||
type ComputeRouteRequest,
|
||||
} from "./routes.ts";
|
||||
|
||||
|
|
@ -44,10 +46,10 @@ export {
|
|||
export {
|
||||
ActivitySummarySchema, ActivityDetailSchema,
|
||||
ActivityListResponseSchema,
|
||||
CreateActivityRequestSchema,
|
||||
CreateActivityRequestSchema, CreateActivityResponseSchema,
|
||||
type ActivitySummary, type ActivityDetail,
|
||||
type ActivityListResponse,
|
||||
type CreateActivityRequest,
|
||||
type CreateActivityRequest, type CreateActivityResponse,
|
||||
} from "./activities.ts";
|
||||
|
||||
// Uploads
|
||||
|
|
|
|||
|
|
@ -17,7 +17,9 @@ export const RouteSummarySchema = z.object({
|
|||
|
||||
/** Route version info */
|
||||
export const RouteVersionSchema = z.object({
|
||||
id: z.uuid(),
|
||||
version: z.number(),
|
||||
createdBy: z.string().nullable(),
|
||||
changeDescription: z.string().nullable(),
|
||||
createdAt: z.iso.datetime(),
|
||||
});
|
||||
|
|
@ -64,7 +66,11 @@ export const ComputeRouteRequestSchema = z.object({
|
|||
})).optional(),
|
||||
});
|
||||
|
||||
/** Response to POST /api/v1/routes */
|
||||
export const CreateRouteResponseSchema = z.object({ id: z.uuid() });
|
||||
|
||||
export type RouteSummary = z.infer<typeof RouteSummarySchema>;
|
||||
export type CreateRouteResponse = z.infer<typeof CreateRouteResponseSchema>;
|
||||
export type RouteVersion = z.infer<typeof RouteVersionSchema>;
|
||||
export type RouteDetail = z.infer<typeof RouteDetailSchema>;
|
||||
export type RouteListResponse = z.infer<typeof RouteListResponseSchema>;
|
||||
|
|
|
|||
|
|
@ -463,3 +463,13 @@ export const consumedJwtJti = journalSchema.table("consumed_jwt_jti", {
|
|||
// Sweep runs `DELETE WHERE expires_at < now()` on a daily schedule.
|
||||
expiresAtIdx: index("consumed_jwt_jti_expires_at_idx").on(t.expiresAt),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Canonical row types — derive from the schema, never re-declare by hand.
|
||||
// API wire shapes live in @trails-cool/api; these are the database truth.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type RouteRow = typeof routes.$inferSelect;
|
||||
export type RouteVersionRow = typeof routeVersions.$inferSelect;
|
||||
export type ActivityRow = typeof activities.$inferSelect;
|
||||
export type UserRow = typeof users.$inferSelect;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,13 @@
|
|||
/**
|
||||
* Shared TypeScript types for trails.cool
|
||||
* Shared TypeScript types for trails.cool — the Waypoint wire format
|
||||
* used by both the Planner and Journal apps (Yjs document, GPX
|
||||
* extensions, handoff payloads).
|
||||
*
|
||||
* These types are used by both the Planner and Journal apps.
|
||||
* Not here on purpose: database row types are derived from the Drizzle
|
||||
* schema (@trails-cool/db, e.g. RouteRow), and API response shapes are
|
||||
* the Zod contracts in @trails-cool/api. Earlier hand-written Route /
|
||||
* Activity interfaces in this file drifted from both and had zero
|
||||
* importers when they were removed.
|
||||
*/
|
||||
|
||||
export interface WaypointPoiTags {
|
||||
|
|
@ -26,48 +32,3 @@ export interface Waypoint {
|
|||
osmId?: number;
|
||||
poiTags?: WaypointPoiTags;
|
||||
}
|
||||
|
||||
export interface RouteMetadata {
|
||||
created: Date;
|
||||
updated: Date;
|
||||
owner: string;
|
||||
contributors: string[];
|
||||
routingProfile: string;
|
||||
dayBreaks: number[];
|
||||
distance: number;
|
||||
elevation: {
|
||||
gain: number;
|
||||
loss: number;
|
||||
};
|
||||
tags: string[];
|
||||
}
|
||||
|
||||
export interface Route {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
gpx: string;
|
||||
metadata: RouteMetadata;
|
||||
plannerState?: Uint8Array;
|
||||
versions: RouteVersion[];
|
||||
}
|
||||
|
||||
export interface RouteVersion {
|
||||
version: number;
|
||||
gpx: string;
|
||||
createdAt: Date;
|
||||
createdBy: string;
|
||||
changeDescription?: string;
|
||||
}
|
||||
|
||||
export interface Activity {
|
||||
id: string;
|
||||
routeId?: string;
|
||||
name: string;
|
||||
description: string;
|
||||
gpx: string;
|
||||
startedAt: Date;
|
||||
duration: number;
|
||||
photos: string[];
|
||||
participants: string[];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,9 @@ export default defineConfig({
|
|||
trace: "on-first-retry",
|
||||
screenshot: "only-on-failure",
|
||||
},
|
||||
// NOTE: specs only run if a project below matches them — a new
|
||||
// e2e/*.test.ts file MUST be registered here or it silently never
|
||||
// executes (settings/explore/social sat unregistered for months).
|
||||
projects: [
|
||||
{
|
||||
name: "journal",
|
||||
|
|
|
|||
599
pnpm-lock.yaml
generated
599
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue