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

251 lines
8.3 KiB
TypeScript

import { useEffect, useRef, useState } from 'react';
import { View, ActivityIndicator, AppState, Platform } from 'react-native';
import { useRouter } from 'expo-router';
import * as Notifications from 'expo-notifications';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../../stores/auth';
import { useNotificationStore } from '../../stores/notifications';
import { useMailConsentStore } from '../../stores/mailConsent';
import { useColors } from '../../lib/theme';
import { NativeTabs } from '../../components/NativeTabs';
import { MailConsentReminderSheet } from '../../components/mail/MailConsentReminderSheet';
import { protection } from '../../lib/protection';
import { preloadTabIcons, getTabIcon } from '../../lib/tabIcons';
import { apiFetch } from '../../lib/api';
export default function AppLayout() {
const router = useRouter();
const { t } = useTranslation();
const { session, loading } = useAuthStore();
const colors = useColors();
const loadNotifications = useNotificationStore((s) => s.load);
const startRealtime = useNotificationStore((s) => s.startRealtime);
const stopRealtime = useNotificationStore((s) => s.stopRealtime);
const resetNotifications = useNotificationStore((s) => s.reset);
const { visible: consentVisible, connections: consentConnections, show: showConsent, hide: hideConsent, markConsented } = useMailConsentStore();
const rearmInFlightRef = useRef(false);
const bypassNotifiedRef = useRef(false);
// Android-Tab-Icons müssen async aus Ionicons-Font generiert werden (kein
// SF-Symbol-Support). preloadTabIcons() läuft schon beim Modul-Import — hier
// nur den ready-State tracken damit wir re-rendern wenn der Cache fertig ist.
const [tabIconsReady, setTabIconsReady] = useState(Platform.OS !== 'android');
useEffect(() => {
if (Platform.OS === 'android' && !tabIconsReady) {
preloadTabIcons().then(() => setTabIconsReady(true));
}
}, [tabIconsReady]);
useEffect(() => {
if (!loading && !session) {
router.replace('/signin');
}
}, [session, loading]);
useEffect(() => {
if (!session) {
resetNotifications();
return;
}
loadNotifications();
startRealtime();
return () => {
stopRealtime();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [session?.user?.id]);
useEffect(() => {
if (!session) return;
apiFetch<{ id: string; email: string }[]>('/api/mail-connections/pending-consent')
.then((pending) => {
if (pending.length > 0) {
showConsent(pending);
}
})
.catch(() => {});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [session?.user?.id]);
useEffect(() => {
if (!session || Platform.OS !== 'ios') return;
let cancelled = false;
let pollTimer: ReturnType<typeof setInterval> | null = null;
async function notifyBypassDetected(): Promise<boolean> {
const perms = await Notifications.getPermissionsAsync();
let granted = perms.granted || perms.ios?.status === Notifications.IosAuthorizationStatus.PROVISIONAL;
if (!granted) {
const req = await Notifications.requestPermissionsAsync();
granted = req.granted || req.ios?.status === Notifications.IosAuthorizationStatus.PROVISIONAL;
}
if (!granted) return false;
await Notifications.scheduleNotificationAsync({
content: {
title: 'ReBreak Schutz manipuliert',
body: 'Tippe hier, um den Schutz sofort wieder zu aktivieren.',
sound: 'default',
data: { type: 'protection_bypass_detected' },
},
trigger: null,
});
return true;
}
async function enforceProtection() {
if (cancelled || rearmInFlightRef.current) return;
try {
// Self-Heal: wenn der Schutz an sein soll der VpnService aber tot ist
// (Reinstall / OS-Kill) → neu starten, bevor wir den State lesen.
await protection.reconcileVpn();
if (cancelled) return;
const state = await protection.getCombinedState();
if (cancelled) return;
if (state.phase !== 'recoveringFromBypass') {
bypassNotifiedRef.current = false;
return;
}
if (bypassNotifiedRef.current) return;
bypassNotifiedRef.current = true;
const notified = await notifyBypassDetected();
if (!notified) {
// Fallback wenn Notifications nicht erlaubt sind. Reaktivierung setzt
// NUR den Filter/VPN wieder — kein a11y-Prompt (das passiert nur beim
// ersten Einrichten).
rearmInFlightRef.current = true;
router.replace('/blocker');
await protection.activate().catch(() => null);
}
} finally {
rearmInFlightRef.current = false;
}
}
async function onBypassNotificationTap() {
if (rearmInFlightRef.current) return;
rearmInFlightRef.current = true;
try {
router.replace('/blocker');
// Reaktivierung = nur Filter/VPN wieder setzen (a11y nur beim ersten Mal).
await protection.activate().catch(() => null);
} finally {
rearmInFlightRef.current = false;
}
}
// Initial check + foreground re-check + periodisches Polling als Fallback.
enforceProtection();
const notifTapSub = Notifications.addNotificationResponseReceivedListener((response) => {
const type = response.notification.request.content.data?.type;
if (type === 'protection_bypass_detected') {
void onBypassNotificationTap();
}
});
Notifications.getLastNotificationResponseAsync().then((response) => {
const type = response?.notification.request.content.data?.type;
if (type === 'protection_bypass_detected') {
void onBypassNotificationTap();
}
});
const appStateSub = AppState.addEventListener('change', (s) => {
if (s === 'active') {
enforceProtection();
}
});
pollTimer = setInterval(enforceProtection, 15000);
return () => {
cancelled = true;
notifTapSub.remove();
appStateSub.remove();
if (pollTimer) clearInterval(pollTimer);
};
}, [session, router]);
if (loading || !session) {
return (
<View style={{ flex: 1, backgroundColor: colors.bg, alignItems: 'center', justifyContent: 'center' }}>
<ActivityIndicator color={colors.brandOrange} size="large" />
</View>
);
}
return (
<>
{consentVisible && (
<MailConsentReminderSheet
connections={consentConnections}
onDismiss={hideConsent}
onConsented={markConsented}
/>
)}
<NativeTabs
sidebarAdaptable
hapticFeedbackEnabled
tabBarActiveTintColor={colors.brandOrange}
tabBarInactiveTintColor="#d1d1d6"
scrollEdgeAppearance="default"
tabLabelStyle={{
fontFamily: 'Nunito_600SemiBold',
fontSize: 11,
}}
>
<NativeTabs.Screen
name="index"
options={{
title: t('tabs.home'),
tabBarIcon: () =>
Platform.OS === 'ios'
? { sfSymbol: 'house.fill' }
: (getTabIcon('home') as any),
}}
/>
<NativeTabs.Screen
name="chat"
options={{
title: t('tabs.chat'),
tabBarIcon: () =>
Platform.OS === 'ios'
? { sfSymbol: 'bubble.left.and.bubble.right.fill' }
: (getTabIcon('chat') as any),
}}
/>
<NativeTabs.Screen
name="coach"
options={{
title: t('tabs.coach'),
tabBarIcon: () =>
Platform.OS === 'ios'
? { sfSymbol: 'sparkles' }
: (getTabIcon('coach') as any),
}}
/>
<NativeTabs.Screen
name="blocker"
options={{
title: t('tabs.blocker'),
tabBarIcon: () =>
Platform.OS === 'ios'
? { sfSymbol: 'checkmark.shield.fill' }
: (getTabIcon('blocker') as any),
}}
/>
<NativeTabs.Screen
name="mail"
options={{
title: t('tabs.mail'),
tabBarIcon: () =>
Platform.OS === 'ios'
? { sfSymbol: 'envelope.fill' }
: (getTabIcon('mail') as any),
}}
/>
<NativeTabs.Screen name="notifications" options={{ href: null }} />
</NativeTabs>
</>
);
}