Organize device inventory by customer and restrict token access to its audience
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from 'react';
|
||||
import { ApiError, record, request, tenantPath, type Session } from './api';
|
||||
import { ApiError, record, request, tenant, tenantPath, type Tenant, type Session } from './api';
|
||||
|
||||
const scopeLabels = {
|
||||
'inventory:read': 'Inventar lesen',
|
||||
@@ -27,8 +27,10 @@ export interface McpToken {
|
||||
expires_at: string;
|
||||
last_used_at: string | null;
|
||||
revoked_at: string | null;
|
||||
audience?: 'selected' | 'all';
|
||||
tenant_ids?: string[];
|
||||
}
|
||||
interface Listing { tokens: McpToken[]; allowed_scopes: Scope[]; default_scopes: Scope[] }
|
||||
interface Listing { tokens: McpToken[]; allowed_scopes: Scope[]; default_scopes: Scope[]; available_customers?: Tenant[]; can_select_all: boolean }
|
||||
|
||||
function requireContract(condition: unknown): asserts condition {
|
||||
if (!condition) throw new Error('Ungültige Antwort der Tokenverwaltung');
|
||||
@@ -46,7 +48,13 @@ 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),
|
||||
const audience = r.audience;
|
||||
if (audience !== undefined) {
|
||||
requireContract(audience === 'selected' || audience === 'all');
|
||||
requireContract(Array.isArray(r.tenant_ids) && r.tenant_ids.every(id => typeof id === 'string'));
|
||||
requireContract(audience === 'all' ? r.tenant_ids.length === 0 : r.tenant_ids.length > 0);
|
||||
}
|
||||
return { ...(audience === undefined ? {} : { audience, tenant_ids: r.tenant_ids as string[] }), 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) };
|
||||
@@ -58,7 +66,9 @@ export function mcpTokenListing(value: unknown): Listing {
|
||||
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 };
|
||||
if (r.available_customers !== undefined) requireContract(Array.isArray(r.available_customers));
|
||||
return { tokens, allowed_scopes: allowed, default_scopes: defaults,
|
||||
available_customers: r.available_customers?.map(tenant), can_select_all: r.can_select_all === true };
|
||||
}
|
||||
export function canManageMcpTokens(auth: Session, tenantId: string): boolean {
|
||||
return auth.principal.simulated === false && !!auth.csrf_token && auth.permissions?.includes('tokens:manage') === true
|
||||
@@ -95,6 +105,8 @@ function TokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }
|
||||
const [listing, setListing] = useState<Listing | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [selected, setSelected] = useState<Scope[]>([]);
|
||||
const [allCustomers, setAllCustomers] = useState(false);
|
||||
const [customerIds, setCustomerIds] = useState([tenantId]);
|
||||
const [expires, setExpires] = useState(defaultExpiry);
|
||||
const [secret, setSecret] = useState<{ token: string; tokenId: string; name: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -126,7 +138,12 @@ function TokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }
|
||||
event.preventDefault();
|
||||
if (busy || secret || !listing) return;
|
||||
let body;
|
||||
try { body = mcpTokenDraft(name, selected, listing.allowed_scopes, expires); }
|
||||
try { body = mcpTokenDraft(name, selected, listing.allowed_scopes, expires);
|
||||
if (listing.available_customers) {
|
||||
if (allCustomers && !listing.can_select_all) throw new Error('Keine Berechtigung für alle Kunden.');
|
||||
if (!allCustomers && (!customerIds.length || customerIds.some(id => !listing.available_customers!.some(c => c.tenant_id === id)))) throw new Error('Bitte mindestens einen verfügbaren Kunden auswählen.');
|
||||
body = { ...body, audience: allCustomers ? 'all' : 'selected', tenant_ids: allCustomers ? [] : customerIds };
|
||||
} }
|
||||
catch (err) { setError(err instanceof Error ? err.message : 'Tokenangaben prüfen.'); return; }
|
||||
setBusy(true); setError(''); setNotice('');
|
||||
const controller = new AbortController(); mutation.current = controller;
|
||||
@@ -137,7 +154,7 @@ function TokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }
|
||||
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());
|
||||
setName(''); setAllCustomers(false); setCustomerIds([tenantId]); 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.'));
|
||||
@@ -187,6 +204,11 @@ function TokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }
|
||||
<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>
|
||||
{listing.available_customers && <fieldset><legend>Kundenzugriff</legend>
|
||||
{listing.can_select_all && <label><input type="checkbox" checked={allCustomers} onChange={e => setAllCustomers(e.target.checked)}/>Alle aktuellen und zukünftigen Kunden</label>}
|
||||
{!allCustomers && listing.available_customers.map(customer => <label key={customer.tenant_id}><input type="checkbox" checked={customerIds.includes(customer.tenant_id)}
|
||||
onChange={e => setCustomerIds(previous => e.target.checked ? [...previous, customer.tenant_id] : previous.filter(id => id !== customer.tenant_id))}/>{customer.name}</label>)}
|
||||
</fieldset>}
|
||||
<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))}/>
|
||||
@@ -195,16 +217,17 @@ function TokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }
|
||||
</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>
|
||||
<button disabled={!selected.length || (!allCustomers && !customerIds.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>
|
||||
<thead><tr><th>Name und ID</th><th>Kundenzugriff</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.audience === 'all' ? 'Alle aktuellen und zukünftigen Kunden' : (token.tenant_ids ?? [tenantId]).map(id => listing.available_customers?.find(c => c.tenant_id === id)?.name ?? auth.tenants.find(c => c.tenant_id === id)?.name ?? id).join(', ')}</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>
|
||||
|
||||
Reference in New Issue
Block a user