diff --git a/apps/api/src/modules/resources/index.ts b/apps/api/src/modules/resources/index.ts index 56be1a3..f0bff2f 100644 --- a/apps/api/src/modules/resources/index.ts +++ b/apps/api/src/modules/resources/index.ts @@ -1,12 +1,12 @@ import type { FastifyInstance } from 'fastify'; import { z } from 'zod'; -import { randomUUID, createHash } from 'node:crypto'; +import { randomUUID, createHash, createHmac, timingSafeEqual } from 'node:crypto'; import { domainToUnicode } from 'node:url'; import { ACTION_CAPABILITY, ACTIONS, loadInstance, type ActionName } from '@kc/connectors'; import { ConnectorError, type ChildKind } from '@kc/connector-sdk'; import { decrypt, encrypt, randomToken } from '../../core/crypto.js'; import { CHILD_MANAGE, CUSTOMER_ACTIONS } from '../../core/actions.js'; -import { rl } from '../../core/config.js'; +import { config, rl } from '../../core/config.js'; import { DESTRUCTIVE_ACTIONS } from '@kc/connector-sdk'; import { one, query, run } from '../../core/db.js'; import { audit } from '../../core/audit.js'; @@ -19,6 +19,23 @@ import type { KcModule } from '../../core/module.js'; import { findDrift } from '@kc/platform/drift'; const STALE_FACTOR = 3; +/** Apple-Profil-Links: KeyHelp liefert das Profil nur per http → das Kundencenter reicht es per https durch. Signiertes Token, 24 h gültig, ohne Anmeldung (QR-Scan am Handy). */ +const PROFILE_TTL_SEC = 24 * 3600; +const profileSig = (body: string) => createHmac('sha256', config.secretKey).update(`mail-profile:${body}`).digest('base64url'); +const profileLink = (resourceId: string, childId: string, protocol: string) => { + const body = Buffer.from(JSON.stringify({ r: resourceId, c: childId, p: protocol, x: Math.floor(Date.now() / 1000) + PROFILE_TTL_SEC })).toString('base64url'); + return `${config.baseUrl}/api/mail-profile/${body}.${profileSig(body)}`; +}; +function readProfileToken(token: string): { r: string; c: string; p: 'imap' | 'pop3' } | null { + const [body, sig] = token.split('.'); if (!body || !sig) return null; + const want = Buffer.from(profileSig(body)); const got = Buffer.from(sig); + if (want.length !== got.length || !timingSafeEqual(want, got)) return null; + try { + const t = z.object({ r: z.string().uuid(), c: z.string().min(1).max(40), p: z.enum(['imap', 'pop3']), x: z.number().int() }).parse(JSON.parse(Buffer.from(body, 'base64url').toString('utf8'))); + return t.x * 1000 > Date.now() ? t : null; + } catch { return null; } +} +const KEYHELP_PROFILE = /^http:\/\/autoconfig-apple\.[a-z0-9.-]{1,253}\/setup\.mobileconfig\?email=[^&\s]{3,400}&protocol=(imap|pop3)$/; const json = (v: unknown, d: T): T => (v == null ? d : typeof v === 'string' ? JSON.parse(v) : (v as T)); /** Ressource + Instanzzustand; "stale" = Provider gestört oder Daten älter als 3 Abgleichintervalle. */ @@ -244,9 +261,28 @@ export const resourcesModule: KcModule = { 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 }); + const info = await connector.children.connectionInfo(ctx, { parentRef: r.external_ref, kind, id: childId }); + return { ...info, profiles: info.profiles.map((p) => ({ ...p, url: profileLink(id, childId, p.protocol) })) }; } catch (e) { return providerError(e); } }); + /** Öffentlich (Token statt Anmeldung): holt das Apple-Profil beim Anbieter und liefert es per https aus. */ + app.get('/mail-profile/:token', { config: rl(30, '1 minute') }, async (req, reply) => { + const { token } = z.object({ token: z.string().min(10).max(600) }).parse(req.params); + const t = readProfileToken(token); if (!t) throw new AppError(404, 'LINK_INVALID', 'Der Link ist ungültig oder abgelaufen. Bitte die Verbindungsdaten im Kundencenter neu öffnen.'); + const r = await loadResource(t.r); + if (!r || !r.enabled || !childCaps(r).includes('children.read')) throw notFound(); + let src: string | undefined; + try { + const { connector, ctx } = await loadInstance(r.instance_id, req.correlationId); + if (!connector.children?.connectionInfo) throw notFound(); + src = (await connector.children.connectionInfo(ctx, { parentRef: r.external_ref, kind: 'email', id: t.c })).profiles.find((p) => p.protocol === t.p)?.url; + } catch (e) { return providerError(e); } + if (!src || !KEYHELP_PROFILE.test(src)) throw notFound(); + const res = await fetch(src, { redirect: 'error', signal: AbortSignal.timeout(10_000) }).catch(() => null); + const buf = res?.ok ? Buffer.from(await res.arrayBuffer()) : null; + if (!buf || buf.length > 256_000 || !buf.includes('PayloadContent')) throw new AppError(502, 'CONNECTOR_ERROR', 'Das Einrichtungsprofil konnte nicht geladen werden.'); + return reply.header('content-type', 'application/x-apple-aspen-config').header('content-disposition', `attachment; filename="${t.p}.mobileconfig"`).header('cache-control', 'no-store').send(buf); + }); /** Ä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); diff --git a/apps/web/src/components/HostingPanel.tsx b/apps/web/src/components/HostingPanel.tsx index 90337d2..ecdc82d 100644 --- a/apps/web/src/components/HostingPanel.tsx +++ b/apps/web/src/components/HostingPanel.tsx @@ -81,7 +81,7 @@ function ConnectionDialog({ resourceId, child, onClose }: { resourceId: string; {info && <>

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.

Apple-Geräte (iPhone, iPad, Mac)

-

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.

+

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. Die Links sind 24 Stunden gültig.

{info.profiles.map((p) =>
{qr[p.protocol] && {`QR-Code:} {p.label}
)}