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

+36
View File
@@ -0,0 +1,36 @@
const accounts = require("../lib/accounts");
const totp = require("../lib/totp");
const logger = require("../utils/logger");
module.exports.login = async (sessions, { username, password, code }, meta) => {
if (!await accounts.count()) return { code: 409, message: "The server has not been set up yet" };
const account = await accounts.checkCredentials({ username, password });
if (!account) return { code: 401, message: "Username or password incorrect" };
if (account.totpEnabled) {
if (!code) return { code: 202, message: "This account asks for a code from your authenticator" };
if (!totp.verify(account.totpSecret, code)) return { code: 401, message: "That code is not right or has expired" };
}
const token = await sessions.create(account.id, meta);
logger.info(`${account.username} logged in`, { ip: meta.ip });
return { token, username: account.username, role: account.role };
};
module.exports.accountFromCredentials = credentials => accounts.checkCredentials(credentials);
module.exports.checkAccountCredentials = async credentials => {
const account = await accounts.checkCredentials(credentials);
return !!account && !account.totpEnabled;
};
module.exports.logout = (sessions, token) => sessions.remove(token);
module.exports.currentUser = session => ({
id: session.account.id,
username: session.username,
role: session.role,
totpEnabled: !!session.account.totpEnabled,
createdAt: session.createdAt,
});
+109
View File
@@ -0,0 +1,109 @@
const { WebSocketServer } = require("ws");
const { MuxSession } = require("../lib/MuxSession");
const { attachJoiner } = require("./relay");
const { randomToken } = require("../utils/ids");
const logger = require("../utils/logger");
const { summarizePolicy } = require("../lib/access");
const invites = require("../lib/invites");
const packageJson = require("../../package.json");
const PROTOCOL_VERSION = 1;
const HANDSHAKE_TIMEOUT = 15_000;
const createControlServer = ({ config, auth, registry, connections, intel, visitors }) => {
const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: 1024 * 1024 });
const fail = (session, code, message, wsCode = 4000) => {
session.sendControl({ type: "error", code, message });
session.close(wsCode, code);
};
wss.on("connection", (ws, req) => {
const forwarded = config.trustProxy && req.headers["x-forwarded-for"]
? String(req.headers["x-forwarded-for"]).split(",")[0].trim()
: null;
const session = new MuxSession(ws, { parity: 0, name: `cli ${req.socket.remoteAddress}` });
session.client = { id: randomToken(12), ip: forwarded || req.socket.remoteAddress || "", connectedAt: Date.now() };
const headerToken = auth.bearerFromHeaders(req.headers);
let state = "hello";
let role = null;
const timer = setTimeout(() => { if (state !== "ready") fail(session, "bad_request", "handshake timeout"); }, HANDSHAKE_TIMEOUT);
session.once("close", () => clearTimeout(timer));
let queue = Promise.resolve();
const handle = async message => {
try {
if (message.type === "bye") {
session.saidBye = true;
session.close(1000, "bye");
return;
}
if (state === "hello") {
if (message.type !== "hello") return fail(session, "bad_request", "expected hello");
if (message.version !== PROTOCOL_VERSION) return fail(session, "unsupported_version", `unsupported protocol version ${message.version}`);
role = message.role === "joiner" ? "joiner" : message.role === "owner" ? "owner" : null;
if (!role) return fail(session, "bad_request", "role must be owner or joiner");
if (role === "owner") {
const device = await auth.deviceFor(headerToken || message.token);
if (!device) return fail(session, "unauthorized", "invalid token", 4401);
session.account = await auth.accountFor(device);
if (!session.account) return fail(session, "unauthorized", "the account behind this device is gone", 4401);
session.credential = device.credential;
if (device.guest) {
session.guest = device.guest.label;
await invites.used(device.guest);
}
}
session.sendControl({ type: "hello", version: PROTOCOL_VERSION, server: `frislit/${packageJson.version}`, baseDomain: config.baseDomain });
state = "setup";
return;
}
if (state === "setup") {
if (role === "owner") {
if (message.type !== "register") return fail(session, "bad_request", "expected register");
const { tunnel, resumed } = await registry.register(session, message);
state = "ready";
session.sendControl({
type: "registered",
id: tunnel.id,
mode: tunnel.mode,
url: registry.publicUrl(tunnel),
customUrls: registry.customUrls(tunnel),
persistent: tunnel.persistent,
access: summarizePolicy(tunnel.policy),
shareCode: tunnel.shareCode,
connectUrl: registry.connectUrl(tunnel),
resumeToken: tunnel.resumeToken,
resumed,
});
return;
}
if (message.type !== "join") return fail(session, "bad_request", "expected join");
const tunnel = registry.join(session, message.code);
state = "ready";
attachJoiner(tunnel, session, { connections, intel, visitors });
session.sendControl({ type: "joined", id: tunnel.id, port: tunnel.target.port, online: tunnel.online });
logger.info(`Joiner attached to ${tunnel.id}`, { from: req.socket.remoteAddress });
}
} catch (err) {
fail(session, err.code || "bad_request", err.message);
}
};
session.on("control", message => {
queue = queue.then(() => handle(message)).catch(err => logger.error(`control failed: ${err.stack || err}`));
});
session.on("stream", stream => {
if (role !== "joiner" || state !== "ready") stream.destroy(new Error("unexpected stream"));
});
});
return {
handleUpgrade: (req, socket, head) => wss.handleUpgrade(req, socket, head, ws => wss.emit("connection", ws, req)),
close: () => wss.close(),
};
};
module.exports = { createControlServer };
+304
View File
@@ -0,0 +1,304 @@
const { requestInfo, classifyHost, proxyRequest, proxyUpgrade, QUERY_PARAM, REPLAY_IP } = require("../lib/proxy");
const { SERVICE_WORKER_SOURCE, SW_PATH, injectedScript } = require("../lib/browser");
const { evaluate, isRestricted, accountAllowed, tokenFromRequest: accessToken, basicCredentials, cookieFor } = require("../lib/access");
const { verifyPassword } = require("../utils/password");
const { accountFromCredentials } = require("./auth");
const { sendJson } = require("../utils/html");
const { sendAppState } = require("../utils/pages");
const { sendFile, sendIndex } = require("../utils/static");
const { createApp } = require("../utils/router");
const { authenticate, requireAdmin } = require("../middlewares/auth");
const { NAME_REGEX } = require("../utils/ids");
const logger = require("../utils/logger");
const UI_PREFIX = "/@frislit";
const API_PREFIX = "/@frislit/api";
const SELECT_PAGE = "/@frislit/select";
const GATE_PATH = "/@frislit/gate";
const wantsHtml = req => /\btext\/html\b/.test(req.headers.accept || "");
const ACME_PREFIX = "/.well-known/acme-challenge/";
const FLAGS = ["tor", "vpn", "datacenter", "blocklisted"];
const createRouter = ({ config, auth, registry, traffic, visitors, breakpoints, connections, access, stats, devices, sessions, attempts, certificates, domains, quotas, frames, intel, control }) => {
const announce = (tunnel, entry) => {
if (!tunnel.session || tunnel.session.closed) return;
const { request, response, ...rest } = entry;
const details = intel.lookup(entry.ip);
tunnel.session.sendControl({ type: "request", ...rest, country: details.country, org: details.org, flags: FLAGS.filter(flag => details[flag]) });
};
const record = (tunnel, entry) => {
entry.intel = intel.lookup(entry.ip);
if (entry.ip !== REPLAY_IP) visitors.seen(tunnel.id, entry.ip, entry.intel);
traffic.record(tunnel.id, entry);
stats.recordRequest(tunnel.id);
};
const onRequest = tunnel => entry => {
announce(tunnel, entry);
record(tunnel, entry);
};
const websocket = tunnel => ({
open: (entry, writers) => {
record(tunnel, entry);
frames.opened(entry.connection, writers);
},
frame: (connection, direction, opcode, payload) => frames.record(tunnel.id, connection, direction, opcode, payload),
close: (connection, entry) => {
frames.closed(connection);
traffic.finish(connection, entry.duration).catch(() => null);
announce(tunnel, entry);
},
});
const api = createApp();
api.use(API_PREFIX, require("../routes/service"));
api.use(`${API_PREFIX}/setup`, require("../routes/setup"));
api.use(`${API_PREFIX}/auth`, require("../routes/auth"));
api.use(`${API_PREFIX}/tunnels`, authenticate, require("../routes/tunnels"));
api.use(`${API_PREFIX}/persistent`, authenticate, require("../routes/persistent"));
api.use(`${API_PREFIX}/quotas`, authenticate, require("../routes/quotas"));
api.use(`${API_PREFIX}/settings`, authenticate, require("../routes/settings"));
api.use(`${API_PREFIX}/devices`, authenticate, require("../routes/devices"));
api.use(`${API_PREFIX}/invites`, authenticate, require("../routes/invites"));
api.use(`${API_PREFIX}/accounts`, authenticate, requireAdmin, require("../routes/accounts"));
api.use(`${API_PREFIX}/tls`, authenticate, requireAdmin, require("../routes/tls"));
api.use(`${API_PREFIX}/oidc`, authenticate, requireAdmin, require("../routes/oidc"));
const notFound = (req, res, id) => sendAppState(req, res, 404, { kind: "missing", id });
const offline = (req, res, id) => sendAppState(req, res, 502, { kind: "offline", id });
const accepts = async (policy, credentials, tunnel) => {
if (policy.auth === "password") return verifyPassword(credentials.password, policy.passwordHash);
const account = await accountFromCredentials(credentials);
if (!account || account.totpEnabled) return false;
return accountAllowed(policy, account.id, tunnel.accountId);
};
const denial = async (req, res, info, tunnel) => {
const policy = tunnel.policy;
if (!isRestricted(policy)) return null;
const details = intel.lookup(info.clientIp);
const reason = evaluate(policy, info.clientIp, details);
if (reason) {
visitors.blocked(tunnel.id, info.clientIp, details, reason);
return { deny: () => sendAppState(req, res, 403, { kind: "blocked", id: tunnel.id, ip: info.clientIp, reason }) };
}
if (policy.auth === "none") return null;
if (access.allows(accessToken(req), tunnel.id)) return null;
const key = `gate:${tunnel.id}:${info.clientIp}`;
const credentials = attempts.blocked(key) ? null : basicCredentials(req);
if (credentials && await accepts(policy, credentials, tunnel)) {
attempts.forget(key);
return { cookie: cookieFor(access.create(tunnel.id), info.secure) };
}
if (credentials) {
attempts.record(key);
logger.warn(`Failed gate attempt for ${tunnel.id}`, { ip: info.clientIp });
}
// Browsers always send sec-fetch-mode; challenging them turns the 401 into Firefox's auth dialog.
const headers = req.headers["sec-fetch-mode"] ? {} : { "WWW-Authenticate": `Basic realm="${tunnel.id}", charset="UTF-8"` };
const authorize = policy.auth === "frislit" ? `${config.publicUrl}${API_PREFIX}/gate/${tunnel.id}/authorize` : null;
return { deny: () => sendAppState(req, res, 401, { kind: "gate", id: tunnel.id, auth: policy.auth, authorize }, headers) };
};
const completeGate = (req, res, info, url) => {
const to = url.searchParams.get("to") || "";
const token = access.redeem(url.searchParams.get("code"), info.hostname);
res.writeHead(302, { Location: /^\/(?![/\\])/.test(to) ? to : "/", "Cache-Control": "no-store", ...(token && { "Set-Cookie": cookieFor(token, info.secure) }) });
res.end();
};
const tunnelFor = (id, modes) => {
const tunnel = registry.get(id);
if (!tunnel || !modes.includes(tunnel.mode)) return { error: "not-found" };
if (!tunnel.online) return { error: "offline", tunnel };
return { tunnel };
};
const noTunnel = (req, res, location = SELECT_PAGE) => {
if (!wantsHtml(req)) return sendJson(res, 404, { error: "no_tunnel_selected" });
res.writeHead(302, { Location: location, "Cache-Control": "no-store" });
res.end();
};
const handleUi = async (req, res, info, pathname) => {
if (pathname === API_PREFIX || pathname.startsWith(`${API_PREFIX}/`)) {
const handled = await api.handle(req, res, pathname, { config, auth, registry, traffic, visitors, breakpoints, connections, access, stats, devices, sessions, attempts, certificates, domains, quotas, frames, intel, onRequest, info });
if (!handled) sendJson(res, 404, { error: "not_found" });
return;
}
if (!["GET", "HEAD"].includes(req.method)) return sendJson(res, 405, { error: "method_not_allowed" });
const relative = pathname === UI_PREFIX ? "" : pathname.slice(UI_PREFIX.length + 1);
if (relative && !relative.includes("..") && sendFile(req, res, relative)) return;
sendIndex(req, res);
};
const pathTunnel = id => {
if (!NAME_REGEX.test(id)) return null;
const tunnel = registry.get(id);
return tunnel && tunnel.mode === "path" ? tunnel : null;
};
const serveSelected = async (req, res, info, id) => {
const tunnel = pathTunnel(id);
if (!tunnel) return notFound(req, res, id);
if (!tunnel.online) return offline(req, res, id);
const gate = await denial(req, res, info, tunnel);
if (gate?.deny) return gate.deny();
return proxyRequest(req, res, tunnel, info,
{ pathMode: true, inject: injectedScript(id), onRequest: onRequest(tunnel), setCookie: gate?.cookie, breakpoints });
};
const hostFor = hostname => {
const host = classifyHost(hostname, config.baseDomain);
if (host.kind !== "unknown") return host;
const name = domains.tunnelFor(hostname);
return name ? { kind: "custom", id: name } : host;
};
const hostTunnel = host => tunnelFor(host.id, host.kind === "custom" ? ["subdomain", "path"] : ["subdomain"]);
const acmeChallenge = (req, res, pathname) => {
const response = certificates?.challengeResponse(pathname.slice(ACME_PREFIX.length));
if (!response) return false;
res.writeHead(200, { "Content-Type": "application/octet-stream", "Content-Length": Buffer.byteLength(response) });
res.end(req.method === "HEAD" ? undefined : response);
return true;
};
const handleRedirect = (req, res) => {
const url = new URL(req.url, "http://frislit.invalid");
if (url.pathname.startsWith(ACME_PREFIX) && acmeChallenge(req, res, url.pathname)) return;
const host = String(req.headers.host || config.baseDomain).replace(/:\d+$/, "").toLowerCase();
if (!certificates?.covers() && !certificates?.secureContextFor(host)) return handleRequest(req, res);
const publicPort = config.publicUrlConfigured ? new URL(config.publicUrlConfigured).port : null;
const port = publicPort === null
? (config.httpsPort === 443 ? "" : `:${config.httpsPort}`)
: publicPort ? `:${publicPort}` : "";
res.writeHead(308, { Location: `https://${host}${port}${req.url}`, "Cache-Control": "no-store" });
res.end();
};
const handleRequest = async (req, res) => {
const info = requestInfo(req, config);
const url = new URL(req.url, "http://frislit.invalid");
const pathname = url.pathname;
if (pathname.startsWith(ACME_PREFIX) && acmeChallenge(req, res, pathname)) return;
if (pathname === GATE_PATH && config.ready && !config.setupRequired) return completeGate(req, res, info, url);
const isUi = pathname === UI_PREFIX || pathname.startsWith(`${UI_PREFIX}/`);
if (!config.ready || config.setupRequired) {
if (isUi) return handleUi(req, res, info, pathname);
return noTunnel(req, res, `${UI_PREFIX}/`);
}
const host = hostFor(info.hostname);
if (isUi && host.kind !== "custom") {
if (pathname === SW_PATH) {
if (!["GET", "HEAD"].includes(req.method)) return sendJson(res, 405, { error: "method_not_allowed" });
res.writeHead(200, {
"Content-Type": "text/javascript; charset=utf-8",
"Service-Worker-Allowed": "/",
"Cache-Control": "no-cache",
"Content-Length": Buffer.byteLength(SERVICE_WORKER_SOURCE),
});
return res.end(req.method === "HEAD" ? undefined : SERVICE_WORKER_SOURCE);
}
return handleUi(req, res, info, pathname);
}
if (host.kind === "subdomain" || host.kind === "custom") {
const { tunnel, error } = hostTunnel(host);
if (error === "not-found" && host.kind !== "custom") return notFound(req, res, host.id);
if (error) return offline(req, res, host.id);
const gate = await denial(req, res, info, tunnel);
if (gate?.deny) return gate.deny();
return proxyRequest(req, res, tunnel, info,
{ pathMode: false, inject: null, onRequest: onRequest(tunnel), setCookie: gate?.cookie, breakpoints });
}
if (host.kind !== "base") return noTunnel(req, res, SELECT_PAGE);
const selection = /^\/@([^/]+)(\/.*)?$/.exec(pathname);
if (selection) {
const id = selection[1].toLowerCase();
if (!pathTunnel(id)) return notFound(req, res, id);
return sendAppState(req, res, 200, { kind: "attach", id, to: `${selection[2] || "/"}${url.search}` });
}
if (url.searchParams.has(QUERY_PARAM)) {
return serveSelected(req, res, info, String(url.searchParams.get(QUERY_PARAM)).toLowerCase());
}
return noTunnel(req, res);
};
const handleUpgrade = (req, socket, head) => {
const info = requestInfo(req, config);
const pathname = new URL(req.url, "http://frislit.invalid").pathname;
const reject = (status, text) => {
socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
socket.destroy();
};
if (!config.ready || config.setupRequired) return reject(503, "Setup required");
const host = hostFor(info.hostname);
if (host.kind === "base" && pathname === "/@frislit/ws") return control.handleUpgrade(req, socket, head);
let target;
if (host.kind === "subdomain" || host.kind === "custom") target = hostTunnel(host);
else if (host.kind === "base") {
if (pathname.startsWith("/@")) return reject(404, "Not Found");
const selected = new URL(req.url, "http://frislit.invalid").searchParams.get(QUERY_PARAM);
if (!selected) return reject(404, "No tunnel selected");
target = tunnelFor(String(selected).toLowerCase(), ["path"]);
} else return reject(404, "Not Found");
if (target.error === "not-found" && host.kind !== "custom") return reject(404, "Tunnel not found");
if (target.error) return reject(502, "Tunnel offline");
if (isRestricted(target.tunnel.policy)) {
const details = intel.lookup(info.clientIp);
const reason = evaluate(target.tunnel.policy, info.clientIp, details);
if (reason) {
visitors.blocked(target.tunnel.id, info.clientIp, details, reason);
return reject(403, "Forbidden");
}
if (target.tunnel.policy.auth !== "none" && !access.allows(accessToken(req), target.tunnel.id)) {
return reject(401, "Unauthorized");
}
}
proxyUpgrade(req, socket, head, target.tunnel, info, { pathMode: host.kind === "base", ws: websocket(target.tunnel) });
};
return {
handleRedirect,
handleRequest: (req, res) => {
Promise.resolve()
.then(() => handleRequest(req, res))
.catch(err => {
logger.error(`request failed: ${err.stack || err}`);
if (res.writableEnded) return;
if (!res.headersSent) res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Internal error");
});
},
handleUpgrade: (req, socket, head) => {
try {
handleUpgrade(req, socket, head);
} catch (err) {
logger.error(`upgrade failed: ${err.stack || err}`);
socket.destroy();
}
},
};
};
module.exports = { createRouter };
+137
View File
@@ -0,0 +1,137 @@
const persistent = require("../lib/persistent");
const { buildPolicy, describePolicy, emptyPolicy } = require("../lib/access");
const { announceAccess } = require("./tunnels");
const ids = require("../utils/ids");
const NOT_FOUND = { code: 404, message: "Persistent tunnel not found" };
const isAdmin = viewer => viewer.role === "admin";
const policyFrom = (input, previous) => {
try {
return { policy: buildPolicy({ ...input, password: input.password || undefined }, previous) };
} catch (err) {
return { code: err.code === "bad_request" ? 400 : 500, message: err.message };
}
};
const applyLive = (req, name, policy) => {
const live = req.registry.get(name);
if (!live) return;
live.policy = policy;
req.access.forget(name);
announceAccess(live);
};
const serialize = async (req, definition) => {
const live = req.registry.get(definition.name);
return {
name: definition.name,
owner: definition.owner,
accountId: definition.accountId,
access: describePolicy(definition.policy),
createdAt: definition.createdAt,
online: !!live?.online,
live: !!live,
url: req.registry.urlFor(definition.name),
domains: await req.domains.listFor(definition.name),
};
};
const definitionFor = async (req, name) => {
const definition = await persistent.load(name);
if (!definition || (!isAdmin(req.session) && definition.accountId !== req.session.account.id)) return null;
return definition;
};
const domainOf = async (req, name, hostname) => {
if (!await definitionFor(req, name)) return null;
const normalized = String(hostname || "").trim().toLowerCase();
return req.domains.tunnelFor(normalized) === name ? normalized : null;
};
module.exports.list = async req => {
const definitions = await persistent.list(isAdmin(req.session) ? null : req.session.account.id);
return Promise.all(definitions.map(definition => serialize(req, definition)));
};
module.exports.get = async (req, name) => {
const definition = await definitionFor(req, name);
if (!definition) return NOT_FOUND;
return { tunnel: await serialize(req, definition) };
};
module.exports.create = async (req, input) => {
const name = String(input.name || "").trim().toLowerCase();
if (!ids.isValidName(name)) return { code: 400, message: "Use 3-32 characters a-z, 0-9 or \"-\" for the name" };
const live = req.registry.get(name);
if (live && live.accountId !== req.session.account.id && !isAdmin(req.session)) {
return { code: 409, message: `"${name}" is in use by another account` };
}
const wantsPolicy = ["auth", "password", "allow", "block"].some(key => input[key] !== undefined);
const { policy, code, message } = wantsPolicy ? policyFrom(input, live ? live.policy : emptyPolicy()) : { policy: live ? live.policy : emptyPolicy() };
if (code) return { code, message };
const accountId = live ? live.accountId : req.session.account.id;
let definition;
try {
await req.quotas.enforce(accountId, "persistent", (await persistent.list(accountId)).length);
definition = await persistent.create(name, accountId, policy);
} catch (err) {
return { code: { name_taken: 409, quota_exceeded: 429 }[err.code] || 500, message: err.message };
}
definition.owner = live ? live.owner : req.session.account.username;
if (live) {
live.persistent = true;
applyLive(req, name, policy);
}
return { message: `${name} is now persistent`, tunnel: await serialize(req, definition) };
};
module.exports.updateAccess = async (req, name, input) => {
const definition = await definitionFor(req, name);
if (!definition) return NOT_FOUND;
const { policy, code, message } = policyFrom(input, definition.policy);
if (code) return { code, message };
await persistent.savePolicy(name, policy);
applyLive(req, name, policy);
return { message: "Access updated", access: describePolicy(policy) };
};
module.exports.remove = async (req, name) => {
if (!await definitionFor(req, name)) return NOT_FOUND;
await req.domains.removeForTunnel(name);
await persistent.remove(name);
const live = req.registry.get(name);
if (live) live.persistent = false;
return { message: `${name} is no longer persistent` };
};
module.exports.addDomain = async (req, name, input) => {
const definition = await definitionFor(req, name);
if (!definition) return NOT_FOUND;
try {
await req.quotas.enforce(definition.accountId, "domains", await req.domains.countFor(definition.accountId));
const domain = await req.domains.add(input.hostname, name, definition.accountId);
return { message: `${domain.hostname} added`, domain };
} catch (err) {
return { code: { bad_request: 400, conflict: 409, quota_exceeded: 429 }[err.code] || 500, message: err.message };
}
};
module.exports.checkDomain = async (req, name, hostname) => {
const domain = await domainOf(req, name, hostname);
if (!domain) return { code: 404, message: "Domain not found" };
await req.domains.check(domain);
const current = (await req.domains.listFor(name)).find(entry => entry.hostname === domain);
return { message: current.state === "active" ? `${domain} is active` : `${domain} checked`, domain: current };
};
module.exports.removeDomain = async (req, name, hostname) => {
const domain = await domainOf(req, name, hostname);
if (!domain) return { code: 404, message: "Domain not found" };
await req.domains.remove(domain);
return { message: `${domain} removed` };
};
+24
View File
@@ -0,0 +1,24 @@
const persistent = require("../lib/persistent");
const usageFor = async (req, accountId) => ({
tunnels: [...req.registry.tunnels.values()].filter(tunnel => tunnel.accountId === accountId).length,
persistent: (await persistent.list(accountId)).length,
domains: await req.domains.countFor(accountId),
traffic: await req.quotas.trafficFor(accountId),
});
const mine = async req => ({
defaults: req.quotas.defaults,
limits: await req.quotas.limitsFor(req.account.id),
usage: await usageFor(req, req.account.id),
});
const saveDefaults = async (req, input) => {
try {
return { message: "Limits saved", defaults: await req.quotas.saveDefaults(input) };
} catch (err) {
return { code: err.code === "bad_request" ? 400 : 500, message: err.message };
}
};
module.exports = { usageFor, mine, saveDefaults };
+81
View File
@@ -0,0 +1,81 @@
const { PassThrough } = require("node:stream");
const logger = require("../utils/logger");
const ANNOUNCE_DELAY = 150;
const tap = observe => new PassThrough({
transform(chunk, _encoding, callback) {
observe(chunk);
callback(null, chunk);
},
});
const summary = entry => ({
key: entry.key,
protocol: entry.protocol,
ip: entry.ip,
country: entry.intel.country,
org: entry.intel.org,
client: entry.client,
bytesIn: entry.bytesIn,
bytesOut: entry.bytesOut,
duration: (entry.endedAt || Date.now()) - entry.startedAt,
reason: entry.reason,
detail: entry.detail,
});
const relayStream = (tunnel, session, joinerStream, meta, { connections, intel, visitors }) => {
if (!tunnel.online) {
joinerStream.destroy(new Error("owner offline"));
return;
}
const protocol = meta.protocol === "udp" ? "udp" : "tcp";
const ip = session.client.ip;
const details = intel.lookup(ip);
const entry = connections.open(tunnel.id, { protocol, ip, intel: details, client: meta.remote || "", joiner: session.client.id });
visitors.seen(tunnel.id, ip, details);
const ownerStream = tunnel.session.open({ protocol, remote: meta.remote || "" });
const announce = event => {
if (tunnel.session && !tunnel.session.closed) tunnel.session.sendControl({ type: "connection", event, ...summary(entry) });
};
let announced = false;
const opened = () => {
if (announced) return;
announced = true;
clearTimeout(timer);
announce("open");
};
const timer = setTimeout(opened, ANNOUNCE_DELAY);
const observe = direction => chunk => {
connections.data(entry, direction, chunk);
if (entry.detail) opened();
};
if (protocol === "udp") {
joinerStream.on("datagram", data => { observe("in")(data); ownerStream.sendDatagram(data); });
ownerStream.on("datagram", data => { observe("out")(data); joinerStream.sendDatagram(data); });
}
joinerStream.pipe(tap(observe("in"))).pipe(ownerStream);
ownerStream.pipe(tap(observe("out"))).pipe(joinerStream);
let reason = null;
const finish = cause => {
if (!reason) reason = cause;
if (entry.endedAt) return;
connections.close(entry, reason);
opened();
announce("close");
};
joinerStream.on("error", () => { finish(session.closed ? "client disconnected" : "error"); ownerStream.destroy(); });
ownerStream.on("error", () => { finish(tunnel.session.closed ? "tunnel closed" : "error"); joinerStream.destroy(); });
joinerStream.on("close", () => { finish("client closed"); ownerStream.destroy(); });
ownerStream.on("close", () => { finish("app closed"); joinerStream.destroy(); });
logger.debug(`relay ${tunnel.id}: ${protocol} stream ${joinerStream.id} -> ${ownerStream.id}`);
};
const attachJoiner = (tunnel, session, context) => {
session.on("stream", (stream, meta) => relayStream(tunnel, session, stream, meta, context));
};
module.exports = { attachJoiner };
+38
View File
@@ -0,0 +1,38 @@
const settingsStore = require("../lib/settings");
const { applySettings, UI_SETTING_KEYS } = require("../utils/config");
const { verifyPassword } = require("../utils/password");
const accounts = require("../lib/accounts");
const { pickSettings } = require("./setup");
const logger = require("../utils/logger");
module.exports.getSettings = config => ({
settings: Object.fromEntries(UI_SETTING_KEYS.map(key => [key, key === "publicUrl" ? config.publicUrlConfigured : config[key]])),
sources: Object.fromEntries(UI_SETTING_KEYS.map(key => [key, config.sources[key]])),
effectivePublicUrl: config.publicUrl,
listen: config.listen,
port: config.port,
configFile: config.configFile,
});
module.exports.updateSettings = async (config, body) => {
const settings = pickSettings(body);
if (!Object.keys(settings).length) return { code: 400, message: "No settings provided" };
try {
applySettings(config, settings);
} catch (err) {
return { code: 400, message: err.message };
}
await settingsStore.write(settings);
logger.info("Settings updated from the web UI", settings);
return module.exports.getSettings(config);
};
module.exports.changePassword = async (account, { currentPassword, newPassword }) => {
if (!await verifyPassword(typeof currentPassword === "string" ? currentPassword : "", account.passwordHash)) {
return { code: 401, message: "Current password is incorrect" };
}
const result = await accounts.update(account.id, { password: newPassword });
if (result.code) return result;
logger.info(`${account.username} changed the password`);
return { message: "Password changed" };
};
+51
View File
@@ -0,0 +1,51 @@
const settingsStore = require("../lib/settings");
const accounts = require("../lib/accounts");
const { applySettings, UI_SETTING_KEYS } = require("../utils/config");
const logger = require("../utils/logger");
module.exports.isSetupRequired = async () => !await accounts.count();
module.exports.getSetupStatus = async config => {
const setupRequired = await module.exports.isSetupRequired();
const status = { setupRequired, ready: config.ready };
if (!setupRequired) return status;
return {
...status,
settings: Object.fromEntries(UI_SETTING_KEYS.map(key => [key, key === "publicUrl" ? config.publicUrlConfigured : config[key]])),
sources: Object.fromEntries(UI_SETTING_KEYS.map(key => [key, config.sources[key]])),
};
};
module.exports.validateAccount = ({ username, password }) => accounts.validate({ username, password });
module.exports.pickSettings = body => {
const settings = {};
for (const key of UI_SETTING_KEYS) if (body[key] !== undefined) settings[key] = body[key];
if ("gracePeriod" in settings) settings.gracePeriod = Number(settings.gracePeriod);
if ("trustProxy" in settings) settings.trustProxy = settings.trustProxy === true || settings.trustProxy === "true";
return settings;
};
module.exports.completeSetup = async (config, { username, password, settings }) => {
if (!await module.exports.isSetupRequired()) return { code: 409, message: "Setup has already been completed" };
const accountError = accounts.validate({ username, password });
if (accountError) return { code: 400, message: accountError };
const picked = module.exports.pickSettings(settings || {});
const changed = Object.fromEntries(Object.entries(picked)
.filter(([key, value]) => value !== (key === "publicUrl" ? config.publicUrlConfigured : config[key])));
try {
applySettings(config, changed);
} catch (err) {
return { code: 400, message: err.message };
}
if (!config.ready) return { code: 400, message: "baseDomain is required" };
const created = await accounts.create({ username, password, role: "admin" });
if (created.code) return created;
await settingsStore.write(changed);
config.setupRequired = false;
logger.info(`Setup completed, admin account "${username}" created`);
return { message: "Setup complete", account: created.account };
};
+217
View File
@@ -0,0 +1,217 @@
const { endSession } = require("../lib/registry");
const { replayRequest } = require("../lib/proxy");
const { serialize } = require("../lib/breakpoints");
const { buildPolicy, describePolicy, summarizePolicy } = require("../lib/access");
const logger = require("../utils/logger");
const announceAccess = tunnel => {
if (tunnel.session && !tunnel.session.closed) tunnel.session.sendControl({ type: "access", access: summarizePolicy(tunnel.policy) });
};
module.exports.announceAccess = announceAccess;
const persistent = require("../lib/persistent");
const serializeTunnel = (registry, tunnel) => ({
id: tunnel.id,
mode: tunnel.mode,
target: tunnel.target.authority,
url: registry.publicUrl(tunnel),
customUrls: registry.customUrls(tunnel),
persistent: tunnel.persistent,
shareCode: tunnel.shareCode,
online: tunnel.online,
graceUntil: tunnel.graceUntil,
joiners: tunnel.joiners.size,
createdAt: tunnel.createdAt,
owner: tunnel.owner,
guest: tunnel.guest,
access: describePolicy(tunnel.policy),
});
const mayTouch = (tunnel, viewer) => !!tunnel && (viewer.role === "admin" || tunnel.accountId === viewer.account.id);
const serializeClients = tunnel => [...tunnel.joiners].map(session => ({
id: session.client?.id || "",
ip: session.client?.ip || "",
connectedAt: session.client?.connectedAt || null,
streams: session.streams ? session.streams.size : 0,
})).sort((a, b) => (a.connectedAt || 0) - (b.connectedAt || 0));
module.exports.mayTouch = mayTouch;
module.exports.getTunnel = async (registry, traffic, id, viewer) => {
const tunnel = registry.get(id);
if (!mayTouch(tunnel, viewer)) return null;
const base = { ...serializeTunnel(registry, tunnel), requests: await traffic.count(id) };
return tunnel.mode === "tcp" ? { ...base, clients: serializeClients(tunnel) } : base;
};
module.exports.listTunnels = (registry, viewer) =>
[...registry.tunnels.values()]
.filter(tunnel => mayTouch(tunnel, viewer))
.sort((a, b) => b.createdAt - a.createdAt)
.map(tunnel => serializeTunnel(registry, tunnel));
const tcpTunnel = (registry, id, viewer) => {
const tunnel = registry.get(id);
if (!mayTouch(tunnel, viewer)) return { code: 404, message: "Tunnel not found" };
if (tunnel.mode !== "tcp") return { code: 400, message: "Only tcp tunnels have clients" };
return { tunnel };
};
module.exports.disconnectClient = (registry, id, clientId, viewer) => {
const { tunnel, code, message } = tcpTunnel(registry, id, viewer);
if (code) return { code, message };
const session = [...tunnel.joiners].find(joiner => joiner.client?.id === clientId);
if (!session) return { code: 404, message: "Client not connected" };
endSession(session, "disconnected by the administrator");
tunnel.joiners.delete(session);
return { message: "Client disconnected" };
};
module.exports.disconnectAllClients = (registry, id, viewer) => {
const { tunnel, code, message } = tcpTunnel(registry, id, viewer);
if (code) return { code, message };
const count = tunnel.joiners.size;
for (const session of tunnel.joiners) endSession(session, "disconnected by the administrator");
tunnel.joiners.clear();
return { message: `Disconnected ${count} ${count === 1 ? "client" : "clients"}` };
};
module.exports.updateAccess = async (registry, access, id, input, viewer) => {
const tunnel = registry.get(id);
if (!mayTouch(tunnel, viewer)) return { code: 404, message: "Tunnel not found" };
try {
tunnel.policy = buildPolicy({ ...input, password: input.password || undefined }, tunnel.policy);
} catch (err) {
return { code: err.code === "bad_request" ? 400 : 500, message: err.message };
}
access.forget(id);
if (tunnel.persistent) await persistent.savePolicy(tunnel.id, tunnel.policy);
announceAccess(tunnel);
return { message: "Access updated", access: describePolicy(tunnel.policy) };
};
module.exports.updateMode = async (registry, id, input, viewer) => {
const tunnel = registry.get(id);
if (!mayTouch(tunnel, viewer)) return { code: 404, message: "Tunnel not found" };
if (tunnel.mode === "tcp") return { code: 400, message: "TCP tunnels have no forwarding mode" };
const mode = String(input.mode || "").toLowerCase();
if (!["path", "subdomain"].includes(mode)) return { code: 400, message: "mode must be path or subdomain" };
if (mode === "subdomain" && registry.config.managesTls && !registry.config.wildcard) {
return { code: 400, message: "Subdomain tunnels need a wildcard certificate: set the forwarding mode to subdomain first" };
}
tunnel.mode = mode;
if (tunnel.persistent) await persistent.saveMode(tunnel.id, mode);
logger.info(`Forwarding of ${tunnel.id} set to ${mode}`);
return { message: `Forwarding set to ${mode}`, mode, url: registry.publicUrl(tunnel) };
};
const METHOD = /^[A-Z]{3,10}$/;
const editedPart = (stored, input) => {
const part = { ...stored };
if (input.headers !== undefined) {
if (!Array.isArray(input.headers) || input.headers.some(pair => !Array.isArray(pair) || pair.length !== 2)) {
throw new Error("Headers must be a list of [name, value] pairs");
}
part.headers = input.headers.map(([name, value]) => [String(name).trim(), String(value).trim()]).filter(([name]) => name);
}
if (input.body !== undefined) {
const body = Buffer.from(String(input.body), "utf8");
part.body = body.length ? body.toString("base64") : null;
part.bytes = body.length;
part.truncated = false;
}
return part;
};
const edited = (stored, input) => {
const out = { ...stored, request: editedPart(stored.request, input) };
if (input.method !== undefined) {
const method = String(input.method).trim().toUpperCase();
if (!METHOD.test(method)) throw new Error("Invalid method");
out.method = method;
}
if (input.path !== undefined) {
const path = String(input.path).trim();
if (!path.startsWith("/")) throw new Error("The path must start with /");
out.path = path;
}
return out;
};
const editedResponse = (stored, input) => {
const out = editedPart(stored, input);
if (input.status !== undefined) {
const status = Number(input.status);
if (!Number.isInteger(status) || status < 100 || status > 599) throw new Error("Invalid status");
out.status = status;
}
return out;
};
const bufferOf = part => (part.body ? Buffer.from(part.body, "base64") : Buffer.alloc(0));
module.exports.replay = async (req, id, requestId, input) => {
const tunnel = req.registry.get(id);
if (!mayTouch(tunnel, req.session)) return { code: 404, message: "Tunnel not found" };
if (!tunnel.online) return { code: 502, message: "The tunnel is offline" };
const stored = await req.traffic.get(id, requestId);
if (!stored) return { code: 404, message: "That request is no longer stored" };
if (stored.kind === "ws") return { code: 400, message: "WebSocket connections cannot be replayed" };
let request;
try {
request = edited(stored, input);
} catch (err) {
return { code: 400, message: err.message };
}
if (request.request.truncated) return { code: 400, message: "The request body was too large to store" };
const status = await replayRequest(tunnel, request, req.onRequest(tunnel));
return { message: `Replayed, ${status}`, status };
};
module.exports.getBreakpoints = (req, id) => {
if (!mayTouch(req.registry.get(id), req.session)) return { code: 404, message: "Tunnel not found" };
return { rules: req.breakpoints.rulesFor(id), held: req.breakpoints.list(id), now: Date.now() };
};
module.exports.setBreakpoints = (req, id, input) => {
if (!mayTouch(req.registry.get(id), req.session)) return { code: 404, message: "Tunnel not found" };
try {
return { message: "Breakpoints updated", rules: req.breakpoints.setRules(id, input.rules) };
} catch (err) {
return { code: 400, message: err.message };
}
};
module.exports.resolveBreakpoint = (req, id, holdId, input) => {
if (!mayTouch(req.registry.get(id), req.session)) return { code: 404, message: "Tunnel not found" };
const held = req.breakpoints.get(id, holdId);
if (!held) return { code: 404, message: "That request is no longer waiting" };
if (input.action === "drop") {
req.breakpoints.settle(holdId, { action: "drop" });
return { message: "Dropped" };
}
const stored = serialize(held);
try {
if (held.phase === "response") {
const response = editedResponse(stored.response, input);
req.breakpoints.settle(holdId, { action: "continue", status: response.status, headers: response.headers, body: bufferOf(response) });
} else {
const request = edited(stored, input);
req.breakpoints.settle(holdId, { action: "continue", method: request.method, path: request.path, headers: request.request.headers, body: bufferOf(request.request) });
}
} catch (err) {
return { code: 400, message: err.message };
}
return { message: "Continued" };
};
module.exports.closeTunnel = (registry, id, viewer) => {
if (!mayTouch(registry.get(id), viewer)) return { code: 404, message: "Tunnel not found" };
registry.remove(id, "closed from the web UI");
return { message: "Tunnel closed" };
};