"use strict";
(() => {
var exports = {};
exports.id = 1764;
exports.ids = [1764,1992];
exports.modules = {

/***/ 770640:
/***/ ((module) => {

module.exports = require("cookies");

/***/ }),

/***/ 922687:
/***/ ((module) => {

module.exports = require("password-hash");

/***/ }),

/***/ 446555:
/***/ ((module) => {

module.exports = import("uuid");;

/***/ }),

/***/ 439491:
/***/ ((module) => {

module.exports = require("assert");

/***/ }),

/***/ 714300:
/***/ ((module) => {

module.exports = require("buffer");

/***/ }),

/***/ 532081:
/***/ ((module) => {

module.exports = require("child_process");

/***/ }),

/***/ 706113:
/***/ ((module) => {

module.exports = require("crypto");

/***/ }),

/***/ 809523:
/***/ ((module) => {

module.exports = require("dns");

/***/ }),

/***/ 582361:
/***/ ((module) => {

module.exports = require("events");

/***/ }),

/***/ 657147:
/***/ ((module) => {

module.exports = require("fs");

/***/ }),

/***/ 113685:
/***/ ((module) => {

module.exports = require("http");

/***/ }),

/***/ 795687:
/***/ ((module) => {

module.exports = require("https");

/***/ }),

/***/ 241808:
/***/ ((module) => {

module.exports = require("net");

/***/ }),

/***/ 272254:
/***/ ((module) => {

module.exports = require("node:buffer");

/***/ }),

/***/ 487561:
/***/ ((module) => {

module.exports = require("node:fs");

/***/ }),

/***/ 788849:
/***/ ((module) => {

module.exports = require("node:http");

/***/ }),

/***/ 22286:
/***/ ((module) => {

module.exports = require("node:https");

/***/ }),

/***/ 487503:
/***/ ((module) => {

module.exports = require("node:net");

/***/ }),

/***/ 149411:
/***/ ((module) => {

module.exports = require("node:path");

/***/ }),

/***/ 497742:
/***/ ((module) => {

module.exports = require("node:process");

/***/ }),

/***/ 484492:
/***/ ((module) => {

module.exports = require("node:stream");

/***/ }),

/***/ 572477:
/***/ ((module) => {

module.exports = require("node:stream/web");

/***/ }),

/***/ 941041:
/***/ ((module) => {

module.exports = require("node:url");

/***/ }),

/***/ 447261:
/***/ ((module) => {

module.exports = require("node:util");

/***/ }),

/***/ 165628:
/***/ ((module) => {

module.exports = require("node:zlib");

/***/ }),

/***/ 822037:
/***/ ((module) => {

module.exports = require("os");

/***/ }),

/***/ 371017:
/***/ ((module) => {

module.exports = require("path");

/***/ }),

/***/ 677282:
/***/ ((module) => {

module.exports = require("process");

/***/ }),

/***/ 285477:
/***/ ((module) => {

module.exports = require("punycode");

/***/ }),

/***/ 12781:
/***/ ((module) => {

module.exports = require("stream");

/***/ }),

/***/ 371576:
/***/ ((module) => {

module.exports = require("string_decoder");

/***/ }),

/***/ 924404:
/***/ ((module) => {

module.exports = require("tls");

/***/ }),

/***/ 76224:
/***/ ((module) => {

module.exports = require("tty");

/***/ }),

/***/ 257310:
/***/ ((module) => {

module.exports = require("url");

/***/ }),

/***/ 473837:
/***/ ((module) => {

module.exports = require("util");

/***/ }),

/***/ 271267:
/***/ ((module) => {

module.exports = require("worker_threads");

/***/ }),

/***/ 959796:
/***/ ((module) => {

module.exports = require("zlib");

/***/ }),

/***/ 449376:
/***/ (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 __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 };
    }
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.pii_expire = exports.pii_retention_to_future = void 0;
var misc_1 = __webpack_require__(854006);
var server_settings_1 = __webpack_require__(558305);
// this converts what's in the pii_expired setting to a new Date in the future
function pii_retention_to_future(pii_retention, data) {
    if (!pii_retention)
        return;
    var future = (0, misc_1.expire_time)(pii_retention);
    if (data != null) {
        data.expire = future;
    }
    return future;
}
exports.pii_retention_to_future = pii_retention_to_future;
// use this to get the "expire" value for storing certain entries in the DB,
// which contain personally identifiable information.
// if data is set, it's expire field will be set. in any case, it returns the "Date"
// in the future.
function pii_expire(db, data) {
    return __awaiter(this, void 0, void 0, function () {
        var settings;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, (0, server_settings_1.get_server_settings)(db)];
                case 1:
                    settings = _a.sent();
                    return [2 /*return*/, pii_retention_to_future(settings.pii_retention, data)];
            }
        });
    });
}
exports.pii_expire = pii_expire;
//# sourceMappingURL=pii.js.map

