smc-hub
Version:
CoCalc: Backend webserver component
175 lines • 9.55 kB
JavaScript
;
/* Handle a proxy request */
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 http_proxy_1 = require("http-proxy");
var lru_cache_1 = __importDefault(require("lru-cache"));
var strip_remember_me_cookie_1 = __importDefault(require("./strip-remember-me-cookie"));
var version_1 = require("./version");
var target_1 = require("./target");
var logger_1 = __importDefault(require("../logger"));
var util_1 = require("./util");
var winston = logger_1.default("proxy: handle-request");
function init(_a) {
var _this = this;
var projectControl = _a.projectControl, isPersonal = _a.isPersonal;
/* Cache at most 5000 proxies, each for up to 3 minutes.
Throwing away proxies at any time from the cache is fine since
the proxy is just used to handle *individual* http requests,
and the cache is entirely for speed. Also, invalidating cache entries
works around weird cases, where maybe error/close don't get
properly called, but the proxy is not working due to network
issues. Invalidating cache entries quickly is also good from
a permissions and security point of view.
*/
var cache = new lru_cache_1.default({
max: 5000,
maxAge: 1000 * 60 * 3,
dispose: function (_key, proxy) {
var _a;
// important to close the proxy whenever it gets removed
// from the cache, to avoid wasting resources.
(_a = proxy) === null || _a === void 0 ? void 0 : _a.close();
},
});
function handleProxyRequest(req, res) {
return __awaiter(this, void 0, void 0, function () {
var dbg, remember_me, cookie, url, _a, host, port, internal_url, target, proxy, remove_from_cache_1;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
dbg = function (m) {
// for low level debugging -- silly isn't logged by default
winston.silly(req.url + ": " + m);
};
dbg("got request");
if (!isPersonal && version_1.versionCheckFails(req, res)) {
dbg("version check failed");
// note that the versionCheckFails function already sent back an error response.
return [2 /*return*/];
}
if (req.headers["cookie"] != null) {
cookie = void 0;
(_b = strip_remember_me_cookie_1.default(req.headers["cookie"]), cookie = _b.cookie, remember_me = _b.remember_me);
req.headers["cookie"] = cookie;
}
if (!isPersonal && !remember_me) {
dbg("no rememember me set, so blocking");
// Not in personal mode and there is no remember me set all, so
// definitely block access. 4xx since this is a *client* problem.
res.writeHead(426, { "Content-Type": "text/html" });
res.end("Please login to <a target='_blank' href='#{DOMAIN_URL}'>#{DOMAIN_URL}</a> with cookies enabled, then refresh this page.");
return [2 /*return*/];
}
url = util_1.stripBasePath(req.url);
return [4 /*yield*/, target_1.getTarget({
remember_me: remember_me,
url: url,
isPersonal: isPersonal,
projectControl: projectControl,
})];
case 1:
_a = _c.sent(), host = _a.host, port = _a.port, internal_url = _a.internal_url;
target = "http://" + host + ":" + port;
dbg("target resolves to " + target);
if (cache.has(target)) {
// we already have the proxy for this target in the cache
dbg("using cached proxy");
proxy = cache.get(target);
}
else {
dbg("make a new proxy server to " + target);
proxy = http_proxy_1.createProxyServer({
ws: false,
target: target,
timeout: 7000,
});
// and cache it.
cache.set(target, proxy);
dbg("created new proxy");
remove_from_cache_1 = function () {
cache.del(target); // this also closes the proxy.
target_1.invalidateTargetCache(remember_me, url);
};
proxy.on("error", function (e) {
dbg("http proxy error event (ending proxy) -- " + e);
remove_from_cache_1();
});
proxy.on("close", remove_from_cache_1);
}
if (internal_url != null) {
dbg("changing req url from " + req.url + " to " + internal_url);
req.url = internal_url;
}
dbg("handling the request using the proxy");
proxy.web(req, res);
return [2 /*return*/];
}
});
});
}
return function (req, res) { return __awaiter(_this, void 0, void 0, function () {
var err_1, msg;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, handleProxyRequest(req, res)];
case 1:
_a.sent();
return [3 /*break*/, 3];
case 2:
err_1 = _a.sent();
msg = "WARNING: error proxying request " + req.url + " -- " + err_1;
res.writeHead(500, { "Content-Type": "text/html" });
res.end(msg);
// Not something to log as an error; it's normal for it to happen, e.g., when
// a project isn't running.
winston.debug(msg);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); };
}
exports.default = init;
//# sourceMappingURL=handle-request.js.map