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,11 @@
// No-op CredentialAdapter for providers whose credentials never expire and
// cannot be refreshed (e.g. Komoot basic-auth, public-mode connections).
import type { CredentialAdapter, Credentials } from "../types.ts";
export const noopCredentialAdapter: CredentialAdapter<Credentials> = {
isExpired: () => false,
async refresh(creds) {
return creds;
},
};

View file

@ -4,8 +4,10 @@
import { registerManifest } from "../registry.ts";
import { wahooManifest } from "./wahoo/manifest.ts";
import { komootManifest } from "./komoot/manifest.ts";
registerManifest(wahooManifest);
registerManifest(komootManifest);
// Re-export so callers (mostly tests) can grab a manifest directly.
export { wahooManifest };
export { wahooManifest, komootManifest };

View file

@ -0,0 +1,128 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
// Mock server-only deps before import
vi.mock("../../../crypto.server.ts", () => ({
decrypt: vi.fn((s: string) => `decrypted:${s}`),
encrypt: vi.fn((s: string) => `encrypted:${s}`),
}));
vi.mock("../../../komoot.server.ts", () => ({
fetchKomootTours: vi.fn(),
fetchKomootTourGpx: vi.fn(),
}));
vi.mock("../../../sync/imports.server.ts", () => ({
isAlreadyImported: vi.fn(),
importActivity: vi.fn(),
recordImport: vi.fn(),
}));
vi.mock("../../manager.ts", () => ({
getServiceById: vi.fn(),
}));
import { komootImporter } from "./importer.ts";
import { fetchKomootTours, fetchKomootTourGpx } from "../../../komoot.server.ts";
import { isAlreadyImported, importActivity } from "../../../sync/imports.server.ts";
import { getServiceById } from "../../manager.ts";
const mockFetchTours = vi.mocked(fetchKomootTours);
const mockFetchGpx = vi.mocked(fetchKomootTourGpx);
const mockIsAlreadyImported = vi.mocked(isAlreadyImported);
const mockImportActivity = vi.mocked(importActivity);
const mockGetServiceById = vi.mocked(getServiceById);
function makeCtx(creds: unknown, serviceId = "svc-1") {
return {
serviceId,
withFreshCredentials: async <T>(fn: (c: unknown) => Promise<T>) => fn(creds),
};
}
describe("komootImporter.listImportable", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("lists public tours without auth token", async () => {
mockFetchTours.mockResolvedValueOnce({
tours: [
{ id: "111", name: "Morning ride", sport: "bike", date: "2024-01-01T00:00:00Z", distance: 30000, duration: 5400, elevationUp: 200, elevationDown: 190 },
],
totalPages: 1,
});
const ctx = makeCtx({ mode: "public", komootUserId: "999" });
const result = await komootImporter.listImportable(ctx, 1);
expect(mockFetchTours).toHaveBeenCalledWith("999", 1, undefined);
expect(result.workouts).toHaveLength(1);
expect(result.workouts[0]!.id).toBe("111");
});
it("passes basic auth token for authenticated mode", async () => {
mockFetchTours.mockResolvedValueOnce({ tours: [], totalPages: 1 });
const ctx = makeCtx({
mode: "authenticated",
email: "test@example.com",
encryptedPassword: "enc-pw",
komootUserId: "888",
});
await komootImporter.listImportable(ctx, 1);
// decrypt returns `decrypted:enc-pw`, so basic token = base64(test@example.com:decrypted:enc-pw)
const expectedToken = Buffer.from("test@example.com:decrypted:enc-pw").toString("base64");
expect(mockFetchTours).toHaveBeenCalledWith("888", 1, expectedToken);
});
});
describe("komootImporter.importOne", () => {
beforeEach(() => {
vi.clearAllMocks();
mockGetServiceById.mockResolvedValue({
id: "svc-1",
userId: "user-1",
provider: "komoot",
credentialKind: "public",
credentials: { mode: "public", komootUserId: "999" },
status: "active",
providerUserId: "999",
grantedScopes: [],
createdAt: new Date(),
});
mockIsAlreadyImported.mockResolvedValue(false);
mockImportActivity.mockResolvedValue({ activityId: "act-123" });
mockFetchTours.mockResolvedValue({ tours: [{ id: "tour-1", name: "Test Tour", sport: "hike", date: "2024-01-01T00:00:00Z", distance: 10000, duration: 3600, elevationUp: 100, elevationDown: 100 }], totalPages: 1 });
mockFetchGpx.mockResolvedValue("<gpx>...</gpx>");
});
it("imports a tour with GPX", async () => {
const ctx = makeCtx({ mode: "public", komootUserId: "999" });
const result = await komootImporter.importOne(ctx, "tour-1");
expect(result.activityId).toBe("act-123");
expect(result.hadGeometry).toBe(true);
expect(mockImportActivity).toHaveBeenCalledWith("user-1", "komoot", "tour-1", {
name: "Test Tour",
gpx: "<gpx>...</gpx>",
});
});
it("throws when tour is already imported", async () => {
mockIsAlreadyImported.mockResolvedValue(true);
const ctx = makeCtx({ mode: "public", komootUserId: "999" });
await expect(komootImporter.importOne(ctx, "tour-1")).rejects.toThrow("already imported");
});
it("imports without geometry when GPX fetch fails", async () => {
mockFetchGpx.mockRejectedValue(new Error("404"));
const ctx = makeCtx({ mode: "public", komootUserId: "999" });
const result = await komootImporter.importOne(ctx, "tour-1");
expect(result.hadGeometry).toBe(false);
expect(mockImportActivity).toHaveBeenCalledWith("user-1", "komoot", "tour-1", {
name: "Test Tour",
gpx: undefined,
});
});
});

