Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(web): mint, list, and revoke CLI API keys in account settings
Richie McIlroyb5d051e74f6b
diff --git a/apps/web/__tests__/unit/agent-auth.test.ts b/apps/web/__tests__/unit/agent-auth.test.tsindex 42b5f984d..f3c1f440d 100644--- a/apps/web/__tests__/unit/agent-auth.test.ts+++ b/apps/web/__tests__/unit/agent-auth.test.ts@@ -5,11 +5,13 @@ import {} from "@cap/web-backend";import { describe, expect, it } from "vitest";import {+ agentScopeProfiles,buildAgentCallbackUrl,createAgentAccessToken,hashAgentSecret,isAgentCodeVerifier,isAgentLoopbackRedirectUri,+ isAgentScopeProfile,parseAgentAuthorizationRequest,parseAgentScopes,verifyAgentCodeChallenge,@@ -108,6 +110,32 @@ describe("agent browser authorization", () => {expect(hashAgentSecret(token)).not.toContain(token);});});+describe("agent scope profiles", () => {+ it("mirrors the CLI login profiles incrementally", () => {+ const { creator, admin, full } = agentScopeProfiles;+ expect(creator).toContain("caps:upload");+ expect(creator).not.toContain("organizations:manage");+ expect(admin).toContain("organizations:manage");+ expect(admin).not.toContain("developer:secrets");+ expect(full).toContain("developer:secrets");+ expect(admin).toEqual(expect.arrayContaining(creator));+ expect(full).toEqual(expect.arrayContaining(admin));+ });++ it("every profile passes scope validation as sent by the CLI", () => {+ for (const scopes of Object.values(agentScopeProfiles)) {+ expect(parseAgentScopes(scopes.join(" "))).toEqual(scopes);+ }+ });++ it("rejects unknown profile names", () => {+ expect(isAgentScopeProfile("creator")).toBe(true);+ expect(isAgentScopeProfile("full")).toBe(true);+ expect(isAgentScopeProfile("root")).toBe(false);+ expect(isAgentScopeProfile("")).toBe(false);+ });+});+describe("legacy agent credentials", () => {it("accepts desktop-era keys without extending mobile or extension keys", () => {expect(isLegacyAgentKeySource("desktop")).toBe(true);diff --git a/apps/web/app/(org)/dashboard/settings/account/Settings.tsx b/apps/web/app/(org)/dashboard/settings/account/Settings.tsxindex 07217511b..05cdc1014 100644--- a/apps/web/app/(org)/dashboard/settings/account/Settings.tsx+++ b/apps/web/app/(org)/dashboard/settings/account/Settings.tsx@@ -294,8 +294,8 @@ export const Settings = () => {<div className="space-y-1"><CardTitle>Sign out of all devices</CardTitle><CardDescription>- Invalidate every Cap web session and desktop app authentication- token connected to your account.+ Invalidate every Cap web session, desktop app authentication token,+ and CLI API key connected to your account.</CardDescription></div><Button@@ -315,7 +315,7 @@ export const Settings = () => {<DialogContent><DialogHeadericon={<LogOut className="size-4" />}- description="This will immediately invalidate existing Cap web sessions, desktop session tokens, and desktop API keys for your account."+ description="This will immediately invalidate existing Cap web sessions, desktop session tokens, desktop API keys, and CLI API keys for your account."><DialogTitle>Sign out of all devices?</DialogTitle></DialogHeader>diff --git a/apps/web/app/(org)/dashboard/settings/account/components/CliApiKeys.tsx b/apps/web/app/(org)/dashboard/settings/account/components/CliApiKeys.tsxnew file mode 100644index 000000000..0749209d2--- /dev/null+++ b/apps/web/app/(org)/dashboard/settings/account/components/CliApiKeys.tsx@@ -0,0 +1,314 @@+"use client";++import {+ Button,+ Card,+ CardDescription,+ CardTitle,+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Input,+ Select,+} from "@cap/ui";+import { useMutation } from "@tanstack/react-query";+import { KeyRound, Trash2 } from "lucide-react";+import { useRouter } from "next/navigation";+import { useId, useState } from "react";+import { toast } from "sonner";+import { ApiKeyDisplay } from "../../../developers/_components/ApiKeyDisplay";+import {+ type CliApiKeySummary,+ createCliApiKey,+ revokeCliApiKey,+} from "../server";++const profileOptions = [+ {+ value: "creator",+ label: "Creator: caps, uploads, library, analytics, notifications",+ },+ {+ value: "admin",+ label: "Admin: creator plus organizations, billing, integrations",+ },+ {+ value: "full",+ label: "Full: admin plus developer apps and credentials",+ },+];++const expiryOptions = [+ { value: "30", label: "30 days" },+ { value: "90", label: "90 days" },+ { value: "365", label: "1 year" },+];++// Locale-pinned so the server-rendered HTML matches what every browser hydrates.+const formatDate = (iso: string) =>+ new Date(iso).toLocaleDateString("en-US", {+ year: "numeric",+ month: "short",+ day: "numeric",+ });++export const CliApiKeys = ({+ initialKeys,+}: {+ initialKeys: CliApiKeySummary[];+}) => {+ const router = useRouter();+ const [keys, setKeys] = useState(initialKeys);+ const [createOpen, setCreateOpen] = useState(false);+ const [name, setName] = useState("");+ const [profile, setProfile] = useState("creator");+ const [expiresInDays, setExpiresInDays] = useState("90");+ const [mintedToken, setMintedToken] = useState<string | null>(null);+ const [revokeTarget, setRevokeTarget] = useState<CliApiKeySummary | null>(+ null,+ );+ const nameId = useId();++ const createMutation = useMutation({+ mutationFn: () =>+ createCliApiKey({+ name,+ profile,+ expiresInDays: Number(expiresInDays),+ }),+ onSuccess: ({ token, key }) => {+ setKeys((current) => [key, ...current]);+ setCreateOpen(false);+ setName("");+ setMintedToken(token);+ router.refresh();+ },+ onError: (error) => {+ toast.error(+ error instanceof Error ? error.message : "Failed to create API key",+ );+ },+ });++ const revokeMutation = useMutation({+ mutationFn: (keyId: string) => revokeCliApiKey(keyId),+ onSuccess: (_, keyId) => {+ setKeys((current) => current.filter((key) => key.id !== keyId));+ setRevokeTarget(null);+ toast.success("API key revoked");+ router.refresh();+ },+ onError: () => {+ toast.error("Failed to revoke API key");+ },+ });++ return (+ <Card className="flex flex-col gap-4 mt-6">+ <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">+ <div className="space-y-1">+ <CardTitle>Cap CLI access</CardTitle>+ <CardDescription>+ API keys authenticate the Cap CLI in environments without a browser,+ such as CI runners and remote sandboxes. Keys created by{" "}+ <code>cap auth login</code> also appear here.+ </CardDescription>+ </div>+ <Button+ type="button"+ size="sm"+ variant="dark"+ icon={<KeyRound className="size-4" />}+ onClick={() => setCreateOpen(true)}+ >+ Create API key+ </Button>+ </div>+ {keys.length > 0 && (+ <div className="flex flex-col divide-y divide-gray-3 rounded-xl border border-gray-4">+ {keys.map((key) => {+ const expired = new Date(key.expiresAt).getTime() <= Date.now();+ return (+ <div+ className="flex flex-col gap-2 px-4 py-3 md:flex-row md:items-center md:justify-between"+ key={key.id}+ >+ <div className="min-w-0">+ <p className="truncate text-sm font-medium text-gray-12">+ {key.name}+ </p>+ <p className="text-xs text-gray-10">+ {key.scopes.length} scopes · created{" "}+ {formatDate(key.createdAt)} ·{" "}+ {key.lastUsedAt+ ? `last used ${formatDate(key.lastUsedAt)}`+ : "never used"}{" "}+ ·{" "}+ {expired+ ? "expired"+ : `expires ${formatDate(key.expiresAt)}`}+ </p>+ </div>+ <Button+ type="button"+ size="xs"+ variant="destructive"+ icon={<Trash2 className="size-3.5" />}+ onClick={() => setRevokeTarget(key)}+ >+ Revoke+ </Button>+ </div>+ );+ })}+ </div>+ )}++ <Dialog open={createOpen} onOpenChange={setCreateOpen}>+ <DialogContent>+ <DialogHeader+ icon={<KeyRound className="size-4" />}+ description="The key gets the same permissions as the matching cap auth login profile."+ >+ <DialogTitle>Create a CLI API key</DialogTitle>+ </DialogHeader>+ <form+ onSubmit={(event) => {+ event.preventDefault();+ createMutation.mutate();+ }}+ >+ <div className="p-5 space-y-4">+ <div className="space-y-1.5">+ <label className="text-sm text-gray-11" htmlFor={nameId}>+ Name+ </label>+ <Input+ id={nameId}+ maxLength={100}+ onChange={(event) => setName(event.target.value)}+ placeholder="e.g. Build sandbox"+ type="text"+ value={name}+ />+ </div>+ <div className="space-y-1.5">+ <p className="text-sm text-gray-11">Access profile</p>+ <Select+ onValueChange={setProfile}+ options={profileOptions}+ placeholder="Access profile"+ value={profile}+ />+ </div>+ <div className="space-y-1.5">+ <p className="text-sm text-gray-11">Expires after</p>+ <Select+ onValueChange={setExpiresInDays}+ options={expiryOptions}+ placeholder="Expiry"+ value={expiresInDays}+ />+ </div>+ </div>+ <DialogFooter>+ <Button+ type="button"+ size="sm"+ variant="gray"+ onClick={() => setCreateOpen(false)}+ >+ Cancel+ </Button>+ <Button+ type="submit"+ size="sm"+ variant="dark"+ disabled={name.trim().length === 0 || createMutation.isPending}+ spinner={createMutation.isPending}+ >+ {createMutation.isPending ? "Creating..." : "Create key"}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>++ <Dialog+ open={mintedToken !== null}+ onOpenChange={(open) => {+ if (!open) setMintedToken(null);+ }}+ >+ <DialogContent>+ <DialogHeader+ icon={<KeyRound className="size-4" />}+ description="Cap stores only a hash of this key, so it cannot be shown again."+ >+ <DialogTitle>Copy your API key</DialogTitle>+ </DialogHeader>+ <div className="p-5 space-y-4">+ {mintedToken && (+ <ApiKeyDisplay label="API key" sensitive value={mintedToken} />+ )}+ <p className="text-sm text-gray-11">+ Set it as <code>CAP_API_KEY</code> (or{" "}+ <code>CAP_AGENT_TOKEN</code>) in the environment where the Cap CLI+ runs, then verify with <code>cap auth status --json</code>.+ </p>+ </div>+ <DialogFooter>+ <Button+ type="button"+ size="sm"+ variant="dark"+ onClick={() => setMintedToken(null)}+ >+ Done+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <Dialog+ open={revokeTarget !== null}+ onOpenChange={(open) => {+ if (!open) setRevokeTarget(null);+ }}+ >+ <DialogContent>+ <DialogHeader+ icon={<Trash2 className="size-4" />}+ description="Anything authenticating with this key loses access immediately."+ >+ <DialogTitle>Revoke "{revokeTarget?.name}"?</DialogTitle>+ </DialogHeader>+ <DialogFooter>+ <Button+ type="button"+ size="sm"+ variant="gray"+ onClick={() => setRevokeTarget(null)}+ >+ Cancel+ </Button>+ <Button+ type="button"+ size="sm"+ variant="destructive"+ disabled={revokeMutation.isPending}+ spinner={revokeMutation.isPending}+ onClick={() =>+ revokeTarget && revokeMutation.mutate(revokeTarget.id)+ }+ >+ {revokeMutation.isPending ? "Revoking..." : "Revoke key"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </Card>+ );+};diff --git a/apps/web/app/(org)/dashboard/settings/account/page.tsx b/apps/web/app/(org)/dashboard/settings/account/page.tsxindex 1408e3b9d..ffb245b2b 100644--- a/apps/web/app/(org)/dashboard/settings/account/page.tsx+++ b/apps/web/app/(org)/dashboard/settings/account/page.tsx@@ -1,10 +1,20 @@import type { Metadata } from "next";+import { CliApiKeys } from "./components/CliApiKeys";import { Settings } from "./Settings";+import { listCliApiKeys } from "./server";export const metadata: Metadata = {title: "Settings — Cap",};export default async function SettingsPage() {- return <Settings />;+ // The key list is an enhancement to the settings page, not a dependency: if the session is+ // mid-redirect or the query hiccups, render the page with an empty list instead of a 500.+ const cliApiKeys = await listCliApiKeys().catch(() => []);+ return (+ <>+ <Settings />+ <CliApiKeys initialKeys={cliApiKeys} />+ </>+ );}diff --git a/apps/web/app/(org)/dashboard/settings/account/server.ts b/apps/web/app/(org)/dashboard/settings/account/server.tsindex e2e0c1dec..2c94686b1 100644--- a/apps/web/app/(org)/dashboard/settings/account/server.ts+++ b/apps/web/app/(org)/dashboard/settings/account/server.ts@@ -2,7 +2,9 @@import { db } from "@cap/database";import { getCurrentUser } from "@cap/database/auth/session";+import { nanoId } from "@cap/database/helpers";import {+ agentApiKeys,authApiKeys,organizationMembers,organizations,@@ -10,8 +12,26 @@ import {users,} from "@cap/database/schema";import type { Organisation } from "@cap/web-domain";-import { and, eq, or, sql } from "drizzle-orm";+import { and, desc, eq, isNull, or, sql } from "drizzle-orm";import { revalidatePath } from "next/cache";+import {+ agentScopeProfiles,+ createAgentAccessToken,+ hashAgentSecret,+ isAgentScopeProfile,+} from "@/lib/agent-auth";+import { isRateLimited, RATE_LIMIT_IDS } from "@/lib/rate-limit";++export type CliApiKeySummary = {+ id: string;+ name: string;+ scopes: string[];+ createdAt: string;+ lastUsedAt: string | null;+ expiresAt: string;+};++const cliApiKeyExpiryDays = new Set([30, 90, 365]);export async function patchAccountSettings(firstName?: string,@@ -69,6 +89,117 @@ export async function patchAccountSettings(revalidatePath("/dashboard/settings/account");}+export async function listCliApiKeys(): Promise<CliApiKeySummary[]> {+ const currentUser = await getCurrentUser();+ if (!currentUser) throw new Error("Unauthorized");++ const keys = await db()+ .select({+ id: agentApiKeys.id,+ name: agentApiKeys.name,+ scopes: agentApiKeys.scopes,+ createdAt: agentApiKeys.createdAt,+ lastUsedAt: agentApiKeys.lastUsedAt,+ expiresAt: agentApiKeys.expiresAt,+ })+ .from(agentApiKeys)+ .where(+ and(+ eq(agentApiKeys.userId, currentUser.id),+ isNull(agentApiKeys.revokedAt),+ ),+ )+ .orderBy(desc(agentApiKeys.createdAt))+ .limit(100);++ return keys.map((key) => ({+ id: key.id,+ name: key.name,+ scopes: [...key.scopes],+ createdAt: key.createdAt.toISOString(),+ lastUsedAt: key.lastUsedAt?.toISOString() ?? null,+ expiresAt: key.expiresAt.toISOString(),+ }));+}++export async function createCliApiKey(input: {+ name: string;+ profile: string;+ expiresInDays: number;+}): Promise<{ token: string; key: CliApiKeySummary }> {+ const currentUser = await getCurrentUser();+ if (!currentUser) throw new Error("Unauthorized");++ const name = input.name.trim();+ if (name.length === 0 || name.length > 100) {+ throw new Error("The key name must be between 1 and 100 characters");+ }+ if (!isAgentScopeProfile(input.profile)) {+ throw new Error("Unknown access profile");+ }+ if (!cliApiKeyExpiryDays.has(input.expiresInDays)) {+ throw new Error("Unknown expiry");+ }++ // Same bucket as the CLI OAuth authorize page: both mint agent credentials.+ if (+ await isRateLimited(RATE_LIMIT_IDS.AGENT_AUTHORIZATION, {+ key: `agent-authorization:${currentUser.id}`,+ })+ ) {+ throw new Error("Too many API key requests. Try again later.");+ }++ const token = createAgentAccessToken();+ const now = new Date();+ const expiresAt = new Date(+ now.getTime() + input.expiresInDays * 24 * 60 * 60 * 1000,+ );+ const scopes = agentScopeProfiles[input.profile];+ const id = nanoId();+ await db()+ .insert(agentApiKeys)+ .values({+ id,+ userId: currentUser.id,+ tokenHash: hashAgentSecret(token),+ name,+ scopes,+ expiresAt,+ });++ revalidatePath("/dashboard/settings/account");+ return {+ token,+ key: {+ id,+ name,+ scopes: [...scopes],+ createdAt: now.toISOString(),+ lastUsedAt: null,+ expiresAt: expiresAt.toISOString(),+ },+ };+}++export async function revokeCliApiKey(keyId: string): Promise<void> {+ const currentUser = await getCurrentUser();+ if (!currentUser) throw new Error("Unauthorized");++ await db()+ .update(agentApiKeys)+ .set({ revokedAt: new Date() })+ .where(+ and(+ eq(agentApiKeys.id, keyId),+ eq(agentApiKeys.userId, currentUser.id),+ isNull(agentApiKeys.revokedAt),+ ),+ );++ revalidatePath("/dashboard/settings/account");+}+export async function signOutAllDevices() {const currentUser = await getCurrentUser();if (!currentUser) throw new Error("Unauthorized");@@ -80,5 +211,14 @@ export async function signOutAllDevices() {.where(eq(users.id, currentUser.id));await tx.delete(sessions).where(eq(sessions.userId, currentUser.id));await tx.delete(authApiKeys).where(eq(authApiKeys.userId, currentUser.id));+ await tx+ .update(agentApiKeys)+ .set({ revokedAt: new Date() })+ .where(+ and(+ eq(agentApiKeys.userId, currentUser.id),+ isNull(agentApiKeys.revokedAt),+ ),+ );});}diff --git a/apps/web/lib/agent-auth.ts b/apps/web/lib/agent-auth.tsindex 54c844fe7..9ddf93668 100644--- a/apps/web/lib/agent-auth.ts+++ b/apps/web/lib/agent-auth.ts@@ -27,6 +27,57 @@ export const agentScopes = ["developer:secrets",] as const satisfies readonly Agent.AgentScope[];+// Mirrors the CLI's `cap auth login --profile` scope sets (apps/cli/src/agent_auth.rs) so a key+// minted from the dashboard grants exactly what the equivalent browser login would.+const creatorProfileScopes: Agent.AgentScope[] = [+ "caps:read",+ "caps:comment",+ "caps:write",+ "profile:read",+ "profile:write",+ "caps:upload",+ "caps:process",+ "caps:delete",+ "library:read",+ "library:write",+ "analytics:read",+ "notifications:read",+ "notifications:write",+];++const adminProfileScopes: Agent.AgentScope[] = [+ ...creatorProfileScopes,+ "organizations:read",+ "organizations:manage",+ "organizations:members",+ "integrations:read",+ "integrations:write",+ "billing:read",+ "billing:write",+];++const fullProfileScopes: Agent.AgentScope[] = [+ ...adminProfileScopes,+ "developer:read",+ "developer:write",+ "developer:secrets",+];++const canonicalScopeOrder = (scopes: Agent.AgentScope[]) =>+ agentScopes.filter((scope) => scopes.includes(scope));++export const agentScopeProfiles = {+ creator: canonicalScopeOrder(creatorProfileScopes),+ admin: canonicalScopeOrder(adminProfileScopes),+ full: canonicalScopeOrder(fullProfileScopes),+} as const;++export type AgentScopeProfile = keyof typeof agentScopeProfiles;++export const isAgentScopeProfile = (+ value: string,+): value is AgentScopeProfile => Object.hasOwn(agentScopeProfiles, value);+export type AgentAuthorizationRequest = {clientId: "cap-cli";redirectUri: string;