"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const joi_1 = __importDefault(require("joi"));
const validationWrapper_js_1 = require("../core/validation/validationWrapper.js");
const hdbError_js_1 = require("../core/utility/errors/hdbError.js");
const keys_js_1 = require("../core/security/keys.js");
const tokenAuthentication_ts_1 = require("../core/security/tokenAuthentication.js");
const Server_ts_1 = require("../core/server/Server.js");
const jwtKeyMap = {
    '.jwtPrivate': 'privateKey',
    '.jwtPublic': 'publicKey',
    '.jwtPass': 'passphrase',
};
/**
 * Resolves a cryptographic key by name for use in replication or resource contexts.
 *
 * Supports JWT RSA keys (`.jwtPrivate`, `.jwtPublic`, `.jwtPass`) and arbitrary
 * private keys managed by the key store.
 *
 * @param req - The request object. Must have `bypass_auth` set to `true` — direct
 *              calls from the operations API are not permitted.
 * @param req.name - The name of the key to retrieve.
 * @returns The resolved key material as a string.
 */
async function keyResolver(req) {
    const validation = (0, validationWrapper_js_1.validateBySchema)(req, joi_1.default.object({
        name: joi_1.default.string().required(),
    }));
    if (validation)
        throw new hdbError_js_1.ClientError(validation.message);
    const { name } = req;
    // Handle JWT keys
    const jwtField = jwtKeyMap[name];
    if (jwtField) {
        const jwt = await (0, tokenAuthentication_ts_1.getJWTRSAKeys)();
        return jwt[jwtField];
    }
    // Handle private keys
    const privateKeys = (0, keys_js_1.getPrivateKeys)();
    const privateKey = privateKeys.get(name);
    if (privateKey) {
        return privateKey;
    }
    throw new hdbError_js_1.ClientError('Key not found');
}
Server_ts_1.server.registerOperation?.({
    name: 'get_key',
    execute: keyResolver,
    httpMethod: 'GET',
    parametersSchema: [{ name: 'hostname', in: 'path', schema: { type: 'string' } }],
});
//# sourceMappingURL=keyService.js.map