Add account API key management

This commit is contained in:
Mike Cao committed 2026-09-01 21:50:07 -07:00
1 parent 98b824ce48
commit f1c5b4f7bb
32 files changed
+1618 -15

No files matched your search

+8 -7
View File
@@ -2,7 +2,7 @@ import { Column, Row, Text, Tooltip, TooltipTrigger } from '@umami/react-zen';
import { IconLabel } from '@/components/common/IconLabel';
import Link from '@/components/common/Link';
import { useMessages, useNavigation } from '@/components/hooks';
import { ArrowLeft, Settings2, ShieldCheck, UserCircle, Users } from '@/components/icons';
import { ArrowLeft, KeyRound, Settings2, ShieldCheck, UserCircle, Users } from '@/components/icons';
export function SettingsNav({
isCollapsed,
@@ -16,7 +16,7 @@ export function SettingsNav({
const items = [
{
label: t(labels.application),
label: t(labels.settings),
items: [
{
id: 'preferences',
@@ -24,11 +24,6 @@ export function SettingsNav({
path: renderUrl('/settings/preferences'),
icon: <Settings2 />,
},
],
},
{
label: t(labels.account),
items: [
{
id: 'profile',
label: t(labels.profile),
@@ -47,6 +42,12 @@ export function SettingsNav({
path: renderUrl('/settings/security'),
icon: <ShieldCheck />,
},
{
id: 'api-keys',
label: t(labels.apiKeys),
path: renderUrl('/settings/api-keys'),
icon: <KeyRound />,
},
],
},
];
@@ -0,0 +1,30 @@
import { Button, Dialog, DialogTrigger, Icon, Modal, Text } from '@umami/react-zen';
import { useMessages, useModified } from '@/components/hooks';
import { Plus } from '@/components/icons';
import { ApiKeyAddForm } from './ApiKeyAddForm';
export function ApiKeyAddButton({ onSave }: { onSave?: () => void }) {
const { t, labels } = useMessages();
const { touch } = useModified();
const handleSave = () => {
touch('api-keys');
onSave?.();
};
return (
<DialogTrigger>
<Button variant="primary">
<Icon>
<Plus />
</Icon>
<Text>{t(labels.createApiKey)}</Text>
</Button>
<Modal>
<Dialog title={t(labels.createApiKey)} style={{ width: 480 }}>
{({ close }) => <ApiKeyAddForm onSave={handleSave} onClose={close} />}
</Dialog>
</Modal>
</DialogTrigger>
);
}
@@ -0,0 +1,70 @@
import {
Alert,
AlertTitle,
Button,
Column,
Form,
FormButtons,
FormField,
FormSubmitButton,
Icon,
Row,
TextField,
} from '@umami/react-zen';
import { useState } from 'react';
import { CopyButton } from '@/components/common/CopyButton';
import { useMessages, useUpdateQuery } from '@/components/hooks';
import { AlertTriangle } from '@/components/icons';
export function ApiKeyAddForm({ onSave, onClose }: { onSave: () => void; onClose: () => void }) {
const { t, labels, messages, getErrorMessage } = useMessages();
const { mutateAsync, error, isPending } = useUpdateQuery('/me/api-keys');
const [createdKey, setCreatedKey] = useState<string | null>(null);
const handleSubmit = async (data: any) => {
await mutateAsync(data, {
onSuccess: async result => {
setCreatedKey(result.key);
onSave?.();
},
});
};
if (createdKey) {
return (
<Column gap="4">
<Alert>
<Icon>
<AlertTriangle />
</Icon>
<AlertTitle>{t(messages.apiKeyCreated)}</AlertTitle>
</Alert>
<Row alignItems="center" gap="2">
<TextField value={createdKey} isReadOnly style={{ flex: 1, fontFamily: 'monospace' }} />
<CopyButton value={createdKey} label={t(labels.copy)} />
</Row>
<Row justifyContent="flex-end">
<Button variant="primary" onPress={onClose}>
{t(labels.close)}
</Button>
</Row>
</Column>
);
}
return (
<Form onSubmit={handleSubmit} error={getErrorMessage(error)}>
<FormField name="name" label={t(labels.name)}>
<TextField autoComplete="off" autoFocus />
</FormField>
<FormButtons>
<Button isDisabled={isPending} onPress={onClose}>
{t(labels.cancel)}
</Button>
<FormSubmitButton variant="primary" isDisabled={isPending}>
{t(labels.save)}
</FormSubmitButton>
</FormButtons>
</Form>
);
}
@@ -0,0 +1,47 @@
import { ConfirmationForm } from '@/components/common/ConfirmationForm';
import { useDeleteQuery, useMessages, useModified } from '@/components/hooks';
import { Trash } from '@/components/icons';
import { DialogButton } from '@/components/input/DialogButton';
export function ApiKeyDeleteButton({
keyId,
name,
onSave,
}: {
keyId: string;
name: string;
onSave?: () => void;
}) {
const { t, labels, messages, getErrorMessage } = useMessages();
const { mutateAsync, isPending, error } = useDeleteQuery(`/me/api-keys/${keyId}`);
const { touch } = useModified();
const handleConfirm = async (close: () => void) => {
await mutateAsync(null, {
onSuccess: () => {
touch('api-keys');
onSave?.();
close();
},
});
};
return (
<DialogButton icon={<Trash />} title={t(labels.confirm)} variant="quiet" width="400px">
{({ close }) => (
<ConfirmationForm
message={t.rich(messages.confirmRemove, {
target: name,
b: chunks => <b>{chunks}</b>,
})}
isLoading={isPending}
error={getErrorMessage(error)}
onConfirm={handleConfirm.bind(null, close)}
onClose={close}
buttonLabel={t(labels.delete)}
buttonVariant="danger"
/>
)}
</DialogButton>
);
}
@@ -0,0 +1,30 @@
'use client';
import { Column } from '@umami/react-zen';
import { PageBody } from '@/components/common/PageBody';
import { PageHeader } from '@/components/common/PageHeader';
import { Panel } from '@/components/common/Panel';
import { useConfig, useMessages } from '@/components/hooks';
import { ApiKeyAddButton } from './ApiKeyAddButton';
import { ApiKeysTable } from './ApiKeysTable';
export function ApiKeysPage() {
const { t, labels } = useMessages();
const { cloudMode } = useConfig();
if (cloudMode) {
return null;
}
return (
<PageBody>
<Column gap="6">
<PageHeader title={t(labels.apiKeys)}>
<ApiKeyAddButton />
</PageHeader>
<Panel>
<ApiKeysTable />
</Panel>
</Column>
</PageBody>
);
}
@@ -0,0 +1,46 @@
import { DataColumn, DataTable, Text } from '@umami/react-zen';
import { DateDistance } from '@/components/common/DateDistance';
import { EmptyPlaceholder } from '@/components/common/EmptyPlaceholder';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import { type ApiKeyData, useApiKeysQuery, useMessages } from '@/components/hooks';
import { KeyRound } from '@/components/icons';
import { ApiKeyDeleteButton } from './ApiKeyDeleteButton';
export function ApiKeysTable() {
const { t, labels, messages } = useMessages();
const { data, isLoading, error } = useApiKeysQuery();
return (
<LoadingPanel
data={data}
isLoading={isLoading}
error={error}
isEmpty={!data?.length}
renderEmpty={() => (
<EmptyPlaceholder icon={<KeyRound />} description={t(messages.noApiKeys)} />
)}
>
<DataTable data={data ?? []}>
<DataColumn id="name" label={t(labels.name)} />
<DataColumn id="keyPrefix" label={t(labels.apiKey)}>
{(row: ApiKeyData) => <code>{row.keyPrefix}…</code>}
</DataColumn>
<DataColumn id="createdAt" label={t(labels.created)}>
{(row: ApiKeyData) => <DateDistance date={new Date(row.createdAt)} />}
</DataColumn>
<DataColumn id="lastUsedAt" label={t(labels.lastUsed)}>
{(row: ApiKeyData) =>
row.lastUsedAt ? (
<DateDistance date={new Date(row.lastUsedAt)} />
) : (
<Text color="muted">{t(labels.never)}</Text>
)
}
</DataColumn>
<DataColumn id="action" label=" " align="end" width="48px">
{(row: ApiKeyData) => <ApiKeyDeleteButton keyId={row.id} name={row.name} />}
</DataColumn>
</DataTable>
</LoadingPanel>
);
}
+10
View File
@@ -0,0 +1,10 @@
import type { Metadata } from 'next';
import { ApiKeysPage } from './ApiKeysPage';
export default function () {
return <ApiKeysPage />;
}
export const metadata: Metadata = {
title: 'API keys',
};
@@ -0,0 +1,80 @@
// Generated by `pnpm openapi:contracts`. Do not edit directly.
import type { ZodOpenApiOperationObject } from 'zod-openapi';
import { defineOperation } from '@/openapi/operation';
const operation1 = defineOperation({
method: 'delete',
path: '/api/me/api-keys/{keyId}',
audience: 'public',
auth: 'bearer',
operation: {
operationId: 'deleteMeApiKeysKeyId',
summary: 'Delete me api keys key id',
tags: ['Account'],
parameters: [
{
name: 'keyId',
in: 'path',
required: true,
schema: {
type: 'string',
},
},
],
responses: {
'200': {
description: 'The operation completed successfully.',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
ok: {
const: true,
},
},
required: ['ok'],
},
},
},
},
'401': {
description: 'Unauthorized.',
content: {
'application/json': {
example: {
error: {
message: 'Unauthorized.',
code: 'unauthorized',
status: 401,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
'404': {
description: 'Not found.',
content: {
'application/json': {
example: {
error: {
message: 'Not found.',
code: 'not-found',
status: 404,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
},
} as ZodOpenApiOperationObject,
});
export const operations = [operation1] as const;
@@ -0,0 +1,61 @@
import { beforeEach, expect, test, vi } from 'vitest';
import { parseRequest } from '@/lib/request';
import { DELETE } from './route';
const mocks = vi.hoisted(() => ({
deleteApiKey: vi.fn(),
}));
vi.mock('@/lib/request', () => ({
parseRequest: vi.fn(),
}));
vi.mock('@/queries/prisma/apiKey', () => ({
deleteApiKey: mocks.deleteApiKey,
}));
const parseRequestMock = vi.mocked(parseRequest);
function deleteRequest(keyId = 'key-1') {
return DELETE(new Request(`http://localhost/api/me/api-keys/${keyId}`, { method: 'DELETE' }), {
params: Promise.resolve({ keyId }),
});
}
beforeEach(() => {
vi.unstubAllEnvs();
vi.stubEnv('CLOUD_MODE', '');
parseRequestMock.mockReset();
mocks.deleteApiKey.mockReset();
parseRequestMock.mockResolvedValue({
auth: { user: { id: 'user-1' } },
error: undefined,
});
});
test('DELETE removes a key owned by the current user', async () => {
mocks.deleteApiKey.mockResolvedValue(1);
const response = await deleteRequest();
expect(response.status).toBe(200);
expect(mocks.deleteApiKey).toHaveBeenCalledWith('key-1', 'user-1');
});
test('DELETE returns 404 when the key does not belong to the user', async () => {
mocks.deleteApiKey.mockResolvedValue(0);
const response = await deleteRequest('someone-elses-key');
expect(response.status).toBe(404);
});
test('DELETE returns 404 in cloud mode', async () => {
vi.stubEnv('CLOUD_MODE', '1');
const response = await deleteRequest();
expect(response.status).toBe(404);
expect(mocks.deleteApiKey).not.toHaveBeenCalled();
});
+26
View File
@@ -0,0 +1,26 @@
import { isApiKeyEnabled } from '@/lib/api-key';
import { parseRequest } from '@/lib/request';
import { notFound, ok } from '@/lib/response';
import { deleteApiKey } from '@/queries/prisma/apiKey';
export async function DELETE(request: Request, { params }: { params: Promise<{ keyId: string }> }) {
const { auth, error } = await parseRequest(request);
if (error) {
return error();
}
if (!isApiKeyEnabled()) {
return notFound();
}
const { keyId } = await params;
const count = await deleteApiKey(keyId, auth.user.id);
if (!count) {
return notFound();
}
return ok();
}
@@ -0,0 +1,198 @@
// Generated by `pnpm openapi:contracts`. Do not edit directly.
import type { ZodOpenApiOperationObject } from 'zod-openapi';
import { defineOperation } from '@/openapi/operation';
const operation1 = defineOperation({
method: 'get',
path: '/api/me/api-keys',
audience: 'public',
auth: 'bearer',
operation: {
operationId: 'getMeApiKeys',
summary: 'Get me api keys',
tags: ['Account'],
responses: {
'200': {
description: 'The operation completed successfully.',
content: {
'application/json': {
schema: {
type: 'array',
items: {
type: 'object',
properties: {
id: {
type: 'string',
},
createdAt: {
type: 'string',
format: 'date-time',
},
name: {
type: 'string',
},
keyPrefix: {
type: 'string',
},
lastUsedAt: {
type: 'string',
format: 'date-time',
},
},
required: ['id', 'createdAt', 'name', 'keyPrefix', 'lastUsedAt'],
},
},
},
},
},
'401': {
description: 'Unauthorized.',
content: {
'application/json': {
example: {
error: {
message: 'Unauthorized.',
code: 'unauthorized',
status: 401,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
'404': {
description: 'Not found.',
content: {
'application/json': {
example: {
error: {
message: 'Not found.',
code: 'not-found',
status: 404,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
},
} as ZodOpenApiOperationObject,
});
const operation2 = defineOperation({
method: 'post',
path: '/api/me/api-keys',
audience: 'public',
auth: 'bearer',
operation: {
operationId: 'postMeApiKeys',
summary: 'Create or update me api keys',
tags: ['Account'],
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
properties: {
name: {
minimum: 1,
maximum: 255,
},
},
required: ['name'],
},
},
},
},
responses: {
'200': {
description: 'The operation completed successfully.',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
key: {
type: 'string',
},
id: {
type: 'string',
},
createdAt: {
type: 'string',
format: 'date-time',
},
name: {
type: 'string',
},
keyPrefix: {
type: 'string',
},
},
required: ['key', 'id', 'createdAt', 'name', 'keyPrefix'],
},
},
},
},
'400': {
description: 'Bad request.',
content: {
'application/json': {
example: {
error: {
message: 'Bad request.',
code: 'bad-request',
status: 400,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
'401': {
description: 'Unauthorized.',
content: {
'application/json': {
example: {
error: {
message: 'Unauthorized.',
code: 'unauthorized',
status: 401,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
'404': {
description: 'Not found.',
content: {
'application/json': {
example: {
error: {
message: 'Not found.',
code: 'not-found',
status: 404,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
},
} as ZodOpenApiOperationObject,
});
export const operations = [operation1, operation2] as const;
+100
View File
@@ -0,0 +1,100 @@
import { beforeEach, expect, test, vi } from 'vitest';
import { parseRequest } from '@/lib/request';
import { GET, POST } from './route';
const mocks = vi.hoisted(() => ({
createApiKey: vi.fn(),
getUserApiKeys: vi.fn(),
}));
vi.mock('@/lib/request', () => ({
parseRequest: vi.fn(),
}));
vi.mock('@/queries/prisma/apiKey', () => ({
createApiKey: mocks.createApiKey,
getUserApiKeys: mocks.getUserApiKeys,
}));
const parseRequestMock = vi.mocked(parseRequest);
beforeEach(() => {
vi.unstubAllEnvs();
vi.stubEnv('CLOUD_MODE', '');
parseRequestMock.mockReset();
mocks.createApiKey.mockReset();
mocks.getUserApiKeys.mockReset();
parseRequestMock.mockResolvedValue({
auth: { user: { id: 'user-1' } },
body: { name: 'CI pipeline' },
error: undefined,
});
});
test('GET returns the current user api keys', async () => {
const keys = [{ id: 'key-1', name: 'CI pipeline', keyPrefix: 'umami_abcdefgh' }];
mocks.getUserApiKeys.mockResolvedValue(keys as any);
const response = await GET(new Request('http://localhost/api/me/api-keys'));
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual(keys);
expect(mocks.getUserApiKeys).toHaveBeenCalledWith('user-1');
});
test('GET returns 404 in cloud mode', async () => {
vi.stubEnv('CLOUD_MODE', '1');
const response = await GET(new Request('http://localhost/api/me/api-keys'));
expect(response.status).toBe(404);
expect(mocks.getUserApiKeys).not.toHaveBeenCalled();
});
test('GET returns the auth error when unauthenticated', async () => {
parseRequestMock.mockResolvedValue({
auth: null,
error: () => new Response(null, { status: 401 }),
});
const response = await GET(new Request('http://localhost/api/me/api-keys'));
expect(response.status).toBe(401);
});
test('POST creates a key, stores only the hash, and returns the plaintext once', async () => {
mocks.createApiKey.mockImplementation(async data => ({
id: data.id,
name: data.name,
keyPrefix: data.keyPrefix,
createdAt: new Date('2026-01-01T00:00:00Z'),
}));
const response = await POST(new Request('http://localhost/api/me/api-keys', { method: 'POST' }));
expect(response.status).toBe(200);
const body = await response.json();
expect(body.key).toMatch(/^umami_[0-9a-zA-Z]{32}$/);
expect(body.name).toBe('CI pipeline');
expect(body.keyPrefix).toBe(body.key.slice(0, 14));
expect(body).not.toHaveProperty('keyHash');
const stored = mocks.createApiKey.mock.calls[0][0];
expect(stored.userId).toBe('user-1');
expect(stored.keyHash).not.toBe(body.key);
expect(stored.keyHash).toHaveLength(128);
expect(stored).not.toHaveProperty('key');
});
test('POST returns 404 in cloud mode', async () => {
vi.stubEnv('CLOUD_MODE', '1');
const response = await POST(new Request('http://localhost/api/me/api-keys', { method: 'POST' }));
expect(response.status).toBe(404);
expect(mocks.createApiKey).not.toHaveBeenCalled();
});
+49
View File
@@ -0,0 +1,49 @@
import { z } from 'zod';
import { generateApiKey, getApiKeyPrefix, hashApiKey, isApiKeyEnabled } from '@/lib/api-key';
import { uuid } from '@/lib/crypto';
import { parseRequest } from '@/lib/request';
import { json, notFound } from '@/lib/response';
import { createApiKey, getUserApiKeys } from '@/queries/prisma/apiKey';
export async function GET(request: Request) {
const { auth, error } = await parseRequest(request);
if (error) {
return error();
}
if (!isApiKeyEnabled()) {
return notFound();
}
return json(await getUserApiKeys(auth.user.id));
}
export async function POST(request: Request) {
const schema = z.object({
name: z.string().trim().min(1).max(255),
});
const { auth, body, error } = await parseRequest(request, schema);
if (error) {
return error();
}
if (!isApiKeyEnabled()) {
return notFound();
}
const key = generateApiKey();
const apiKey = await createApiKey({
id: uuid(),
userId: auth.user.id,
name: body.name,
keyHash: hashApiKey(key),
keyPrefix: getApiKeyPrefix(key),
});
// The plaintext key is only returned once, at creation time.
return json({ ...apiKey, key });
}
+12
View File
@@ -38,6 +38,18 @@ const operation1 = defineOperation({
},
required: ['id', 'username', 'role', 'isAdmin'],
},
apiKey: {
type: 'object',
properties: {
id: {
type: 'string',
},
name: {
type: 'string',
},
},
required: ['id', 'name'],
},
shareToken: {
type: 'object',
properties: {
@@ -770,6 +770,46 @@ const operation2 = defineOperation({
required: ['id', 'userId', 'otp', 'expiresAt'],
},
},
apiKeys: {
type: 'array',
items: {
type: 'object',
properties: {
id: {
type: 'string',
},
userId: {
type: 'string',
},
createdAt: {
type: 'string',
format: 'date-time',
},
name: {
type: 'string',
},
keyHash: {
type: 'string',
},
keyPrefix: {
type: 'string',
},
lastUsedAt: {
type: 'string',
format: 'date-time',
},
},
required: [
'id',
'userId',
'createdAt',
'name',
'keyHash',
'keyPrefix',
'lastUsedAt',
],
},
},
_count: {
type: 'object',
properties: {
@@ -806,6 +846,9 @@ const operation2 = defineOperation({
twoFactorRateLimit: {
type: 'number',
},
apiKeys: {
type: 'number',
},
},
required: [
'websites',
@@ -819,6 +862,7 @@ const operation2 = defineOperation({
'twoFactorBackupCodes',
'twoFactorOtpUseds',
'twoFactorRateLimit',
'apiKeys',
],
},
},
@@ -840,6 +884,7 @@ const operation2 = defineOperation({
'boards',
'twoFactorBackupCodes',
'twoFactorOtpUseds',
'apiKeys',
'_count',
],
},