"use strict";
// This file is part of HFS - Copyright [Redacted PhoneNumber], [Redacted Person] <[Redacted Email]> - License https://www.gnu.org/licenses/gpl-3.0.txt
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sessionMiddleware = exports.paramsDecoder = exports.prepareState = exports.getProxyDetected = exports.someSecurity = exports.cloudflareDetected = exports.headRequests = exports.gzipper = exports.sessionDuration = void 0;
const koa_compress_1 = __importDefault(require("koa-compress"));
const const_1 = require("./const");
const misc_1 = require("./misc");
const stream_1 = require("stream");
const block_1 = require("./block");
const perm_1 = require("./perm");
const connections_1 = require("./connections");
const auth_1 = require("./auth");
const zlib_1 = require("zlib");
const listen_1 = require("./listen");
const config_1 = require("./config");
const koa_session_1 = __importDefault(require("koa-session"));
const index_1 = require("./index");
const events_1 = __importDefault(require("./events"));
const allowSessionIpChange = (0, config_1.defineConfig)(misc_1.CFG.allow_session_ip_change, false);
const forceHttps = (0, config_1.defineConfig)('force_https', true);
const ignoreProxies = (0, config_1.defineConfig)('ignore_proxies', false);
const allowAuthorizationHeader = (0, config_1.defineConfig)('authorization_header', true);
exports.sessionDuration = (0, config_1.defineConfig)('session_duration', Number(process.env.SESSION_DURATION) || misc_1.DAY / 1000, v => v * 1000);
exports.gzipper = (0, koa_compress_1.default)({
threshold: 2048,
gzip: { flush: zlib_1.constants.Z_SYNC_FLUSH },
deflate: { flush: zlib_1.constants.Z_SYNC_FLUSH },
br: false,
filter(type) {
return /text|javascript|style/i.test(type);
},
});
const headRequests = async (ctx, next) => {
const head = ctx.method === 'HEAD';
if (head)
ctx.method = 'GET'; // let other middlewares work, so we can collect the size at the end
await next();
if (!head || ctx.body === undefined)
return;
const { length, status } = ctx.response;
if (ctx.body)
ctx.body = stream_1.Readable.from(''); // empty the body for this is a HEAD request. Using Readable avoids koa from trying to set length to 0
ctx.status = status;
if (length)
ctx.response.length = length;
};
exports.headRequests = headRequests;
let proxyDetected;
const someSecurity = (ctx, next) => {
var _a;
ctx.request.ip = (0, connections_1.normalizeIp)(ctx.ip);
const ss = ctx.session;
const allowIpChange = (_a = ss === null || ss === void 0 ? void 0 : ss[allowSessionIpChange.key()]) !== null && _a !== void 0 ? _a : allowSessionIpChange.get(); // session can override server setting
if ((ss === null || ss === void 0 ? void 0 : ss.username) && (!allowIpChange || !ctx.secure && allowIpChange === 'https'))
if (!ss.ip)
ss.ip = ctx.ip;
else if (ss.ip !== ctx.ip) {
delete ss.username;
ss.ip = ctx.ip;
}
try {
if ((0, misc_1.dirTraversal)(decodeURI(ctx.path)))
return ctx.status = const_1.HTTP_FOOL;
if (!ctx.state.skipFilters && (0, block_1.applyBlock)(ctx.socket, ctx.ip))
return;
if (!ctx.ips.length && ctx.get('X-Forwarded-For') // empty ctx.ips implies we didn't configure for proxies
// we have some dev-proxies to ignore
&& !(const_1.DEV && [process.env.FRONTEND_PROXY, process.env.ADMIN_PROXY].includes(ctx.get('X-Forwarded-port')))) {
proxyDetected = ctx;
ctx.state.whenProxyDetected = new Date();
}
if (ctx.get('cf-ray'))
exports.cloudflareDetected = new Date();
}
catch (_b) {
return ctx.status = const_1.HTTP_FOOL;
}
if (!ctx.secure && forceHttps.get() && (0, listen_1.getHttpsWorkingPort)() && !(0, misc_1.isLocalHost)(ctx)) {
const { URL } = ctx;
URL.protocol = 'https';
URL.port = (0, listen_1.getHttpsWorkingPort)();
ctx.status = 307; // this ensures the client doesn't switch to a simpler GET request
return ctx.redirect(URL.href);
}
return next();
};
exports.someSecurity = someSecurity;
// limited to http proxies
function getProxyDetected() {
if ((proxyDetected === null || proxyDetected === void 0 ? void 0 : proxyDetected.state.whenProxyDetected) < Date.now() - misc_1.DAY)
proxyDetected = undefined;
return !ignoreProxies.get() && proxyDetected
&& { from: proxyDetected.ip, for: proxyDetected.get('X-Forwarded-For') };
}
exports.getProxyDetected = getProxyDetected;
const prepareState = async (ctx, next) => {
var _a, _b;
if ((_a = ctx.session) === null || _a === void 0 ? void 0 : _a.username) {
if (ctx.session.ts < auth_1.invalidateSessionBefore.get(ctx.session.username))
delete ctx.session.username;
ctx.session.maxAge = exports.sessionDuration.compiled();
}
// calculate these once and for all
ctx.state.connection = (0, connections_1.socket2connection)(ctx.socket);
const a = ctx.state.account = await urlLogin() || await getHttpAccount() || (0, perm_1.getAccount)((_b = ctx.session) === null || _b === void 0 ? void 0 : _b.username, false);
if (a && !(0, perm_1.accountCanLogin)(a))
ctx.state.account = undefined;
ctx.state.revProxyPath = ctx.get('x-forwarded-prefix');
(0, connections_1.updateConnectionForCtx)(ctx);
await next();
function urlLogin() {
const { login } = ctx.query;
if (!login)
return;
const [u, p] = (0, misc_1.splitAt)(':', String(login));
ctx.redirect(ctx.originalUrl.slice(0, -ctx.querystring.length - 1)); // redirect to hide credentials
return doLogin(u, p, 'url');
}
function getHttpAccount() {
var _a;
const b64 = allowAuthorizationHeader.get() && ((_a = ctx.get('authorization')) === null || _a === void 0 ? void 0 : _a.split(' ')[1]);
if (!b64)
return;
try {
const [u, p] = atob(b64).split(':');
return doLogin(u, p || '', 'header');
}
catch (_b) { }
}
async function doLogin(u, p, via) {
var _a, _b;
if (!u || u === ((_a = ctx.session) === null || _a === void 0 ? void 0 : _a.username))
return; // providing credentials, but not needed
if ((_b = (await events_1.default.emitAsync('attemptingLogin', { ctx, username: u, via }))) === null || _b === void 0 ? void 0 : _b.isDefaultPrevented())
return;
const a = await (0, auth_1.srpCheck)(u, p);
if (a) {
await (0, auth_1.setLoggedIn)(ctx, a.username);
ctx.headers['x-username'] = a.username; // give an easier way to determine if the login was successful
}
else if (u)
events_1.default.emit('failedLogin', ctx, { username: u });
return a;
}
};
exports.prepareState = prepareState;
const paramsDecoder = async (ctx, next) => {
ctx.state.params = ctx.method === 'POST' && ctx.originalUrl.startsWith(const_1.API_URI)
&& ((0, misc_1.tryJson)(await (0, misc_1.stream2string)(ctx.req)) || {});
await next();
};
exports.paramsDecoder = paramsDecoder;
// once https cookie is created, http cannot do the same. The solution is to use 2 different cookies.
// But koa-session doesn't support 2 cookies, so I made this hacky solution: keep track of the options object, to modify the key at run-time.
let internalSessionMw;
let options;
events_1.default.once('app', () => // wait for app to be defined
internalSessionMw = (0, koa_session_1.default)(options = { signed: true, rolling: true, sameSite: 'lax' }, index_1.app));
const sessionMiddleware = (ctx, next) => {
options.key = 'hfs_' + ctx.protocol;
return internalSessionMw(ctx, next);
};
exports.sessionMiddleware = sessionMiddleware;