/***/ }),

/***/ 558305:
/***/ (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 };
    }
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.get_server_settings = void 0;
var async_utils_1 = __webpack_require__(644181);
// just to make this async friendly, that's all
function get_server_settings(db) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, (0, async_utils_1.callback2)(db.get_server_settings_cached)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    });
}
exports.get_server_settings = get_server_settings;
//# sourceMappingURL=server-settings.js.map

/***/ }),

/***/ 338553:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ signUp)
/* harmony export */ });
/* harmony import */ var _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(854006);
/* harmony import */ var _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_cocalc_util_misc__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var uuid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(446555);
/* harmony import */ var _cocalc_server_auth_is_account_available__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29459);
/* harmony import */ var _cocalc_server_auth_is_account_available__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_auth_is_account_available__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _cocalc_server_auth_is_domain_exclusive_sso__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(497364);
/* harmony import */ var _cocalc_server_auth_is_domain_exclusive_sso__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_auth_is_domain_exclusive_sso__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _cocalc_server_accounts_create_account__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2113);
/* harmony import */ var _cocalc_server_accounts_create_account__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_accounts_create_account__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _sign_in__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(656816);
/* harmony import */ var _cocalc_server_email_welcome_email__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(508905);
/* harmony import */ var _cocalc_server_email_welcome_email__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_email_welcome_email__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _cocalc_server_auth_tokens_redeem__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(14790);
/* harmony import */ var _cocalc_server_auth_tokens_redeem__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_auth_tokens_redeem__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _cocalc_server_settings_server_settings__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(526177);
/* harmony import */ var _cocalc_server_settings_server_settings__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_settings_server_settings__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var lib_api_is_post__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(447618);
/* harmony import */ var _cocalc_server_auth_recaptcha__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(437415);
/* harmony import */ var _cocalc_server_auth_recaptcha__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_auth_recaptcha__WEBPACK_IMPORTED_MODULE_9__);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([uuid__WEBPACK_IMPORTED_MODULE_1__]);
uuid__WEBPACK_IMPORTED_MODULE_1__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];
/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */ /*
Sign up for a new account:

0. If email/password matches an existing account, just sign them in.  Reduces confusion.
1. Reject if password is absurdly weak.
2. Query the database to make sure the email address is not already taken.
3. Generate a random account_id. Do not check it is not already taken, since that's
   highly unlikely, and the insert in 4 would fail anyways.
4. Write account to the database.
5. Sign user in
*/ 










