Add Komoot import with public (bio verification) and authenticated modes

Two-mode import: public mode verifies Komoot account ownership by checking
that the user's trails.cool profile URL appears in their Komoot bio — no
credentials stored. Authenticated mode uses email + password (AES-256-GCM
encrypted) to import private tours as well.

Includes unit tests for crypto/komoot client and E2E tests for the full
connect + import flow.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Ullrich Schäfer 2026-05-23 10:18:46 +02:00
parent b63fd1a303
commit 03304c354b
No known key found for this signature in database
GPG key ID: A32FF691A0F752D9
22 changed files with 1612 additions and 4 deletions

View file

@ -0,0 +1,48 @@
// POST /api/sync/komoot/connect
// Validates Komoot email/password credentials and stores them encrypted.
import { data, redirect } from "react-router";
import type { Route } from "./+types/api.sync.komoot.connect";
import { getSessionUser } from "~/lib/auth/session.server";
import { loginKomoot } from "~/lib/komoot.server";
import { encrypt } from "~/lib/crypto.server";
import { link } from "~/lib/connected-services/manager";
export async function action({ request }: Route.ActionArgs) {
const user = await getSessionUser(request);
if (!user) return redirect("/auth/login");
const body = (await request.json()) as { email?: string; password?: string };
const email = body.email?.trim() ?? "";
const password = body.password ?? "";
if (!email || !password) {
return data({ error: "missing_fields" }, { status: 400 });
}
let username: string;
try {
const result = await loginKomoot(email, password);
username = result.username;
} catch {
return data({ error: "invalid_credentials" }, { status: 401 });
}
const encryptedPassword = encrypt(password);
await link({
userId: user.id,
provider: "komoot",
credentialKind: "web-login",
credentials: {
mode: "authenticated",
email,
encryptedPassword,
komootUserId: username,
},
providerUserId: username,
grantedScopes: [],
});
return data({ success: true });
}

View file

@ -0,0 +1,41 @@
// POST /api/sync/komoot/verify
// Verifies Komoot public profile ownership by checking that the user's
// trails.cool profile URL appears in their Komoot bio.
// On success, creates or replaces the connected service row in public mode.
import { data, redirect } from "react-router";
import type { Route } from "./+types/api.sync.komoot.verify";
import { getSessionUser } from "~/lib/auth/session.server";
import { parseKomootUserId, verifyKomootOwnership } from "~/lib/komoot.server";
import { link } from "~/lib/connected-services/manager";
export async function action({ request }: Route.ActionArgs) {
const user = await getSessionUser(request);
if (!user) return redirect("/auth/login");
const body = (await request.json()) as { komootProfileUrl?: string };
const input = body.komootProfileUrl?.trim() ?? "";
const komootUserId = parseKomootUserId(input);
if (!komootUserId) {
return data({ error: "invalid_url" }, { status: 400 });
}
const origin = process.env.ORIGIN ?? "http://localhost:3000";
const trailsProfileUrl = `${origin}/users/${user.username}`;
const verified = await verifyKomootOwnership(komootUserId, trailsProfileUrl);
if (!verified) {
return data({ error: "not_verified" }, { status: 422 });
}
await link({
userId: user.id,
provider: "komoot",
credentialKind: "public",
credentials: { mode: "public", komootUserId },
providerUserId: komootUserId,
grantedScopes: [],
});
return data({ success: true });
}

View file

