Postfach: Verbindungsdaten mit Apple-QR-Code wie in KeyHelp

Neuer optionaler Connector-Aufruf children.connectionInfo (nur email, ohne Passwort).
KeyHelp: Server = Hostname des Panels (oder Einstellung mailServer), feste Ports,
Apple-Profil über autoconfig-apple.<Hauptdomain> (Subdomains → Hauptdomain).
API: GET /resources/:id/children/email/:childId/connection (wer Postfächer sieht).
Web: Button „Verbindungsdaten“ je Postfach mit QR-Codes und manuellen Daten.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Claude (KI) 2026-10-16 11:35:37 +02:00
parent f475e8bd36
commit 6a7b5446d5
5 changed files with 116 additions and 6 deletions

View file

@ -235,6 +235,18 @@ export const resourcesModule: KcModule = {
try { const { connector, ctx } = await loadInstance(r.instance_id, req.correlationId); return await connector.children!.list(ctx, r.external_ref, kind as ChildKind); }
catch (e) { return providerError(e); }
});
/** Verbindungsdaten eines Postfachs (Server, Ports, Einrichtungsprofile) – lesend, ohne Passwort; wer die Postfächer sehen darf, darf auch das. */
app.get('/resources/:id/children/:kind/:childId/connection', { config: rl(60, '1 minute') }, async (req) => {
const a = requireAuth(req);
const { id, kind, childId } = kindParam.extend({ childId: z.string().min(1).max(40) }).parse(req.params);
const r = await loadResource(id);
if (!r || !access(a, r) || !childCaps(r).includes('children.read') || kind !== 'email') throw notFound();
try {
const { connector, ctx } = await loadInstance(r.instance_id, req.correlationId);
if (!connector.children?.connectionInfo) throw notFound();
return await connector.children.connectionInfo(ctx, { parentRef: r.external_ref, kind, id: childId });
} catch (e) { return providerError(e); }
});
/** Änderung an einem Unterobjekt: läuft als persistenter Auftrag; Passwörter nur verschlüsselt im Auftrag, nach der Ausführung entfernt. */
app.post('/resources/:id/children/:kind', { config: rl(30, '1 minute') }, async (req, reply) => {
const a = requireAuth(req);

View file

@ -1,5 +1,6 @@
'use client';
import { useCallback, useEffect, useState, type FormEvent } from 'react';
import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react';
import QRCode from 'qrcode';
import { api, errMsg } from '@/lib/api';
import { copyText } from '@/lib/clipboard';
import { generatePassword, MIN_CHILD_PASSWORD } from '@/lib/password';
@ -56,15 +57,57 @@ function PasswordField({ id, value, onChange, label = 'Passwort' }: { id: string
{value && <button type="button" className="btn small" onClick={async () => setCopied(await copyText(value))}>{copied ? 'Kopiert ✓' : 'Kopieren'}</button>}</div></div>);
}
interface ConnInfo { host: string; alternativeHosts: string[]; usernames: string[]; ports: { protocol: string; port: number; security: 'tls' | 'starttls' }[]; profiles: { protocol: string; label: string; url: string }[] }
/** Verbindungsdaten eines Postfachs wie in KeyHelp: Apple-Profile (Link + QR-Code) und Daten für die manuelle Einrichtung. */
function ConnectionDialog({ resourceId, child, onClose }: { resourceId: string; child: Child; onClose: () => void }) {
const [info, setInfo] = useState<ConnInfo | null>(null); const [err, setErr] = useState(''); const [qr, setQr] = useState<Record<string, string>>({}); const [copied, setCopied] = useState('');
const closeRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
closeRef.current?.focus(); const esc = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); }; window.addEventListener('keydown', esc);
api<ConnInfo>('GET', `/resources/${resourceId}/children/email/${encodeURIComponent(child.id)}/connection`).then(async (i) => {
setInfo(i); setQr(Object.fromEntries(await Promise.all(i.profiles.map(async (p) => [p.protocol, await QRCode.toDataURL(p.url, { margin: 2, width: 200 })] as const))));
}).catch((e) => setErr(errMsg(e)));
return () => window.removeEventListener('keydown', esc);
}, [resourceId, child.id, onClose]);
const copy = async (k: string, v: string) => { if (await copyText(v)) { setCopied(k); setTimeout(() => setCopied(''), 1500); } };
const ports = (proto: string, sec: 'tls' | 'starttls') => info?.ports.filter((p) => sec === p.security && (proto === 'SMTP' ? p.protocol === 'SMTP' : p.protocol !== 'SMTP')).map((p) => <div key={p.protocol + p.port}><strong>{p.port}</strong> {p.protocol}</div>);
return (<div role="dialog" aria-modal="true" aria-labelledby="cd-t" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.45)', display: 'grid', placeItems: 'center', padding: 16, zIndex: 50 }}>
<div className="card" style={{ maxWidth: 640, width: '100%', maxHeight: 'calc(100vh - 32px)', overflowY: 'auto' }}>
<div className="row between"><h2 id="cd-t" style={{ margin: 0 }}>Verbindungsdaten</h2><button ref={closeRef} className="btn small" onClick={onClose}>Schließen</button></div>
<p className="mono" style={{ marginTop: 4 }}>{child.name}</p>
{err && <Alert kind="err">{err}</Alert>}
{!info && !err && <p className="muted" role="status">Wird beim Anbieter gelesen …</p>}
{info && <>
<p>E-Mail-Programme wie Outlook, Thunderbird oder Apple Mail können das Postfach automatisch einrichten: Adresse und Passwort eingeben, den Rest holt das Programm selbst vom Server.</p>
<h3>Apple-Geräte (iPhone, iPad, Mac)</h3>
<p className="small">Den QR-Code mit der Kamera scannen oder den Link in Safari öffnen, das Profil laden und unter Einstellungen installieren. Das Passwort wird bei der Installation abgefragt.</p>
<div className="row" style={{ gap: 16, alignItems: 'flex-start', flexWrap: 'wrap' }}>{info.profiles.map((p) => <div key={p.protocol} style={{ textAlign: 'center' }}>
{qr[p.protocol] && <img src={qr[p.protocol]} width={200} height={200} alt={`QR-Code: ${p.label}`} style={{ background: '#fff', borderRadius: 8, display: 'block' }} />}
<a className="small" href={p.url} target="_blank" rel="noopener noreferrer">{p.label}</a></div>)}</div>
<h3>Manuelle Einrichtung</h3>
<div className="tablewrap"><table><thead><tr><th><span className="sr">Angabe</span></th><th>Posteingang</th><th>Postausgang</th></tr></thead><tbody>
<tr><th scope="row">Server</th><td colSpan={2}><span className="mono">{info.host}</span> <button className="btn small" onClick={() => void copy('host', info.host)}>{copied === 'host' ? 'Kopiert ✓' : 'Kopieren'}</button></td></tr>
{info.alternativeHosts.length > 0 && <tr><th scope="row">Alternative Server</th><td colSpan={2} className="mono">{info.alternativeHosts.map((h) => <div key={h}>{h}</div>)}</td></tr>}
<tr><th scope="row">Benutzername</th><td colSpan={2}>{info.usernames.map((u) => <div key={u}><span className="mono">{u}</span> <button className="btn small" onClick={() => void copy(u, u)}>{copied === u ? 'Kopiert ✓' : 'Kopieren'}</button></div>)}</td></tr>
<tr><th scope="row">Passwort</th><td colSpan={2} className="small">Das Passwort des Postfachs (wird hier nicht angezeigt).</td></tr>
<tr><th scope="row">Port SSL/TLS (empfohlen)</th><td>{ports('IN', 'tls')}</td><td>{ports('SMTP', 'tls')}</td></tr>
<tr><th scope="row">Port STARTTLS</th><td>{ports('IN', 'starttls')}</td><td>{ports('SMTP', 'starttls')}</td></tr>
</tbody></table></div>
<p className="small muted">Postausgang: Anmeldung erforderlich, gleicher Benutzername und gleiches Passwort wie beim Posteingang.</p>
</>}
</div></div>);
}
export function HostingPanel({ resourceId, canLogin }: { resourceId: string; canLogin: boolean }) {
const [kinds, setKinds] = useState<Kinds | null>(null); const [kind, setKind] = useState<Kind>('domain'); const [rows, setRows] = useState<Child[] | null>(null); const [err, setErr] = useState('');
const [msg, setMsg] = useState<{ k: 'ok' | 'err' | 'info'; t: string } | null>(null); const [adding, setAdding] = useState(false); const [del, setDel] = useState<string | null>(null); const [busy, setBusy] = useState(false); const [pw, setPw] = useState('');
const [domains, setDomains] = useState<Child[]>([]);
const [domains, setDomains] = useState<Child[]>([]); const [conn, setConn] = useState<Child | null>(null);
useEffect(() => { api<Kinds>('GET', `/resources/${resourceId}/children`).then((k) => { setKinds(k); if (k.kinds[0]) setKind(k.kinds[0].kind); }).catch((e) => setErr(errMsg(e))); }, [resourceId]);
const load = useCallback(() => { setRows(null); setErr(''); api<Child[]>('GET', `/resources/${resourceId}/children/${kind}`).then(setRows).catch((e) => { setErr(errMsg(e)); setRows([]); }); }, [resourceId, kind]);
useEffect(() => { if (kinds) load(); }, [kinds, load]);
useEffect(() => { api<Child[]>('GET', `/resources/${resourceId}/children/domain`).then(setDomains).catch(() => setDomains([])); }, [resourceId]);
const canWrite = kinds?.kinds.find((k) => k.kind === kind)?.canWrite ?? false;
const canWrite = kinds?.kinds.find((k) => k.kind === kind)?.canWrite ?? false; const showConn = kind === 'email'; const closeConn = useCallback(() => setConn(null), []); const actions = canWrite || showConn;
async function submit(op: 'create' | 'update' | 'delete', data: Record<string, unknown>, opts: { id?: string; password?: string; okText: string }) {
setBusy(true); setMsg(null);
@ -100,7 +143,7 @@ export function HostingPanel({ resourceId, canLogin }: { resourceId: string; can
{kind === 'ftp' && <><div className="cols"><Field id="hp-fu" label="Benutzername (optional, sonst automatisch)"><input id="hp-fu" name="user" pattern="[A-Za-z0-9._-]{1,32}" /></Field><Field id="hp-fh" label="Verzeichnis" hint="Beginnt mit /www/ oder /files"><input id="hp-fh" name="home" defaultValue="/www/" /></Field><Field id="hp-fd" label="Beschreibung"><input id="hp-fd" name="desc" maxLength={200} /></Field></div><PasswordField id="hp-pw" value={pw} onChange={setPw} /></>}
<div className="row"><button className="btn primary" type="submit" disabled={busy}>{busy ? 'Bitte warten …' : 'Anlegen'}</button><button className="btn" type="button" onClick={() => setAdding(false)}>Abbrechen</button></div></form>}
{rows === null ? <p className="muted" role="status">Wird beim Anbieter gelesen …</p> : rows.length === 0 && !err ? <Empty title="Keine Einträge" /> : (
<div className="tablewrap"><table><thead><tr><th>Name</th><th>Details</th><th>Status</th>{canWrite && <th><span className="sr">Aktionen</span></th>}</tr></thead><tbody>
<div className="tablewrap"><table><thead><tr><th>Name</th><th>Details</th><th>Status</th>{actions && <th><span className="sr">Aktionen</span></th>}</tr></thead><tbody>
{rows.map((r) => { const [c, i, l] = STATE[r.state] ?? ['info', '○', r.state]; const d = r.details; return (<tr key={r.id}>
<td className="mono">{r.name}</td>
<td className="small">{r.kind === 'domain' && <>{d.subdomain ? 'Subdomain' : d.system ? 'System-Domain' : 'Hauptdomain'} · PHP {d.phpVersion} · {d.letsEncrypt ? 'Let’s Encrypt' : 'kein Let’s Encrypt'}{d.forceHttps ? ' · HTTPS erzwungen' : ''}</>}
@ -111,8 +154,9 @@ export function HostingPanel({ resourceId, canLogin }: { resourceId: string; can
{r.kind === 'dirprotect' && <>Benutzer <span className="mono">{d.username ?? '–'}</span>{d.realm ? ` · „${d.realm}“` : ''}{d.exceptions?.length ? ` · Ausnahmen: ${d.exceptions.join(', ')}` : ''}</>}
{r.kind === 'certificate' && <>{d.issuer ?? '–'} · gültig bis {r.validUntil ? fmtDate(r.validUntil) : '–'} · {(d.securedDomains ?? []).join(', ')}</>}</td>
<td><span className={`badge ${c}`}><span aria-hidden="true">{i}</span>{l}</span></td>
{canWrite && <td>{del === r.id ? <div role="alertdialog" aria-label="Löschen bestätigen"><p className="small" style={{ margin: '0 0 8px' }}><strong>„{r.name}“ endgültig löschen?</strong>{r.kind !== 'domain' ? ' Die Daten gehen verloren.' : ' Zugehörige Inhalte können verloren gehen.'}</p><div className="row"><button className="btn small danger" disabled={busy} onClick={() => submit('delete', {}, { id: r.id, okText: 'Wurde gelöscht.' })}>Ja, löschen</button><button className="btn small" onClick={() => setDel(null)}>Abbrechen</button></div></div>
: <div className="row" style={{ gap: 8 }}><button className="btn small danger" onClick={() => setDel(r.id)} disabled={busy || (r.kind === 'domain' && d.system)}>Löschen</button></div>}</td>}</tr>); })}</tbody></table></div>)}
{actions && <td>{canWrite && del === r.id ? <div role="alertdialog" aria-label="Löschen bestätigen"><p className="small" style={{ margin: '0 0 8px' }}><strong>„{r.name}“ endgültig löschen?</strong>{r.kind !== 'domain' ? ' Die Daten gehen verloren.' : ' Zugehörige Inhalte können verloren gehen.'}</p><div className="row"><button className="btn small danger" disabled={busy} onClick={() => submit('delete', {}, { id: r.id, okText: 'Wurde gelöscht.' })}>Ja, löschen</button><button className="btn small" onClick={() => setDel(null)}>Abbrechen</button></div></div>
: <div className="row" style={{ gap: 8 }}>{showConn && <button className="btn small" onClick={() => setConn(r)}>Verbindungsdaten</button>}{canWrite && <button className="btn small danger" onClick={() => setDel(r.id)} disabled={busy || (r.kind === 'domain' && d.system)}>Löschen</button>}</div>}</td>}</tr>); })}</tbody></table></div>)}
</div>
{conn && <ConnectionDialog resourceId={resourceId} child={conn} onClose={closeConn} />}
</>);
}

