import * as jose from 'jose';
import { webcrypto } from 'crypto';
// Polyfill globalThis.crypto for Node 18 (jose requires Web Crypto API)
if (!globalThis.crypto) {
    globalThis.crypto = webcrypto;
}
export { jose };
// Cache the JWKS remote key set per tenant to avoid repeated fetches
const jwksCache = new Map();
function getJWKS(tenantId) {
    let jwks = jwksCache.get(tenantId);
    if (!jwks) {
        const url = new URL(`https://login.microsoftonline.com/${tenantId}/discovery/v2.0/keys`);
        jwks = jose.createRemoteJWKSet(url);
        jwksCache.set(tenantId, jwks);
    }
    return jwks;
}
// Entra config from environment — same vars used by http.ts
const entraClientId = process.env.ENTRA_CLIENT_ID;
const entraTenantId = process.env.ENTRA_TENANT_ID;
/**
 * Verify an Entra ID token (JWT) and extract identity claims.
 * Returns the identity on success, or throws on failure.
 */
export async function verifyEntraToken(idToken) {
    if (!entraClientId || !entraTenantId) {
        throw new Error('Entra ID not configured on server');
    }
    const jwks = getJWKS(entraTenantId);
    const { payload } = await jose.jwtVerify(idToken, jwks, {
        issuer: `https://login.microsoftonline.com/${entraTenantId}/v2.0`,
        audience: entraClientId,
        clockTolerance: 300, // Accept tokens expired up to 5 minutes ago
    });
    const oid = payload.oid;
    const email = (payload.preferred_username || payload.email);
    const tid = payload.tid;
    if (!oid) {
        throw new Error('Token missing oid claim');
    }
    if (!tid) {
        throw new Error('Token missing tid claim');
    }
    if (tid !== entraTenantId) {
        throw new Error(`Tenant mismatch: expected ${entraTenantId}, got ${tid}`);
    }
    return {
        oid,
        email: email || 'unknown',
        tid,
    };
}
/**
 * Check whether Entra identity verification is configured on this server.
 */
export function isEntraConfigured() {
    return !!(entraClientId && entraTenantId);
}
//# sourceMappingURL=entra.js.map