import { ImapFlow } from "imapflow"; import mysql from "mysql2/promise"; const databaseUrl = process.env.DATABASE_URL; if (!databaseUrl) throw new Error("Variable DATABASE_URL manquante"); const connection = await mysql.createConnection(databaseUrl); try { const [rows] = await connection.query(` SELECT emailImportAddress, emailImportHost, emailImportPort, azureTenantId, azureClientId, azureClientSecret FROM importSettings WHERE emailImportEnabled = 1 AND emailImportAuthMode = 'oauth2' ORDER BY id LIMIT 1 `); const settings = rows[0]; if (!settings) throw new Error("Aucune configuration OAuth2 IMAP active"); const tenantId = settings.azureTenantId || process.env.AZURE_AD_TENANT_ID; const clientId = settings.azureClientId || process.env.AZURE_AD_CLIENT_ID; const clientSecret = settings.azureClientSecret || process.env.AZURE_AD_CLIENT_SECRET; if (!tenantId || !clientId || !clientSecret) { throw new Error("Configuration Azure AD incomplète"); } const response = await fetch( `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ client_id: clientId, client_secret: clientSecret, scope: "https://outlook.office365.com/.default", grant_type: "client_credentials", }), }, ); const tokenResponse = await response.json(); if (!response.ok || !tokenResponse.access_token) { throw new Error(`Échec OAuth2 : ${tokenResponse.error || response.status}`); } const host = settings.emailImportHost || "outlook.office365.com"; const client = new ImapFlow({ host, port: settings.emailImportPort || 993, secure: true, auth: { user: settings.emailImportAddress, accessToken: tokenResponse.access_token, }, tls: { servername: host, rejectUnauthorized: true }, verifyOnly: true, logger: false, }); try { await client.connect(); console.log(`Authentification ImapFlow OAuth2 réussie pour ${settings.emailImportAddress}`); } finally { if (client.usable) await client.logout().catch(() => client.close()); else client.close(); } } finally { await connection.end(); }