4bdc6c66c7
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.
308 lines
9.6 KiB
TypeScript
308 lines
9.6 KiB
TypeScript
/**
|
|
* 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;
|