"use strict";
exports.id = 5114;
exports.ids = [5114];
exports.modules = {

/***/ 939894:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {


Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.verifyPassword = void 0;
var password_hash_1 = __webpack_require__(18303);
Object.defineProperty(exports, "verifyPassword", ({ enumerable: true, get: function () { return password_hash_1.verify; } }));
// You can change the parameters at any time and no existing passwords
// or cookies should break.  This will only impact newly created
// passwords and cookies.  Old ones can be read just fine (with the old
// parameters).
var HASH_ALGORITHM = "sha512";
var HASH_ITERATIONS = 1000;
var HASH_SALT_LENGTH = 32;
function passwordHash(password) {
    // This blocks the server for around 5ms.
    // There are newer async libraries as explained at https://www.npmjs.com/package/password-hash
    // that do NOT block, which maybe we should be using instead....
    return (0, password_hash_1.generate)(password, {
        algorithm: HASH_ALGORITHM,
        saltLength: HASH_SALT_LENGTH,
        iterations: HASH_ITERATIONS,
    });
}
exports["default"] = passwordHash;
//# sourceMappingURL=password-hash.js.map

/***/ }),

/***/ 19864:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


/*
 *  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 }));
/* Determine the base path for this CoCalc service.

The default export of this module is base path, which should
be used by the CoCalc backend hub server.
*/
var DEFN = "\nThe basePath is the URL prefix for all paths, relative to the\nhost root. It must start with a leading slash /, but does not\nend with one unless it is '/'.  It also should not include ://.\nSome examples of valid basePaths:\n\n- /\n- /10f0e544-313c-4efe-8718-1111ac97ad11/port/5000\n\nThese are not valid:\n\n- //\n- \"\" (empty string)\n- /foo/\n- https://cocalc.com/\n\nIf the environment variable BASE_PATH is set then use that (e.g., used\nwhen running a project), or throw an error if our assumptions are not satisfied.\n\nOtherwise, if this code is running in a CoCalc project (i.e., if the env variable\nCOCALC_PROJECT_ID is set), then the base path is a combination of\nCOCALC_PROJECT_ID and the port that the hub will serve on.\n\nIf neither of the above conditions are met, then the base path is /.\n\nNOTES:\n\n- We use this code in a project started by the hub to determine the base path;\nin that case, the env variable BASE_PATH is set, since otherwise the project\nitself would view the base path as being relative to its own id.\n\n";
var port_1 = __importDefault(__webpack_require__(91117));
function isValidBasePath(s) {
    if (s[0] != "/")
        return false;
    if (s.length == 1)
        return true;
    if (s[s.length - 1] == "/")
        return false;
    if (s.includes("://"))
        return false;
    return true;
}
function basePath() {
    if (true) {
        if (!isValidBasePath("/")) {
            throw Error("BASE_PATH (=\"".concat("/", "\") is invalid - ").concat(DEFN, "."));
        }
        return "/";
    }
    if (!process.env.COCALC_PROJECT_ID)
        return "/";
    return "/".concat(process.env.COCALC_PROJECT_ID, "/port/").concat(port_1.default);
}
exports["default"] = basePath();
//# sourceMappingURL=base-path.js.map

/***/ }),

/***/ 91117:
/***/ ((__unused_webpack_module, exports) => {


/* Determine the port that the hub will serve on.

If the environment variable PORT is set, use that port; otherwise, use port 5000.

The default export of this module is the port number.
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
var DEFAULT_PORT = 5000;
function port() {
    if (process.env.PORT) {
        return parseInt(process.env.PORT);
    }
    return DEFAULT_PORT;
}
exports["default"] = port();
//# sourceMappingURL=port.js.map

/***/ }),

/***/ 17763:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


/*
 *  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 }));
exports.timeInSeconds = void 0;
var pool_1 = __importDefault(__webpack_require__(818245));
exports["default"] = pool_1.default;
var util_1 = __webpack_require__(532465);
Object.defineProperty(exports, "timeInSeconds", ({ enumerable: true, get: function () { return util_1.timeInSeconds; } }));
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 425335:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {


Object.defineProperty(exports, "__esModule", ({ value: true }));
var path_1 = __webpack_require__(371017);
var data_1 = __webpack_require__(838699);
var fs_1 = __webpack_require__(657147);
function dbPassword() {
    var filename = (0, path_1.join)(data_1.secrets, "postgres");
    try {
        // fine to use sync, since reading db password happens only on startup
        return (0, fs_1.readFileSync)(filename).toString().trim();
    }
    catch (_a) {
        return undefined;
    }
}
exports["default"] = dbPassword;
//# sourceMappingURL=password.js.map

/***/ }),

/***/ 820976:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Z": () => (/* binding */ getAccountId)
/* harmony export */ });
/* unused harmony export getRememberMeHash */
/* harmony import */ var _cocalc_database_pool__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17763);
/* harmony import */ var _cocalc_database_pool__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_cocalc_database_pool__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _cocalc_server_auth_hash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(233437);
/* harmony import */ var _cocalc_server_auth_remember_me__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(420818);
/* harmony import */ var _cocalc_server_auth_remember_me__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_auth_remember_me__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var cookies__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(770640);
/* harmony import */ var cookies__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(cookies__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _cocalc_server_auth_api__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(878474);
/* harmony import */ var _cocalc_server_auth_api__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_auth_api__WEBPACK_IMPORTED_MODULE_4__);
/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */ 




