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>
240 lines
8.1 KiB
TypeScript
240 lines
8.1 KiB
TypeScript
import { ImapFlow } from "imapflow";
|
|
import {
|
|
getMailConnections,
|
|
deleteOldMailBlocked,
|
|
getAlreadyBlockedUidSet,
|
|
insertMailBlocked,
|
|
upsertMailBlockedStat,
|
|
updateMailConnectionScanStats,
|
|
} from "../../db/mail";
|
|
import { getBlocklistedDomainsSet } from "../../db/domains";
|
|
import { getProfile } from "../../db/profile";
|
|
import { getPlanLimits } from "../../utils/plan-features";
|
|
import { resolveProviderMeta } from "../../utils/imap-providers";
|
|
// Single-Source-of-Truth (Mo's Finding #4)
|
|
// @ts-expect-error — .mjs ohne types, GAMBLING_KEYWORDS ist string[]
|
|
import { GAMBLING_KEYWORDS } from "../../utils/gambling-keywords.mjs";
|
|
|
|
|
|
/**
|
|
* POST /api/mail/scan-internal
|
|
* Called by cron or IMAP proxy. Scans ALL mailbox folders.
|
|
* Free: only custom domains + keywords. Pro/Legend: global blocklist + custom.
|
|
*/
|
|
export default defineEventHandler(async (event) => {
|
|
const secret = getHeader(event, "x-admin-secret");
|
|
const adminSecret = process.env.NUXT_ADMIN_SECRET || process.env.ADMIN_SECRET;
|
|
if (!secret || !adminSecret || secret !== adminSecret) {
|
|
throw createError({ statusCode: 401, message: "Unauthorized" });
|
|
}
|
|
|
|
const body = (await readBody(event)) as { userId?: string };
|
|
const userId = body?.userId;
|
|
if (!userId)
|
|
throw createError({ statusCode: 400, message: "userId missing" });
|
|
|
|
const connections = await getMailConnections(userId);
|
|
if (connections.length === 0) return { ok: true, scanned: 0, blocked: 0, skippedNoConsent: 0 };
|
|
|
|
// Consent-Gate (DSGVO Art. 9): Cron ist NICHT user-initiiert — Art. 9-Daten dürfen
|
|
// ohne explizite Einwilligung nicht verarbeitet werden. Connections ohne consent_at überspringen.
|
|
const skippedNoConsent = connections.filter((c) => !c.consentAt).length;
|
|
const eligibleConnections = connections.filter((c) => c.consentAt);
|
|
|
|
if (skippedNoConsent > 0) {
|
|
console.log(
|
|
`[scan-internal] skipping ${skippedNoConsent} connections for userId=${userId} — no consent_at (pending re-consent)`,
|
|
);
|
|
}
|
|
|
|
if (eligibleConnections.length === 0) {
|
|
return { ok: true, scanned: 0, blocked: 0, skippedNoConsent };
|
|
}
|
|
|
|
// Plan-aware blocklist
|
|
// Grace-Period: wenn globalBlocklistGraceUntil noch in der Zukunft liegt,
|
|
// behandeln wir den User als 'full' auch wenn sein Plan 'curated' sagt.
|
|
const profile = await getProfile(userId);
|
|
const limits = getPlanLimits(profile?.plan ?? "free");
|
|
const inGrace =
|
|
profile?.globalBlocklistGraceUntil != null &&
|
|
new Date(profile.globalBlocklistGraceUntil) > new Date();
|
|
const includeGlobal = limits.globalBlocklist === "full" || inGrace;
|
|
|
|
await deleteOldMailBlocked(userId);
|
|
|
|
let totalScanned = 0;
|
|
let totalBlocked = 0;
|
|
|
|
for (const connection of eligibleConnections) {
|
|
let password: string;
|
|
try {
|
|
password = decrypt(connection.passwordEncrypted);
|
|
} catch {
|
|
continue;
|
|
}
|
|
|
|
// useStarttls=true → STARTTLS (secure=false + requireTLS=true)
|
|
// rejectUnauthorized=false → self-signed Certs zulassen (nur Custom-IMAP)
|
|
const useImplicitTls = !connection.useStarttls;
|
|
const imap = new ImapFlow({
|
|
host: connection.imapHost,
|
|
port: connection.imapPort,
|
|
secure: useImplicitTls,
|
|
...(connection.useStarttls ? { requireTLS: true } : {}),
|
|
auth: { user: connection.email, pass: password },
|
|
logger: false,
|
|
tls: { rejectUnauthorized: connection.rejectUnauthorized ?? true },
|
|
});
|
|
|
|
let scanned = 0;
|
|
let newlyBlocked = 0;
|
|
|
|
try {
|
|
await imap.connect();
|
|
|
|
// Scan ALL mailbox folders (not just hardcoded list)
|
|
const mailboxes = await imap.list();
|
|
const scannable = mailboxes.filter(
|
|
(mb: any) => !mb.flags?.has("\\Noselect"),
|
|
);
|
|
console.log(
|
|
`[scan-internal] ${connection.email} scanning ${scannable.length} folders`,
|
|
);
|
|
|
|
for (const mb of scannable) {
|
|
let lock: any;
|
|
try {
|
|
lock = await imap.getMailboxLock(mb.path);
|
|
} catch {
|
|
continue;
|
|
}
|
|
try {
|
|
const SCAN_LIMIT = 200;
|
|
const status = await imap.status(mb.path, { messages: true });
|
|
const msgCount = (status as any).messages ?? 0;
|
|
if (msgCount === 0) continue;
|
|
|
|
const fetchRange =
|
|
msgCount > SCAN_LIMIT ? `${msgCount - SCAN_LIMIT + 1}:*` : "1:*";
|
|
const allMessages = await imap.fetchAll(fetchRange, {
|
|
envelope: true,
|
|
});
|
|
scanned += allMessages.length;
|
|
totalScanned += allMessages.length;
|
|
|
|
const allUids = allMessages.map(
|
|
(m: any) => `${mb.path}:${String(m.uid ?? m.seq)}`,
|
|
);
|
|
const [blockedDomainSet, alreadyBlockedSet] = await Promise.all([
|
|
getBlocklistedDomainsSet(
|
|
allMessages
|
|
.map(
|
|
(m: any) =>
|
|
(m.envelope?.from?.[0]?.address ?? "")
|
|
.toLowerCase()
|
|
.split("@")[1] ?? "",
|
|
)
|
|
.filter(Boolean),
|
|
userId,
|
|
includeGlobal,
|
|
),
|
|
getAlreadyBlockedUidSet(allUids, userId),
|
|
]);
|
|
|
|
const toInsert: Parameters<typeof insertMailBlocked>[0] = [];
|
|
const uidsToDelete: string[] = [];
|
|
|
|
for (const msg of allMessages) {
|
|
const from = msg.envelope?.from?.[0];
|
|
const senderEmail = (from?.address ?? "").toLowerCase();
|
|
const senderName = from?.name ?? null;
|
|
const subject = (msg.envelope?.subject ?? "").trim();
|
|
const msgDate = msg.envelope?.date ?? new Date();
|
|
const uid = `${mb.path}:${String(msg.uid ?? msg.seq)}`;
|
|
|
|
const haystack = `${senderEmail} ${subject}`.toLowerCase();
|
|
const isGamblingKeyword = GAMBLING_KEYWORDS.some((kw) =>
|
|
haystack.includes(kw),
|
|
);
|
|
const senderDomain = senderEmail.split("@")[1] ?? "";
|
|
const isBlocklisted = senderDomain
|
|
? blockedDomainSet.has(senderDomain)
|
|
: false;
|
|
|
|
if (!isGamblingKeyword && !isBlocklisted) continue;
|
|
if (alreadyBlockedSet.has(uid)) continue;
|
|
|
|
uidsToDelete.push(String(msg.uid));
|
|
toInsert.push({
|
|
userId,
|
|
connectionId: connection.id,
|
|
gmailMessageId: uid,
|
|
senderEmail: senderEmail || "unbekannt",
|
|
senderName,
|
|
subject: subject.slice(0, 200) || "(kein Betreff)",
|
|
receivedAt: msgDate,
|
|
action: "deleted",
|
|
});
|
|
newlyBlocked++;
|
|
}
|
|
|
|
if (uidsToDelete.length > 0) {
|
|
try {
|
|
await imap.messageDelete(uidsToDelete.join(","), { uid: true });
|
|
} catch {
|
|
try {
|
|
for (const uid of uidsToDelete) {
|
|
await imap
|
|
.messageFlagsAdd(uid, ["\\Deleted"], { uid: true })
|
|
.catch(() => {});
|
|
}
|
|
await (imap as any).expunge().catch(() => {});
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
}
|
|
console.log(
|
|
`[scan-internal] ${connection.email} | ${mb.path} | deleted ${uidsToDelete.length} gambling mails`,
|
|
);
|
|
}
|
|
|
|
await insertMailBlocked(toInsert);
|
|
|
|
// Aggregat-Stats aktualisieren (vor 24h-Cleanup resistent)
|
|
if (toInsert.length > 0) {
|
|
const providerMeta = resolveProviderMeta(connection.imapHost);
|
|
await upsertMailBlockedStat({
|
|
userId,
|
|
mailConnectionId: connection.id,
|
|
provider: providerMeta.provider,
|
|
providerLabel: providerMeta.providerLabel,
|
|
count: toInsert.length,
|
|
});
|
|
}
|
|
} finally {
|
|
lock.release();
|
|
}
|
|
}
|
|
|
|
await imap.logout();
|
|
} catch {
|
|
try {
|
|
await imap.logout();
|
|
} catch {}
|
|
}
|
|
|
|
totalBlocked += newlyBlocked;
|
|
await updateMailConnectionScanStats(
|
|
connection.id,
|
|
scanned,
|
|
newlyBlocked,
|
|
connection.emailsBlocked,
|
|
connection.emailsScanned,
|
|
connection.scanInterval,
|
|
);
|
|
}
|
|
|
|
return { ok: true, scanned: totalScanned, blocked: totalBlocked, skippedNoConsent };
|
|
});
|