fix(server): client address from the page's port, stricter Chronos identity, Host networking notes

Review fixes on top of the public ports change (owner review 3):

- Settings > Network and TLS: opened over HTTPS, the client address uses the port
  the page came through (a container's 8443 published as 8444 with Public HTTPS
  port still empty showed the wrong 8443), and a "Use <port>" button fills that
  port in. Saving a Public HTTPS port other than the page's asks first, since the
  HTTPS redirect follows it at once and a typo would lock the panel's link out.
- GetInfoAsync tells Chronos from other services by stricter rules on both the
  trusted and the untrusted-certificate path: any redirect, any answer that is not
  JSON, more than 1 MB, or an error without the X-Chronos-Api header is not
  Chronos. Another service's certificate is no longer offered for trust after a
  cross-scheme redirect, an error page or a JSON 401/403/404, and a JSON 401 over
  HTTP no longer reads as a wrong password.
- The HTTP port typed without a scheme (TLS to a plain HTTP port) now gives the
  not-Chronos error instead of "the server did not answer".
- The Uploader's certificate question names the address with its port.
- A link-local IPv6 address with a zone index is refused instead of losing it.
- In a container, the first save of the settings removes HttpPort/HttpsPort from
  server.json, so the start-up warning stops; the warning says so.
- Guide, README, compose and template: with network type Host the mappings do
  nothing and CHRONOS_HTTP_PORT / CHRONOS_HTTPS_PORT move the listening ports off
  ones another service uses; the template overview is back to two sentences.
- BRIEF, DECISIONS and CHANGELOG updated; en/it strings added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-04 10:28:08 +01:00
1 parent 369e754bec
commit 0aa2fb8135
19 files changed
+303 -67

No files matched your search

