"use strict";
/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = require("@cocalc/backend/logger");
const path_to_files_1 = __importDefault(require("./path-to-files"));
const authenticate_1 = __importDefault(require("./authenticate"));
const get_vhost_info_1 = __importDefault(require("./get-vhost-info"));
const handle_raw_1 = require("./handle-raw");
const base_path_1 = __importDefault(require("@cocalc/backend/base-path"));
const logger = (0, logger_1.getLogger)("virtual-hosts");
function virtualHostsMiddleware() {
    // we return the middleware to match the standard pattern for express,
    // and give more flexibility.
    return async function (req, res, next) {
        // For debugging in cc-in-cc dev, just manually set host to something
        // else and comment this out.  That's the only way, since dev is otherwise
        // impossible because otherwise the haproxy server sends queries
        // all straight to the production share server!
        const vhost = req.headers.host?.toLowerCase();
        // const vhost = "vertramp.org";
        // const vhost = "python-wasm.org";
        if (vhost == null) {
            // logger.debug("no host header set");
            next();
            return;
        }
        logger.debug("checking for vhost", vhost);
        const info = await (0, get_vhost_info_1.default)(vhost);
        if (info == null) {
            // logger.debug("no vhost info for ", vhost);
            next();
            return;
        }
        let path = req.url;
        if (base_path_1.default && base_path_1.default != "/") {
            // This is only going to happen in case of doing
            // cc-in-cc development.
            path = req.url.slice(base_path_1.default.length);
        }
        if (path == "") {
            path = "/";
        }
        // logger.debug({ vhost, url: req.url, info, path });
        const isAuth = (0, authenticate_1.default)({
            req,
            res,
            path,
            auth: info.auth,
        });
        if (!isAuth) {
            logger.debug("not authenticated -- denying vhost='%s', path='%s'", vhost, path);
            res.status(403).end();
            return;
        }
        if (info.cross_origin_isolation) {
            // The following two headers make it possible to serve content that used
            // SharedArrayBuffer from vhosts and raw shared content.  This is very
            // important as it is a prerequisite for modern use of WebAssembly.
            // E.g., https://python-wasm.cocalc.com uses this.
            res.setHeader("Cross-origin-Embedder-Policy", "require-corp");
            res.setHeader("Cross-origin-Opener-Policy", "same-origin");
        }
        const dir = (0, path_to_files_1.default)(info.project_id, info.path);
        /* logger.debug(
          "serving virtual host path -- vhost='%s',dir='%s'",
          vhost,
          dir
        ); */
        req.url = path;
        (0, handle_raw_1.staticHandler)(dir, req, res, () => {
            res.status(404).end();
        });
    };
}
exports.default = virtualHostsMiddleware;
//# sourceMappingURL=virtual-hosts.js.map