trails/apps/journal/app/routes/settings.connections.tsx
Ullrich Schäfer 0360757ae8 feat(journal): Garmin activity import — provider, webhook pipeline, backfill (§1–5)
Garmin Connect as the third connected-services provider (spec:
garmin-import). The interesting parts:

- Push-first ingestion: Garmin has no list endpoint. The webhook
  normalizes ping (callbackURL) and push (inline) notification batches
  into events; the slow work (authorized FIT download, FIT→GPX via the
  shared converter, activity creation) runs in a garmin-import-activity
  pg-boss job so the webhook answers fast. Callback URLs are validated
  against Garmin's API host before any fetch (SSRF guard).
- History via backfill requests: /sync/import/garmin is a date-range
  requester with honest async progress (no pick list — the concept
  doesn't exist in a push model). Ranges chunk to Garmin's 90-day cap;
  overlaps are free via sync_imports dedupe. Requests persist in
  import_batches via two new nullable columns (range_start/range_end).
- OAuth2 + PKCE on the existing oauth credential kind. Design
  correction from apply: the verifier rides a short-lived httpOnly
  cookie scoped to the callback path — the state param is visible in
  redirect URLs and must never carry it. Manifests opt in via pkce:true.
- Deregistration notifications flip the connection to 'revoked'
  (row kept for audit, imports retained, re-connect prompt shown).
- Framework evolutions, all additive: parseWebhook returns
  WebhookEvent[] (Garmin batches; Wahoo adapted), manifest gains
  configured()/importUrl/pkce, importActivity accepts summary stats
  for FIT-less imports, manager gains markRevoked.
- Env-gated: no GARMIN_CLIENT_ID → provider hidden on
  /settings/connections. Privacy manifest entry (DE+EN). i18n en+de.

Rollout (§6) stays gated on the Garmin Developer Program application
(submitted 2026-06-07). Fixtures are doc-shaped; the staging soak
swaps in recorded payloads if shapes differ.

Gate: typecheck ✓ lint ✓ unit+integration ✓ e2e 70/72 + both known
flakes green isolated ✓ openspec validate ✓

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 17:47:22 +02:00

82 lines
3 KiB
TypeScript

import { data, useSearchParams } from "react-router";
import { useTranslation } from "react-i18next";
import type { Route } from "./+types/settings.connections";
import { loadConnectionsSettings } from "./settings.connections.server";
const KNOWN_ERRORS = ["too_many_tokens", "sync_failed", "generic"] as const;
type KnownError = (typeof KNOWN_ERRORS)[number];
function isKnownError(value: string | null): value is KnownError {
return value !== null && (KNOWN_ERRORS as readonly string[]).includes(value);
}
export function meta() {
return [{ title: "Connected services — Settings — trails.cool" }];
}
export async function loader({ request }: Route.LoaderArgs) {
return data(await loadConnectionsSettings(request));
}
export default function ConnectionsSettings({ loaderData }: Route.ComponentProps) {
const { providers } = loaderData;
const { t } = useTranslation(["journal"]);
const [searchParams] = useSearchParams();
const errorParam = searchParams.get("error");
const errorKey: KnownError | null = isKnownError(errorParam) ? errorParam : errorParam ? "generic" : null;
return (
<section>
<h2 className="text-lg font-semibold text-gray-900">{t("settings.services.title")}</h2>
{errorKey && (
<div
role="alert"
className="mt-4 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800"
>
{t(`settings.services.errors.${errorKey}`)}
</div>
)}
<div className="mt-4 space-y-3">
{providers.map((p) => (
<div
key={p.id}
className="flex items-center justify-between rounded-md border border-gray-200 px-4 py-3"
>
<div>
<p className="font-medium text-gray-900">{p.name}</p>
{p.connected && p.providerUserId && (
<p className="text-xs text-gray-500">
{t("settings.services.connectedAs", { id: p.providerUserId })}
</p>
)}
</div>
{p.connected ? (
<div className="flex items-center gap-3">
<a
href={p.importUrl ?? `/sync/import/${p.id}`}
className="text-sm text-blue-600 hover:underline"
>
{t("sync.import")}
</a>
<form method="post" action={`/api/sync/disconnect/${p.id}`}>
<button
type="submit"
className="text-sm text-red-600 hover:underline"
>
{t("settings.services.disconnect")}
</button>
</form>
</div>
) : (
<a
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")}
</a>
)}
</div>
))}
</div>
</section>
);
}