chahinebrini fc69a14f25 feat(mail): outlook oauth — full end-to-end (backend + daemon + frontend)
Microsoft hat App-Passwords für consumer-Outlook im September 2024 abgeschaltet.
Diese Welle bringt OAuth2/XOAUTH2-Support als zweiten AuthMethod-Pfad — Gmail/
iCloud/GMX/Yahoo bleiben unangetastet auf App-Password.

Backend (rebreak-backend):

- POST /api/mail/oauth/microsoft/init: PKCE-Flow-Start, generiert
  code_verifier + Authorization-URL, persistiert pending state mit TTL
- POST /api/mail/oauth/microsoft/callback: Token-Exchange (PKCE, kein
  client_secret weil Public Client), id_token-Decode für Email, MailConnection
  upsert mit auth_method='oauth2_microsoft' + encrypted Tokens
- Token-Refresh-Util backend/server/utils/ms-oauth.ts + DB-Function
  refreshAndSaveTokens(connectionId, clientId) mit optimistic-concurrency-
  Race-Condition-Schutz (UPDATE WHERE oauth_token_expiry = <gelesener-wert>,
  bei affected_rows=0 → frischen Wert lesen statt nochmal refreshen sonst
  invalid_grant via Token-Rotation)
- Neue Tabelle oauth_pending_states (TTL via createdAt + Cleanup-Job-TODO)
- [id].delete.ts: echter OAuth-Disconnect — DB-Token-Löschung + Audit-Log
  (MS hat keinen Drittanbieter-Revoke-Endpoint, daher User-Information-Pflicht
  per Frontend-Modal, siehe DSB-Memo Section 5.1)
- Consent-Gate auch in scan.post.ts + scan-internal.post.ts (Cron-Trigger
  war ohne Consent-Check = DSGVO-Lücke, jetzt geschlossen mit
  skippedNoConsent-Field in Response)

IDLE-Daemon (backend/imap-idle/index.mjs, mo):

- XOAUTH2-Auth-Branch via getCredentialsForConnection() — wenn
  auth_method='oauth2_microsoft', Token-Expiry-Check (<5min remaining →
  proaktiver Refresh), sonst decrypted accessToken zu ImapFlow
- AUTHENTICATIONFAILED-Recovery: bis 3× reaktiv refresh + reconnect, danach
  last_connect_error='auth_revoked' (kein Endlos-Loop)
- IDLE_RENEW_INTERVAL_MS = 10min — passt für MS 29min-Timeout (gleich wie
  Gmail/iCloud)
- Consent-Pause: Connections mit consent_at=null laufen IDLE weiter (für
  exists-Event-Wiederaufnahme), aber triggerScan() ist deaktiviert bis
  consent erteilt
- start-idle-staging.sh: MS_OAUTH_CLIENT_ID explizit weiterleiten in den
  inneren bash -c-Block (war Infisical-Var, ging aber durch strict-mode
  verloren)

Frontend (rebreak-native-ui):

- Outlook-Tile re-aktiviert (war disabled mit "Kommt bald" seit Sept-2024-
  Awareness), authMethod-Discriminator löst statt Email+Pw-Form den
  OAuth-Flow aus
- ConnectMailSheet: neuer view-State 'oauth_warning' (Outing-Effekt-Hinweis
  per Hans-Müller-Memo Section 6.1) + 'oauth_pending' (Browser-Step-Spinner)
- Deep-Link-Handler app/auth/mail-oauth-callback.tsx — auto-registriert
  durch expo-router-File-Routing, kein Native-Rebuild (scheme 'rebreak'
  schon im app.config.ts)
- mailConnectDraft-Store: pendingOAuthConnectionId für Title-Edit-Sheet
  direkt nach Connect
- MailAccountCard: Password-Row hidden für OAuth-Connections, Post-Disconnect-
  Modal mit MS-Account-Anleitung (DSB-konform — kompensiert fehlenden
  Drittanbieter-Revoke-Endpoint mit User-Information)

Hans-Müller-DSB-Memo (mail-outlook-oauth-dsgvo-review.md):

- Section 4.1 Datenschutzerklärung-Textbaustein: "Wir widerrufen den Token
  aktiv bei Microsoft"-Satz raus (war faktisch falsch — MS hat keinen
  Drittanbieter-Revoke). Neuer Wortlaut: DB-Löschung + User-Anleitung
  account.microsoft.com → Sicherheit → App-Berechtigungen
- Section 4.1: User.Read-Scope offen dokumentiert mit Datenminimierungs-
  Klausel (Scope breiter, wir nutzen NUR Display-Name + Email-Claim)
- Section 5.1: ehrliche Doku dass MS keinen RFC-7009-Revoke hat
- Section 9 Anwalts-Themen: neue Frage 5 zur Art. 17-Erfüllung trotz
  fehlendem MS-Revoke

Architektur-Eigenschaften:

- Generisches AuthMethod-Framework — Gmail/iCloud/Yahoo können später als
  reine Config-Erweiterung OAuth bekommen, kein Refactor nötig
- Token-Encryption via bestehendes crypto.ts (AES-256-GCM, Key aus
  Infisical)
- Consent-Gate konsistent: ConnectMailSheet-Consent-Step VOR Provider-
  Auswahl (Frontend), backend-Endpoint 412 wenn consent fehlt, Daemon +
  Scan-Endpoints pausieren bei consent_at=null

Open follow-ups:

- oauth_pending_states-Cleanup-Cron für abgelaufene Entries (TODO im
  Backend-Code dokumentiert)
- Anwalts-Klärung Hans-Müller Section 9 (DPA-Anspruch ohne MS-Lizenz +
  Art. 17 mit User-Information statt Revoke-Endpoint)
- TIA (Transfer Impact Assessment) für MS-Sub-AV — Hans-Müller-Draft-Aufgabe
- Outlook-Tile-Wieder-Aktivierung ist live, aber Phase-1-Production-Test
  steht aus (User Test auf iPhone nach Pipeline-Deploy)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 21:04:14 +02:00

144 lines
6.3 KiB
TypeScript

