Addresses 8 issues from the Journal architecture audit: 1. DB indexes on routes.ownerId + activities.ownerId. Listing queries on these tables were full table scans; adds composite indexes matching the order-by columns (updatedAt/startedAt/createdAt). 2. Zod validation on /api/auth/register body. Previously the action destructured request.json() with zero schema validation. 3. N+1 GeoJSON batch fetch collapsed to a single ANY($1::text[]) query in both routes.server and activities.server. 4. Webhook envelope validation in /api/sync/webhook/:provider. 5. AbortSignal.timeout(30s) on all external fetches (Komoot, Wahoo) via a new fetchWithTimeout helper in lib/http.server.ts. 6. .limit(100) on listPublicRoutesForOwner / listPublicActivitiesForOwner. 9. Welcome email moved off fire-and-forget onto a pg-boss job with retryLimit: 3 (send-welcome-email). 10. process.env.ORIGIN ?? "http://localhost:3000" centralized into lib/config.server.ts::getOrigin() across 14 call sites. Issues 7 (centralized apiError/auth guards across 60+ route files) and 8 (split .server.ts boundaries across 20+ route files) intentionally deferred — both are pure refactors that would balloon this PR past reviewability and warrant their own focused PRs. Tests added: - lib/config.server.test.ts (2 cases) - lib/http.server.test.ts (3 cases — timeout abort, success passthrough, caller-signal composition) - routes/api.sync.webhook.$provider.test.ts (6 cases) - routes/api.auth.register.test.ts (7 cases — schema rejection paths + the new welcome-email enqueue assertion) Full repo: pnpm typecheck, pnpm lint, pnpm test all green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
69 lines
2.6 KiB
TypeScript
69 lines
2.6 KiB
TypeScript
// Wahoo WebhookReceiver capability adapter.
|
|
//
|
|
// Wahoo posts `workout_summary` events to /api/sync/webhook/wahoo when a
|
|
// workout completes. We route the event to the right local user via
|
|
// provider_user_id, deduplicate via sync_imports, then download + convert
|
|
// the FIT file (if present) and create an activity.
|
|
|
|
import { fitToGpx } from "../../fit.ts";
|
|
import { fetchWithTimeout } from "../../../http.server.ts";
|
|
import { isAlreadyImported, importActivity } from "../../../sync/imports.server.ts";
|
|
import { getServiceByProviderUser, withFreshCredentials } from "../../manager.ts";
|
|
import type { OAuthCredentials } from "../../types.ts";
|
|
import type { WebhookEvent, WebhookReceiver } from "../../registry.ts";
|
|
|
|
interface WahooWebhookBody {
|
|
event_type?: string;
|
|
user?: { id?: number };
|
|
workout_summary?: {
|
|
id?: number;
|
|
workout?: { id?: number };
|
|
file?: { url?: string };
|
|
};
|
|
}
|
|
|
|
|
|
export const wahooWebhook: WebhookReceiver = {
|
|
parseWebhook(body: unknown): WebhookEvent | null {
|
|
const payload = body as WahooWebhookBody;
|
|
if (payload.event_type !== "workout_summary" || !payload.user?.id) return null;
|
|
|
|
return {
|
|
eventType: payload.event_type,
|
|
providerUserId: String(payload.user.id),
|
|
workoutId: String(
|
|
payload.workout_summary?.workout?.id ?? payload.workout_summary?.id ?? "",
|
|
),
|
|
fileUrl: payload.workout_summary?.file?.url,
|
|
};
|
|
},
|
|
|
|
async handle(event: WebhookEvent): Promise<void> {
|
|
// Match incoming webhooks to local users via provider_user_id.
|
|
// Unknown users return silently — no leak.
|
|
const service = await getServiceByProviderUser("wahoo", event.providerUserId);
|
|
if (!service) return;
|
|
|
|
if (await isAlreadyImported(service.userId, "wahoo", event.workoutId)) return;
|
|
|
|
let gpx: string | null = null;
|
|
if (event.fileUrl) {
|
|
// Wahoo CDN URLs are pre-signed; no auth header needed. We still go
|
|
// through withFreshCredentials so the manager has a chance to refresh
|
|
// a near-expired credential before any subsequent Wahoo call this
|
|
// handler might make.
|
|
const buffer = await withFreshCredentials(service.id, async (_creds) => {
|
|
void (_creds as unknown as OAuthCredentials);
|
|
const resp = await fetchWithTimeout(event.fileUrl!);
|
|
if (!resp.ok) throw new Error(`Wahoo file download failed: ${resp.status}`);
|
|
return Buffer.from(await resp.arrayBuffer());
|
|
});
|
|
gpx = await fitToGpx(buffer, "Wahoo workout");
|
|
}
|
|
|
|
await importActivity(service.userId, "wahoo", event.workoutId, {
|
|
name: "Wahoo workout",
|
|
gpx: gpx ?? undefined,
|
|
});
|
|
},
|
|
};
|