chahinebrini 0ab635c74a feat: art-9 consent flow + outlook-oauth schema + cooldown patterns + mail draft persist
DSGVO Art. 9 — Compliance-Gap im Mail-Connect-Flow geschlossen (Hans-Müller-DSB
hat den Gap für Gmail/iCloud/GMX identifiziert, schon vor Outlook-OAuth-Pflicht):

- Schema: mail_connections.consent_at + consent_version + consent_ip_address;
  neue consent_logs-Tabelle für Audit (grant + revoke append-only)
- Endpoints:
  - POST /api/mail-connections/consent (Bulk-Array für Re-Consent, partial-fail
    wirft sofort = DSGVO-sicher gegen silent-skip fremder IDs)
  - POST /api/mail-connections/:id mit consent-gate (412 wenn consentVersion fehlt)
  - DELETE /api/mail-connections/:id mit Widerruf-Log (OAuth-Token-Revoke als
    TODO für mo Phase 2)
  - GET /api/mail-connections/pending-consent — listet Bestands-Connections
    mit consent_at=NULL für Re-Consent-Modal
- Account-Lösch-Bug fix: deleteAllMailConnections() war in user/delete nicht
  eingebunden — Verbindungen blieben als Waisen
- Frontend:
  - ConnectMailSheet: neuer Consent-Step VOR Provider-Grid (view-Machine
    consent → grid → form), exakter Hans-Müller-Wortlaut für Art. 9 Abs. 2
    lit. a Einwilligung
  - MailConsentReminderSheet: Re-Consent-Modal beim App-Open für Bestands-User
  - Stores mailConsent + mailConnectDraft (letzterer fixt Bug: Email/Provider
    ging verloren wenn User Browser für App-Pw-Generierung öffnete)
  - 12 neue i18n-Keys mail.consent.* in DE + EN
- Versionierter Consent-Text: art9-mail-v1-2026-05-13 (Bump bei Text-Änderung
  triggert Re-Consent für alle)

Outlook-OAuth Schema (Phase 0 — additiv, Endpoints kommen später):

- mail_connections: auth_method (default 'app_password' → keine Bestands-
  Connection bricht), oauth_access_token, oauth_refresh_token,
  oauth_token_expiry, oauth_scope
- Encryption via bestehendes server/utils/crypto.ts (AES-256-GCM, Key aus
  Infisical)
- Plan-Doc backend/docs/mail-outlook-oauth-plan.md (mo)
- DSB-Review backend/docs/mail-outlook-oauth-dsgvo-review.md (Hans-Müller):
  MS als Sub-AV via DPA Sep 2025, EU Data Boundary seit Feb 2025; 5 Pflicht-
  Aufgaben + Anwalts-Klärung zu DPA-Anspruch ohne MS-Lizenz

Profile — Cooldown-Pattern-Analysis als Collapsible:

- CooldownPatternAnalysis: 24h-Uhrzeit-Heatmap, Mo–So-Wochentag-Histogramm,
  Top-5-Reason-Wortcloud mit Stop-Words-Filter, Cancel-Rate-Anzeige
- DiGA-relevant: NLP läuft client-side, reason-Texte verlassen das Device
  nicht (gut für DSB-Akte)
- useProfileData: useCooldownHistoryFull (limit=100) für Pattern-Analyse
- Neutral formuliert, kein Stigma, alle Headings als Frage

Plan-Docs (kein Code):

- backend/docs/mail-custom-keywords-plan.md — Pro/Legend Custom-Keyword-Filter
  (3.25 PT MVP, user-scoped, Body-Match in Phase 2)

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

599 lines
17 KiB
TypeScript

