rebreak-monorepo/backend/nitro.config.ts
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

91 lines
5.2 KiB
TypeScript

import { defineNitroConfig } from "nitropack/config";
export default defineNitroConfig({
compatibilityDate: "latest",
srcDir: "server",
preset: "node-server",
// Supabase als external dep — nicht bundlen
externals: {
inline: [/^(?!@supabase\/supabase-js)/],
},
imports: {
dirs: ["db", "db/**", "utils", "utils/**"],
exclude: ["**/node_modules/**"],
},
runtimeConfig: {
// ─── Database / Core ─────────────────────────────────────────────────
databaseUrl: process.env.DATABASE_URL ?? process.env.NUXT_DATABASE_URL ?? "",
encryptionKey: process.env.ENCRYPTION_KEY ?? "",
// ─── Admin / Cron ────────────────────────────────────────────────────
adminSecret: process.env.ADMIN_SECRET ?? "",
cronSecret: process.env.CRON_SECRET ?? "",
// ─── LLM-Provider ────────────────────────────────────────────────────
// Infisical staging hat NUXT_*-prefix für openrouter+groq, andere ohne.
openrouterApiKey: process.env.OPENROUTER_API_KEY ?? process.env.NUXT_OPENROUTER_API_KEY ?? "",
openaiApiKey: process.env.OPENAI_API_KEY ?? process.env.NUXT_OPENAI_API_KEY ?? "",
groqApiKey: process.env.GROQ_API_KEY ?? process.env.NUXT_GROQ_API_KEY ?? "",
googleAiApiKey: process.env.GOOGLE_AI_API_KEY ?? "",
// ─── TTS-Provider ────────────────────────────────────────────────────
googleApiKey: process.env.GOOGLE_API_KEY ?? process.env.NUXT_GOOGLE_API_KEY ?? "",
deepgramApiKey: process.env.DEEPGRAM_API_KEY ?? process.env.NUXT_DEEPGRAM_API_KEY ?? "",
azureTtsKey: process.env.AZURE_TTS_KEY ?? "",
azureTtsRegion: process.env.AZURE_TTS_REGION ?? "",
// NEU im backend/-Layout (existieren in nuxt.config.ts NICHT, aber backend code liest sie)
cartesiaApiKey: process.env.CARTESIA_API_KEY ?? "",
cartesiaVoiceId: process.env.CARTESIA_VOICE_ID ?? "",
elevenlabsApiKey: process.env.ELEVENLABS_API_KEY ?? "",
elevenlabsVoiceId: process.env.ELEVENLABS_VOICE_ID ?? "",
// ─── Supabase (Server-only) ──────────────────────────────────────────
// Im alten Nuxt-Layout via @nuxtjs/supabase auto-injected. In standalone Nitro
// explizit deklarieren, damit auth/middleware nicht 500't.
// server/utils/auth.ts:32 liest `config.public.supabase ?? config.supabase`,
// also beide Pfade müssen existieren.
// Infisical staging-Namen: SUPABASE_KEY (nicht ANON_KEY), SUPABASE_SERVICE_KEY
// (nicht SERVICE_ROLE_KEY). NIE umbenennen ohne Infisical-secret-rotation.
supabaseUrl: process.env.SUPABASE_URL ?? "https://db-staging.rebreak.org",
supabaseAnonKey: process.env.SUPABASE_KEY ?? process.env.SUPABASE_ANON_KEY ?? "",
supabaseServiceKey: process.env.SUPABASE_SERVICE_KEY ?? process.env.SUPABASE_SERVICE_ROLE_KEY ?? "",
// ─── Stripe ──────────────────────────────────────────────────────────
stripeSecretKey: process.env.STRIPE_SECRET_KEY ?? "",
stripeWebhookSecret: process.env.STRIPE_WEBHOOK_SECRET ?? "",
// ─── Email / External APIs ───────────────────────────────────────────
resendApiKey: process.env.RESEND_API_KEY ?? "",
// ─── Microsoft OAuth (PKCE, Public Client) ───────────────────────────────
// Client-ID der Azure-App-Registrierung "Rebreak Mail Access".
// Tenant: 'common' (Multi-Tenant + Personal-Accounts) — hardcoded im Code.
// Kein client_secret: Public Client / PKCE-Flow (keine Client-Secret-Exposure).
// Infisical secret name: MS_OAUTH_CLIENT_ID
msOauthClientId: process.env.MS_OAUTH_CLIENT_ID ?? "427575e1-0ec5-4468-b4a2-7ae3ce99a154",
// ─── Bot-User-IDs (DB-User-References für Lyra/Rebreak-Bot-Posts) ────
lyraBotUserId: process.env.LYRA_BOT_USER_ID ?? "",
rebreakBotUserId: process.env.REBREAK_BOT_USER_ID ?? "",
// ─── Public (client-readable) ────────────────────────────────────────
public: {
stripePublishableKey: process.env.STRIPE_PUBLISHABLE_KEY ?? "",
appUrl: process.env.APP_URL ?? "https://staging.rebreak.org",
apiBase: process.env.API_BASE ?? "https://staging.rebreak.org",
// server/utils/auth.ts liest config.public.supabase.{url,key}
// — wenn das fehlt, 500-cascade auf allen authentifizierten Routes
// (Incident 2026-05-06).
supabase: {
url:
process.env.SUPABASE_URL ??
"https://db-staging.rebreak.org",
key: process.env.SUPABASE_KEY ?? process.env.SUPABASE_ANON_KEY ?? "",
},
},
},
});