An open-source, faster Devin alternative
TypeScript
api keys: optional expiry on dashboard-created keys
Mohamed Habib via Computer3c14e86b19d7
diff --git a/cloudflare-workers/api-edge/src/api_keys.ts b/cloudflare-workers/api-edge/src/api_keys.tsindex 68392a2c..516b544a 100644--- a/cloudflare-workers/api-edge/src/api_keys.ts+++ b/cloudflare-workers/api-edge/src/api_keys.ts@@ -10,6 +10,7 @@ export interface CreatedAPIKey {keyPrefix: string;scopes: string[];createdAt: string;+ expiresAt?: string;}export async function hashAPIKey(key: string): Promise<string> {@@ -19,11 +20,12 @@ export async function hashAPIKey(key: string): Promise<string> {/*** Creates an ordinary OpenComputer org key. The caller owns the one-time- * plaintext response; only its SHA-256 hash is persisted.+ * plaintext response; only its SHA-256 hash is persisted. `expiresAt` (epoch+ * seconds) is optional; key validation refuses the key after it.*/export async function createAPIKey(env: APIKeyEnv,- input: { orgID: string; userID: string; name: string },+ input: { orgID: string; userID: string; name: string; expiresAt?: number },): Promise<CreatedAPIKey> {const bytes = new Uint8Array(32);crypto.getRandomValues(bytes);@@ -34,10 +36,10 @@ export async function createAPIKey(const now = Math.floor(Date.now() / 1000);await env.OPENCOMPUTER_DB.prepare(- `INSERT INTO api_keys (id, org_id, created_by, key_hash, key_prefix, name, scopes, created_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'sandbox:*', ?7)`,+ `INSERT INTO api_keys (id, org_id, created_by, key_hash, key_prefix, name, scopes, created_at, expires_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'sandbox:*', ?7, ?8)`,)- .bind(id, input.orgID, input.userID, hash, prefix, input.name, now)+ .bind(id, input.orgID, input.userID, hash, prefix, input.name, now, input.expiresAt ?? null).run();return {@@ -48,5 +50,8 @@ export async function createAPIKey(keyPrefix: prefix,scopes: ["sandbox:*"],createdAt: new Date(now * 1000).toISOString(),+ ...(input.expiresAt !== undefined+ ? { expiresAt: new Date(input.expiresAt * 1000).toISOString() }+ : {}),};}diff --git a/cloudflare-workers/api-edge/src/cli_auth.test.ts b/cloudflare-workers/api-edge/src/cli_auth.test.tsindex a4abe37c..456ec3dc 100644--- a/cloudflare-workers/api-edge/src/cli_auth.test.ts+++ b/cloudflare-workers/api-edge/src/cli_auth.test.ts@@ -728,6 +728,68 @@ describe("CLI identity and credential lifecycle", () => {entry.sql.includes("INSERT INTO api_keys") && entry.args[5] === "Dashboard key");expect(insert?.args).not.toContain(body.key);+ expect(insert?.args[7]).toBeNull();+ });++ it("stores and returns an expiry when a dashboard key is created with one", 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 expiresAt = new Date(Date.now() + 7 * 24 * 3600 * 1000);+ expiresAt.setMilliseconds(0);++ const resp = await worker.fetch(request("/api/dashboard/api-keys", {+ method: "POST",+ headers: {+ cookie: cookie ?? "",+ "content-type": "application/json",+ },+ body: JSON.stringify({ name: "Expiring key", expiresAt: expiresAt.toISOString() }),+ }), testEnv(db), ctx);+ expect(resp.status).toBe(201);+ const body = await resp.json<Record<string, unknown>>();+ expect(body.expiresAt).toBe(expiresAt.toISOString());+ const insert = db.executed.find((entry) =>+ entry.sql.includes("INSERT INTO api_keys") && entry.args[5] === "Expiring key"+ );+ expect(insert?.args[7]).toBe(expiresAt.getTime() / 1000);+ });++ it.each([+ ["in the past", new Date(Date.now() - 60_000).toISOString()],+ ["not a timestamp", "next week"],+ ["not a string", 1234567890],+ ])("rejects a dashboard key expiry that is %s", async (_label, expiresAt) => {+ 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", {+ method: "POST",+ headers: {+ cookie: cookie ?? "",+ "content-type": "application/json",+ },+ body: JSON.stringify({ name: "Bad expiry", expiresAt }),+ }), testEnv(db), ctx);+ expect(resp.status).toBe(400);+ expect(db.executed.some((entry) =>+ entry.sql.includes("INSERT INTO api_keys") && entry.args[5] === "Bad expiry"+ )).toBe(false);});it("renames a dashboard API key scoped to the caller's org", async () => {diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex 5291f98a..d6314599 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -643,12 +643,21 @@ async function handleListAPIKeys(_req: Request, env: DashboardEnv, caller: Calle}async function handleCreateAPIKey(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {- const body = await req.json<{ name?: string }>().catch(() => ({} as { name?: string }));+ const body = await req.json<{ name?: string; expiresAt?: unknown }>()+ .catch(() => ({} as { name?: string; expiresAt?: unknown }));const name = (body.name ?? "Untitled").trim() || "Untitled";+ let expiresAt: number | undefined;+ if (body.expiresAt !== undefined && body.expiresAt !== null) {+ const ms = typeof body.expiresAt === "string" ? Date.parse(body.expiresAt) : NaN;+ if (Number.isNaN(ms)) return json({ error: "expiresAt must be an ISO 8601 timestamp" }, 400);+ if (ms <= Date.now()) return json({ error: "expiresAt must be in the future" }, 400);+ expiresAt = Math.floor(ms / 1000);+ }return json(await createAPIKey(env, {orgID: caller.orgID,userID: caller.userID,name,+ expiresAt,}), 201);}diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex c855d1da..032cebb2 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -266,10 +266,10 @@ export const deletePreviewUrl = (sandboxId: string, port: number) =>export const getAPIKeys = () =>apiFetch('/api-keys', {}, z.array(S.APIKeySchema))-export const createAPIKey = (name: string) =>+export const createAPIKey = (name: string, expiresAt?: string) =>apiFetch('/api-keys',- { method: 'POST', body: JSON.stringify({ name }) },+ { method: 'POST', body: JSON.stringify({ name, expiresAt }) },S.CreatedAPIKeySchema,)diff --git a/web/src/api/mock.ts b/web/src/api/mock.tsindex 41d8bd73..a3e4202f 100644--- a/web/src/api/mock.ts+++ b/web/src/api/mock.ts@@ -323,8 +323,18 @@ const apiKeys = [keyPrefix: 'osb_live_Lp9x',name: 'CI pipeline',scopes: ['sandboxes:write'],+ expiresAt: new Date(Date.now() + 76 * 86_400_000).toISOString(),createdAt: at(14),},+ {+ id: 'k3',+ orgId: 'org_digger',+ keyPrefix: 'osb_live_Qe4m',+ name: 'Demo laptop',+ scopes: ['sandboxes:write'],+ expiresAt: at(2),+ createdAt: at(9),+ },]const autumn = {diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.tsindex d84d32c7..6e4c7f72 100644--- a/web/src/api/schemas.ts+++ b/web/src/api/schemas.ts@@ -171,6 +171,7 @@ export const CreatedAPIKeySchema = z.object({key: z.string(),keyPrefix: z.string(),createdAt: z.string(),+ expiresAt: z.string().optional(),})export const OrgMemberSchema = z.object({diff --git a/web/src/pages/APIKeys.tsx b/web/src/pages/APIKeys.tsxindex 3550a589..c76d186d 100644--- a/web/src/pages/APIKeys.tsx+++ b/web/src/pages/APIKeys.tsx@@ -20,12 +20,26 @@ import {DialogHeader,DialogTitle,} from '@/components/ui/dialog'-import { Field, Input } from '@/components/form'+import { Field, Input, Select } from '@/components/form'import { CopyRow } from '@/components/copy-row'import { EmptyState } from '@/components/empty-state'import { ConfirmDialog } from '@/components/confirm-dialog'import { ResourceTable, type Column } from '@/components/resource-table'+// Days until a new key expires; 'never' leaves expires_at unset.+const EXPIRY_OPTIONS = [+ { value: 'never', label: 'Never' },+ { value: '7', label: '7 days' },+ { value: '30', label: '30 days' },+ { value: '90', label: '90 days' },+ { value: '365', label: '1 year' },+]++function expiryFromOption(option: string): string | undefined {+ if (option === 'never') return undefined+ return new Date(Date.now() + Number(option) * 86_400_000).toISOString()+}+export default function APIKeys() {const queryClient = useQueryClient()const { data: keys, isLoading } = useQuery({@@ -35,17 +49,20 @@ export default function APIKeys() {const [showCreate, setShowCreate] = useState(false)const [newKeyName, setNewKeyName] = useState('')+ const [newKeyExpiry, setNewKeyExpiry] = useState('never')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),+ mutationFn: ({ name, expiry }: { name: string; expiry: string }) =>+ createAPIKey(name, expiryFromOption(expiry)),onSuccess: (data) => {setCreatedKey(data.key)setShowCreate(false)setNewKeyName('')+ setNewKeyExpiry('never')void queryClient.invalidateQueries({ queryKey: ['api-keys'] })},onError: (error) => notifyError("Couldn't create the API key.", error),@@ -102,6 +119,18 @@ export default function APIKeys() {</span>),},+ {+ key: 'expires',+ header: 'Expires',+ cell: (k) =>+ k.expiresAt && new Date(k.expiresAt).getTime() <= Date.now() ? (+ <span className="text-status-error font-mono text-xs">Expired</span>+ ) : (+ <span className="text-muted-foreground font-mono text-xs">+ {k.expiresAt ? new Date(k.expiresAt).toLocaleString() : 'Never'}+ </span>+ ),+ },{key: 'actions',header: '',@@ -205,17 +234,32 @@ export default function APIKeys() {<formonSubmit={(e) => {e.preventDefault()- if (newKeyName.trim()) createMutation.mutate(newKeyName.trim())+ if (newKeyName.trim()) {+ createMutation.mutate({+ name: newKeyName.trim(),+ expiry: newKeyExpiry,+ })+ }}}>- <Field label="Key name" htmlFor="key-name">- <Input- id="key-name"- value={newKeyName}- onChange={(e) => setNewKeyName(e.target.value)}- placeholder="e.g. Production"- />- </Field>+ <div className="space-y-4">+ <Field label="Key name" htmlFor="key-name">+ <Input+ id="key-name"+ value={newKeyName}+ onChange={(e) => setNewKeyName(e.target.value)}+ placeholder="e.g. Production"+ />+ </Field>+ <Field label="Expires" htmlFor="key-expiry">+ <Select+ id="key-expiry"+ value={newKeyExpiry}+ onValueChange={setNewKeyExpiry}+ options={EXPIRY_OPTIONS}+ />+ </Field>+ </div><DialogFooter className="mt-4"><Buttontype="button"@@ -223,6 +267,7 @@ export default function APIKeys() {onClick={() => {setShowCreate(false)setNewKeyName('')+ setNewKeyExpiry('never')}}>Canceldiff --git a/web/src/pages/api-keys.test.tsx b/web/src/pages/api-keys.test.tsxnew file mode 100644index 00000000..24ef5f07--- /dev/null+++ b/web/src/pages/api-keys.test.tsx@@ -0,0 +1,46 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { renderToStaticMarkup } from 'react-dom/server'+import { describe, expect, it } from 'vitest'+import type { APIKey } from '@/api/client'+import APIKeys from './APIKeys'++function key(name: string, expiresAt?: string): APIKey {+ return {+ id: `key_${name}`,+ orgId: 'org_0123456789abcdef01234567',+ keyPrefix: 'osb_example',+ name,+ scopes: [],+ createdAt: '2026-07-17T00:00:00.000Z',+ ...(expiresAt ? { expiresAt } : {}),+ }+}++function renderAPIKeys(keys: APIKey[]) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },+ })+ queryClient.setQueryData(['api-keys'], keys)+ return renderToStaticMarkup(+ <QueryClientProvider client={queryClient}>+ <APIKeys />+ </QueryClientProvider>,+ )+}++describe('API keys', () => {+ it('shows when each key expires', () => {+ const future = new Date(Date.now() + 7 * 86_400_000).toISOString()+ const past = new Date(Date.now() - 60_000).toISOString()+ const markup = renderAPIKeys([+ key('Forever'),+ key('Weekly', future),+ key('Stale', past),+ ])++ expect(markup).toContain('Expires')+ expect(markup).toContain('Never')+ expect(markup).toContain(new Date(future).toLocaleString())+ expect(markup).toContain('Expired')+ })+})