// Return account_id if they are signed in.
// If not, returns undefined.
// This is determined by looking in their cookie and checking
// who it identifies in the database.
async function getAccountId(req, noCache = false) {
    if (req == null) return;
    // caching a bit --  We thus want the query below to happen rarely.  We also
    // get expire field as well (since it is usually there) so that the result isn't empty
    // (hence not cached) when a cookie has expired.
    const hash = getRememberMeHash(req);
    if (!hash) {
        // not signed in via a cookie.
        // What about an api key?
        if (req.header("Authorization")) {
            try {
                return await (0,_cocalc_server_auth_api__WEBPACK_IMPORTED_MODULE_4__.getAccountIdFromApiKey)(req);
            } catch (_err) {
                // non-fatal, at least for now...
                return;
            }
        }
        return;
    }
    const pool = _cocalc_database_pool__WEBPACK_IMPORTED_MODULE_0___default()(noCache ? "short" : undefined);
    // important to use CHAR(127) instead of TEXT for 100x performance gain.
    const result = await pool.query("SELECT account_id, expire FROM remember_me WHERE hash = $1::CHAR(127)", [
        hash
    ]);
    if (result.rows.length == 0) {
        return;
    }
    const { account_id , expire  } = result.rows[0];
    if (expire <= new Date()) {
        // expired
        return;
    }
    return account_id;
};
function getRememberMeHash(req) {
    const cookies = new (cookies__WEBPACK_IMPORTED_MODULE_3___default())(req);
    const rememberMe = cookies.get(_cocalc_server_auth_remember_me__WEBPACK_IMPORTED_MODULE_2__.COOKIE_NAME);
    if (!rememberMe) {
        return;
    }
    const x = rememberMe.split("$");
    if (x.length !== 4) {
        throw Error("badly formatted remember_me cookie");
    }
    return (0,_cocalc_server_auth_hash__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Z)(x[0], x[1], parseInt(x[2]), x[3]).slice(0, 127);
}


/***/ }),

/***/ 516582:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Z": () => (/* binding */ getAccountInfo),
/* harmony export */   "o": () => (/* binding */ getName)
/* harmony export */ });
/* harmony import */ var _cocalc_database_pool__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17763);
/* harmony import */ var _cocalc_database_pool__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_cocalc_database_pool__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(262898);
/* harmony import */ var lib_account_get_account__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(820976);
/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */ 


async function getAccountInfo(account_id, req) {
    return {
        account_id,
        ...await getName(account_id),
        publicPaths: await getPublicPaths(account_id, req)
    };
};
async function getName(account_id) {
    if (!(0,_util__WEBPACK_IMPORTED_MODULE_1__/* .isUUID */ .t)(account_id)) {
        throw Error("invalid UUID");
    }
    const pool = _cocalc_database_pool__WEBPACK_IMPORTED_MODULE_0___default()("long");
    // Get the database entry
    const { rows  } = await pool.query("SELECT name, first_name, last_name, email_address, passports FROM accounts WHERE account_id=$1", [
        account_id
    ]);
    if (rows.length == 0) {
        throw Error("no such user");
    }
    const is_anonymous = !rows[0].email_address && !rows[0].passports;
    return {
        first_name: rows[0].first_name,
        last_name: rows[0].last_name,
        name: rows[0].name,
        email_address: rows[0].email_address,
        is_anonymous
    };
}
async function getPublicPaths(account_id, req // used to get account_id of requester to see if we should include unlisted and disabled public_paths
) {
    if (!(0,_util__WEBPACK_IMPORTED_MODULE_1__/* .isUUID */ .t)(account_id)) {
        // VERY important to check this because we substitute the account_id
        // into the query string directly, and this is input directly from the user!
        throw Error("invalid UUID");
    }
    const pool = _cocalc_database_pool__WEBPACK_IMPORTED_MODULE_0___default()("medium");
    // Returns public paths for which account_id is a collaborator on the project and they have
    // actively used the project at some point.
    // We sort from most recently edited.
    const query = `SELECT public_paths.id as id, public_paths.path as path, public_paths.description as description,
  public_paths.disabled as disabled, public_paths.unlisted as unlisted, public_paths.vhost as vhost, public_paths.authenticated as authenticated,
  (SELECT COUNT(*)::INT FROM public_path_stars WHERE public_path_id=public_paths.id) AS stars,
  public_paths.counter::INT AS counter,
  ${(0,_cocalc_database_pool__WEBPACK_IMPORTED_MODULE_0__.timeInSeconds)("public_paths.last_edited", "last_edited")} FROM public_paths, projects WHERE public_paths.project_id = projects.project_id AND projects.last_active ? '${account_id}' AND projects.users ? '${account_id}'  ORDER BY public_paths.last_edited DESC`;
    const { rows  } = await pool.query(query);
    // If there are any disabled or unlisted public_paths, we also get the id of the requestor so we can filter them out.
    return await filterNonPublicAndNotAuthenticated(rows, account_id, req);
}
async function filterNonPublicAndNotAuthenticated(rows, account_id, req) {
    const v = [];
    let client_id = undefined;
    for (const row of rows){
        if (!row.disabled && !row.unlisted && !row.authenticated) {
            v.push(row);
            continue;
        }
        if (client_id == null) {
            client_id = await (0,lib_account_get_account__WEBPACK_IMPORTED_MODULE_2__/* ["default"] */ .Z)(req) ?? "";
        }
        if (client_id == account_id) {
            v.push(row);
        } else if (row.authenticated === true && client_id !== "") {
            v.push(row);
        }
    }
    return v;
}


