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:
parent
b63fd1a303
commit
03304c354b
22 changed files with 1612 additions and 4 deletions
|
|
@ -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;
|
||||
},
|
||||
};
|
||||
|
|
@ -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 };
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -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 };
|
||||
});
|
||||
},
|
||||
};
|
||||
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
||||
|
|
|
|||
49
apps/journal/app/lib/crypto.server.test.ts
Normal file
49
apps/journal/app/lib/crypto.server.test.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
|
||||
// Set env before importing module
|
||||
beforeEach(() => {
|
||||
process.env.INTEGRATION_SECRET = "test-secret-for-unit-tests";
|
||||
});
|
||||
|
||||
const { encrypt, decrypt } = await import("./crypto.server.ts");
|
||||
|
||||
describe("crypto.server", () => {
|
||||
it("roundtrips ASCII plaintext", () => {
|
||||
const plaintext = "hello world";
|
||||
expect(decrypt(encrypt(plaintext))).toBe(plaintext);
|
||||
});
|
||||
|
||||
it("roundtrips unicode plaintext", () => {
|
||||
const plaintext = "Über dich 🏔️ trails.cool";
|
||||
expect(decrypt(encrypt(plaintext))).toBe(plaintext);
|
||||
});
|
||||
|
||||
it("produces different ciphertext for the same input (random IV)", () => {
|
||||
const plaintext = "same input";
|
||||
const c1 = encrypt(plaintext);
|
||||
const c2 = encrypt(plaintext);
|
||||
expect(c1).not.toBe(c2);
|
||||
// But both decrypt correctly
|
||||
expect(decrypt(c1)).toBe(plaintext);
|
||||
expect(decrypt(c2)).toBe(plaintext);
|
||||
});
|
||||
|
||||
it("throws on tampered auth tag", () => {
|
||||
const encoded = encrypt("sensitive");
|
||||
// Decode the base64 payload, split on ":", flip bytes in the auth tag
|
||||
const payload = Buffer.from(encoded, "base64").toString("utf8");
|
||||
const parts = payload.split(":");
|
||||
// parts: [ivHex, encryptedHex, authTagHex]
|
||||
const authTagBuf = Buffer.from(parts[2]!, "hex");
|
||||
authTagBuf[0] = authTagBuf[0]! ^ 0xff;
|
||||
parts[2] = authTagBuf.toString("hex");
|
||||
const tampered = Buffer.from(parts.join(":")).toString("base64");
|
||||
expect(() => decrypt(tampered)).toThrow();
|
||||
});
|
||||
|
||||
it("throws on invalid format", () => {
|
||||
expect(() => decrypt(Buffer.from("notvalidformat").toString("base64"))).toThrow(
|
||||
"Invalid encrypted payload format",
|
||||
);
|
||||
});
|
||||
});
|
||||
41
apps/journal/app/lib/crypto.server.ts
Normal file
41
apps/journal/app/lib/crypto.server.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
// AES-256-GCM encrypt/decrypt for storing sensitive integration credentials.
|
||||
// Key is derived from INTEGRATION_SECRET env var using scrypt.
|
||||
//
|
||||
// Encoded format: base64(salt_hex:iv_hex:ciphertext_hex:authtag_hex)
|
||||
// All fields are hex-encoded before joining so the separator is unambiguous.
|
||||
|
||||
import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "node:crypto";
|
||||
|
||||
const SALT = "trails-cool-integrations";
|
||||
const KEY_LEN = 32; // AES-256
|
||||
const IV_LEN = 12; // GCM standard
|
||||
|
||||
function getKey(): Buffer {
|
||||
const secret = process.env.INTEGRATION_SECRET;
|
||||
if (!secret) throw new Error("INTEGRATION_SECRET env var is not set");
|
||||
return scryptSync(secret, SALT, KEY_LEN) as Buffer;
|
||||
}
|
||||
|
||||
export function encrypt(plaintext: string): string {
|
||||
const key = getKey();
|
||||
const iv = randomBytes(IV_LEN);
|
||||
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
||||
const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
||||
const authTag = cipher.getAuthTag();
|
||||
const payload = [iv.toString("hex"), encrypted.toString("hex"), authTag.toString("hex")].join(":");
|
||||
return Buffer.from(payload).toString("base64");
|
||||
}
|
||||
|
||||
export function decrypt(encoded: string): string {
|
||||
const key = getKey();
|
||||
const payload = Buffer.from(encoded, "base64").toString("utf8");
|
||||
const parts = payload.split(":");
|
||||
if (parts.length !== 3) throw new Error("Invalid encrypted payload format");
|
||||
const [ivHex, encryptedHex, authTagHex] = parts as [string, string, string];
|
||||
const iv = Buffer.from(ivHex, "hex");
|
||||
const encrypted = Buffer.from(encryptedHex, "hex");
|
||||
const authTag = Buffer.from(authTagHex, "hex");
|
||||
const decipher = createDecipheriv("aes-256-gcm", key, iv);
|
||||
decipher.setAuthTag(authTag);
|
||||
return decipher.update(encrypted) + decipher.final("utf8");
|
||||
}
|
||||
184
apps/journal/app/lib/komoot.server.test.ts
Normal file
184
apps/journal/app/lib/komoot.server.test.ts
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
parseKomootUserId,
|
||||
verifyKomootOwnership,
|
||||
fetchPublicProfile,
|
||||
fetchKomootTours,
|
||||
} from "./komoot.server.ts";
|
||||
|
||||
describe("parseKomootUserId", () => {
|
||||
it("accepts a plain numeric ID", () => {
|
||||
expect(parseKomootUserId("27595800585")).toBe("27595800585");
|
||||
});
|
||||
|
||||
it("accepts a full komoot.com URL", () => {
|
||||
expect(parseKomootUserId("https://www.komoot.com/user/27595800585")).toBe("27595800585");
|
||||
});
|
||||
|
||||
it("accepts a locale-prefixed URL (de-de)", () => {
|
||||
expect(parseKomootUserId("https://www.komoot.com/de-de/user/27595800585")).toBe("27595800585");
|
||||
});
|
||||
|
||||
it("accepts komoot.de URL", () => {
|
||||
expect(parseKomootUserId("https://www.komoot.de/user/12345")).toBe("12345");
|
||||
});
|
||||
|
||||
it("returns null for an invalid input", () => {
|
||||
expect(parseKomootUserId("not-a-user")).toBeNull();
|
||||
expect(parseKomootUserId("https://example.com/user/abc")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetchPublicProfile", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("fetch", vi.fn());
|
||||
});
|
||||
|
||||
it("maps response fields correctly", async () => {
|
||||
vi.mocked(fetch).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
username: "27595800585",
|
||||
display_name: "Test User",
|
||||
content: { text: "Visit https://trails.cool/users/ullrich for my routes", link: null },
|
||||
}),
|
||||
} as Response);
|
||||
|
||||
const profile = await fetchPublicProfile("27595800585");
|
||||
expect(profile.displayName).toBe("Test User");
|
||||
expect(profile.contentText).toBe("Visit https://trails.cool/users/ullrich for my routes");
|
||||
expect(profile.contentLink).toBeNull();
|
||||
});
|
||||
|
||||
it("falls back to username when display_name missing", async () => {
|
||||
vi.mocked(fetch).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ username: "99999", content: {} }),
|
||||
} as Response);
|
||||
|
||||
const profile = await fetchPublicProfile("99999");
|
||||
expect(profile.displayName).toBe("99999");
|
||||
});
|
||||
|
||||
it("throws on non-ok response", async () => {
|
||||
vi.mocked(fetch).mockResolvedValueOnce({ ok: false, status: 404 } as Response);
|
||||
await expect(fetchPublicProfile("bad")).rejects.toThrow("404");
|
||||
});
|
||||
});
|
||||
|
||||
describe("verifyKomootOwnership", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("fetch", vi.fn());
|
||||
});
|
||||
|
||||
it("returns true when bio contains the trails URL (exact match)", async () => {
|
||||
vi.mocked(fetch).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
username: "123",
|
||||
content: { text: "https://trails.cool/users/ullrich" },
|
||||
}),
|
||||
} as Response);
|
||||
expect(await verifyKomootOwnership("123", "https://trails.cool/users/ullrich")).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for case-insensitive match", async () => {
|
||||
vi.mocked(fetch).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
username: "123",
|
||||
content: { text: "HTTPS://TRAILS.COOL/USERS/ULLRICH" },
|
||||
}),
|
||||
} as Response);
|
||||
expect(await verifyKomootOwnership("123", "https://trails.cool/users/ullrich")).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when bio does not contain the trails URL", async () => {
|
||||
vi.mocked(fetch).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
username: "123",
|
||||
content: { text: "Just a normal bio with no trails link" },
|
||||
}),
|
||||
} as Response);
|
||||
expect(await verifyKomootOwnership("123", "https://trails.cool/users/ullrich")).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false when content_text is null", async () => {
|
||||
vi.mocked(fetch).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ username: "123", content: { text: null } }),
|
||||
} as Response);
|
||||
expect(await verifyKomootOwnership("123", "https://trails.cool/users/ullrich")).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false when fetch fails", async () => {
|
||||
vi.mocked(fetch).mockResolvedValueOnce({ ok: false, status: 404 } as Response);
|
||||
expect(await verifyKomootOwnership("bad", "https://trails.cool/users/x")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetchKomootTours", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("fetch", vi.fn());
|
||||
});
|
||||
|
||||
it("appends status=public when no auth token", async () => {
|
||||
vi.mocked(fetch).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
_embedded: { tours: [] },
|
||||
page: { totalPages: 1, number: 0 },
|
||||
}),
|
||||
} as Response);
|
||||
await fetchKomootTours("123", 1);
|
||||
const [url] = vi.mocked(fetch).mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toContain("status=public");
|
||||
});
|
||||
|
||||
it("omits status=public when auth token provided", async () => {
|
||||
vi.mocked(fetch).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
_embedded: { tours: [] },
|
||||
page: { totalPages: 1, number: 0 },
|
||||
}),
|
||||
} as Response);
|
||||
await fetchKomootTours("123", 1, "sometoken");
|
||||
const [url] = vi.mocked(fetch).mock.calls[0] as [string, RequestInit];
|
||||
expect(url).not.toContain("status=public");
|
||||
});
|
||||
|
||||
it("maps tour fields correctly", async () => {
|
||||
vi.mocked(fetch).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
_embedded: {
|
||||
tours: [
|
||||
{
|
||||
id: 987654321,
|
||||
name: "Morning ride",
|
||||
type: "touringbicycle",
|
||||
date: "2024-06-01T08:00:00Z",
|
||||
distance: 42000,
|
||||
duration: 7200,
|
||||
elevation_up: 300,
|
||||
elevation_down: 290,
|
||||
},
|
||||
],
|
||||
},
|
||||
page: { totalPages: 3, number: 0 },
|
||||
}),
|
||||
} as Response);
|
||||
const result = await fetchKomootTours("123", 1);
|
||||
expect(result.tours).toHaveLength(1);
|
||||
expect(result.tours[0]).toMatchObject({
|
||||
id: "987654321",
|
||||
name: "Morning ride",
|
||||
sport: "touringbicycle",
|
||||
distance: 42000,
|
||||
duration: 7200,
|
||||
});
|
||||
expect(result.totalPages).toBe(3);
|
||||
});
|
||||
});
|
||||
188
apps/journal/app/lib/komoot.server.ts
Normal file
188
apps/journal/app/lib/komoot.server.ts
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
// Komoot API client. Covers unauthenticated public profile access and
|
||||
// authenticated tour listing / GPX export.
|
||||
//
|
||||
// All network calls use plain fetch; no auth state is cached here.
|
||||
|
||||
const API_BASE = "https://api.komoot.de/v007";
|
||||
const AUTH_BASE = "https://api.komoot.de/v006";
|
||||
|
||||
export interface KomootTour {
|
||||
id: string;
|
||||
name: string;
|
||||
sport: string;
|
||||
date: string;
|
||||
distance: number;
|
||||
duration: number;
|
||||
elevationUp: number;
|
||||
elevationDown: number;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// URL parsing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Accepts a plain numeric ID or a Komoot profile URL in any locale variant.
|
||||
// Returns the numeric user ID string, or null if it cannot be parsed.
|
||||
export function parseKomootUserId(input: string): string | null {
|
||||
const trimmed = input.trim();
|
||||
// Plain numeric ID
|
||||
if (/^\d+$/.test(trimmed)) return trimmed;
|
||||
// URL forms: https://www.komoot.com/user/12345 or .../de-de/user/12345
|
||||
const match = trimmed.match(/komoot\.(?:com|de)\/(?:[a-z]{2}-[a-z]{2}\/)?user\/(\d+)/i);
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public profile
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface KomootPublicProfileResponse {
|
||||
username: string;
|
||||
display_name?: string;
|
||||
content?: {
|
||||
text?: string | null;
|
||||
link?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchPublicProfile(komootUserId: string): Promise<{
|
||||
displayName: string;
|
||||
contentText: string | null;
|
||||
contentLink: string | null;
|
||||
}> {
|
||||
const resp = await fetch(`${API_BASE}/users/${komootUserId}/`);
|
||||
if (!resp.ok) {
|
||||
throw new Error(`Komoot profile fetch failed: ${resp.status}`);
|
||||
}
|
||||
const data = (await resp.json()) as KomootPublicProfileResponse;
|
||||
return {
|
||||
displayName: data.display_name ?? data.username,
|
||||
contentText: data.content?.text ?? null,
|
||||
contentLink: data.content?.link ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
// Returns true if the profile's content text contains the trails profile URL
|
||||
// (case-insensitive, trimmed).
|
||||
export async function verifyKomootOwnership(
|
||||
komootUserId: string,
|
||||
trailsProfileUrl: string,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const profile = await fetchPublicProfile(komootUserId);
|
||||
if (!profile.contentText) return false;
|
||||
return profile.contentText.toLowerCase().includes(trailsProfileUrl.toLowerCase().trim());
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Authentication
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface KomootAuthResponse {
|
||||
username: string;
|
||||
// The API returns user data nested under the email key in v006
|
||||
email?: string;
|
||||
}
|
||||
|
||||
// Login with email+password via Basic auth. Returns the Komoot username
|
||||
// (numeric user ID) and the base64-encoded Basic auth token.
|
||||
export async function loginKomoot(
|
||||
email: string,
|
||||
password: string,
|
||||
): Promise<{ username: string; basicAuthToken: string }> {
|
||||
const basicAuthToken = Buffer.from(`${email}:${password}`).toString("base64");
|
||||
const resp = await fetch(`${AUTH_BASE}/account/email/${encodeURIComponent(email)}/`, {
|
||||
headers: { Authorization: `Basic ${basicAuthToken}` },
|
||||
});
|
||||
if (!resp.ok) {
|
||||
throw new Error(`Komoot login failed: ${resp.status}`);
|
||||
}
|
||||
const data = (await resp.json()) as KomootAuthResponse;
|
||||
return { username: data.username, basicAuthToken };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tours
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface KomootTourRaw {
|
||||
id: number;
|
||||
name: string;
|
||||
type: string;
|
||||
date: string;
|
||||
distance?: number;
|
||||
duration?: number;
|
||||
elevation_up?: number;
|
||||
elevation_down?: number;
|
||||
}
|
||||
|
||||
interface KomootToursResponse {
|
||||
_embedded?: {
|
||||
tours?: KomootTourRaw[];
|
||||
};
|
||||
page?: {
|
||||
totalPages?: number;
|
||||
number?: number;
|
||||
};
|
||||
}
|
||||
|
||||
function toTour(raw: KomootTourRaw): KomootTour {
|
||||
return {
|
||||
id: String(raw.id),
|
||||
name: raw.name || `Tour ${raw.id}`,
|
||||
sport: raw.type,
|
||||
date: raw.date,
|
||||
distance: raw.distance ?? 0,
|
||||
duration: raw.duration ?? 0,
|
||||
elevationUp: raw.elevation_up ?? 0,
|
||||
elevationDown: raw.elevation_down ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchKomootTours(
|
||||
komootUserId: string,
|
||||
page: number,
|
||||
basicAuthToken?: string,
|
||||
): Promise<{ tours: KomootTour[]; totalPages: number }> {
|
||||
const params = new URLSearchParams({
|
||||
page: String(page - 1), // Komoot uses 0-based pages
|
||||
limit: "50",
|
||||
});
|
||||
if (!basicAuthToken) {
|
||||
params.set("status", "public");
|
||||
}
|
||||
const headers: Record<string, string> = {};
|
||||
if (basicAuthToken) {
|
||||
headers["Authorization"] = `Basic ${basicAuthToken}`;
|
||||
}
|
||||
const resp = await fetch(`${API_BASE}/users/${komootUserId}/tours/?${params}`, { headers });
|
||||
if (!resp.ok) {
|
||||
throw new Error(`Komoot tours fetch failed: ${resp.status}`);
|
||||
}
|
||||
const data = (await resp.json()) as KomootToursResponse;
|
||||
const tours = (data._embedded?.tours ?? []).map(toTour);
|
||||
const totalPages = data.page?.totalPages ?? 1;
|
||||
return { tours, totalPages };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GPX export
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function fetchKomootTourGpx(
|
||||
tourId: string,
|
||||
basicAuthToken?: string,
|
||||
): Promise<string> {
|
||||
const headers: Record<string, string> = {};
|
||||
if (basicAuthToken) {
|
||||
headers["Authorization"] = `Basic ${basicAuthToken}`;
|
||||
}
|
||||
const resp = await fetch(`${API_BASE}/tours/${tourId}.gpx`, { headers });
|
||||
if (!resp.ok) {
|
||||
throw new Error(`Komoot GPX fetch failed: ${resp.status}`);
|
||||
}
|
||||
return resp.text();
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue