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

181 lines
6.2 KiB
TypeScript

/**
* Microsoft Identity Platform — OAuth2 PKCE utilities.
*
* Tenant: 'common' — covers consumer Outlook/Hotmail/Live/MSN accounts
* AND Microsoft 365 work/school accounts. Decision: common > consumers because
* the Azure App Registration was created as Multi-Tenant + Personal Accounts.
*
* Public Client / No Client-Secret — PKCE (S256) is the security mechanism.
* Microsoft explicitly supports PKCE without client_secret for public clients
* (mobile/native apps). See: https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow
*/
import { createHash, randomBytes } from "crypto";
const MS_TENANT = "common";
const MS_TOKEN_ENDPOINT = `https://login.microsoftonline.com/${MS_TENANT}/oauth2/v2.0/token`;
export const MS_AUTH_BASE = `https://login.microsoftonline.com/${MS_TENANT}/oauth2/v2.0/authorize`;
/**
* OAuth scopes requested.
* Matches the DSGVO-Memo Section 4.3 (Datenminimierung).
* User.Read is included per User decision (email extraction from ID-token).
* Hans-Müller-Memo will document this in the next revision.
*/
export const MS_OAUTH_SCOPES = [
"https://outlook.office.com/IMAP.AccessAsUser.All",
"offline_access",
"openid",
"User.Read",
].join(" ");
/**
* The redirect_uri registered in the Azure App Registration for the native client.
* Must match exactly what the client sends — scheme registered in app.json.
*/
export const MS_REDIRECT_URI = "rebreak://auth/mail-oauth-callback";
// ── PKCE Helpers ─────────────────────────────────────────────────────────────
/** Generates a cryptographically random code_verifier (43-128 chars, URL-safe). */
export function generateCodeVerifier(): string {
// 96 random bytes → 128 base64url chars (well within PKCE 43-128 range)
return randomBytes(96).toString("base64url");
}
/** Computes S256 code_challenge from the verifier. */
export function computeCodeChallenge(verifier: string): string {
return createHash("sha256").update(verifier).digest("base64url");
}
/** Generates a random state ID for CSRF protection (hex, 32 chars = 128 bits). */
export function generateStateId(): string {
return randomBytes(16).toString("hex");
}
// ── Token Exchange ────────────────────────────────────────────────────────────
export interface MicrosoftTokenResponse {
access_token: string;
/** Microsoft ALWAYS returns a refresh_token when offline_access scope is included. */
refresh_token: string;
/** Seconds until access_token expires (typically 3600 for MS). */
expires_in: number;
scope: string;
token_type: string;
/** JWT containing user claims (email, sub, etc.). Returned because openid scope is included. */
id_token?: string;
}
/**
* Exchanges an authorization_code for tokens.
* Called from callback endpoint after state validation.
*/
export async function exchangeCodeForTokens(params: {
clientId: string;
code: string;
codeVerifier: string;
}): Promise<MicrosoftTokenResponse> {
const body = new URLSearchParams({
grant_type: "authorization_code",
client_id: params.clientId,
code: params.code,
redirect_uri: MS_REDIRECT_URI,
code_verifier: params.codeVerifier,
scope: MS_OAUTH_SCOPES,
});
const res = await fetch(MS_TOKEN_ENDPOINT, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: body.toString(),
});
if (!res.ok) {
const errText = await res.text().catch(() => "unknown error");
throw new Error(`MS token exchange failed (${res.status}): ${errText}`);
}
const data = await res.json() as MicrosoftTokenResponse;
if (!data.access_token || !data.refresh_token) {
throw new Error("MS token response missing access_token or refresh_token");
}
return data;
}
/**
* Refreshes a Microsoft access_token using a refresh_token.
*
* CRITICAL: Microsoft rotates refresh_tokens — the response may contain a NEW
* refresh_token that invalidates the old one. Always persist the new refresh_token
* if present, otherwise the next refresh will fail with AADSTS70043.
*/
export async function refreshMicrosoftTokens(params: {
clientId: string;
refreshToken: string;
}): Promise<{
access_token: string;
/** May be a NEW token (MS refresh token rotation). Persist this immediately. */
refresh_token: string;
expires_in: number;
}> {
const body = new URLSearchParams({
grant_type: "refresh_token",
client_id: params.clientId,
refresh_token: params.refreshToken,
scope: MS_OAUTH_SCOPES,
});
const res = await fetch(MS_TOKEN_ENDPOINT, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: body.toString(),
});
if (!res.ok) {
const errText = await res.text().catch(() => "unknown error");
throw new Error(`MS token refresh failed (${res.status}): ${errText}`);
}
const data = await res.json() as MicrosoftTokenResponse;
if (!data.access_token) {
throw new Error("MS refresh response missing access_token");
}
return {
access_token: data.access_token,
// MS may omit refresh_token if it didn't rotate — fall back to original
refresh_token: data.refresh_token ?? params.refreshToken,
expires_in: data.expires_in,
};
}
/**
* Extracts the email claim from a Microsoft ID-token (JWT).
* The ID-token is a standard JWT — we only need the payload, no signature
* verification required here because:
* 1. We received it directly from Microsoft's token endpoint over HTTPS.
* 2. We don't rely on it for auth decisions — just for extracting the email
* to store in mail_connections.email.
*
* Claims checked (in order): email → preferred_username → upn
*/
export function extractEmailFromIdToken(idToken: string): string | null {
try {
const [, payloadB64] = idToken.split(".");
if (!payloadB64) return null;
const payload = JSON.parse(Buffer.from(payloadB64, "base64url").toString("utf8"));
return (
payload.email ??
payload.preferred_username ??
payload.upn ??
null
);
} catch {
return null;
}
}