Skip to content

refactor: replace tRPC apiKeys router with Better Auth + Electric - #954

Merged
saddlepaddle merged 3 commits into
mainfrom
mcp-oauth-cleanup
Jan 26, 2026
Merged

saddlepaddle merged 3 commits into
mainfrom
mcp-oauth-cleanup

Conversation

@saddlepaddle

@saddlepaddle saddlepaddle commented Jan 26, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Replace the tRPC apiKeysRouter with direct Better Auth client methods + Electric sync
  • Remove duplicate myOrganizations endpoint from organization router

Changes

API Keys

  • Add apiKeyClient() plugin to both web and desktop auth clients
  • Add auth.apikeys table to Electric sync proxy (filtered by userId)
  • Update ApiKeysSettings component to:
    • Use Electric collection for listing (with client-side org filtering)
    • Use authClient.apiKey.create() for creating keys
    • Use authClient.apiKey.delete() for revoking keys
  • Delete packages/trpc/src/router/agent/api-keys.ts

Duplicate Cleanup

  • Remove myOrganizations from organizationRouter (was duplicate of userRouter.myOrganizations)
  • Update OAuth consent page to use user.myOrganizations

Test plan

  • Create API key from desktop settings
  • Verify key appears in list (Electric sync)
  • Verify key works for MCP authentication
  • Revoke key and verify it's removed
  • OAuth consent page still shows organizations correctly

Summary by CodeRabbit

  • New Features

    • API key authentication added to desktop and client auth flows.
    • Consent page now derives organizations from the current user for selection.
  • Refactor

    • API Keys settings revamped: local collection-backed listing, Generate API Key flow with dialogs, revoke confirmation and success toasts, default naming for unnamed keys, and "No API keys yet" messaging.
    • API Keys table now shows last request time.

✏️ Tip: You can customize this high-level summary in your review settings.

- Add apiKeyClient() plugin to auth clients (web + desktop)
- Add auth.apikeys table to Electric sync (filtered by userId)
- Update ApiKeysSettings to use Electric collection + authClient.apiKey
- Remove tRPC apiKeysRouter (no longer needed)
- Remove duplicate myOrganizations from organization router
- Update consent page to use user.myOrganizations
@coderabbitai

coderabbitai Bot commented Jan 26, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@saddlepaddle has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 2 minutes and 40 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📝 Walkthrough

Walkthrough

This PR migrates API key management from TRPC endpoints to Better Auth's apiKey plugin, adds support for the auth.apikeys table across the Electric data layer and collections, updates desktop and shared auth clients to include the plugin, moves the desktop UI to local Electric collections with authClient operations, and removes the legacy TRPC apiKeys router and an organization endpoint.

Changes

Cohort / File(s) Summary
Electric Data Access Layer
apps/api/src/app/api/electric/[...path]/utils.ts, apps/api/src/app/api/electric/[...path]/route.ts
Added "auth.apikeys" to AllowedTable, extended buildWhereClause to filter auth.apikeys by userId, and set specific columns for auth.apikeys in the Electric proxy route.
Auth Client Configuration
apps/desktop/src/renderer/lib/auth-client.ts, packages/auth/src/client.ts
Imported and registered apiKeyClient() in desktop and shared auth client plugin arrays.
Local Collections
apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/collections.ts
Added apiKeysCollection (shape SelectApikey) configured for auth.apikeys and exposed apiKeys in getCollections.
Desktop API Keys UI
apps/desktop/src/renderer/routes/_authenticated/settings/api-keys/components/ApiKeysSettings/ApiKeysSettings.tsx
Replaced TRPC calls with authClient operations and useLiveQuery on local apiKeysCollection; added generate/revoke flows using authClient, toast/alert UX, and adjusted table fields (e.g., lastRequest).
TRPC Router & Organization Router
packages/trpc/src/router/agent/api-keys.ts, packages/trpc/src/router/agent/index.ts, packages/trpc/src/root.ts, packages/trpc/src/router/organization/organization.ts
Removed the agent apiKeys router and its export from root, and removed myOrganizations endpoint from organizationRouter.
Web OAuth Consent
apps/web/src/app/oauth/consent/page.tsx
Switched TRPC query from organization.myOrganizations to user.myOrganizations and updated mapping of organization fields.

Sequence Diagram(s)

sequenceDiagram
    participant UI as API Keys UI
    participant Col as Electric Collections
    participant AC as Auth Client
    participant BA as Better Auth

    rect rgba(100, 150, 200, 0.5)
    note over UI,AC: Generate API Key Flow
    UI->>AC: authClient.apiKey.create(name, metadata)
    AC->>BA: apiKeyClient plugin -> create key
    BA-->>AC: returns key material + metadata
    AC-->>UI: delivers generated key
    Col->>Col: Electric syncs new auth.apikeys row
    end

    rect rgba(150, 100, 200, 0.5)
    note over UI,Col: Fetch & Display Keys Flow
    UI->>Col: useLiveQuery(apiKeysCollection)
    Col->>Col: local query filtered by orgId/userId
    Col-->>UI: returns array of apiKeys
    UI->>UI: render keys table
    end

    rect rgba(100, 200, 150, 0.5)
    note over UI,AC: Revoke API Key Flow
    UI->>AC: authClient.apiKey.delete(keyId)
    AC->>BA: apiKeyClient revoke operation
    BA-->>AC: success confirmation
    AC-->>UI: revocation success
    Col->>Col: Electric sync removes auth.apikeys row
    end
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly Related PRs

