"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LicenseType = exports.LicenseOrganization = exports.LicenseError = exports.LicenseService = exports.prodPublicKey = void 0;
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const logger_1 = require("../utils/logger");
const fs_1 = require("fs");
const path_1 = require("../utils/path");
exports.prodPublicKey = `-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAoaL0vbGVpI6fw/YY6vvf
QFHA097QBPIzLf+8LccaFaN7kz/pvX70V3clnmtE/vY5yhzGksypOX9CfcZpyH1/
nHmeJNWugts9SaO/+/SYC9iVmi34M/DjRQnKmhmAcd9/X6hxCwtf6nR32Igy2Z0X
iBvdUcstTrDT55YpHf+g2myVWqPfyv5+q9KlqrySb7Po/PGsdpth4Jqkqhl49hQv
6D0sp2wRHEqjtblOz4ZYyh++02Xir+mhAYxPPrhx4ymm4jPmiqYP5aUky4udPydF
lBHj/sKGzlU/kcd/jiws7l0Iy7DDV0ajRkbJ3C18hW7rs0xRxhGdySaj0VBA7vtR
Z7zjDADNm9KqLQPB9nKGPSBLzQBYW+mQP92seyKRd2f29g4hFkX+kkZnS7CAvfLs
jIBw7GlHuTiZCMAgiPatU/7WxneD8Qs/s+cMMk5CTImWL/BWdtd18TMjL1G/LiTA
3uNFnbdzrRYAC33/02W73dyk64uYtZ9rPkMJnYMMWMU8zpauQxzezxuSYCEtp2N8
6YsWnPaZkrdZKQxUsQ2AoDJ+GWYlMJZoNh+wj0pyZcZ/BEAGCvK3DcGlgjb2mgJX
SBAqI8x0afhfXqckthbsIaqi+0kdAgQV0VDKI0OCZgesrjwPlawmBbpgCdZ28oc3
4w1zLjAq74LInPITHxMzaaECAwEAAQ==
-----END PUBLIC KEY-----
`;
class LicenseService {
    logger = logger_1.Logger.getInstance("license.service");
    publicKey = exports.prodPublicKey;
    validateLicense(license) {
        let licensePayload;
        // argument -> env variable -> iocd.license.key file
        let licenseKeyString = license || process.env['IOCD_LICENSE_KEY'];
        if (!licenseKeyString) {
            this.logger.debug('No license key in environment variable, checking iocd.license.key file');
            try {
                const licenseFilePath = path_1.PathUtils.getLicensePath();
                licenseKeyString = (0, fs_1.readFileSync)(licenseFilePath, 'utf-8');
            }
            catch (error) {
                this.logger.debug('Error reading iocd.license.key file from config directory', error);
            }
        }
        if (!licenseKeyString) {
            this.logger.debug('No license key found in environment variable or iocd.license.key file');
            return {
                status: "Invalid",
                type: "Trial",
                isExpired: true,
                errorMessage: 'No license key found. Please set the `IOCD_LICENSE_KEY` environment variable or add a `iocd.license.key` file in the config folder.\n' +
                    'To acquire a valid license key, contact us at sales@interop.io'
            };
        }
        try {
            licensePayload = this.validateJWT(licenseKeyString);
        }
        catch (error) {
            this.logger.debug('Error validating license token', error);
            return {
                status: "Invalid",
                type: "Trial",
                isExpired: true,
                errorMessage: "The provided license key is invalid. To acquire a valid license key, contact us at sales@interop.io"
            };
        }
        const isPaidLicense = licensePayload.type.toLowerCase() === LicenseType.paid;
        const organization = licensePayload.organization.displayName ?? licensePayload.licensee;
        const expirationTimestamp = licensePayload.expiration ?? new Date().getTime() + 7 * 24 * 60 * 60 * 1000; // Default to 7 days from now if no expiration
        let isExpired = false;
        let expirationDate = undefined;
        if (licensePayload.expiration) {
            expirationDate = new Date(expirationTimestamp);
            isExpired = expirationDate <= new Date();
        }
        let isActive = isPaidLicense || (!isPaidLicense && !isExpired);
        let errorMessage = undefined;
        if (isPaidLicense) {
            if (!expirationDate) {
                this.logger.info(`Using a paid license that was issued for client "${organization}" with no expiration date.`);
            }
            else {
                if (isExpired) {
                    this.logger.warn(`Using a paid license that was issued for client "${organization}", but it has expired at ${expirationDate.toString()}`);
                }
                else {
                    this.logger.info(`Using a paid license that was issued for client "${organization}" and is valid until ${expirationDate.toString()}`);
                }
            }
        }
        else {
            if (!expirationDate) {
                // This should never happen, but just in case
                errorMessage = `The trial license for "${organization}" is missing an expiration date. To acquire a valid license key, contact us at sales@interop.io`;
                this.logger.warn(errorMessage);
                isActive = false;
            }
            else {
                // trial license
                if (isExpired) {
                    errorMessage = `The trial license for "${organization}" has expired at ${expirationDate.toString()}. To acquire a valid license key, contact us at sales@interop.io`;
                    this.logger.warn(errorMessage);
                }
                else {
                    this.logger.info(`Using a trial license that was issued for "${organization}" and is valid until ${expirationDate.toString()}`);
                }
            }
        }
        return {
            status: isActive ? "Active" : "Inactive",
            type: isPaidLicense ? "Paid" : "Trial",
            licensePayload,
            isExpired,
            errorMessage
        };
    }
    validateJWT(licenseKeyString) {
        if (!licenseKeyString ||
            typeof licenseKeyString !== 'string' ||
            !licenseKeyString.length) {
            throw new Error('The provided license key is not a valid string.');
        }
        try {
            const jwtPayload = jsonwebtoken_1.default.verify(licenseKeyString, this.publicKey, {
                algorithms: ['RS256'],
            });
            return jwtPayload;
        }
        catch (error) {
            this.logger.debug('Error validating license token', error);
            throw new Error('The provided license key is invalid. To acquire a valid license key, contact us at sales@interop.io');
        }
    }
    /**
     * Only called in unit tests.
     */
    setProdPublicKey() {
        this.publicKey = exports.prodPublicKey;
    }
    /**
     * Only called in unit tests.
     */
    setTestPublicKey(publicKey) {
        this.publicKey = publicKey;
    }
}
exports.LicenseService = LicenseService;
class LicenseError extends Error {
    licensePayload;
    constructor(message, licensePayload) {
        super(message);
        this.licensePayload = licensePayload;
    }
}
exports.LicenseError = LicenseError;
class LicenseOrganization {
    /**
     * Organization display name. Used in logs.
     * @example "InteropIO"
     */
    displayName;
    /**
     * Organization identifier. Unused.
     * @example "interopio"
     */
    identifier;
}
exports.LicenseOrganization = LicenseOrganization;
var LicenseType;
(function (LicenseType) {
    LicenseType["paid"] = "paid";
    LicenseType["trail"] = "trail";
})(LicenseType || (exports.LicenseType = LicenseType = {}));
exports.default = new LicenseService();
//# sourceMappingURL=license.service.js.map