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

340 lines
11 KiB
TypeScript

import { useState } from 'react';
import {
ActivityIndicator,
Alert,
ScrollView,
Text,
TouchableOpacity,
View,
} from 'react-native';
import { useBottomTabBarHeight } from 'react-native-bottom-tabs';
import { useTranslation } from 'react-i18next';
import { Ionicons } from '@expo/vector-icons';
import { AppHeader } from '../../components/AppHeader';
import { MailStatsRow } from '../../components/mail/MailStatsRow';
import { MailAccountCard } from '../../components/mail/MailAccountCard';
import { MailEmptyState } from '../../components/mail/MailEmptyState';
import { MailActivityLog } from '../../components/mail/MailActivityLog';
import { MailBlockedByDayChart } from '../../components/mail/MailBlockedByDayChart';
import { MailDistributionChart } from '../../components/mail/MailDistributionChart';
import { ConnectMailSheet } from '../../components/mail/ConnectMailSheet';
import { EditMailTitleSheet } from '../../components/mail/EditMailTitleSheet';
import { SuccessAlert } from '../../components/SuccessAlert';
import { useMailStatus } from '../../hooks/useMailStatus';
import { useMailDisconnect } from '../../hooks/useMailDisconnect';
import { useMailStats } from '../../hooks/useMailStats';
import { useUserPlan } from '../../hooks/useUserPlan';
import { useColors } from '../../lib/theme';
import { useMailConnectDraft } from '../../stores/mailConnectDraft';
const PLAN_LABEL: Record<string, string> = { free: 'Free', pro: 'Pro', legend: 'Legend' };
function MailOverLimitBanner({
usedCount,
maxAccounts,
planLabel,
pausedEmails,
colors,
}: {
usedCount: number;
maxAccounts: number;
planLabel: string;
pausedEmails: string[];
colors: import('../../lib/theme').ColorScheme;
}) {
const { t } = useTranslation();
const over = usedCount - maxAccounts;
if (over <= 0) return null;
return (
<View
style={{
backgroundColor: 'rgba(217,119,6,0.08)',
borderRadius: 14,
padding: 14,
marginBottom: 14,
borderWidth: 1,
borderColor: 'rgba(217,119,6,0.2)',
gap: 6,
}}
>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
<Ionicons name="warning-outline" size={16} color="#d97706" />
<Text style={{ fontSize: 14, fontFamily: 'Nunito_700Bold', color: '#d97706', flex: 1 }}>
{t('plan_limit.mail_banner_title')}
</Text>
</View>
<Text style={{ fontSize: 13, color: colors.text, fontFamily: 'Nunito_400Regular', lineHeight: 18 }}>
{t(over === 1 ? 'plan_limit.mail_banner_body_one' : 'plan_limit.mail_banner_body_other', {
used: usedCount,
plan: planLabel,
max: maxAccounts,
over,
})}
</Text>
{pausedEmails.length > 0 && (
<Text style={{ fontSize: 12, color: colors.textMuted, fontFamily: 'Nunito_400Regular' }}>
{pausedEmails.join(', ')}
</Text>
)}
</View>
);
}
export default function MailScreen() {
const { t } = useTranslation();
const tabBarHeight = useBottomTabBarHeight();
const colors = useColors();
const { plan } = useUserPlan();
const { connected, accounts, totalBlocked, maxAccounts, loading, refresh } =
useMailStatus(plan);
const { disconnect, disconnecting } = useMailDisconnect();
const hasAccounts = accounts.length > 0;
const { blockedByDay, blockedByConnection } = useMailStats(hasAccounts);
const [sheetVisible, setSheetVisible] = useState(false);
const [successVisible, setSuccessVisible] = useState(false);
const [disconnectingId, setDisconnectingId] = useState<string | null>(null);
const [expandedAccount, setExpandedAccount] = useState<string | null>(null);
const [activityLogExpanded, setActivityLogExpanded] = useState(false);
const [oauthTitleSheetConnectionId, setOauthTitleSheetConnectionId] = useState<string | null>(null);
const { pendingOAuthConnectionId, setPendingOAuthConnectionId } = useMailConnectDraft();
const nextScanAt =
accounts
.map((a) => a.nextScanAt)
.filter((v): v is string => v !== null)
.sort()[0] ?? null;
const pausedAccounts = accounts.filter((a) => a.paused === true);
const overLimit = maxAccounts !== Infinity && accounts.length > maxAccounts;
const limitReached = maxAccounts !== Infinity && accounts.length >= maxAccounts;
const distinctProviders = [
...new Set(accounts.map((a) => a.provider.toLowerCase())),
];
function handleAddPress() {
if (limitReached) {
Alert.alert(t('mail.upgrade_alert_title'), t('mail.upgrade_alert_desc'));
return;
}
setSheetVisible(true);
}
async function handleDisconnect(id: string) {
setDisconnectingId(id);
await disconnect(id);
setDisconnectingId(null);
if (expandedAccount === id) setExpandedAccount(null);
refresh();
}
function handleConnectSuccess() {
refresh();
if (pendingOAuthConnectionId) {
setOauthTitleSheetConnectionId(pendingOAuthConnectionId);
setPendingOAuthConnectionId(null);
} else {
setSuccessVisible(true);
}
}
function toggleAccount(id: string) {
setExpandedAccount((prev) => (prev === id ? null : id));
}
if (loading) {
return (
<View style={{ flex: 1, backgroundColor: colors.bg }}>
<AppHeader />
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<ActivityIndicator size="large" color="#007AFF" />
</View>
</View>
);
}
return (
<View style={{ flex: 1, backgroundColor: colors.bg }}>
<AppHeader />
<ScrollView
contentContainerStyle={{
paddingHorizontal: 16,
paddingTop: 16,
paddingBottom: tabBarHeight + 24,
}}
showsVerticalScrollIndicator={false}
>
{/* Über-Limit-Banner */}
{overLimit && pausedAccounts.length > 0 && (
<MailOverLimitBanner
usedCount={accounts.length}
maxAccounts={maxAccounts}
planLabel={PLAN_LABEL[plan] ?? plan}
pausedEmails={pausedAccounts.map((a) => a.email)}
colors={colors}
/>
)}
{/* Stats card */}
{hasAccounts && (
<View style={{ marginBottom: 14 }}>
<MailStatsRow
totalBlocked={totalBlocked}
accountCount={accounts.length}
isLegend={plan === 'legend'}
/>
</View>
)}
{/* Section header + add button */}
{hasAccounts && (
<View
style={{
flexDirection: 'row',
alignItems: 'center',
marginBottom: 10,
paddingHorizontal: 2,
}}
>
<View style={{ flex: 1, marginRight: 10 }}>
<Text
style={{
fontSize: 11,
fontFamily: 'Nunito_700Bold',
color: colors.textMuted,
textTransform: 'uppercase',
letterSpacing: 0.8,
}}
>
{t('mail.section_accounts')}
</Text>
<Text
style={{
fontSize: 11,
fontFamily: 'Nunito_400Regular',
color: colors.textMuted,
marginTop: 2,
}}
>
{maxAccounts === Infinity
? t('mail.section_accounts_count_unlimited', { used: accounts.length })
: t('mail.section_accounts_count', {
used: accounts.length,
max: maxAccounts,
})}
</Text>
</View>
<TouchableOpacity
onPress={handleAddPress}
disabled={limitReached}
activeOpacity={limitReached ? 1 : 0.8}
accessibilityLabel={t('mail.add_account_a11y')}
style={{
backgroundColor: limitReached ? colors.surfaceElevated : '#007AFF',
borderRadius: 12,
opacity: limitReached ? 0.7 : 1,
shadowColor: '#007AFF',
shadowOffset: { width: 0, height: 4 },
shadowOpacity: limitReached ? 0 : 0.25,
shadowRadius: 8,
elevation: limitReached ? 0 : 4,
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 14,
paddingVertical: 10,
}}
>
<Ionicons
name="add"
size={18}
color={limitReached ? colors.textMuted : '#fff'}
style={{ marginRight: 6 }}
/>
<Text
style={{
fontSize: 13,
fontFamily: 'Nunito_700Bold',
color: limitReached ? colors.textMuted : '#fff',
}}
>
{t('mail.add_account')}
</Text>
</TouchableOpacity>
</View>
)}
{/* Account cards or empty */}
{accounts.length === 0 ? (
<MailEmptyState onConnectPress={handleAddPress} />
) : (
<View>
{accounts.map((account, idx) => (
<View key={account.id} style={{ marginTop: idx === 0 ? 0 : 10 }}>
<MailAccountCard
account={account}
plan={plan}
expanded={expandedAccount === account.id}
onToggle={() => toggleAccount(account.id)}
onDisconnect={handleDisconnect}
onIntervalChanged={refresh}
onEditSuccess={handleConnectSuccess}
disconnecting={disconnectingId === account.id && disconnecting}
/>
</View>
))}
</View>
)}
{/* Charts — nur wenn Accounts vorhanden */}
{hasAccounts && (
<View style={{ gap: 12, marginTop: 14 }}>
<MailBlockedByDayChart data={blockedByDay} />
<MailDistributionChart data={blockedByConnection} />
</View>
)}
{/* Activity log */}
{hasAccounts && (
<View style={{ marginTop: 14 }}>
<MailActivityLog
expanded={activityLogExpanded}
onToggle={() => setActivityLogExpanded((p) => !p)}
providers={distinctProviders}
/>
</View>
)}
</ScrollView>
<ConnectMailSheet
visible={sheetVisible}
onClose={() => setSheetVisible(false)}
onSuccess={handleConnectSuccess}
/>
{oauthTitleSheetConnectionId && (
<EditMailTitleSheet
visible={!!oauthTitleSheetConnectionId}
connectionId={oauthTitleSheetConnectionId}
currentTitle={null}
onClose={() => { setOauthTitleSheetConnectionId(null); setSuccessVisible(true); }}
onSuccess={() => { setOauthTitleSheetConnectionId(null); setSuccessVisible(true); refresh(); }}
/>
)}
<SuccessAlert
visible={successVisible}
title={t('mail.connect_success_title')}
message={t('mail.connect_success_message')}
onClose={() => setSuccessVisible(false)}
/>
</View>
);
}