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

+2 -1
View File
@@ -228,7 +228,8 @@ security problems go privately to the maintainers (`SECURITY.md`), never into a
- Ports: in a container the server listens on 8080 and 8443 (read-only in the admin panel); the host ports clients use
are the *Public HTTP/HTTPS port* settings (`CHRONOS_PUBLIC_HTTP_PORT`, `CHRONOS_PUBLIC_HTTPS_PORT`). Clients type the
*Client address* of Settings › Network and TLS; LAN discovery reaches them only with host networking (Unraid network
type *Host*). The user guide (`deploy/releases-repo/README.md`) explains both.
type *Host*), where the port mappings do nothing and `CHRONOS_HTTP_PORT` / `CHRONOS_HTTPS_PORT` move the listening
ports off ones another service uses. The user guide (`deploy/releases-repo/README.md`) explains both.
## Repository layout
+5
View File
@@ -17,6 +17,8 @@ services:
# ports. LAN discovery reaches clients only with "network_mode: host"; on this bridge network clients type the
# client address. With host networking drop "ports", give the postgres service
# ports: ["127.0.0.1:5432:5432"] and set CHRONOS_DB_HOST to 127.0.0.1: the name "postgres" no longer resolves there.
# The server then listens on the host's 8080 and 8443 itself: if another service uses either, set CHRONOS_HTTP_PORT
# or CHRONOS_HTTPS_PORT below to a free port and leave the public ports unset.
ports:
- "8080:8080"
- "8443:8443"
@@ -41,6 +43,9 @@ services:
# longer change them.
# CHRONOS_PUBLIC_HTTP_PORT: "8080"
# CHRONOS_PUBLIC_HTTPS_PORT: "8443"
# The ports the server listens on, with network_mode: host only (on a bridge network the mapping above decides).
# CHRONOS_HTTP_PORT: "8080"
# CHRONOS_HTTPS_PORT: "8443"
CHRONOS_SERVER_NAME: Chronos Server
# Jobs run one at a time. Photos the running job processes at once (default: half the cores), and the priority queue
# (a higher job pauses the running one, which resumes afterwards). Set here, they can no longer be changed in the
+7 -1
View File
@@ -108,6 +108,10 @@ certificate is never offered for trust.
client address in Chronos and in the Uploader. With `network_mode: host` the name `postgres` no longer resolves: remove the
`ports` of the `chronos` service, publish PostgreSQL on loopback (`ports: ["127.0.0.1:5432:5432"]` under `postgres`)
and set `CHRONOS_DB_HOST: 127.0.0.1`.
- With host networking the port mappings do nothing: the server listens on the host's 8080 and 8443 itself, and the
container does not start when another service already uses either. Then add the variable `CHRONOS_HTTP_PORT` or
`CHRONOS_HTTPS_PORT` with a free port (compose: under `environment`; Unraid: *Add another Path, Port, Variable…* ›
*Variable*, Key `CHRONOS_HTTPS_PORT`), and leave the public ports empty: clients reach the listening ports directly.
- Behind a reverse proxy (`CHRONOS_TLS_MODE=proxy`), only the proxies listed in `CHRONOS_TRUSTED_PROXIES` may set
`X-Forwarded-*` headers. By default that is loopback only: other machines on your network reach the HTTP port
directly, so they must not choose the address the sign-in limit and the audit log see. List your proxy's own
@@ -137,7 +141,9 @@ certificate is never offered for trust.
array's free space rather than the cache's. Change it with the archive share, or remove it and clear *Space path*.
4. Open the WebUI (`http://[IP]:8080/admin`). Clients connect to the *Client address* in Settings › Network and TLS,
`https://[IP]:<HTTPS port>`. On network type *Bridge* LAN discovery stays inside Docker, so clients do not find the
server by themselves: type that address. Network type *Host* lets them find it.
server by themselves: type that address. Network type *Host* lets them find it; the server then listens on the
host's own 8080 and 8443, so when another service uses either, add the variable `CHRONOS_HTTP_PORT` or
`CHRONOS_HTTPS_PORT` first (see host networking above).
Upgrading a container made from an earlier template, or one on `:nightly`: edit the container, set *Repository* to
`…/chronos-server:latest`, and set *Public HTTP port* and *Public HTTPS port* to the host ports the template maps (for
+3 -3
View File
@@ -9,7 +9,7 @@
<Privileged>false</Privileged>
<Support>https://gitea.encke-hake.ts.net/BalboSoft/Chronos/issues</Support>
<Project>https://gitea.encke-hake.ts.net/BalboSoft/Chronos</Project>
<Overview>Chronos Server keeps a shared, verified archive of time-lapse photo sequences and renders them. Pair it with the official PostgreSQL 17 container. Clients connect to the Client address the admin panel shows (Settings, Network and TLS); LAN discovery reaches them only with network type Host.</Overview>
<Overview>Chronos Server keeps a shared, verified archive of time-lapse photo sequences and renders them; pair it with the official PostgreSQL 17 container. Clients connect to the Client address the admin panel shows (Settings, Network and TLS); LAN discovery needs network type Host.</Overview>
<Category>MediaServer:Photos Tools:</Category>
<WebUI>http://[IP]:[PORT:8080]/admin</WebUI>
<TemplateURL>https://gitea.encke-hake.ts.net/BalboSoft/Chronos/raw/branch/main/deploy/unraid/chronos.xml</TemplateURL>
@@ -21,8 +21,8 @@
<DonateText/>
<DonateLink/>
<Requires>A PostgreSQL 16 or 17 container (official "postgres" template) with a database and user for Chronos.</Requires>
<Config Name="HTTP port" Target="8080" Default="8080" Mode="tcp" Description="Admin panel and API over HTTP. When you change it, enter the same port in Public HTTP port." Type="Port" Display="always" Required="true" Mask="false">8080</Config>
<Config Name="HTTPS port" Target="8443" Default="8443" Mode="tcp" Description="API over TLS for Chronos clients, which connect to https://[server IP]:[this port]. When you change it, enter the same port in Public HTTPS port." Type="Port" Display="always" Required="true" Mask="false">8443</Config>
<Config Name="HTTP port" Target="8080" Default="8080" Mode="tcp" Description="Admin panel and API over HTTP; when you change it, enter the same port in Public HTTP port. Network type Host ignores this mapping: the server then listens on 8080 itself." Type="Port" Display="always" Required="true" Mask="false">8080</Config>
<Config Name="HTTPS port" Target="8443" Default="8443" Mode="tcp" Description="API over TLS for Chronos clients, which connect to https://[server IP]:[this port]; when you change it, enter the same port in Public HTTPS port. Network type Host ignores this mapping: the server then listens on 8443 itself." Type="Port" Display="always" Required="true" Mask="false">8443</Config>
<Config Name="Public HTTP port" Target="CHRONOS_PUBLIC_HTTP_PORT" Default="" Mode="" Description="The HTTP port above, when it is not 8080; LAN discovery announces it. Set here, the admin panel can no longer change it (empty: 8080, changeable in the admin panel)." Type="Variable" Display="always" Required="false" Mask="false"/>
<Config Name="Public HTTPS port" Target="CHRONOS_PUBLIC_HTTPS_PORT" Default="" Mode="" Description="The HTTPS port above, when it is not 8443: the port of the client address, the admin panel's redirect and LAN discovery. Set here, the admin panel can no longer change it (empty: 8443, changeable in the admin panel)." Type="Variable" Display="always" Required="false" Mask="false"/>
<Config Name="Archive" Target="/archive" Default="/mnt/user/Timelapse" Mode="rw" Description="Originals, sidecars, proxies and renders." Type="Path" Display="always" Required="true" Mask="false">/mnt/user/Timelapse</Config>
+17 -9
View File
@@ -1501,9 +1501,11 @@ per-sequence sync actions and states; conflict resolution only for settings JSON
mine / take server / save both). The address field, here and in the Uploader (§15), reads
one rule: no scheme means HTTPS, and then no port means 8443, the server's HTTPS port;
`https://<name>` alone keeps 443 (a reverse proxy); a typed port is kept; a bare IPv6
address gets its brackets. An address that answers but not as a Chronos Server (an HTML
page, a redirect to a sign-in page, a 4xx without a Chronos error, JSON of another shape)
fails with one sentence naming the address and the port to check; behind a certificate not
address gets its brackets; a link-local one with a zone index is refused. An address that
answers but not as a Chronos Server (any redirect, an answer that is not JSON, an error
without Chronos's `X-Chronos-Api` header and error code, JSON of another shape, more than
1 MB, or plain HTTP on a port reached over HTTPS) fails with one sentence naming the
address and the port to check; behind a certificate not
trusted yet, `server/info` is read once without checking it and without credentials, and only
a Chronos answer leads to the fingerprint question, so another service's certificate is never
offered for trust (amended 2026-11-04, owner review 3).
@@ -2132,9 +2134,12 @@ Network and TLS (amended 2026-11-04, owner review 3): HTTP port and HTTPS port (
container *Container HTTP/HTTPS port*, read-only: the template maps them to host ports),
*Public HTTP port* and *Public HTTPS port* (empty: the listening port, shown as placeholder;
applied at once to LAN discovery and the HTTPS redirect), and a read-only *Client address*
with Copy: `https://<the host name the browser used>:<public HTTPS port>`, the proxy's
address in TLS mode proxy, which is what users type in Chronos and the Uploader; the
discovery tooltip says that a container needs network type Host for it. The
with Copy: `https://<the host name the browser used>:<the HTTPS port the page came through,
else the public HTTPS port>`, the proxy's address in TLS mode proxy, which is what users type
in Chronos and the Uploader; when the page's HTTPS port is not the saved one, a *Use <port>*
button fills it in as the Public HTTPS port, and saving a Public HTTPS port other than the
page's asks first, as the redirect follows it at once; the discovery tooltip says that a
container needs network type Host for it. The
last group of Settings, About, is read-only: version, API version, database and uptime (the
server name and the fingerprint are in the groups above); an old `#/about` link opens Settings on it (amended 2026-10-26,
R4, R5). Same UI rules: tooltips only, light/dark, localised via `/api/v1/i18n`, keyboard
@@ -2287,8 +2292,9 @@ conversion the tighter of the two, §14.3: amended 2026-10-26, R7),
`CHRONOS_DB_NAME`, `CHRONOS_DB_USER`, `CHRONOS_DB_PASSWORD`, `CHRONOS_DB_SSLMODE=prefer`,
`CHRONOS_HTTP_PORT=8080`, `CHRONOS_HTTPS_PORT=8443` (in a container, where
`DOTNET_RUNNING_IN_CONTAINER=true`, the listening ports are the template's: only these
variables change them, the admin panel shows them read-only and a `server.json` value is
ignored with a warning), `CHRONOS_PUBLIC_HTTP_PORT` and `CHRONOS_PUBLIC_HTTPS_PORT` (the host
variables change them, which network type Host needs when another service uses 8080 or
8443; the admin panel shows them read-only and a `server.json` value is ignored with a
warning and removed at the next save), `CHRONOS_PUBLIC_HTTP_PORT` and `CHRONOS_PUBLIC_HTTPS_PORT` (the host
ports clients use when a container's ports are published as others: LAN discovery, the HTTPS
redirect and the admin panel's client address use them; also the admin panel's *Public
HTTP/HTTPS port*, `PublicHttpPort`/`PublicHttpsPort` in `server.json`, applied at once;
@@ -2562,7 +2568,9 @@ the default), so the admin panel's Settings › Logs chooses them; a value given
template locks its setting; TZ also sets the time zone of the schedules; amended
2026-10-26, R10, R11), *Public HTTP port* `CHRONOS_PUBLIC_HTTP_PORT` and *Public HTTPS port*
`CHRONOS_PUBLIC_HTTPS_PORT`, empty by default, next to the ports, whose descriptions say to
enter the same host port there when it changes; the overview names the client address and
enter the same host port there when it changes and that network type Host ignores the mapping (the
server then listens on 8080 and 8443 itself; the user guide says to add `CHRONOS_HTTP_PORT` /
`CHRONOS_HTTPS_PORT` when another service uses either); the overview names the client address and
that LAN discovery needs network type Host (amended 2026-11-04, owner review 3), description ≤ 2 sentences.
Registry and Project `https://gitea.encke-hake.ts.net/BalboSoft/Chronos`,
Support `https://gitea.encke-hake.ts.net/BalboSoft/Chronos/issues`, TemplateURL
+12 -3
View File
@@ -10,7 +10,10 @@ commits follow Conventional Commits (release notes are generated from them by `C
(owner review 3). The admin panel's Settings › Network and TLS listed the container's ports (8080, 8443) as if
clients used them. In a container it now shows them read-only as *Container HTTP port* and *Container HTTPS port*,
followed by *Public HTTP port* and *Public HTTPS port* (the host ports; empty: the same as the listening ports) and
a *Client address* with Copy: exactly what to type in Chronos and in the Uploader.
a *Client address* with Copy: exactly what to type in Chronos and in the Uploader. Opened over HTTPS, the client
address uses the port the page came through, and when the saved one differs a *Use …* button fills it in as the
Public HTTPS port. Saving a Public HTTPS port other than that one asks first, since the panel's link follows it at
once.
- An address typed without a port (`192.168.1.20`, `nas.local`) now means port 8443, as the placeholder shows;
`https://name` alone still means 443 (a reverse proxy), and a typed port is kept. Addresses saved earlier keep their
port.
@@ -18,13 +21,16 @@ commits follow Conventional Commits (release notes are generated from them by `C
sign-in page, a 404 or 401, JSON of another kind) now says *No Chronos server answers at …; check the port*, naming
the address with its port. Before, JSON of another kind passed as a server (the Uploader then sent it the
password), a 401 read as a wrong password, and another service's self-signed certificate was offered for trust;
that certificate is now never offered.
that certificate is now never offered (redirects of any kind, error pages, JSON errors without Chronos's header and
oversized answers included). The HTTP port typed without a scheme (`192.168.1.20:8087`) gives the same message
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 (`fe80::1%12`) is refused as an invalid address instead of losing its zone.
### Changed
- The public ports are server settings: edited in the admin panel and applied at once to LAN discovery and the
redirect to HTTPS, or set by `CHRONOS_PUBLIC_HTTP_PORT` / `CHRONOS_PUBLIC_HTTPS_PORT`, which lock them. In a
container the listening ports change only through `CHRONOS_HTTP_PORT` / `CHRONOS_HTTPS_PORT`; a port saved for them
in `server.json` is ignored, with a warning in the log.
in `server.json` is ignored, with a warning in the log, and removed at the next save of the settings.
- The Unraid template and the compose file have *Public HTTP port* (`CHRONOS_PUBLIC_HTTP_PORT`) next to *Public HTTPS
port*; the port descriptions say to enter the same host port there. LAN discovery's tooltip, the template and the
user guide say that discovery leaves a container only with network type *Host*: on *Bridge*, type the client
@@ -35,6 +41,9 @@ commits follow Conventional Commits (release notes are generated from them by `C
HTTP port* and *Public HTTPS port* to the host ports the template maps (for example 8087 and 8444), or, after the
update, enter them in the admin panel's Settings › Network and TLS. Then connect Chronos and the Uploader to the
*Client address* shown there (for example `https://192.168.1.20:8444`).
- Network type *Host* (for LAN discovery) ignores the port mappings: the server listens on the host's 8080 and 8443.
If another service uses either, add the variable `CHRONOS_HTTP_PORT` or `CHRONOS_HTTPS_PORT` with a free port first,
and leave the public ports empty.
## [0.1.0-rc.8] — 2026-11-03
+7 -2
View File
@@ -615,7 +615,12 @@ One line per decision: date · decision · alternative · reason.
| 2026-11-04 | `ServerSettingsDto` gains `PublicHttpPort`, `PublicHttpsPort` and `InContainer`, appended as optional positional members. In a request a null public port keeps the saved value and 0 clears it; responses send null when unset. | null clears | A client or script of the earlier shape sends no public ports: with null as "clear" every save from it would drop them, or be refused as `setting_locked` when a variable fixes them. |
| 2026-11-04 | In a container (`DOTNET_RUNNING_IN_CONTAINER=true`, read in `ServerOptions.Load`; tests set `ServerOptions.InContainer`) the listening ports are locked (listed in `Locked`, `lockedBy` `DOTNET_RUNNING_IN_CONTAINER` unless a `CHRONOS_HTTP(S)_PORT` sets them) and a `server.json` value for them is ignored with a warning at start; the variables still change them. | Keep honouring server.json | The template publishes the default container ports: a port saved from the panel before would leave the container unreachable after a restart. Host networking users who need other ports set the variables. |
| 2026-11-04 | Listening ports are validated only when a request changes them. | Always validate | A value the panel cannot change (a container's, the test server's 0) must never block saving the other settings. |
| 2026-11-04 | The admin panel's client address is computed in the browser from the saved settings: `https://` + `location.hostname` (IPv6 in brackets) + `:` + public HTTPS port or HTTPS port (no port when 443); `location.origin` in TLS mode proxy. No other page shows a pairing code or a connect hint, so it appears only in Settings › Network and TLS. | Server-side address | Only the browser knows the host name the LAN uses for the server (an IP, a NAS name); the server sees its container address. |
| 2026-11-04 | The admin panel's client address is computed in the browser: `https://` + `location.hostname` (IPv6 in brackets) + `:` + the port the page came through when the browser speaks HTTPS to the server itself, else (plain HTTP, only from the server's own machine) the public HTTPS port or HTTPS port (no port when 443); `location.origin` in TLS mode proxy. When the page's HTTPS port is not the saved one (a container's 8443 published as 8444, Public HTTPS port still empty), a *Use 8444* button next to Public HTTPS port fills it in. No other page shows a pairing code or a connect hint, so it appears only in Settings › Network and TLS. | Server-side address | Only the browser knows the host name the LAN uses for the server (an IP, a NAS name); the server sees its container address. |
| 2026-11-04 | One address rule for both clients, `Chronos.Protocol.Client.ChronosAddress` (both apps reference Chronos.Protocol, which builds on Linux): no scheme and no port means https on 8443, `https://host` keeps 443, a typed port is kept, a bare IPv6 address is bracketed. Saved addresses carry their scheme, so they keep their port. | A copy per app | The placeholder and the error text say `nas.local:8443`; "192.168.30.23" meant port 443. |
| 2026-11-04 | `ChronosClient.GetInfoAsync` throws `NotChronosServerException` for an HTML or redirected page, JSON without a Chronos `ServerInfo` (name, version, API version, lists, limits), or a 4xx without a Chronos error; on an untrusted certificate it reads `server/info` once more with certificate checks off and no token, and only a Chronos answer leads to the fingerprint question. Nothing is trusted or stored by that read. | Ask about the fingerprint first | Before, `{}` was accepted as a server (the Uploader then sent the password to it), a 401 read as a wrong password, and the self-signed certificate of another service on port 8443 was offered for trust. |
| 2026-11-04 | `ChronosClient.GetInfoAsync` throws `NotChronosServerException` when `server/info` is not Chronos's: any 3xx (Chronos never redirects it), any answer that is not JSON whatever its status, more than 1 MB, JSON without a Chronos `ServerInfo` (name, version, API version, lists, limits), or an error without the `X-Chronos-Api` header every Chronos response carries and a Chronos error code. A busy answer (408, 429, 502-504) with JSON or no body cannot tell. On an untrusted certificate it reads `server/info` once more with certificate checks off, no token, no cookies and no redirects, under the same rules, and only a Chronos answer leads to the fingerprint question. Nothing is trusted or stored by that read. | Ask about the fingerprint first | Before, `{}` was accepted as a server (the Uploader then sent the password to it), a 401 read as a wrong password, and the self-signed certificate of another service on port 8443 was offered for trust. |
| 2026-11-04 | The not-Chronos error names the normalised address (port included) in new keys `Server.Error.NotChronosAt` and `Uploader.Connect.Error.NotChronosAt`; the old keys stay as they are. | Add {0} to the old keys | The 36 other cultures translate the old keys without the placeholder; changing it would fail the i18n check until they are translated again. |
| 2026-11-04 | Saving a public HTTPS port (or clearing it to the listening one) other than both the saved one and the port this page came through over HTTPS asks first (*Send clients to port 8445?*); the server does not check it. | Server-side warning in the log | The HTTPS redirect follows the saved port at once, so a typo would send the panel's link to a dead port or another service's sign-in page; only the browser knows which port really reached the server. Saving other settings never asks. |
| 2026-11-04 | `GetInfoAsync`: when TLS fails on an HTTPS address and no certificate was refused (the port speaks plain HTTP: the HTTP port typed without a scheme, `192.168.30.23:8087`), it reads `server/info` over `http://` on the same authority, without credentials; any answer gives `NotChronosServerException` (check the port, the client address), no answer rethrows (unreachable). | Report it as unreachable | The server did answer; the useful advice is the port and the panel's client address. |
| 2026-11-04 | In a container, the first save of the settings removes `HttpPort` and `HttpsPort` from `server.json` (also when nothing else changed); the start-up warning says so. | Remove them at load | Load only reads; the panel cannot edit locked ports, so without this the warning came back at every start. |
| 2026-11-04 | Host networking: the guide, README and compose comments say the port mappings do nothing there, the server listens on the host's 8080/8443 and `CHRONOS_HTTP_PORT` / `CHRONOS_HTTPS_PORT` move it off ports another service uses (public ports empty). No template entries for them. | Advanced template entries *Listening HTTP/HTTPS port* | On Bridge such an entry would unmap the template's ports; Host users add a variable, which Unraid offers on every container. |
| 2026-11-04 | `ChronosAddress` refuses a link-local IPv6 address with a zone index (`fe80::1%12`): *Invalid address*. | Keep the zone as `%25` | `Uri` and the connection would drop the zone, failing later with a less clear error; the LAN address or name works. |
+7
View File
@@ -840,6 +840,11 @@
<data name="Admin.Settings.Parallelism.Tip" xml:space="preserve"><value>Photos the running job processes at once; jobs run one at a time</value></data>
<data name="Admin.Settings.PemMissing" xml:space="preserve"><value>The PEM file was not found; enter its full path on the server.</value><comment>long</comment></data>
<data name="Admin.Settings.PemOnly.Tip" xml:space="preserve"><value>Used only in Own certificate mode</value></data>
<data name="Admin.Settings.PortChangeBody" xml:space="preserve"><value>This page came through port {0}. The panel&apos;s link and LAN discovery move to the new port at once; if it is wrong, open the panel on port {0} to fix it.</value><comment>long</comment></data>
<data name="Admin.Settings.PortChangeConfirm" xml:space="preserve"><value>Save port</value></data>
<data name="Admin.Settings.PortChangeConfirm.Tip" xml:space="preserve"><value>Save {0} as the Public HTTPS port; clients and the HTTPS redirect use it at once</value></data>
<data name="Admin.Settings.PortChangeKeep.Tip" xml:space="preserve"><value>Back to the form, nothing saved</value></data>
<data name="Admin.Settings.PortChangeTitle" xml:space="preserve"><value>Send clients to port {0}?</value></data>
<data name="Admin.Settings.Priority.High" xml:space="preserve"><value>High</value></data>
<data name="Admin.Settings.Priority.Low" xml:space="preserve"><value>Low</value></data>
<data name="Admin.Settings.Priority.Normal" xml:space="preserve"><value>Normal</value></data>
@@ -871,6 +876,8 @@
<data name="Admin.Settings.TokenLifetimeDays.Tip" xml:space="preserve"><value>Days a client stays signed in without being used</value></data>
<data name="Admin.Settings.UploadRetentionHours" xml:space="preserve"><value>Abandoned after (h)</value></data>
<data name="Admin.Settings.UploadRetentionHours.Tip" xml:space="preserve"><value>Hours after which unfinished uploads are discarded</value></data>
<data name="Admin.Settings.UsePagePort" xml:space="preserve"><value>Use {0}</value></data>
<data name="Admin.Settings.UsePagePort.Tip" xml:space="preserve"><value>This page came through port {0}, so clients reach the server there: fill it in as the Public HTTPS port, then save, and discovery and the HTTPS redirect follow</value></data>
<data name="Admin.SignOut" xml:space="preserve"><value>Sign out</value></data>
<data name="Admin.SignOut.Tip" xml:space="preserve"><value>Sign out of the admin panel</value></data>
<data name="Admin.Theme.Tip" xml:space="preserve"><value>Switch between light and dark</value></data>
+7
View File
@@ -833,6 +833,11 @@
<data name="Admin.Settings.Parallelism.Tip" xml:space="preserve"><value>Foto che l'attività in corso elabora insieme; le attività girano una alla volta</value></data>
<data name="Admin.Settings.PemMissing" xml:space="preserve"><value>File PEM non trovato; inserisci il percorso completo sul server.</value></data>
<data name="Admin.Settings.PemOnly.Tip" xml:space="preserve"><value>Usato solo in modalità Certificato proprio</value></data>
<data name="Admin.Settings.PortChangeBody" xml:space="preserve"><value>Questa pagina è arrivata dalla porta {0}. Il collegamento al pannello e il rilevamento LAN passano subito alla nuova porta; se è sbagliata, apri il pannello sulla porta {0} per correggerla.</value></data>
<data name="Admin.Settings.PortChangeConfirm" xml:space="preserve"><value>Salva porta</value></data>
<data name="Admin.Settings.PortChangeConfirm.Tip" xml:space="preserve"><value>Salva {0} come porta HTTPS pubblica; i client e il reindirizzamento HTTPS la usano subito</value></data>
<data name="Admin.Settings.PortChangeKeep.Tip" xml:space="preserve"><value>Torna al modulo senza salvare</value></data>
<data name="Admin.Settings.PortChangeTitle" xml:space="preserve"><value>Mandare i client alla porta {0}?</value></data>
<data name="Admin.Settings.Priority.High" xml:space="preserve"><value>Alta</value></data>
<data name="Admin.Settings.Priority.Low" xml:space="preserve"><value>Bassa</value></data>
<data name="Admin.Settings.Priority.Normal" xml:space="preserve"><value>Normale</value></data>
@@ -864,6 +869,8 @@
<data name="Admin.Settings.TokenLifetimeDays.Tip" xml:space="preserve"><value>Giorni in cui un client resta connesso senza essere usato</value></data>
<data name="Admin.Settings.UploadRetentionHours" xml:space="preserve"><value>Abbandono dopo (h)</value></data>
<data name="Admin.Settings.UploadRetentionHours.Tip" xml:space="preserve"><value>Ore dopo le quali i caricamenti incompleti vengono scartati</value></data>
<data name="Admin.Settings.UsePagePort" xml:space="preserve"><value>Usa {0}</value></data>
<data name="Admin.Settings.UsePagePort.Tip" xml:space="preserve"><value>Questa pagina è arrivata dalla porta {0}, quindi i client raggiungono il server lì: inseriscila come porta HTTPS pubblica e salva, così il rilevamento LAN e il reindirizzamento HTTPS la seguono</value></data>
<data name="Admin.SignOut" xml:space="preserve"><value>Esci</value></data>
<data name="Admin.SignOut.Tip" xml:space="preserve"><value>Esci dal pannello di amministrazione</value></data>
<data name="Admin.Theme.Tip" xml:space="preserve"><value>Alterna tema chiaro e scuro</value></data>
+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;
@@ -33,5 +33,9 @@ public sealed class ServerAddressTests
[Case(" ")]
[Case("ftp://nas.local")]
[Case("https://")]
// A zone index cannot reach the request: refused rather than dropped.
[Case("fe80::1%12")]
[Case("[fe80::1%12]:8443")]
[Case("https://[fe80::1%2512]")]
public void InvalidServerAddressesAreRejected(string typed) => Assert.False(ServerAddress.TryParse(typed, out _));
}
@@ -21,17 +21,48 @@ namespace Chronos.Server.Tests.Api;
[Category("server")]
public sealed class ServerIdentityTests(TestContext context)
{
/// <summary>Answers of another service, each under its own path.</summary>
private static readonly string[] OtherAnswers =
[
"html/", "redirect/", "away/", "empty/", "json/", "unauthorized/", "missing/", "text/", "failed/", "gateway/", "json401/", "json403/",
"json404/", "huge/", "hugejson/",
];
[Test]
public async Task AnAddressThatAnswersAsSomethingElseIsNotAChronosServer()
{
await using var other = await OtherService.StartAsync(context);
foreach (var path in new[] { "html/", "redirect/", "empty/", "json/", "unauthorized/", "missing/" })
// Over HTTP, and over HTTPS behind the service's own certificate, which nobody trusted.
foreach (var address in new[] { other.Http, other.Https }.SelectMany(root => OtherAnswers.Select(path => new Uri(root, path))))
{
var address = new Uri(other.Http, path);
using var client = new ChronosClient(address, new CertificatePinning([]), "tests");
var error = await Assert.ThrowsAsync<NotChronosServerException>(() => client.GetInfoAsync(context.Cancellation));
Assert.Equal(address, error.Address, path);
var error = await Assert.ThrowsAsync<NotChronosServerException>(() => client.GetInfoAsync(context.Cancellation), address.ToString());
Assert.Equal(address, error.Address, address.ToString());
}
Assert.Equal(0, other.Authorized, "no request carried credentials");
}
[Test]
public async Task TheHttpPortTypedWithoutASchemeIsNotAChronosServer()
{
// "192.168.30.23:8087", the port of the panel's link: HTTPS to a port that answers plain HTTP.
await using var server = await TestServer.StartAsync(context);
Assert.True(ChronosAddress.TryParse($"127.0.0.1:{server.HttpBase.Port}", out var typed));
using var client = new ChronosClient(typed, new CertificatePinning([]), "tests");
var error = await Assert.ThrowsAsync<NotChronosServerException>(() => client.GetInfoAsync(context.Cancellation));
Assert.Equal(typed, error.Address);
await using var other = await OtherService.StartAsync(context);
using var otherClient = new ChronosClient(new UriBuilder(other.Http) { Scheme = "https", Port = other.Http.Port }.Uri, new CertificatePinning([]), "tests");
await Assert.ThrowsAsync<NotChronosServerException>(() => otherClient.GetInfoAsync(context.Cancellation));
// A port where nothing answers is still unreachable, not another service.
var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);
listener.Start();
var closed = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
using var nobody = new ChronosClient(new Uri($"https://127.0.0.1:{closed}/"), new CertificatePinning([]), "tests");
await Assert.ThrowsAsync<HttpRequestException>(() => nobody.GetInfoAsync(context.Cancellation));
}
[Test]
@@ -110,6 +141,17 @@ public sealed class ServerIdentityTests(TestContext context)
app.MapGet("/empty/api/v1/server/info", () => Results.Content("{}", "application/json"));
app.MapGet("/json/api/v1/server/info", () => Results.Content("""{"status":"ok","name":"router"}""", "application/json"));
app.MapGet("/unauthorized/api/v1/server/info", () => Results.StatusCode(StatusCodes.Status401Unauthorized));
// An absolute redirect to plain HTTP, which a client never follows from HTTPS.
app.MapGet("/away/api/v1/server/info", (HttpContext http) => Results.Redirect($"http://{http.Request.Host}/login"));
app.MapGet("/text/api/v1/server/info", () => Results.Text("ok"));
app.MapGet("/failed/api/v1/server/info", () => Results.Content("<!doctype html><title>Error</title>", "text/html", statusCode: StatusCodes.Status500InternalServerError));
app.MapGet("/gateway/api/v1/server/info", () => Results.Content("<!doctype html><title>Bad gateway</title>", "text/html", statusCode: StatusCodes.Status502BadGateway));
// Errors in JSON with a code of their own, as many web services write them.
foreach (var (path, status) in new[] { ("json401", 401), ("json403", 403), ("json404", 404) })
app.MapGet($"/{path}/api/v1/server/info", () => Results.Content("""{"code":"denied","message":"Sign in"}""", "application/json", statusCode: status));
// More than a server info ever holds.
app.MapGet("/huge/api/v1/server/info", () => Results.Content("<!doctype html>" + new string('x', 2 << 20), "text/html"));
app.MapGet("/hugejson/api/v1/server/info", () => Results.Content("{\"name\":\"" + new string('x', 2 << 20) + "\"}", "application/json"));
await app.StartAsync(context.Cancellation);
service = new OtherService(app);
return service;
@@ -166,6 +166,34 @@ public sealed class PublicPortTests(TestContext context)
Assert.False(ServerOptions.Load(Env((ServerOptions.ContainerVariable, "false"))).InContainer);
}
[Test]
public async Task AContainerRemovesListeningPortsSavedEarlierAtTheNextSave()
{
await using var server = await TestServer.StartAsync(context, o =>
{
// As ServerOptions.Load leaves a container whose server.json held ports.
o.InContainer = true;
o.IgnoredSavedPorts = true;
Directory.CreateDirectory(o.DataPath);
File.WriteAllText(o.SettingsFile, """{ "HttpPort": 8087, "HttpsPort": 8444, "ServerName": "NAS" }""");
});
var admin = await server.AdminAsync();
// Nothing changed, and still the saved ports go: the panel cannot edit them, so it could never remove them otherwise.
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", await SettingsAsync(admin), ProtocolJson.Default.ServerSettingsDto))
await saved.ExpectAsync(HttpStatusCode.OK);
var file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject();
Assert.False(file.ContainsKey("HttpPort") || file.ContainsKey("HttpsPort"), "the saved listening ports are removed");
Assert.Equal("NAS", file["ServerName"]!.GetValue<string>());
Assert.False(server.Options.IgnoredSavedPorts);
var restarted = ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = server.Options.DataPath,
["CHRONOS_DB"] = "postgres",
[ServerOptions.ContainerVariable] = "true",
});
Assert.False(restarted.IgnoredSavedPorts, "the next start no longer warns");
}
[Test]
public async Task ASettingsAnswerStaysReadableInTheShapeBeforePublicPorts()
{
@@ -190,7 +218,10 @@ public sealed class PublicPortTests(TestContext context)
await using var server = await TestServer.StartAsync(context);
var page = await server.Client.GetStringAsync("/admin/pages/settings.js");
foreach (var part in new[] { "publicPort(\"publicHttpPort\"", "publicPort(\"publicHttpsPort\"", "field(\"clientAddress\"", "id=\"copy-address\"",
"Admin.Settings.ContainerPort.Tip", "settings.publicHttpsPort ?? settings.httpsPort", "location.origin", "navigator.clipboard.writeText" })
"Admin.Settings.ContainerPort.Tip", "settings.publicHttpsPort ?? settings.httpsPort", "location.origin", "navigator.clipboard.writeText",
// The port the page came through over HTTPS wins over a saved one, is offered for the Public HTTPS port,
// and saving another one asks first (the HTTPS redirect follows it at once).
"pagePort() ?? savedHttps()", "id=\"use-page-port\"", "Admin.Settings.UsePagePort", "Admin.Settings.PortChangeTitle", "confirmDialog({" })
Assert.Contains(part, page);
}