Schema rename + ConnectedServiceManager foundation (groups 1-2)

Implements tasks 1.1-1.4 and 2.1-2.5 of deepen-connected-services:

DB:
- Rename journal.sync_connections -> journal.connected_services.
- Add credential_kind discriminator (oauth | web-login | device) and
  credentials JSONB (shape per kind), status column, and a unique index
  on (user_id, provider) lifting the previously app-only invariant
  into the DB.
- Idempotent backfill in 0002_connected_services.sql moves existing
  Wahoo rows' tokens into the JSONB blob with credential_kind='oauth'.

Code:
- New apps/journal/app/lib/connected-services/ module:
  - types.ts: ConnectedService, CredentialKind, OAuthCredentials,
    NeedsRelinkError, CredentialAdapter, ProviderOAuthConfig, etc.
  - credential-adapters/oauth.ts: standard OAuth2 refresh_token flow,
    revoke endpoint, 4xx -> NeedsRelinkError / 5xx -> transient.
  - manager.ts: ConnectedServiceManager (link, unlink, withFreshCredentials,
    markNeedsRelink). Centralizes credential lifecycle in one chokepoint.
  - registry.ts: ProviderManifest type + capability seam interfaces
    (Importer, RoutePusher, WebhookReceiver). Manifests register
    themselves at import time.

Tests:
- manager.test.ts (8 tests): refresh-on-expired, refresh-fail->needs_relink,
  ConnectionNotActiveError, link/unlink, revoke is best-effort.
- credential-adapters/oauth.test.ts (10 tests): refresh contract,
  refresh_token retention, 4xx vs 5xx behaviour, revoke.
- All 18 new tests pass.

Compatibility:
- apps/journal/app/lib/sync/connections.server.ts is now a thin shim
  translating the legacy TokenSet API onto the JSONB-shaped table so
  existing callers (routes, pushes.server.ts) keep working until tasks
  5.x migrate them to the manager. To be deleted in task 5.6.

Pre-existing journal test failures (12) are unrelated to this change:
they pre-date this PR and stem from a workspace resolution issue with
@trails-cool/fit (verified by running tests against main).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ullrich Schäfer 2026-05-08 00:24:52 +02:00
parent cfba3146e2
commit 6de516718d
No known key found for this signature in database
GPG key ID: A32FF691A0F752D9
11 changed files with 1155 additions and 70 deletions

View file

@ -186,27 +186,42 @@ export const oauthTokens = journalSchema.table("oauth_tokens", {
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
export const syncConnections = journalSchema.table("sync_connections", {
id: text("id").primaryKey(),
userId: text("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
provider: text("provider").notNull(),
accessToken: text("access_token").notNull(),
refreshToken: text("refresh_token").notNull(),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
providerUserId: text("provider_user_id"),
// Scopes the user actually granted at OAuth time. Wahoo doesn't return a
// scope field in token responses and grants scopes all-or-nothing, so we
// record the requested scope set on exchangeCode. Used to detect when an
// existing connection predates a scope upgrade (e.g. routes_write) and
// needs a re-auth before a new push call can succeed.
grantedScopes: text("granted_scopes")
.array()
.notNull()
.default(sql`ARRAY[]::text[]`),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
// External-service connections (OAuth, web-login, mobile-paired devices).
// `credential_kind` discriminates the shape of `credentials` JSONB:
// - 'oauth': { access_token, refresh_token, expires_at }
// - 'web-login': { email, encrypted_password, session_jar } (Komoot, future)
// - 'device': {} (Apple Health, future)
// See docs/adr/0001 and CONTEXT.md (Connected Services).
export const connectedServices = journalSchema.table(
"connected_services",
{
id: text("id").primaryKey(),
userId: text("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
provider: text("provider").notNull(),
credentialKind: text("credential_kind").notNull(),
credentials: jsonb("credentials").notNull(),
// 'active' | 'needs_relink' | 'revoked'. Manager flips to 'needs_relink'
// when CredentialAdapter.refresh returns a permanent failure.
status: text("status").notNull().default("active"),
providerUserId: text("provider_user_id"),
// OAuth-only. Promoted out of the credentials JSONB because feature gates
// (e.g. routes_write check on push) read this on every call.
grantedScopes: text("granted_scopes")
.array()
.notNull()
.default(sql`ARRAY[]::text[]`),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => ({
userProviderUnique: uniqueIndex("connected_services_user_provider_unique").on(
t.userId,
t.provider,
),
}),
);
export const syncImports = journalSchema.table("sync_imports", {
id: text("id").primaryKey(),