Implements tasks 1.3, 3.2-3.3, 4.1-4.4, 5.1-5.6, 6.1 of
deepen-connected-services. Built TDD: contract test red, adapter green
for each capability seam.
Capability adapters (providers/wahoo/):
- importer.ts: Importer seam — listImportable + importOne against
Wahoo /v1/workouts. Filters fitness_app_id >= 1000 (Wahoo doesn't
share third-party data). 2 contract tests green.
- pusher.ts: RoutePusher seam — pushRoute(ctx, input) -> {remoteId,
version}. FIT-Course conversion, route:<id> external_id, PUT-vs-POST
decision, PUT->POST-on-404 fallback all internal to the adapter
(per ADR-0003). Idempotency via sync_pushes preserved. 4 contract
tests green.
- webhook.ts: WebhookReceiver seam — parseWebhook + handle. Routes
events to local users via provider_user_id; unknown user returns
silently. 6 contract tests green.
- manifest.ts: declares credential_kind=oauth, OAuth config, scopes,
buildAuthUrl, exchangeCode, and references each capability adapter.
Module shape:
- connected-services/index.ts: side-effect imports providers/index.ts
to register manifests, then re-exports manager + registry + types.
- connected-services/providers/index.ts: barrel that calls
registerManifest(wahooManifest).
- connected-services/oauth-state.server.ts: OAuth state encode/decode
(extracted from legacy pushes.server.ts).
- connected-services/push-action.server.ts: orchestration above the
RoutePusher seam — load route, ownership check, scope check, build
RoutePushInput, invoke pusher, return PushOutcome union. Replaces
the legacy pushRouteToProvider in lib/sync/pushes.server.ts.
Caller migration (group 5):
- api.sync.connect.$provider.ts -> manifest.buildAuthUrl
- api.sync.callback.$provider.ts -> manifest.exchangeCode + link()
- api.sync.disconnect.$provider.ts -> unlinkByUserProvider (calls
best-effort revoke via the credential adapter, then deletes locally)
- api.sync.webhook.$provider.ts -> manifest.webhookReceiver dispatch
- api.sync.push.$provider.$routeId.ts -> push-action.pushRouteToProvider
- sync.import.$provider.tsx -> manifest.importer.listImportable +
inline FIT->GPX in the action (form-supplied metadata bypasses the
Importer seam which is reserved for automatic / webhook imports)
- routes.$id.tsx -> getService instead of getConnection
- settings.connections.tsx -> getAllManifests instead of legacy registry
Legacy lib/sync/ deleted except imports.server.ts (which manages the
sync_imports table, untouched by this change).
DB migration verified locally (task 1.3): pnpm db:migrate-data renamed
the table and backfilled credentials JSONB; pnpm db:push then dropped
the legacy access_token/refresh_token/expires_at columns. Final shape
matches the schema; check constraints + unique index in place.
Test status (task 6.1):
- pnpm typecheck: green across all 15 workspaces
- pnpm lint: green
- @trails-cool/journal: 112 passed, 31 skipped — 12 fewer tests than
before because pushes.server.test.ts and the legacy wahoo.test.ts
were deleted. Their coverage is replaced by the new contract tests
(importer/pusher/webhook) plus manager.test.ts + oauth.test.ts.
Remaining: 6.2 (e2e), 6.3-6.4 (manual smoke + staging migration test),
7.1-7.3 (followups + spec deltas at archive).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
130 lines
3.8 KiB
TypeScript
130 lines
3.8 KiB
TypeScript
// Wahoo provider manifest. Declares credential kind, OAuth config,
|
|
// authorization/exchange flows, and capability adapters.
|
|
//
|
|
// Adding to the registry happens via providers/index.ts which imports each
|
|
// provider's barrel. Don't `import`-cycle this file from registry.ts.
|
|
|
|
import { oauthCredentialAdapter } from "../../credential-adapters/oauth.ts";
|
|
import type {
|
|
ProviderManifest,
|
|
CapabilityContext,
|
|
} from "../../registry.ts";
|
|
import type { OAuthCredentials, ProviderOAuthConfig } from "../../types.ts";
|
|
import { wahooImporter } from "./importer.ts";
|
|
import { wahooPusher } from "./pusher.ts";
|
|
import { wahooWebhook } from "./webhook.ts";
|
|
|
|
const WAHOO_API = "https://api.wahooligan.com";
|
|
const WAHOO_AUTH = "https://api.wahooligan.com/oauth";
|
|
|
|
const SCOPES = [
|
|
"workouts_read",
|
|
"user_read",
|
|
"offline_data",
|
|
"routes_read",
|
|
"routes_write",
|
|
];
|
|
|
|
function clientId(): string {
|
|
return process.env.WAHOO_CLIENT_ID ?? "";
|
|
}
|
|
function clientSecret(): string {
|
|
return process.env.WAHOO_CLIENT_SECRET ?? "";
|
|
}
|
|
|
|
const oauthConfig: ProviderOAuthConfig = {
|
|
get tokenUrl() {
|
|
return `${WAHOO_AUTH}/token`;
|
|
},
|
|
get clientId() {
|
|
return clientId();
|
|
},
|
|
get clientSecret() {
|
|
return clientSecret();
|
|
},
|
|
get revokeUrl() {
|
|
return `${WAHOO_API}/v1/permissions`;
|
|
},
|
|
};
|
|
|
|
export const wahooManifest: ProviderManifest = {
|
|
id: "wahoo",
|
|
displayName: "Wahoo",
|
|
credentialKind: "oauth",
|
|
credentialAdapter: oauthCredentialAdapter as ProviderManifest["credentialAdapter"],
|
|
oauthConfig,
|
|
scopes: SCOPES,
|
|
|
|
buildAuthUrl(redirectUri: string, state: string): string {
|
|
const params = new URLSearchParams({
|
|
client_id: clientId(),
|
|
redirect_uri: redirectUri,
|
|
response_type: "code",
|
|
scope: SCOPES.join(" "),
|
|
state,
|
|
});
|
|
return `${WAHOO_AUTH}/authorize?${params}`;
|
|
},
|
|
|
|
async exchangeCode(
|
|
code: string,
|
|
redirectUri: string,
|
|
): Promise<{
|
|
credentials: OAuthCredentials;
|
|
providerUserId: string | null;
|
|
grantedScopes: string[];
|
|
}> {
|
|
const resp = await fetch(`${WAHOO_AUTH}/token`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
body: new URLSearchParams({
|
|
client_id: clientId(),
|
|
client_secret: clientSecret(),
|
|
code,
|
|
grant_type: "authorization_code",
|
|
redirect_uri: redirectUri,
|
|
}).toString(),
|
|
});
|
|
if (!resp.ok) {
|
|
const text = await resp.text().catch(() => "");
|
|
const err = new Error(`Wahoo token exchange failed: ${resp.status} ${text}`);
|
|
// Attach a code so callers can distinguish the "too many tokens" sandbox case.
|
|
(err as Error & { code?: string }).code = text.includes("Too many unrevoked access tokens")
|
|
? "too_many_tokens"
|
|
: "generic";
|
|
throw err;
|
|
}
|
|
const data = (await resp.json()) as {
|
|
access_token: string;
|
|
refresh_token: string;
|
|
expires_in: number;
|
|
};
|
|
|
|
// Pull provider user id so webhook routing works.
|
|
const userResp = await fetch(`${WAHOO_API}/v1/user`, {
|
|
headers: { Authorization: `Bearer ${data.access_token}` },
|
|
});
|
|
const user = userResp.ok
|
|
? ((await userResp.json()) as { id: number })
|
|
: null;
|
|
|
|
return {
|
|
credentials: {
|
|
access_token: data.access_token,
|
|
refresh_token: data.refresh_token,
|
|
expires_at: new Date(Date.now() + data.expires_in * 1000).toISOString(),
|
|
},
|
|
providerUserId: user?.id != null ? String(user.id) : null,
|
|
// Wahoo does not return a `scope` field and grants scopes
|
|
// all-or-nothing, so the requested set is the granted set.
|
|
grantedScopes: SCOPES,
|
|
};
|
|
},
|
|
|
|
importer: wahooImporter,
|
|
routePusher: wahooPusher,
|
|
webhookReceiver: wahooWebhook,
|
|
};
|
|
|
|
// Re-export the capability adapters for direct testing access if needed.
|
|
export type { CapabilityContext };
|