async function signUp(req, res) {
    if (!(0,lib_api_is_post__WEBPACK_IMPORTED_MODULE_10__/* ["default"] */ .Z)(req, res)) return;
    let { terms , email , password , firstName , lastName , registrationToken ,  } = req.body;
    password = (password ?? "").trim();
    email = (email ?? "").toLowerCase().trim();
    firstName = (firstName ? firstName : "Anonymous").trim();
    lastName = (lastName ? lastName : `User-${Math.round(new Date().valueOf() / 1000)}`).trim();
    registrationToken = (registrationToken ?? "").trim();
    // if email is empty, then trying to create an anonymous account,
    // which may be allowed, depending on server settings.
    const isAnonymous = !email;
    if (!isAnonymous && email && password) {
        // Maybe there is already an account with this email and password?
        try {
            const account_id = await (0,_sign_in__WEBPACK_IMPORTED_MODULE_5__.getAccount)(email, password);
            await (0,_sign_in__WEBPACK_IMPORTED_MODULE_5__.signUserIn)(req, res, account_id);
            return;
        } catch (_err) {
        // fine -- just means they don't already have an account.
        }
    }
    if (!isAnonymous) {
        const issues = checkObviousConditions({
            terms,
            email,
            password
        });
        if ((0,_cocalc_util_misc__WEBPACK_IMPORTED_MODULE_0__.len)(issues) > 0) {
            res.json({
                issues
            });
            return;
        }
    }
    // The UI doesn't let users try to make an account via signUp if
    // email isn't enabled.  However, they might try to directly POST
    // to the API, so we check here as well.
    const { email_signup , anonymous_signup  } = await (0,_cocalc_server_settings_server_settings__WEBPACK_IMPORTED_MODULE_8__.getServerSettings)();
    try {
        await _cocalc_server_auth_recaptcha__WEBPACK_IMPORTED_MODULE_9___default()(req);
    } catch (err) {
        res.json({
            issues: {
                reCaptcha: err.message
            }
        });
        return;
    }
    if (isAnonymous) {
        // Check anonymous sign up conditions.
        if (!anonymous_signup) {
            res.json({
                issues: {
                    email: "Anonymous account creation is disabled."
                }
            });
            return;
        }
    } else {
        // Check the email sign up conditions.
        if (!email_signup) {
            res.json({
                issues: {
                    email: "Email account creation is disabled."
                }
            });
            return;
        }
        const exclusive = await _cocalc_server_auth_is_domain_exclusive_sso__WEBPACK_IMPORTED_MODULE_3___default()(email);
        if (exclusive) {
            res.json({
                issues: {
                    email: `To sign up with "@${exclusive}", you have to use the corresponding single sign on mechanism.  Delete your email address above, then click the SSO icon.`
                }
            });
            return;
        }
        if (!await _cocalc_server_auth_is_account_available__WEBPACK_IMPORTED_MODULE_2___default()(email)) {
            res.json({
                issues: {
                    email: `Email address "${email}" already in use.`
                }
            });
            return;
        }
    }
    try {
        await _cocalc_server_auth_tokens_redeem__WEBPACK_IMPORTED_MODULE_7___default()(registrationToken);
    } catch (err1) {
        res.json({
            issues: {
                registrationToken: `Issue with registration token -- ${err1.message}`
            }
        });
        return;
    }
    try {
        const account_id = (0,uuid__WEBPACK_IMPORTED_MODULE_1__.v4)();
        await _cocalc_server_accounts_create_account__WEBPACK_IMPORTED_MODULE_4___default()({
            email,
            password,
            firstName,
            lastName,
            account_id
        });
        if (email) {
            try {
                await _cocalc_server_email_welcome_email__WEBPACK_IMPORTED_MODULE_6___default()(email, account_id);
            } catch (err) {
                // Expected to fail, e.g., when sendgrid or smtp not configured yet.
                // TODO: should log using debug instead of console?
                console.log(`WARNING: failed to send welcome email to ${email}`, err);
            }
        }
        await (0,_sign_in__WEBPACK_IMPORTED_MODULE_5__.signUserIn)(req, res, account_id); // sets a cookie
        res.json({
            account_id
        });
    } catch (err2) {
        res.json({
            error: err2.message
        });
    }
};
function checkObviousConditions({ terms , email , password  }) {
    const issues = {};
    if (!terms) {
        issues.terms = "You must agree to the terms of usage.";
    }
    if (!email || !(0,_cocalc_util_misc__WEBPACK_IMPORTED_MODULE_0__.is_valid_email_address)(email)) {
        issues.email = "You must provide a valid email address.";
    }
    if (!password || password.length < 6) {
        issues.password = "Your password must not be trivial to guess.";
    }
    return issues;
}

__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

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


/*
Create account.  Doesn't do any checking that server allows
for this type of account, etc. -- that is assumed to have been
done before calling this.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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__(541808));
var password_hash_1 = __importDefault(__webpack_require__(987909));
var account_creation_actions_1 = __importStar(__webpack_require__(786791));
function createAccount(_a) {
    var email = _a.email, password = _a.password, firstName = _a.firstName, lastName = _a.lastName, account_id = _a.account_id;
    return __awaiter(this, void 0, void 0, function () {
        var pool;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    pool = (0, pool_1.default)();
                    return [4 /*yield*/, pool.query("INSERT INTO accounts (email_address, password_hash, first_name, last_name, account_id, created) VALUES($1::TEXT, $2::TEXT, $3::TEXT, $4::TEXT, $5::UUID, NOW())", [
                            email ? email : undefined,
                            password ? (0, password_hash_1.default)(password) : undefined,
                            firstName,
                            lastName,
                            account_id,
                        ])];
                case 1:
                    _b.sent();
                    if (!email) return [3 /*break*/, 3];
                    return [4 /*yield*/, (0, account_creation_actions_1.default)(email, account_id)];
                case 2:
                    _b.sent();
                    _b.label = 3;
                case 3: return [4 /*yield*/, (0, account_creation_actions_1.creationActionsDone)(account_id)];
                case 4:
                    _b.sent();
                    return [2 /*return*/];
            }
        });
    });
}
exports["default"] = createAccount;
//# sourceMappingURL=create-account.js.map

/***/ }),

/***/ 497364:
/***/ (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;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
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__(541808));
var parse_domain_1 = __webpack_require__(268040);
function isDomainExclusiveSSO(email_address) {
    var _a;
    return __awaiter(this, void 0, void 0, function () {
        var raw_domain, exclusiveDomains, parsed, domain, topLevelDomains, canonical;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    if (!email_address) {
                        return [2 /*return*/];
                    }
                    raw_domain = (_a = email_address.split("@")[1]) === null || _a === void 0 ? void 0 : _a.trim().toLowerCase();
                    if (!raw_domain) {
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, getExclusiveDomains()];
                case 1:
                    exclusiveDomains = _b.sent();
                    if (exclusiveDomains.length == 0) {
                        // For most servers, this is the case.
                        return [2 /*return*/];
                    }
                    parsed = (0, parse_domain_1.parseDomain)(raw_domain);
                    if (parsed.type != parse_domain_1.ParseResultType.Listed) {
                        // Domain not in the public suffix list
                        return [2 /*return*/];
                    }
                    domain = parsed.domain, topLevelDomains = parsed.topLevelDomains;
                    canonical = __spreadArray([domain !== null && domain !== void 0 ? domain : ""], __read(topLevelDomains), false).join(".");
                    if (exclusiveDomains.includes(canonical)) {
                        return [2 /*return*/, canonical];
                    }
                    return [2 /*return*/];
            }
        });
    });
}
exports["default"] = isDomainExclusiveSSO;
function getExclusiveDomains() {
    return __awaiter(this, void 0, void 0, function () {
        var pool, rows, v, rows_1, rows_1_1, row, exclusive_domains;
        var e_1, _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    pool = (0, pool_1.default)("minutes");
                    return [4 /*yield*/, pool.query("SELECT conf#>'{exclusive_domains}' as exclusive_domains FROM passport_settings")];
                case 1:
                    rows = (_b.sent()).rows;
                    v = [];
                    try {
                        for (rows_1 = __values(rows), rows_1_1 = rows_1.next(); !rows_1_1.done; rows_1_1 = rows_1.next()) {
                            row = rows_1_1.value;
                            exclusive_domains = row.exclusive_domains;
                            if (exclusive_domains) {
                                v.push.apply(v, __spreadArray([], __read(exclusive_domains), false));
                            }
                        }
                    }
                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                    finally {
                        try {
                            if (rows_1_1 && !rows_1_1.done && (_a = rows_1.return)) _a.call(rows_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                    }
                    return [2 /*return*/, v];
            }
        });
    });
}
//# sourceMappingURL=is-domain-exclusive-sso.js.map

/***/ }),

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


/*
Verify recaptcha or throw error on failure.

Does nothing if recaptcha is not configured on the server.
*/
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__(526177);
var node_fetch_1 = __importDefault(__webpack_require__(978220));
function reCaptcha(req) {
    return __awaiter(this, void 0, void 0, function () {
        var re_captcha_v3_secret_key, reCaptchaToken, url, response, result;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, (0, server_settings_1.getServerSettings)()];
                case 1:
                    re_captcha_v3_secret_key = (_a.sent()).re_captcha_v3_secret_key;
                    if (!re_captcha_v3_secret_key)
                        return [2 /*return*/];
                    reCaptchaToken = req.body.reCaptchaToken;
                    if (!reCaptchaToken) {
                        throw Error("reCaptcha token must be provided");
                    }
                    url = "https://www.google.com/recaptcha/api/siteverify?secret=".concat(re_captcha_v3_secret_key, "&response=").concat(reCaptchaToken, "&remoteip=").concat(req.socket.remoteAddress);
                    return [4 /*yield*/, (0, node_fetch_1.default)(url)];
                case 2:
                    response = _a.sent();
                    return [4 /*yield*/, response.json()];
                case 3:
                    result = _a.sent();
                    if (!result.success) {
                        throw Error("reCaptcha may be misconfigured. ".concat(JSON.stringify(result["error-codes"])));
                    }
                    if (!result.score || result.score < 0.5) {
                        throw Error("Only humans are allowed to use this feature.  Please try again.");
                    }
                    return [2 /*return*/];
            }
        });
    });
}
exports["default"] = reCaptcha;
//# sourceMappingURL=recaptcha.js.map

/***/ }),

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


/* Redeem a registration token.

Raise an exception on failure with the error explaining the exception.

If no token is needed because of how site is configured,
then returns no matter what the input is.
*/
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 get_requires_token_1 = __importDefault(__webpack_require__(99297));
var pool_1 = __importDefault(__webpack_require__(541808));
function redeem(token) {
    return __awaiter(this, void 0, void 0, function () {
        var required, client, q_match, match, _a, expires, counter_raw, limit, disabled_raw, counter, disabled, q_inc, err_1;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, (0, get_requires_token_1.default)()];
                case 1:
                    required = _b.sent();
                    if (!required) {
                        // no token required, so nothing to do.
                        return [2 /*return*/];
                    }
                    if (!token) {
                        throw Error("no registration token provided");
                    }
                    client = (0, pool_1.default)();
                    _b.label = 2;
                case 2:
                    _b.trys.push([2, 9, , 11]);
                    return [4 /*yield*/, client.query("BEGIN")];
                case 3:
                    _b.sent();
                    q_match = "SELECT \"expires\", \"counter\", \"limit\", \"disabled\"\n                     FROM registration_tokens\n                     WHERE token = $1::TEXT\n                     FOR UPDATE";
                    return [4 /*yield*/, client.query(q_match, [token])];
                case 4:
                    match = _b.sent();
                    if (match.rows.length != 1) {
                        throw Error("Registration token is wrong.");
                    }
                    _a = match.rows[0], expires = _a.expires, counter_raw = _a.counter, limit = _a.limit, disabled_raw = _a.disabled;
                    counter = counter_raw !== null && counter_raw !== void 0 ? counter_raw : 0;
                    disabled = disabled_raw !== null && disabled_raw !== void 0 ? disabled_raw : false;
                    if (disabled) {
                        throw Error("Registration token disabled.");
                    }
                    if (expires != null && expires.getTime() < new Date().getTime()) {
                        throw Error("Registration token no longer valid.");
                    }
                    if (!(limit != null && limit <= counter)) return [3 /*break*/, 5];
                    throw Error("Registration token used up.");
                case 5:
                    q_inc = "UPDATE registration_tokens SET \"counter\" = coalesce(\"counter\", 0) + 1\n                     WHERE token = $1::TEXT";
                    return [4 /*yield*/, client.query(q_inc, [token])];
                case 6:
                    _b.sent();
                    _b.label = 7;
                case 7: 
                // all good, let's commit
                return [4 /*yield*/, client.query("COMMIT")];
                case 8:
                    // all good, let's commit
                    _b.sent();
                    return [3 /*break*/, 11];
                case 9:
                    err_1 = _b.sent();
                    return [4 /*yield*/, client.query("ROLLBACK")];
                case 10:
                    _b.sent();
                    throw err_1;
                case 11: return [2 /*return*/];
            }
        });
    });
}
exports["default"] = redeem;
//# sourceMappingURL=redeem.js.map

/***/ }),

/***/ 401696:
/***/ (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 smtp_1 = __importDefault(__webpack_require__(738182));
var sendgrid_1 = __importDefault(__webpack_require__(92500));
var throttle_1 = __importDefault(__webpack_require__(385094));
var server_settings_1 = __webpack_require__(526177);
function sendEmail(message, account_id // account that we are sending this email *on behalf of*, if any (used for throttling).
) {
    return __awaiter(this, void 0, void 0, function () {
        var email_backend, _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, (0, throttle_1.default)(account_id)];
                case 1:
                    _b.sent();
                    return [4 /*yield*/, (0, server_settings_1.getServerSettings)()];
                case 2:
                    email_backend = (_b.sent()).email_backend;
                    _a = email_backend;
                    switch (_a) {
                        case "": return [3 /*break*/, 3];
                        case "none": return [3 /*break*/, 3];
                        case "smtp": return [3 /*break*/, 4];
                        case "sendgrid": return [3 /*break*/, 6];
                    }
                    return [3 /*break*/, 8];
                case 3: throw Error("no email backend configured");
                case 4: return [4 /*yield*/, (0, smtp_1.default)(message)];
                case 5: return [2 /*return*/, _b.sent()];
                case 6: return [4 /*yield*/, (0, sendgrid_1.default)(message)];
                case 7: return [2 /*return*/, _b.sent()];
                case 8: throw Error("no valid email backend configured: ".concat(email_backend));
            }
        });
    });
}
exports["default"] = sendEmail;
//# sourceMappingURL=send-email.js.map

/***/ }),

/***/ 385094:
/***/ (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 }));
/*
Enforce limits on the number of that a user can cause to be sent.

For now starting with a simple limit: at most XXX messages per day.
*/
var DAILY_LIMIT = 1000;
var pii_1 = __webpack_require__(449376);
var pool_1 = __importDefault(__webpack_require__(541808));
var settings_1 = __webpack_require__(840336);
// Call this function whenever an email will be sent on behalf of the given account.
// It will increment a counter for each day, and if it goes too high it throws
// an exceptions, which prevents further emais from being sent for that user.
function sendEmailThrottle(id // account_id or project_id or organization_id...
) {
    var _a;
    return __awaiter(this, void 0, void 0, function () {
        var day, pool, rows, settings, expire;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    if (!id)
                        return [2 /*return*/]; // not associated to a particular user
                    day = startOfToday();
                    pool = (0, pool_1.default)("short");
                    return [4 /*yield*/, pool.query("SELECT count FROM email_counter WHERE time=$1 AND id=$2", [day, id])];
                case 1:
                    rows = (_b.sent()).rows;
                    if (rows.length > 0 && rows[0].count > DAILY_LIMIT) {
                        throw Error("You may send at most ".concat(DAILY_LIMIT, " emails per day, and you have reached that limit."));
                    }
                    if (!(rows.length > 0)) return [3 /*break*/, 3];
                    // This will always work with no race conditions, since the given entry exists.
                    return [4 /*yield*/, pool.query("UPDATE email_counter SET count = count + 1 WHERE id=$1 AND time=$2", [id, day])];
                case 2:
                    // This will always work with no race conditions, since the given entry exists.
                    _b.sent();
                    return [3 /*break*/, 6];
                case 3: return [4 /*yield*/, (0, settings_1.getServerSettings)()];
                case 4:
                    settings = _b.sent();
                    expire = (0, pii_1.pii_retention_to_future)((_a = settings.pii_retention) !== null && _a !== void 0 ? _a : false);
                    // It's possible another server created email_counter in the meantime,
                    // hence the "ON CONFLICT".
                    return [4 /*yield*/, pool.query("INSERT INTO email_counter (id,time,count,expire) VALUES($1,$2,1,$3) ON CONFLICT (id, time) DO UPDATE SET count = excluded.count + 1", [id, day, expire])];
                case 5:
                    // It's possible another server created email_counter in the meantime,
                    // hence the "ON CONFLICT".
                    _b.sent();
                    _b.label = 6;
                case 6: return [2 /*return*/];
            }
        });
    });
}
exports["default"] = sendEmailThrottle;
function startOfToday() {
    // https://stackoverflow.com/questions/7195513/how-do-you-get-the-unix-timestamp-for-the-start-of-today-in-javascript
    var now = new Date();
    return new Date(now.getFullYear(), now.getMonth(), now.getDate());
}
//# sourceMappingURL=throttle.js.map

/***/ }),

/***/ 837527:
/***/ (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.getVerifyEmail = void 0;
var pool_1 = __importDefault(__webpack_require__(541808));
var random_key_1 = __webpack_require__(630900);
var site_url_1 = __importDefault(__webpack_require__(661348));
function getVerifyEmail(email_address) {
    return __awaiter(this, void 0, void 0, function () {
        var token, site_url, url;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, getToken(email_address)];
                case 1:
                    token = _a.sent();
                    return [4 /*yield*/, (0, site_url_1.default)()];
                case 2:
                    site_url = _a.sent();
                    url = "".concat(site_url, "/auth/verify/").concat(token, "?email=").concat(encodeURIComponent(email_address));
                    return [2 /*return*/, body(url)];
            }
        });
    });
}
exports.getVerifyEmail = getVerifyEmail;
function getToken(email_address) {
    return __awaiter(this, void 0, void 0, function () {
        var pool, rows, _a, account_id, email_address_challenge, token, data;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    pool = (0, pool_1.default)();
                    return [4 /*yield*/, pool.query("SELECT account_id, email_address_challenge FROM accounts WHERE email_address=$1", [email_address])];
                case 1:
                    rows = (_b.sent()).rows;
                    if (rows.length == 0) {
                        throw Error("no account with email address \"".concat(email_address, "\""));
                    }
                    _a = rows[0], account_id = _a.account_id, email_address_challenge = _a.email_address_challenge;
                    if ((email_address_challenge === null || email_address_challenge === void 0 ? void 0 : email_address_challenge.token) &&
                        email_address_challenge.email == email_address) {
                        // return the same token if there is one for the same email
                        return [2 /*return*/, email_address_challenge.token];
                    }
                    token = (0, random_key_1.generate)(16).toLowerCase();
                    data = { email: email_address, token: token, time: new Date() };
                    return [4 /*yield*/, pool.query("UPDATE accounts SET email_address_challenge = $1::JSONB WHERE account_id = $2::UUID", [data, account_id])];
                case 2:
                    _b.sent();
                    return [2 /*return*/, token];
            }
        });
    });
}
function body(url) {
    var html = "\n<p style=\"margin-top:0;margin-bottom:20px;\">\n<strong>\nPlease <a href=\"".concat(url, "\">verify your email address</a>!\n</strong>\n</p>\n\n<p style=\"margin-top:0;margin-bottom:20px;\">\nIf the above link does not work, please copy and paste the following\nURL into a new browser tab:\n</p>\n\n<pre style=\"margin-top:10px;margin-bottom:10px;font-size:11px;\">\n").concat(url, "\n</pre>\n");
    var text = "\nPlease verify your email address by visiting the following URL in your web browser:\n\n".concat(url, "\n\n");
    return { html: html, text: text };
}
//# sourceMappingURL=verify.js.map

/***/ }),

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