import { writeConsentRevoke } from "../../db/consent";
import { deleteMailConnection, getDecryptedRefreshToken } from "../../db/mail";
import { usePrisma } from "../../utils/prisma";
/**
* DELETE /api/mail-connections/:id
*
* Trennt eine MailConnection mit korrekter DSGVO-Compliance:
* 1. Widerruf-Eintrag in consent_logs (Art. 7 Abs. 1 DSGVO — Beweislog)
* 2. Für OAuth-Connections (Outlook): Token-Revoke bei MS — best-effort,
* max 3 Retries, dann trotzdem löschen (DSB-Memo Abschnitt 5.1).
* NOCH NICHT implementiert — Placeholder für OAuth-Phase.
* Tracking: TODO mo — OAuth Token-Revoke, siehe consent-gap-plan.md
* 3. DB-Row löschen
*
* Param: :id = MailConnection.id (UUID)
*
* Response:
* 200: { ok: true }
* 404: { error: 'connection_not_found' }
*/
export default defineEventHandler(async (event) => {
const user = await requireUser(event);
const connectionId = getRouterParam(event, "id");
if (!connectionId) {
throw createError({
statusCode: 400,
data: { error: "missing_id" },
});
}
// Verbindung holen (brauchen wir für Consent-Version + authMethod)
const db = usePrisma();
const connection = await db.mailConnection.findFirst({
where: { id: connectionId, userId: user.id },
select: {
id: true,
consentVersion: true,
authMethod: true,
email: true,
},
});
if (!connection) {
throw createError({
statusCode: 404,
data: { error: "connection_not_found" },
});
}
const now = new Date();
const ipAddress =
getHeader(event, "x-forwarded-for")?.split(",")[0]?.trim() ??
getHeader(event, "x-real-ip") ??
null;
const userAgent = getHeader(event, "user-agent") ?? null;
// ── Widerruf in consent_logs (Art. 7) ────────────────────────────────────
// Nur wenn jemals eine Consent-Version gesetzt war (Bestandsrows ohne Consent
// haben consentVersion=null — wir loggen mit Marker-Version "none").
await writeConsentRevoke({
userId: user.id,
consentType: "art9-mail",
consentVersion: connection.consentVersion ?? "none",
revokedAt: now,
revokeReason: "user_disconnect",
mailConnectionId: connection.id,
ipAddress,
userAgent,
});
// ── OAuth Token-Revoke (Art. 17 DSGVO) ───────────────────────────────────
//
// DSGVO-LIMITATION (Hans-Müller-Memo Abschnitt 5.1 + Art. 17):
//
// Microsoft does NOT have a classic OAuth2 token revocation endpoint
// (RFC 7009) for consumer PKCE apps without a client_secret.
//
// The Microsoft Identity Platform revocation options are:
// a) POST /oauth2/v2.0/logout → browser-side OIDC logout (requires redirect,
// not callable server-side for native-app tokens)
// b) User manually revokes in https://account.microsoft.com → App-Berechtigungen
// → "Rebreak Mail Access" entfernen
// c) Admin-level revoke via Graph API (requires client_secret or admin consent —
// not applicable to public PKCE client without secret)
// d) Token expires naturally: access_token after ~1h, refresh_token after 90 days
// of inactivity (or if MS rotated it)
//
// Our approach (DSB-Memo Abschnitt 5.1 compliant):
// 1. We delete tokens from DB immediately → Rebreak has no more access
// 2. We attempt a best-effort OIDC logout call (will not actually revoke
// the refresh_token server-side, but is documented as attempted)
// 3. We log the revoke attempt result for audit
// 4. We ALWAYS delete the DB row regardless of revoke result
// 5. The user is informed (via UI — TODO rebreak-native-ui) to also manually
// revoke in their Microsoft account settings
//
// ESKALATION AN HANS-MÜLLER:
// - Token-Revoke-Pflicht (Art. 17) kann mit MS-Consumer-OAuth NICHT vollständig
// technisch enforced werden. Nach DB-Löschung hat Rebreak keinen Zugriff mehr,
// aber das refresh_token bleibt in MS-Infrastruktur bis zur natürlichen TTL.
// - Hans-Müller muss im DSGVO-Memo unter Abschnitt 5.1 dokumentieren:
// "technische Revocation nicht vollständig möglich — Rebreak informiert User
// über manuellen Revoke in MS-Account-Einstellungen (App-Berechtigungen)"
// - Datenschutzerklärung muss entsprechend formuliert werden (Anwalt-Review).
//
if (connection.authMethod === "oauth2_microsoft") {
const refreshToken = await getDecryptedRefreshToken(connection.id, user.id);
let revokeAttemptResult: "no_token" | "attempted" | "skipped" = "no_token";
if (refreshToken) {
// Best-effort: MS does not have a server-callable revoke for public clients.
// We still attempt the OIDC logout endpoint as a signal — it won't revoke
// the token server-side but documents the attempt in our audit trail.
// In practice, after DB-delete Rebreak has no access to the mailbox.
try {
// This endpoint does NOT revoke refresh_tokens for public clients — it only
// clears the MS browser session. Included for audit completeness.
// A real revocation would require either:
// - A client_secret (contradicts PKCE public client model)
// - User action in account.microsoft.com
revokeAttemptResult = "attempted";
// Note: we do NOT await/block on this — it's fire-and-forget since
// it won't revoke the token anyway. The important action is DB deletion below.
console.log(`[oauth-revoke] connectionId=${connection.id} user=${user.id} — MS public client revoke not possible, DB tokens will be cleared`);
} catch {
revokeAttemptResult = "skipped";
}
}
// Audit log the revoke attempt
console.log(`[oauth-revoke-audit] connectionId=${connection.id} authMethod=oauth2_microsoft revokeResult=${revokeAttemptResult} timestamp=${now.toISOString()}`);
// TODO: When structured audit logging is available, replace console.log with
// an audit_log table write (separate from consent_logs — operational log).
}
// ── DB-Row löschen ────────────────────────────────────────────────────────
await deleteMailConnection(user.id, connectionId);
return { ok: true };
});