"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodeAzureSessionsTokenClaims = decodeAzureSessionsTokenClaims;
exports.isServicePrincipalToken = isServicePrincipalToken;
exports.formatTokenIdentityForDiagnostics = formatTokenIdentityForDiagnostics;
function decodeAzureSessionsTokenClaims(token) {
    try {
        const payloadSegment = token.split('.')[1];
        if (!payloadSegment) {
            return null;
        }
        const json = Buffer.from(payloadSegment, 'base64url').toString('utf8');
        return JSON.parse(json);
    }
    catch {
        return null;
    }
}
/** App-only (service principal) tokens use idtyp=app. User tokens via az cli still include appid. */
function isServicePrincipalToken(claims) {
    if (!claims) {
        return false;
    }
    if (claims.idtyp === 'app') {
        return true;
    }
    if (claims.idtyp === 'user') {
        return false;
    }
    // Fallback: app-only tokens lack a username
    const hasUserIdentity = Boolean(claims.preferred_username ?? claims.upn);
    return !hasUserIdentity && Boolean(claims.appid);
}
function formatTokenIdentityForDiagnostics(claims) {
    if (!claims) {
        return 'unknown (could not decode token)';
    }
    const user = claims.preferred_username ?? claims.upn ?? 'unknown-user';
    const oid = claims.oid ?? 'unknown-oid';
    const aud = Array.isArray(claims.aud) ? claims.aud.join(',') : (claims.aud ?? 'unknown-aud');
    if (isServicePrincipalToken(claims)) {
        return `service-principal appid=${claims.appid ?? claims.oid}, oid=${oid}, aud=${aud}`;
    }
    const viaApp = claims.appid ? ` (via client app ${claims.appid})` : '';
    return `user ${user}${viaApp}, oid=${oid}, aud=${aud}`;
}
//# sourceMappingURL=jwtClaims.js.map