View file

@ -207,6 +207,31 @@ export function createKeyHelpConnector(deps: KeyHelpDeps = {}): Connector {
if (!created || typeof created.id !== 'number') throw new ConnectorError('INVALID_RESPONSE', 'keine ID');
return { child: mapChild(kind, await call<Row>(ctx, 'GET', `/${path}/${created.id}`)) };
},
/**
* Wie das Fenster "Verbindungsdaten" in KeyHelp: Server = Hostname des Panels (bzw. Einstellung mailServer), feste Ports,
* Apple-Profil über autoconfig-apple.<Hauptdomain>. KeyHelp liefert das Profil nur per http aus; es enthält kein Passwort.
*/
async connectionInfo(ctx, req) {
if (req.kind !== 'email') throw new ConnectorError('UNSUPPORTED', 'Verbindungsdaten gibt es nur für Postfächer');
const row = owned(await optional(call<Row>(ctx, 'GET', `/emails/${encodeURIComponent(str(req.id, 'id', 40))}`)), req.parentRef);
const ascii = String(row.email ?? ''); const utf8 = String(row.email_utf8 || ascii);
if (!ascii.includes('@')) throw new ConnectorError('INVALID_RESPONSE', 'Postfach ohne Adresse');
let dom = owned(await optional(call<Row>(ctx, 'GET', `/domains/name/${encodeURIComponent(ascii.split('@')[1]!)}`)), req.parentRef);
for (let i = 0; i < 5 && Number(dom.id_parent_domain) > 0; i++) { const p = await optional(call<Row>(ctx, 'GET', `/domains/${encodeURIComponent(String(dom.id_parent_domain))}`)); if (!p || String(p.id_user) !== req.parentRef) break; dom = p; }
const main = String(dom.domain ?? '').toLowerCase(); if (!DOMAIN_RE.test(main)) throw new ConnectorError('INVALID_RESPONSE', 'Hauptdomain ungültig');
const hostOk = (h: unknown) => (typeof h === 'string' && DOMAIN_RE.test(h.trim()) ? h.trim().toLowerCase() : undefined);
let host = hostOk(ctx.config.mailServer);
if (!host) { try { host = hostOk((await call<{ meta?: { hostname?: string } }>(ctx, 'GET', '/server'))?.meta?.hostname); } catch { /* Ersatz unten */ } }
host ??= new URL(base(ctx)).hostname;
const alternativeHosts = String(ctx.config.mailServerAlternatives ?? '').split(/[\s,]+/).map(hostOk).filter((h): h is string => !!h && h !== host);
const profile = (protocol: 'imap' | 'pop3') => `http://autoconfig-apple.${main}/setup.mobileconfig?email=${encodeURIComponent(utf8)}&protocol=${protocol}`;
return {
host, alternativeHosts, usernames: utf8 !== ascii ? [utf8, ascii] : [ascii],
ports: [{ protocol: 'IMAP', port: 993, security: 'tls' }, { protocol: 'POP3', port: 995, security: 'tls' }, { protocol: 'SMTP', port: 465, security: 'tls' },
{ protocol: 'IMAP', port: 143, security: 'starttls' }, { protocol: 'POP3', port: 110, security: 'starttls' }, { protocol: 'SMTP', port: 587, security: 'starttls' }],
profiles: [{ protocol: 'imap', label: 'IMAP-Konto einrichten', url: profile('imap') }, { protocol: 'pop3', label: 'POP3-Konto einrichten', url: profile('pop3') }],
};
},
};
void NAMEKEY;
@ -219,6 +244,8 @@ export function createKeyHelpConnector(deps: KeyHelpDeps = {}): Connector {
{ name: 'apiKey', label: 'API-Schlüssel', secret: true, required: true, help: 'In KeyHelp unter Konfiguration → API anlegen und auf die IP-Adresse dieses Servers beschränken.' },
{ name: 'verifyTls', label: 'Zertifikat von KeyHelp prüfen', advanced: true, options: [{ value: 'true', label: 'Ja, prüfen (empfohlen)' }, { value: 'false', label: 'Nein, nicht prüfen (unsicher)' }], help: 'Nur ändern, wenn KeyHelp ein selbstsigniertes Zertifikat verwendet. Besser ist es, statt „nicht prüfen“ den Fingerabdruck unten einzutragen.' },
{ name: 'tlsFingerprint', label: 'Zertifikat-Fingerabdruck (SHA-256)', advanced: true, placeholder: 'AB:CD:EF:…', help: 'Nur bei selbstsigniertem Zertifikat: Das Kundencenter vertraut dann genau diesem Zertifikat. Mit „Vom Server holen“ eintragen und mit KeyHelp abgleichen.' },
{ name: 'mailServer', label: 'Mailserver für Verbindungsdaten', advanced: true, placeholder: 'mail.example.de', help: 'Leer = Hostname des KeyHelp-Servers (wie in KeyHelp unter „Verbindungsdaten“). Nur ändern, wenn KeyHelp dort eine eigene Domain anzeigt.' },
{ name: 'mailServerAlternatives', label: 'Alternative Mailserver', advanced: true, placeholder: 'mail.kunde.de, mail.andere.de', help: 'Optional, durch Komma getrennt. Werden in den Verbindungsdaten zusätzlich angezeigt.' },
],
capabilities: () => capabilities,
async healthCheck(ctx) {

View file

@ -202,3 +202,22 @@ describe('KeyHelp-Connector: DNS und Verzeichnisschutz nur lesend (#74)', () =>
});
});
describe('KeyHelp-Connector: Verbindungsdaten für Postfächer', () => {
it('liefert Server, Ports und Apple-Profil der Hauptdomain – ohne Passwort, nur für eigene Postfächer', async () => {
const f = createFake(); const ch = mk(f).children!;
f.state.domains.push({ id: 12, id_user: 1, id_parent_domain: 10, domain: 'shop.alpha.example.test', domain_utf8: 'shop.alpha.example.test', status: 1, is_subdomain: true, security: {} });
f.state.emails.push({ id: 32, id_user: 1, email: 'xn--mller-kva@shop.alpha.example.test', email_utf8: 'müller@shop.alpha.example.test', status: 1, aliases: [], forwardings: [], password_hash: 'GEHEIM' });
const i = await ch.connectionInfo!(ctx(), { parentRef: '1', kind: 'email', id: '30' });
expect(i.host).toBe('kh.test'); expect(i.usernames).toEqual(['info@alpha.example.test']);
expect(i.ports.map((p) => `${p.protocol}:${p.port}:${p.security}`)).toEqual(['IMAP:993:tls', 'POP3:995:tls', 'SMTP:465:tls', 'IMAP:143:starttls', 'POP3:110:starttls', 'SMTP:587:starttls']);
expect(i.profiles[0]!.url).toBe('http://autoconfig-apple.alpha.example.test/setup.mobileconfig?email=info%40alpha.example.test&protocol=imap');
const sub = await ch.connectionInfo!(ctx({ mailServer: 'mail.example.test', mailServerAlternatives: 'mx2.example.test, kaputt!, mail.example.test' }), { parentRef: '1', kind: 'email', id: '32' });
expect(sub.host).toBe('mail.example.test'); expect(sub.alternativeHosts).toEqual(['mx2.example.test']);
expect(sub.usernames).toEqual(['müller@shop.alpha.example.test', 'xn--mller-kva@shop.alpha.example.test']);
expect(sub.profiles[1]!.url).toBe(`http://autoconfig-apple.alpha.example.test/setup.mobileconfig?email=${encodeURIComponent('müller@shop.alpha.example.test')}&protocol=pop3`); // Subdomain → Hauptdomain
expect(JSON.stringify([i, sub])).not.toMatch(/GEHEIM|password/i);
await expect(ch.connectionInfo!(ctx(), { parentRef: '1', kind: 'email', id: '31' })).rejects.toMatchObject({ code: 'NOT_FOUND' }); // fremdes Postfach
await expect(ch.connectionInfo!(ctx(), { parentRef: '1', kind: 'database', id: '40' })).rejects.toMatchObject({ code: 'UNSUPPORTED' });
});
});

