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

+40
View File
@@ -0,0 +1,40 @@
const WINDOW = 15 * 60 * 1000;
const MAX_FAILURES = 20;
const MAX_KEYS = 10_000;
class AttemptLimiter {
constructor({ window = WINDOW, max = MAX_FAILURES } = {}) {
this.window = window;
this.max = max;
this.failures = new Map();
this.sweeper = setInterval(() => this.sweep(), window);
this.sweeper.unref();
}
blocked(key) {
const entry = this.failures.get(key);
if (!entry) return false;
if (Date.now() - entry.since > this.window) { this.failures.delete(key); return false; }
return entry.count >= this.max;
}
record(key) {
const now = Date.now();
const entry = this.failures.get(key);
if (entry && now - entry.since <= this.window) { entry.count += 1; return; }
if (this.failures.size >= MAX_KEYS) this.sweep();
if (this.failures.size >= MAX_KEYS) this.failures.delete(this.failures.keys().next().value);
this.failures.set(key, { count: 1, since: now });
}
forget(key) {
this.failures.delete(key);
}
sweep() {
const now = Date.now();
for (const [key, entry] of this.failures) if (now - entry.since > this.window) this.failures.delete(key);
}
}
module.exports = { AttemptLimiter };
+34
View File
@@ -0,0 +1,34 @@
const crypto = require("node:crypto");
const accounts = require("../lib/accounts");
const invites = require("../lib/invites");
const safeEqual = (a, b) => {
const ha = crypto.createHash("sha256").update(String(a)).digest();
const hb = crypto.createHash("sha256").update(String(b)).digest();
return crypto.timingSafeEqual(ha, hb);
};
const createAuth = devices => ({
deviceFor: async presented => {
const device = await devices.verify(presented);
if (device) return { accountId: device.accountId, credential: `device:${device.id}` };
const invite = await invites.verify(presented);
return invite && { accountId: invite.accountId, credential: `invite:${invite.id}`, guest: invite };
},
accountFor: async device => {
const account = await accounts.byId(device.accountId);
return account ? { id: account.id, username: account.username, role: account.role } : null;
},
verifyToken: async presented => !!await devices.verify(presented),
bearerFromHeaders: headers => {
const value = headers["authorization"];
if (!value) return null;
const match = /^Bearer\s+(.+)$/i.exec(value.trim());
return match ? match[1].trim() : null;
},
});
module.exports = { createAuth, safeEqual };
+149
View File
@@ -0,0 +1,149 @@
const fs = require("node:fs");
const path = require("node:path");
const yaml = require("js-yaml");
const logger = require("./logger");
const DEFAULTS = {
listen: "0.0.0.0",
port: 8080,
httpsPort: 443,
redirectPort: 80,
baseDomain: "",
publicUrl: "",
tlsMode: "proxy",
acmeDirectoryUrl: "",
trustProxy: false,
httpMode: "subdomain",
gracePeriod: 30,
};
const ENV = {
listen: "FRISLIT_LISTEN",
port: "FRISLIT_PORT",
httpsPort: "FRISLIT_HTTPS_PORT",
redirectPort: "FRISLIT_REDIRECT_PORT",
tlsMode: "FRISLIT_TLS_MODE",
acmeDirectoryUrl: "FRISLIT_ACME_DIRECTORY",
baseDomain: "FRISLIT_BASE_DOMAIN",
publicUrl: "FRISLIT_PUBLIC_URL",
trustProxy: "FRISLIT_TRUST_PROXY",
httpMode: "FRISLIT_HTTP_MODE",
gracePeriod: "FRISLIT_GRACE_PERIOD",
};
const UI_SETTING_KEYS = ["baseDomain", "publicUrl", "httpMode", "gracePeriod", "tlsMode", "trustProxy"];
const PINNED_BY_ENV = { tlsMode: "The HTTPS mode" };
// A deployment configured for tunlit keeps working: FRISLIT_* wins, TUNLIT_* is the fallback.
const readEnv = name => {
const value = process.env[name];
if (value !== undefined && value !== "") return value;
const old = name.replace(/^FRISLIT_/, "TUNLIT_");
const legacy = process.env[old];
if (legacy !== undefined && legacy !== "") {
logger.warn(`Using the deprecated ${old}; rename it to ${name}`);
return legacy;
}
return undefined;
};
const pinned = (config, key) => key in PINNED_BY_ENV && config.sources[key] === "env";
const parseBool = value => ["1", "true", "yes", "on"].includes(String(value).trim().toLowerCase());
const normalize = config => {
config.port = Number(config.port);
config.httpsPort = Number(config.httpsPort);
config.redirectPort = Number(config.redirectPort);
config.gracePeriod = Number(config.gracePeriod);
config.baseDomain = String(config.baseDomain || "").trim().toLowerCase().replace(/^\.+/, "").replace(/\.+$/, "");
config.httpMode = String(config.httpMode || "subdomain").trim().toLowerCase();
config.tlsMode = String(config.tlsMode || "proxy").trim().toLowerCase();
config.acmeDirectoryUrl = String(config.acmeDirectoryUrl || "").trim();
config.managesTls = config.tlsMode === "acme";
config.trustProxy = config.managesTls
? false
: typeof config.trustProxy === "boolean" ? config.trustProxy : parseBool(config.trustProxy);
config.publicUrlConfigured = String(config.publicUrlConfigured ?? config.publicUrl ?? "").trim().replace(/\/+$/, "");
config.publicUrl = config.publicUrlConfigured || (config.baseDomain ? `https://${config.baseDomain}` : "");
config.publicScheme = config.publicUrl.startsWith("http://") ? "http" : "https";
config.wildcard = config.httpMode === "subdomain";
config.ready = !!config.baseDomain;
};
const validate = config => {
const problems = [];
if (!["subdomain", "path"].includes(config.httpMode)) problems.push("httpMode must be \"subdomain\" or \"path\"");
if (!["proxy", "acme"].includes(config.tlsMode)) problems.push("tlsMode must be \"proxy\" or \"acme\"");
for (const key of ["port", "httpsPort", "redirectPort"]) {
if (!Number.isInteger(config[key]) || config[key] < 1 || config[key] > 65535) problems.push(`${key} must be a number between 1 and 65535`);
}
if (!Number.isFinite(config.gracePeriod) || config.gracePeriod < 0) problems.push("gracePeriod must be a non-negative number of seconds");
if (config.publicUrlConfigured && !/^https?:\/\/[^/\s]+$/.test(config.publicUrlConfigured)) problems.push("publicUrl must look like https://host[:port] without a path");
if (config.baseDomain && !/^[a-z0-9.-]+$/.test(config.baseDomain)) problems.push("baseDomain must be a hostname");
return problems;
};
const loadConfig = () => {
const file = readEnv("FRISLIT_CONFIG") || path.join(process.cwd(), "config.yml");
let fromFile = {};
if (fs.existsSync(file)) {
const parsed = yaml.load(fs.readFileSync(file, "utf8"));
if (parsed && typeof parsed !== "object") throw new Error(`${file} must contain a YAML mapping`);
fromFile = parsed || {};
}
const config = { ...DEFAULTS };
const sources = Object.fromEntries(Object.keys(DEFAULTS).map(key => [key, "default"]));
for (const key of Object.keys(DEFAULTS)) {
if (fromFile[key] !== undefined && fromFile[key] !== null && fromFile[key] !== "") { config[key] = fromFile[key]; sources[key] = "file"; }
}
for (const [key, name] of Object.entries(ENV)) {
const value = readEnv(name);
if (value !== undefined) { config[key] = value; sources[key] = "env"; }
}
normalize(config);
const problems = validate(config);
if (problems.length) throw new Error("Invalid configuration:\n - " + problems.join("\n - "));
config.sources = sources;
config.configFile = file;
return config;
};
const applySettings = (config, requested) => {
const settings = { ...requested };
for (const key of Object.keys(settings).filter(key => pinned(config, key))) {
if (String(settings[key]).trim().toLowerCase() !== config[key]) {
throw Object.assign(new Error(`${PINNED_BY_ENV[key]} is set by ${ENV[key]}`), { code: "invalid_settings" });
}
delete settings[key];
}
const next = { ...config, ...settings };
if ("publicUrl" in settings) next.publicUrlConfigured = settings.publicUrl;
normalize(next);
const problems = validate(next);
if (problems.length) throw Object.assign(new Error(problems.join(", ")), { code: "invalid_settings" });
Object.assign(config, next);
for (const key of Object.keys(settings)) config.sources[key] = "ui";
return config;
};
const applyStored = (config, stored) => {
for (const key of UI_SETTING_KEYS) {
const value = stored[key];
if (value === undefined || value === null || value === "" || pinned(config, key)) continue;
config[key] = value;
config.sources[key] = "ui";
}
if ("publicUrl" in stored) config.publicUrlConfigured = stored.publicUrl;
normalize(config);
const problems = validate(config);
if (problems.length) throw new Error("Stored settings are invalid:\n - " + problems.join("\n - "));
return config;
};
module.exports = { loadConfig, applySettings, applyStored, UI_SETTING_KEYS };
+42
View File
@@ -0,0 +1,42 @@
const fs = require("node:fs");
const path = require("node:path");
const { Sequelize } = require("sequelize");
const { dataDir } = require("./paths");
const logger = require("./logger");
const storage = adoptLegacyDatabase(path.join(dataDir(), "frislit.db"));
/*
* A data directory that was served by tunlit still holds tunlit.db. Rename it
* instead of starting from an empty database; if the rename fails (read-only
* mount, different filesystem), use the old file in place.
*/
function adoptLegacyDatabase(target) {
const legacy = path.join(path.dirname(target), "tunlit.db");
if (fs.existsSync(target) || !fs.existsSync(legacy)) return target;
try {
fs.renameSync(legacy, target);
for (const suffix of ["-wal", "-shm"]) {
if (fs.existsSync(legacy + suffix)) fs.renameSync(legacy + suffix, target + suffix);
}
logger.info(`Adopted the tunlit database as ${path.basename(target)}`);
return target;
} catch (error) {
logger.warn(`Could not rename tunlit.db (${error.message}), using it in place`);
return legacy;
}
}
Sequelize.DATE.prototype._stringify = function (date) {
return (date instanceof Date ? date : new Date(date)).toISOString();
};
module.exports = new Sequelize({
dialect: "sqlite",
storage,
logging: message => logger.debug(message),
query: { raw: true },
});
module.exports.storagePath = storage;
+7
View File
@@ -0,0 +1,7 @@
const sendJson = (res, status, data, extraHeaders = {}) => {
const body = JSON.stringify(data);
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Content-Length": Buffer.byteLength(body), "Cache-Control": "no-store", ...extraHeaders });
res.end(body);
};
module.exports = { sendJson };
+31
View File
@@ -0,0 +1,31 @@
const crypto = require("node:crypto");
const ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
const MIXED = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const NAME_REGEX = /^[a-z0-9-]{3,32}$/;
const RESERVED = new Set(["frislit"]);
const SECRET_LENGTH = 26;
const randomFrom = (alphabet, length) => {
const bytes = crypto.randomBytes(length);
let out = "";
for (let i = 0; i < length; i++) out += alphabet[bytes[i] % alphabet.length];
return out;
};
const randomId = (length = 6) => randomFrom(ALPHABET, length);
const randomSecret = () => randomFrom(MIXED, SECRET_LENGTH);
const randomToken = (length = 32) => randomFrom(MIXED, length);
const isValidName = name => NAME_REGEX.test(name) && !RESERVED.has(name);
const isReserved = name => RESERVED.has(name);
const hashSecret = secret => crypto.createHash("sha256").update(secret).digest();
const hashToken = token => crypto.createHash("sha256").update(String(token)).digest("hex");
const splitShareCode = code => {
if (typeof code !== "string" || !/^[a-z0-9-]+[A-Za-z0-9]{26}$/.test(code)) return null;
return { id: code.slice(0, -SECRET_LENGTH), secret: code.slice(-SECRET_LENGTH) };
};
module.exports = { randomId, randomSecret, randomToken, isValidName, isReserved, hashSecret, hashToken, splitShareCode, NAME_REGEX };
+24
View File
@@ -0,0 +1,24 @@
const LEVELS = { error: 0, warn: 1, info: 2, debug: 3 };
const COLORS = { error: "\x1b[31m", warn: "\x1b[33m", info: "\x1b[32m", debug: "\x1b[35m" };
const RESET = "\x1b[0m";
const level = LEVELS[process.env.LOG_LEVEL] ?? LEVELS.info;
const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
const log = (lvl, message, meta) => {
if (LEVELS[lvl] > level) return;
const time = new Date().toISOString();
const tag = useColor ? `${COLORS[lvl]}${lvl.padEnd(5)}${RESET}` : lvl.padEnd(5);
const extra = meta && Object.keys(meta).length
? " " + Object.entries(meta).map(([k, v]) => `${k}=${typeof v === "object" ? JSON.stringify(v) : v}`).join(" ")
: "";
const line = `${time} ${tag} ${message}${extra}`;
(lvl === "error" || lvl === "warn" ? console.error : console.log)(line);
};
module.exports = {
error: (m, meta) => log("error", m, meta),
warn: (m, meta) => log("warn", m, meta),
info: (m, meta) => log("info", m, meta),
debug: (m, meta) => log("debug", m, meta),
};
+41
View File
@@ -0,0 +1,41 @@
const fs = require("node:fs");
const path = require("node:path");
const { DataTypes } = require("sequelize");
const db = require("./database");
const logger = require("./logger");
const MIGRATION_DIR = path.join(__dirname, "..", "migrations");
const ensureTable = async queryInterface => {
const tables = await queryInterface.showAllTables();
if (tables.includes("SequelizeMeta")) return;
await queryInterface.createTable("SequelizeMeta", {
name: { type: DataTypes.STRING, allowNull: false, primaryKey: true },
});
};
const executed = async () => {
const rows = await db.query("SELECT name FROM SequelizeMeta ORDER BY name ASC", { type: db.QueryTypes.SELECT });
return rows.map(row => row.name);
};
const runMigrations = async () => {
const queryInterface = db.getQueryInterface();
await ensureTable(queryInterface);
const done = new Set(await executed());
const files = fs.existsSync(MIGRATION_DIR)
? fs.readdirSync(MIGRATION_DIR).filter(file => file.endsWith(".js")).sort()
: [];
const pending = files.filter(file => !done.has(file));
if (!pending.length) return;
for (const file of pending) {
const migration = require(path.join(MIGRATION_DIR, file));
await migration.up(queryInterface, db);
await db.query("INSERT INTO SequelizeMeta (name) VALUES (?)", { replacements: [file] });
logger.info(`Applied migration ${file}`);
}
};
module.exports = { runMigrations };
+27
View File
@@ -0,0 +1,27 @@
const { readIndex } = require("./static");
const { sendJson } = require("./html");
const isNavigation = req => {
const dest = req.headers["sec-fetch-dest"];
if (dest === "document") return true;
if (dest && dest !== "empty") return false;
return /\btext\/html\b/.test(req.headers.accept || "");
};
const sendAppState = (req, res, status, state, extraHeaders = {}) => {
const html = readIndex();
if (!isNavigation(req) || !html) return sendJson(res, status, { error: state.kind, ...state }, extraHeaders);
const payload = JSON.stringify(state).replace(/</g, "\\u003c");
const body = html.replace("</head>", `<script>window.__frislit__=${payload}</script></head>`);
res.writeHead(status, {
"Content-Type": "text/html; charset=utf-8",
"Content-Length": Buffer.byteLength(body),
"Cache-Control": "no-store",
...extraHeaders,
});
res.end(req.method === "HEAD" ? undefined : body);
};
module.exports = { sendAppState, isNavigation };
+24
View File
@@ -0,0 +1,24 @@
const crypto = require("node:crypto");
const KEY_LENGTH = 64;
const SCRYPT_OPTIONS = { N: 16384, r: 8, p: 1 };
const scrypt = (password, salt, length) => new Promise((resolve, reject) => {
crypto.scrypt(password, salt, length, SCRYPT_OPTIONS, (err, derived) => err ? reject(err) : resolve(derived));
});
const hashPassword = password => {
const salt = crypto.randomBytes(16);
const hash = crypto.scryptSync(password, salt, KEY_LENGTH, SCRYPT_OPTIONS);
return `scrypt$${salt.toString("hex")}$${hash.toString("hex")}`;
};
const verifyPassword = async (password, stored) => {
const [scheme, saltHex, hashHex] = String(stored || "").split("$");
if (scheme !== "scrypt" || !saltHex || !hashHex) return false;
const expected = Buffer.from(hashHex, "hex");
const actual = await scrypt(String(password), Buffer.from(saltHex, "hex"), expected.length);
return crypto.timingSafeEqual(actual, expected);
};
module.exports = { hashPassword, verifyPassword };
+5
View File
@@ -0,0 +1,5 @@
const path = require("node:path");
const dataDir = () => process.env.FRISLIT_DATA_DIR || process.env.TUNLIT_DATA_DIR || path.join(process.cwd(), "data");
module.exports = { dataDir };
+79
View File
@@ -0,0 +1,79 @@
const { sendJson } = require("./html");
const MAX_BODY = 64 * 1024;
const readBody = req => new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
req.on("data", chunk => {
size += chunk.length;
if (size > MAX_BODY) { reject(Object.assign(new Error("Request body too large"), { status: 413 })); req.destroy(); return; }
chunks.push(chunk);
});
req.on("end", () => {
if (!chunks.length) return resolve({});
try { resolve(JSON.parse(Buffer.concat(chunks).toString("utf8"))); } catch { reject(Object.assign(new Error("Body must be valid JSON"), { status: 400 })); }
});
req.on("error", reject);
});
const compile = pattern => {
const keys = [];
const source = pattern.replace(/\/:([a-zA-Z]+)/g, (_, key) => { keys.push(key); return "/([^/]+)"; });
return { regex: new RegExp(`^${source}/?$`), keys };
};
const Router = () => {
const routes = [];
const add = method => (pattern, ...handlers) => routes.push({ method, ...compile(pattern), handlers });
return { routes, get: add("GET"), post: add("POST"), put: add("PUT"), patch: add("PATCH"), delete: add("DELETE") };
};
const createResponse = res => ({
raw: res,
statusCode: 200,
headers: {},
status(code) { this.statusCode = code; return this; },
header(name, value) { this.headers[name] = value; return this; },
json(data) { sendJson(res, this.statusCode, data, this.headers); },
});
const createApp = () => {
const mounts = [];
const app = {
use: (prefix, ...args) => {
const router = args.pop();
mounts.push({ prefix, middlewares: args, router });
},
handle: async (req, res, pathname, context) => {
const url = new URL(req.url, "http://frislit.invalid");
for (const mount of mounts) {
if (pathname !== mount.prefix && !pathname.startsWith(`${mount.prefix}/`)) continue;
const rest = pathname.slice(mount.prefix.length) || "/";
for (const route of mount.router.routes) {
if (route.method !== req.method) continue;
const match = route.regex.exec(rest);
if (!match) continue;
const request = { raw: req, method: req.method, headers: req.headers, query: url.searchParams, params: Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])])), body: {}, ...context };
const response = createResponse(res);
try {
if (["POST", "PUT", "PATCH"].includes(req.method)) request.body = await readBody(req);
for (const handler of [...mount.middlewares, ...route.handlers]) {
let proceed = false;
await handler(request, response, () => { proceed = true; });
if (!proceed) return true;
}
} catch (err) {
if (!res.headersSent) sendJson(res, err.status || 500, { code: err.status || 500, message: err.status ? err.message : "Internal error" });
if (!err.status) throw err;
}
return true;
}
}
return false;
},
};
return app;
};
module.exports = { Router, createApp };
+60
View File
@@ -0,0 +1,60 @@
const fs = require("node:fs");
const path = require("node:path");
const DIST_DIR = path.join(__dirname, "..", "..", "client", "dist");
const MIME = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".ico": "image/x-icon",
".json": "application/json; charset=utf-8",
".woff": "font/woff",
".woff2": "font/woff2",
".txt": "text/plain; charset=utf-8",
".map": "application/json; charset=utf-8",
};
const hasBuild = () => fs.existsSync(path.join(DIST_DIR, "index.html"));
let cached = null;
const readIndex = () => {
const file = path.join(DIST_DIR, "index.html");
if (!fs.existsSync(file)) return null;
const stamp = fs.statSync(file).mtimeMs;
if (!cached || cached.stamp !== stamp) cached = { stamp, html: fs.readFileSync(file, "utf8") };
return cached.html;
};
const sendFile = (req, res, relative) => {
const file = path.normalize(path.join(DIST_DIR, relative));
if (!file.startsWith(DIST_DIR + path.sep)) return false;
let stats;
try {
stats = fs.statSync(file);
} catch {
return false;
}
if (!stats.isFile()) return false;
const immutable = relative.startsWith("assets/");
res.writeHead(200, {
"Content-Type": MIME[path.extname(file).toLowerCase()] || "application/octet-stream",
"Content-Length": stats.size,
"Cache-Control": immutable ? "public, max-age=31536000, immutable" : "no-cache",
});
if (req.method === "HEAD") return res.end(), true;
fs.createReadStream(file).pipe(res);
return true;
};
const MISSING_BUILD = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>frislit</title></head><body style="font-family:system-ui;background:#000A12;color:#fff;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0"><main style="max-width:32rem;text-align:center"><h1>Web UI not built</h1><p style="color:#B7B7B7">Run <code>npm run build</code> in <code>client/</code> (or use <code>npm run dev</code> for the Vite dev server) and reload.</p></main></body></html>`;
const sendIndex = (req, res) => {
if (sendFile(req, res, "index.html")) return;
res.writeHead(503, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
res.end(MISSING_BUILD);
};
module.exports = { hasBuild, readIndex, sendFile, sendIndex };