/***/ }),

/***/ 262898:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Fe": () => (/* reexport safe */ _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_1__.containingPath),
/* harmony export */   "RF": () => (/* binding */ trunc),
/* harmony export */   "RT": () => (/* reexport safe */ _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_1__.getExtension),
/* harmony export */   "YQ": () => (/* binding */ getTitle),
/* harmony export */   "t": () => (/* binding */ isUUID)
/* harmony export */ });
/* unused harmony export isSha1Hash */
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(371017);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(477389);
/* harmony import */ var _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_cocalc_util_misc__WEBPACK_IMPORTED_MODULE_1__);
/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */ 

function isUUID(s) {
    // todo: add full check.
    return typeof s == "string" && s.length == 36;
}
function isSha1Hash(s) {
    return typeof s == "string" && s.length == 40;
// todo: could add full check (i.e., each character is in 0-e)
}
function trunc(s, n) {
    return s.length > n ? s.slice(0, n - 1) + "\u2026" : s;
}
function getTitle({ path , relativePath  }) {
    const b = (0,path__WEBPACK_IMPORTED_MODULE_0__.basename)(relativePath);
    return b ? b : (0,path__WEBPACK_IMPORTED_MODULE_0__.basename)(path);
}


/***/ }),

/***/ 422638:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Z": () => (/* binding */ withCustomize)
/* harmony export */ });
/* harmony import */ var _cocalc_server_settings_customize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(280783);
/* harmony import */ var _cocalc_server_settings_customize__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_settings_customize__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lib_account_get_account__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(820976);
/* harmony import */ var lib_share_get_account_info__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(516582);
/* harmony import */ var _cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(954314);
/* harmony import */ var _cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _cocalc_util_db_schema_site_defaults__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(16563);
/*
 *  This file is part of CoCalc: Copyright © 2021 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */ 




const revalidate = 30;
async function withCustomize(obj, options = {}) {
    var ref, ref1;
    let customize;
    try {
        // NOTE: important to make a (shallow) copy, since customize gets mutated below.
        customize = {
            ...await _cocalc_server_settings_customize__WEBPACK_IMPORTED_MODULE_0___default()()
        };
    } catch (_err) {
        // fallback to be empty; during static build
        // this happens.
        customize = {};
    }
    if (((ref = obj.context) === null || ref === void 0 ? void 0 : ref.req) != null) {
        const account_id = await (0,lib_account_get_account__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Z)(obj.context.req);
        customize.isAuthenticated = !!account_id;
        if (account_id) {
            var ref2;
            customize.account = {
                account_id,
                ...options.name ? await (0,lib_share_get_account_info__WEBPACK_IMPORTED_MODULE_2__/* .getName */ .o)(account_id) : undefined
            };
            // Also, if a project id is in the props and account_id is set, it's very
            // useful to know if the user is a collaborator on the project, since that
            // can impact a lot about how we display things.  This is typically used
            // for the share pages.
            const project_id = (ref2 = obj.props) === null || ref2 === void 0 ? void 0 : ref2.project_id;
            if (project_id) {
                customize.isCollaborator = await _cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_3___default()({
                    account_id,
                    project_id
                });
            }
        }
    } else {
        customize.isAuthenticated = false;
    }
    customize.onCoCalcCom = customize.kucalc === _cocalc_util_db_schema_site_defaults__WEBPACK_IMPORTED_MODULE_4__.KUCALC_COCALC_COM;
    customize.noindex = ((ref1 = obj.props) === null || ref1 === void 0 ? void 0 : ref1.unlisted) ?? false;
    customize.imprintOrPolicies = ((customize.imprint ?? "" + customize.policies) ?? "") != "";
    customize.serverTime = Date.now();
    if (obj == null) {
        return {
            props: {
                customize
            }
        };
    }
    if (obj.revalidate != null) {
        obj.revalidate = Math.min(revalidate, obj.revalidate);
    }
    if (obj.props == null) {
        obj.props = {
            customize
        };
    } else {
        obj.props.customize = customize;
    }
    delete obj.context;
    return obj;
};


/***/ }),

/***/ 41998:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


