"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAuthenticationDetails = exports.authVerify = void 0;
const https_1 = __importDefault(require("https"));
const errors_1 = require("../errors");
const logging_1 = require("../logging");
const generateAndSignRequest_1 = require("./generateAndSignRequest");
const normalizeRequest_1 = require("./normalizeRequest");
const authVerify = async (verifyCall) => {
    return new Promise((resolve, reject) => {
        let callResponse = '';
        const req = https_1.default.request({
            hostname: verifyCall.http.authority,
            port: 443,
            path: verifyCall.http.path,
            method: verifyCall.http.method,
            headers: verifyCall.headers,
        }, (res) => {
            res.setEncoding('utf-8');
            res.on('data', (chunk) => {
                callResponse += chunk;
            });
            if (!res.statusCode || res.statusCode !== 200) {
                reject({
                    statusCode: res.statusCode,
                    message: res.statusMessage,
                });
            }
            res.on('end', async () => {
                const authContext = JSON.parse(callResponse);
                resolve(authContext);
            });
        });
        req.on('error', (e) => {
            reject(e);
        });
        req.write(verifyCall.body);
        req.end();
    });
};
exports.authVerify = authVerify;
const getAuthenticationDetails = async (event, body) => {
    if (event.rawPath === '/auth' ||
        event.rawPath.startsWith('/auth/pages/')) {
        // /auth is the verify endpoint. Authentication/Authorization is handled by the function
        //  instead of in the handler.
        // /auth/pages/ will be used for test pages containing the webauthn register/login/signing code.
        return;
    }
    const normalizedRequest = (0, normalizeRequest_1.normalizeApiRequest)(event, body);
    const verifyCall = await (0, generateAndSignRequest_1.generateAndSignRequest)(normalizedRequest, event.requestContext.http.sourceIp);
    try {
        return await (0, exports.authVerify)(verifyCall);
    }
    catch (error) {
        logging_1.logger.error('VerifyAuthentication call failed with: ' + JSON.stringify(error));
        throw errors_1.TechnicalError.actionNotAuthorized();
    }
};
exports.getAuthenticationDetails = getAuthenticationDetails;
//# sourceMappingURL=getAuthenticationDetails.js.map