// Settings (BRIEF §14.8): server name, ports, TLS, discovery, jobs, limits, language, retention, logs. Values fixed by
// environment variables are read-only here; ports, TLS and chunk size apply at the next restart. How long job history is
// kept is a parameter of the Job history clean-up schedule (Jobs › Scheduled, owner review 2, R10); Keep audit shows the
// Audit log clean-up schedule's age limit (0 while it is off), and saving a new one sets it. Jobs run one at a time
// (owner review 1): the parallelism (photos at once) and the priority queue apply at once, as do the log levels,
// retention, size limits and rotation (owner review 2, R11). About (version, API, database, uptime) is the last group,
// read-only (owner review 2); #/about opens here on it. Network (owner review 3): the public ports are the host ports
// clients use when they differ from the listening ones (a container publishes 8443 as another port) and apply at once;
// in a container the listening ports are the container's, read-only. Client address is what to type in the Uploader and
// in Chronos: this host as the browser reached it, on the HTTPS port this page came through (else the public HTTPS port;
// the proxy's address in TLS mode proxy). When that port is not the saved one, a button fills it in; saving a public HTTPS
// port other than the page's asks first, as the HTTPS redirect follows it at once. Videos folder (owner review 1, R9) is
// where the Videos page's Copy to folder puts renders: read-only when CHRONOS_VIDEOS_PATH fixes it, empty turns copying off.
import { t, applyStrings, languages } from "../i18n.js";
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, formatDuration, markInvalid, clearInvalid, invalidText, escapeReverts, routeParams, confirmDialog, PROXY_WARNING } from "../ui.js";
import { kindLabel } from "../jobs.js";
import { icons } from "../icons.js";
/** Levels of the priority queue, highest first. */
const LEVELS = ["high", "normal", "low"];
/** Log levels, least severe first (the server's wire names). */
const LOG_LEVELS = ["trace", "debug", "information", "warning", "error", "critical", "none"];
const ROTATIONS = ["daily", "hourly"];
/** Settings the server names in error details whose field here has another name. */
const FIELDS = { maxuploadbytes: "maxUploadMb", chunksizebytes: "chunkSizeMib" };
const PEM_FILES = ["tlsCert", "tlsKey"];
const MB = 1e6;
const MIB = 1024 * 1024;
export async function render(root, { api, info, setMeta, actions }) {
// Only the About group's database and uptime, filled in when the dashboard answers: the form never waits for its
// archive statistics, and without them those rows keep a dash.
const status = api.get("/api/v1/server/dashboard").then((d) => ({ ...d, at: Date.now() }), () => null);
let dashboard = null;
let settings;
try {
settings = await api.get("/api/v1/server/settings");
} catch (err) {
root.innerHTML = `
${escapeHtml(errorText(err))}
`;
return;
}
setMeta("");
// In the header, like the other pages' main action, so toasts never cover it.
actions.innerHTML = ``;
applyStrings(actions);
const same = (a, b) => a.toLowerCase() === b.toLowerCase();
const locked = (name) => settings.locked.some((l) => same(l, name));
// The server names the variable that fixes each locked setting: CHRONOS_LOG_LEVEL fixes the console's level too, unless
// CHRONOS_LOG_CONSOLE_LEVEL sets its own (BRIEF §14.9).
const variable = (name) => Object.entries(settings.lockedBy ?? {}).find(([setting]) => same(setting, name))?.[1] ?? name;
// Chronos Desktop owns the settings of the library it shares (owner review 5, #67): no variable names them.
const lockTip = (name) => variable(name) === "desktop" ? t("Admin.Settings.LockedByDesktop.Tip") : t("Admin.Settings.Locked.Tip", variable(name));
const lock = (name) => locked(name) ? `disabled title="${attr(lockTip(name))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`;
const field = (name, input) => ``;
const number = (name, value, attrs = "") => field(name, ``);
const text = (name, value, attrs = "dir=\"auto\"") => field(name, ``);
// A value this page does not know stays listed, so saving the other settings never changes it.
const choice = (name, value, values, label) => field(name, ``);
const level = (name, value) => choice(name, value, LOG_LEVELS, (l) => `Admin.Settings.Level.${cap(l)}`);
// A container's listening port is the template's Target, mapped to a host port: shown, never edited here.
const listening = (name, value) => settings.inContainer
? field(`container${cap(name)}`, ``)
: number(name, value, 'min="1" max="65535"');
// Empty: the listening port, which the placeholder shows.
const publicPort = (name, value, port) => number(name, value ?? "", `min="1" max="65535" placeholder="${attr(port)}"`);
// This page came through another HTTPS port than the one saved (a container's 8443 published as 8444, Public HTTPS port
// still empty): a button fills it in, so the redirect, discovery and the client address follow.
const publicHttps = () => {
const page = pagePort();
if (page === null || page === savedHttps() || locked("publicHttpsPort")) return publicPort("publicHttpsPort", settings.publicHttpsPort, settings.httpsPort);
return field("publicHttpsPort", ``);
};
function draw() {
root.innerHTML = `
${about()}`;
applyStrings(root);
const form = root.querySelector("form");
escapeReverts(form);
form.addEventListener("submit", save);
form.elements.tlsMode.addEventListener("change", () => pemFiles(form));
pemFiles(form);
root.querySelector("#use-page-port")?.addEventListener("click", (e) => {
form.elements.publicHttpsPort.value = String(pagePort());
e.currentTarget.remove();
form.elements.publicHttpsPort.focus();
});
const address = root.querySelector("#client-address");
root.querySelector("#copy-address").addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(address.value);
toast(t("Admin.Settings.AddressCopied"));
} catch {
address.focus();
address.select();
}
});
// The levels matter only while the priority queue is on.
form.elements.priorityQueue.addEventListener("change", () => { root.querySelector(".priorities").hidden = !form.elements.priorityQueue.checked; });
}
/**
* About, outside the form: nothing to save. The server name and the certificate fingerprint are left to the Server
* and Network groups above; the uptime counts on from when it was read.
*/
function about() {
const rows = [
["Admin.About.Version", `${escapeHtml(info?.version ?? "—")}`],
["Admin.About.Api", `${escapeHtml(info?.apiVersion ?? "—")}`],
["Admin.About.Database", `${escapeHtml(database())}`],
["Admin.About.Uptime", `${escapeHtml(uptime())}`],
];
return `
${rows.map(([key, value]) => `
${value}
`).join("")}
`;
}
function database() {
return dashboard?.database ?? "—";
}
function uptime() {
return dashboard ? formatDuration(dashboard.uptimeSeconds + (Date.now() - dashboard.at) / 1000) : "—";
}
/**
* What clients type to reach this server: the host name the browser used (an IPv6 address in brackets) on the port
* this page came through over HTTPS, which reaches the server whatever is saved; over plain HTTP (this machine), the
* public HTTPS port, else the HTTPS port; behind a reverse proxy, the proxy's address this page came through.
*/
function clientAddress() {
if (settings.tlsMode === "proxy") return location.origin;
const host = location.hostname.includes(":") && !location.hostname.startsWith("[") ? `[${location.hostname}]` : location.hostname;
const port = pagePort() ?? savedHttps();
return port === 443 ? `https://${host}` : `https://${host}:${port}`;
}
/** The HTTPS port clients are told to use, as saved: the public one, else the one the server listens on. */
function savedHttps() {
return settings.publicHttpsPort ?? settings.httpsPort;
}
/** The port this page came through when the browser speaks HTTPS to the server itself (not through a proxy), else null. */
function pagePort() {
if (location.protocol !== "https:" || settings.tlsMode === "proxy") return null;
return Number(location.port || 443);
}
/** The certificate and key files are used only in Own certificate mode; elsewhere they are off and say so. */
function pemFiles(form) {
const pem = form.elements.tlsMode.value === "pem";
for (const name of PEM_FILES.filter((n) => !locked(n))) {
const input = form.elements[name];
clearInvalid(input);
input.disabled = !pem;
input.title = t(pem ? `Admin.Settings.${cap(name)}.Tip` : "Admin.Settings.PemOnly.Tip");
}
}
/**
* The videos folder to send (owner review 1, R9): null keeps it (locked by CHRONOS_VIDEOS_PATH, or not changed), an empty
* text clears it and turns copying off, else the folder, which the server checks (not inside the archive).
*/
function videosPath() {
const input = root.querySelector('[name="videosPath"]');
if (!input || input.disabled) return null;
const next = input.value.trim();
return next === (settings.videosPath ?? "") ? null : next;
}
async function save(e) {
e.preventDefault();
const form = e.target;
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
const data = new FormData(form);
const value = (name, fallback) => (form.elements[name]?.disabled ? fallback : data.get(name));
// Text a number field cannot read is sent as -1, which the server refuses, so it is marked rather than cleared.
const publicValue = (name) => {
const input = form.elements[name];
if (input.disabled) return settings[name];
if (input.validity.badInput) return -1;
return input.value.trim() === "" ? 0 : Number(input.value);
};
// A new public HTTPS port other than the one this page came through moves the HTTPS redirect away from it at once: a
// typo would send the panel's link to a port where nothing, or another service, answers. Asked once before saving.
const nextPublic = publicValue("publicHttpsPort");
const page = pagePort();
const nextHttps = nextPublic === 0 || nextPublic == null ? settings.httpsPort : nextPublic;
if (page !== null && nextPublic !== -1 && nextHttps !== savedHttps() && nextHttps !== page && !await confirmDialog({
title: t("Admin.Settings.PortChangeTitle", nextHttps),
body: t("Admin.Settings.PortChangeBody", page),
confirm: t("Admin.Settings.PortChangeConfirm"),
confirmTip: t("Admin.Settings.PortChangeConfirm.Tip", nextHttps),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Settings.PortChangeKeep.Tip"),
})) {
form.elements.publicHttpsPort.focus();
return;
}
const request = {
...settings,
serverName: String(value("serverName", settings.serverName)).trim(),
language: String(value("language", settings.language)),
parallelism: Number(value("parallelism", settings.parallelism)),
priorityQueue: form.elements.priorityQueue.disabled ? settings.priorityQueue : form.elements.priorityQueue.checked,
jobPriorities: settings.jobPriorities.map((p) => ({ kind: p.kind, level: String(data.get(`priority:${p.kind}`) ?? p.level) })),
discovery: form.elements.discovery.disabled ? settings.discovery : form.elements.discovery.checked,
httpPort: Number(value("httpPort", settings.httpPort)),
httpsPort: Number(value("httpsPort", settings.httpsPort)),
// Empty clears a public port (0); a locked one is sent as it is.
publicHttpPort: publicValue("publicHttpPort"),
publicHttpsPort: nextPublic,
tlsMode: String(value("tlsMode", settings.tlsMode)),
tlsCert: String(value("tlsCert", settings.tlsCert ?? "")).trim() || null,
tlsKey: String(value("tlsKey", settings.tlsKey ?? "")).trim() || null,
videosPath: videosPath(),
maxUploadBytes: Math.round(Number(data.get("maxUploadMb")) * MB),
chunkSizeBytes: Math.round(Number(data.get("chunkSizeMib")) * MIB),
tokenLifetimeDays: Number(data.get("tokenLifetimeDays")),
uploadRetentionHours: Number(data.get("uploadRetentionHours")),
logs: {
fileLevel: String(value("logLevel", settings.logs.fileLevel)),
consoleLevel: String(value("consoleLogLevel", settings.logs.consoleLevel)),
retentionDays: Number(value("logRetentionDays", settings.logs.retentionDays)),
maxFileMb: Number(value("logMaxFileMb", settings.logs.maxFileMb)),
maxTotalMb: Number(value("logMaxTotalMb", settings.logs.maxTotalMb)),
rotation: String(value("logRotation", settings.logs.rotation)),
auditRetentionDays: Number(value("auditRetentionDays", settings.logs.auditRetentionDays)),
diagnosticsLogMb: Number(value("diagnosticsLogMb", settings.logs.diagnosticsLogMb)),
},
};
try {
settings = await api.put("/api/v1/server/settings", request);
draw();
toast(t("Admin.Common.Saved"));
} catch (err) {
const key = String(err.details ?? "").toLowerCase();
const input = (FIELDS[key] && form.elements[FIELDS[key]]) || [...form.elements].find((el) => el.name && el.name.toLowerCase() === key);
let message = errorText(err);
if (input && err.code === "invalid_setting") message = PEM_FILES.includes(input.name) ? t("Admin.Settings.PemMissing") : invalidText(input);
if (input && !input.disabled) {
markInvalid(input, message);
input.focus();
}
toast(message, true);
}
}
draw();
// Once: the route drops the group, so a later redraw (a language change) leaves the focus where it is.
if (routeParams().get("group") === "about") {
history.replaceState(null, "", "#/settings");
root.querySelector(".about").scrollIntoView({ block: "start" });
root.querySelector("#about-title").focus({ preventScroll: true });
}
// Only the two rows change, so the focus and the form's edits stay; a page left meanwhile is not touched.
status.then((d) => {
dashboard = d;
if (!d || !root.isConnected) return;
root.querySelector("#about-database").textContent = database();
root.querySelector("#about-uptime").textContent = uptime();
});
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}