Poem

🐰✨ I hopped from TRPC to Better Auth's light,
Keys tucked in collections, gleaming bright,
I nibble old routers, plant plugin seeds,
Syncing rows and toasts for devs' good deeds,
A tiny rabbit cheers — keys safe tonight!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: replacing tRPC's apiKeys router with Better Auth and Electric, which is the core objective of this refactoring PR.
Description check ✅ Passed The PR description provides a clear summary of changes, related modifications, and a test plan, though it doesn't fully follow the template structure with all sections populated.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/desktop/src/renderer/routes/_authenticated/settings/api-keys/components/ApiKeysSettings/ApiKeysSettings.tsx (1)

93-116: Generate button not disabled when no active organization.

The handler on line 94 guards against missing activeOrganizationId, but the button's disabled prop on line 286 doesn't include this check. Users can click the button and nothing happens, with no feedback.

Suggested fix
 <Button
 	onClick={handleGenerateKey}
-	disabled={!newKeyName.trim() || isGenerating}
+	disabled={!newKeyName.trim() || isGenerating || !activeOrganizationId}
 >
 	{isGenerating ? "Generating..." : "Generate Key"}
 </Button>

Additionally, consider handling the case where result.data?.key is falsy (lines 105-110) to provide user feedback if the API succeeds but returns no key.

Also applies to: 284-289

🧹 Nitpick comments (1)
apps/desktop/src/renderer/routes/_authenticated/settings/api-keys/components/ApiKeysSettings/ApiKeysSettings.tsx (1)

48-55: Silent error swallowing in metadata parsing.

Per coding guidelines, errors should not be silently swallowed. If metadata contains invalid JSON, this could indicate a data integrity issue that would go unnoticed.

Suggested fix
 function parseMetadata(metadata: string | null): ApiKeyMetadata {
 	if (!metadata) return {};
 	try {
 		return JSON.parse(metadata) as ApiKeyMetadata;
 	} catch {
+		console.warn("[api-keys/parseMetadata] Failed to parse metadata:", metadata);
 		return {};
 	}
 }

@github-actions

github-actions Bot commented Jan 26, 2026 •

Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ✅ Neon database branch
  • ✅ Electric Fly.io app

Thank you for your contribution! 🎉

…rmation

- Electric proxy now enforces column filtering for auth.apikeys (excludes sensitive key hash)
- Simplified ApiKeysSettings by removing org filtering (keys authenticate users, not orgs)
- Added delete confirmation dialog using alerter pattern with toast feedback

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In
`@apps/desktop/src/renderer/routes/_authenticated/settings/api-keys/components/ApiKeysSettings/ApiKeysSettings.tsx`:
- Around line 93-96: The authClient.apiKey.delete call inside handleRevokeKey
currently lacks error handling; wrap the deletion in a try/catch, call await
authClient.apiKey.delete({ keyId: id }) inside the try, show toast.success("API
key revoked") on success, and in the catch log the error (e.g., console.error or
the existing logger) and show toast.error with a user-friendly message (e.g.,
"Failed to revoke API key") so failures are surfaced to the user; update the
handleRevokeKey function and keep the existing id, toast and
authClient.apiKey.delete identifiers.
🧹 Nitpick comments (2)
apps/api/src/app/api/electric/[...path]/route.ts (1)

49-54: Consider extracting the column whitelist to a named constant for maintainability.

The table name "auth.apikeys" is already defined in the AllowedTable type in utils.ts, providing type safety. However, the hardcoded column list "id,name,start,created_at,last_request" serves a specific security purpose—excluding the sensitive key hash—and would benefit from being extracted to a module-level constant. This makes the intent clearer and prevents accidental staleness if the schema changes.

♻️ Suggested refactor
+// At module top
+const API_KEYS_SAFE_COLUMNS = "id,name,start,created_at,last_request" as const;
+
 // In the handler
 if (tableName === "auth.apikeys") {
-	originUrl.searchParams.set(
-		"columns",
-		"id,name,start,created_at,last_request",
-	);
+	originUrl.searchParams.set("columns", API_KEYS_SAFE_COLUMNS);
 }
apps/desktop/src/renderer/routes/_authenticated/settings/api-keys/components/ApiKeysSettings/ApiKeysSettings.tsx (1)

88-89: Prefer a params object for handleRevokeKey.

