Add local password-TOTP sessions and scoped revocable MCP tokens
This commit is contained in:
@@ -0,0 +1,220 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from 'react';
|
||||
import { ApiError, record, request, tenantPath, type Session } from './api';
|
||||
|
||||
const scopeLabels = {
|
||||
'inventory:read': 'Inventar lesen',
|
||||
'logs:read': 'Gespeicherte Protokolle lesen',
|
||||
'operations:read': 'Aufträge und Ergebnisse lesen',
|
||||
'operations:plan': 'Aufträge planen',
|
||||
'operations:submit': 'Aufträge zur Genehmigung einreichen',
|
||||
'jobs:cancel': 'Abbruch von Aufträgen anfordern',
|
||||
'scripts:execute': 'Skriptaufträge anfordern',
|
||||
'system:execute': 'SYSTEM-Aufträge anfordern',
|
||||
'root:execute': 'root-Aufträge anfordern',
|
||||
'updates:apply': 'Updateaufträge anfordern',
|
||||
'catalog:write': 'Katalogeinträge schreiben',
|
||||
} as const;
|
||||
type Scope = keyof typeof scopeLabels;
|
||||
const readScopes = new Set<string>(['inventory:read', 'logs:read', 'operations:read']);
|
||||
const day = 24 * 60 * 60 * 1000;
|
||||
|
||||
export interface McpToken {
|
||||
token_id: string;
|
||||
name: string;
|
||||
principal: string;
|
||||
scopes: Scope[];
|
||||
created_at: string;
|
||||
expires_at: string;
|
||||
last_used_at: string | null;
|
||||
revoked_at: string | null;
|
||||
}
|
||||
interface Listing { tokens: McpToken[]; allowed_scopes: Scope[]; default_scopes: Scope[] }
|
||||
|
||||
function requireContract(condition: unknown): asserts condition {
|
||||
if (!condition) throw new Error('Ungültige Antwort der Tokenverwaltung');
|
||||
}
|
||||
function scopes(value: unknown): Scope[] {
|
||||
requireContract(Array.isArray(value) && value.every(s => typeof s === 'string' && Object.hasOwn(scopeLabels, s))
|
||||
&& new Set(value).size === value.length);
|
||||
return [...value] as Scope[];
|
||||
}
|
||||
function timestamp(value: unknown): string {
|
||||
requireContract(typeof value === 'string' && Number.isFinite(Date.parse(value)));
|
||||
return value;
|
||||
}
|
||||
export function mcpToken(value: unknown): McpToken {
|
||||
const r = record(value);
|
||||
requireContract(typeof r.token_id === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(r.token_id)
|
||||
&& typeof r.name === 'string' && r.name.length > 0 && typeof r.principal === 'string' && r.principal.length > 0);
|
||||
return { token_id: r.token_id, name: r.name, principal: r.principal, scopes: scopes(r.scopes),
|
||||
created_at: timestamp(r.created_at), expires_at: timestamp(r.expires_at),
|
||||
last_used_at: r.last_used_at === null ? null : timestamp(r.last_used_at),
|
||||
revoked_at: r.revoked_at === null ? null : timestamp(r.revoked_at) };
|
||||
}
|
||||
export function mcpTokenListing(value: unknown): Listing {
|
||||
const r = record(value);
|
||||
requireContract(Array.isArray(r.tokens));
|
||||
const allowed = scopes(r.allowed_scopes), defaults = scopes(r.default_scopes);
|
||||
requireContract(defaults.every(s => readScopes.has(s) && allowed.includes(s)));
|
||||
const tokens = r.tokens.map(mcpToken);
|
||||
requireContract(new Set(tokens.map(t => t.token_id)).size === tokens.length);
|
||||
return { tokens, allowed_scopes: allowed, default_scopes: defaults };
|
||||
}
|
||||
export function canManageMcpTokens(auth: Session, tenantId: string): boolean {
|
||||
return auth.principal.simulated === false && !!auth.csrf_token && auth.permissions?.includes('tokens:manage') === true
|
||||
&& auth.tenants.some(tenant => tenant.tenant_id === tenantId);
|
||||
}
|
||||
export function mcpTokenDraft(name: string, selected: string[], allowed: string[], expires: string, now = Date.now()) {
|
||||
const cleanName = name.trim(), selectedScopes = scopes(selected), expiresAt = new Date(expires).getTime();
|
||||
if (!cleanName || Array.from(cleanName).length > 120 || /\p{Cc}/u.test(cleanName)) throw new Error('Ein Name mit höchstens 120 Zeichen ist erforderlich.');
|
||||
if (!selectedScopes.length || !selectedScopes.every(s => allowed.includes(s))) throw new Error('Mindestens ein verfügbares Recht auswählen.');
|
||||
if (!Number.isFinite(expiresAt) || expiresAt <= now || expiresAt > now + 365 * day) throw new Error('Das Ablaufdatum muss in den nächsten 365 Tagen liegen.');
|
||||
return { name: cleanName, scopes: selectedScopes, expires_at: new Date(expiresAt).toISOString() };
|
||||
}
|
||||
function defaultExpiry(): string {
|
||||
const value = new Date(Date.now() + 90 * day);
|
||||
return new Date(value.getTime() - value.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
|
||||
}
|
||||
function DateLabel({ value }: { value: string | null }) {
|
||||
return value ? <time dateTime={value}>{new Date(value).toLocaleString('de-DE')}</time> : <>Bisher ungenutzt</>;
|
||||
}
|
||||
function requestFailure(error: unknown, fallback: string): string {
|
||||
if (error instanceof ApiError && [401, 403].includes(error.status)) return 'Die Sitzung oder Berechtigung ist abgelaufen. Bitte erneut anmelden.';
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function McpTokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }) {
|
||||
if (!canManageMcpTokens(auth, tenantId)) return null;
|
||||
// Reset even an in-flight creation when the actual session, tenant or rights change.
|
||||
const context = JSON.stringify([tenantId, auth.principal.id, auth.csrf_token, auth.permissions]);
|
||||
return <TokenManagement key={context} auth={auth} tenantId={tenantId}/>;
|
||||
}
|
||||
|
||||
function TokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }) {
|
||||
const path = tenantPath(tenantId, '/mcp-tokens');
|
||||
const [listing, setListing] = useState<Listing | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [selected, setSelected] = useState<Scope[]>([]);
|
||||
const [expires, setExpires] = useState(defaultExpiry);
|
||||
const [secret, setSecret] = useState<{ token: string; tokenId: string; name: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [notice, setNotice] = useState('');
|
||||
const [reload, setReload] = useState(0);
|
||||
const [revokeId, setRevokeId] = useState<string | null>(null);
|
||||
const mounted = useRef(false);
|
||||
const mutation = useRef<AbortController | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => { mounted.current = false; mutation.current?.abort(); };
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
request(path, { signal: controller.signal }).then(value => {
|
||||
if (controller.signal.aborted) return;
|
||||
const next = mcpTokenListing(value);
|
||||
setListing(next);
|
||||
setSelected(current => reload === 0 ? next.default_scopes : current.filter(s => next.allowed_scopes.includes(s)));
|
||||
}).catch(err => {
|
||||
if (!controller.signal.aborted) setError(requestFailure(err, 'Die Tokenliste konnte nicht geladen werden.'));
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [path, reload]);
|
||||
|
||||
async function create(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (busy || secret || !listing) return;
|
||||
let body;
|
||||
try { body = mcpTokenDraft(name, selected, listing.allowed_scopes, expires); }
|
||||
catch (err) { setError(err instanceof Error ? err.message : 'Tokenangaben prüfen.'); return; }
|
||||
setBusy(true); setError(''); setNotice('');
|
||||
const controller = new AbortController(); mutation.current = controller;
|
||||
try {
|
||||
const reply = record(await request(path, { body, csrf: auth.csrf_token, signal: controller.signal }));
|
||||
if (!mounted.current) return;
|
||||
const metadata = mcpToken(reply);
|
||||
requireContract(typeof reply.token === 'string' && reply.token.length >= 32 && reply.token.length <= 512);
|
||||
setSecret({ token: reply.token, tokenId: metadata.token_id, name: metadata.name });
|
||||
setListing(current => current && { ...current, tokens: [metadata, ...current.tokens] });
|
||||
setName(''); setSelected(listing.default_scopes); setExpires(defaultExpiry());
|
||||
} catch (err) {
|
||||
if (mounted.current) {
|
||||
setError(requestFailure(err, 'Die Erstellung konnte nicht bestätigt werden. Prüfen Sie vor einem neuen Versuch die aktualisierte Tokenliste.'));
|
||||
setReload(value => value + 1);
|
||||
}
|
||||
} finally { if (mounted.current) setBusy(false); }
|
||||
}
|
||||
async function revoke(token: McpToken) {
|
||||
if (busy) return;
|
||||
setBusy(true); setError(''); setNotice('');
|
||||
const controller = new AbortController(); mutation.current = controller;
|
||||
try {
|
||||
const metadata = mcpToken(await request(`${path}/${encodeURIComponent(token.token_id)}/revoke`,
|
||||
{ body: {}, csrf: auth.csrf_token, signal: controller.signal }));
|
||||
if (!mounted.current) return;
|
||||
requireContract(metadata.token_id === token.token_id && metadata.revoked_at !== null);
|
||||
setListing(current => current && { ...current, tokens: current.tokens.map(row => row.token_id === metadata.token_id ? metadata : row) });
|
||||
if (secret?.tokenId === token.token_id) setSecret(null);
|
||||
setRevokeId(null); setNotice(`Token „${metadata.name}“ widerrufen.`);
|
||||
} catch (err) {
|
||||
if (mounted.current) {
|
||||
setError(requestFailure(err, 'Der Widerruf konnte nicht bestätigt werden. Der aktuelle Tokenstatus wird erneut geladen.'));
|
||||
setReload(value => value + 1);
|
||||
}
|
||||
} finally { if (mounted.current) setBusy(false); }
|
||||
}
|
||||
async function copy() {
|
||||
if (!secret) return;
|
||||
try { await navigator.clipboard.writeText(secret.token); if (mounted.current) setNotice('Token kopiert.'); }
|
||||
catch { if (mounted.current) setError('Kopieren ist im Browser nicht verfügbar. Sie können den angezeigten Token markieren und kopieren.'); }
|
||||
}
|
||||
|
||||
return <section aria-label="MCP-Tokens">
|
||||
<h2>MCP-Tokens</h2>
|
||||
<p>Erstellen Sie einen Zugang für Ihren MCP-Client. Skript- und Wartungsaufträge benötigen weiterhin die Genehmigung in der WebUI.</p>
|
||||
{error && <p className="error" role="alert">{error}</p>}
|
||||
{notice && <p role="status">{notice}</p>}
|
||||
{secret && <article aria-label="Neu erstelltes MCP-Token">
|
||||
<h3>Token für {secret.name}</h3>
|
||||
<p>Kopieren Sie diesen Token jetzt. Nach dem Schließen dieser Anzeige ist der Geheimwert nicht erneut abrufbar.</p>
|
||||
<label>Einmaliger Token<textarea readOnly rows={3} value={secret.token} autoComplete="off" spellCheck={false}/></label>
|
||||
<button type="button" onClick={() => void copy()}>Token kopieren</button>
|
||||
<button type="button" onClick={() => { setSecret(null); setNotice(''); }}>Tokenanzeige schließen</button>
|
||||
</article>}
|
||||
{!listing ? <p role="status">Tokenliste wird geladen …</p> : <>
|
||||
<form onSubmit={create}>
|
||||
<fieldset disabled={busy || secret !== null || listing.allowed_scopes.length === 0}>
|
||||
<legend>Neues MCP-Token</legend>
|
||||
<label>Name<input value={name} onChange={e => setName(e.target.value)} maxLength={240} required autoComplete="off" placeholder="Zum Beispiel mein MCP-Client"/></label>
|
||||
<fieldset><legend>Rechte</legend>
|
||||
{listing.allowed_scopes.map(scope => <label key={scope}>
|
||||
<input type="checkbox" checked={selected.includes(scope)} onChange={e => setSelected(current => e.target.checked ? [...current, scope] : current.filter(s => s !== scope))}/>
|
||||
{scopeLabels[scope]} <code>{scope}</code>
|
||||
</label>)}
|
||||
</fieldset>
|
||||
<label>Ablaufdatum und Uhrzeit<input type="datetime-local" required value={expires} onChange={e => setExpires(e.target.value)}/></label>
|
||||
<small>Ortszeit dieses Browsers. Höchstens 365 Tage Gültigkeit.</small>
|
||||
<button disabled={!selected.length} type="submit">Token erstellen</button>
|
||||
</fieldset>
|
||||
{listing.allowed_scopes.length === 0 && <p>Ihre Mitgliedschaft bietet keine Rechte für ein MCP-Token.</p>}
|
||||
</form>
|
||||
<h3>Ausgestellte Tokens</h3>
|
||||
<button type="button" disabled={busy} onClick={() => { setError(''); setReload(value => value + 1); }}>Tokenliste aktualisieren</button>
|
||||
{!listing.tokens.length ? <p>Es wurden noch keine Tokens erstellt.</p> : <div className="table"><table>
|
||||
<thead><tr><th>Name und ID</th><th>Rechte</th><th>Erstellt und zuletzt verwendet</th><th>Gültigkeit</th><th>Verwaltung</th></tr></thead>
|
||||
<tbody>{listing.tokens.map(token => <tr key={token.token_id}>
|
||||
<td>{token.name}<small><code>{token.token_id}</code></small><small>{token.principal}</small></td>
|
||||
<td>{token.scopes.map(scope => <small key={scope}>{scopeLabels[scope]} <code>{scope}</code></small>)}</td>
|
||||
<td><DateLabel value={token.created_at}/><small>Zuletzt verwendet</small><DateLabel value={token.last_used_at}/></td>
|
||||
<td>{token.revoked_at ? <>Widerrufen am <DateLabel value={token.revoked_at}/></> : <>{Date.parse(token.expires_at) <= Date.now() ? 'Abgelaufen am ' : 'Läuft ab am '}<DateLabel value={token.expires_at}/></>}</td>
|
||||
<td>{token.revoked_at === null && (revokeId === token.token_id ? <>
|
||||
<p>Zugang für „{token.name}“ jetzt beenden?</p>
|
||||
<button type="button" className="danger" disabled={busy} onClick={() => void revoke(token)}>Widerruf bestätigen</button>
|
||||
<button type="button" disabled={busy} onClick={() => setRevokeId(null)}>Abbrechen</button>
|
||||
</> : <button type="button" disabled={busy} onClick={() => setRevokeId(token.token_id)}>Widerrufen</button>)}</td>
|
||||
</tr>)}</tbody>
|
||||
</table></div>}
|
||||
</>}
|
||||
</section>;
|
||||
}
|
||||
Reference in New Issue
Block a user