/*
Send a welcome email to a person if they create an account and
we know their email address.

Throws error if email address is not set for this use
in the database or if sending of email is not configured.
*/
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 send_email_1 = __importDefault(__webpack_require__(401696));
var settings_1 = __webpack_require__(840336);
var theme_1 = __webpack_require__(981975);
var verify_1 = __webpack_require__(837527);
var misc_1 = __webpack_require__(854006);
var site_url_1 = __importDefault(__webpack_require__(661348));
function sendWelcomeEmail(email_address, account_id) {
    return __awaiter(this, void 0, void 0, function () {
        var _a, text, html;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    if (!(0, misc_1.is_valid_email_address)(email_address)) {
                        throw Error("invalid email address");
                    }
                    return [4 /*yield*/, getWelcomeEmail(email_address)];
                case 1:
                    _a = _b.sent(), text = _a.text, html = _a.html;
                    return [4 /*yield*/, (0, send_email_1.default)({
                            to: email_address,
                            subject: "Welcome!",
                            text: text,
                            html: html,
                            categories: ["welcome"],
                            asm_group: 147985,
                        }, account_id)];
                case 2:
                    _b.sent();
                    return [2 /*return*/];
            }
        });
    });
}
exports["default"] = sendWelcomeEmail;
function getWelcomeEmail(email_address) {
    return __awaiter(this, void 0, void 0, function () {
        var verify, _a, help_email, site_name, site_url, html, text;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, (0, verify_1.getVerifyEmail)(email_address)];
                case 1:
                    verify = _b.sent();
                    return [4 /*yield*/, (0, settings_1.getServerSettings)()];
                case 2:
                    _a = _b.sent(), help_email = _a.help_email, site_name = _a.site_name;
                    return [4 /*yield*/, (0, site_url_1.default)()];
                case 3:
                    site_url = _b.sent();
                    html = "<h1>Welcome to ".concat(site_name, "</h1>\n\n<p style=\"margin-top:0;margin-bottom:10px;\">\n<a href=\"").concat(site_url, "\">").concat(site_name, "</a> helps you to work with open-source scientific software in your web browser.\n</p>\n\n<p style=\"margin-top:0;margin-bottom:20px;\">\nYou received this email because an account with the email address ").concat(email_address, " was created.\n</p>\n\n").concat(verify.html, "\n\n<hr size=\"1\"/>\n\n<h3>Exploring ").concat(site_name, "</h3>\n<p style=\"margin-top:0;margin-bottom:10px;\">\nIn ").concat(site_name, " your work happens inside <strong>private projects</strong>.\nThese are personal workspaces which contain your files, computational worksheets, and data.\nYou can run your computations through the web interface, via interactive worksheets\nand notebooks, or by executing a program in a terminal. ").concat(site_name, " supports\nonline editing of\n    <a href=\"https://cocalc.com/features/jupyter-notebook\">Jupyter Notebooks</a>,\n    <a href=\"https://cocalc.com/features/sage\">Sage Worksheets</a>,\n    <a href=\"https://cocalc.com/features/latex-editor\">LaTeX files</a>, etc.\n</p>\n\n<p style=\"margin-top:0;margin-bottom:10px;\">\n<strong>How to get from 0 to 100:</strong>\n</p>\n\n<ul>\n<li style=\"margin-top:0;margin-bottom:10px;\">\n    <strong><a href=\"https://doc.cocalc.com/\">CoCalc Manual:</a></strong> learn more about CoCalc's features.\n</li>\n<li style=\"margin-top:0;margin-bottom:10px;\">\n    <a href=\"https://doc.cocalc.com/jupyter.html\">Working with Jupyter Notebooks</a>\n</li>\n<li style=\"margin-top:0;margin-bottom:10px;\">\n    <a href=\"https://doc.cocalc.com/sagews.html\">Working with SageMath Worksheets</a>\n</li>\n<li style=\"margin-top:0;margin-bottom:10px;\">\n    <strong><a href=\"https://cocalc.com/policies/pricing.html\">Subscriptions:</a></strong> make hosting more robust and increase project quotas\n</li>\n<li style=\"margin-top:0;margin-bottom:10px;\">\n    <a href=\"https://doc.cocalc.com/teaching-instructors.html\">Teaching a course on CoCalc</a>.\n</li>\n<li style=\"margin-top:0;margin-bottom:10px;\">\n    <a href=\"https://doc.cocalc.com/howto/connectivity-issues.html\">Troubleshooting connectivity issues</a>\n</li>\n<li style=\"margin-top:0;margin-bottom:10px;\">\n    <a href=\"https://github.com/sagemathinc/cocalc/wiki/MathematicalSyntaxErrors\">Common mathematical syntax errors:</a> look into this if you are new to working with a programming language!\n</li>\n</ul>\n\n\n<p style=\"margin-top:0;margin-bottom:20px;\">\n<strong>Collaboration:</strong>\nYou can invite collaborators to work with you inside a project.\nLike you, they can edit the files in that project.\nEdits are visible in <strong>real time</strong> for everyone online.\nYou can share your thoughts in a <strong>side chat</strong> next to each document.\n</p>\n\n\n<p><strong>Software:</strong>\n<ul>\n<li style=\"margin-top:0;margin-bottom:10px;\">Mathematical Calculation:\n    <a href=\"https://www.sagemath.org/\">SageMath</a>,\n    <a href=\"https://www.sympy.org/\">SymPy</a>, etc.\n</li>\n<li style=\"margin-top:0;margin-bottom:10px;\">Statistics and Data Science:\n    <a href=\"https://www.r-project.org/\">R project</a>,\n    <a href=\"http://pandas.pydata.org/\">Pandas</a>,\n    <a href=\"http://www.statsmodels.org/\">statsmodels</a>,\n    <a href=\"http://scikit-learn.org/\">scikit-learn</a>,\n    <a href=\"http://www.nltk.org/\">NLTK</a>, and <a href=\"https://cocalc.com/software\">much more</a>.\n</li>\n<li style=\"margin-top:0;margin-bottom:10px;\">Various other Computation:\n    <a href=\"https://www.tensorflow.org/\">Tensorflow</a>,\n    <a href=\"https://cocalc.com/features/octave\">Octave</a>,\n    <a href=\"https://cocalc.com/features/julia\">Julia</a>, etc.\n</li>\n</ul>\n\n<p style=\"margin-top:0;margin-bottom:20px;\">\nVisit our <a href=\"https://cocalc.com/features\">Feature Overview Page</a> for more details!\n</p>\n\n\n<p style=\"margin-top:20px;margin-bottom:10px;\">\n<strong>Questions?</strong>\n</p>\n<p style=\"margin-top:0;margin-bottom:10px;\">\nSchedule a Live Demo with a specialist from CoCalc.com: <a href=\"").concat(theme_1.LIVE_DEMO_REQUEST, "\">request form</a>.\n</p>\n<p style=\"margin-top:0;margin-bottom:20px;\">\nIn case of problems, concerns why you received this email, or other questions please contact:\n<a href=\"mailto:").concat(help_email, "\">").concat(help_email, "</a>.\n</p>\n");
                    text = "\nWelcome to ".concat(site_name, "!\n\n").concat(site_name, " helps you to work with open-source scientific software in your web browser.\n\n").concat(site_url, "\n\nYou received this email because an account with the email address ").concat(email_address, " was created.\n\n").concat(verify.text, "\n\nEXPLORING ").concat(site_name, "\n\nIn ").concat(site_name, " your work happens inside private projects.  These are personal\nworkspaces which contain your files, computational worksheets, and data.\nYou can run your computations through the web interface, via interactive worksheets\nand notebooks, or by executing a program in a terminal. ").concat(site_name, " supports\nonline editing of Jupyter Notebooks, Sage Worksheets, LaTeX files, and much more.\n\nHOW TO GET FROM 0 to 100:\n\nCoCalc Manual: https://doc.cocalc.com/\n\nWorking with Jupyter Notebooks: https://doc.cocalc.com/jupyter.html\n\nWorking with SageMath Worksheets: https://doc.cocalc.com/sagews.html\n\nSubscriptions: https://cocalc.com/policies/pricing.html\n\nTeaching a course on CoCalc: https://doc.cocalc.com/teaching-instructors.html\n\nTroubleshooting connectivity issues: https://doc.cocalc.com/howto/connectivity-issues.html\n\nCommon mathematical syntax errors: https://github.com/sagemathinc/cocalc/wiki/MathematicalSyntaxErrors\n\nCOLLABORATION\n\nYou can invite collaborators to work with you inside a project.\nLike you, they can edit the files in that project.\nEdits are visible in real time for everyone online.\nYou can share your thoughts in a side chat next to each document.\n\nSOFTWARE\n\n- Mathematical Calculation: https://www.sagemath.org, https://www.sympy.org, etc.\n\n- Statistics and Data Science: https://www.r-project.org/, http://pandas.pydata.org/,\nhttp://www.statsmodels.org/, http://scikit-learn.org/, http://www.nltk.org/, and\nmuch more.  See https://cocalc.com/software\n\nVarious other Computation: https://www.tensorflow.org/, https://cocalc.com/features/octave,\nhttps://cocalc.com/features/julia\n\nVisit our Feature Overview Page at https://cocalc.com/features for more details!\n\nQUESTIONS?\n\nSchedule a Live Demo with a specialist from CoCalc.com:\n\n").concat(theme_1.LIVE_DEMO_REQUEST, "\n\nIn case of problems, concerns why you received this email, or other questions\nplease contact ").concat(help_email, ".");
                    return [2 /*return*/, { html: html, text: text }];
            }
        });
    });
}
//# sourceMappingURL=welcome-email.js.map

/***/ })

};
;

// load runtime
var __webpack_require__ = require("../../../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = __webpack_require__.X(0, [1970,2921,2185,2014,6652,1050,6942,2454,8220,884,1808,9738,8312,540,8416,4181,7554,5016,6177,1348,6816,9022,6791,9297], () => (__webpack_exec__(338553)));
module.exports = __webpack_exports__;

})();