/*
User management of the v1 API key associated to an account.
This supports three actions:

- get: get the existing key associated to an account; return undefined if there is no api key set.
- delete: delete the existing key associated to an account
- regenerate: delete the existing key and replace it by a new random key.

If the user has a password, then it must be provided and be correct. If they have no password,
then the provided one is ignored.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getAccountWithApiKey = void 0;
var pool_1 = __importDefault(__webpack_require__(17763));
var misc_1 = __webpack_require__(477389);
var is_password_correct_1 = __importDefault(__webpack_require__(231899));
var has_password_1 = __importDefault(__webpack_require__(423640));
var random_key_1 = __webpack_require__(689685);
function manage(_a) {
    var account_id = _a.account_id, password = _a.password, action = _a.action;
    return __awaiter(this, void 0, void 0, function () {
        var pool, _b, rows, api_key;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    if (!misc_1.isValidUUID) {
                        throw Error("account_id is not a valid uuid");
                    }
                    return [4 /*yield*/, (0, has_password_1.default)(account_id)];
                case 1:
                    if (!_c.sent()) return [3 /*break*/, 3];
                    if (!password) {
                        throw Error("password must be provided");
                    }
                    return [4 /*yield*/, (0, is_password_correct_1.default)({ account_id: account_id, password: password })];
                case 2:
                    // verify password is correct
                    if (!(_c.sent())) {
                        throw Error("invalid password");
                    }
                    _c.label = 3;
                case 3:
                    pool = (0, pool_1.default)();
                    _b = action;
                    switch (_b) {
                        case "get": return [3 /*break*/, 4];
                        case "delete": return [3 /*break*/, 6];
                        case "regenerate": return [3 /*break*/, 8];
                    }
                    return [3 /*break*/, 10];
                case 4: return [4 /*yield*/, pool.query("SELECT api_key FROM accounts WHERE account_id=$1::UUID", [account_id])];
                case 5:
                    rows = (_c.sent()).rows;
                    if (rows.length == 0) {
                        throw Error("no such account");
                    }
                    return [2 /*return*/, rows[0].api_key];
                case 6: return [4 /*yield*/, pool.query("UPDATE accounts SET api_key=NULL WHERE account_id=$1::UUID", [account_id])];
                case 7:
                    _c.sent();
                    return [2 /*return*/];
                case 8:
                    api_key = "sk_".concat((0, random_key_1.generate)());
                    return [4 /*yield*/, pool.query("UPDATE accounts SET api_key=$1 WHERE account_id=$2::UUID", [api_key, account_id])];
                case 9:
                    _c.sent();
                    return [2 /*return*/, api_key];
                case 10: throw Error("unknown action=\"".concat(action, "\""));
            }
        });
    });
}
exports["default"] = manage;
/* Get the account that has the given api key, or returns undefined if there
is no such account. */
function getAccountWithApiKey(api_key) {
    var _a;
    return __awaiter(this, void 0, void 0, function () {
        var pool, rows;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    pool = (0, pool_1.default)("medium");
                    return [4 /*yield*/, pool.query("SELECT account_id FROM accounts WHERE api_key = $1::TEXT", [api_key])];
                case 1:
                    rows = (_b.sent()).rows;
                    return [2 /*return*/, (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.account_id];
            }
        });
    });
}
exports.getAccountWithApiKey = getAccountWithApiKey;
//# sourceMappingURL=manage.js.map

/***/ }),

/***/ 878474:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getAccountIdFromApiKey = exports.getApiKey = void 0;
var misc_1 = __webpack_require__(477389);
var manage_1 = __webpack_require__(41998);
function getApiKey(req) {
    var h = req.header("Authorization");
    if (h == null) {
        throw Error("You must provide authentication via an API key.");
    }
    var _a = __read((0, misc_1.split)(h), 2), type = _a[0], user = _a[1];
    switch (type) {
        case "Bearer":
            return user;
        case "Basic":
            return Buffer.from(user, "base64").toString().split(":")[0];
    }
    throw Error("Unknown authorization type '".concat(type, "'"));
}
exports.getApiKey = getApiKey;
function getAccountIdFromApiKey(req) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, (0, manage_1.getAccountWithApiKey)(getApiKey(req))];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    });
}
exports.getAccountIdFromApiKey = getAccountIdFromApiKey;
//# sourceMappingURL=api.js.map

/***/ }),

/***/ 423640:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


/*
If the account with given id does not exist, throw an error.

Return true if the account with given id exists and has a password set.

Otherwise, return false... since auth is only doing via a passport.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
var pool_1 = __importDefault(__webpack_require__(17763));
function hasPassword(account_id) {
    return __awaiter(this, void 0, void 0, function () {
        var pool, rows;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    pool = (0, pool_1.default)("short");
                    return [4 /*yield*/, pool.query("SELECT password_hash FROM accounts WHERE account_id=$1::UUID", [account_id])];
                case 1:
                    rows = (_a.sent()).rows;
                    if (rows.length == 0) {
                        throw Error("no such account");
                    }
                    return [2 /*return*/, !!rows[0].password_hash];
            }
        });
    });
}
exports["default"] = hasPassword;
//# sourceMappingURL=has-password.js.map

/***/ }),

/***/ 233437:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var crypto_1 = __webpack_require__(706113);
// This function is private and burried inside the password-hash
// library.  To avoid having to fork/modify that library, we've just
// copied it here.  We need it for remember_me cookies.
function hash(algorithm, salt, iterations, password) {
    // there are cases where createHmac throws an error, because "salt" is undefined
    if (algorithm == null || salt == null) {
        throw new Error("undefined arguments: algorithm='".concat(algorithm, "' salt='").concat(salt, "'"));
    }
    iterations = iterations || 1;
    if (!isFinite(iterations) || iterations > 10000) {
        // If somebody could make their own cookie, they might set the number of iterations
        // to be very large and hang the server.
        throw Error("number of iterations invalid or too large");
    }
    var hash = password;
    for (var i = 1, end = iterations, asc = 1 <= end; asc ? i <= end : i >= end; asc ? i++ : i--) {
        hash = (0, crypto_1.createHmac)(algorithm, salt).update(hash).digest("hex");
    }
    return algorithm + "$" + salt + "$" + iterations + "$" + hash;
}
exports.Z = hash;
//# sourceMappingURL=hash.js.map

/***/ }),

/***/ 231899:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