This keeps call sites clearer and aligns with the guideline for functions with 2+ params. As per coding guidelines, functions with 2+ parameters should accept a single params object.

♻️ Suggested refactor
-	const handleRevokeKey = (id: string, name: string | null) => {
+	const handleRevokeKey = ({
+		id,
+		name,
+	}: {
+		id: string;
+		name: string | null;
+	}) => {
 		alert.destructive({
 			title: "Revoke API Key",
 			description: `Are you sure you want to revoke "${name ?? "Unnamed Key"}"? This action cannot be undone.`,
 			confirmText: "Revoke",
 			onConfirm: async () => {
 				await authClient.apiKey.delete({ keyId: id });
 				toast.success("API key revoked");
 			},
 		});
 	};
-															onClick={() => handleRevokeKey(key.id, key.name)}
+															onClick={() =>
+																handleRevokeKey({ id: key.id, name: key.name })
+															}

Also applies to: 209-209

Comment on lines +93 to +96
onConfirm: async () => {
await authClient.apiKey.delete({ keyId: id });
toast.success("API key revoked");
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

fd "ApiKeysSettings.tsx" apps/desktop/src/renderer

Repository: superset-sh/superset

Length of output: 176


🏁 Script executed:

cat -n apps/desktop/src/renderer/routes/_authenticated/settings/api-keys/components/ApiKeysSettings/ApiKeysSettings.tsx | sed -n '85,105p'

Repository: superset-sh/superset

Length of output: 747


🏁 Script executed:

cat -n apps/desktop/src/renderer/routes/_authenticated/settings/api-keys/components/ApiKeysSettings/ApiKeysSettings.tsx | head -30

Repository: superset-sh/superset

Length of output: 1002


🏁 Script executed:

cat -n apps/desktop/src/renderer/routes/_authenticated/settings/api-keys/components/ApiKeysSettings/ApiKeysSettings.tsx | sed -n '50,90p'

Repository: superset-sh/superset

Length of output: 1374


🏁 Script executed:

rg "handleRevokeKey|handleGenerateKey" apps/desktop/src/renderer/routes/_authenticated/settings/api-keys/components/ApiKeysSettings/ApiKeysSettings.tsx -A 15

Repository: superset-sh/superset

Length of output: 2301


🏁 Script executed:

rg "alert\.(destructive|warning|info)" apps/desktop/src/renderer -A 8 | head -80

Repository: superset-sh/superset

Length of output: 4747


🏁 Script executed:

cat -n apps/desktop/src/renderer/routes/_authenticated/settings/members/components/MembersSettings/components/MemberActions/MemberActions.tsx | grep -A 20 "handleRemove\|handleChangeRole" | head -50

Repository: superset-sh/superset

Length of output: 2012


Add error handling around API key revocation.

The authClient.apiKey.delete call in handleRevokeKey lacks error handling. If deletion fails, the error is silently swallowed and the user receives no feedback. The handleGenerateKey function directly above uses proper error handling with logging, which should be mirrored here.

🔧 Suggested fix
 			onConfirm: async () => {
-				await authClient.apiKey.delete({ keyId: id });
-				toast.success("API key revoked");
+				try {
+					await authClient.apiKey.delete({ keyId: id });
+					toast.success("API key revoked");
+				} catch (error) {
+					console.error(
+						"[api-keys/revoke] Failed to revoke API key:",
+						error,
+					);
+					toast.error("Failed to revoke API key");
+				}
 			},
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
onConfirm: async () => {
await authClient.apiKey.delete({ keyId: id });
toast.success("API key revoked");
},
onConfirm: async () => {
try {
await authClient.apiKey.delete({ keyId: id });
toast.success("API key revoked");
} catch (error) {
console.error(
"[api-keys/revoke] Failed to revoke API key:",
error,
);
toast.error("Failed to revoke API key");
}
},
🤖 Prompt for AI Agents
In
`@apps/desktop/src/renderer/routes/_authenticated/settings/api-keys/components/ApiKeysSettings/ApiKeysSettings.tsx`
around lines 93 - 96, The authClient.apiKey.delete call inside handleRevokeKey
currently lacks error handling; wrap the deletion in a try/catch, call await
authClient.apiKey.delete({ keyId: id }) inside the try, show toast.success("API
key revoked") on success, and in the catch log the error (e.g., console.error or
the existing logger) and show toast.error with a user-friendly message (e.g.,
"Failed to revoke API key") so failures are surfaced to the user; update the
handleRevokeKey function and keep the existing id, toast and
authClient.apiKey.delete identifiers.

@saddlepaddle
saddlepaddle merged commit f3c0724 into main Jan 26, 2026
13 checks passed
@Kitenite
Kitenite deleted the mcp-oauth-cleanup branch January 26, 2026 22:08

This branch was previously deployed

1 inactive deployment
preview — 2a07ad8d Deployed Jan 26, 2026 by saddlepaddle via Deploy Admin #1137
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant