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

+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 };