/*
Returns true if the account with given id exists and the password
is correct for the account.  Returns false in all other cases.

NOTE: Of course some accounts don't even have a password, in which
case this will always return false.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
var pool_1 = __importDefault(__webpack_require__(17763));
var password_hash_1 = __webpack_require__(939894);
function isPasswordCorrect(_a) {
    var account_id = _a.account_id, password = _a.password;
    return __awaiter(this, void 0, void 0, function () {
        var pool, rows, password_hash;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    pool = (0, pool_1.default)();
                    return [4 /*yield*/, pool.query("SELECT password_hash FROM accounts WHERE account_id=$1", [account_id])];
                case 1:
                    rows = (_b.sent()).rows;
                    if (rows.length == 0)
                        return [2 /*return*/, false];
                    password_hash = rows[0].password_hash;
                    if (!password_hash)
                        return [2 /*return*/, false];
                    return [2 /*return*/, (0, password_hash_1.verifyPassword)(password, password_hash)];
            }
        });
    });
}
exports["default"] = isPasswordCorrect;
//# sourceMappingURL=is-password-correct.js.map

/***/ }),

/***/ 420818:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.deleteAllRememberMe = exports.deleteRememberMe = exports.createRememberMeCookie = exports.COOKIE_NAME = void 0;
var base_path_1 = __importDefault(__webpack_require__(19864));
var uuid_1 = __webpack_require__(860413);
var password_hash_1 = __importDefault(__webpack_require__(939894));
var pool_1 = __importDefault(__webpack_require__(17763));
var util_1 = __webpack_require__(532465);
exports.COOKIE_NAME = "".concat(base_path_1.default.length <= 1 ? "" : encodeURIComponent(base_path_1.default), "remember_me");
// Create a remember me cookie for the given account_id and store
// it in the database.  The cookie is similar to using a server
// assigned random uuid-v4 as a password.  The user knows the
// uuid-v4, and we only store what it hashes to, so even if
// somebody gets our database, they can't make fake cookies and use
// them to sign in.
function createRememberMeCookie(account_id) {
    return __awaiter(this, void 0, void 0, function () {
        var session_id, hash_session_id, x, value, ttl_s, pool;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    session_id = (0, uuid_1.v4)();
                    hash_session_id = (0, password_hash_1.default)(session_id);
                    x = hash_session_id.split("$");
                    value = [x[0], x[1], x[2], session_id].join("$");
                    ttl_s = 24 * 3600 * 30;
                    pool = (0, pool_1.default)();
                    return [4 /*yield*/, pool.query("INSERT INTO remember_me (hash, expire, account_id) VALUES($1::TEXT, $2::TIMESTAMP, $3::UUID)", [hash_session_id.slice(0, 127), (0, util_1.expireTime)(ttl_s), account_id])];
                case 1:
                    _a.sent();
                    return [2 /*return*/, { value: value, ttl_s: ttl_s }];
            }
        });
    });
}
exports.createRememberMeCookie = createRememberMeCookie;
// delete the remember me database entry for the given hash
function deleteRememberMe(hash) {
    return __awaiter(this, void 0, void 0, function () {
        var pool;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    pool = (0, pool_1.default)();
                    return [4 /*yield*/, pool.query("DELETE FROM remember_me WHERE hash=$1::TEXT", [
                            hash.slice(0, 127),
                        ])];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
exports.deleteRememberMe = deleteRememberMe;
// delete all remember me cookies for the account
function deleteAllRememberMe(account_id) {
    return __awaiter(this, void 0, void 0, function () {
        var pool;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    pool = (0, pool_1.default)();
                    return [4 /*yield*/, pool.query("DELETE FROM remember_me WHERE account_id=$1::UUID", [
                            account_id,
                        ])];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
exports.deleteAllRememberMe = deleteAllRememberMe;
//# sourceMappingURL=remember-me.js.map

/***/ }),

/***/ 954314:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
var pool_1 = __importDefault(__webpack_require__(17763));
var misc_1 = __webpack_require__(477389);
function isCollaborator(_a) {
    var _b;
    var account_id = _a.account_id, project_id = _a.project_id;
    return __awaiter(this, void 0, void 0, function () {
        var pool, rows, group;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    if (!(0, misc_1.is_valid_uuid_string)(account_id) || !(0, misc_1.is_valid_uuid_string)(project_id)) {
                        throw Error("invalid input");
                    }
                    pool = (0, pool_1.default)("long");
                    return [4 /*yield*/, pool.query("SELECT users#>'{".concat(account_id, ",group}' AS group FROM projects WHERE project_id=$1"), [project_id])];
                case 1:
                    rows = (_c.sent()).rows;
                    group = (_b = rows[0]) === null || _b === void 0 ? void 0 : _b.group;
                    return [2 /*return*/, group == "owner" || group == "collaborator"];
            }
        });
    });
}
exports["default"] = isCollaborator;
//# sourceMappingURL=is-collaborator.js.map

/***/ }),

/***/ 280783:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


