"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTokenPublicKey = void 0;
const client_kms_1 = require("@aws-sdk/client-kms");
const envs_1 = require("../envs");
const internalAuthKeyName = 'signature-key';
const getKey = async (kmsClient, keyName) => {
    const keyAlias = keyName === internalAuthKeyName
        ? `alias/${(0, envs_1.maybeGetEnvParam)('ENVIRONMENT')}-security-auth-management-${keyName}`
        : `alias/orgs/jwtsigningkey/${keyName}`;
    const getKeyCommand = new client_kms_1.GetPublicKeyCommand({
        KeyId: keyAlias,
    });
    const key = await kmsClient.send(getKeyCommand);
    if (!key.KeyId || !key.PublicKey) {
        throw Error(`Signing Key ${keyAlias} could not be retrieved`);
    }
    return {
        keyId: key.KeyId,
        publicKey: Buffer.from(key.PublicKey).toString('base64'),
        keyAlias: keyAlias,
    };
};
const getTokenPublicKey = async (keyName = internalAuthKeyName) => {
    const prefix = '-----BEGIN PUBLIC KEY-----\n';
    const postfix = '-----END PUBLIC KEY-----';
    const kmsClient = new client_kms_1.KMSClient({
        region: (0, envs_1.maybeGetEnvParam)('AWS_REGION')
    });
    const key = await getKey(kmsClient, keyName);
    const publicKeyLines = key.publicKey.match(/.{0,64}/g);
    if (!publicKeyLines) {
        throw Error(`Could not parse public key ${keyName}`);
    }
    return prefix + publicKeyLines.join('\n') + postfix;
};
exports.getTokenPublicKey = getTokenPublicKey;
//# sourceMappingURL=token.js.map