"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleAdminUICORSOrigin = void 0;
exports.setupCors = setupCors;
const debug_1 = require("./debug");
const cors_1 = __importDefault(require("cors"));
function setupCors(app, { allowedCorsOrigins }) {
    const corsDebug = (0, debug_1.createDebug)('signalk-server:cors');
    const corsOptions = {
        credentials: true
    };
    const corsOrigins = allowedCorsOrigins
        ? allowedCorsOrigins
            .split(',')
            .map((s) => s.trim().replace(/\/*$/, ''))
        : [];
    // default wildcard cors configuration does not work
    // with credentials:include client requests, so add
    // our own wildcard rule that will match all origins
    // but respond with that origin, not the default *
    if (allowedCorsOrigins?.startsWith('*')) {
        corsOptions.origin = (origin, cb) => cb(null, origin);
        corsDebug('Allowing all origins');
    }
    else if (corsOrigins.length > 0) {
        // set origin only if corsOrigins are set so that
        // we get the default cors module functionality
        // for simple requests by default
        corsOptions.origin = corsOrigins;
        corsDebug(`corsOrigins:${corsOrigins.toString()}`);
    }
    app.use((0, cors_1.default)(corsOptions));
    app.use((req, res, next) => {
        const origin = req.header('origin');
        if (origin !== undefined && !corsOrigins.includes(origin)) {
            corsDebug(`${origin} is not present in corsOrigins: ${corsOrigins.toString()}`);
        }
        else {
            corsDebug(`${origin} is allowed`);
        }
        next();
    });
}
const handleAdminUICORSOrigin = (securityConfig) => {
    let allowedCorsOrigins = [];
    if (securityConfig.adminUIOrigin &&
        securityConfig.allowedCorsOrigins &&
        securityConfig.allowedCorsOrigins.length > 0) {
        allowedCorsOrigins = securityConfig.allowedCorsOrigins?.split(',');
        const adminUIOriginUrl = new URL(securityConfig.adminUIOrigin);
        if (allowedCorsOrigins.indexOf(securityConfig.adminUIOrigin) === -1 &&
            adminUIOriginUrl.hostname !== 'localhost') {
            allowedCorsOrigins.push(securityConfig.adminUIOrigin);
        }
    }
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { adminUIOrigin, ...configWithoutAdminUIOrigin } = securityConfig;
    return {
        ...configWithoutAdminUIOrigin,
        allowedCorsOrigins: allowedCorsOrigins.join(',')
    };
};
exports.handleAdminUICORSOrigin = handleAdminUICORSOrigin;
//# sourceMappingURL=cors.js.map