/*
 *  This file is part of CoCalc: Copyright © 2021 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
var server_settings_1 = __webpack_require__(567934);
var site_url_1 = __importDefault(__webpack_require__(295847));
var site_defaults_1 = __webpack_require__(16563);
var fallback = function (a, b) {
    return typeof a == "string" && a.length > 0 ? a : "".concat(b);
};
/*
Create a Javascript object that describes properties of the server.
This is used on the next.js server landing pages and the share server
to customize their look and behavior.

This function is cached via the parameters in ./server-settings, i.e.,
for a few seconds.
*/
var cachedSettings = undefined;
var cachedCustomize = undefined;
function getCustomize() {
    return __awaiter(this, void 0, void 0, function () {
        var settings;
        var _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, (0, server_settings_1.getServerSettings)()];
                case 1:
                    settings = _b.sent();
                    if (settings === cachedSettings && cachedCustomize != null) {
                        return [2 /*return*/, cachedCustomize];
                    }
                    cachedSettings = settings;
                    _a = {
                        siteName: fallback(settings.site_name, "On Premises CoCalc"),
                        siteDescription: fallback(settings.site_description, "Collaborative Calculation using Python, Sage, R, Julia, and more."),
                        organizationName: settings.organization_name,
                        organizationEmail: settings.organization_email,
                        organizationURL: settings.organization_url,
                        termsOfServiceURL: settings.terms_of_service_url,
                        helpEmail: settings.help_email,
                        contactEmail: fallback(settings.organization_email, settings.help_email),
                        isCommercial: settings.commercial,
                        kucalc: settings.kucalc,
                        sshGateway: settings.ssh_gateway,
                        anonymousSignup: settings.anonymous_signup,
                        emailSignup: settings.email_signup,
                        accountCreationInstructions: settings.account_creation_email_instructions,
                        logoSquareURL: settings.logo_square,
                        logoRectangularURL: settings.logo_rectangular,
                        splashImage: settings.splash_image,
                        shareServer: !!settings.share_server,
                        // additionally restrict showing landing pages only in cocalc.com-mode
                        landingPages: !!settings.landing_pages && settings.kucalc === site_defaults_1.KUCALC_COCALC_COM,
                        googleAnalytics: settings.google_analytics,
                        indexInfo: settings.index_info_html,
                        imprint: settings.imprint,
                        policies: settings.policies,
                        // Is important for invite emails, password reset, etc. (e.g., so we can construct a url to our site).
                        // This *can* start with http:// to explicitly use http instead of https, and can end
                        // in something like :3594 to indicate a port.
                        dns: settings.dns
                    };
                    return [4 /*yield*/, (0, site_url_1.default)(settings.dns)];
                case 2:
                    cachedCustomize = (
                    // siteURL is derived from settings.dns and the basePath -- it combines the dns, https://
                    // and the basePath.  It never ends in a slash.  This is used in practice for
                    // things like invite emails, password reset, etc.
                    _a.siteURL = _b.sent(),
                        _a.zendesk = settings.zendesk_token &&
                            settings.zendesk_username &&
                            settings.zendesk_uri,
                        // obviously only the public key here!
                        _a.stripePublishableKey = settings.stripe_publishable_key,
                        // obviously only the public key here too!
                        _a.reCaptchaKey = settings.re_captcha_v3_publishable_key,
                        _a);
                    return [2 /*return*/, cachedCustomize];
            }
        });
    });
}
exports["default"] = getCustomize;
//# sourceMappingURL=customize.js.map

/***/ }),

/***/ 295847:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
var server_settings_1 = __webpack_require__(567934);
var base_path_1 = __importDefault(__webpack_require__(19864));
// Returns url of this site in terms of the base path (determined
// by an env variable when server starts) and the "Domain name"
// setting of site settings.  This URL does NOT end in a /
function siteURL(dns) {
    var _a;
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    if (!!dns) return [3 /*break*/, 2];
                    return [4 /*yield*/, (0, server_settings_1.getServerSettings)()];
                case 1:
                    dns = (_a = (_b.sent()).dns) === null || _a === void 0 ? void 0 : _a.toLowerCase();
                    _b.label = 2;
                case 2:
                    if (!dns) {
                        dns = "localhost";
                    }
                    if (!dns.startsWith("http")) {
                        dns = "https://" + dns;
                    }
                    return [2 /*return*/, "".concat(dns).concat(base_path_1.default == "/" ? "" : base_path_1.default)];
            }
        });
    });
}
exports["default"] = siteURL;
//# sourceMappingURL=site-url.js.map

/***/ }),

/***/ 328577:
/***/ ((__unused_webpack_module, exports) => {


Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DOC_CLOUD_STORAGE_URL = exports.DUMMY_SECRET = void 0;
exports.DUMMY_SECRET = "[SECRET HIDDEN]";
exports.DOC_CLOUD_STORAGE_URL = "https://doc.cocalc.com/project-settings.html#cloud-storage-remote-file-systems";
//# sourceMappingURL=project.js.map

/***/ }),

/***/ 912707:
/***/ ((__unused_webpack_module, exports) => {


/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FALLBACK_COMPUTE_IMAGE = exports.DEFAULT_COMPUTE_IMAGE = exports.DEFAULT_NEW_FILENAMES = exports.NEW_FILENAMES = exports.DEFAULT_FONT_SIZE = void 0;
exports.DEFAULT_FONT_SIZE = 14;
// key for new filenames algorithm in account/other_settings and associated default value
exports.NEW_FILENAMES = "new_filenames";
exports.DEFAULT_NEW_FILENAMES = "iso";
// better make sure the storage server has something available under "default"
exports.DEFAULT_COMPUTE_IMAGE = "ubuntu2004";
// this is the fallback value to use for the compute image, in case it isn't set
// in particular, for projects and public_path shares!
// historical note: we used "default" to refer to ubuntu 18.04, but once
// we switch over to 20.04, we will keep older projects on 18.04 (explicit upgrade)
exports.FALLBACK_COMPUTE_IMAGE = "default";
//# sourceMappingURL=defaults.js.map

/***/ }),