import { useState } from 'react';
import {
ActivityIndicator,
Linking,
ScrollView,
Switch,
Text,
TouchableOpacity,
View,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import { useMailConnect, detectProvider, type MailProvider } from '../../hooks/useMailConnect';
import { humanizeMailError } from '../../lib/mailErrors';
import { apiFetch } from '../../lib/api';
import { useColors } from '../../lib/theme';
import { FormSheet } from '../FormSheet';
import { SheetFieldStack } from '../SheetFieldStack';
import { useMailConnectDraft } from '../../stores/mailConnectDraft';
const CONSENT_VERSION = 'art9-mail-v1-2026-05-13';
const PRIVACY_URL = 'https://rebreak.org/datenschutz';
type Props = {
visible: boolean;
onClose: () => void;
onSuccess: () => void;
};
type ProviderConfig = {
id: MailProvider;
labelKey: string;
icon: React.ComponentProps<typeof Ionicons>['name'];
color: string;
guideKey: string;
guideUrl: string;
disabled?: boolean;
disabledLabelKey?: string;
};
const PROVIDERS: ProviderConfig[] = [
{
id: 'gmail',
labelKey: 'mail.provider_gmail',
icon: 'mail',
color: '#EA4335',
guideKey: 'mail.app_password_guide_gmail',
guideUrl: 'https://myaccount.google.com/apppasswords',
},
{
id: 'icloud',
labelKey: 'mail.provider_icloud',
icon: 'cloud',
color: '#007AFF',
guideKey: 'mail.app_password_guide_icloud',
guideUrl: 'https://appleid.apple.com/account/manage',
},
{
id: 'outlook',
labelKey: 'mail.provider_outlook',
icon: 'mail-open',
color: '#0078D4',
guideKey: 'mail.app_password_guide_outlook',
guideUrl: 'https://account.microsoft.com/security',
disabled: true,
disabledLabelKey: 'mail.provider_outlook_disabled_badge',
},
{
id: 'yahoo',
labelKey: 'mail.provider_yahoo',
icon: 'at',
color: '#7C3AED',
guideKey: 'mail.app_password_guide_yahoo',
guideUrl: 'https://login.yahoo.com/account/security',
},
{
id: 'gmx',
labelKey: 'mail.provider_gmx',
icon: 'mail-unread',
color: '#E87A22',
guideKey: 'mail.app_password_guide_gmx',
guideUrl: 'https://www.gmx.net/mail/security',
},
{
id: 'other',
labelKey: 'mail.provider_other',
icon: 'server',
color: '#737373',
guideKey: 'mail.app_password_guide_other',
guideUrl: '',
},
];
/**
* Bottom-Sheet zum Verbinden eines Postfachs.
*
* Drei Ansichten im selben Sheet (kein Navigations-Header):
* 1. Consent-Screen (Art. 9 DSGVO) — MUSS zuerst bestätigt werden
* 2. Provider-Grid (6 Tiles) — nach Consent-Bestätigung freigeschaltet
* 3. Formular: Email + App-Passwort als SheetFieldStack
*/
export function ConnectMailSheet({ visible, onClose, onSuccess }: Props) {
const { t } = useTranslation();
const colors = useColors();
const { connect, connecting, error: connectError } = useMailConnect();
const {
view,
consentGiven,
selectedProvider,
email,
setView,
setConsentGiven,
setSelectedProvider,
setEmail,
reset: resetDraft,
} = useMailConnectDraft();
const [password, setPassword] = useState('');
const [passwordVisible, setPasswordVisible] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
const [fieldsComplete, setFieldsComplete] = useState(false);
function handleClose() {
resetDraft();
setPassword('');
setPasswordVisible(false);
setFormError(null);
setFieldsComplete(false);
onClose();
}
function handleConsentNext() {
setView('grid');
}
function handleProviderSelect(provider: ProviderConfig) {
setSelectedProvider(provider);
setEmail('');
setPassword('');
setFormError(null);
setFieldsComplete(false);
setView('form');
}
async function handleConnect() {
setFormError(null);
try {
await apiFetch('/api/mail-connections/consent', {
method: 'POST',
body: { consentVersion: CONSENT_VERSION },
});
} catch {
// Backend macht Consent atomar beim Connect-Endpoint — Fehler hier ignorieren.
}
const result = await connect({ email: email.trim(), password });
if (result.ok) {
handleClose();
onSuccess();
} else if (result.error?.includes('412') || result.error?.includes('consent_required')) {
setView('consent');
setConsentGiven(false);
} else {
setFormError(t(humanizeMailError(result.error)));
}
}
const sheetTitle =
view === 'form' && selectedProvider
? t(selectedProvider.labelKey)
: t('mail.connect_sheet_title');
return (
<FormSheet
visible={visible}
onClose={handleClose}
title={sheetTitle}
initialHeightPct={0.75}
growWithKeyboard
>
{view === 'consent' ? (
<ConsentStep
consentGiven={consentGiven}
onToggleConsent={setConsentGiven}
onNext={handleConsentNext}
t={t}
colors={colors}
/>
) : view === 'grid' ? (
<ProviderGrid providers={PROVIDERS} onSelect={handleProviderSelect} t={t} />
) : (
<SheetFieldStack
fields={[
{
key: 'email',
label: t('mail.form_email_label'),
placeholder: t('mail.form_email_placeholder'),
value: email,
onChangeText: (v) => { setEmail(v); setFormError(null); },
keyboardType: 'email-address',
autoCapitalize: 'none',
autoCorrect: false,
validate: (v) =>
v.trim().length === 0 ? t('mail.form_fields_required') : undefined,
},
{
key: 'password',
label: t('mail.form_password_label'),
placeholder: t('mail.form_password_placeholder'),
value: password,
onChangeText: (v) => { setPassword(v); setFormError(null); },
secureTextEntry: !passwordVisible,
autoCapitalize: 'none',
autoCorrect: false,
validate: (v) =>
v.trim().length === 0 ? t('mail.form_fields_required') : undefined,
suffix: (
<TouchableOpacity
activeOpacity={0.7}
onPress={() => setPasswordVisible((p) => !p)}
hitSlop={8}
>
<Ionicons
name={passwordVisible ? 'eye-off-outline' : 'eye-outline'}
size={20}
color="#a3a3a3"
/>
</TouchableOpacity>
),
},
]}
intro={
<View style={{ gap: 10 }}>
{/* App-Password-Guide — provider-spezifisch, nicht für 'other' */}
{selectedProvider && selectedProvider.id !== 'other' && (
<View
style={{
flexDirection: 'row',
gap: 10,
padding: 12,
backgroundColor: '#f0f7ff',
borderRadius: 12,
borderWidth: 1,
borderColor: '#bfdbfe',
}}
>
<Ionicons
name="information-circle"
size={18}
color="#1d4ed8"
style={{ marginTop: 1 }}
/>
<View style={{ flex: 1, gap: 4 }}>
<Text
style={{ fontSize: 12, fontFamily: 'Nunito_600SemiBold', color: '#1e3a8a' }}
>
{t('mail.app_password_required_title')}
</Text>
<Text
style={{
fontSize: 12,
fontFamily: 'Nunito_400Regular',
color: '#1d4ed8',
lineHeight: 17,
}}
>
{t(selectedProvider.guideKey)}
</Text>
{selectedProvider.guideUrl.length > 0 && (
<TouchableOpacity
activeOpacity={0.7}
onPress={() => Linking.openURL(selectedProvider.guideUrl)}
>
<Text
style={{
fontSize: 12,
fontFamily: 'Nunito_600SemiBold',
color: '#007AFF',
marginTop: 2,
}}
>
{t('mail.app_password_open_link')}
</Text>
</TouchableOpacity>
)}
</View>
</View>
)}
{/* Datenschutz-Zusicherung — immer sichtbar */}
<View
style={{
flexDirection: 'row',
gap: 8,
padding: 12,
backgroundColor: '#f0fdf4',
borderRadius: 12,
borderWidth: 1,
borderColor: '#bbf7d0',
}}
>
<Ionicons name="shield-checkmark" size={16} color="#16a34a" style={{ marginTop: 1 }} />
<Text
style={{
flex: 1,
fontSize: 12,
fontFamily: 'Nunito_400Regular',
color: '#166534',
lineHeight: 17,
}}
>
{t('mail.form_privacy_note')}
</Text>
</View>
</View>
}
onComplete={() => setFieldsComplete(true)}
>
{/* Fehler */}
{(formError ?? (connectError ? t(humanizeMailError(connectError)) : null)) && (
<Text
style={{
fontSize: 13,
fontFamily: 'Nunito_400Regular',
color: '#dc2626',
marginBottom: 10,
}}
>
{formError ?? t(humanizeMailError(connectError))}
</Text>
)}
{/* Connect-Button */}
<TouchableOpacity
activeOpacity={0.85}
onPress={handleConnect}
disabled={connecting}
style={{ marginTop: 4, marginBottom: 12 }}
>
<View
style={{
backgroundColor: connecting ? '#d4d4d4' : '#007AFF',
borderRadius: 14,
paddingVertical: 14,
alignItems: 'center',
}}
>
{connecting ? (
<ActivityIndicator color="#fff" />
) : (
<Text style={{ fontSize: 15, fontFamily: 'Nunito_700Bold', color: '#fff' }}>
{t('mail.form_connect_btn')}
</Text>
)}
</View>
</TouchableOpacity>
</SheetFieldStack>
)}
</FormSheet>
);
}
// ---------------------------------------------------------------------------
// Sub-View: Consent (Art. 9 DSGVO) — muss als erster Schritt bestätigt werden
// ---------------------------------------------------------------------------
function ConsentStep({
consentGiven,
onToggleConsent,
onNext,
t,
colors,
}: {
consentGiven: boolean;
onToggleConsent: (v: boolean) => void;
onNext: () => void;
t: (key: string) => string;
colors: ReturnType<typeof useColors>;
}) {
return (
<ScrollView
style={{ flex: 1 }}
contentContainerStyle={{ padding: 20, gap: 16 }}
showsVerticalScrollIndicator={false}
>
<Text
style={{
fontSize: 14,
fontFamily: 'Nunito_400Regular',
color: colors.text,
lineHeight: 21,
}}
>
{t('mail.consent.intro')}
</Text>
<View
style={{
backgroundColor: '#fefce8',
borderRadius: 12,
borderWidth: 1,
borderColor: '#fde68a',
padding: 14,
gap: 12,
}}
>
<View style={{ flexDirection: 'row', alignItems: 'flex-start', gap: 10 }}>
<Ionicons
name="document-text-outline"
size={18}
color="#92400e"
style={{ marginTop: 1 }}
/>
<Text
style={{
flex: 1,
fontSize: 13,
fontFamily: 'Nunito_400Regular',
color: '#78350f',
lineHeight: 19,
}}
>
{t('mail.consent.legal_text')}
</Text>
</View>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
gap: 12,
paddingTop: 4,
borderTopWidth: 1,
borderTopColor: '#fde68a',
}}
>
<Switch
value={consentGiven}
onValueChange={onToggleConsent}
trackColor={{ false: '#d1d5db', true: '#16a34a' }}
thumbColor="#fff"
/>
<TouchableOpacity
activeOpacity={0.7}
onPress={() => onToggleConsent(!consentGiven)}
style={{ flex: 1 }}
>
<Text
style={{
fontSize: 13,
fontFamily: 'Nunito_600SemiBold',
color: '#78350f',
lineHeight: 18,
}}
>
{t('mail.consent.checkbox_label')}
</Text>
</TouchableOpacity>
</View>
</View>
<TouchableOpacity
activeOpacity={0.7}
onPress={() => Linking.openURL(PRIVACY_URL)}
>
<Text
style={{
fontSize: 13,
fontFamily: 'Nunito_600SemiBold',
color: '#007AFF',
textAlign: 'center',
}}
>
{t('mail.consent.more_link')}
</Text>
</TouchableOpacity>
<TouchableOpacity
activeOpacity={consentGiven ? 0.85 : 1}
onPress={consentGiven ? onNext : undefined}
disabled={!consentGiven}
style={{ marginTop: 4, marginBottom: 12 }}
>
<View
style={{
backgroundColor: consentGiven ? '#007AFF' : '#d4d4d4',
borderRadius: 14,
paddingVertical: 14,
alignItems: 'center',
}}
>
<Text style={{ fontSize: 15, fontFamily: 'Nunito_700Bold', color: '#fff' }}>
{t('mail.consent.cta_next')}
</Text>
</View>
</TouchableOpacity>
</ScrollView>
);
}
// ---------------------------------------------------------------------------
// Sub-View: Provider-Grid
// ---------------------------------------------------------------------------
function ProviderGrid({
providers,
onSelect,
t,
}: {
providers: ProviderConfig[];
onSelect: (p: ProviderConfig) => void;
t: (key: string) => string;
}) {
const colors = useColors();
return (
<ScrollView
style={{ flex: 1 }}
contentContainerStyle={{ padding: 20, gap: 12 }}
showsVerticalScrollIndicator={false}
>
<Text
style={{
fontSize: 13,
fontFamily: 'Nunito_400Regular',
color: colors.textMuted,
marginBottom: 4,
lineHeight: 18,
}}
>
{t('mail.connect_sheet_subtitle')}
</Text>
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 10 }}>
{providers.map((p) => (
<TouchableOpacity
key={p.id}
onPress={p.disabled ? undefined : () => onSelect(p)}
activeOpacity={p.disabled ? 1 : 0.7}
disabled={p.disabled}
style={{ width: '47%', opacity: p.disabled ? 0.45 : 1 }}
>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
gap: 10,
backgroundColor: colors.surface,
borderWidth: 1,
borderColor: colors.border,
borderRadius: 14,
padding: 14,
}}
>
<View
style={{
width: 36,
height: 36,
borderRadius: 10,
backgroundColor: p.color + '18',
alignItems: 'center',
justifyContent: 'center',
}}
>
<Ionicons name={p.icon} size={18} color={p.color} />
</View>
<View style={{ flex: 1 }}>
<Text
style={{ fontSize: 13, fontFamily: 'Nunito_700Bold', color: colors.text }}
numberOfLines={1}
>
{t(p.labelKey)}
</Text>
{p.disabled && p.disabledLabelKey && (
<Text
style={{
fontSize: 10,
fontFamily: 'Nunito_600SemiBold',
color: '#737373',
marginTop: 2,
}}
numberOfLines={1}
>
{t(p.disabledLabelKey)}
</Text>
)}
</View>
{!p.disabled && (
<Ionicons name="chevron-forward" size={14} color={colors.border} />
)}
</View>
</TouchableOpacity>
))}
</View>
</ScrollView>
);
}