chore: restart the repository with a clean history
CI / Docker image (push) Successful in 12s
CI / Server (push) Successful in 25s
CI / CLI (push) Successful in 13s
Development image / Development image (push) Successful in 21s
CI / CLI (windows) (push) Successful in 57s
CI / CLI (linux-arm64, static) (push) Successful in 1m37s
Release / Prepare release (push) Successful in 2s
Release / Server (linux-x64) (push) Successful in 53s
Release / CLI (linux-arm64, static) (push) Successful in 1m32s
Release / Docker image (push) Successful in 2m48s
Release / Server (windows-x64) (push) Successful in 6m20s
Release / CLI (windows-x64) (push) Successful in 6m48s
Release / CLI (linux-x64) (push) Successful in 7m8s
Release / Publish release (push) Successful in 1s

Squash the tree into one commit, drop docs/architecture.html, reset the version line to 0.3.0, consolidate the changelog, enable Renovate automerge for non-major updates and add AGENTS.md.
This commit is contained in:
fristy committed 2026-11-10 11:31:13 +03:00
commit 650807c1fb
438 files changed
+45070

No files matched your search

+297
View File
@@ -0,0 +1,297 @@
const { EventEmitter } = require("node:events");
const { Duplex } = require("node:stream");
const { TYPES, WINDOW_SIZE, CHUNK_SIZE, MAX_DATAGRAM, encode, decode } = require("./frames");
const logger = require("../utils/logger");
const WS_HIGH_WATER = 4 * 1024 * 1024;
const PING_INTERVAL = 20_000;
const DRAIN_INTERVAL = 20;
const DEAD_AFTER = 60_000;
class MuxStream extends Duplex {
constructor(session, id, meta) {
super({ readableHighWaterMark: 64 * 1024, writableHighWaterMark: 64 * 1024, allowHalfOpen: true });
this.session = session;
this.id = id;
this.meta = meta;
this.protocol = meta.protocol === "udp" ? "udp" : "tcp";
this.sendWindow = WINDOW_SIZE;
this.pendingUpdate = 0;
this.writeQueue = [];
this.closeSent = false;
this.closeReceived = false;
this.finished = false;
}
setTimeout() { return this; }
setNoDelay() { return this; }
setKeepAlive() { return this; }
ref() { return this; }
unref() { return this; }
address() { return {}; }
get remoteAddress() { return this.meta.remote || ""; }
_read() {
if (this.pendingUpdate > 0 && !this.finished && !this.closeReceived) {
const amount = this.pendingUpdate;
this.pendingUpdate = 0;
const payload = Buffer.allocUnsafe(4);
payload.writeUInt32BE(amount, 0);
this.session._send(TYPES.WINDOW_UPDATE, this.id, payload);
}
}
_write(chunk, _encoding, callback) {
if (this.finished) return callback();
let offset = 0;
const pieces = [];
while (offset < chunk.length) {
pieces.push(chunk.subarray(offset, offset + CHUNK_SIZE));
offset += CHUNK_SIZE;
}
this.writeQueue.push({ pieces, index: 0, callback });
this._flushWrites();
}
_flushWrites() {
while (this.writeQueue.length && !this.finished) {
const item = this.writeQueue[0];
while (item.index < item.pieces.length) {
const piece = item.pieces[item.index];
if (this.sendWindow < piece.length || this.session.bufferedAmount() > WS_HIGH_WATER) {
this.session._wantDrain(this);
return;
}
this.sendWindow -= piece.length;
this.session._send(TYPES.DATA, this.id, piece);
item.index++;
}
this.writeQueue.shift();
item.callback();
}
if (this.writeQueue.length === 0 && this.finalCallback) {
const cb = this.finalCallback;
this.finalCallback = null;
this._sendClose();
cb();
}
}
_final(callback) {
if (this.finished) return callback();
this.finalCallback = callback;
this._flushWrites();
}
_sendClose() {
if (this.closeSent || this.finished) return;
this.closeSent = true;
this.session._send(TYPES.CLOSE, this.id);
this._maybeFinish();
}
_destroy(err, callback) {
for (const item of this.writeQueue) item.callback(err || new Error("stream destroyed"));
this.writeQueue = [];
if (!this.finished) {
this.finished = true;
if (!this.resetReceived && !(this.closeSent && this.closeReceived)) this.session._send(TYPES.RESET, this.id);
this.session._forget(this.id);
}
callback(err);
}
sendDatagram(data) {
if (this.finished || data.length > MAX_DATAGRAM) return false;
if (this.session.bufferedAmount() > WS_HIGH_WATER) return false;
this.session._send(TYPES.DATAGRAM, this.id, data);
return true;
}
_maybeFinish() {
if (this.closeSent && this.closeReceived && !this.finished) {
this.finished = true;
this.session._forget(this.id);
}
}
_onData(payload) {
if (this.closeReceived || this.finished) return;
this.pendingUpdate += payload.length;
this.push(Buffer.from(payload));
}
_onClose() {
if (this.closeReceived) return;
this.closeReceived = true;
this.push(null);
this._maybeFinish();
}
_onReset() {
this.resetReceived = true;
this.destroy(new Error("stream reset by peer"));
}
_onWindowUpdate(amount) {
this.sendWindow += amount;
this._flushWrites();
}
_onDatagram(payload) {
if (this.finished) return;
this.emit("datagram", Buffer.from(payload));
}
}
class MuxSession extends EventEmitter {
constructor(ws, { parity = 0, name = "mux" } = {}) {
super();
this.ws = ws;
this.name = name;
this.streams = new Map();
this.nextId = parity === 0 ? 2 : 1;
this.closed = false;
this.waitingForDrain = new Set();
this.drainTimer = null;
this.lastActivity = Date.now();
this.bytesSent = 0;
this.bytesReceived = 0;
ws.on("message", (data, isBinary) => {
this.lastActivity = Date.now();
if (isBinary) this._onFrame(data);
else this._onControl(data);
});
ws.on("close", (code, reason) => this._onSocketClose(code, reason));
ws.on("error", err => logger.debug(`${name}: websocket error: ${err.message}`));
this.pingTimer = setInterval(() => {
if (Date.now() - this.lastActivity > DEAD_AFTER) {
logger.info(`${name}: peer timed out`);
this.close(4008, "timeout");
return;
}
this.sendControl({ type: "ping" });
}, PING_INTERVAL);
}
bufferedAmount() {
return this.ws.bufferedAmount || 0;
}
_wantDrain(stream) {
this.waitingForDrain.add(stream);
if (this.drainTimer) return;
this.drainTimer = setInterval(() => this._drain(), DRAIN_INTERVAL);
}
_stopDraining() {
if (!this.drainTimer) return;
clearInterval(this.drainTimer);
this.drainTimer = null;
}
_drain() {
if (!this.waitingForDrain.size) return this._stopDraining();
if (this.bufferedAmount() > WS_HIGH_WATER) return;
const waiting = [...this.waitingForDrain];
this.waitingForDrain.clear();
for (const stream of waiting) stream._flushWrites();
if (!this.waitingForDrain.size) this._stopDraining();
}
sendControl(message) {
if (this.closed || this.ws.readyState !== this.ws.OPEN) return;
this.ws.send(JSON.stringify(message));
}
_send(type, streamId, payload) {
if (process.env.FRISLIT_MUX_DEBUG) logger.debug(`${this.name} > type=${type} stream=${streamId} len=${payload ? payload.length : 0}`);
if (this.closed || this.ws.readyState !== this.ws.OPEN) return;
if (payload && (type === TYPES.DATA || type === TYPES.DATAGRAM)) this.bytesSent += payload.length;
this.ws.send(encode(type, streamId, payload), { binary: true });
}
open(meta) {
if (this.closed) throw new Error("session closed");
const id = this.nextId;
this.nextId += 2;
const stream = new MuxStream(this, id, meta);
this.streams.set(id, stream);
this._send(TYPES.OPEN, id, JSON.stringify(meta));
return stream;
}
_forget(id) {
this.streams.delete(id);
}
_onControl(data) {
let message;
try {
message = JSON.parse(data.toString());
} catch {
return;
}
if (!message || typeof message.type !== "string") return;
if (message.type === "ping") return this.sendControl({ type: "pong" });
if (message.type === "pong") return;
this.emit("control", message);
}
_onFrame(data) {
const frame = decode(data);
if (!frame) return;
const { type, streamId, payload } = frame;
if (payload && (type === TYPES.DATA || type === TYPES.DATAGRAM)) this.bytesReceived += payload.length;
const stream = this.streams.get(streamId);
if (process.env.FRISLIT_MUX_DEBUG) logger.debug(`${this.name} < type=${type} stream=${streamId} len=${payload.length} known=${!!stream}`);
if (type === TYPES.OPEN) {
if (stream) return;
let meta = {};
try {
meta = JSON.parse(payload.toString("utf8")) || {};
} catch { }
const created = new MuxStream(this, streamId, meta);
this.streams.set(streamId, created);
this.emit("stream", created, meta);
return;
}
if (!stream) return;
switch (type) {
case TYPES.DATA: return stream._onData(payload);
case TYPES.CLOSE: return stream._onClose();
case TYPES.RESET: return stream._onReset();
case TYPES.DATAGRAM: return stream._onDatagram(payload);
case TYPES.WINDOW_UPDATE:
if (payload.length >= 4) stream._onWindowUpdate(payload.readUInt32BE(0));
return;
default:
return;
}
}
_onSocketClose(code, reason) {
if (this.closed) return;
this.closed = true;
clearInterval(this.pingTimer);
this._stopDraining();
for (const stream of [...this.streams.values()]) {
stream.resetReceived = true;
stream.destroy(new Error("session closed"));
}
this.streams.clear();
this.emit("close", code, reason?.toString());
}
close(code = 1000, reason = "") {
if (this.ws.readyState === this.ws.OPEN || this.ws.readyState === this.ws.CONNECTING) {
try { this.ws.close(code, reason); } catch { }
}
setTimeout(() => { try { this.ws.terminate(); } catch { } }, 2000).unref();
}
}
module.exports = { MuxSession };
+257
View File
@@ -0,0 +1,257 @@
const { randomToken } = require("../utils/ids");
const { hashPassword } = require("../utils/password");
const COOKIE_NAME = "frislit-access";
const TTL = 12 * 60 * 60 * 1000;
const AUTH_MODES = ["none", "password", "frislit"];
const stripScope = address => String(address || "").replace(/%.*$/, "");
const toBytes = address => {
const value = stripScope(address).replace(/^\[|\]$/g, "");
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(value);
const plain = mapped ? mapped[1] : value;
if (/^\d+\.\d+\.\d+\.\d+$/.test(plain)) {
const parts = plain.split(".").map(Number);
if (parts.some(part => !Number.isInteger(part) || part < 0 || part > 255)) return null;
return Buffer.from(parts);
}
if (!value.includes(":")) return null;
const [head, tail = ""] = value.split("::");
const expand = part => (part ? part.split(":").filter(Boolean) : []);
const left = expand(head);
const right = expand(tail);
const missing = 8 - left.length - right.length;
if (missing < 0 || (missing > 0 && !value.includes("::"))) return null;
const groups = [...left, ...Array(Math.max(missing, 0)).fill("0"), ...right];
if (groups.length !== 8) return null;
const bytes = Buffer.alloc(16);
for (let i = 0; i < 8; i++) {
const group = parseInt(groups[i], 16);
if (Number.isNaN(group) || group < 0 || group > 0xffff) return null;
bytes.writeUInt16BE(group, i * 2);
}
return bytes;
};
const parseRule = rule => {
const text = String(rule || "").trim();
if (!text) return null;
const [address, prefix] = text.split("/");
const bytes = toBytes(address);
if (!bytes) return null;
const bits = prefix === undefined ? bytes.length * 8 : Number(prefix);
if (!Number.isInteger(bits) || bits < 0 || bits > bytes.length * 8) return null;
return { bytes, bits, text };
};
const matchesRule = (address, rule) => {
const bytes = toBytes(address);
if (!bytes || bytes.length !== rule.bytes.length) return false;
const whole = rule.bits >> 3;
if (!bytes.subarray(0, whole).equals(rule.bytes.subarray(0, whole))) return false;
const remainder = rule.bits & 7;
if (!remainder) return true;
const mask = 0xff << (8 - remainder) & 0xff;
return (bytes[whole] & mask) === (rule.bytes[whole] & mask);
};
const isAllowed = (address, rules = []) => {
if (!rules.length) return true;
return rules.map(parseRule).filter(Boolean).some(rule => matchesRule(address, rule));
};
const CATEGORIES = ["tor", "vpn", "datacenter", "blocklist"];
const CATEGORY_KEYS = { tor: "tor", vpn: "vpn", datacenter: "datacenter", blocklist: "blocklisted" };
const CATEGORY_LABELS = { tor: "Tor exit nodes", vpn: "VPN services", datacenter: "datacenters", blocklist: "blocklisted addresses" };
const fail = message => Object.assign(new Error(message), { code: "bad_request" });
const emptyPolicy = () => ({
auth: "none",
passwordHash: null,
accounts: [],
allow: { ips: [], countries: [] },
block: { ips: [], countries: [], categories: [] },
});
const accountIds = value => {
const ids = [...new Set((Array.isArray(value) ? value : []).map(Number))];
for (const id of ids) if (!Number.isInteger(id) || id <= 0) throw fail("Accounts must be account ids");
if (ids.length > 100) throw fail("At most 100 accounts");
return ids;
};
const accountAllowed = (policy, accountId, ownerId) =>
!policy.accounts?.length || accountId === ownerId || policy.accounts.includes(accountId);
const listOf = value => (Array.isArray(value) ? value : String(value).split(",")).map(entry => String(entry).trim()).filter(Boolean);
const ipRules = value => {
const rules = listOf(value);
for (const rule of rules) if (!parseRule(rule)) throw fail(`"${rule}" is not an IP address or CIDR range`);
if (rules.length > 64) throw fail("At most 64 IP rules");
return rules;
};
const countryCodes = value => {
const codes = [...new Set(listOf(value).map(code => code.toUpperCase()))];
for (const code of codes) if (!/^[A-Z]{2}$/.test(code)) throw fail(`"${code}" is not a country code`);
return codes;
};
const categories = value => {
const list = [...new Set(listOf(value).map(entry => entry.toLowerCase()))];
for (const entry of list) if (!CATEGORIES.includes(entry)) throw fail(`"${entry}" is not one of ${CATEGORIES.join(", ")}`);
return list;
};
const buildPolicy = (input = {}, previous = emptyPolicy()) => {
const policy = { ...previous, allow: { ...previous.allow }, block: { ...previous.block } };
if (input.allow?.ips !== undefined) policy.allow.ips = ipRules(input.allow.ips);
if (input.allow?.countries !== undefined) policy.allow.countries = countryCodes(input.allow.countries);
if (input.block?.ips !== undefined) policy.block.ips = ipRules(input.block.ips);
if (input.block?.countries !== undefined) policy.block.countries = countryCodes(input.block.countries);
if (input.block?.categories !== undefined) policy.block.categories = categories(input.block.categories);
if (input.accounts !== undefined) policy.accounts = accountIds(input.accounts);
if (input.auth !== undefined) {
const auth = String(input.auth || "none");
if (!AUTH_MODES.includes(auth)) throw Object.assign(new Error(`auth must be one of ${AUTH_MODES.join(", ")}`), { code: "bad_request" });
policy.auth = auth;
}
if (input.password) {
const password = String(input.password);
if (password.length < 4) throw Object.assign(new Error("The tunnel password must be at least 4 characters"), { code: "bad_request" });
policy.passwordHash = hashPassword(password);
if (input.auth === undefined) policy.auth = "password";
}
if (policy.auth === "password" && !policy.passwordHash) {
throw Object.assign(new Error("Password protection needs a password"), { code: "bad_request" });
}
if (policy.auth !== "password") policy.passwordHash = null;
return policy;
};
const describePolicy = (policy = emptyPolicy()) => ({
auth: policy.auth,
hasPassword: !!policy.passwordHash,
accounts: policy.accounts || [],
allow: policy.allow,
block: policy.block,
});
const hasRules = policy => policy.allow.ips.length + policy.allow.countries.length + policy.block.ips.length + policy.block.countries.length + policy.block.categories.length > 0;
const isRestricted = (policy = emptyPolicy()) => policy.auth !== "none" || hasRules(policy);
const evaluate = (policy, ip, intel) => {
if (!hasRules(policy)) return null;
const { allow, block } = policy;
if (block.ips.length && isAllowed(ip, block.ips)) return "address";
if (block.countries.includes(intel.country)) return "country";
const category = block.categories.find(entry => intel[CATEGORY_KEYS[entry]]);
if (category) return category;
if (allow.ips.length && !isAllowed(ip, allow.ips)) return "address";
if (allow.countries.length && !allow.countries.includes(intel.country)) return "country";
return null;
};
const summarizePolicy = policy => {
const parts = [];
if (policy.auth === "frislit") parts.push("frislit login required");
if (policy.auth === "password") parts.push("password protected");
if (policy.allow.ips.length) parts.push(`allowed: ${policy.allow.ips.join(", ")}`);
if (policy.allow.countries.length) parts.push(`only ${policy.allow.countries.join(", ")}`);
if (policy.block.ips.length) parts.push(`blocked: ${policy.block.ips.join(", ")}`);
if (policy.block.countries.length) parts.push(`not ${policy.block.countries.join(", ")}`);
if (policy.block.categories.length) parts.push(`no ${policy.block.categories.map(entry => CATEGORY_LABELS[entry]).join(", ")}`);
return parts.join(" · ") || null;
};
const CODE_TTL = 60 * 1000;
class AccessStore {
constructor(ttl = TTL) {
this.ttl = ttl;
this.tokens = new Map();
this.codes = new Map();
this.sweeper = setInterval(() => this.sweep(), 10 * 60 * 1000);
this.sweeper.unref();
}
create(tunnelId) {
const token = randomToken(32);
this.tokens.set(token, { tunnelId, expiresAt: Date.now() + this.ttl });
return token;
}
issueCode(tunnelId, host) {
const code = randomToken(32);
this.codes.set(code, { tunnelId, host, expiresAt: Date.now() + CODE_TTL });
return code;
}
redeem(code, host) {
const entry = code && this.codes.get(code);
if (!entry) return null;
this.codes.delete(code);
if (entry.expiresAt < Date.now() || entry.host !== host) return null;
return this.create(entry.tunnelId);
}
allows(token, tunnelId) {
const entry = token && this.tokens.get(token);
if (!entry) return false;
if (entry.expiresAt < Date.now()) {
this.tokens.delete(token);
return false;
}
return entry.tunnelId === tunnelId;
}
forget(tunnelId) {
for (const [token, entry] of this.tokens) if (entry.tunnelId === tunnelId) this.tokens.delete(token);
}
sweep() {
const now = Date.now();
for (const [token, entry] of this.tokens) if (entry.expiresAt < now) this.tokens.delete(token);
for (const [code, entry] of this.codes) if (entry.expiresAt < now) this.codes.delete(code);
}
}
const cookieFor = (token, secure) =>
`${COOKIE_NAME}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${Math.floor(TTL / 1000)}${secure ? "; Secure" : ""}`;
const tokenFromRequest = req => {
for (const part of String(req.headers.cookie || "").split(";")) {
const index = part.indexOf("=");
if (index === -1) continue;
if (part.slice(0, index).trim() === COOKIE_NAME) return part.slice(index + 1).trim();
}
return null;
};
const basicCredentials = req => {
const header = req.headers.authorization;
const match = header && /^Basic\s+(.+)$/i.exec(header.trim());
if (!match) return null;
const decoded = Buffer.from(match[1], "base64").toString("utf8");
const separator = decoded.indexOf(":");
if (separator === -1) return null;
return { username: decoded.slice(0, separator), password: decoded.slice(separator + 1) };
};
module.exports = {
AccessStore, isAllowed, emptyPolicy, buildPolicy, describePolicy, summarizePolicy, isRestricted, evaluate,
accountAllowed, cookieFor, tokenFromRequest, basicCredentials,
};
+91
View File
@@ -0,0 +1,91 @@
const Account = require("../models/Account");
const Session = require("../models/Session");
const Device = require("../models/Device");
const Invite = require("../models/Invite");
const { hashPassword, verifyPassword } = require("../utils/password");
const ABSENT = hashPassword("account-that-does-not-exist");
const USERNAME_REGEX = /^[a-zA-Z0-9._-]{3,32}$/;
const ROLES = ["admin", "user"];
const describe = account => ({
id: account.id,
username: account.username,
role: account.role,
quotas: account.quotas ? JSON.parse(account.quotas) : null,
createdAt: account.createdAt,
});
const validate = ({ username, password }) => {
if (username !== undefined && !USERNAME_REGEX.test(String(username || ""))) {
return "The username must be 3 to 32 letters, digits, dots, dashes or underscores";
}
if (password !== undefined && String(password || "").length < 8) return "The password must be at least 8 characters";
return null;
};
const count = () => Account.count();
const byUsername = username => Account.findOne({ where: { username: String(username || "") } });
const byId = id => Account.findByPk(id);
const list = () => Account.findAll({ order: [["id", "ASC"]] }).then(rows => rows.map(describe));
const create = async ({ username, password, role = "user" }) => {
const problem = validate({ username, password });
if (problem) return { code: 400, message: problem };
if (!ROLES.includes(role)) return { code: 400, message: `The role must be one of ${ROLES.join(", ")}` };
if (await byUsername(username)) return { code: 409, message: "That username is taken" };
await Account.create({ username, passwordHash: hashPassword(password), role });
return { account: describe(await byUsername(username)) };
};
const adminCount = () => Account.count({ where: { role: "admin" } });
const update = async (id, { role, password, quotas }) => {
const account = await byId(id);
if (!account) return { code: 404, message: "That account does not exist" };
const values = {};
if (role !== undefined && role !== account.role) {
if (!ROLES.includes(role)) return { code: 400, message: `The role must be one of ${ROLES.join(", ")}` };
if (account.role === "admin" && await adminCount() <= 1) return { code: 409, message: "The last admin cannot lose the role" };
values.role = role;
}
if (password !== undefined) {
const problem = validate({ password });
if (problem) return { code: 400, message: problem };
values.passwordHash = hashPassword(password);
await Session.destroy({ where: { accountId: account.id } });
}
if (quotas !== undefined) values.quotas = quotas ? JSON.stringify(quotas) : null;
if (Object.keys(values).length) await Account.update(values, { where: { id: account.id } });
return { account: describe(await byId(account.id)) };
};
const remove = async id => {
const account = await byId(id);
if (!account) return { code: 404, message: "That account does not exist" };
if (account.role === "admin" && await adminCount() <= 1) return { code: 409, message: "The last admin cannot be deleted" };
await Session.destroy({ where: { accountId: account.id } });
await Device.destroy({ where: { accountId: account.id } });
await Invite.destroy({ where: { accountId: account.id } });
await Account.destroy({ where: { id: account.id } });
return { message: "Account deleted" };
};
const checkCredentials = async ({ username, password } = {}) => {
const account = await byUsername(username);
const matches = await verifyPassword(String(password || ""), account ? account.passwordHash : ABSENT);
return account && matches ? account : null;
};
module.exports = { describe, validate, count, byId, byUsername, list, create, update, remove, checkCredentials, USERNAME_REGEX };
+89
View File
@@ -0,0 +1,89 @@
const { randomToken } = require("../utils/ids");
const MAX_RULES = 32;
const METHOD = /^[A-Z]{3,10}$/;
const PHASES = ["request", "response", "both"];
const fail = message => Object.assign(new Error(message), { code: "bad_request" });
const normalizeRules = input => {
if (!Array.isArray(input)) throw fail("rules must be a list");
if (input.length > MAX_RULES) throw fail(`At most ${MAX_RULES} breakpoints`);
return input.map(rule => {
const method = rule.method ? String(rule.method).trim().toUpperCase() : null;
if (method && !METHOD.test(method)) throw fail(`"${rule.method}" is not a method`);
const path = String(rule.path).trim();
if (!path.startsWith("/")) throw fail("A breakpoint path must start with /");
const phase = String(rule.phase);
if (!PHASES.includes(phase)) throw fail(`phase must be one of ${PHASES.join(", ")}`);
return { method, path, phase };
});
};
class Breakpoints {
constructor() {
this.rules = new Map();
this.held = new Map();
}
rulesFor(tunnel) {
return this.rules.get(tunnel) || [];
}
setRules(tunnel, input) {
const rules = normalizeRules(input);
if (rules.length) this.rules.set(tunnel, rules); else this.rules.delete(tunnel);
return rules;
}
matches(tunnel, method, path, phase) {
return this.rulesFor(tunnel).some(rule => (rule.phase === phase || rule.phase === "both") && (!rule.method || rule.method === method) && path.startsWith(rule.path));
}
hold(tunnel, request) {
const id = randomToken(12);
let resolve;
const decision = new Promise(done => { resolve = done; });
this.held.set(id, { id, tunnel, ...request, resolve });
return { id, decision };
}
settle(id, decision) {
const entry = this.held.get(id);
if (!entry) return false;
this.held.delete(id);
entry.resolve(decision);
return true;
}
get(tunnel, id) {
const entry = this.held.get(id);
return entry && entry.tunnel === tunnel ? entry : null;
}
list(tunnel) {
return [...this.held.values()].filter(entry => entry.tunnel === tunnel).map(serialize);
}
forget(tunnel) {
this.rules.delete(tunnel);
for (const entry of this.held.values()) if (entry.tunnel === tunnel) this.settle(entry.id, { action: "cancel" });
}
}
const part = ({ headers, body, bytes, truncated }) => ({ headers, body: body ? body.toString("base64") : null, bytes, truncated });
const serialize = entry => ({
id: entry.id,
phase: entry.phase,
time: entry.time,
method: entry.method,
path: entry.path,
ip: entry.ip,
host: entry.host,
status: entry.response?.status,
request: part(entry.request),
...(entry.response ? { response: { status: entry.response.status, ...part(entry.response) } } : {}),
});
module.exports = { Breakpoints, serialize };
+96
View File
@@ -0,0 +1,96 @@
const { QUERY_PARAM } = require("./proxy");
const UI_PREFIX = "/@frislit";
const SW_PATH = `${UI_PREFIX}/sw.js`;
const STORAGE_KEY = "frislit-tunnel";
const serviceWorker = () => `const PARAM = ${JSON.stringify(QUERY_PARAM)};
const UI_PREFIX = ${JSON.stringify(UI_PREFIX)};
const bindings = new Map();
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", event => event.waitUntil(self.clients.claim()));
self.addEventListener("message", event => {
const data = event.data || {};
if (data.type !== "frislit-bind" || !data.tunnel || !event.source) return;
bindings.set(event.source.id, data.tunnel);
event.source.postMessage({ type: "frislit-bound", tunnel: data.tunnel });
});
const ATTACH_PATH = new RegExp("^/@[a-z0-9-]{3,32}(/|$)");
const isOwnPath = url => url.pathname === UI_PREFIX || url.pathname.startsWith(UI_PREFIX + "/")
|| ATTACH_PATH.test(url.pathname);
const forward = async (request, tunnel, navigation) => {
const url = new URL(request.url);
url.searchParams.set(PARAM, tunnel);
const init = {
method: request.method,
headers: request.headers,
credentials: request.credentials,
redirect: navigation ? "manual" : "follow",
};
if (request.method !== "GET" && request.method !== "HEAD") init.body = await request.blob();
return fetch(new Request(url.toString(), init));
};
self.addEventListener("fetch", event => {
const request = event.request;
let url;
try {
url = new URL(request.url);
} catch {
return;
}
if (url.origin !== self.location.origin) return;
if (isOwnPath(url) || url.searchParams.has(PARAM)) return;
const navigation = request.mode === "navigate";
const tunnel = bindings.get(event.clientId);
if (tunnel) {
if (navigation && event.resultingClientId) bindings.set(event.resultingClientId, tunnel);
event.respondWith(forward(request, tunnel, navigation));
return;
}
if (navigation) {
const target = new URL(UI_PREFIX + "/reattach", self.location.origin);
target.searchParams.set("to", request.url);
event.respondWith(Response.redirect(target.toString(), 302));
}
});
`;
const injectedScript = id => `<script>(function(){
var TUNNEL=${JSON.stringify(id)},PARAM=${JSON.stringify(QUERY_PARAM)},SW=${JSON.stringify(SW_PATH)};
try{sessionStorage.setItem(${JSON.stringify(STORAGE_KEY)},TUNNEL);}catch(e){}
try{if(navigator.serviceWorker){
var register=navigator.serviceWorker.register.bind(navigator.serviceWorker);
Object.defineProperty(navigator.serviceWorker,"register",{configurable:false,writable:false,value:function(){
return Promise.reject(new DOMException("Service workers are managed by frislit in path mode","SecurityError"));}});
navigator.serviceWorker.getRegistrations().then(function(list){var mine=false;
list.forEach(function(r){var s=((r.active||r.waiting||r.installing)||{}).scriptURL||"";
if(s.indexOf(SW)!==-1){mine=true;}else{r.unregister();}});
if(!mine){register(SW,{scope:"/"});}});
navigator.serviceWorker.ready.then(function(r){var w=navigator.serviceWorker.controller||r.active;
if(w)w.postMessage({type:"frislit-bind",tunnel:TUNNEL});});
}}catch(e){}
try{var Original=window.WebSocket;if(Original){var fix=function(value){var url;
try{url=new URL(String(value),location.href);}catch(e){return value;}
if(location.protocol==="https:"&&url.protocol==="ws:")url.protocol="wss:";
if(url.host===location.host)url.searchParams.set(PARAM,TUNNEL);return url.toString();};
window.WebSocket=new Proxy(Original,{construct:function(target,args){args[0]=fix(args[0]);return new target(args[0],args[1]);}});}}catch(e){}
})();</script>`;
const SERVICE_WORKER_SOURCE = serviceWorker();
try {
new Function(SERVICE_WORKER_SOURCE);
} catch (err) {
throw new Error(`The generated service worker does not parse: ${err.message}`);
}
module.exports = { SERVICE_WORKER_SOURCE, SW_PATH, injectedScript };
+36
View File
@@ -0,0 +1,36 @@
const { Transform } = require("node:stream");
const MAX_BODY = 64 * 1024;
class Tap extends Transform {
constructor(limit = MAX_BODY) {
super();
this.limit = limit;
this.chunks = [];
this.kept = 0;
this.total = 0;
}
_transform(chunk, _encoding, callback) {
this.total += chunk.length;
if (this.kept < this.limit) {
const room = this.limit - this.kept;
const piece = chunk.length > room ? chunk.subarray(0, room) : chunk;
this.chunks.push(piece);
this.kept += piece.length;
}
callback(null, chunk);
}
result() {
return {
body: this.chunks.length ? Buffer.concat(this.chunks, this.kept) : null,
bytes: this.total,
truncated: this.total > this.kept,
};
}
}
const headerList = headers => Object.entries(headers).flatMap(([name, value]) => [].concat(value).map(one => [name, String(one)]));
module.exports = { Tap, headerList, MAX_BODY };
+149
View File
@@ -0,0 +1,149 @@
const { Op } = require("sequelize");
const Connection = require("../models/Connection");
const { randomToken } = require("../utils/ids");
const { sniff } = require("./sniff");
const logger = require("../utils/logger");
const PER_TUNNEL_LIMIT = 500;
const PAGE_SIZE = 50;
const FLUSH_INTERVAL = 500;
const SORTABLE = { started: "startedAt", in: "bytesIn", out: "bytesOut", ip: "ip" };
const serialize = row => ({
key: row.key,
protocol: row.protocol,
ip: row.ip,
intel: JSON.parse(row.intel),
client: row.client,
joiner: row.joiner,
startedAt: new Date(row.startedAt).getTime(),
endedAt: row.endedAt ? new Date(row.endedAt).getTime() : null,
bytesIn: row.bytesIn,
bytesOut: row.bytesOut,
reason: row.reason,
detail: row.detail && JSON.parse(row.detail),
});
class ConnectionLog {
constructor() {
this.live = new Map();
this.inserts = [];
this.dirty = new Set();
this.timer = null;
}
start() {
if (this.timer) return;
this.timer = setInterval(() => this.flush(), FLUSH_INTERVAL);
this.timer.unref();
}
stop() {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
open(tunnel, { protocol, ip, intel, client, joiner }) {
const entry = {
key: randomToken(16), tunnel, protocol, ip, intel, client, joiner,
startedAt: Date.now(), endedAt: null, bytesIn: 0, bytesOut: 0, reason: null, detail: null,
sniffed: { in: false, out: false },
};
this.live.set(entry.key, entry);
this.inserts.push(entry);
return entry;
}
data(entry, direction, buffer) {
entry[direction === "in" ? "bytesIn" : "bytesOut"] += buffer.length;
if (!entry.sniffed[direction]) {
entry.sniffed[direction] = true;
if (!entry.detail) {
entry.detail = sniff(entry.protocol, direction, buffer);
if (entry.detail) this.dirty.add(entry.key);
}
}
}
close(entry, reason) {
entry.endedAt = Date.now();
entry.reason = reason;
this.dirty.add(entry.key);
}
async flush() {
const inserts = this.inserts;
const dirty = [...this.dirty];
this.inserts = [];
this.dirty.clear();
if (!inserts.length && !dirty.length) return;
try {
if (inserts.length) {
await Connection.bulkCreate(inserts.map(entry => ({ ...entry, intel: JSON.stringify(entry.intel), detail: entry.detail && JSON.stringify(entry.detail), startedAt: new Date(entry.startedAt), endedAt: entry.endedAt && new Date(entry.endedAt) })));
for (const tunnel of new Set(inserts.map(entry => entry.tunnel))) await this.prune(tunnel);
}
const fresh = new Set(inserts.map(entry => entry.key));
for (const key of dirty) {
const entry = this.live.get(key);
if (!fresh.has(key)) await this.update(entry);
if (entry.endedAt) this.live.delete(key);
}
} catch (err) {
logger.warn(`Could not store connections: ${err.message}`);
}
}
update(entry) {
return Connection.update({
bytesIn: entry.bytesIn, bytesOut: entry.bytesOut, reason: entry.reason,
detail: entry.detail && JSON.stringify(entry.detail), endedAt: entry.endedAt && new Date(entry.endedAt),
}, { where: { key: entry.key } });
}
async prune(tunnel) {
const rows = await Connection.findAll({
where: { tunnel, endedAt: { [Op.ne]: null } }, order: [["startedAt", "DESC"]], offset: PER_TUNNEL_LIMIT, limit: 1, attributes: ["startedAt"],
});
if (!rows.length) return;
await Connection.destroy({ where: { tunnel, endedAt: { [Op.ne]: null }, startedAt: { [Op.lte]: rows[0].startedAt } } });
}
current(row) {
const live = this.live.get(row.key);
return live ? { ...serialize(row), bytesIn: live.bytesIn, bytesOut: live.bytesOut, detail: live.detail } : serialize(row);
}
async list(tunnel, { sort = "started", order = "desc", offset = 0, limit = PAGE_SIZE } = {}) {
await this.flush();
const rows = await Connection.findAll({
where: { tunnel },
order: [[SORTABLE[sort] || "startedAt", order === "asc" ? "ASC" : "DESC"], ["id", "DESC"]],
offset: Math.max(offset, 0),
limit: Math.min(Math.max(limit, 1), PER_TUNNEL_LIMIT),
});
return rows.map(row => this.current(row));
}
count(tunnel) {
return Connection.count({ where: { tunnel } });
}
async get(tunnel, key) {
await this.flush();
const row = await Connection.findOne({ where: { tunnel, key } });
return row ? this.current(row) : null;
}
async clear(tunnel) {
await this.flush();
await Connection.destroy({ where: { tunnel, endedAt: { [Op.ne]: null } } });
}
async forget(tunnel) {
for (const [key, entry] of this.live) if (entry.tunnel === tunnel) this.live.delete(key);
this.inserts = this.inserts.filter(entry => entry.tunnel !== tunnel);
await Connection.destroy({ where: { tunnel } });
}
}
module.exports = { ConnectionLog };
+150
View File
@@ -0,0 +1,150 @@
const crypto = require("node:crypto");
const Device = require("../models/Device");
const Account = require("../models/Account");
const { hashToken, randomToken } = require("../utils/ids");
const logger = require("../utils/logger");
const CODE_TTL = 10 * 60 * 1000;
const CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
const CODE_LENGTH = 8;
const TOUCH_AFTER = 60_000;
const humanCode = () => {
const bytes = crypto.randomBytes(CODE_LENGTH);
let code = "";
for (let i = 0; i < CODE_LENGTH; i++) {
if (i === 4) code += "-";
code += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];
}
return code;
};
const describeDevice = (device, owner) => ({
id: device.id,
name: device.name,
kind: device.kind,
owner: owner || null,
createdAt: device.createdAt,
lastUsedAt: device.lastUsedAt,
ip: device.ip,
userAgent: device.userAgent,
});
class DeviceStore {
constructor() {
this.pending = new Map();
this.sweeper = setInterval(() => this.sweep(), 60_000);
this.sweeper.unref();
}
sweep() {
const now = Date.now();
for (const [code, request] of this.pending) if (request.expiresAt < now) this.pending.delete(code);
}
createCode({ client = "cli", ip = "", userAgent = "" } = {}) {
this.sweep();
const code = humanCode();
const pollToken = randomToken(32);
const expiresAt = Date.now() + CODE_TTL;
this.pending.set(code, { code, pollToken, client, ip, userAgent, createdAt: Date.now(), expiresAt, status: "pending", issued: null });
logger.info(`Device code ${code} requested`, { ip, client });
return { code, pollToken, expiresAt };
}
get(code) {
this.sweep();
return this.pending.get(String(code || "").toUpperCase().trim()) || null;
}
describe(code) {
const request = this.get(code);
if (!request) return null;
return {
code: request.code, client: request.client, ip: request.ip,
userAgent: request.userAgent, createdAt: request.createdAt,
expiresAt: request.expiresAt, status: request.status,
};
}
async createKey(accountId, name) {
const label = String(name || "").trim();
if (!label) return { code: 400, message: "Give the key a name" };
const token = randomToken(48);
const device = await Device.create({ accountId, name: label, kind: "key", tokenHash: hashToken(token) });
logger.info(`API key "${label}" created`, { id: device.id });
return { device: describeDevice(device), token };
}
async approve(code, { name, accountId } = {}) {
const request = this.get(code);
if (!request) return { code: 404, message: "That code is unknown or has expired" };
if (request.status !== "pending") return { code: 409, message: "That code was already used" };
const token = randomToken(48);
const device = await Device.create({
accountId,
name: String(name || "").trim() || request.client || "CLI",
tokenHash: hashToken(token),
ip: request.ip || null,
userAgent: request.userAgent || null,
});
request.status = "authorized";
request.issued = token;
logger.info(`Device "${device.name}" authorized`, { id: device.id, ip: request.ip });
return { device: describeDevice(device) };
}
deny(code) {
const request = this.get(code);
if (!request) return { code: 404, message: "That code is unknown or has expired" };
this.pending.delete(request.code);
logger.info(`Device code ${request.code} denied`);
return { message: "Request denied" };
}
poll(pollToken) {
this.sweep();
for (const request of this.pending.values()) {
if (request.pollToken !== pollToken) continue;
if (request.status !== "authorized") return { status: "pending" };
const token = request.issued;
this.pending.delete(request.code);
return { status: "authorized", token };
}
return { status: "invalid" };
}
async verify(token) {
if (typeof token !== "string" || !token) return null;
const device = await Device.findOne({ where: { tokenHash: hashToken(token) } });
if (!device) return null;
if (!device.lastUsedAt || Date.now() - new Date(device.lastUsedAt).getTime() > TOUCH_AFTER) {
await Device.update({ lastUsedAt: new Date() }, { where: { id: device.id } });
}
return device;
}
async list(accountId) {
const where = accountId === undefined ? {} : { accountId };
const devices = await Device.findAll({ where, order: [["createdAt", "DESC"]] });
if (accountId !== undefined) return devices.map(device => describeDevice(device));
const accounts = await Account.findAll();
const names = new Map(accounts.map(account => [account.id, account.username]));
return devices.map(device => describeDevice(device, names.get(device.accountId)));
}
async revoke(id, accountId) {
const where = accountId === undefined ? { id } : { id, accountId };
const device = await Device.findOne({ where });
if (!device) return { code: 404, message: "Device not found" };
await Device.destroy({ where: { id: device.id } });
logger.info(`Device "${device.name}" revoked`, { id });
return { message: `${device.name} revoked` };
}
}
module.exports = { DeviceStore };
+139
View File
@@ -0,0 +1,139 @@
const dns = require("node:dns").promises;
const Domain = require("../models/Domain");
const logger = require("../utils/logger");
const RECHECK_INTERVAL = 5 * 60 * 1000;
const HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,62}$/;
const UNSETTLED = ["pending", "issuing", "error"];
const normalize = hostname => String(hostname || "").trim().toLowerCase().replace(/\.$/, "");
const fail = (message, code) => Object.assign(new Error(message), { code });
class DomainManager {
constructor({ config, certificates }) {
this.config = config;
this.certificates = certificates;
this.byHost = new Map();
this.checking = new Map();
this.timer = null;
}
async load() {
const rows = await Domain.findAll();
this.byHost = new Map(rows.map(row => [row.hostname, row.tunnelName]));
}
start() {
if (this.timer) return;
const recheck = () => this.recheck().catch(err => logger.warn(`Domain check failed: ${err.message}`));
this.timer = setInterval(recheck, RECHECK_INTERVAL);
this.timer.unref();
recheck();
}
stop() {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
tunnelFor(hostname) {
return this.byHost.get(hostname) || null;
}
countFor(accountId) {
return Domain.count({ where: { accountId } });
}
hostsFor(tunnelName) {
return [...this.byHost].filter(([, name]) => name === tunnelName).map(([hostname]) => hostname);
}
describe(row) {
return {
hostname: row.hostname,
tunnel: row.tunnelName,
state: row.state,
error: row.lastError || null,
checkedAt: row.checkedAt,
createdAt: row.createdAt,
url: `${this.config.publicScheme}://${row.hostname}`,
certificate: this.certificates.info(row.hostname),
};
}
validate(hostname) {
const base = this.config.baseDomain;
if (!HOSTNAME.test(hostname)) throw fail(`"${hostname}" is not a valid hostname`, "bad_request");
if (hostname === base || hostname.endsWith(`.${base}`)) throw fail(`Names under ${base} are handled by the server itself`, "bad_request");
return hostname;
}
async listFor(tunnelName) {
const rows = await Domain.findAll({ where: { tunnelName }, order: [["hostname", "ASC"]] });
return rows.map(row => this.describe(row));
}
async add(rawHostname, tunnelName, accountId) {
const hostname = this.validate(normalize(rawHostname));
if (this.byHost.has(hostname)) throw fail(`${hostname} is already in use`, "conflict");
const row = await Domain.create({ hostname, tunnelName, accountId });
this.byHost.set(hostname, tunnelName);
logger.info(`Domain ${hostname} added for ${tunnelName}`);
this.check(hostname).catch(err => logger.warn(`Domain check for ${hostname} failed: ${err.message}`));
return this.describe(row);
}
async remove(hostname) {
await Domain.destroy({ where: { hostname } });
this.byHost.delete(hostname);
await this.certificates.forget(hostname);
logger.info(`Domain ${hostname} removed`);
}
async removeForTunnel(tunnelName) {
for (const hostname of this.hostsFor(tunnelName)) await this.remove(hostname);
}
async recheck() {
const rows = await Domain.findAll({ where: { state: UNSETTLED }, attributes: ["hostname"] });
for (const row of rows) await this.check(row.hostname).catch(err => logger.warn(`Domain check for ${row.hostname} failed: ${err.message}`));
}
async pointsHere(hostname) {
const base = this.config.baseDomain;
const cnames = await dns.resolveCname(hostname).catch(() => []);
if (cnames.some(target => normalize(target) === base)) return true;
const addresses = async name => [
...await dns.resolve4(name).catch(() => []),
...await dns.resolve6(name).catch(() => []),
];
const expected = new Set(await addresses(base));
if (!expected.size) return false;
return (await addresses(hostname)).some(address => expected.has(address));
}
check(hostname) {
if (!this.byHost.has(hostname)) return Promise.resolve();
if (!this.checking.has(hostname)) {
this.checking.set(hostname, this.verify(hostname).finally(() => this.checking.delete(hostname)));
}
return this.checking.get(hostname);
}
async verify(hostname) {
const update = (state, lastError = null) => Domain.update({ state, lastError, checkedAt: new Date() }, { where: { hostname } });
try {
if (!await this.pointsHere(hostname)) return await update("pending", `${hostname} does not point at ${this.config.baseDomain} yet`);
if (!this.config.managesTls || !this.certificates.dueFor(hostname)) return await update("active");
await update("issuing");
await this.certificates.issueFor(hostname);
await update("active");
} catch (err) {
await update("error", err.message);
}
}
}
module.exports = { DomainManager };
+21
View File
@@ -0,0 +1,21 @@
const TYPES = { OPEN: 0x01, DATA: 0x02, CLOSE: 0x03, WINDOW_UPDATE: 0x04, DATAGRAM: 0x05, RESET: 0x06 };
const HEADER_SIZE = 5;
const WINDOW_SIZE = 1024 * 1024;
const CHUNK_SIZE = 64 * 1024;
const MAX_DATAGRAM = 65507;
const encode = (type, streamId, payload) => {
const body = payload ? (Buffer.isBuffer(payload) ? payload : Buffer.from(payload)) : Buffer.alloc(0);
const frame = Buffer.allocUnsafe(HEADER_SIZE + body.length);
frame[0] = type;
frame.writeUInt32BE(streamId >>> 0, 1);
body.copy(frame, HEADER_SIZE);
return frame;
};
const decode = buffer => {
if (!Buffer.isBuffer(buffer) || buffer.length < HEADER_SIZE) return null;
return { type: buffer[0], streamId: buffer.readUInt32BE(1), payload: buffer.subarray(HEADER_SIZE) };
};
module.exports = { TYPES, WINDOW_SIZE, CHUNK_SIZE, MAX_DATAGRAM, encode, decode };
+63
View File
@@ -0,0 +1,63 @@
const packageJson = require("../../package.json");
const pairs = list => list.map(([name, value]) => ({ name, value }));
const header = (list, wanted) => list.find(([name]) => name.toLowerCase() === wanted)?.[1] ?? "";
const text = body => {
if (!body) return undefined;
const bytes = Buffer.from(body, "base64");
const decoded = bytes.toString("utf8");
return Buffer.from(decoded, "utf8").equals(bytes) ? { text: decoded } : { text: body, encoding: "base64" };
};
const message = frame => ({
type: frame.direction === "in" ? "send" : "receive",
time: frame.time / 1000,
opcode: frame.opcode,
data: frame.payload ? Buffer.from(frame.payload, "base64").toString(frame.opcode === 1 ? "utf8" : "base64") : "",
});
const entry = (row, scheme, frames) => {
const url = new URL(row.path, `${scheme}://${row.host}`);
return {
startedDateTime: new Date(row.time).toISOString(),
time: row.duration,
request: {
method: row.kind === "ws" ? "GET" : row.method,
url: url.toString(),
httpVersion: "HTTP/1.1",
cookies: [],
headers: pairs(row.request.headers),
queryString: pairs([...url.searchParams]),
headersSize: -1,
bodySize: row.request.bytes,
...(row.request.body && { postData: { mimeType: header(row.request.headers, "content-type"), ...text(row.request.body) } }),
},
response: {
status: row.status ?? 0,
statusText: "",
httpVersion: "HTTP/1.1",
cookies: [],
headers: pairs(row.response.headers),
content: { size: row.response.bytes, mimeType: header(row.response.headers, "content-type"), ...text(row.response.body) },
redirectURL: header(row.response.headers, "location"),
headersSize: -1,
bodySize: row.response.bytes,
},
cache: {},
timings: { send: 0, wait: row.duration, receive: 0 },
...(row.ip && { serverIPAddress: row.ip }),
...(row.kind === "ws" && { _webSocketMessages: (frames.get(row.connection) || []).map(message) }),
};
};
const toHar = (rows, scheme, frames) => ({
log: {
version: "1.2",
creator: { name: "frislit", version: packageJson.version },
entries: rows.map(row => entry(row, scheme, frames)),
},
});
module.exports = { toHar };
+179
View File
@@ -0,0 +1,179 @@
const fs = require("node:fs/promises");
const path = require("node:path");
const zlib = require("node:zlib");
const { Reader } = require("mmdb-lib");
const { dataDir } = require("../utils/paths");
const logger = require("../utils/logger");
const DAY = 24 * 60 * 60 * 1000;
const LISTS = {
tor: "https://check.torproject.org/torbulkexitlist",
datacenter: "https://raw.githubusercontent.com/X4BNet/lists_vpn/main/output/datacenter/ipv4.txt",
vpn: "https://raw.githubusercontent.com/X4BNet/lists_vpn/main/output/vpn/ipv4.txt",
blocklist: "https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/firehol_level1.netset",
};
const DATABASES = { country: "dbip-country-lite", asn: "dbip-asn-lite" };
const PRIVATE = [
["10.0.0.0", 8], ["172.16.0.0", 12], ["192.168.0.0", 16], ["127.0.0.0", 8], ["169.254.0.0", 16], ["100.64.0.0", 10], ["0.0.0.0", 8],
].map(([base, bits]) => [ipv4(base) >>> 0, bits]);
function ipv4(text) {
const parts = text.split(".");
if (parts.length !== 4) return null;
let value = 0;
for (const part of parts) {
const octet = Number(part);
if (!Number.isInteger(octet) || octet < 0 || octet > 255) return null;
value = value * 256 + octet;
}
return value;
}
const normalize = address => {
const text = String(address || "").replace(/%.*$/, "").replace(/^\[|\]$/g, "");
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(text);
return mapped ? mapped[1] : text;
};
const isPrivate = ip => {
const value = ipv4(ip);
if (value !== null) return PRIVATE.some(([base, bits]) => (value >>> (32 - bits)) === (base >>> (32 - bits)));
return /^(::1$|fc|fd|fe80)/i.test(ip);
};
class RangeSet {
constructor(lines) {
this.ranges = [];
for (const line of lines) {
const text = line.trim();
if (!text || text.startsWith("#")) continue;
const [address, prefix = "32"] = text.split("/");
const start = ipv4(address);
const bits = Number(prefix);
if (start === null || !Number.isInteger(bits) || bits < 0 || bits > 32) continue;
const size = 2 ** (32 - bits);
const from = Math.floor(start / size) * size;
this.ranges.push([from, from + size - 1]);
}
this.ranges.sort((a, b) => a[0] - b[0]);
}
has(ip) {
const value = ipv4(ip);
if (value === null) return false;
let low = 0;
let high = this.ranges.length - 1;
while (low <= high) {
const middle = (low + high) >> 1;
const [from, to] = this.ranges[middle];
if (value < from) high = middle - 1;
else if (value > to) low = middle + 1;
else return true;
}
return false;
}
}
const months = () => {
const now = new Date();
const stamp = date => `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}`;
return [stamp(now), stamp(new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 1, 1)))];
};
class Intel {
constructor() {
this.dir = path.join(dataDir(), "intel");
this.readers = {};
this.lists = {};
this.timer = null;
this.updatedAt = {};
}
async load() {
await fs.mkdir(this.dir, { recursive: true });
for (const name of Object.keys(DATABASES)) await this.loadDatabase(name).catch(() => null);
for (const name of Object.keys(LISTS)) await this.loadList(name).catch(() => null);
}
async loadDatabase(name) {
const file = path.join(this.dir, `${name}.mmdb`);
this.readers[name] = new Reader(await fs.readFile(file));
this.updatedAt[name] = (await fs.stat(file)).mtime;
}
async loadList(name) {
const file = path.join(this.dir, `${name}.txt`);
this.lists[name] = new RangeSet((await fs.readFile(file, "utf8")).split("\n"));
this.updatedAt[name] = (await fs.stat(file)).mtime;
}
start() {
if (this.timer) return;
const refresh = () => this.refresh().catch(err => logger.warn(`IP intelligence update failed: ${err.message}`));
this.timer = setInterval(refresh, DAY);
this.timer.unref();
refresh();
}
stop() {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
stale(name, maxAge) {
return !this.updatedAt[name] || Date.now() - this.updatedAt[name].getTime() > maxAge;
}
async fetch(url) {
const response = await globalThis.fetch(url, { headers: { "user-agent": "frislit" } });
if (!response.ok) throw new Error(`${url} answered ${response.status}`);
return Buffer.from(await response.arrayBuffer());
}
async refresh() {
for (const [name, base] of Object.entries(DATABASES)) {
if (!this.stale(name, 7 * DAY)) continue;
for (const month of months()) {
try {
const body = await this.fetch(`https://download.db-ip.com/free/${base}-${month}.mmdb.gz`);
await fs.writeFile(path.join(this.dir, `${name}.mmdb`), zlib.gunzipSync(body));
await this.loadDatabase(name);
logger.info(`IP intelligence: ${base} ${month} loaded`);
break;
} catch (err) {
logger.debug(`IP intelligence: ${base} ${month} not available: ${err.message}`);
}
}
}
for (const [name, url] of Object.entries(LISTS)) {
if (!this.stale(name, DAY)) continue;
const body = await this.fetch(url);
await fs.writeFile(path.join(this.dir, `${name}.txt`), body);
await this.loadList(name);
}
}
lookup(address) {
const ip = normalize(address);
if (isPrivate(ip)) return { ip, private: true };
const valid = /^[0-9a-f.:]+$/i.test(ip);
const country = valid ? this.readers.country?.get(ip) : null;
const asn = valid ? this.readers.asn?.get(ip) : null;
return {
ip,
private: false,
country: country?.country?.iso_code || null,
continent: country?.continent?.code || null,
eu: !!country?.country?.is_in_european_union,
asn: asn?.autonomous_system_number || null,
org: asn?.autonomous_system_organization || null,
tor: !!this.lists.tor?.has(ip),
vpn: !!this.lists.vpn?.has(ip),
datacenter: !!this.lists.datacenter?.has(ip),
blocklisted: !!this.lists.blocklist?.has(ip),
};
}
}
module.exports = { Intel };
+49
View File
@@ -0,0 +1,49 @@
const Invite = require("../models/Invite");
const Account = require("../models/Account");
const { hashToken, randomToken } = require("../utils/ids");
const logger = require("../utils/logger");
const describe = (invite, owner) => ({
id: invite.id,
label: invite.label,
owner: owner || null,
createdAt: invite.createdAt,
lastUsedAt: invite.lastUsedAt,
uses: invite.uses,
});
const linkFor = (publicUrl, token) => `${publicUrl}/@frislit/invite/${token}`;
const create = async (accountId, label) => {
const name = String(label || "").trim();
if (!name) return { code: 400, message: "Give the invite a label" };
const token = randomToken(48);
const invite = await Invite.create({ accountId, label: name, tokenHash: hashToken(token) });
logger.info(`Invite "${name}" created`, { id: invite.id });
return { invite: describe(invite), token };
};
const list = async accountId => {
const where = accountId === undefined ? {} : { accountId };
const invites = await Invite.findAll({ where, order: [["createdAt", "DESC"]] });
if (accountId !== undefined) return invites.map(invite => describe(invite));
const names = new Map((await Account.findAll()).map(account => [account.id, account.username]));
return invites.map(invite => describe(invite, names.get(invite.accountId)));
};
const revoke = async (id, accountId) => {
const where = accountId === undefined ? { id } : { id, accountId };
const invite = await Invite.findOne({ where });
if (!invite) return { code: 404, message: "Invite not found" };
await Invite.destroy({ where: { id: invite.id } });
logger.info(`Invite "${invite.label}" revoked`, { id });
return { message: `${invite.label} revoked` };
};
const verify = token => (typeof token === "string" && token ? Invite.findOne({ where: { tokenHash: hashToken(token) } }) : null);
const used = async invite => {
await Invite.update({ lastUsedAt: new Date(), uses: invite.uses + 1 }, { where: { id: invite.id } });
};
module.exports = { create, list, revoke, verify, used, linkFor };
+160
View File
@@ -0,0 +1,160 @@
const client = require("openid-client");
const crypto = require("node:crypto");
const OidcProvider = require("../models/OidcProvider");
const accounts = require("./accounts");
const logger = require("../utils/logger");
const STATE_TTL = 10 * 60 * 1000;
const states = new Map();
const remember = (state, data) => {
const now = Date.now();
for (const [key, entry] of states) if (now - entry.at > STATE_TTL) states.delete(key);
states.set(state, { at: now, ...data });
};
const take = state => {
const entry = states.get(state);
states.delete(state);
if (!entry || Date.now() - entry.at > STATE_TTL) return null;
return entry;
};
const redirectUri = config => `${config.publicUrl}/@frislit/api/auth/oidc/callback`;
const describe = provider => ({
id: provider.id,
name: provider.name,
issuer: provider.issuer,
clientId: provider.clientId,
hasSecret: !!provider.clientSecret,
scope: provider.scope,
usernameClaim: provider.usernameClaim,
createAccounts: !!provider.createAccounts,
enabled: !!provider.enabled,
});
const list = async () => (await OidcProvider.findAll({ order: [["id", "ASC"]] })).map(describe);
const enabled = async () =>
(await OidcProvider.findAll({ where: { enabled: true }, order: [["id", "ASC"]] }))
.map(provider => ({ id: provider.id, name: provider.name }));
const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
const discover = provider => {
const issuer = new URL(provider.issuer);
const options = issuer.protocol === "http:" && LOOPBACK.has(issuer.hostname)
? { execute: [client.allowInsecureRequests] }
: undefined;
return client.discovery(issuer, provider.clientId, provider.clientSecret || undefined, undefined, options);
};
const save = async (id, values) => {
if (values.issuer !== undefined) {
let issuer;
try {
issuer = new URL(values.issuer);
} catch {
return { code: 400, message: "The issuer must be a URL" };
}
if (issuer.protocol === "http:" && !LOOPBACK.has(issuer.hostname)) {
return { code: 400, message: "The issuer must be https, except on localhost" };
}
}
if (id) {
const provider = await OidcProvider.findByPk(id);
if (!provider) return { code: 404, message: "That provider does not exist" };
await OidcProvider.update(values, { where: { id } });
return { provider: describe(await OidcProvider.findByPk(id)) };
}
for (const key of ["name", "issuer", "clientId"]) {
if (!String(values[key] || "").trim()) return { code: 400, message: `${key} is required` };
}
const created = await OidcProvider.create(values);
return { provider: describe(created) };
};
const remove = async id => {
const provider = await OidcProvider.findByPk(id);
if (!provider) return { code: 404, message: "That provider does not exist" };
await OidcProvider.destroy({ where: { id } });
return { message: `${provider.name} removed` };
};
const begin = async (id, config, next) => {
const provider = await OidcProvider.findOne({ where: { id, enabled: true } });
if (!provider) return { code: 404, message: "That provider is not available" };
try {
const configuration = await discover(provider);
const state = client.randomState();
const nonce = client.randomNonce();
const codeVerifier = client.randomPKCECodeVerifier();
const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier);
remember(state, { nonce, codeVerifier, providerId: provider.id, next });
const url = client.buildAuthorizationUrl(configuration, {
redirect_uri: redirectUri(config),
scope: provider.scope,
state, nonce,
code_challenge: codeChallenge,
code_challenge_method: "S256",
});
return { url: url.href };
} catch (err) {
logger.error(`Could not reach the OIDC provider ${provider.name}: ${err.message}`);
return { code: 502, message: `Could not reach ${provider.name}: ${err.message}` };
}
};
const complete = async (query, config) => {
const entry = take(query.state);
if (!entry) return { code: 400, message: "That sign-in has expired, start again" };
const provider = await OidcProvider.findByPk(entry.providerId);
if (!provider) return { code: 404, message: "That provider is gone" };
try {
const configuration = await discover(provider);
const url = new URL(`${redirectUri(config)}?${new URLSearchParams(query).toString()}`);
const tokens = await client.authorizationCodeGrant(configuration, url, {
expectedState: query.state,
expectedNonce: entry.nonce,
pkceCodeVerifier: entry.codeVerifier,
});
let claims = tokens.claims();
try {
claims = await client.fetchUserInfo(configuration, tokens.access_token, claims.sub);
} catch (err) {
logger.debug(`userinfo not available, using the id token: ${err.message}`);
}
const raw = claims[provider.usernameClaim] || claims.preferred_username || claims.email || claims.sub;
const username = String(raw || "").split("@")[0].replace(/[^a-zA-Z0-9._-]/g, "").slice(0, 32);
if (username.length < 3) return { code: 400, message: `"${raw}" is not a usable username` };
let account = await accounts.byUsername(username);
if (!account) {
if (!provider.createAccounts) return { code: 403, message: `${username} has no account here` };
const created = await accounts.create({
username,
password: crypto.randomBytes(24).toString("base64url"),
role: "user",
});
if (created.code) return created;
account = await accounts.byUsername(username);
logger.info(`Created ${username} from ${provider.name}`);
}
logger.info(`${account.username} signed in through ${provider.name}`);
return { account, next: entry.next };
} catch (err) {
logger.error(`OIDC sign-in failed: ${err.message}`);
return { code: 502, message: err.message };
}
};
module.exports = { list, enabled, save, remove, begin, complete, describe, redirectUri };
+166
View File
@@ -0,0 +1,166 @@
const {
generateRegistrationOptions, verifyRegistrationResponse,
generateAuthenticationOptions, verifyAuthenticationResponse,
} = require("@simplewebauthn/server");
const Passkey = require("../models/Passkey");
const Account = require("../models/Account");
const logger = require("../utils/logger");
const RP_NAME = "frislit";
const CHALLENGE_TTL = 5 * 60 * 1000;
const challenges = new Map();
const remember = (challenge, data) => {
const now = Date.now();
for (const [key, entry] of challenges) if (now - entry.at > CHALLENGE_TTL) challenges.delete(key);
challenges.set(challenge, { at: now, ...data });
};
const take = challenge => {
const entry = challenges.get(challenge);
challenges.delete(challenge);
if (!entry || Date.now() - entry.at > CHALLENGE_TTL) return null;
return entry;
};
const challengeOf = response =>
JSON.parse(Buffer.from(response.response.clientDataJSON, "base64url").toString()).challenge;
const transportsOf = passkey => (passkey.transports ? JSON.parse(passkey.transports) : undefined);
const describe = passkey => ({
id: passkey.id,
name: passkey.name,
createdAt: passkey.createdAt,
lastUsedAt: passkey.lastUsedAt,
});
const relyingParty = origin => ({ origin, rpID: new URL(origin).hostname });
const startRegistration = async (account, origin) => {
const { rpID } = relyingParty(origin);
const existing = await Passkey.findAll({ where: { accountId: account.id } });
const options = await generateRegistrationOptions({
rpName: RP_NAME,
rpID,
userID: Buffer.from(String(account.id)),
userName: account.username,
userDisplayName: account.username,
attestationType: "none",
excludeCredentials: existing.map(passkey => ({
id: passkey.credentialId, type: "public-key", transports: transportsOf(passkey),
})),
authenticatorSelection: { residentKey: "preferred", userVerification: "preferred" },
});
remember(options.challenge, { kind: "registration", accountId: account.id });
return options;
};
const finishRegistration = async (account, response, name, origin) => {
const entry = take(challengeOf(response));
if (!entry || entry.kind !== "registration" || entry.accountId !== account.id) {
return { code: 400, message: "That registration has expired, start again" };
}
try {
const { origin: expectedOrigin, rpID } = relyingParty(origin);
const verification = await verifyRegistrationResponse({
response,
expectedChallenge: challengeOf(response),
expectedOrigin,
expectedRPID: rpID,
});
if (!verification.verified || !verification.registrationInfo) {
return { code: 400, message: "The passkey could not be verified" };
}
const { credential, credentialDeviceType, credentialBackedUp } = verification.registrationInfo;
await Passkey.create({
accountId: account.id,
name: String(name || "").trim().slice(0, 40) || "Passkey",
credentialId: credential.id,
publicKey: Buffer.from(credential.publicKey).toString("base64url"),
counter: credential.counter,
deviceType: credentialDeviceType,
backedUp: credentialBackedUp,
transports: response.response.transports ? JSON.stringify(response.response.transports) : null,
});
logger.info(`${account.username} added a passkey`);
return { message: "Passkey added" };
} catch (err) {
logger.warn(`Passkey registration failed: ${err.message}`);
return { code: 400, message: err.message };
}
};
const startAuthentication = async (username, origin) => {
const { rpID } = relyingParty(origin);
let allowCredentials;
if (username) {
const account = await Account.findOne({ where: { username: String(username) } });
const passkeys = account ? await Passkey.findAll({ where: { accountId: account.id } }) : [];
if (passkeys.length) {
allowCredentials = passkeys.map(passkey => ({
id: passkey.credentialId, type: "public-key", transports: transportsOf(passkey),
}));
}
}
const options = await generateAuthenticationOptions({ rpID, allowCredentials, userVerification: "preferred" });
remember(options.challenge, { kind: "authentication" });
return options;
};
const finishAuthentication = async (response, origin) => {
const entry = take(challengeOf(response));
if (!entry || entry.kind !== "authentication") return { code: 400, message: "That sign-in has expired, try again" };
const passkey = await Passkey.findOne({ where: { credentialId: response.id } });
if (!passkey) return { code: 401, message: "This passkey is not registered here" };
const account = await Account.findByPk(passkey.accountId);
if (!account) return { code: 401, message: "The account behind this passkey is gone" };
try {
const { origin: expectedOrigin, rpID } = relyingParty(origin);
const verification = await verifyAuthenticationResponse({
response,
expectedChallenge: challengeOf(response),
expectedOrigin,
expectedRPID: rpID,
credential: {
id: passkey.credentialId,
publicKey: new Uint8Array(Buffer.from(passkey.publicKey, "base64url")),
counter: passkey.counter,
transports: transportsOf(passkey),
},
});
if (!verification.verified) return { code: 401, message: "The passkey could not be verified" };
await Passkey.update(
{ counter: verification.authenticationInfo.newCounter, lastUsedAt: new Date() },
{ where: { id: passkey.id } },
);
return { account };
} catch (err) {
logger.warn(`Passkey sign-in failed: ${err.message}`);
return { code: 401, message: err.message };
}
};
const list = async accountId =>
(await Passkey.findAll({ where: { accountId }, order: [["createdAt", "DESC"]] })).map(describe);
const remove = async (accountId, id) => {
const passkey = await Passkey.findOne({ where: { id, accountId } });
if (!passkey) return { code: 404, message: "Passkey not found" };
await Passkey.destroy({ where: { id: passkey.id } });
return { message: `${passkey.name} removed` };
};
module.exports = { startRegistration, finishRegistration, startAuthentication, finishAuthentication, list, remove };
+47
View File
@@ -0,0 +1,47 @@
const TunnelModel = require("../models/Tunnel");
const Account = require("../models/Account");
const { emptyPolicy } = require("./access");
const toPolicy = row => ({ ...emptyPolicy(), ...JSON.parse(row.rules), auth: row.auth, passwordHash: row.passwordHash || null });
const columns = policy => ({
rules: JSON.stringify({ allow: policy.allow, block: policy.block, accounts: policy.accounts || [] }),
auth: policy.auth,
passwordHash: policy.passwordHash || null,
});
const toDefinition = row => ({
name: row.name,
accountId: row.accountId,
mode: row.mode || null,
policy: toPolicy(row),
createdAt: row.createdAt,
});
const load = async name => {
const row = await TunnelModel.findOne({ where: { name } });
return row ? toDefinition(row) : null;
};
const list = async accountId => {
const rows = await TunnelModel.findAll({ where: accountId ? { accountId } : {}, order: [["name", "ASC"]] });
const accounts = await Account.findAll({ where: { id: [...new Set(rows.map(row => row.accountId))] }, attributes: ["id", "username"] });
const names = new Map(accounts.map(account => [account.id, account.username]));
return rows.map(row => ({ ...toDefinition(row), owner: names.get(row.accountId) || null }));
};
const create = async (name, accountId, policy = emptyPolicy()) => {
if (await TunnelModel.findOne({ where: { name } })) {
throw Object.assign(new Error(`"${name}" is already a persistent tunnel`), { code: "name_taken" });
}
await TunnelModel.create({ name, accountId, ...columns(policy) });
return load(name);
};
const savePolicy = (name, policy) => TunnelModel.update(columns(policy), { where: { name } });
const saveMode = (name, mode) => TunnelModel.update({ mode }, { where: { name } });
const remove = name => TunnelModel.destroy({ where: { name } });
module.exports = { load, list, create, savePolicy, saveMode, remove };
+31
View File
@@ -0,0 +1,31 @@
const net = require("node:net");
const tls = require("node:tls");
const proxyProtocol = require("./proxy-protocol");
const proxyFront = (secureOptions, onConnection) => net.createServer(socket => {
let buffer = Buffer.alloc(0);
const hand = (rest, ip) => {
if (rest.length) socket.unshift(rest);
const tunnel = new tls.TLSSocket(socket, { isServer: true, SNICallback: secureOptions.SNICallback });
if (ip) tunnel.frislitIp = ip;
onConnection(tunnel);
};
const read = () => {
let chunk;
while ((chunk = socket.read()) !== null) buffer = Buffer.concat([buffer, chunk]);
if (!proxyProtocol.isPrefix(buffer)) return hand(buffer, null);
const parsed = proxyProtocol.parse(buffer);
if (!parsed) {
if (buffer.length > 4096) return socket.destroy();
return socket.once("readable", read);
}
hand(buffer.subarray(parsed.length), parsed.ip);
};
socket.pause();
socket.once("readable", read);
});
module.exports = { proxyFront };
+48
View File
@@ -0,0 +1,48 @@
const test = require("node:test");
const assert = require("node:assert");
const net = require("node:net");
const { SIGNATURE } = require("./proxy-protocol");
const { proxyFront } = require("./proxy-front");
const header = ip => {
const address = Buffer.from(ip.split(".").map(Number));
const body = Buffer.concat([address, address, Buffer.alloc(4)]);
const buffer = Buffer.alloc(16 + body.length);
SIGNATURE.copy(buffer, 0);
buffer[12] = 0x21;
buffer[13] = 0x11;
buffer.writeUInt16BE(body.length, 14);
body.copy(buffer, 16);
return buffer;
};
const withFront = async (payload, assertOnTunnel) => new Promise((resolve, reject) => {
const front = proxyFront({}, tunnel => {
try {
assertOnTunnel(tunnel);
tunnel.destroy();
front.close(() => resolve());
} catch (error) {
front.close(() => reject(error));
}
});
front.listen(0, "127.0.0.1", () => {
const socket = net.connect(front.address().port, "127.0.0.1");
socket.on("connect", () => socket.write(payload));
socket.on("error", () => {});
});
setTimeout(() => reject(new Error("the front did not hand over a connection")), 3000).unref();
});
test("hands the source address of a proxied connection to the TLS socket", async () => {
await withFront(header("203.0.113.7"), tunnel => {
assert.strictEqual(tunnel.frislitIp, "203.0.113.7");
});
});
test("passes a direct connection through untouched", async () => {
await withFront(Buffer.from([0x16, 0x03, 0x01, 0x00, 0x2a]), tunnel => {
assert.strictEqual(tunnel.frislitIp, undefined);
});
});
+30
View File
@@ -0,0 +1,30 @@
const SIGNATURE = Buffer.from([0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x0d, 0x0a, 0x51, 0x55, 0x49, 0x54, 0x0a]);
const isPrefix = buffer => buffer.length < SIGNATURE.length
? SIGNATURE.subarray(0, buffer.length).equals(buffer)
: buffer.subarray(0, SIGNATURE.length).equals(SIGNATURE);
const ipv6 = buffer => {
const parts = [];
for (let i = 0; i < 8; i++) parts.push(buffer.readUInt16BE(i * 2).toString(16));
return parts.join(":");
};
const parse = buffer => {
if (buffer.length < 16) return null;
if ((buffer[12] >> 4) !== 2) return null;
const length = buffer.readUInt16BE(14);
if (buffer.length < 16 + length) return null;
const command = buffer[12] & 0x0f;
const family = buffer[13] >> 4;
const total = 16 + length;
if (command !== 1) return { ip: null, length: total };
if (family === 1) return { ip: `${buffer[16]}.${buffer[17]}.${buffer[18]}.${buffer[19]}`, length: total };
if (family === 2) return { ip: ipv6(buffer.subarray(16, 32)), length: total };
return { ip: null, length: total };
};
module.exports = { SIGNATURE, isPrefix, parse };
+43
View File
@@ -0,0 +1,43 @@
const test = require("node:test");
const assert = require("node:assert");
const { SIGNATURE, isPrefix, parse } = require("./proxy-protocol");
const header = (family, source, destination, command = 0x21) => {
const body = Buffer.concat([source, destination, Buffer.alloc(4)]);
const buffer = Buffer.alloc(16 + body.length);
SIGNATURE.copy(buffer, 0);
buffer[12] = command;
buffer[13] = family;
buffer.writeUInt16BE(body.length, 14);
body.copy(buffer, 16);
return buffer;
};
test("parses an IPv4 source address", () => {
const parsed = parse(header(0x11, Buffer.from([203, 0, 113, 7]), Buffer.from([10, 0, 0, 1])));
assert.strictEqual(parsed.ip, "203.0.113.7");
assert.strictEqual(parsed.length, 16 + 12);
});
test("parses an IPv6 source address", () => {
const source = Buffer.from([0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
const parsed = parse(header(0x21, source, Buffer.alloc(16)));
assert.strictEqual(parsed.ip, "2001:db8:0:0:0:0:0:1");
});
test("returns null until the header is complete", () => {
const buffer = header(0x11, Buffer.from([1, 2, 3, 4]), Buffer.from([5, 6, 7, 8]));
assert.strictEqual(parse(buffer.subarray(0, 10)), null);
assert.strictEqual(parse(buffer.subarray(0, 20)), null);
});
test("has no address for a LOCAL command", () => {
const parsed = parse(header(0x00, Buffer.alloc(0), Buffer.alloc(0), 0x20));
assert.strictEqual(parsed.ip, null);
});
test("tells the signature apart from a TLS handshake", () => {
assert.strictEqual(isPrefix(SIGNATURE.subarray(0, 5)), true);
assert.strictEqual(isPrefix(SIGNATURE), true);
assert.strictEqual(isPrefix(Buffer.from([0x16, 0x03, 0x01, 0x00])), false);
});
+466
View File
@@ -0,0 +1,466 @@
const http = require("node:http");
const zlib = require("node:zlib");
const { Transform } = require("node:stream");
const { randomToken } = require("../utils/ids");
const { FrameParser, encodeFrame } = require("./websocket");
const { sendAppState } = require("../utils/pages");
const { Tap, headerList } = require("./capture");
const logger = require("../utils/logger");
const REPLAY_IP = "replay";
const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade"]);
const QUERY_PARAM = "frislit-tunnel";
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1", "0.0.0.0"]);
const requestInfo = (req, config) => {
const trust = config.trustProxy;
const forwardedHost = trust && req.headers["x-forwarded-host"] ? String(req.headers["x-forwarded-host"]).split(",")[0].trim() : null;
const hostHeader = forwardedHost || req.headers.host || "";
const hostname = hostHeader.replace(/:\d+$/, "").toLowerCase();
const forwardedProto = trust && req.headers["x-forwarded-proto"] ? String(req.headers["x-forwarded-proto"]).split(",")[0].trim().toLowerCase() : null;
const proto = forwardedProto || (req.socket.encrypted ? "https" : "http");
const forwardedFor = trust && req.headers["x-forwarded-for"] ? String(req.headers["x-forwarded-for"]).split(",")[0].trim() : null;
const clientIp = req.socket?.frislitIp || forwardedFor || req.socket.remoteAddress || "";
return { host: hostHeader, hostname, proto, secure: proto === "https", clientIp };
};
const classifyHost = (hostname, baseDomain) => {
if (hostname === baseDomain) return { kind: "base" };
if (hostname.endsWith(`.${baseDomain}`)) {
const label = hostname.slice(0, -(baseDomain.length + 1));
if (label && !label.includes(".")) return { kind: "subdomain", id: label };
}
return { kind: "unknown" };
};
const stripQueryParam = url => {
const idx = url.indexOf("?");
if (idx === -1) return url;
const path = url.slice(0, idx);
const params = new URLSearchParams(url.slice(idx + 1));
if (!params.has(QUERY_PARAM)) return url;
params.delete(QUERY_PARAM);
const rest = params.toString();
return rest ? `${path}?${rest}` : path;
};
const hostHeader = target => (target.port === 80 || target.port === 443 ? target.host : target.authority);
const buildUpstreamHeaders = (req, info, tunnel, { pathMode }) => {
const headers = {};
for (const [name, value] of Object.entries(req.headers)) {
if (HOP_BY_HOP.has(name) || name === "host") continue;
headers[name] = value;
}
headers.host = tunnel.keepHost ? info.host : hostHeader(tunnel.target);
headers["x-forwarded-host"] = info.host;
headers["x-forwarded-proto"] = info.proto;
headers["x-forwarded-for"] = req.headers["x-forwarded-for"] && !headers["x-forwarded-for"] ? req.headers["x-forwarded-for"] : (info.clientIp || "");
if (headers["x-forwarded-for"] === "") delete headers["x-forwarded-for"];
return headers;
};
const appendCookie = (headers, cookie) => {
const name = Object.keys(headers).find(key => key.toLowerCase() === "set-cookie") || "set-cookie";
const existing = headers[name];
headers[name] = existing ? [...(Array.isArray(existing) ? existing : [existing]), cookie] : [cookie];
};
const sameAuthority = (a, b) => {
if (a === b) return true;
const pa = a.match(/^(.*):(\d+)$/), pb = b.match(/^(.*):(\d+)$/);
if (!pa || !pb || pa[2] !== pb[2]) return false;
return LOCAL_HOSTS.has(pa[1].toLowerCase()) && LOCAL_HOSTS.has(pb[1].toLowerCase());
};
const authorityOf = url => (url.port ? url.host : `${url.hostname}:${url.protocol === "https:" ? 443 : 80}`);
const rewriteLocation = (location, tunnel, info, { pathMode }) => {
let url;
try {
url = new URL(location, `http://${tunnel.target.authority}/`);
} catch {
return location;
}
if (!/^https?:$/.test(url.protocol)) return location;
if (!sameAuthority(authorityOf(url), tunnel.target.authority)) return location;
const rest = `${url.pathname}${url.search}${url.hash}`;
return pathMode ? rest : `${info.proto}://${info.host}${rest}`;
};
const rewriteSetCookie = value => {
const parts = String(value).split(";").map(p => p.trim()).filter(Boolean);
if (!parts.length) return value;
const out = [parts[0]];
for (const attr of parts.slice(1)) {
const [name, ...rest] = attr.split("=");
const key = name.trim().toLowerCase();
if (key === "domain") continue;
if (key === "expires") {
const date = Date.parse(rest.join("="));
if (!Number.isNaN(date) && date >= Date.now()) continue;
}
out.push(attr);
}
return out.join("; ");
};
const buildDownstreamHeaders = (upstream, tunnel, info, { pathMode }) => {
const headers = {};
for (let i = 0; i < upstream.rawHeaders.length; i += 2) {
const name = upstream.rawHeaders[i];
const key = name.toLowerCase();
let value = upstream.rawHeaders[i + 1];
if (HOP_BY_HOP.has(key)) continue;
if (key === "location") value = rewriteLocation(value, tunnel, info, { pathMode });
if (key === "set-cookie" && pathMode) value = rewriteSetCookie(value);
if (headers[name] === undefined) headers[name] = value;
else if (Array.isArray(headers[name])) headers[name].push(value);
else headers[name] = [headers[name], value];
}
return headers;
};
class InjectTransform extends Transform {
constructor(snippet) {
super();
this.snippet = Buffer.from(snippet);
this.carry = Buffer.alloc(0);
this.done = false;
}
_transform(chunk, _enc, cb) {
if (this.done) return cb(null, chunk);
const buf = this.carry.length ? Buffer.concat([this.carry, chunk]) : chunk;
const lower = buf.toString("latin1").toLowerCase();
const idx = lower.indexOf("</head>");
if (idx !== -1) {
this.done = true;
this.carry = Buffer.alloc(0);
return cb(null, Buffer.concat([buf.subarray(0, idx), this.snippet, buf.subarray(idx)]));
}
const keep = Math.min(6, buf.length);
this.carry = Buffer.from(buf.subarray(buf.length - keep));
cb(null, buf.subarray(0, buf.length - keep));
}
_flush(cb) {
if (this.done) return cb(null, this.carry);
cb(null, Buffer.concat([this.carry, this.snippet]));
}
}
const decoderFor = encoding => {
switch ((encoding || "").trim().toLowerCase()) {
case "gzip": case "x-gzip": return zlib.createGunzip();
case "deflate": return zlib.createInflate();
case "br": return zlib.createBrotliDecompress();
case "zstd": return typeof zlib.createZstdDecompress === "function" ? zlib.createZstdDecompress() : null;
case "": case "identity": return "identity";
default: return null;
}
};
const HOLD_LIMIT = 8 * 1024 * 1024;
const collect = (source, limit) => new Promise((resolve, reject) => {
const chunks = [];
let total = 0;
const onData = chunk => {
chunks.push(chunk);
total += chunk.length;
if (total > limit) {
source.off("data", onData).off("end", onEnd).pause();
resolve({ overflow: chunks });
}
};
const onEnd = () => resolve({ body: Buffer.concat(chunks) });
source.on("data", onData).once("end", onEnd).once("error", reject);
});
const decodeBody = (body, encoding) => {
try {
switch ((encoding || "").trim().toLowerCase()) {
case "gzip": case "x-gzip": return zlib.gunzipSync(body);
case "deflate": return zlib.inflateSync(body);
case "br": return zlib.brotliDecompressSync(body);
case "zstd": return zlib.zstdDecompressSync(body);
case "": case "identity": return body;
default: return null;
}
} catch {
return null;
}
};
const injectInto = (body, snippet) => {
const index = body.toString("latin1").toLowerCase().indexOf("</head>");
const marker = Buffer.from(snippet);
return index === -1 ? Buffer.concat([body, marker]) : Buffer.concat([body.subarray(0, index), marker, body.subarray(index)]);
};
const captureOf = body => ({ body: body.length ? body : null, bytes: body.length, truncated: false });
const headersFromPairs = pairs => {
const headers = {};
for (const [name, value] of pairs) {
const key = name.toLowerCase();
headers[key] = headers[key] === undefined ? value : [].concat(headers[key], value);
}
return headers;
};
const observe = (shape, info, onRequest) => {
let done = false;
return (status, captured) => {
if (done) return;
done = true;
onRequest({
time: shape.time,
duration: Date.now() - shape.time,
kind: "http",
method: shape.method,
path: shape.path,
status,
ip: info.clientIp,
host: info.host,
request: { headers: shape.headers, ...captured.request },
response: captured.response,
});
};
};
const proxyRequest = async (req, res, tunnel, info, { pathMode, inject: snippet, onRequest, setCookie, breakpoints }) => {
const shape = { time: Date.now(), method: req.method, path: stripQueryParam(req.url), headers: headerList(req.headers) };
let incoming = req.headers;
let body = null;
if (breakpoints.matches(tunnel.id, shape.method, shape.path, "request")) {
const collected = await collect(req, HOLD_LIMIT).catch(() => null);
if (!collected) return res.destroy();
if (collected.overflow) return res.writeHead(413, { "Content-Type": "text/plain" }).end("Request too large to hold");
body = collected.body;
const hold = breakpoints.hold(tunnel.id, { ...shape, phase: "request", ip: info.clientIp, host: info.host, request: { headers: shape.headers, ...captureOf(body) } });
res.on("close", () => breakpoints.settle(hold.id, { action: "cancel" }));
const decision = await hold.decision;
if (decision.action === "cancel") return;
if (decision.action === "drop") {
observe(shape, info, onRequest)(503, { request: captureOf(body), response: {} });
res.writeHead(503, { "Content-Type": "text/plain" }).end("Dropped at a breakpoint");
return;
}
shape.method = decision.method;
shape.path = decision.path;
shape.headers = decision.headers;
incoming = headersFromPairs(decision.headers);
body = decision.body;
}
const stream = tunnel.session.open({ protocol: "tcp", remote: info.clientIp });
const headers = buildUpstreamHeaders({ headers: incoming }, info, tunnel, { pathMode });
const wantsHtml = pathMode && (/text\/html/i.test(incoming.accept || "") || incoming["sec-fetch-dest"] === "document");
if (wantsHtml) delete headers["accept-encoding"];
if (body) {
if (body.length) headers["content-length"] = body.length; else delete headers["content-length"];
}
const upstream = http.request({
createConnection: () => stream,
method: shape.method,
path: shape.path,
headers,
setHost: false,
});
const finish = observe(shape, info, onRequest);
const requestTap = body ? null : new Tap();
let responseTap = null;
const captured = () => ({
request: requestTap ? requestTap.result() : captureOf(body),
response: responseTap ? responseTap.result() : {},
});
let responded = false;
const fail = (status, message) => {
if (responded || res.headersSent) return res.destroy();
responded = true;
logger.debug(`proxy ${tunnel.id}: ${message}`);
finish(status, captured());
if (status === 502) sendAppState(req, res, 502, { kind: "offline", id: tunnel.id });
else res.writeHead(status, { "Content-Type": "text/plain" }).end(message);
};
upstream.on("error", err => fail(502, `upstream error: ${err.message}`));
stream.on("error", () => {});
req.on("error", () => upstream.destroy());
res.on("close", () => { if (!res.writableFinished) upstream.destroy(); });
const isHtml = headers => /^text\/html/i.test(String(headers["content-type"] || ""));
upstream.on("response", async upstreamRes => {
responded = true;
responseTap = new Tap();
const outcome = { status: upstreamRes.statusCode, headers: headerList(upstreamRes.headers), body: null };
res.on("close", () => finish(outcome.status, {
...captured(),
response: { ...(outcome.body ? captureOf(outcome.body) : responseTap.result()), headers: outcome.headers },
}));
let outHeaders = buildDownstreamHeaders(upstreamRes, tunnel, info, { pathMode });
let out = upstreamRes;
if (breakpoints.matches(tunnel.id, shape.method, shape.path, "response")) {
const collected = await collect(upstreamRes, HOLD_LIMIT).catch(() => null);
if (!collected) return res.destroy();
if (collected.body) {
const decoded = decodeBody(collected.body, upstreamRes.headers["content-encoding"]);
const dropped = new Set([...HOP_BY_HOP, ...(decoded ? ["content-encoding", "content-length"] : [])]);
const heldHeaders = outcome.headers.filter(([name]) => !dropped.has(name.toLowerCase()));
const hold = breakpoints.hold(tunnel.id, {
...shape, phase: "response", ip: info.clientIp, host: info.host,
request: { headers: shape.headers, ...captured().request },
response: { status: upstreamRes.statusCode, headers: heldHeaders, ...captureOf(decoded || collected.body) },
});
res.on("close", () => breakpoints.settle(hold.id, { action: "cancel" }));
const decision = await hold.decision;
if (decision.action === "cancel") return;
if (decision.action === "drop") {
outcome.status = 503;
outcome.headers = [];
outcome.body = Buffer.alloc(0);
return res.writeHead(503, { "Content-Type": "text/plain" }).end("Dropped at a breakpoint");
}
const replyHeaders = headersFromPairs(decision.headers);
outHeaders = buildDownstreamHeaders({ rawHeaders: decision.headers.flat() }, tunnel, info, { pathMode });
const reply = snippet && decision.status === 200 && isHtml(replyHeaders) ? injectInto(decision.body, snippet) : decision.body;
for (const name of Object.keys(outHeaders)) if (name.toLowerCase() === "content-length") delete outHeaders[name];
outHeaders["content-length"] = reply.length;
if (setCookie) appendCookie(outHeaders, setCookie);
outcome.status = decision.status;
outcome.headers = decision.headers;
outcome.body = reply;
return res.writeHead(decision.status, outHeaders).end(reply);
}
res.writeHead(upstreamRes.statusCode, upstreamRes.statusMessage, outHeaders);
responseTap.pipe(res);
for (const chunk of collected.overflow) responseTap.write(chunk);
upstreamRes.pipe(responseTap);
upstreamRes.on("error", () => res.destroy());
return;
}
const inject = !!snippet && upstreamRes.statusCode === 200 && isHtml(upstreamRes.headers);
if (inject) {
const decoder = decoderFor(upstreamRes.headers["content-encoding"]);
if (decoder) {
for (const name of Object.keys(outHeaders)) {
const key = name.toLowerCase();
if (key === "content-length" || key === "content-encoding") delete outHeaders[name];
}
if (decoder !== "identity") {
decoder.on("error", () => res.destroy());
out = upstreamRes.pipe(decoder);
}
out = out.pipe(new InjectTransform(snippet));
}
}
if (setCookie) appendCookie(outHeaders, setCookie);
res.writeHead(upstreamRes.statusCode, upstreamRes.statusMessage, outHeaders);
out = out.pipe(responseTap);
out.pipe(res);
upstreamRes.on("error", () => res.destroy());
});
if (requestTap) req.pipe(requestTap).pipe(upstream);
else upstream.end(body);
};
const replayRequest = (tunnel, stored, onRequest) => new Promise(resolve => {
const headers = {};
for (const [name, value] of stored.request.headers) {
const key = name.toLowerCase();
if (HOP_BY_HOP.has(key) || key === "host" || key === "content-length") continue;
headers[name] = headers[name] === undefined ? value : [].concat(headers[name], value);
}
headers.host = tunnel.keepHost ? stored.host : hostHeader(tunnel.target);
headers["x-forwarded-host"] = stored.host;
const body = stored.request.body ? Buffer.from(stored.request.body, "base64") : null;
if (body) headers["content-length"] = body.length;
const startedAt = Date.now();
const stream = tunnel.session.open({ protocol: "tcp", remote: "replay" });
const upstream = http.request({ createConnection: () => stream, method: stored.method, path: stored.path, headers, setHost: false });
let settled = false;
const done = (status, response) => {
if (settled) return;
settled = true;
onRequest({
time: startedAt,
duration: Date.now() - startedAt,
kind: "http",
method: stored.method,
path: stored.path,
status,
ip: REPLAY_IP,
host: stored.host,
request: { headers: headerList(headers), body, bytes: body?.length || 0, truncated: false },
response,
});
resolve(status);
};
stream.on("error", () => {});
upstream.on("error", () => done(502, {}));
upstream.on("response", response => {
const tap = new Tap();
response.on("error", () => done(502, {}));
response.pipe(tap).on("finish", () => done(response.statusCode, { ...tap.result(), headers: headerList(response.headers) })).resume();
});
upstream.end(body);
});
const tap = parser => new Transform({
transform(chunk, _encoding, callback) {
parser.push(chunk);
callback(null, chunk);
},
});
const proxyUpgrade = (req, socket, head, tunnel, info, { pathMode, ws }) => {
const stream = tunnel.session.open({ protocol: "tcp", remote: info.clientIp });
const headers = buildUpstreamHeaders(req, info, tunnel, { pathMode });
headers.connection = "Upgrade";
headers.upgrade = req.headers.upgrade;
let raw = `${req.method} ${stripQueryParam(req.url)} HTTP/1.1\r\n`;
for (const [name, value] of Object.entries(headers)) {
for (const v of [].concat(value)) raw += `${name}: ${v}\r\n`;
}
raw += "\r\n";
const connection = randomToken(16);
const startedAt = Date.now();
const entry = { time: startedAt, kind: "ws", method: req.method, path: stripQueryParam(req.url), status: 101, ip: info.clientIp, host: info.host, connection };
ws.open({ ...entry, duration: 0, request: { headers: headerList(req.headers) }, response: {} }, {
in: payload => stream.write(encodeFrame(1, payload, true)),
out: payload => socket.write(encodeFrame(1, payload, false)),
});
socket.on("close", () => ws.close(connection, { ...entry, duration: Date.now() - startedAt }));
const incoming = new FrameParser((opcode, payload) => ws.frame(connection, "in", opcode, payload));
const outgoing = new FrameParser((opcode, payload) => ws.frame(connection, "out", opcode, payload), { skipHead: true });
stream.write(raw);
if (head.length) {
stream.write(head);
incoming.push(head);
}
socket.setNoDelay(true);
socket.pipe(tap(incoming)).pipe(stream).pipe(tap(outgoing)).pipe(socket);
const bail = () => { socket.destroy(); stream.destroy(); };
stream.on("error", bail);
socket.on("error", bail);
socket.on("close", () => stream.destroy());
stream.on("close", () => socket.destroy());
};
module.exports = { requestInfo, classifyHost, proxyRequest, proxyUpgrade, replayRequest, QUERY_PARAM, REPLAY_IP };
+110
View File
@@ -0,0 +1,110 @@
const { EventEmitter } = require("node:events");
const Account = require("../models/Account");
const Usage = require("../models/Usage");
const settings = require("./settings");
const logger = require("../utils/logger");
const KEYS = ["tunnels", "persistent", "domains", "traffic"];
const LABELS = { tunnels: "tunnels", persistent: "persistent tunnels", domains: "custom domains", traffic: "monthly traffic" };
const FLUSH_INTERVAL = 30 * 1000;
const month = () => new Date().toISOString().slice(0, 7);
const fail = (message, code) => Object.assign(new Error(message), { code });
const parseLimits = (input = {}, partial = false) => {
const limits = {};
for (const key of KEYS) {
const raw = input[key];
if (raw === undefined || raw === null || raw === "") {
if (!partial) limits[key] = 0;
continue;
}
const value = Number(raw);
if (!Number.isInteger(value) || value < 0) throw fail(`${LABELS[key]} must be a whole number, 0 for no limit`, "bad_request");
limits[key] = value;
}
return limits;
};
const NONE = parseLimits();
class Quotas extends EventEmitter {
constructor() {
super();
this.defaults = NONE;
this.pending = new Map();
this.timer = null;
}
async load() {
this.defaults = parseLimits((await settings.read()).quotas);
}
async saveDefaults(input) {
this.defaults = parseLimits(input);
await settings.write({ quotas: this.defaults });
return this.defaults;
}
static parseOverride(input) {
if (input === null) return null;
const limits = parseLimits(input, true);
return Object.keys(limits).length ? limits : null;
}
async limitsFor(accountId) {
const account = await Account.findByPk(accountId, { attributes: ["role", "quotas"] });
if (!account || account.role === "admin") return NONE;
return { ...this.defaults, ...(account.quotas ? JSON.parse(account.quotas) : {}) };
}
async trafficFor(accountId) {
const row = await Usage.findOne({ where: { accountId, month: month() } });
return row ? Number(row.bytesIn) + Number(row.bytesOut) : 0;
}
async enforce(accountId, key, used) {
const limit = (await this.limitsFor(accountId))[key];
if (limit && used >= limit) throw fail(`Limit of ${limit} ${LABELS[key]} reached`, "quota_exceeded");
}
async enforceTraffic(accountId) {
const limit = (await this.limitsFor(accountId)).traffic;
if (limit && await this.trafficFor(accountId) >= limit) throw fail("Monthly traffic limit reached", "quota_exceeded");
}
record(accountId, bytesIn, bytesOut, requests) {
if (!(bytesIn || bytesOut || requests)) return;
const entry = this.pending.get(accountId) || { bytesIn: 0, bytesOut: 0, requests: 0 };
entry.bytesIn += bytesIn;
entry.bytesOut += bytesOut;
entry.requests += requests;
this.pending.set(accountId, entry);
}
start() {
if (this.timer) return;
this.timer = setInterval(() => this.flush().catch(err => logger.warn(`Could not store usage: ${err.message}`)), FLUSH_INTERVAL);
this.timer.unref();
}
stop() {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
async flush() {
const batch = this.pending;
this.pending = new Map();
const current = month();
for (const [accountId, delta] of batch) {
const [row] = await Usage.findOrCreate({ where: { accountId, month: current } });
await Usage.increment(delta, { where: { id: row.id } });
const limit = (await this.limitsFor(accountId)).traffic;
if (limit && await this.trafficFor(accountId) >= limit) this.emit("exceeded", accountId);
}
}
}
module.exports = { Quotas };
+260
View File
@@ -0,0 +1,260 @@
const { EventEmitter } = require("node:events");
const crypto = require("node:crypto");
const ids = require("../utils/ids");
const { emptyPolicy, buildPolicy, evaluate } = require("./access");
const persistent = require("./persistent");
const { safeEqual } = require("../utils/auth");
const logger = require("../utils/logger");
const endSession = (session, reason, code = 4003) => {
if (!session || session.closed) return;
session.sendControl({ type: "bye", reason });
session.close(code, reason);
};
class Tunnel {
constructor({ id, mode, target, keepHost, accountId, owner, guest }) {
this.id = id;
this.accountId = accountId || null;
this.owner = owner || null;
this.guest = guest || null;
this.mode = mode;
this.target = target;
this.keepHost = !!keepHost;
this.session = null;
this.resumeToken = ids.randomToken(32);
this.secret = mode === "tcp" ? ids.randomSecret() : null;
this.secretHash = this.secret ? ids.hashSecret(this.secret) : null;
this.joiners = new Set();
this.graceTimer = null;
this.graceUntil = null;
this.createdAt = Date.now();
this.policy = emptyPolicy();
this.persistent = false;
}
get online() {
return !!this.session && !this.session.closed;
}
get shareCode() {
return this.secret ? `${this.id}${this.secret}` : null;
}
}
const parseTarget = raw => {
if (typeof raw !== "string") return null;
let value = raw.trim();
if (/^\d+$/.test(value)) value = `127.0.0.1:${value}`;
const match = /^(\[[^\]]+\]|[^:]+):(\d{1,5})$/.exec(value);
if (!match) return null;
const port = Number(match[2]);
if (port < 1 || port > 65535) return null;
const host = match[1];
return { host, port, authority: `${host}:${port}` };
};
class Registry extends EventEmitter {
constructor(config, domains, quotas, intel) {
super();
this.config = config;
this.domains = domains;
this.quotas = quotas;
this.intel = intel;
this.tunnels = new Map();
}
get(id) {
return this.tunnels.get(id) || null;
}
async _allocateId(requested, account) {
if (requested !== undefined && requested !== null && requested !== "") {
const name = String(requested).toLowerCase();
if (ids.isReserved(name)) throw Object.assign(new Error(`The name "${name}" is taken by the server itself`), { code: "invalid_name" });
if (!ids.isValidName(name)) throw Object.assign(new Error(`Invalid name "${name}": use 3-32 characters a-z, 0-9 or "-"`), { code: "invalid_name" });
if (this.tunnels.has(name)) throw Object.assign(new Error(`The name "${name}" is already in use`), { code: "name_taken" });
const definition = await persistent.load(name);
if (definition && definition.accountId !== account.id) {
throw Object.assign(new Error(`The name "${name}" is reserved by another account`), { code: "name_reserved" });
}
return { id: name, definition };
}
for (let i = 0; i < 50; i++) {
const id = ids.randomId(6);
if (!this.tunnels.has(id) && !ids.isReserved(id) && !await persistent.load(id)) return { id, definition: null };
}
throw Object.assign(new Error("Could not allocate a tunnel id"), { code: "bad_request" });
}
async register(session, { mode, httpMode, target, name, keepHost, resume, policy, share }) {
if (!["http", "tcp"].includes(mode)) throw Object.assign(new Error("mode must be http or tcp"), { code: "bad_request" });
if (mode === "http") {
const requested = httpMode === undefined || httpMode === null || httpMode === "" ? this.config.httpMode : String(httpMode).toLowerCase();
if (!["path", "subdomain"].includes(requested)) throw Object.assign(new Error(`Unknown forwarding mode "${httpMode}": use path or subdomain`), { code: "bad_request" });
if (requested === "subdomain" && this.config.managesTls && !this.config.wildcard) {
throw Object.assign(new Error("Subdomain tunnels need a wildcard certificate: set the forwarding mode to subdomain first"), { code: "bad_request" });
}
mode = requested;
} else {
mode = "tcp";
}
const parsedTarget = parseTarget(target);
if (!parsedTarget) throw Object.assign(new Error("target must be a port or host:port"), { code: "bad_request" });
const account = session.account || {};
if (typeof resume === "string" && resume.length) {
const existing = this._findByResumeToken(resume);
if (existing && existing.mode === mode && existing.accountId === account.id) {
if (policy) {
existing.policy = buildPolicy(policy);
if (existing.persistent) await persistent.savePolicy(existing.id, existing.policy);
}
this._attach(existing, session, parsedTarget, keepHost);
logger.info(`Tunnel ${existing.id} resumed`, { mode });
return { tunnel: existing, resumed: true };
}
}
const owned = [...this.tunnels.values()].filter(tunnel => tunnel.accountId === account.id).length;
await this.quotas.enforce(account.id, "tunnels", owned);
await this.quotas.enforceTraffic(account.id);
const previous = mode === "tcp" ? ids.splitShareCode(share) : null;
const wanted = name || (previous && !this.tunnels.has(previous.id) ? previous.id : undefined);
const { id, definition } = await this._allocateId(wanted, account);
if (!httpMode && mode !== "tcp" && (definition?.mode === "path" || definition?.mode === "subdomain")) {
const sticky = definition.mode;
if (sticky !== "subdomain" || !this.config.managesTls || this.config.wildcard) mode = sticky;
}
const tunnel = new Tunnel({ id, mode, target: parsedTarget, keepHost, accountId: account.id, owner: account.username, guest: session.guest });
if (previous && previous.id === id) {
tunnel.secret = previous.secret;
tunnel.secretHash = ids.hashSecret(previous.secret);
}
if (definition) {
tunnel.persistent = true;
tunnel.policy = definition.policy;
if (httpMode) await persistent.saveMode(id, mode);
}
if (policy) {
tunnel.policy = buildPolicy(policy);
if (definition) await persistent.savePolicy(id, tunnel.policy);
}
this.tunnels.set(id, tunnel);
this._attach(tunnel, session, parsedTarget, keepHost);
logger.info(`Tunnel ${id} registered`, { mode, target: parsedTarget.authority, owner: account.username, guest: session.guest });
return { tunnel, resumed: false };
}
_findByResumeToken(token) {
for (const tunnel of this.tunnels.values()) {
if (safeEqual(tunnel.resumeToken, token)) return tunnel;
}
return null;
}
_attach(tunnel, session, target, keepHost) {
tunnel.credential = session.credential;
if (tunnel.graceTimer) {
clearTimeout(tunnel.graceTimer);
tunnel.graceTimer = null;
}
tunnel.graceUntil = null;
if (tunnel.session && tunnel.session !== session && !tunnel.session.closed) {
endSession(tunnel.session, "replaced by a newer connection", 4001);
}
tunnel.session = session;
tunnel.target = target;
tunnel.keepHost = !!keepHost;
session.tunnel = tunnel;
session.once("close", () => {
if (tunnel.session !== session) return;
tunnel.session = null;
if (session.saidBye) return this.remove(tunnel.id, "closed by owner");
this._startGrace(tunnel);
});
this.emit("online", tunnel);
}
_startGrace(tunnel) {
const seconds = this.config.gracePeriod;
logger.info(`Tunnel ${tunnel.id} offline, reserved for ${seconds}s`);
this.emit("offline", tunnel);
if (seconds <= 0) return this.remove(tunnel.id, "grace period is 0");
tunnel.graceUntil = Date.now() + seconds * 1000;
tunnel.graceTimer = setTimeout(() => this.remove(tunnel.id, "grace period expired"), seconds * 1000);
}
remove(id, reason) {
const tunnel = this.tunnels.get(id);
if (!tunnel) return;
this.emit("forget", tunnel);
this.tunnels.delete(id);
if (tunnel.graceTimer) clearTimeout(tunnel.graceTimer);
endSession(tunnel.session, `tunnel closed (${reason})`, 4004);
for (const joiner of tunnel.joiners) endSession(joiner, "tunnel closed", 4004);
tunnel.joiners.clear();
logger.info(`Tunnel ${id} removed`, { reason });
this.emit("removed", tunnel);
}
closeFor(accountId, reason) {
for (const tunnel of [...this.tunnels.values()]) {
if (tunnel.accountId === accountId) this.remove(tunnel.id, reason);
}
}
closeCredential(credential, reason) {
for (const tunnel of [...this.tunnels.values()]) {
if (tunnel.credential === credential) this.remove(tunnel.id, reason);
}
}
join(session, code) {
const parts = ids.splitShareCode(code);
if (!parts) throw Object.assign(new Error("Invalid share code"), { code: "invalid_code" });
const tunnel = this.tunnels.get(parts.id);
if (!tunnel || tunnel.mode !== "tcp" || !tunnel.secretHash) throw Object.assign(new Error("Invalid share code"), { code: "invalid_code" });
if (!crypto.timingSafeEqual(tunnel.secretHash, ids.hashSecret(parts.secret))) throw Object.assign(new Error("Invalid share code"), { code: "invalid_code" });
const ip = session.client?.ip;
const details = this.intel.lookup(ip);
const reason = evaluate(tunnel.policy, ip, details);
if (reason) {
this.emit("blocked", tunnel, ip, details, reason);
throw Object.assign(new Error("Your address is not allowed to use this tunnel"), { code: "forbidden" });
}
tunnel.joiners.add(session);
session.tunnel = tunnel;
session.once("close", () => tunnel.joiners.delete(session));
return tunnel;
}
connectUrl(tunnel) {
return tunnel.shareCode ? `${this.config.publicUrl}/@frislit/connect/${tunnel.shareCode}` : null;
}
publicUrl(tunnel) {
return tunnel.mode === "tcp" ? null : this.urlFor(tunnel.id, tunnel.mode);
}
urlFor(name, mode = this.config.httpMode) {
const { publicScheme, baseDomain, publicUrl } = this.config;
if (mode === "subdomain") {
const port = new URL(publicUrl).port;
return `${publicScheme}://${name}.${baseDomain}${port ? `:${port}` : ""}`;
}
return `${publicUrl}/@${name}`;
}
customUrls(tunnel) {
if (tunnel.mode === "tcp") return [];
return this.domains.hostsFor(tunnel.id).map(hostname => `${this.config.publicScheme}://${hostname}`);
}
}
module.exports = { Registry, endSession };
+75
View File
@@ -0,0 +1,75 @@
const { Op } = require("sequelize");
const Session = require("../models/Session");
const Account = require("../models/Account");
const COOKIE_NAME = "frislit-admin";
const TTL = 7 * 24 * 60 * 60 * 1000;
const TOUCH_AFTER = 60_000;
class SessionStore {
constructor() {
this.sweeper = setInterval(() => this.sweep(), 60 * 60 * 1000);
this.sweeper.unref();
}
async create(accountId, meta = {}) {
const session = await Session.create({ accountId, ip: meta.ip || null, userAgent: meta.userAgent || null });
return session.get ? session.get("token") : session.token;
}
async get(token) {
if (!token) return null;
const session = await Session.findOne({ where: { token: String(token) } });
if (!session) return null;
if (Date.now() - new Date(session.lastSeen).getTime() > TTL) {
await Session.destroy({ where: { id: session.id } });
return null;
}
const account = await Account.findByPk(session.accountId);
if (!account) {
await Session.destroy({ where: { id: session.id } });
return null;
}
if (Date.now() - new Date(session.lastSeen).getTime() > TOUCH_AFTER) {
await Session.update({ lastSeen: new Date() }, { where: { id: session.id } });
}
return { id: session.id, account, username: account.username, role: account.role, createdAt: session.createdAt };
}
remove(token) {
return Session.destroy({ where: { token: String(token || "") } });
}
forAccount(accountId) {
return Session.destroy({ where: { accountId } });
}
sweep() {
return Session.destroy({ where: { lastSeen: { [Op.lt]: new Date(Date.now() - TTL) } } });
}
}
const parseCookies = header => {
const out = [];
for (const part of String(header || "").split(";")) {
const index = part.indexOf("=");
if (index === -1) continue;
const name = part.slice(0, index).trim();
if (name) out.push({ name, value: part.slice(index + 1).trim() });
}
return out;
};
const tokenFromRequest = req => parseCookies(req.headers.cookie).find(cookie => cookie.name === COOKIE_NAME)?.value || null;
const sessionCookie = (token, secure) =>
`${COOKIE_NAME}=${token}; Path=/@frislit; HttpOnly; SameSite=Lax; Max-Age=${TTL / 1000}${secure ? "; Secure" : ""}`;
const clearSessionCookie = secure =>
`${COOKIE_NAME}=; Path=/@frislit; HttpOnly; SameSite=Lax; Max-Age=0${secure ? "; Secure" : ""}`;
module.exports = { SessionStore, tokenFromRequest, sessionCookie, clearSessionCookie };
+25
View File
@@ -0,0 +1,25 @@
const Setting = require("../models/Setting");
const read = async () => {
const rows = await Setting.findAll();
const values = {};
for (const row of rows) {
try {
values[row.key] = JSON.parse(row.value);
} catch {
values[row.key] = row.value;
}
}
return values;
};
const write = async values => {
for (const [key, value] of Object.entries(values)) {
const encoded = JSON.stringify(value);
const row = await Setting.findOne({ where: { key } });
if (row) await Setting.update({ value: encoded }, { where: { key } });
else await Setting.create({ key, value: encoded });
}
};
module.exports = { read, write };
+139
View File
@@ -0,0 +1,139 @@
const METHODS = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|CONNECT|TRACE) (\S+) HTTP\/1\.[01]\r\n/;
const varint = (buffer, offset) => {
let value = 0;
let shift = 0;
for (let i = offset; i < buffer.length && shift < 35; i++) {
value |= (buffer[i] & 0x7f) << shift;
if ((buffer[i] & 0x80) === 0) return [value, i + 1];
shift += 7;
}
return null;
};
const tls = buffer => {
if (buffer.length < 44 || buffer[0] !== 0x16 || buffer[1] !== 0x03 || buffer[5] !== 0x01) return null;
let at = 43;
at += 1 + buffer[at];
if (at + 2 > buffer.length) return { name: "TLS", info: null };
at += 2 + buffer.readUInt16BE(at);
if (at + 1 > buffer.length) return { name: "TLS", info: null };
at += 1 + buffer[at];
if (at + 2 > buffer.length) return { name: "TLS", info: null };
const end = Math.min(buffer.length, at + 2 + buffer.readUInt16BE(at));
at += 2;
let sni = null;
const alpn = [];
while (at + 4 <= end) {
const type = buffer.readUInt16BE(at);
const length = buffer.readUInt16BE(at + 2);
const body = buffer.subarray(at + 4, Math.min(end, at + 4 + length));
if (type === 0 && body.length >= 5) sni = body.subarray(5, 5 + body.readUInt16BE(3)).toString("utf8");
if (type === 16 && body.length >= 2) {
let cursor = 2;
while (cursor < body.length) {
const size = body[cursor];
alpn.push(body.subarray(cursor + 1, cursor + 1 + size).toString("utf8"));
cursor += 1 + size;
}
}
at += 4 + length;
}
return { name: "TLS", info: [sni, alpn.length ? alpn.join(", ") : null].filter(Boolean).join(" · ") || null };
};
const http = buffer => {
const head = buffer.subarray(0, 2048).toString("latin1");
if (head.startsWith("PRI * HTTP/2.0\r\n")) return { name: "HTTP/2", info: null };
const match = METHODS.exec(head);
if (!match) return null;
const host = /\r\nhost:\s*([^\r\n]+)/i.exec(head);
return { name: "HTTP", info: [host?.[1], `${match[1]} ${match[2]}`].filter(Boolean).join(" · ") };
};
const ssh = buffer => {
if (!buffer.subarray(0, 4).equals(Buffer.from("SSH-"))) return null;
return { name: "SSH", info: buffer.subarray(0, 64).toString("latin1").split("\r\n")[0].slice(0, 48) };
};
const postgres = buffer => {
if (buffer.length < 8) return null;
const length = buffer.readUInt32BE(0);
const code = buffer.readUInt32BE(4);
if (code === 80877103 || code === 80877104) return { name: "PostgreSQL", info: null };
if (code !== 196608 || length > 10000) return null;
const params = buffer.subarray(8, Math.min(length, buffer.length)).toString("utf8").split("\0");
const pairs = {};
for (let i = 0; i + 1 < params.length; i += 2) pairs[params[i]] = params[i + 1];
return { name: "PostgreSQL", info: [pairs.user, pairs.database].filter(Boolean).join(" @ ") || null };
};
const mysql = buffer => {
if (buffer.length < 6 || buffer[3] !== 0 || buffer[4] !== 0x0a) return null;
const end = buffer.indexOf(0, 5);
if (end === -1 || end > 64) return null;
return { name: "MySQL", info: buffer.subarray(5, end).toString("latin1") };
};
const redis = buffer => {
const head = buffer.subarray(0, 64).toString("latin1");
const match = /^\*\d+\r\n\$\d+\r\n([A-Za-z]+)\r\n/.exec(head);
return match ? { name: "Redis", info: match[1].toUpperCase() } : null;
};
const mqtt = buffer => {
if (buffer[0] !== 0x10) return null;
const head = varint(buffer, 1);
if (!head) return null;
const at = head[1];
if (buffer.length < at + 6 || buffer.readUInt16BE(at) !== 4 || buffer.subarray(at + 2, at + 6).toString("latin1") !== "MQTT") return null;
return { name: "MQTT", info: null };
};
const minecraft = buffer => {
const length = varint(buffer, 0);
if (!length || buffer[length[1]] !== 0) return null;
const version = varint(buffer, length[1] + 1);
if (!version) return null;
const host = varint(buffer, version[1]);
if (!host || host[0] > 255 || host[1] + host[0] + 3 > buffer.length) return null;
const name = buffer.subarray(host[1], host[1] + host[0]).toString("utf8");
const port = buffer.readUInt16BE(host[1] + host[0]);
const state = buffer[host[1] + host[0] + 2];
if (!/^[\w.:-]+$/.test(name) || (state !== 1 && state !== 2)) return null;
return { name: "Minecraft", info: `${name}:${port} · ${state === 1 ? "status" : "login"}` };
};
const dns = buffer => {
if (buffer.length < 17 || (buffer[2] & 0x80) !== 0 || buffer.readUInt16BE(4) !== 1) return null;
const labels = [];
let at = 12;
while (at < buffer.length && buffer[at] !== 0) {
const size = buffer[at];
if (size > 63 || at + 1 + size > buffer.length) return null;
labels.push(buffer.subarray(at + 1, at + 1 + size).toString("latin1"));
at += 1 + size;
}
if (!labels.length) return null;
return { name: "DNS", info: labels.join(".") };
};
const wireguard = buffer => (buffer.length === 148 && buffer[0] === 1 && buffer[1] === 0 && buffer[2] === 0 && buffer[3] === 0 ? { name: "WireGuard", info: null } : null);
const quic = buffer => (buffer.length >= 5 && (buffer[0] & 0xc0) === 0xc0 && buffer.readUInt32BE(1) === 1 ? { name: "QUIC", info: null } : null);
const TCP_IN = [tls, http, ssh, postgres, redis, mqtt, minecraft];
const TCP_OUT = [ssh, mysql];
const UDP = [dns, quic, wireguard];
const sniff = (protocol, direction, buffer) => {
if (!buffer.length) return null;
const detectors = protocol === "udp" ? UDP : direction === "in" ? TCP_IN : TCP_OUT;
for (const detector of detectors) {
const result = detector(buffer);
if (result) return result;
}
return null;
};
module.exports = { sniff };
+104
View File
@@ -0,0 +1,104 @@
const INTERVAL = 2000;
const BUCKETS = 90;
const empty = () => ({
buckets: [],
totals: { in: 0, out: 0, requests: 0 },
pendingRequests: 0,
lastSent: 0,
lastReceived: 0,
session: null,
});
class Stats {
constructor(registry, quotas, { interval = INTERVAL, buckets = BUCKETS } = {}) {
this.registry = registry;
this.quotas = quotas;
this.interval = interval;
this.limit = buckets;
this.series = new Map();
this.timer = null;
}
start() {
if (this.timer) return;
this.timer = setInterval(() => this.sample(), this.interval);
this.timer.unref();
}
stop() {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
_for(tunnelId) {
let entry = this.series.get(tunnelId);
if (!entry) {
entry = empty();
this.series.set(tunnelId, entry);
}
return entry;
}
recordRequest(tunnelId) {
this._for(tunnelId).pendingRequests += 1;
}
sample() {
const now = Date.now();
for (const tunnel of this.registry.tunnels.values()) {
const entry = this._for(tunnel.id);
const session = tunnel.session;
let inBytes = 0;
let outBytes = 0;
if (session && !session.closed) {
if (entry.session !== session) {
entry.session = session;
entry.lastSent = 0;
entry.lastReceived = 0;
}
inBytes = Math.max(0, session.bytesSent - entry.lastSent);
outBytes = Math.max(0, session.bytesReceived - entry.lastReceived);
entry.lastSent = session.bytesSent;
entry.lastReceived = session.bytesReceived;
} else {
entry.session = null;
}
const requests = entry.pendingRequests;
entry.pendingRequests = 0;
entry.totals.in += inBytes;
entry.totals.out += outBytes;
entry.totals.requests += requests;
this.quotas.record(tunnel.accountId, inBytes, outBytes, requests);
entry.buckets.push({ t: now, in: inBytes, out: outBytes, requests });
if (entry.buckets.length > this.limit) entry.buckets.splice(0, entry.buckets.length - this.limit);
}
}
read(tunnelId) {
const entry = this.series.get(tunnelId);
const seconds = this.interval / 1000;
if (!entry) return { interval: seconds, buckets: [], totals: { in: 0, out: 0, requests: 0 }, rates: { in: 0, out: 0 } };
const recent = entry.buckets.slice(-5);
const average = key => recent.length
? recent.reduce((sum, bucket) => sum + bucket[key], 0) / (recent.length * seconds)
: 0;
return {
interval: seconds,
buckets: entry.buckets,
totals: { ...entry.totals },
rates: { in: Math.round(average("in")), out: Math.round(average("out")) },
};
}
forget(tunnelId) {
this.series.delete(tunnelId);
}
}
module.exports = { Stats };
+285
View File
@@ -0,0 +1,285 @@
const tls = require("node:tls");
const dns = require("node:dns").promises;
const acme = require("acme-client");
const store = require("./store");
const providers = require("./providers");
const logger = require("../../utils/logger");
const RENEW_BEFORE = 30 * 24 * 60 * 60 * 1000;
const CHECK_INTERVAL = 12 * 60 * 60 * 1000;
const TXT_TIMEOUT = 120 * 1000;
const TXT_STEP = 5 * 1000;
const waitForTxt = async (record, value) => {
for (let deadline = Date.now() + TXT_TIMEOUT; Date.now() < deadline;) {
const rows = await dns.resolveTxt(record).catch(() => []);
if (rows.some(parts => parts.join("") === value)) return;
await new Promise(resolve => setTimeout(resolve, TXT_STEP));
}
throw new Error(`The TXT record ${record} did not show up within ${TXT_TIMEOUT / 1000}s`);
};
const domainsFor = config => config.wildcard ? [config.baseDomain, `*.${config.baseDomain}`] : [config.baseDomain];
class CertificateManager {
constructor(config) {
this.config = config;
this.context = null;
this.current = null;
this.state = "none";
this.error = null;
this.busy = false;
this.challenges = new Map();
this.timer = null;
this.extra = new Map();
this.issuing = new Set();
}
get domain() {
return this.config.baseDomain;
}
async load() {
const row = await store.certificate(this.domain);
if (!row) {
this.state = "none";
return null;
}
this.current = {
domain: row.domain,
altNames: JSON.parse(row.altNames || "[]"),
issuedAt: row.issuedAt,
expiresAt: row.expiresAt,
};
this.context = tls.createSecureContext({ key: row.privateKey, cert: row.chain });
this.state = new Date(row.expiresAt).getTime() < Date.now() ? "expired" : "ready";
return this.current;
}
async loadExtra() {
this.extra.clear();
for (const row of await store.certificates()) {
if (row.domain === this.domain) continue;
this.extra.set(row.domain, {
context: tls.createSecureContext({ key: row.privateKey, cert: row.chain }),
expiresAt: new Date(row.expiresAt),
});
}
}
secureContextFor(servername) {
const name = String(servername || "").toLowerCase();
return this.extra.get(name)?.context || this.context;
}
info(hostname) {
const entry = this.extra.get(hostname);
return entry ? { expiresAt: entry.expiresAt } : null;
}
dueFor(hostname) {
const entry = this.extra.get(hostname);
return !entry || entry.expiresAt.getTime() - Date.now() < RENEW_BEFORE;
}
async issueFor(hostname) {
if (this.issuing.has(hostname)) throw new Error(`A certificate request for ${hostname} is already running`);
if (!this.config.managesTls) throw new Error("frislit does not manage certificates on this server");
this.issuing.add(hostname);
try {
const { settings, client } = await this.client();
const [key, csr] = await acme.crypto.createCsr({ commonName: hostname, altNames: [hostname] });
const handlers = this.challengeHandlers(settings);
const chain = await client.auto({
csr,
email: settings.email || undefined,
termsOfServiceAgreed: true,
skipChallengeVerification: true,
challengePriority: ["http-01"],
challengeCreateFn: handlers.create,
challengeRemoveFn: handlers.remove,
});
const info = acme.crypto.readCertificateInfo(chain);
await store.saveCertificate({
domain: hostname, altNames: [hostname],
privateKey: key.toString(), chain: chain.toString(),
expiresAt: info.notAfter,
});
this.extra.set(hostname, {
context: tls.createSecureContext({ key: key.toString(), cert: chain.toString() }),
expiresAt: info.notAfter,
});
logger.info(`Certificate issued for ${hostname}, valid until ${info.notAfter.toISOString()}`);
} finally {
this.issuing.delete(hostname);
}
}
async forget(hostname) {
this.extra.delete(hostname);
await store.forgetCertificate(hostname);
}
covers() {
if (!this.current) return false;
const wanted = domainsFor(this.config);
return wanted.every(name => this.current.altNames.includes(name));
}
dueForRenewal() {
if (!this.current) return true;
if (!this.covers()) return true;
return new Date(this.current.expiresAt).getTime() - Date.now() < RENEW_BEFORE;
}
status() {
const state = this.busy ? this.state
: !this.current ? (this.error ? "error" : "none")
: !this.covers() ? "stale"
: new Date(this.current.expiresAt).getTime() < Date.now() ? "expired" : "ready";
return {
state,
busy: this.busy,
error: this.error,
domains: domainsFor(this.config),
certificate: this.current,
dueForRenewal: this.dueForRenewal(),
pendingRecords: providers.get("manual").records(),
};
}
async client() {
const settings = await store.settings();
let accountKey = settings.accountKey;
if (!accountKey) {
accountKey = (await acme.crypto.createPrivateKey()).toString();
await store.saveSettings({ accountKey });
}
const directoryUrl = this.config.acmeDirectoryUrl || acme.directory.letsencrypt.production;
return { settings, client: new acme.Client({ directoryUrl, accountKey }) };
}
challengeHandlers(settings) {
const provider = providers.get(settings.provider) || providers.get("manual");
const create = async (authz, challenge, keyAuthorization) => {
if (challenge.type === "http-01") {
this.challenges.set(challenge.token, keyAuthorization);
return;
}
const record = `_acme-challenge.${authz.identifier.value.replace(/^\*\./, "")}`;
logger.info(`Adding DNS challenge for ${record} via ${provider.id}`);
await provider.create(settings.credential, record, keyAuthorization);
if (challenge.type === "dns-01") await waitForTxt(record, keyAuthorization);
};
const remove = async (authz, challenge, keyAuthorization) => {
if (challenge.type === "http-01") {
this.challenges.delete(challenge.token);
return;
}
const record = `_acme-challenge.${authz.identifier.value.replace(/^\*\./, "")}`;
try {
await provider.remove(settings.credential, record, keyAuthorization);
} catch (err) {
logger.warn(`Could not remove the DNS challenge for ${record}: ${err.message}`);
}
};
return { create, remove };
}
async request() {
if (this.busy) return { code: 409, message: "A certificate request is already running" };
if (!this.config.ready) return { code: 400, message: "Set the base domain first" };
const { settings, client } = await this.client();
if (this.config.wildcard && settings.provider === "http") {
return { code: 400, message: "Subdomain forwarding needs a wildcard certificate, which requires a DNS provider" };
}
const provider = providers.get(settings.provider);
if (!provider) return { code: 400, message: `Unknown DNS provider "${settings.provider}"` };
if (provider.needsCredential && !settings.credential) return { code: 400, message: `${provider.title} needs an API token` };
this.busy = true;
this.run(settings, client).catch(err => logger.error(`Certificate request crashed: ${err.stack || err}`));
return { message: "Requesting a certificate", status: this.status() };
}
async run(settings, client) {
this.state = "requesting";
this.error = null;
const altNames = domainsFor(this.config);
try {
const [key, csr] = await acme.crypto.createCsr({ commonName: altNames[0], altNames });
const handlers = this.challengeHandlers(settings);
const chain = await client.auto({
csr,
email: settings.email || undefined,
termsOfServiceAgreed: true,
skipChallengeVerification: true,
challengePriority: settings.provider === "http" ? ["http-01"] : ["dns-01"],
challengeCreateFn: handlers.create,
challengeRemoveFn: handlers.remove,
});
const info = acme.crypto.readCertificateInfo(chain);
await store.saveCertificate({
domain: this.domain, altNames,
privateKey: key.toString(), chain: chain.toString(),
expiresAt: info.notAfter,
});
providers.get("manual").reset();
await this.load();
logger.info(`Certificate issued for ${altNames.join(", ")}, valid until ${info.notAfter.toISOString()}`);
} catch (err) {
this.error = err.message;
this.state = this.current ? "ready" : "error";
providers.get("manual").reset();
logger.error(`Certificate request failed: ${err.message}`);
} finally {
this.busy = false;
}
}
continueManual() {
return providers.get("manual").continue();
}
challengeResponse(token) {
return this.challenges.get(token) || null;
}
secureContext() {
return this.context;
}
start() {
if (this.timer) return;
this.timer = setInterval(() => this.maybeRenew(), CHECK_INTERVAL);
this.timer.unref();
}
stop() {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
async maybeRenew() {
if (!this.config.managesTls || !this.config.ready) return;
if (!this.busy && this.dueForRenewal()) {
logger.info("Certificate is due for renewal");
const result = await this.request();
if (result.code) logger.warn(`Renewal could not start: ${result.message}`);
}
for (const hostname of this.extra.keys()) {
if (!this.dueFor(hostname)) continue;
logger.info(`Certificate for ${hostname} is due for renewal`);
await this.issueFor(hostname).catch(err => logger.warn(`Renewal for ${hostname} failed: ${err.message}`));
}
}
}
module.exports = { CertificateManager, domainsFor };
+53
View File
@@ -0,0 +1,53 @@
const API = "https://api.cloudflare.com/client/v4";
const call = async (token, path, options = {}) => {
const response = await fetch(`${API}${path}`, {
...options,
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", ...options.headers },
});
const body = await response.json().catch(() => ({}));
if (!response.ok || body.success === false) {
const detail = body.errors?.map(error => error.message).join(", ") || response.statusText;
throw new Error(`Cloudflare: ${detail}`);
}
return body.result;
};
const zoneFor = async (token, hostname) => {
const labels = hostname.split(".");
for (let i = 0; i < labels.length - 1; i++) {
const candidate = labels.slice(i).join(".");
const zones = await call(token, `/zones?name=${encodeURIComponent(candidate)}`);
if (zones?.length) return zones[0];
}
throw new Error(`Cloudflare: no zone found for ${hostname}. Check that the token can read this zone.`);
};
module.exports = {
id: "cloudflare",
title: "Cloudflare",
needsCredential: true,
credentialLabel: "API token",
async verify(token, hostname) {
const zone = await zoneFor(token, hostname);
return { message: `Token works, zone ${zone.name} found` };
},
async create(token, record, value) {
const zone = await zoneFor(token, record);
return call(token, `/zones/${zone.id}/dns_records`, {
method: "POST",
body: JSON.stringify({ type: "TXT", name: record, content: value, ttl: 60 }),
});
},
async remove(token, record, value) {
const zone = await zoneFor(token, record);
const existing = await call(token, `/zones/${zone.id}/dns_records?type=TXT&name=${encodeURIComponent(record)}`);
for (const entry of existing || []) {
if (entry.content !== value) continue;
await call(token, `/zones/${zone.id}/dns_records/${entry.id}`, { method: "DELETE" });
}
},
};
+18
View File
@@ -0,0 +1,18 @@
const cloudflare = require("./cloudflare");
const manual = require("./manual");
const http = { id: "http", title: "No DNS provider", needsCredential: false, httpOnly: true };
const PROVIDERS = { cloudflare, manual, http };
const get = id => PROVIDERS[id] || null;
const describe = () => Object.values(PROVIDERS).map(provider => ({
id: provider.id,
title: provider.title,
needsCredential: !!provider.needsCredential,
credentialLabel: provider.credentialLabel || null,
httpOnly: !!provider.httpOnly,
}));
module.exports = { get, describe, PROVIDERS };
+40
View File
@@ -0,0 +1,40 @@
const WAIT_TIMEOUT = 15 * 60 * 1000;
const pending = new Map();
const settle = (key, error) => {
const entry = pending.get(key);
if (!entry) return;
pending.delete(key);
clearTimeout(entry.timer);
if (error) entry.reject(error); else entry.resolve();
};
module.exports = {
id: "manual",
title: "Add the record yourself",
needsCredential: false,
records: () => [...pending.values()].map(({ record, value }) => ({ record, value })),
create(_token, record, value) {
const key = `${record}:${value}`;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => settle(key, new Error("Timed out waiting for the TXT record to be added")), WAIT_TIMEOUT);
timer.unref();
pending.set(key, { record, value, timer, resolve, reject });
});
},
remove() {},
continue() {
const keys = [...pending.keys()];
for (const key of keys) settle(key);
return keys.length > 0;
},
reset() {
for (const key of [...pending.keys()]) settle(key, new Error("Cancelled"));
},
};
+33
View File
@@ -0,0 +1,33 @@
const Acme = require("../../models/Acme");
const Certificate = require("../../models/Certificate");
const DEFAULTS = { email: null, provider: "manual", credential: null, accountKey: null };
const settings = async () => {
const row = await Acme.findOne();
return row ? { ...DEFAULTS, ...row } : { ...DEFAULTS };
};
const saveSettings = async values => {
const row = await Acme.findOne();
if (row) return Acme.update(values, { where: { id: row.id } });
return Acme.create({ ...DEFAULTS, ...values });
};
const certificate = domain => Certificate.findOne({ where: { domain } });
const certificates = () => Certificate.findAll();
const saveCertificate = async ({ domain, altNames, privateKey, chain, expiresAt }) => {
const values = {
domain, altNames: JSON.stringify(altNames), privateKey, chain,
issuedAt: new Date(), expiresAt,
};
const row = await Certificate.findOne({ where: { domain } });
if (row) return Certificate.update(values, { where: { id: row.id } });
return Certificate.create(values);
};
const forgetCertificate = domain => Certificate.destroy({ where: { domain } });
module.exports = { settings, saveSettings, certificate, certificates, saveCertificate, forgetCertificate };
+52
View File
@@ -0,0 +1,52 @@
const speakeasy = require("speakeasy");
const Account = require("../models/Account");
const Session = require("../models/Session");
const logger = require("../utils/logger");
const WINDOW = 1;
const secretFor = async account => {
if (account.totpSecret) return account.totpSecret;
const secret = speakeasy.generateSecret({ length: 20 }).base32;
await Account.update({ totpSecret: secret }, { where: { id: account.id } });
return secret;
};
const otpauthUrl = (secret, username, issuer) =>
`otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(username)}` +
`?secret=${secret}&issuer=${encodeURIComponent(issuer)}`;
const verify = (secret, code) => speakeasy.totp.verify({
secret: secret || "",
encoding: "base32",
token: String(code || "").replace(/\s/g, ""),
window: WINDOW,
});
const begin = async (account, issuer) => {
if (account.totpEnabled) return { code: 409, message: "Two-factor is already on for this account" };
const secret = await secretFor(account);
return { secret, url: otpauthUrl(secret, account.username, issuer) };
};
const enable = async (account, code) => {
if (account.totpEnabled) return { code: 409, message: "Two-factor is already on for this account" };
if (!account.totpSecret) return { code: 409, message: "Start the setup first" };
if (!verify(account.totpSecret, code)) return { code: 401, message: "That code is not right. Check your clock and try the next one." };
await Account.update({ totpEnabled: true }, { where: { id: account.id } });
await Session.destroy({ where: { accountId: account.id } });
logger.info(`${account.username} turned on two-factor`);
return { message: "Two-factor is on" };
};
const disable = async (account, code) => {
if (!account.totpEnabled) return { code: 409, message: "Two-factor is already off" };
if (!verify(account.totpSecret, code)) return { code: 401, message: "That code is not right" };
await Account.update({ totpEnabled: false, totpSecret: null }, { where: { id: account.id } });
logger.info(`${account.username} turned off two-factor`);
return { message: "Two-factor is off" };
};
module.exports = { begin, enable, disable, verify };
+189
View File
@@ -0,0 +1,189 @@
const { Op, fn, col, literal, where: sqlWhere } = require("sequelize");
const country = () => fn("json_extract", col("intel"), literal("'$.country'"));
const Request = require("../models/Request");
const Frame = require("../models/Frame");
const logger = require("../utils/logger");
const PER_TUNNEL_LIMIT = 200;
const PAGE_SIZE = 50;
const SORTABLE = { time: "id", status: "status", duration: "duration", path: "path", method: "method" };
const criteria = (tunnelId, { search, methods = [], statuses = [], countries = [] }) => {
const where = { tunnel: tunnelId };
if (search) where[Op.or] = [{ path: { [Op.like]: `%${search}%` } }, { ip: { [Op.like]: `%${search}%` } }];
if (methods.length) {
const wantsWs = methods.includes("WS");
const plain = methods.filter(method => method !== "WS");
const options = [];
if (plain.length) options.push({ kind: "http", method: plain });
if (wantsWs) options.push({ kind: "ws" });
where[Op.and] = [...(where[Op.and] || []), { [Op.or]: options }];
}
if (statuses.length) {
where[Op.and] = [...(where[Op.and] || []), { [Op.or]: statuses.map(hundreds => ({ status: { [Op.between]: [hundreds * 100, hundreds * 100 + 99] } })) }];
}
if (countries.length) {
where[Op.and] = [...(where[Op.and] || []), sqlWhere(country(), { [Op.in]: countries })];
}
return where;
};
const FLUSH_INTERVAL = 500;
const toText = body => (body ? Buffer.from(body).toString("base64") : null);
const summarise = row => ({
id: row.id,
time: new Date(row.time).getTime(),
duration: row.duration,
kind: row.kind,
connection: row.connection,
intel: row.intel ? JSON.parse(row.intel) : null,
method: row.method,
path: row.path,
status: row.status,
ip: row.ip,
host: row.host,
requestBytes: row.requestBytes,
responseBytes: row.responseBytes,
});
const detail = row => ({
...summarise(row),
request: {
headers: JSON.parse(row.requestHeaders || "[]"),
body: toText(row.requestBody),
bytes: row.requestBytes,
truncated: !!row.requestTruncated,
},
response: {
headers: JSON.parse(row.responseHeaders || "[]"),
body: toText(row.responseBody),
bytes: row.responseBytes,
truncated: !!row.responseTruncated,
},
});
class TrafficLog {
constructor({ limit = PER_TUNNEL_LIMIT, interval = FLUSH_INTERVAL } = {}) {
this.limit = limit;
this.interval = interval;
this.pending = [];
this.counts = new Map();
this.timer = null;
}
start() {
if (this.timer) return;
this.timer = setInterval(() => this.flush(), this.interval);
this.timer.unref();
}
stop() {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
record(tunnelId, entry) {
this.pending.push({
tunnel: tunnelId,
time: new Date(entry.time),
duration: entry.duration || 0,
kind: entry.kind || "http",
connection: entry.connection || null,
intel: entry.intel ? JSON.stringify(entry.intel) : null,
method: entry.method || null,
path: entry.path || null,
status: entry.status || null,
ip: entry.ip || null,
host: entry.host || null,
requestHeaders: JSON.stringify(entry.request?.headers || []),
requestBody: entry.request?.body || null,
requestBytes: entry.request?.bytes || 0,
requestTruncated: !!entry.request?.truncated,
responseHeaders: JSON.stringify(entry.response?.headers || []),
responseBody: entry.response?.body || null,
responseBytes: entry.response?.bytes || 0,
responseTruncated: !!entry.response?.truncated,
});
this.counts.set(tunnelId, (this.counts.get(tunnelId) || 0) + 1);
}
async flush() {
if (!this.pending.length) return;
const batch = this.pending;
this.pending = [];
try {
await Request.bulkCreate(batch);
for (const tunnel of new Set(batch.map(row => row.tunnel))) await this.prune(tunnel);
} catch (err) {
logger.warn(`Could not store ${batch.length} request(s): ${err.message}`);
}
}
async prune(tunnel) {
const rows = await Request.findAll({
where: { tunnel }, order: [["id", "DESC"]], offset: this.limit, limit: 1, attributes: ["id"],
});
if (!rows.length) return;
const stale = { tunnel, id: { [Op.lte]: rows[0].id } };
const connections = (await Request.findAll({ where: { ...stale, connection: { [Op.ne]: null } }, attributes: ["connection"] })).map(row => row.connection);
if (connections.length) await Frame.destroy({ where: { connection: connections } });
await Request.destroy({ where: stale });
}
async finish(connection, duration) {
const row = this.pending.find(entry => entry.connection === connection);
if (row) row.duration = duration;
else await Request.update({ duration }, { where: { connection } });
}
async list(tunnelId, { filter = {}, sort = "time", order = "desc", offset = 0, limit = PAGE_SIZE } = {}) {
await this.flush();
const column = SORTABLE[sort] || "id";
const rows = await Request.findAll({
where: criteria(tunnelId, filter),
order: [[column, order === "asc" ? "ASC" : "DESC"], ["id", "DESC"]],
offset: Math.max(offset, 0),
limit: Math.min(Math.max(limit, 1), PER_TUNNEL_LIMIT),
attributes: { exclude: ["requestBody", "responseBody", "requestHeaders", "responseHeaders"] },
});
return rows.map(summarise);
}
async all(tunnelId) {
await this.flush();
const rows = await Request.findAll({ where: { tunnel: tunnelId }, order: [["id", "ASC"]] });
return rows.map(detail);
}
async get(tunnelId, id) {
await this.flush();
const row = await Request.findOne({ where: { tunnel: tunnelId, id } });
return row ? detail(row) : null;
}
count(tunnelId, filter = {}) {
return Request.count({ where: criteria(tunnelId, filter) });
}
async countries(tunnelId) {
const rows = await Request.findAll({
where: { tunnel: tunnelId },
attributes: [[country(), "code"], [fn("COUNT", col("id")), "count"]],
group: ["code"],
});
return rows.filter(row => row.code).map(row => ({ code: row.code, count: row.count })).sort((a, b) => b.count - a.count);
}
async forget(tunnelId) {
this.pending = this.pending.filter(row => row.tunnel !== tunnelId);
this.counts.delete(tunnelId);
await Frame.destroy({ where: { tunnel: tunnelId } });
const removed = await Request.destroy({ where: { tunnel: tunnelId } });
if (removed) logger.debug(`Dropped ${removed} stored request(s) for ${tunnelId}`);
}
}
module.exports = { TrafficLog };
+113
View File
@@ -0,0 +1,113 @@
const { Op } = require("sequelize");
const Visitor = require("../models/Visitor");
const logger = require("../utils/logger");
const PER_TUNNEL_LIMIT = 500;
const PAGE_SIZE = 50;
const FLUSH_INTERVAL = 500;
const SORTABLE = { last: "lastSeen", first: "firstSeen", requests: "requests", blocked: "blocked", ip: "ip" };
const summarise = row => ({
ip: row.ip,
intel: JSON.parse(row.intel),
requests: row.requests,
blocked: row.blocked,
reason: row.reason,
firstSeen: new Date(row.firstSeen).getTime(),
lastSeen: new Date(row.lastSeen).getTime(),
});
class Visitors {
constructor({ limit = PER_TUNNEL_LIMIT, interval = FLUSH_INTERVAL } = {}) {
this.limit = limit;
this.interval = interval;
this.pending = new Map();
this.timer = null;
}
start() {
if (this.timer) return;
this.timer = setInterval(() => this.flush(), this.interval);
this.timer.unref();
}
stop() {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
touch(tunnel, ip, intel) {
const key = `${tunnel}\n${ip}`;
const entry = this.pending.get(key) || { tunnel, ip, requests: 0, blocked: 0, reason: null, firstSeen: Date.now() };
entry.intel = intel;
entry.lastSeen = Date.now();
this.pending.set(key, entry);
return entry;
}
seen(tunnel, ip, intel) {
this.touch(tunnel, ip, intel).requests += 1;
}
blocked(tunnel, ip, intel, reason) {
const entry = this.touch(tunnel, ip, intel);
entry.blocked += 1;
entry.reason = reason;
}
async flush() {
if (!this.pending.size) return;
const batch = [...this.pending.values()];
this.pending.clear();
try {
for (const entry of batch) {
const intel = JSON.stringify(entry.intel);
const row = await Visitor.findOne({ where: { tunnel: entry.tunnel, ip: entry.ip } });
if (row) {
await Visitor.update({
intel,
requests: row.requests + entry.requests,
blocked: row.blocked + entry.blocked,
reason: entry.reason || row.reason,
lastSeen: new Date(entry.lastSeen),
}, { where: { id: row.id } });
} else {
await Visitor.create({ ...entry, intel, firstSeen: new Date(entry.firstSeen), lastSeen: new Date(entry.lastSeen) });
}
}
for (const tunnel of new Set(batch.map(entry => entry.tunnel))) await this.prune(tunnel);
} catch (err) {
logger.warn(`Could not store ${batch.length} visitor(s): ${err.message}`);
}
}
async prune(tunnel) {
const rows = await Visitor.findAll({
where: { tunnel }, order: [["lastSeen", "DESC"]], offset: this.limit, limit: 1, attributes: ["lastSeen"],
});
if (rows.length) await Visitor.destroy({ where: { tunnel, lastSeen: { [Op.lte]: rows[0].lastSeen } } });
}
async list(tunnel, { sort = "last", order = "desc", offset = 0, limit = PAGE_SIZE } = {}) {
await this.flush();
const rows = await Visitor.findAll({
where: { tunnel },
order: [[SORTABLE[sort] || "lastSeen", order === "asc" ? "ASC" : "DESC"], ["id", "DESC"]],
offset: Math.max(offset, 0),
limit: Math.min(Math.max(limit, 1), PER_TUNNEL_LIMIT),
});
return rows.map(summarise);
}
count(tunnel) {
return Visitor.count({ where: { tunnel } });
}
async forget(tunnel) {
for (const [key, entry] of this.pending) if (entry.tunnel === tunnel) this.pending.delete(key);
await Visitor.destroy({ where: { tunnel } });
}
}
module.exports = { Visitors };
+91
View File
@@ -0,0 +1,91 @@
const { randomBytes } = require("node:crypto");
const MAX_FRAME = 16 * 1024 * 1024;
class FrameParser {
constructor(onMessage, { skipHead = false } = {}) {
this.onMessage = onMessage;
this.buffer = Buffer.alloc(0);
this.fragments = null;
this.dead = false;
this.awaitingHead = skipHead;
}
push(chunk) {
if (this.dead) return;
this.buffer = this.buffer.length ? Buffer.concat([this.buffer, chunk]) : chunk;
if (this.awaitingHead) {
const end = this.buffer.indexOf("\r\n\r\n");
if (end === -1) return;
this.buffer = this.buffer.subarray(end + 4);
this.awaitingHead = false;
}
this.drain();
}
drain() {
for (;;) {
const buffer = this.buffer;
if (buffer.length < 2) return;
const fin = (buffer[0] & 0x80) !== 0;
const opcode = buffer[0] & 0x0f;
const masked = (buffer[1] & 0x80) !== 0;
let length = buffer[1] & 0x7f;
let offset = 2;
if (length === 126) {
if (buffer.length < 4) return;
length = buffer.readUInt16BE(2);
offset = 4;
} else if (length === 127) {
if (buffer.length < 10) return;
length = Number(buffer.readBigUInt64BE(2));
offset = 10;
}
if (length > MAX_FRAME) {
this.dead = true;
this.buffer = Buffer.alloc(0);
return;
}
const start = offset + (masked ? 4 : 0);
if (buffer.length < start + length) return;
let payload = Buffer.from(buffer.subarray(start, start + length));
if (masked) {
const key = buffer.subarray(offset, offset + 4);
for (let i = 0; i < length; i++) payload[i] ^= key[i & 3];
}
this.buffer = buffer.subarray(start + length);
if (opcode >= 8) {
this.onMessage(opcode, payload);
} else if (opcode === 0) {
if (!this.fragments) continue;
this.fragments.parts.push(payload);
if (fin) {
const { opcode: first, parts } = this.fragments;
this.fragments = null;
this.onMessage(first, Buffer.concat(parts));
}
} else if (fin) {
this.onMessage(opcode, payload);
} else {
this.fragments = { opcode, parts: [payload] };
}
}
}
}
const encodeFrame = (opcode, payload, masked) => {
const length = payload.length;
const header = [0x80 | opcode];
if (length < 126) header.push(length);
else if (length < 65536) header.push(126, length >> 8, length & 0xff);
else header.push(127, 0, 0, 0, 0, length >>> 24, (length >>> 16) & 0xff, (length >>> 8) & 0xff, length & 0xff);
if (!masked) return Buffer.concat([Buffer.from(header), payload]);
header[1] |= 0x80;
const key = randomBytes(4);
const body = Buffer.allocUnsafe(length);
for (let i = 0; i < length; i++) body[i] = payload[i] ^ key[i & 3];
return Buffer.concat([Buffer.from(header), key, body]);
};
module.exports = { FrameParser, encodeFrame };
+104
View File
@@ -0,0 +1,104 @@
const { Op } = require("sequelize");
const Frame = require("../models/Frame");
const logger = require("../utils/logger");
const MAX_PAYLOAD = 16 * 1024;
const PER_CONNECTION = 500;
const FLUSH_INTERVAL = 500;
const summarise = row => ({
id: row.id,
direction: row.direction,
opcode: row.opcode,
time: new Date(row.time).getTime(),
bytes: row.bytes,
truncated: !!row.truncated,
payload: row.payload ? Buffer.from(row.payload).toString("base64") : null,
});
class FrameLog {
constructor() {
this.pending = [];
this.open = new Map();
this.timer = null;
}
start() {
if (this.timer) return;
this.timer = setInterval(() => this.flush(), FLUSH_INTERVAL);
this.timer.unref();
}
stop() {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
opened(connection, writers) {
this.open.set(connection, writers);
}
closed(connection) {
this.open.delete(connection);
}
isOpen(connection) {
return this.open.has(connection);
}
inject(tunnel, connection, direction, payload) {
const writers = this.open.get(connection);
if (!writers) return false;
writers[direction](payload);
this.record(tunnel, connection, direction, 1, payload);
return true;
}
record(tunnel, connection, direction, opcode, payload) {
this.pending.push({
tunnel, connection, direction, opcode,
time: new Date(),
bytes: payload.length,
payload: payload.length ? payload.subarray(0, MAX_PAYLOAD) : null,
truncated: payload.length > MAX_PAYLOAD,
});
}
async flush() {
if (!this.pending.length) return;
const batch = this.pending;
this.pending = [];
try {
await Frame.bulkCreate(batch);
for (const connection of new Set(batch.map(row => row.connection))) await this.prune(connection);
} catch (err) {
logger.warn(`Could not store ${batch.length} frame(s): ${err.message}`);
}
}
async prune(connection) {
const rows = await Frame.findAll({ where: { connection }, order: [["id", "DESC"]], offset: PER_CONNECTION, limit: 1, attributes: ["id"] });
if (rows.length) await Frame.destroy({ where: { connection, id: { [Op.lte]: rows[0].id } } });
}
async list(tunnel, connection, after = 0) {
await this.flush();
const where = { tunnel, connection };
if (after) where.id = { [Op.gt]: after };
const rows = await Frame.findAll({ where, order: [["id", "ASC"]], limit: PER_CONNECTION });
return rows.map(summarise);
}
async forConnections(tunnel, connections) {
await this.flush();
const rows = await Frame.findAll({ where: { tunnel, connection: connections }, order: [["id", "ASC"]] });
const grouped = new Map();
for (const row of rows) {
if (!grouped.has(row.connection)) grouped.set(row.connection, []);
grouped.get(row.connection).push(summarise(row));
}
return grouped;
}
}
module.exports = { FrameLog };