@ -284,6 +284,15 @@ export default function PrivacyPage() {
Routenversion erfolgt höchstens eine Übermittlung; Sie können
die Wahoo-Verbindung jederzeit in den Einstellungen trennen.
</li>
<li>
<strong>Komoot</strong> (Komoot GmbH) Optionaler Import von
Touren aus Komoot. Im öffentlichen Modus wird ausschließlich
die Komoot-Nutzer-ID gespeichert; es werden keine Zugangsdaten
erfasst. Im authentifizierten Modus werden E-Mail-Adresse und
Passwort verschlüsselt gespeichert, um auch private Touren zu
importieren. Die Verbindung kann jederzeit in den Einstellungen
getrennt werden.
</li>
<li>
<strong>Hosting</strong> Die Dienste werden in Rechenzentren
innerhalb der EU betrieben. Ein Auftragsverarbeitungsvertrag mit
@ -300,7 +309,9 @@ export default function PrivacyPage() {
Wahoo (only when you opt in: OAuth tokens for sync, plus route
geometry/name/description when you click &ldquo;Send to
Wahoo&rdquo; on a route sent so the route appears on your
ELEMNT/BOLT/ROAM); hosting provider in the EU under a DPA.
ELEMNT/BOLT/ROAM); Komoot (only when you opt in: public mode
stores your Komoot user ID only; authenticated mode stores your
encrypted Komoot password); hosting provider in the EU under a DPA.
</p>
</section>

View file

@ -0,0 +1,204 @@
// Komoot connection management page. Supports two modes:
// Public — verify ownership via bio link (no password stored)
// Authenticated — email + password (password encrypted at rest)
import { useState } from "react";
import { data, redirect, useFetcher } from "react-router";
import { useTranslation } from "react-i18next";
import type { Route } from "./+types/settings.connections.komoot";
import { getSessionUser } from "~/lib/auth/session.server";
import { getService } from "~/lib/connected-services/manager";
export function meta() {
return [{ title: "Connect Komoot — Settings — trails.cool" }];
}
export async function loader({ request }: Route.LoaderArgs) {
const user = await getSessionUser(request);
if (!user) throw redirect("/auth/login");
const service = await getService(user.id, "komoot");
const origin = process.env.ORIGIN ?? "http://localhost:3000";
const trailsProfileUrl = `${origin}/users/${user.username}`;
return data({
connected: !!service,
mode: service ? (service.credentials as { mode?: string }).mode ?? null : null,
providerUserId: service?.providerUserId ?? null,
serviceId: service?.id ?? null,
trailsProfileUrl,
});
}
type VerifyResponse = { success?: boolean; error?: string };
type ConnectResponse = { success?: boolean; error?: string };
export default function KomootConnectPage({ loaderData }: Route.ComponentProps) {
const { connected, mode, providerUserId, serviceId, trailsProfileUrl } = loaderData;
const { t } = useTranslation("journal");
const verifyFetcher = useFetcher<VerifyResponse>();
const connectFetcher = useFetcher<ConnectResponse>();
const [komootProfileUrl, setKomootProfileUrl] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const isVerifying = verifyFetcher.state !== "idle";
const isConnecting = connectFetcher.state !== "idle";
const verifyError = verifyFetcher.data?.error;
const connectError = connectFetcher.data?.error;
function handleVerify(e: React.FormEvent) {
e.preventDefault();
verifyFetcher.submit(
JSON.stringify({ komootProfileUrl }),
{ method: "post", action: "/api/sync/komoot/verify", encType: "application/json" },
);
}
function handleConnect(e: React.FormEvent) {
e.preventDefault();
connectFetcher.submit(
JSON.stringify({ email, password }),
{ method: "post", action: "/api/sync/komoot/connect", encType: "application/json" },
);
}
return (
<section className="space-y-8">
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold text-gray-900">{t("komoot.title")}</h2>
{connected && (
<div className="flex items-center gap-3">
<span className="rounded-full bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700">
{t("komoot.modeBadge", { mode: mode === "public" ? t("komoot.publicMode") : t("komoot.authenticatedMode") })}
</span>
{providerUserId && (
<span className="text-xs text-gray-500">
{t("settings.services.connectedAs", { id: providerUserId })}
</span>
)}
<a
href="/sync/import/komoot"
className="text-sm text-blue-600 hover:underline"
>
{t("sync.import")}
</a>
{serviceId && (
<form method="post" action={`/api/sync/disconnect/komoot`}>
<button type="submit" className="text-sm text-red-600 hover:underline">
{t("settings.services.disconnect")}
</button>
</form>
)}
</div>
)}
</div>
{verifyFetcher.data?.success && (
<div role="status" className="rounded-md border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-800">
{t("komoot.verifySuccess")}
</div>
)}
{connectFetcher.data?.success && (
<div role="status" className="rounded-md border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-800">
{t("komoot.connectSuccess")}
</div>
)}
{/* Public mode section */}
<div className="rounded-md border border-gray-200 p-4">
<h3 className="font-medium text-gray-900">{t("komoot.publicSection")}</h3>
<p className="mt-1 text-sm text-gray-600">
{t("komoot.publicInstructions")}
</p>
<div className="mt-2 rounded-md bg-gray-50 px-3 py-2 font-mono text-sm text-gray-800 select-all">
{trailsProfileUrl}
</div>
<form onSubmit={handleVerify} className="mt-4 flex flex-col gap-3 sm:flex-row sm:items-end">
<div className="flex-1">
<label className="block text-sm font-medium text-gray-700">
{t("komoot.profileUrlLabel")}
</label>
<input
type="text"
value={komootProfileUrl}
onChange={(e) => setKomootProfileUrl(e.target.value)}
placeholder={t("komoot.profileUrlPlaceholder")}
className="mt-1 w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
required
/>
</div>
<button
type="submit"
disabled={isVerifying}
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
>
{isVerifying ? t("komoot.verifying") : t("komoot.verifyButton")}
</button>
</form>
{verifyError && (
<p role="alert" className="mt-2 text-sm text-red-600">
{verifyError === "not_verified"
? t("komoot.verificationError")
: verifyError === "invalid_url"
? t("komoot.invalidUrl")
: t("komoot.verificationError")}
</p>
)}
{isVerifying && (
<p className="mt-2 text-sm text-gray-500">{t("komoot.verifyPending")}</p>
)}
</div>
{/* Authenticated mode section */}
<div className="rounded-md border border-gray-200 p-4">
<h3 className="font-medium text-gray-900">{t("komoot.authenticatedSection")}</h3>
<form onSubmit={handleConnect} className="mt-4 flex flex-col gap-3">
<div>
<label className="block text-sm font-medium text-gray-700">
{t("komoot.emailLabel")}
</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
autoComplete="username"
className="mt-1 w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
{t("komoot.passwordLabel")}
</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
className="mt-1 w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
required
/>
</div>
<button
type="submit"
disabled={isConnecting}
className="self-start rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
>
{isConnecting ? t("komoot.connecting") : t("komoot.connectButton")}
</button>
</form>
{connectError && (
<p role="alert" className="mt-2 text-sm text-red-600">
{connectError === "invalid_credentials"
? t("komoot.authError")
: t("komoot.authError")}
</p>
)}
</div>
</section>
);
}

View file

@ -37,6 +37,7 @@ export async function loader({ request }: Route.LoaderArgs) {
name: m.displayName,
connected: !!conn,
providerUserId: conn?.providerUserId,
connectUrl: m.connectUrl ?? null,
};
});
@ -94,7 +95,7 @@ export default function ConnectionsSettings({ loaderData }: Route.ComponentProps
</div>
) : (
<a
href={`/api/sync/connect/${p.id}`}
href={p.connectUrl ?? `/api/sync/connect/${p.id}`}
className="rounded-md bg-blue-600 px-3 py-1.5 text-sm text-white hover:bg-blue-700"
>
{t("settings.services.connect")}

View file

@ -0,0 +1,260 @@
// Komoot-specific import page. Mirrors the generic sync.import.$provider page
// but fetches GPX directly from Komoot instead of downloading a FIT file.
import { useCallback, useEffect, useRef, useState } from "react";
import { data, redirect, useFetcher } from "react-router";
import { useTranslation } from "react-i18next";
import type { Route } from "./+types/sync.import.komoot";
import { getSessionUser } from "~/lib/auth/session.server";
import { getService, capabilityContextFor } from "~/lib/connected-services";
import { getManifest } from "~/lib/connected-services";
import { getImportedIds, recordImport } from "~/lib/sync/imports.server";
import { createActivity } from "~/lib/activities.server";
import { fetchKomootTourGpx } from "~/lib/komoot.server";
import { decrypt } from "~/lib/crypto.server";
import { ClientDate } from "~/components/ClientDate";
type KomootCreds =
| { mode: "public"; komootUserId: string }
| { mode: "authenticated"; email: string; encryptedPassword: string; komootUserId: string };
function getBasicAuthToken(creds: KomootCreds): string | undefined {
if (creds.mode !== "authenticated") return undefined;
const password = decrypt(creds.encryptedPassword);
return Buffer.from(`${creds.email}:${password}`).toString("base64");
}
export function meta() {
return [{ title: "Import from Komoot — trails.cool" }];
}
export async function loader({ request }: Route.LoaderArgs) {
const user = await getSessionUser(request);
if (!user) return redirect("/auth/login");
const manifest = getManifest("komoot");
if (!manifest?.importer) throw data({ error: "Komoot not configured" }, { status: 500 });
const service = await getService(user.id, "komoot");
if (!service) return redirect("/settings/connections/komoot");
const url = new URL(request.url);
const page = parseInt(url.searchParams.get("page") ?? "1");
const ctx = capabilityContextFor(service.id);
const workoutList = await manifest.importer.listImportable(ctx, page);
const importedIds = await getImportedIds(
user.id,
"komoot",
workoutList.workouts.map((w) => w.id),
);
return data({
workouts: workoutList.workouts.map((w) => ({
...w,
imported: importedIds.has(w.id),
})),
page: workoutList.page,
totalPages: Math.ceil(workoutList.total / workoutList.perPage),
});
}
export async function action({ request }: Route.ActionArgs) {
const user = await getSessionUser(request);
if (!user) return redirect("/auth/login");
const service = await getService(user.id, "komoot");
if (!service) return redirect("/settings/connections/komoot");
const formData = await request.formData();
const tourId = formData.get("workoutId") as string;
const workoutName = formData.get("workoutName") as string;
const startedAt = formData.get("startedAt") as string;
const distance = formData.get("distance") as string;
const duration = formData.get("duration") as string;
const creds = service.credentials as KomootCreds;
const basicAuthToken = getBasicAuthToken(creds);
let gpx: string | undefined;
try {
gpx = await fetchKomootTourGpx(tourId, basicAuthToken);
} catch {
// No GPX available — import without geometry
}
const activityId = await createActivity(user.id, {
name: workoutName || `Komoot tour ${tourId}`,
gpx,
distance: distance ? parseFloat(distance) : null,
duration: duration ? parseInt(duration) : null,
startedAt: startedAt ? new Date(startedAt) : null,
});
await recordImport(user.id, "komoot", tourId, activityId);
return data({ imported: tourId });
}
function TourRow({
workout,
alreadyImported,
}: {
workout: { id: string; name: string; startedAt: string; distance: number | null; duration: number | null };
alreadyImported: boolean;
}) {
const { t } = useTranslation("journal");
const fetcher = useFetcher<{ imported?: string }>();
const isImporting = fetcher.state !== "idle";
const isImported = alreadyImported || fetcher.data?.imported === workout.id;
return (
<li className="flex items-center justify-between rounded-lg border border-gray-200 p-4">
<div>
<p className="font-medium text-gray-900">{workout.name}</p>
<div className="mt-1 flex gap-3 text-sm text-gray-500">
{workout.startedAt && <ClientDate iso={workout.startedAt} />}
{workout.distance != null && <span>{(workout.distance / 1000).toFixed(1)} km</span>}
{workout.duration != null && <span>{Math.round(workout.duration / 60)} min</span>}
</div>
</div>
{isImported ? (
<span className="text-sm text-green-600">{t("sync.imported")}</span>
) : isImporting ? (
<span className="text-sm text-gray-400">{t("sync.importing")}</span>
) : (
<fetcher.Form method="post">
<input type="hidden" name="workoutId" value={workout.id} />
<input type="hidden" name="workoutName" value={workout.name} />
<input type="hidden" name="startedAt" value={workout.startedAt ?? ""} />
<input type="hidden" name="distance" value={workout.distance ?? ""} />
<input type="hidden" name="duration" value={workout.duration ?? ""} />
<button
type="submit"
className="rounded-md bg-blue-600 px-3 py-1.5 text-sm text-white hover:bg-blue-700"
>
{t("sync.import")}
</button>
</fetcher.Form>
)}
</li>
);
}
function tourFormData(w: { id: string; name: string; startedAt: string; distance: number | null; duration: number | null }) {
const fd = new FormData();
fd.set("workoutId", w.id);
fd.set("workoutName", w.name);
fd.set("startedAt", w.startedAt ?? "");
fd.set("distance", w.distance != null ? String(w.distance) : "");
fd.set("duration", w.duration != null ? String(w.duration) : "");
return fd;
}
export default function KomootImportPage({ loaderData }: Route.ComponentProps) {
const { workouts, page, totalPages } = loaderData;
const { t } = useTranslation("journal");
const importableWorkouts = workouts.filter((w) => !w.imported);
const [importAllActive, setImportAllActive] = useState(false);
const [importAllIndex, setImportAllIndex] = useState(0);
const importAllFetcher = useFetcher<{ imported?: string }>();
const importAllRef = useRef({ index: 0, workouts: importableWorkouts });
useEffect(() => {
importAllRef.current.workouts = importableWorkouts;
}, [importableWorkouts]);
useEffect(() => {
if (!importAllActive) return;
if (importAllFetcher.state !== "idle") return;
const nextIndex = importAllFetcher.data
? importAllRef.current.index + 1
: importAllRef.current.index;
importAllRef.current.index = nextIndex;
setImportAllIndex(nextIndex);
if (nextIndex >= importAllRef.current.workouts.length) {
setImportAllActive(false);
return;
}
const w = importAllRef.current.workouts[nextIndex]!;
importAllFetcher.submit(tourFormData(w), { method: "post" });
}, [importAllActive, importAllFetcher.state, importAllFetcher.data]);
const startImportAll = useCallback(() => {
if (importableWorkouts.length === 0) return;
importAllRef.current = { index: 0, workouts: importableWorkouts };
setImportAllIndex(0);
setImportAllActive(true);
importAllFetcher.submit(tourFormData(importableWorkouts[0]!), { method: "post" });
}, [importableWorkouts, importAllFetcher]);
return (
<div className="mx-auto max-w-4xl px-4 py-8">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold text-gray-900">
{t("sync.importFrom", { provider: "Komoot" })}
</h1>
{importableWorkouts.length > 0 && (
importAllActive ? (
<span className="text-sm text-gray-500">
{t("sync.importingProgress", {
current: importAllIndex + 1,
total: importAllRef.current.workouts.length,
})}
</span>
) : (
<button
onClick={startImportAll}
className="rounded-md border border-gray-300 px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-50"
>
{t("sync.importAll", { count: importableWorkouts.length })}
</button>
)
)}
</div>
{workouts.length === 0 ? (
<p className="mt-8 text-center text-gray-500">{t("sync.noWorkouts")}</p>
) : (
<ul className="mt-6 space-y-3">
{workouts.map((w) => (
<TourRow
key={w.id}
workout={w}
alreadyImported={w.imported || importAllFetcher.data?.imported === w.id}
/>
))}
</ul>
)}
{totalPages > 1 && (
<div className="mt-6 flex justify-center gap-2">
{page > 1 && (
<a
href={`/sync/import/komoot?page=${page - 1}`}
className="rounded border border-gray-300 px-3 py-1 text-sm hover:bg-gray-50"
>
{t("sync.previous")}
</a>
)}
<span className="px-3 py-1 text-sm text-gray-500">
{page} / {totalPages}
</span>
{page < totalPages && (
<a
href={`/sync/import/komoot?page=${page + 1}`}
className="rounded border border-gray-300 px-3 py-1 text-sm hover:bg-gray-50"
>
{t("sync.next")}
</a>
)}
</div>
)}
</div>
);
}