View file

@ -0,0 +1,91 @@
// Komoot Importer capability adapter. Implements the Importer seam against
// the Komoot tours API.
//
// Two credential modes:
// public — unauthenticated, public tours only
// authenticated — email/password (password AES-256-GCM encrypted at rest)
import { decrypt } from "../../../crypto.server.ts";
import { fetchKomootTours, fetchKomootTourGpx } from "../../../komoot.server.ts";
import { isAlreadyImported, importActivity } from "../../../sync/imports.server.ts";
import type {
CapabilityContext,
ImportableList,
ImportResult,
Importer,
} from "../../registry.ts";
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 const komootImporter: Importer = {
async listImportable(ctx: CapabilityContext, page: number): Promise<ImportableList> {
return ctx.withFreshCredentials(async (rawCreds) => {
const creds = rawCreds as KomootCreds;
const basicAuthToken = getBasicAuthToken(creds);
const result = await fetchKomootTours(creds.komootUserId, page, basicAuthToken);
return {
workouts: result.tours.map((t) => ({
id: t.id,
name: t.name,
type: t.sport,
startedAt: t.date,
duration: t.duration > 0 ? t.duration : null,
distance: t.distance > 0 ? t.distance : null,
// fileUrl not used for Komoot — GPX is fetched directly in the import route
})),
total: result.tours.length * result.totalPages,
page,
perPage: 50,
};
});
},
async importOne(ctx: CapabilityContext, tourId: string): Promise<ImportResult> {
return ctx.withFreshCredentials(async (rawCreds) => {
const creds = rawCreds as KomootCreds;
const { getServiceById } = await import("../../manager.ts");
const service = await getServiceById(ctx.serviceId);
if (!service) throw new Error(`Connected service ${ctx.serviceId} not found`);
const userId = service.userId;
if (await isAlreadyImported(userId, "komoot", tourId)) {
throw new Error(`Tour ${tourId} already imported`);
}
const basicAuthToken = getBasicAuthToken(creds);
let gpx: string | undefined;
try {
gpx = await fetchKomootTourGpx(tourId, basicAuthToken);
} catch {
// GPX unavailable — import activity without geometry
}
// Fetch first page to find tour name; fall back to generic name
let tourName = `Komoot tour ${tourId}`;
try {
const result = await fetchKomootTours(creds.komootUserId, 1, basicAuthToken);
const tour = result.tours.find((t) => t.id === tourId);
if (tour) tourName = tour.name;
} catch {
// Ignore — use fallback name
}
const { activityId } = await importActivity(userId, "komoot", tourId, {
name: tourName,
gpx,
});
return { activityId, hadGeometry: !!gpx };
});
},
};

View file

@ -0,0 +1,20 @@
// Komoot provider manifest.
//
// Komoot supports two credential modes:
// public — unauthenticated ownership verification via bio link
// authenticated — email + AES-256-GCM encrypted password
//
// Neither mode uses OAuth; credentials are managed via a custom connect page.
import { noopCredentialAdapter } from "../../credential-adapters/noop.ts";
import type { ProviderManifest } from "../../registry.ts";
import { komootImporter } from "./importer.ts";
export const komootManifest: ProviderManifest = {
id: "komoot",
displayName: "Komoot",
credentialKind: "web-login",
credentialAdapter: noopCredentialAdapter,
connectUrl: "/settings/connections/komoot",
importer: komootImporter,
};

View file

@ -96,6 +96,9 @@ export interface ProviderManifest {
oauthConfig?: ProviderOAuthConfig;
// OAuth scopes requested at connect time. Wahoo grants all-or-nothing.
scopes?: string[];
// Custom connect page URL. When set, the connections settings page links
// here instead of the default OAuth connect endpoint.
connectUrl?: string;
// OAuth authorization URL builder (for the connect flow).
buildAuthUrl?: (redirectUri: string, state: string) => string;
// OAuth code exchange (for the callback). Returns the credential blob to

View file

@ -1,7 +1,7 @@
// Types for the Connected Services architecture. See docs/adr/0001-0003 and
// CONTEXT.md (Connected Services section).
export type CredentialKind = "oauth" | "web-login" | "device";
export type CredentialKind = "oauth" | "web-login" | "device" | "public";
export type ConnectionStatus = "active" | "needs_relink" | "revoked";