Skip to content

An open-source, faster Devin alternative

TypeScript

api-keys: allow renaming keys from the dashboard (#831)

devin-ai-integration[bot]3250269f0533
diff --git a/cloudflare-workers/api-edge/src/cli_auth.test.ts b/cloudflare-workers/api-edge/src/cli_auth.test.ts
index ac3b6ec2..a4abe37c 100644
--- a/cloudflare-workers/api-edge/src/cli_auth.test.ts
+++ b/cloudflare-workers/api-edge/src/cli_auth.test.ts
@@ -37,6 +37,16 @@ class FakeStatement {
if (!this.db.user) return null;
return this.db.user as T;
}
+ if (this.sql.includes("FROM api_keys WHERE id")) {
+ return {
+ id: "key-1",
+ key_prefix: "osb_abcd",
+ scopes: "sandbox:*",
+ last_used: null,
+ expires_at: null,
+ created_at: 1700000000,
+ } as T;
+ }
if (
this.sql.includes("FROM api_keys WHERE key_hash") ||
this.sql.includes("FROM api_keys k")
@@ -719,4 +729,59 @@ describe("CLI identity and credential lifecycle", () => {
);
expect(insert?.args).not.toContain(body.key);
});
+
+ it("renames a dashboard API key scoped to the caller's org", async () => {
+ const db = new FakeDB();
+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({
+ user: { id: "workos-user", email: "[email protected]", first_name: "Igor" },
+ })));
+ const callback = await worker.fetch(
+ request("/auth/callback?code=browser-code"),
+ testEnv(db),
+ ctx,
+ );
+ const cookie = callback.headers.get("set-cookie")?.split(";", 1)[0];
+ expect(cookie).toMatch(/^oc_session=/);
+
+ const resp = await worker.fetch(request("/api/dashboard/api-keys/key-1", {
+ method: "PATCH",
+ headers: {
+ cookie: cookie ?? "",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({ name: " Renamed key " }),
+ }), testEnv(db), ctx);
+ expect(resp.status).toBe(200);
+ const body = await resp.json<Record<string, unknown>>();
+ expect(body.name).toBe("Renamed key");
+ expect(body.key).toBeUndefined();
+ const update = db.executed.find((entry) =>
+ entry.sql.includes("UPDATE api_keys SET name")
+ );
+ expect(update?.args).toEqual(["Renamed key", "key-1", orgID]);
+ });
+
+ it("rejects a dashboard API key rename without a name", async () => {
+ const db = new FakeDB();
+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({
+ user: { id: "workos-user", email: "[email protected]", first_name: "Igor" },
+ })));
+ const callback = await worker.fetch(
+ request("/auth/callback?code=browser-code"),
+ testEnv(db),
+ ctx,
+ );
+ const cookie = callback.headers.get("set-cookie")?.split(";", 1)[0];
+
+ const resp = await worker.fetch(request("/api/dashboard/api-keys/key-1", {
+ method: "PATCH",
+ headers: {
+ cookie: cookie ?? "",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({ name: " " }),
+ }), testEnv(db), ctx);
+ expect(resp.status).toBe(400);
+ expect(db.executed.some((entry) => entry.sql.includes("UPDATE api_keys"))).toBe(false);
+ });
});
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index 587864e3..aea082e7 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -652,6 +652,34 @@ async function handleDeleteAPIKey(_req: Request, env: DashboardEnv, caller: Call
return new Response(null, { status: 204 });
}
+async function handleRenameAPIKey(req: Request, env: DashboardEnv, caller: Caller, keyID: string): Promise<Response> {
+ const body = await req.json<{ name?: unknown }>().catch(() => ({} as { name?: unknown }));
+ const name = typeof body.name === "string" ? body.name.trim() : "";
+ if (!name) return json({ error: "name is required" }, 400);
+
+ const row = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT id, key_prefix, scopes, last_used, expires_at, created_at
+ FROM api_keys WHERE id = ?1 AND org_id = ?2`,
+ ).bind(keyID, caller.orgID).first<{
+ id: string; key_prefix: string; scopes: string;
+ last_used: number | null; expires_at: number | null; created_at: number;
+ }>();
+ if (!row) return json({ error: "api key not found" }, 404);
+
+ await env.OPENCOMPUTER_DB.prepare(`UPDATE api_keys SET name = ?1 WHERE id = ?2 AND org_id = ?3`)
+ .bind(name, keyID, caller.orgID).run();
+ return json({
+ id: row.id,
+ orgId: caller.orgID,
+ name,
+ keyPrefix: row.key_prefix,
+ scopes: row.scopes.split(",").map((s) => s.trim()).filter(Boolean),
+ lastUsed: epochToISO(row.last_used),
+ expiresAt: epochToISO(row.expires_at),
+ createdAt: epochToISORequired(row.created_at),
+ });
+}
+
// ── sessions list (cross-cell) ───────────────────────────────────────────
async function handleListSessions(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {
@@ -1123,6 +1151,7 @@ export async function handleDashboard(
{
const m = sub.match(/^\/api-keys\/([^/]+)$/);
if (m && method === "DELETE") return handleDeleteAPIKey(req, env, caller, m[1]);
+ if (m && method === "PATCH") return handleRenameAPIKey(req, env, caller, m[1]);
}
// ── sessions: cross-cell list, then per-cell proxy ─────────────────────
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index 149843cf..c14cd5b7 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -273,6 +273,13 @@ export const createAPIKey = (name: string) =>
S.CreatedAPIKeySchema,
)
+export const renameAPIKey = (keyId: string, name: string) =>
+ apiFetch(
+ `/api-keys/${keyId}`,
+ { method: 'PATCH', body: JSON.stringify({ name }) },
+ S.APIKeySchema,
+ )
+
export const deleteAPIKey = (keyId: string) =>
apiFetch<void>(`/api-keys/${keyId}`, { method: 'DELETE' })
diff --git a/web/src/api/mock.ts b/web/src/api/mock.ts
index c6a18ee7..e27ce153 100644
--- a/web/src/api/mock.ts
+++ b/web/src/api/mock.ts
@@ -1589,6 +1589,15 @@ const POST_ROUTES: [RegExp, () => unknown][] = [
export function mockFetch<T>(path: string, options: RequestInit = {}): T {
const method = (options.method ?? 'GET').toUpperCase()
+ const renameMatch = path.match(/^\/api-keys\/([^/]+)$/)
+ if (method === 'PATCH' && renameMatch) {
+ const body = typeof options.body === 'string' ? options.body : '{}'
+ const { name } = JSON.parse(body) as { name?: string }
+ const key = apiKeys.find((k) => k.id === renameMatch[1])
+ if (!key) throw new ApiError('Not found', 404)
+ key.name = name ?? key.name
+ return key as T
+ }
if (method === 'PUT' && path === '/me/preferences') {
const body = typeof options.body === 'string' ? options.body : '{}'
const updates = JSON.parse(body) as Partial<
diff --git a/web/src/pages/APIKeys.tsx b/web/src/pages/APIKeys.tsx
index d3e7713b..3550a589 100644
--- a/web/src/pages/APIKeys.tsx
+++ b/web/src/pages/APIKeys.tsx
@@ -6,6 +6,7 @@ import {
createAPIKey,
deleteAPIKey,
getAPIKeys,
+ renameAPIKey,
type APIKey,
} from '@/api/client'
import { PageHeader } from '@/components/page-header'
@@ -36,6 +37,8 @@ export default function APIKeys() {
const [newKeyName, setNewKeyName] = useState('')
const [createdKey, setCreatedKey] = useState<string | null>(null)
const [toRevoke, setToRevoke] = useState<APIKey | null>(null)
+ const [toRename, setToRename] = useState<APIKey | null>(null)
+ const [renameValue, setRenameValue] = useState('')
const createMutation = useMutation({
mutationFn: (name: string) => createAPIKey(name),
@@ -48,6 +51,16 @@ export default function APIKeys() {
onError: (error) => notifyError("Couldn't create the API key.", error),
})
+ const renameMutation = useMutation({
+ mutationFn: ({ id, name }: { id: string; name: string }) =>
+ renameAPIKey(id, name),
+ onSuccess: () => {
+ setToRename(null)
+ void queryClient.invalidateQueries({ queryKey: ['api-keys'] })
+ },
+ onError: (error) => notifyError("Couldn't rename the key.", error),
+ })
+
const deleteMutation = useMutation({
mutationFn: (id: string) => deleteAPIKey(id),
onError: (error) => notifyError("Couldn't revoke the key.", error),
@@ -94,14 +107,27 @@ export default function APIKeys() {
header: '',
align: 'right',
cell: (k) => (
- <Button
- variant="ghost"
- size="sm"
- className="text-status-error hover:text-destructive underline-offset-2 hover:bg-transparent hover:underline"
- onClick={() => setToRevoke(k)}
- >
- Revoke
- </Button>
+ <div className="flex justify-end gap-1">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="underline-offset-2 hover:bg-transparent hover:underline"
+ onClick={() => {
+ setToRename(k)
+ setRenameValue(k.name)
+ }}
+ >
+ Rename
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-status-error hover:text-destructive underline-offset-2 hover:bg-transparent hover:underline"
+ onClick={() => setToRevoke(k)}
+ >
+ Revoke
+ </Button>
+ </div>
),
},
]
@@ -212,6 +238,55 @@ export default function APIKeys() {
</DialogContent>
</Dialog>
+ <Dialog
+ open={toRename !== null}
+ onOpenChange={(open) => !open && setToRename(null)}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Rename API key</DialogTitle>
+ <DialogDescription>
+ Give the key a new name. This doesn&apos;t change the key itself.
+ </DialogDescription>
+ </DialogHeader>
+ <form
+ onSubmit={(e) => {
+ e.preventDefault()
+ if (toRename && renameValue.trim()) {
+ renameMutation.mutate({
+ id: toRename.id,
+ name: renameValue.trim(),
+ })
+ }
+ }}
+ >
+ <Field label="Key name" htmlFor="rename-key-name">
+ <Input
+ id="rename-key-name"
+ value={renameValue}
+ onChange={(e) => setRenameValue(e.target.value)}
+ placeholder="e.g. Production"
+ />
+ </Field>
+ <DialogFooter className="mt-4">
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => setToRename(null)}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ disabled={renameMutation.isPending || !renameValue.trim()}
+ >
+ {renameMutation.isPending ? 'Renaming…' : 'Rename key'}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+
<ConfirmDialog
open={toRevoke !== null}
onOpenChange={(open) => !open && setToRevoke(null)}