Repository navigation
refactor: replace tRPC apiKeys router with Better Auth + Electric - #954
Conversation
- 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
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the 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. 📝 WalkthroughWalkthroughThis PR migrates API key management from TRPC endpoints to Better Auth's apiKey plugin, adds support for the Changes
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
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly Related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
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'sdisabledprop 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?.keyis 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 {}; } }
🧹 Preview Cleanup CompleteThe following preview resources have been cleaned up:
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
There was a problem hiding this comment.
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 theAllowedTabletype inutils.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 forhandleRevokeKey.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
| onConfirm: async () => { | ||
| await authClient.apiKey.delete({ keyId: id }); | ||
| toast.success("API key revoked"); | ||
| }, |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
fd "ApiKeysSettings.tsx" apps/desktop/src/rendererRepository: 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 -30Repository: 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 15Repository: superset-sh/superset
Length of output: 2301
🏁 Script executed:
rg "alert\.(destructive|warning|info)" apps/desktop/src/renderer -A 8 | head -80Repository: 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 -50Repository: 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.
| 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.
Summary
apiKeysRouterwith direct Better Auth client methods + Electric syncmyOrganizationsendpoint from organization routerChanges
API Keys
apiKeyClient()plugin to both web and desktop auth clientsauth.apikeystable to Electric sync proxy (filtered byuserId)ApiKeysSettingscomponent to:authClient.apiKey.create()for creating keysauthClient.apiKey.delete()for revoking keyspackages/trpc/src/router/agent/api-keys.tsDuplicate Cleanup
myOrganizationsfromorganizationRouter(was duplicate ofuserRouter.myOrganizations)user.myOrganizationsTest plan
Summary by CodeRabbit
New Features
Refactor
✏️ Tip: You can customize this high-level summary in your review settings.