+10 -2
View File
@@ -7,7 +7,8 @@ namespace Chronos.Protocol.Client;
/// Server addresses as a user types them, shared by the desktop client and the uploader (owner review 3). An address
/// without a scheme is HTTPS and, without a port, on <see cref="DefaultPort"/>, the port Chronos Server listens on, as
/// the placeholder "nas.local:8443" shows; one typed with its scheme keeps that scheme's port ("https://chronos.example.com"
/// is 443, a reverse proxy); a port typed is always kept. A bare IPv6 address gets its brackets.
/// is 443, a reverse proxy); a port typed is always kept. A bare IPv6 address gets its brackets; one with a zone index
/// ("fe80::1%12") is refused, as the request could not keep the zone.
/// </summary>
public static class ChronosAddress
{
@@ -24,10 +25,17 @@ public static class ChronosAddress
if (!schemeTyped)
{
// "fd00::5" alone: an address cannot hold its colons unbracketed ("[fd00::5]:9443" parses as an IP too, already bracketed).
if (!trimmed.StartsWith('[') && IPAddress.TryParse(trimmed, out var ip) && ip.AddressFamily == AddressFamily.InterNetworkV6) trimmed = "[" + trimmed + "]";
if (!trimmed.StartsWith('[') && IPAddress.TryParse(trimmed, out var ip) && ip.AddressFamily == AddressFamily.InterNetworkV6)
{
if (ip.ScopeId != 0) return false;
trimmed = "[" + trimmed + "]";
}
trimmed = "https://" + trimmed;
}
if (!Uri.TryCreate(trimmed, UriKind.Absolute, out var parsed) || parsed.Scheme is not ("https" or "http") || parsed.Host.Length == 0) return false;
// A link-local address with its zone ("fe80::1%12"): the zone would not survive into the request, so it is refused.
if (parsed.HostNameType == UriHostNameType.IPv6 && (parsed.DnsSafeHost.Contains('%', StringComparison.Ordinal)
|| IPAddress.TryParse(parsed.DnsSafeHost, out var host) && host.ScopeId != 0)) return false;
var builder = new UriBuilder(parsed) { Query = string.Empty, Fragment = string.Empty };
if (!schemeTyped && !HasPort(trimmed)) builder.Port = DefaultPort;
if (!builder.Path.EndsWith('/')) builder.Path += "/";
+68 -27
View File
@@ -66,71 +66,112 @@ public sealed class ChronosClient : IDisposable
/// <summary>
/// Reads server info; throws <see cref="UntrustedCertificateException"/> when the TLS certificate of a Chronos Server
/// needs confirmation, and <see cref="NotChronosServerException"/> when the address answers as something else (owner
/// review 3). Behind a certificate that is not trusted yet, the info is first read once more without checking the
/// certificate and without credentials: only an answer that is Chronos's leads to the fingerprint question, so the
/// certificate of another service on the host is never offered for trust. Nothing is trusted here.
/// review 3): a redirect, a page that is not JSON, JSON of another shape, or an error Chronos did not write. Behind a
/// certificate that is not trusted yet, the info is first read once more without checking the certificate and without
/// credentials: only an answer that is Chronos's leads to the fingerprint question, so the certificate of another
/// service on the host is never offered for trust. An HTTPS address whose port answers plain HTTP (the HTTP port typed
/// without a scheme) is not Chronos either. Nothing is trusted here.
/// </summary>
public async Task<ServerInfo> GetInfoAsync(CancellationToken ct = default)
{
ServerInfo info;
HttpResponseMessage response;
try
{
info = await GetAsync(InfoPath, ProtocolJson.Default.ServerInfo, ct).ConfigureAwait(false);
response = await SendRawAsync(new HttpRequestMessage(HttpMethod.Get, InfoPath), ct).ConfigureAwait(false);
}
catch (UntrustedCertificateException) when (_ownsHandler)
{
if (await AnswersAsChronosAsync(ct).ConfigureAwait(false) == false) throw new NotChronosServerException(BaseAddress);
if (await ProbeAsync(BaseAddress, ct).ConfigureAwait(false) is { Chronos: false }) throw new NotChronosServerException(BaseAddress);
throw;
}
catch (ChronosApiException api) when (!api.IsTransient && (int)api.Status < 500 && !IsChronosError(api.Error))
catch (HttpRequestException tls) when (_ownsHandler && tls.HttpRequestError == HttpRequestError.SecureConnectionError
&& BaseAddress.Scheme == Uri.UriSchemeHttps)
{
throw new NotChronosServerException(BaseAddress, api);
// The same authority over plain HTTP: any answer means the port is not Chronos's HTTPS port.
var plain = new UriBuilder(BaseAddress) { Scheme = Uri.UriSchemeHttp, Port = BaseAddress.Port }.Uri;
if (await ProbeAsync(plain, ct).ConfigureAwait(false) is { Answered: true }) throw new NotChronosServerException(BaseAddress, tls);
throw;
}
catch (Exception ex) when (ex is JsonException or NotSupportedException)
using (response)
{
throw new NotChronosServerException(BaseAddress, ex);
var answer = await IdentifyAsync(response, ct).ConfigureAwait(false);
if (answer.Info is { } info) return info;
if (answer.Chronos == false) throw new NotChronosServerException(BaseAddress);
// Chronos's own error, or busy: as any other request reports it.
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
throw new NotChronosServerException(BaseAddress);
}
return IsChronos(info) ? info : throw new NotChronosServerException(BaseAddress);
}
private const string InfoPath = "api/v1/server/info";
/// <summary>More than a server info ever holds: a larger answer is something else.</summary>
private const int MaxInfoBytes = 1 << 20;
/// <summary>What every Chronos Server's info holds; JSON of another shape reads as nulls and zeros.</summary>
private static bool IsChronos(ServerInfo? info) =>
info is { Name.Length: > 0, Version.Length: > 0, ApiVersion: > 0, Capabilities: not null, Formats: not null, Limits: not null };
/// <summary>An error body Chronos wrote (<see cref="EnsureSuccessAsync"/> codes any other reply <c>http_&lt;status&gt;</c>).</summary>
private static bool IsChronosError(ApiError error) => error.Code is { Length: > 0 } code && !code.StartsWith("http_", StringComparison.Ordinal);
/// <summary>What a <c>server/info</c> answer is: Chronos's (with its info when it succeeded), something else, or unknown (busy).</summary>
private readonly record struct Identity(bool? Chronos, ServerInfo? Info = null, bool Answered = true);
/// <summary>
/// The info read without checking the certificate, by a client of its own that holds no token: true when it is
/// Chronos's, false when the address answers as something else, null when it cannot tell (no answer, busy).
/// Tells a <c>server/info</c> answer of Chronos from any other. Chronos answers it anonymously with its JSON and never
/// redirects; every response of its carries <see cref="ApiVersion.Header"/>, so an error is Chronos's only with that
/// header and an error body of its own. A busy answer (408, 429, 502-504) with JSON or no body cannot tell; any answer
/// that is not JSON, or is larger than <see cref="MaxInfoBytes"/>, is something else.
/// </summary>
private async Task<bool?> AnswersAsChronosAsync(CancellationToken ct)
private static async Task<Identity> IdentifyAsync(HttpResponseMessage response, CancellationToken ct)
{
if ((int)response.StatusCode is >= 300 and < 400) return new(false);
var type = response.Content.Headers.ContentType?.MediaType;
var json = type is not null && (type.Equals("application/json", StringComparison.OrdinalIgnoreCase) || type.EndsWith("+json", StringComparison.OrdinalIgnoreCase));
if (ChronosApiException.IsTransientStatus(response.StatusCode)) return new(json || type is null ? null : false);
if (!json || response.Content.Headers.ContentLength > MaxInfoBytes) return new(false);
try
{
await response.Content.LoadIntoBufferAsync(MaxInfoBytes, ct).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var info = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ServerInfo, ct).ConfigureAwait(false);
return IsChronos(info) ? new(true, info) : new(false);
}
if (!response.Headers.Contains(ApiVersion.Header)) return new(false);
var error = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ApiError, ct).ConfigureAwait(false);
return new(error is { Code.Length: > 0 } && !error.Code.StartsWith("http_", StringComparison.Ordinal));
}
catch (Exception ex) when (ex is JsonException or NotSupportedException or HttpRequestException)
{
// Not JSON after all, or more than a server info.
return new(false);
}
}
/// <summary>
/// The info at <paramref name="address"/> read without checking the certificate, by a client of its own that holds no
/// token and follows no redirect; <see cref="Identity.Answered"/> is false when nothing answered (no connection, TLS
/// refused, timeout).
/// </summary>
private static async Task<Identity> ProbeAsync(Uri address, CancellationToken ct)
{
using var handler = new SocketsHttpHandler
{
SslOptions = { RemoteCertificateValidationCallback = static (_, _, _, _) => true },
ConnectTimeout = TimeSpan.FromSeconds(10),
AutomaticDecompression = DecompressionMethods.None,
AllowAutoRedirect = false,
UseCookies = false,
};
using var http = new HttpClient(handler) { BaseAddress = BaseAddress, Timeout = TimeSpan.FromSeconds(20), MaxResponseContentBufferSize = 1 << 20 };
using var http = new HttpClient(handler) { BaseAddress = address, Timeout = TimeSpan.FromSeconds(20) };
http.DefaultRequestHeaders.Add(ApiVersion.Header, ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture));
try
{
using var response = await http.GetAsync(InfoPath, ct).ConfigureAwait(false);
if (response.IsSuccessStatusCode) return IsChronos(await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ServerInfo, ct).ConfigureAwait(false));
if ((int)response.StatusCode is < 400 or >= 500 || ChronosApiException.IsTransientStatus(response.StatusCode)) return null;
var error = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ApiError, ct).ConfigureAwait(false);
return error is not null && IsChronosError(error);
}
catch (Exception ex) when (ex is JsonException or NotSupportedException)
{
return false;
using var response = await http.GetAsync(InfoPath, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
return await IdentifyAsync(response, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is HttpRequestException or IOException || (ex is OperationCanceledException && !ct.IsCancellationRequested))
{
return null;
return new(null, Answered: false);
}
}
+51 -7
View File
@@ -7,9 +7,11 @@
// 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 public HTTPS port (the proxy's address in TLS mode proxy).
// 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.
import { t, applyStrings, languages } from "../i18n.js";
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, formatDuration, markInvalid, clearInvalid, invalidText, escapeReverts, routeParams, PROXY_WARNING } from "../ui.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";
@@ -60,6 +62,15 @@ export async function render(root, { api, info, setMeta, actions }) {
: 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", `<span class="inline"><input class="input narrow num" type="number" name="publicHttpsPort" value="${attr(settings.publicHttpsPort ?? "")}"
min="1" max="65535" placeholder="${attr(settings.httpsPort)}" data-i18n-title="Admin.Settings.PublicHttpsPort.Tip">
<button class="btn small" type="button" id="use-page-port" title="${attr(t("Admin.Settings.UsePagePort.Tip", page))}">${escapeHtml(t("Admin.Settings.UsePagePort", page))}</button></span>`);
};
function draw() {
root.innerHTML = `
@@ -88,7 +99,7 @@ export async function render(root, { api, info, setMeta, actions }) {
${listening("httpPort", settings.httpPort)}
${listening("httpsPort", settings.httpsPort)}
${publicPort("publicHttpPort", settings.publicHttpPort, settings.httpPort)}
${publicPort("publicHttpsPort", settings.publicHttpsPort, settings.httpsPort)}
${publicHttps()}
${field("clientAddress", `<span class="inline"><input class="input mono" id="client-address" readonly dir="ltr" value="${attr(clientAddress())}" data-i18n-title="Admin.Settings.ClientAddress.Tip">
<button class="btn icon" type="button" id="copy-address" data-i18n-title="Admin.Settings.CopyAddress.Tip">${icons.copy}</button></span>`)}
${field("tlsMode", `<select class="input" name="tlsMode" ${lock("tlsMode")}>${["auto", "pem", "proxy"].map((m) =>
@@ -123,6 +134,11 @@ export async function render(root, { api, info, setMeta, actions }) {
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 {
@@ -165,16 +181,28 @@ export async function render(root, { api, info, setMeta, actions }) {
}
/**
* What clients type to reach this server, as saved: the host name the browser used (an IPv6 address in brackets) on
* the public HTTPS port, else the HTTPS port; behind a reverse proxy, the proxy's address this page came through.
* 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 = settings.publicHttpsPort ?? settings.httpsPort;
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";
@@ -199,6 +227,22 @@ export async function render(root, { api, info, setMeta, actions }) {
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(),
@@ -211,7 +255,7 @@ export async function render(root, { api, info, setMeta, actions }) {
httpsPort: Number(value("httpsPort", settings.httpsPort)),
// Empty clears a public port (0); a locked one is sent as it is.
publicHttpPort: publicValue("publicHttpPort"),
publicHttpsPort: publicValue("publicHttpsPort"),
publicHttpsPort: nextPublic,
tlsMode: String(value("tlsMode", settings.tlsMode)),
tlsCert: String(value("tlsCert", settings.tlsCert ?? "")).trim() || null,
tlsKey: String(value("tlsKey", settings.tlsKey ?? "")).trim() || null,
@@ -149,9 +149,12 @@ public sealed class ServerOptions
[JsonIgnore]
public bool InContainer { get; set; }
/// <summary>In a container, <c>server.json</c> held listening ports, which were ignored: the start says so.</summary>
/// <summary>
/// In a container, <c>server.json</c> held listening ports, which were ignored: the start says so, and the next save of
/// the settings removes them from the file (<see cref="ServerSettingsStore.Save"/>).
/// </summary>
[JsonIgnore]
public bool IgnoredSavedPorts { get; private set; }
public bool IgnoredSavedPorts { get; internal set; }
public TlsMode TlsMode { get; set; } = TlsMode.Auto;
public string? TlsCert { get; set; }
@@ -60,14 +60,23 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
var changes = Changes(current, request);
var fixedSettings = LockedSettings(options);
if (changes.FirstOrDefault(c => fixedSettings.Contains(c.Name)) is { Name: { } locked }) return ("setting_locked", locked);
if (changes.Count == 0) return null;
// In a container the listening ports are the template's: ports an earlier version saved are dropped at the first
// save, so the start stops warning about them (owner review 3).
var dropPorts = options.InContainer && options.IgnoredSavedPorts;
if (changes.Count == 0 && !dropPorts) return null;
var file = File.Exists(options.SettingsFile) ? JsonNode.Parse(File.ReadAllText(options.SettingsFile)) as JsonObject ?? [] : [];
foreach (var (name, value) in changes) file[name] = value;
// The former name of the parallelism (jobs run at once before owner review 1) would set it again at the next start.
if (changes.Any(c => c.Name == nameof(ServerOptions.Parallelism))) file.Remove("Workers");
if (options.InContainer)
{
file.Remove(nameof(ServerOptions.HttpPort));
file.Remove(nameof(ServerOptions.HttpsPort));
}
Directory.CreateDirectory(options.DataPath);
AtomicFile.WriteAllText(options.SettingsFile, file.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
if (dropPorts) options.IgnoredSavedPorts = false;
options.ServerName = request.ServerName.Trim();
options.Discovery = request.Discovery;
+2 -1
View File
@@ -97,7 +97,8 @@ public static class ServerHost
if (options.IgnoredSavedPorts)
{
app.Logger.LogWarning("server.json sets HttpPort or HttpsPort, which a container ignores: it listens on {Http} and {Https}, the ports the "
+ "template maps. Set CHRONOS_HTTP_PORT or CHRONOS_HTTPS_PORT to change them, and the public ports to the host ports clients use.",
+ "template maps. Saving the settings in the admin panel removes the saved values. Set the Public HTTP and HTTPS ports to the host "
+ "ports clients use; with network type Host, add the variable CHRONOS_HTTP_PORT or CHRONOS_HTTPS_PORT to listen on other ports.",
options.HttpPort, options.HttpsPort);
}
app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("Chronos Server stopping"));
@@ -161,20 +161,25 @@ public sealed class ConnectViewModel : ObservableObject, INotifyDataErrorInfo
{
var (result, fingerprint) = await _session.SignInAsync(Address, Username.Trim(), Password, CancellationToken.None);
if (result != SignInResult.Untrusted || fingerprint is null) return result;
if (!_dialogs.ConfirmTrust(Display(Address), fingerprint)) return SignInResult.Untrusted;
if (!_dialogs.ConfirmTrust(Asked(), fingerprint)) return SignInResult.Untrusted;
_session.Trust(fingerprint);
(result, _) = await _session.SignInAsync(Address, Username.Trim(), Password, CancellationToken.None);
return result;
}
/// <summary>
/// The address as it is asked, port included: "192.168.1.20" goes to port 8443 (owner review 3), which the trust question
/// and the not-Chronos error both name.
/// </summary>
private string Asked() => ServerAddress.TryParse(Address, out var asked) ? Display(asked.ToString()) : Address.Trim();
/// <summary>Puts each failure where it belongs: on the field it is about, or in the sentence under the form.</summary>
private void ShowResult(SignInResult? result)
{
AddressError = result switch
{
SignInResult.InvalidAddress => Loc.L("Uploader.Connect.Error.InvalidAddress"),
// The address as it was asked, port included: "192.168.1.20" went to port 8443 (owner review 3).
SignInResult.NotChronos => Loc.L("Uploader.Connect.Error.NotChronosAt", "‪" + (ServerAddress.TryParse(Address, out var asked) ? Display(asked.ToString()) : Address.Trim()) + "‬"),
SignInResult.NotChronos => Loc.L("Uploader.Connect.Error.NotChronosAt", "‪" + Asked() + "‬"),
_ => null,
};
PasswordError = result == SignInResult.BadCredentials ? Loc.L("Uploader.Connect.Error.BadCredentials") : null;