/***/ 988772:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {


/* Checks that name satisfies the following constraints
Inspired by -- https://github.com/isiahmeadows/github-limits



Each function checks the basic rules, but NOT for uniqueness,
which requires a DB query.

If a rule fails, throws an Error.
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.checkPublicPathName = exports.checkProjectName = exports.checkAccountName = exports.isReserved = void 0;
var misc_1 = __webpack_require__(477389);
function isReserved(name) {
    return RESERVED.has(name.toLowerCase());
}
exports.isReserved = isReserved;
/*
Account name:
 - between 1 and 39 characters
 - doesn't start with a -
 - only includes the characters 0-9,a-z,A-Z,-
 - Don't allow uuid's.
 - cannot include consecutive hyphens
*/
function checkAccountName(name) {
    if (name.length < 1) {
        throw Error("name must have at least 1 character");
    }
    if (name.length > 39) {
        throw Error("name must have at most 39 characters");
    }
    if ((0, misc_1.is_valid_uuid_string)(name)) {
        throw Error("name must not be a v4 UUID");
    }
    if (name.includes("--")) {
        throw Error("name must not contain consecutive hyphens");
    }
    if (!/^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$/i.test(name)) {
        throw Error("name must contain only a-z,A-Z,0-9, or -, and not start with hyphen.");
    }
    // Check for reserved names.
    if (isReserved(name)) {
        throw Error("username \"".concat(name, "\" is reserved -- not available"));
    }
}
exports.checkAccountName = checkAccountName;
/*
Project name:

- Max length: 100 characters
- All characters must be either a hyphen (-), a period (.), or alphanumeric
- Unique amongst projects with given owner
- Don't allow uuid's.
*/
function checkProjectName(name) {
    if (name.length < 1) {
        throw Error("name must have at least 1 character");
    }
    if (name.length > 100) {
        throw Error("name must have at most 100 characters");
    }
    if ((0, misc_1.is_valid_uuid_string)(name)) {
        throw Error("name must not be a v4 UUID");
    }
    if (!/^[\.a-z\d](?:[\.a-z\d]|-(?=[\.a-z\d])){0,99}$/i.test(name)) {
        throw Error("name must contain only a-z,A-Z,0-9, . or -, and not start with hyphen or have spaces.");
    }
}
exports.checkProjectName = checkProjectName;
/*
Public path name:

- Max length: 100 characters
- All characters must be either a hyphen (-), a period (.), or alphanumeric
- Unique amongst public paths in a given project.
- Don't allow uuid's.
*/
function checkPublicPathName(name) {
    if (name.length < 1) {
        throw Error("name must have at least 1 character");
    }
    if (name.length > 100) {
        throw Error("name must have at most 100 characters");
    }
    if ((0, misc_1.is_valid_uuid_string)(name)) {
        throw Error("name must not be a v4 UUID");
    }
    if (!/^[\.a-z\d](?:[\.a-z\d]|-(?=[\.a-z\d])){0,99}$/i.test(name)) {
        throw Error("name must contain only a-z,A-Z,0-9, . or -, and not start with hyphen or have spaces.");
    }
    // Check for reserved names.  We also ban these for public path names, since
    // we want to have URL's like
    //    https://cocalc.com/sagemathinc/myproject/settings -- configure settings
    //    https://cocalc.com/sagemathinc/myproject/files -- browse all files directly
    //    snapshots, timetravel, new, search, etc...
    if (isReserved(name)) {
        throw Error("path name \"".concat(name, "\" is reserved -- not available"));
    }
}
exports.checkPublicPathName = checkPublicPathName;
// Combined words from what we use, https://www.quora.com/How-do-sites-prevent-vanity-URLs-from-colliding-with-future-features
// and https://github.com/Mottie/github-reserved-names/blob/master/reserved-names.json and
// https://github.com/Mottie/github-reserved-names and random other things.
// If you add more and want to clean this up in the console, this may be helpful:
//       Array.from(RESERVED).sort().join(' ')
var RESERVED = new Set("0 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 500 501 502 503 504 505 506 507 508 509 510 511 about access account accounts activate activities activity ad add address adm admin administration administrator ads adult advertising advisories affiliate affiliates ajax alive all alpha analysis analytics android anon anonymous any api app apps archive archives article articles asct asset assets atom attributes auth authentication avatar backup balancer-manager banner banners beta better billing bin blob blobs blog blogs board book bookmark bot bots bounty branches bug business businesses c cache cadastro calendar call campaign cancel captcha career careers cart case-studies categories category cdn central certification cgi cgi-bin changelog chat check checking checkout cla client cliente clients cloud cocalc cocksucker code codereview collection collections comercial comment comments commit commits communities community companies company compare compras config configuration connect contact contact-us contact_us contactus contest contribute contributing cookbook cookies corp coupons create css cunt customer customer-stories customers customize dashboard dashboards data db default delete demo design designer destroy dev devel develop developer developers diagram diary dict dictionary die diff dir direct_messages directory discover discussions dist doc docs documentation domain download downloads downtime ecommerce edit editor editors edu education email embed employment empty end enterprise entries entry error errors eval event events exit explore facebook faq favorite favorites feature featured features feed feedback feeds file files first fixtures flash fleet fleets flog follow followers following font fonts forgot forked form forum forums founder free friend friends ftp fuck gadget gadgets game games garage get ghost gift gifts gist gists github graph graphs group groups guest guests guide guides help help-wanted home homepage hooks host hosting hostmaster hostname hovercards howto hpg html http httpd https hub i iamges icon icons id idea ideas identity image images imap img inbox include includes index indice individual info information inquiry instagram integration interfaces intern internal intranet introduction invalid-email-address investors invitations invite invoice ipad iphone irc is issue issues it item items java javascript job jobs join journal journals js json jump knowledgebase lab labs language languages last launch layouts ldap-status learn legal library license licenses link links linux list listings lists log log-in log-out log_in log_out login logos logout logs m mac mail mail1 mail2 mail3 mail4 mail5 mailer mailing maintenance malware man manager manual map maps marketing marketplace master me media member members mention mentioned mentioning mentions message messages messenger microblog microblogs migrating milestones mine mirrors mis misc mob mobile module modules monitor motherfucker movie movies mp3 msg msn music musicas mx my mysql name named nan navi navigation net network new news newsletter nick nickname node nodes none nonprofit nonprofits notes notices noticias notification notifications notify ns ns1 ns10 ns2 ns3 ns4 ns5 ns6 ns7 ns8 ns9 null oauth oauth_clients offer offers office official old online open-source openid operator order orders organisations organization organizations orgs overview owner owners page pager pages panel partners password password-reset payment payments perl personal phone photo photoalbum photos php phpmyadmin phppgadmin phpredisadmin pic pics ping piss plan plans plugin plugins policies policy poll polls pop pop3 popular popularity portal post postfix postmaster posts pr premium press price pricing primus privacy privacy-policy privacy_policy privacypolicy private processes product products professional profile profiles project projects promo pub public pulls purpose put python query random ranking raw rdf rdfs read readme recent recommendations recruit recruitment redeem register registration release releases remove render replies reply report reports repositories repository req request requests reset resources restore revert roc root rss ruby rule sag sagemath sagemathinc sale sales sample samples save save-net-neutrality saved school scraping script scripts search secure security self send server server-info server-status service services session sessions setting settings setup share shareholders shit shop show showcases sign-in sign-up sign_in sign_up signin signout signup site sitemap sites smartphone smtp snapshots software soporte source spam spec special sponsors sql src ssh ssl ssladmin ssladministrator sslwebmaster staff stage staging star starred stars start stat state static statistics stats status statuses storage store stores stories style styleguide stylesheet stylesheets subdomain subscribe subscriptions suggest suggestion suggestions suporte support survey surveys suspended svn swf sys sysadmin sysadministrator system tablet tablets tag talk talks task tasks teach teacher teachers teaching team teams tech telnet template templates ten term terms terms-of-service terms_of_service termsofservice test test1 test2 test3 teste testing tests theme themes thread threads timeline timetravel tits tmp todo tool tools top topic topics tos tour train training translations tree trending trends try tutorial tutorials tux tv twitter twittr undef unfollow unsubscribe update updates upload uploads url usage user username users usuario vendas ver version video videos visitor visualization w watch watching weather web webapp webhook webhooks webmail webmaster website websites welcome widget widgets wiki win windows word work works works-with workshop ww wws www www0 www1 www2 www3 www4 www5 www6 www7 www8 www9 wwws wwww xfn xml xmpp xpg xxx yaml year yml you yourdomain yourname yoursite yourusername".split(/\s+/));
//# sourceMappingURL=name-rules.js.map

/***/ }),

