Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions apps/api/src/app/api/electric/[...path]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ export async function GET(request: Request): Promise<Response> {
originUrl.searchParams.set(`params[${index + 1}]`, String(value));
});

if (tableName === "auth.apikeys") {
originUrl.searchParams.set(
"columns",
"id,name,start,created_at,last_request",
);
}

let response = await fetch(originUrl.toString());

if (response.headers.get("content-encoding")) {
Expand Down
5 changes: 5 additions & 0 deletions apps/api/src/app/api/electric/[...path]/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { db } from "@superset/db/client";
import {
agentCommands,
apikeys,
devicePresence,
invitations,
members,
Expand All @@ -21,6 +22,7 @@ export type AllowedTable =
| "auth.organizations"
| "auth.users"
| "auth.invitations"
| "auth.apikeys"
| "device_presence"
| "agent_commands";

Expand Down Expand Up @@ -103,6 +105,9 @@ export async function buildWhereClause(
case "agent_commands":
return build(agentCommands, agentCommands.organizationId, organizationId);

case "auth.apikeys":
return build(apikeys, apikeys.userId, userId);

default:
return null;
}
Expand Down
2 changes: 2 additions & 0 deletions apps/desktop/src/renderer/lib/auth-client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { stripeClient } from "@better-auth/stripe/client";
import type { auth } from "@superset/auth/server";
import {
apiKeyClient,
customSessionClient,
organizationClient,
} from "better-auth/client/plugins";
Expand Down Expand Up @@ -29,6 +30,7 @@ export const authClient = createAuthClient({
organizationClient(),
customSessionClient<typeof auth>(),
stripeClient({ subscription: true }),
apiKeyClient(),
],
fetchOptions: {
credentials: "include",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { createTRPCProxyClient, httpBatchLink } from "@trpc/client";
import { env } from "renderer/env.renderer";
import { getAuthToken } from "renderer/lib/auth-client";
import superjson from "superjson";
import { z } from "zod";

const columnMapper = snakeCamelMapper();
const electricUrl = `${env.NEXT_PUBLIC_API_URL}/api/electric/v1/shape`;
Expand Down Expand Up @@ -68,6 +69,34 @@ const organizationsCollection = createCollection(
}),
);

const apiKeyDisplaySchema = z.object({
id: z.string(),
name: z.string().nullable(),
start: z.string().nullable(),
createdAt: z.coerce.date(),
lastRequest: z.coerce.date().nullable(),
});

type ApiKeyDisplay = z.infer<typeof apiKeyDisplaySchema>;

const apiKeysCollection = createCollection(
electricCollectionOptions<ApiKeyDisplay>({
id: "apikeys",
shapeOptions: {
url: electricUrl,
params: { table: "auth.apikeys" },
headers: {
Authorization: () => {
const token = getAuthToken();
return token ? `Bearer ${token}` : "";
},
},
columnMapper,
},
getKey: (item) => item.id,
}),
);

function createOrgCollections(organizationId: string): OrgCollections {
const headers = {
Authorization: () => {
Expand Down Expand Up @@ -279,5 +308,6 @@ export function getCollections(organizationId: string) {
return {
...orgCollections,
organizations: organizationsCollection,
apiKeys: apiKeysCollection,
};
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { alert } from "@superset/ui/atoms/Alert";
import { Badge } from "@superset/ui/badge";
import { Button } from "@superset/ui/button";
import {
Expand All @@ -11,6 +12,7 @@ import {
import { Input } from "@superset/ui/input";
import { Label } from "@superset/ui/label";
import { Skeleton } from "@superset/ui/skeleton";
import { toast } from "@superset/ui/sonner";
import {
Table,
TableBody,
Expand All @@ -19,15 +21,16 @@ import {
TableHeader,
TableRow,
} from "@superset/ui/table";
import { useCallback, useEffect, useState } from "react";
import { useLiveQuery } from "@tanstack/react-db";
import { useState } from "react";
import {
HiOutlineClipboardDocument,
HiOutlineKey,
HiOutlinePlus,
HiOutlineTrash,
} from "react-icons/hi2";
import { apiTrpcClient } from "renderer/lib/api-trpc-client";
import { electronTrpc } from "renderer/lib/electron-trpc";
import { authClient } from "renderer/lib/auth-client";
import { useCollections } from "renderer/routes/_authenticated/providers/CollectionsProvider";
import {
isItemVisible,
SETTING_ITEM_ID,
Expand All @@ -38,28 +41,19 @@ interface ApiKeysSettingsProps {
visibleItems?: SettingItemId[] | null;
}

interface ApiKey {
id: string;
name: string;
keyPrefix: string;
defaultDeviceId: string | null;
lastUsedAt: Date | null;
usageCount: string;
createdAt: Date;
expiresAt: Date | null;
}

export function ApiKeysSettings({ visibleItems }: ApiKeysSettingsProps) {
const [apiKeys, setApiKeys] = useState<ApiKey[]>([]);
const [isLoading, setIsLoading] = useState(true);
const collections = useCollections();
const [isGenerating, setIsGenerating] = useState(false);
const [showGenerateDialog, setShowGenerateDialog] = useState(false);
const [showNewKeyDialog, setShowNewKeyDialog] = useState(false);
const [newKeyName, setNewKeyName] = useState("");
const [newKeyValue, setNewKeyValue] = useState("");
const [copied, setCopied] = useState(false);

const { data: deviceInfo } = electronTrpc.auth.getDeviceInfo.useQuery();
const { data: apiKeys, isLoading } = useLiveQuery(
(q) => q.from({ apiKeys: collections.apiKeys }),
[collections],
);

const showApiKeysList = isItemVisible(
SETTING_ITEM_ID.API_KEYS_LIST,
Expand All @@ -70,50 +64,37 @@ export function ApiKeysSettings({ visibleItems }: ApiKeysSettingsProps) {
visibleItems,
);

const loadApiKeys = useCallback(async () => {
try {
setIsLoading(true);
const keys = await apiTrpcClient.apiKeys.list.query();
setApiKeys(keys);
} catch (error) {
console.error("[api-keys] Failed to load API keys:", error);
} finally {
setIsLoading(false);
}
}, []);

useEffect(() => {
loadApiKeys();
}, [loadApiKeys]);

const handleGenerateKey = async () => {
if (!newKeyName.trim()) return;

try {
setIsGenerating(true);
const result = await apiTrpcClient.apiKeys.generate.mutate({
const result = await authClient.apiKey.create({
name: newKeyName.trim(),
defaultDeviceId: deviceInfo?.deviceId,
});
setNewKeyValue(result.key);
setShowGenerateDialog(false);
setShowNewKeyDialog(true);
setNewKeyName("");
loadApiKeys();
if (result.data?.key) {
setNewKeyValue(result.data.key);
setShowGenerateDialog(false);
setShowNewKeyDialog(true);
setNewKeyName("");
}
} catch (error) {
console.error("[api-keys] Failed to generate API key:", error);
} finally {
setIsGenerating(false);
}
};

const handleRevokeKey = async (id: string) => {
try {
await apiTrpcClient.apiKeys.revoke.mutate({ id });
loadApiKeys();
} catch (error) {
console.error("[api-keys] Failed to revoke API key:", error);
}
const handleRevokeKey = (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");
},
Comment on lines +93 to +96

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.

});
};

const handleCopyKey = () => {
Expand Down Expand Up @@ -178,7 +159,7 @@ export function ApiKeysSettings({ visibleItems }: ApiKeysSettingsProps) {
</div>
))}
</div>
) : apiKeys.length === 0 ? (
) : !apiKeys || apiKeys.length === 0 ? (
<div className="text-center py-12 text-muted-foreground border rounded-lg">
<HiOutlineKey className="h-12 w-12 mx-auto mb-4 opacity-50" />
<p>No API keys yet</p>
Expand All @@ -204,26 +185,28 @@ export function ApiKeysSettings({ visibleItems }: ApiKeysSettingsProps) {
<TableCell>
<div className="flex items-center gap-2">
<HiOutlineKey className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{key.name}</span>
<span className="font-medium">
{key.name ?? "Unnamed Key"}
</span>
</div>
</TableCell>
<TableCell>
<Badge variant="outline" className="font-mono">
{key.keyPrefix}
{key.start ?? "sk_..."}
</Badge>
</TableCell>
<TableCell className="text-muted-foreground">
{formatDate(key.createdAt)}
</TableCell>
<TableCell className="text-muted-foreground">
{formatDate(key.lastUsedAt)}
{formatDate(key.lastRequest)}
</TableCell>
<TableCell>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive"
onClick={() => handleRevokeKey(key.id)}
onClick={() => handleRevokeKey(key.id, key.name)}
>
<HiOutlineTrash className="h-4 w-4" />
</Button>
Expand Down
10 changes: 5 additions & 5 deletions apps/web/src/app/oauth/consent/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,14 @@ export default async function ConsentPage({ searchParams }: ConsentPageProps) {

// Fetch user's organization memberships via tRPC
const trpc = await api();
const userMemberships = await trpc.organization.myOrganizations.query();
const userOrganizations = await trpc.user.myOrganizations.query();

// Get active organization from session or default to first
const extendedSession = session.session as typeof session.session & {
activeOrganizationId?: string | null;
};
const defaultOrgId =
extendedSession.activeOrganizationId ?? userMemberships[0]?.organizationId;
extendedSession.activeOrganizationId ?? userOrganizations[0]?.id;

return (
<div className="relative flex min-h-screen flex-col">
Expand All @@ -92,9 +92,9 @@ export default async function ConsentPage({ searchParams }: ConsentPageProps) {
clientId={client_id}
scopes={scopes}
userName={session.user.name}
organizations={userMemberships.map((m) => ({
id: m.organizationId,
name: m.organizationName,
organizations={userOrganizations.map((org) => ({
id: org.id,
name: org.name,
}))}
defaultOrganizationId={defaultOrgId}
/>
Expand Down
2 changes: 2 additions & 0 deletions packages/auth/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { stripeClient } from "@better-auth/stripe/client";
import type { auth } from "@superset/auth/server";
import {
apiKeyClient,
customSessionClient,
organizationClient,
} from "better-auth/client/plugins";
Expand All @@ -14,5 +15,6 @@ export const authClient = createAuthClient({
organizationClient(),
customSessionClient<typeof auth>(),
stripeClient({ subscription: true }),
apiKeyClient(),
],
});
3 changes: 1 addition & 2 deletions packages/trpc/src/root.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server";

import { adminRouter } from "./router/admin";
import { agentRouter, apiKeysRouter } from "./router/agent";
import { agentRouter } from "./router/agent";
import { analyticsRouter } from "./router/analytics";
import { deviceRouter } from "./router/device";
import { integrationRouter } from "./router/integration";
Expand All @@ -15,7 +15,6 @@ export const appRouter = createTRPCRouter({
admin: adminRouter,
agent: agentRouter,
analytics: analyticsRouter,
apiKeys: apiKeysRouter,
device: deviceRouter,
integration: integrationRouter,
organization: organizationRouter,
Expand Down
Loading