feat(api-tokens): UI fuer Bearer-Tokens — Modul 3/16 des UI-Backlogs
Backend existierte vollstaendig (POST create mit Einmal-Plaintext-Anzeige, GET list ohne Hashes, DELETE revoke; mcp:read/mcp:write via mcp_server- Plugin registriert), Frontend hatte 0% Abdeckung. - api/apiTokens.ts: TanStack-Hooks (useApiTokens, create mit ApiTokenCreated-Response inkl. Einmal-Token, revoke) - pages/ApiTokens.tsx: Token-Karten (Name, Scope-Badges, Ablauf, zuletzt genutzt, Abgelaufen-Badge), Create-Dialog (Name, Scopes als Komma-Liste, optionale Gueltigkeit in Tagen), EINMALIGE Plaintext-Anzeige mit Copy-Button und Warnung, Revoke mit Confirm — Aktionen hinter mcp:write gegated - Platzierung: Settings-Subpage /settings/api-tokens (statisch, Core-Route) + Settings-Nav-Item (true-core-settings-Muster) - i18n apiTokens.* de/en Verifikation: Vitest 8/8 (Rendering, Scopes, Ablauf-Badge, Permission-Gating, Create-Flow mit Reveal-Dialog, Revoke) · tsc exit 0 · production build exit 0.
This commit is contained in:
@@ -0,0 +1,157 @@
|
|||||||
|
/**
|
||||||
|
* ApiTokens page tests — Bearer token management (module 3/16).
|
||||||
|
*
|
||||||
|
* Covers: rendering, token cards with scopes/expiry, create flow with
|
||||||
|
* ONE-TIME plaintext reveal, copy button, revoke with confirmation,
|
||||||
|
* permission gating (mcp:write), empty and error states.
|
||||||
|
*/
|
||||||
|
import React from 'react';
|
||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||||
|
import { MemoryRouter } from 'react-router-dom';
|
||||||
|
import { ApiTokensPage } from '@/pages/ApiTokens';
|
||||||
|
import type { ApiTokenInfo } from '@/api/apiTokens';
|
||||||
|
|
||||||
|
const createMut = vi.fn().mockImplementation((_payload, opts) => {
|
||||||
|
opts?.onSuccess?.({
|
||||||
|
id: 'tk-new', token: 'secret-plaintext-token', name: 'CI', scopes: [],
|
||||||
|
expires_at: null, last_used_at: null, created_at: '2026-09-13T09:00:00Z',
|
||||||
|
});
|
||||||
|
return Promise.resolve({});
|
||||||
|
});
|
||||||
|
const revokeMut = vi.fn().mockResolvedValue({});
|
||||||
|
|
||||||
|
const makeToken = (overrides: Partial<ApiTokenInfo> = {}): ApiTokenInfo => ({
|
||||||
|
id: 'tk-1',
|
||||||
|
name: 'CI Integration',
|
||||||
|
scopes: ['contacts:read', 'mail:read'],
|
||||||
|
expires_at: null,
|
||||||
|
last_used_at: null,
|
||||||
|
created_at: '2026-09-01T10:00:00Z',
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
let mockItems: ApiTokenInfo[] = [];
|
||||||
|
let mockCanWrite = true;
|
||||||
|
let mockError = false;
|
||||||
|
|
||||||
|
vi.mock('@/api/apiTokens', () => ({
|
||||||
|
useApiTokens: () => ({
|
||||||
|
data: { items: mockItems, total: mockItems.length },
|
||||||
|
isLoading: false,
|
||||||
|
isError: mockError,
|
||||||
|
isFetching: false,
|
||||||
|
refetch: vi.fn(),
|
||||||
|
}),
|
||||||
|
useCreateApiToken: () => ({
|
||||||
|
mutate: createMut,
|
||||||
|
isPending: false,
|
||||||
|
}),
|
||||||
|
useRevokeApiToken: () => ({
|
||||||
|
mutate: revokeMut,
|
||||||
|
isPending: false,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('@/hooks/usePermission', () => ({
|
||||||
|
usePermission: () => ({
|
||||||
|
hasPermission: (perm: string) => mockCanWrite || perm !== 'mcp:write',
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
function renderPage() {
|
||||||
|
return render(
|
||||||
|
<MemoryRouter>
|
||||||
|
<ApiTokensPage />
|
||||||
|
</MemoryRouter>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
mockItems = [];
|
||||||
|
mockCanWrite = true;
|
||||||
|
mockError = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ApiTokensPage', () => {
|
||||||
|
it('renders the page with title', () => {
|
||||||
|
renderPage();
|
||||||
|
expect(screen.getByTestId('api-tokens-page')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows empty state when no tokens exist', () => {
|
||||||
|
renderPage();
|
||||||
|
expect(screen.getByTestId('api-tokens-empty')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows error state on load failure', () => {
|
||||||
|
mockError = true;
|
||||||
|
renderPage();
|
||||||
|
expect(screen.getByTestId('api-tokens-error')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders token cards with scopes', () => {
|
||||||
|
mockItems = [makeToken()];
|
||||||
|
renderPage();
|
||||||
|
expect(screen.getByTestId('api-token-card-tk-1')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('CI Integration')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('contacts:read')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('mail:read')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows expired badge for expired tokens', () => {
|
||||||
|
mockItems = [makeToken({ expires_at: '2020-01-01T00:00:00Z' })];
|
||||||
|
renderPage();
|
||||||
|
expect(screen.getByTestId(`api-token-expired-tk-1`)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hides create + revoke without mcp:write permission', () => {
|
||||||
|
mockItems = [makeToken()];
|
||||||
|
mockCanWrite = false;
|
||||||
|
const { container } = renderPage();
|
||||||
|
expect(screen.queryByTestId('api-token-create-open')).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId('api-token-revoke-tk-1')).not.toBeInTheDocument();
|
||||||
|
expect(container).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates a token and reveals the plaintext ONCE with copy button', async () => {
|
||||||
|
renderPage();
|
||||||
|
fireEvent.click(screen.getByTestId('api-token-create-open'));
|
||||||
|
expect(screen.getByTestId('api-token-create-submit')).toBeInTheDocument();
|
||||||
|
|
||||||
|
const nameInput = screen.getByLabelText(/name/i, { selector: 'input' }) as HTMLInputElement;
|
||||||
|
fireEvent.change(nameInput, { target: { value: 'CI' } });
|
||||||
|
fireEvent.change(screen.getByLabelText(/scopes/i, { selector: 'input' }), {
|
||||||
|
target: { value: 'contacts:read, mail:read' },
|
||||||
|
});
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByTestId('api-token-create-submit'));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(createMut).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
name: 'CI',
|
||||||
|
scopes: ['contacts:read', 'mail:read'],
|
||||||
|
}),
|
||||||
|
expect.anything(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ONE-TIME reveal dialog shows the plaintext token
|
||||||
|
expect(await screen.findByTestId('api-token-plaintext')).toHaveTextContent(
|
||||||
|
'secret-plaintext-token',
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('api-token-copy')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('revokes a token after confirmation', async () => {
|
||||||
|
mockItems = [makeToken()];
|
||||||
|
window.confirm = vi.fn(() => true);
|
||||||
|
renderPage();
|
||||||
|
fireEvent.click(screen.getByTestId('api-token-revoke-tk-1'));
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(revokeMut).toHaveBeenCalledWith('tk-1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
/**
|
||||||
|
* API Tokens client — Bearer tokens for programmatic access.
|
||||||
|
*
|
||||||
|
* Backend: /api/v1/tokens (create, list, revoke).
|
||||||
|
* The plaintext token is returned ONCE at creation — never stored.
|
||||||
|
* Permissions: mcp:read (list) / mcp:write (create, revoke).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { apiGet, apiPost, apiDelete } from '@/api/client';
|
||||||
|
|
||||||
|
export interface ApiTokenInfo {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
scopes: string[];
|
||||||
|
expires_at: string | null;
|
||||||
|
last_used_at: string | null;
|
||||||
|
created_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiTokenListResponse {
|
||||||
|
items: ApiTokenInfo[];
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Response of the create endpoint — includes the plaintext token ONCE. */
|
||||||
|
export interface ApiTokenCreated extends ApiTokenInfo {
|
||||||
|
token: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiTokenCreatePayload {
|
||||||
|
name: string;
|
||||||
|
scopes?: string[];
|
||||||
|
expires_in_days?: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Query hooks ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useApiTokens() {
|
||||||
|
return useQuery<ApiTokenListResponse>({
|
||||||
|
queryKey: ['api-tokens'],
|
||||||
|
queryFn: () => apiGet<ApiTokenListResponse>('/tokens'),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Mutation hooks ──────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useCreateApiToken() {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
return useMutation<ApiTokenCreated, Error, ApiTokenCreatePayload>({
|
||||||
|
mutationFn: (data) => apiPost<ApiTokenCreated>('/tokens', data),
|
||||||
|
onSuccess: () => {
|
||||||
|
qc.invalidateQueries({ queryKey: ['api-tokens'] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRevokeApiToken() {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
return useMutation<void, Error, string>({
|
||||||
|
mutationFn: (tokenId) => apiDelete(`/tokens/${tokenId}`),
|
||||||
|
onSuccess: () => {
|
||||||
|
qc.invalidateQueries({ queryKey: ['api-tokens'] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1659,5 +1659,30 @@
|
|||||||
"deleteConfirm": "Diese Delegation wirklich loeschen?",
|
"deleteConfirm": "Diese Delegation wirklich loeschen?",
|
||||||
"empty": "Keine Delegationen in dieser Ansicht.",
|
"empty": "Keine Delegationen in dieser Ansicht.",
|
||||||
"loadError": "Delegationen konnten nicht geladen werden."
|
"loadError": "Delegationen konnten nicht geladen werden."
|
||||||
|
},
|
||||||
|
"apiTokens": {
|
||||||
|
"title": "API-Tokens",
|
||||||
|
"create": "Token erstellen",
|
||||||
|
"createTitle": "API-Token erstellen",
|
||||||
|
"createSubmit": "Erstellen",
|
||||||
|
"name": "Name",
|
||||||
|
"namePlaceholder": "z.B. CI-Integration",
|
||||||
|
"scopes": "Scopes",
|
||||||
|
"scopesPlaceholder": "z.B. contacts:read, mail:read",
|
||||||
|
"scopesHelper": "Kommagetrennte Liste. Leer = alle Scopes.",
|
||||||
|
"expiresInDays": "Gueltigkeit (Tage, optional)",
|
||||||
|
"expiresPlaceholder": "z.B. 30",
|
||||||
|
"revealTitle": "Token erstellt",
|
||||||
|
"revealWarning": "Dies ist der einzige Moment, in dem das Token im Klartext sichtbar ist. Jetzt kopieren und sicher speichern — spaeter nicht mehr abrufbar.",
|
||||||
|
"copy": "Kopieren",
|
||||||
|
"done": "Fertig",
|
||||||
|
"created": "Erstellt:",
|
||||||
|
"expires": "Laeuft ab:",
|
||||||
|
"lastUsed": "Zuletzt genutzt:",
|
||||||
|
"expiredBadge": "Abgelaufen",
|
||||||
|
"revoke": "Widerrufen",
|
||||||
|
"revokeConfirm": "Token '{{name}}' wirklich widerrufen? Anwendungen damit verlieren sofort den Zugriff.",
|
||||||
|
"empty": "Keine API-Tokens vorhanden.",
|
||||||
|
"loadError": "API-Tokens konnten nicht geladen werden."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1659,5 +1659,30 @@
|
|||||||
"deleteConfirm": "Really delete this delegation?",
|
"deleteConfirm": "Really delete this delegation?",
|
||||||
"empty": "No delegations in this view.",
|
"empty": "No delegations in this view.",
|
||||||
"loadError": "Failed to load delegations."
|
"loadError": "Failed to load delegations."
|
||||||
|
},
|
||||||
|
"apiTokens": {
|
||||||
|
"title": "API Tokens",
|
||||||
|
"create": "Create token",
|
||||||
|
"createTitle": "Create API token",
|
||||||
|
"createSubmit": "Create",
|
||||||
|
"name": "Name",
|
||||||
|
"namePlaceholder": "e.g. CI integration",
|
||||||
|
"scopes": "Scopes",
|
||||||
|
"scopesPlaceholder": "e.g. contacts:read, mail:read",
|
||||||
|
"scopesHelper": "Comma-separated list. Empty = all scopes.",
|
||||||
|
"expiresInDays": "Validity (days, optional)",
|
||||||
|
"expiresPlaceholder": "e.g. 30",
|
||||||
|
"revealTitle": "Token created",
|
||||||
|
"revealWarning": "This is the only moment the plaintext token is visible. Copy and store it safely now — it cannot be retrieved later.",
|
||||||
|
"copy": "Copy",
|
||||||
|
"done": "Done",
|
||||||
|
"created": "Created:",
|
||||||
|
"expires": "Expires:",
|
||||||
|
"lastUsed": "Last used:",
|
||||||
|
"expiredBadge": "Expired",
|
||||||
|
"revoke": "Revoke",
|
||||||
|
"revokeConfirm": "Really revoke token '{{name}}'? Applications using it lose access immediately.",
|
||||||
|
"empty": "No API tokens yet.",
|
||||||
|
"loadError": "Failed to load API tokens."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,307 @@
|
|||||||
|
/**
|
||||||
|
* API Tokens settings page — Bearer tokens for programmatic access
|
||||||
|
* (UI-Backlog module 3/16).
|
||||||
|
*
|
||||||
|
* Backend: /api/v1/tokens (create, list, revoke). The plaintext token is
|
||||||
|
* returned ONCE at creation — shown once with copy button, never again.
|
||||||
|
* Permissions: mcp:read (list) / mcp:write (create, revoke).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import React, { useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import {
|
||||||
|
KeyRound,
|
||||||
|
Plus,
|
||||||
|
Trash2,
|
||||||
|
Copy,
|
||||||
|
Check,
|
||||||
|
Inbox,
|
||||||
|
AlertTriangle,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import {
|
||||||
|
useApiTokens,
|
||||||
|
useCreateApiToken,
|
||||||
|
useRevokeApiToken,
|
||||||
|
type ApiTokenInfo,
|
||||||
|
} from '@/api/apiTokens';
|
||||||
|
import { usePermission } from '@/hooks/usePermission';
|
||||||
|
import { Card } from '@/components/ui/Card';
|
||||||
|
import { Button } from '@/components/ui/Button';
|
||||||
|
import { Modal } from '@/components/ui/Modal';
|
||||||
|
import { Input } from '@/components/ui/Input';
|
||||||
|
import { Badge } from '@/components/ui/Badge';
|
||||||
|
|
||||||
|
function formatDateTime(iso: string | null): string {
|
||||||
|
if (!iso) return '—';
|
||||||
|
try {
|
||||||
|
return new Date(iso).toLocaleString();
|
||||||
|
} catch {
|
||||||
|
return iso;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function TokenCard({
|
||||||
|
token,
|
||||||
|
canWrite,
|
||||||
|
onRevoke,
|
||||||
|
isMutating,
|
||||||
|
}: {
|
||||||
|
token: ApiTokenInfo;
|
||||||
|
canWrite: boolean;
|
||||||
|
onRevoke: (token: ApiTokenInfo) => void;
|
||||||
|
isMutating: boolean;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const expired =
|
||||||
|
token.expires_at !== null && new Date(token.expires_at) < new Date();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="p-4" data-testid={`api-token-card-${token.id}`}>
|
||||||
|
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
|
<KeyRound className="w-4 h-4 text-primary-600 flex-shrink-0" aria-hidden="true" />
|
||||||
|
<span className="text-sm font-medium text-secondary-900 dark:text-secondary-100">
|
||||||
|
{token.name}
|
||||||
|
</span>
|
||||||
|
{expired && (
|
||||||
|
<span data-testid={`api-token-expired-${token.id}`}>
|
||||||
|
<Badge variant="danger">{t('apiTokens.expiredBadge')}</Badge>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 flex flex-wrap gap-1">
|
||||||
|
{token.scopes.map((scope) => (
|
||||||
|
<Badge key={scope} variant="secondary">{scope}</Badge>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 text-xs text-secondary-500 dark:text-secondary-400">
|
||||||
|
{t('apiTokens.created')} {formatDateTime(token.created_at)} ·{' '}
|
||||||
|
{t('apiTokens.expires')} {formatDateTime(token.expires_at)} ·{' '}
|
||||||
|
{t('apiTokens.lastUsed')} {formatDateTime(token.last_used_at)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{canWrite && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onRevoke(token)}
|
||||||
|
disabled={isMutating}
|
||||||
|
aria-label={t('apiTokens.revoke')}
|
||||||
|
data-testid={`api-token-revoke-${token.id}`}
|
||||||
|
className="text-danger-600 hover:text-danger-700"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4" aria-hidden="true" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CreateTokenDialog({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
onSubmit,
|
||||||
|
isSubmitting,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onSubmit: (payload: { name: string; scopes?: string[]; expires_in_days?: number | null }) => void;
|
||||||
|
isSubmitting: boolean;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [name, setName] = useState('');
|
||||||
|
const [scopes, setScopes] = useState('');
|
||||||
|
const [expiresInDays, setExpiresInDays] = useState('');
|
||||||
|
|
||||||
|
const parsedScopes = scopes
|
||||||
|
.split(',')
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
const parsedDays = expiresInDays ? parseInt(expiresInDays, 10) : null;
|
||||||
|
const valid = name.trim().length > 0 && (parsedDays === null || (!isNaN(parsedDays) && parsedDays > 0));
|
||||||
|
|
||||||
|
const submit = () => {
|
||||||
|
if (!valid) return;
|
||||||
|
onSubmit({
|
||||||
|
name: name.trim(),
|
||||||
|
scopes: parsedScopes,
|
||||||
|
expires_in_days: parsedDays,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal open={open} onClose={onClose} title={t('apiTokens.createTitle')}>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<Input
|
||||||
|
label={t('apiTokens.name')}
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
required
|
||||||
|
placeholder={t('apiTokens.namePlaceholder')}
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label={t('apiTokens.scopes')}
|
||||||
|
value={scopes}
|
||||||
|
onChange={(e) => setScopes(e.target.value)}
|
||||||
|
placeholder={t('apiTokens.scopesPlaceholder')}
|
||||||
|
helperText={t('apiTokens.scopesHelper')}
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label={t('apiTokens.expiresInDays')}
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
value={expiresInDays}
|
||||||
|
onChange={(e) => setExpiresInDays(e.target.value)}
|
||||||
|
placeholder={t('apiTokens.expiresPlaceholder')}
|
||||||
|
/>
|
||||||
|
<div className="flex justify-end gap-2 pt-2">
|
||||||
|
<Button variant="ghost" onClick={onClose}>{t('common.cancel')}</Button>
|
||||||
|
<Button onClick={submit} disabled={!valid || isSubmitting} data-testid="api-token-create-submit">
|
||||||
|
{t('apiTokens.createSubmit')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TokenRevealDialog({
|
||||||
|
token,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
token: string | null;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
|
||||||
|
const copy = async () => {
|
||||||
|
if (!token) return;
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(token);
|
||||||
|
setCopied(true);
|
||||||
|
setTimeout(() => setCopied(false), 2000);
|
||||||
|
} catch {
|
||||||
|
// clipboard API unavailable — user can select manually
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal open={!!token} onClose={onClose} title={t('apiTokens.revealTitle')}>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<p className="text-sm text-warning-700 dark:text-warning-300" role="alert">
|
||||||
|
{t('apiTokens.revealWarning')}
|
||||||
|
</p>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<code
|
||||||
|
className="flex-1 block break-all rounded-md bg-secondary-100 dark:bg-secondary-800 px-3 py-2 text-xs font-mono"
|
||||||
|
data-testid="api-token-plaintext"
|
||||||
|
>
|
||||||
|
{token}
|
||||||
|
</code>
|
||||||
|
<Button variant="ghost" size="sm" onClick={copy} aria-label={t('apiTokens.copy')} data-testid="api-token-copy">
|
||||||
|
{copied
|
||||||
|
? <Check className="w-4 h-4 text-success-600" aria-hidden="true" />
|
||||||
|
: <Copy className="w-4 h-4" aria-hidden="true" />}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<Button onClick={onClose} data-testid="api-token-reveal-done">{t('apiTokens.done')}</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ApiTokensPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [showCreate, setShowCreate] = useState(false);
|
||||||
|
const [revealedToken, setRevealedToken] = useState<string | null>(null);
|
||||||
|
const { data, isLoading, isError } = useApiTokens();
|
||||||
|
const createMut = useCreateApiToken();
|
||||||
|
const revokeMut = useRevokeApiToken();
|
||||||
|
const { hasPermission } = usePermission();
|
||||||
|
|
||||||
|
const canWrite = hasPermission('mcp:write');
|
||||||
|
const isMutating = createMut.isPending || revokeMut.isPending;
|
||||||
|
|
||||||
|
const handleSubmit = (payload: { name: string; scopes?: string[]; expires_in_days?: number | null }) => {
|
||||||
|
createMut.mutate(payload, {
|
||||||
|
onSuccess: (result) => {
|
||||||
|
setShowCreate(false);
|
||||||
|
setRevealedToken(result.token);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRevoke = (token: ApiTokenInfo) => {
|
||||||
|
if (window.confirm(t('apiTokens.revokeConfirm', { name: token.name }))) {
|
||||||
|
revokeMut.mutate(token.id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const items = data?.items ?? [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-3xl mx-auto p-4 sm:p-6 space-y-4" data-testid="api-tokens-page">
|
||||||
|
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<h1 className="text-2xl font-bold text-secondary-900 dark:text-secondary-100">
|
||||||
|
{t('apiTokens.title')}
|
||||||
|
</h1>
|
||||||
|
{canWrite && (
|
||||||
|
<Button onClick={() => setShowCreate(true)} data-testid="api-token-create-open">
|
||||||
|
<Plus className="w-4 h-4 mr-2" aria-hidden="true" />
|
||||||
|
{t('apiTokens.create')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isLoading && (
|
||||||
|
<div className="flex items-center justify-center min-h-[30vh]" role="status" data-testid="api-tokens-loading">
|
||||||
|
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500" aria-hidden="true" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isError && (
|
||||||
|
<Card className="p-6 flex items-center gap-3 text-danger-600" data-testid="api-tokens-error">
|
||||||
|
<AlertTriangle className="w-5 h-5" aria-hidden="true" />
|
||||||
|
<span>{t('apiTokens.loadError')}</span>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isLoading && !isError && items.length === 0 && (
|
||||||
|
<Card className="p-8 flex flex-col items-center gap-3 text-secondary-500" data-testid="api-tokens-empty">
|
||||||
|
<Inbox className="w-10 h-10" aria-hidden="true" />
|
||||||
|
<p>{t('apiTokens.empty')}</p>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="space-y-3">
|
||||||
|
{items.map((token) => (
|
||||||
|
<TokenCard
|
||||||
|
key={token.id}
|
||||||
|
token={token}
|
||||||
|
canWrite={canWrite}
|
||||||
|
onRevoke={handleRevoke}
|
||||||
|
isMutating={isMutating}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<CreateTokenDialog
|
||||||
|
open={showCreate}
|
||||||
|
onClose={() => setShowCreate(false)}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
isSubmitting={createMut.isPending}
|
||||||
|
/>
|
||||||
|
<TokenRevealDialog
|
||||||
|
token={revealedToken}
|
||||||
|
onClose={() => setRevealedToken(null)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ApiTokensPage;
|
||||||
@@ -48,6 +48,7 @@ export function SettingsPage() {
|
|||||||
{ to: '/settings/webhooks', label: 'Webhooks', icon: '\ud83d\udd14' },
|
{ to: '/settings/webhooks', label: 'Webhooks', icon: '\ud83d\udd14' },
|
||||||
{ to: '/settings/workspaces', label: 'Workspaces', icon: '\ud83d\udd58\ufe0f' },
|
{ to: '/settings/workspaces', label: 'Workspaces', icon: '\ud83d\udd58\ufe0f' },
|
||||||
{ to: '/settings/backup', label: 'Backup & Restore', icon: '\ud83d\udcbe' },
|
{ to: '/settings/backup', label: 'Backup & Restore', icon: '\ud83d\udcbe' },
|
||||||
|
{ to: '/settings/api-tokens', label: 'API-Tokens', icon: '\ud83d\udd11' },
|
||||||
];
|
];
|
||||||
|
|
||||||
const existingPaths = new Set(hardcodedNavItems.map(item => item.to));
|
const existingPaths = new Set(hardcodedNavItems.map(item => item.to));
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ const CustomFieldsPage = React.lazy(() => import('@/pages/CustomFields').then(m
|
|||||||
const ActivityTimelinePage = React.lazy(() => import('@/pages/ActivityTimeline').then(m => ({ default: m.ActivityTimelinePage })));
|
const ActivityTimelinePage = React.lazy(() => import('@/pages/ActivityTimeline').then(m => ({ default: m.ActivityTimelinePage })));
|
||||||
const ApprovalsPage = React.lazy(() => import('@/pages/Approvals').then(m => ({ default: m.ApprovalsPage })));
|
const ApprovalsPage = React.lazy(() => import('@/pages/Approvals').then(m => ({ default: m.ApprovalsPage })));
|
||||||
const DelegationsPage = React.lazy(() => import('@/pages/Delegations').then(m => ({ default: m.DelegationsPage })));
|
const DelegationsPage = React.lazy(() => import('@/pages/Delegations').then(m => ({ default: m.DelegationsPage })));
|
||||||
|
const ApiTokensPage = React.lazy(() => import('@/pages/ApiTokens').then(m => ({ default: m.ApiTokensPage })));
|
||||||
const SettingsWebhooksPage = React.lazy(() => import('@/pages/SettingsWebhooks').then(m => ({ default: m.SettingsWebhooksPage })));
|
const SettingsWebhooksPage = React.lazy(() => import('@/pages/SettingsWebhooks').then(m => ({ default: m.SettingsWebhooksPage })));
|
||||||
const SettingsBackupPage = React.lazy(() => import('@/pages/SettingsBackup').then(m => ({ default: m.SettingsBackupPage })));
|
const SettingsBackupPage = React.lazy(() => import('@/pages/SettingsBackup').then(m => ({ default: m.SettingsBackupPage })));
|
||||||
const WorkspaceManagerPage = React.lazy(() => import('@/pages/SettingsWorkspaces').then(m => ({ default: m.WorkspaceManagerPage })));
|
const WorkspaceManagerPage = React.lazy(() => import('@/pages/SettingsWorkspaces').then(m => ({ default: m.WorkspaceManagerPage })));
|
||||||
@@ -204,6 +205,7 @@ const router = createBrowserRouter([
|
|||||||
{ path: 'webhooks', element: withSuspense(<SettingsWebhooksPage />) },
|
{ path: 'webhooks', element: withSuspense(<SettingsWebhooksPage />) },
|
||||||
{ path: 'workspaces', element: withSuspense(<WorkspaceManagerPage />) },
|
{ path: 'workspaces', element: withSuspense(<WorkspaceManagerPage />) },
|
||||||
{ path: 'backup', element: withSuspense(<SettingsBackupPage />) },
|
{ path: 'backup', element: withSuspense(<SettingsBackupPage />) },
|
||||||
|
{ path: 'api-tokens', element: withSuspense(<ApiTokensPage />) },
|
||||||
{ path: 'rechte', element: <PermissionRoute permission="settings:read">{withSuspense(<SettingsRechtePage />)}</PermissionRoute> },
|
{ path: 'rechte', element: <PermissionRoute permission="settings:read">{withSuspense(<SettingsRechtePage />)}</PermissionRoute> },
|
||||||
// Phase Q2: plugin settings sub-pages render with bare sub-segments
|
// Phase Q2: plugin settings sub-pages render with bare sub-segments
|
||||||
{ path: '*', element: <ErrorBoundary>{<PluginRouteRenderer variant="settings" />}</ErrorBoundary> },
|
{ path: '*', element: <ErrorBoundary>{<PluginRouteRenderer variant="settings" />}</ErrorBoundary> },
|
||||||
|
|||||||
Reference in New Issue
Block a user