/***/ 685219:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {


/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.UPGRADES_CURRENT_DATE = exports.DEFAULT_QUOTAS = exports.PROJECT_UPGRADES = exports.COMPUTE_STATES = exports.site_settings_conf = exports.client_db = exports.SCHEMA = exports.RECENT_TIMES_KEY = exports.RECENT_TIMES = void 0;
// RECENT_TIMES = these times in minutes are used for active/recently edited
// projects and accounts in postgres-server-queries.coffee's get_stats.
// This translates the semantic meanings to the keys used in the DB, also
// prevents typos!
var schema_static_1 = __webpack_require__(349412);
Object.defineProperty(exports, "RECENT_TIMES", ({ enumerable: true, get: function () { return schema_static_1.RECENT_TIMES; } }));
Object.defineProperty(exports, "RECENT_TIMES_KEY", ({ enumerable: true, get: function () { return schema_static_1.RECENT_TIMES_KEY; } }));
var db_schema_1 = __webpack_require__(335783);
Object.defineProperty(exports, "SCHEMA", ({ enumerable: true, get: function () { return db_schema_1.SCHEMA; } }));
Object.defineProperty(exports, "client_db", ({ enumerable: true, get: function () { return db_schema_1.client_db; } }));
Object.defineProperty(exports, "site_settings_conf", ({ enumerable: true, get: function () { return db_schema_1.site_settings_conf; } }));
// Load the syncstring extensions to the schema
__webpack_require__(590621);
// Will import some other modules and make them available here, since the code
// used to be in this file, and this is assumed in code elsewhere.  Will change later.
var compute_states_1 = __webpack_require__(360702);
Object.defineProperty(exports, "COMPUTE_STATES", ({ enumerable: true, get: function () { return compute_states_1.COMPUTE_STATES; } }));
var upgrade_spec_1 = __webpack_require__(245067);
Object.defineProperty(exports, "PROJECT_UPGRADES", ({ enumerable: true, get: function () { return upgrade_spec_1.upgrades; } }));
Object.defineProperty(exports, "DEFAULT_QUOTAS", ({ enumerable: true, get: function () { return upgrade_spec_1.DEFAULT_QUOTAS; } }));
Object.defineProperty(exports, "UPGRADES_CURRENT_DATE", ({ enumerable: true, get: function () { return upgrade_spec_1.CURRENT_DATE; } }));
//# sourceMappingURL=schema.js.map

/***/ })

};
;