View file

@ -92,6 +92,14 @@ export interface ChildAccess {
* `secrets` (z. B. Passwörter) laufen getrennt von `data`, damit sie nie protokolliert werden.
*/
act(ctx: ConnectorContext, req: { parentRef: string; kind: ChildKind; op: ChildOp; id?: string; data: Record<string, unknown>; secrets?: Record<string, string>; idempotencyKey: string }): Promise<{ child?: NormalizedChild }>;
/** Optional: Verbindungsdaten zur Einrichtung eines Postfachs in Mail-Programmen (nur Art "email"; ohne Passwort). Zugehörigkeit prüft der Connector. */
connectionInfo?(ctx: ConnectorContext, req: { parentRef: string; kind: ChildKind; id: string }): Promise<ChildConnectionInfo>;
}
/** Einrichtungsdaten eines Postfachs. `profiles` sind Links zu Einrichtungsprofilen (z. B. Apple .mobileconfig), die auch als QR-Code taugen. */
export interface ChildConnectionInfo {
host: string; alternativeHosts: string[]; usernames: string[];
ports: { protocol: 'IMAP' | 'POP3' | 'SMTP'; port: number; security: 'tls' | 'starttls' }[];
profiles: { protocol: 'imap' | 'pop3'; label: string; url: string }[];
}
export interface Health { ok: boolean; latencyMs: number; message?: string; version?: string }