"use strict";
/**
 * JWT License Issuer -- Server-side license creation for @connexum/ai-governance.
 *
 * Creates RS256-signed JWT license tokens with proper claims for each tier.
 * Used by the license server, NOT shipped to end users.
 *
 * @connexum/ai-governance
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.JwtIssuer = void 0;
const crypto = __importStar(require("crypto"));
const jwt_validator_1 = require("./jwt-validator");
/* ------------------------------------------------------------------ */
/*  JwtIssuer                                                          */
/* ------------------------------------------------------------------ */
class JwtIssuer {
    config;
    constructor(config) {
        this.config = {
            defaultDurationDays: 365,
            defaultGracePeriodDays: 7,
            ...config,
        };
    }
    /**
     * Issue a new license JWT.
     */
    issue(request) {
        const now = Math.floor(Date.now() / 1000);
        const durationDays = request.durationDays ?? this.config.defaultDurationDays;
        const exp = now + (durationDays * 86400);
        const tierLimits = jwt_validator_1.TIER_LIMITS[request.tier];
        const features = [...tierLimits.features];
        if (request.additionalFeatures) {
            for (const f of request.additionalFeatures) {
                if (!features.includes(f))
                    features.push(f);
            }
        }
        const claims = {
            tier: request.tier,
            org: request.org,
            maxAgents: request.maxAgents ?? tierLimits.maxAgents,
            maxPacks: request.maxPacks ?? tierLimits.maxPacks,
            features,
            iss: 'my-cc.io',
            aud: '@connexum/ai-governance',
            sub: request.org,
            iat: now,
            exp,
            jti: `lic_${crypto.randomBytes(16).toString('hex')}`,
            kid: this.config.kid,
            offlineGracePeriodDays: request.offlineGracePeriodDays ?? this.config.defaultGracePeriodDays,
        };
        const token = this.sign(claims);
        return {
            token,
            claims,
            expiresAt: new Date(exp * 1000).toISOString(),
        };
    }
    /**
     * Sign claims into a JWT.
     */
    sign(claims) {
        const header = {
            alg: 'RS256',
            typ: 'JWT',
            kid: this.config.kid,
        };
        const headerB64 = base64UrlEncode(JSON.stringify(header));
        const payloadB64 = base64UrlEncode(JSON.stringify(claims));
        const signatureInput = `${headerB64}.${payloadB64}`;
        const signer = crypto.createSign('RSA-SHA256');
        signer.update(signatureInput);
        const signature = signer.sign(this.config.privateKey);
        return `${signatureInput}.${bufferToBase64Url(signature)}`;
    }
    /**
     * Generate an RSA-2048 key pair for license signing.
     * Returns { publicKey, privateKey } in PEM format.
     */
    static generateKeyPair() {
        const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
            modulusLength: 2048,
            publicKeyEncoding: { type: 'spki', format: 'pem' },
            privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
        });
        return { publicKey, privateKey };
    }
}
exports.JwtIssuer = JwtIssuer;
/* ------------------------------------------------------------------ */
/*  Base64URL helpers                                                  */
/* ------------------------------------------------------------------ */
function base64UrlEncode(str) {
    return Buffer.from(str)
        .toString('base64')
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=+$/, '');
}
function bufferToBase64Url(buf) {
    return buf
        .toString('base64')
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=+$/, '');
}
//# sourceMappingURL=jwt-issuer.js.map