import { resolveCredential } from './credential.ts'; import { ConfidentialClientApplication } from '@azure/msal-node'; import type AuthManager from '../auth/auth-manager.ts'; export async function acquireAppToken(req: any, auth?: AuthManager): Promise { // If caller provided an AuthManager and client provided a session id, prefer delegated flow const sessionId = req.header('x-session-id') || req.header('x-sessionid'); if (sessionId && auth) { return auth.acquireTokenBySessionId(sessionId); } // Fallback to client-credential using ENV (keep supporting existing env-based usage) const credential = resolveCredential(req); const tenantId = credential.tenantId ?? process.env.TENANT_ID ?? 'common'; const clientId = credential.clientId ?? process.env.CLIENT_ID; const clientSecret = process.env.CLIENT_SECRET; if (!clientId || !clientSecret) { throw new Error('Client credentials not configured (CLIENT_ID/CLIENT_SECRET)'); } const cca = new ConfidentialClientApplication({ auth: { clientId, clientSecret, authority: `https://login.microsoftonline.com/${tenantId}/v2.0`, }, }); const scopes = credential.scopes && credential.scopes.length ? credential.scopes : (process.env.GRAPH_SCOPES || '').split(' ').filter(Boolean); const tokenResponse = await cca.acquireTokenByClientCredential({ scopes }); if (!tokenResponse?.accessToken) throw new Error('Failed to acquire access token'); return tokenResponse.accessToken; } export default acquireAppToken;