From 0cec95c19b8d402eb88344f3f344f30e97045816 Mon Sep 17 00:00:00 2001 From: Slawomir Koszewski Date: Tue, 24 Nov 2026 18:06:34 +0100 Subject: [PATCH] feature: the CA certificates and CRLs are always published over HTTP and HTTPS on the status and Manager ports, the Shell page is an entry of the page menu, and the web interface passes its lint. --- .gitignore | 1 - ADR.md | 36 ++--- CHANGELOG.md | 36 +++++ README.md | 48 +++---- bin/lm-dev-vm.py | 18 +-- .../src/usr/lib/linux-manager/linuxmanager.py | 49 ++----- .../usr/lib/linux-manager/linuxmanager_pki.py | 4 +- .../linuxmanager_web/__init__.py | 3 - .../linux-manager/linuxmanager_web/handler.py | 7 +- .../lib/linux-manager/linuxmanager_web/pki.py | 5 +- .../src/usr/lib/linux-manager/setup | 19 ++- .../linux-manager/linux-manager.json.example | 1 - .../linux-manager/templates/Caddyfile.j2 | 72 ++++------ docs/certificates.md | 2 +- docs/index.md | 6 +- docs/shell.md | 8 +- tests/remote/README.md | 8 +- tests/remote/configs/core.json | 7 +- tests/remote/configs/dev.json | 5 + tests/remote/configs/nat-off.json | 9 +- tests/remote/configs/nat.json | 8 +- tests/remote/configs/oidc.json | 5 +- tests/remote/configs/pki-offline.json | 11 -- tests/remote/configs/pki-simple-ca.json | 11 -- tests/remote/configs/s2s-a-router-off.json | 8 +- tests/remote/configs/s2s-a.json | 7 +- tests/remote/configs/s2s-b.json | 8 +- web/src/AccountPanel.tsx | 3 +- web/src/AcmeSettingsDialog.tsx | 8 +- web/src/App.tsx | 26 +--- web/src/BackupDialog.tsx | 2 +- web/src/BackupPanel.tsx | 21 +-- web/src/BackupSummary.tsx | 37 +---- web/src/CertificatesPanel.tsx | 51 ++++--- web/src/ComponentsPanel.tsx | 9 +- web/src/DnsPanel.tsx | 43 +++--- web/src/DockerPanel.tsx | 6 +- web/src/GroupsPanel.tsx | 54 +++---- web/src/HelpPanel.tsx | 10 +- web/src/HttpsSettingsDialog.tsx | 9 +- web/src/IssuingCaDialog.tsx | 2 +- web/src/LogsPanel.tsx | 51 ++++--- web/src/MetricsPanel.tsx | 47 ++++--- web/src/NetworkPanel.tsx | 6 +- web/src/PageMenu.tsx | 19 ++- web/src/PanelBoard.tsx | 51 +------ web/src/PkiSettingsDialog.tsx | 85 +---------- web/src/RemoteAccessPanel.tsx | 54 +++---- web/src/SearchField.tsx | 6 - web/src/ServerCertificatePanel.tsx | 48 ++++--- web/src/ServerPanel.tsx | 133 ++++-------------- web/src/ServiceAccountsPanel.tsx | 58 ++++---- web/src/SettingsButton.tsx | 4 +- web/src/ShellPanel.tsx | 19 +-- web/src/SiteFiles.tsx | 55 +++++--- web/src/SiteToSitePanel.tsx | 41 +++--- web/src/SiteToSiteStatusPanel.tsx | 7 +- web/src/SitesPanel.tsx | 65 +++++---- web/src/SystemPanel.tsx | 3 +- web/src/TemplateDialog.tsx | 2 +- web/src/UpdatesNotice.tsx | 7 +- web/src/UsersPanel.tsx | 43 +++--- web/src/api.ts | 5 - web/src/backup.ts | 31 ++++ web/src/format.ts | 31 ++++ web/src/https.ts | 16 +++ web/src/ipsec.ts | 66 +++++++++ web/src/pki.ts | 50 +++++++ web/src/search.ts | 5 + web/src/settings.ts | 2 +- web/src/useBoard.ts | 49 +++++++ web/src/useRead.ts | 29 ++-- 72 files changed, 910 insertions(+), 861 deletions(-) create mode 100644 tests/remote/configs/dev.json delete mode 100644 tests/remote/configs/pki-offline.json delete mode 100644 tests/remote/configs/pki-simple-ca.json create mode 100644 web/src/backup.ts create mode 100644 web/src/format.ts create mode 100644 web/src/https.ts create mode 100644 web/src/ipsec.ts create mode 100644 web/src/pki.ts create mode 100644 web/src/search.ts create mode 100644 web/src/useBoard.ts diff --git a/.gitignore b/.gitignore index 5534de5..5107eea 100644 --- a/.gitignore +++ b/.gitignore @@ -15,7 +15,6 @@ tmp node_modules web/dist .venv -dev.json **/.env /.lm-dev-config/ /debian-package/debian/changelog diff --git a/ADR.md b/ADR.md index a727d0f..8d10c5d 100644 --- a/ADR.md +++ b/ADR.md @@ -812,30 +812,34 @@ P2S access. A server whose root should be elsewhere is set up with that source f the source of an existing root is not changed. The server keeps the users' keys, as the OpenVPN profile embeds them. -## ADR-28: CA certificates and CRLs are published at configurable endpoints, and CRLs are short-lived +## ADR-28: CA certificates and CRLs are always published over plain HTTP, and CRLs are short-lived Status: Accepted Context: Clients outside the server, such as Windows and servers using the general-purpose CAs, find the issuer's certificate and the CRL through the AIA and CRL distribution point extensions, and cache a CRL until its next update. The server's CRLs were valid for ten years and published -nowhere. Caddy serves files itself, and the web service already answers on the status port. +nowhere. Caddy fronts every web port of the server: the status web service's and the Manager's, over +plain HTTP and HTTPS. A client fetching an AIA certificate or a CRL may not follow a redirect, and +checking the revocation of an HTTPS server's certificate over HTTPS depends on itself. -Decision: `pki.publish` lists the endpoints, in the order the URLs appear in the certificates: -plain HTTP on the status port, served by the web service; plain HTTP on port 80, HTTPS on the -status HTTPS port and HTTPS on port 443, served by Caddy's `file_server`. The files are DER, as -RFC 5280 asks of these URLs, copied to `/var/lib/linux-manager/pki-publish`, outside the 0700 PKI -directory, so that Caddy's user reads them. Ports 80 and 443 serve only the CA files and are opened -on both interfaces when chosen. The CRLs of the issuing CAs are valid for `pki.crl_days`, a week -by default, signed again at every revocation and by a daily timer once half their validity has -passed; the root CRL has its own `pki.root_crl_days`, half a year by default, so an offline root -needs its CRL signed twice a year, not weekly. +Decision: the files are always published; there is no setting. Caddy's `file_server` serves them +at `/pki/` on `web.port` and on the Manager's port, ahead of the Manager's redirect to HTTPS, and +on `https.web_port` and `https.manager_port`, with the content types RFC 5280 gives. The +certificates name only the plain HTTP URLs: the status port while the status web service is +enabled, then the Manager's port, which always exists. The files are DER, copied to +`/var/lib/linux-manager/pki-publish`, outside the 0700 PKI directory, so that Caddy's user reads +them. The CRLs of the issuing CAs are valid for `pki.crl_days`, a week by default, signed again at +every revocation and by a daily timer once half their validity has passed; the root CRL has its own +`pki.root_crl_days`, half a year by default, so an offline root needs its CRL signed twice a year, +not weekly. -Consequences: A client that caches a CRL sees a revocation within a week. The URLs are fixed in a -certificate when it is signed, so a change of the endpoints or of `wan.local_fqdn` applies to -certificates signed afterwards. HTTPS URLs are offered for clients that cannot use plain HTTP, -although a client checking the revocation of the HTTPS server's own certificate cannot use them; -Caddy's certificate is Let's Encrypt's, so the server's endpoints do not depend on themselves. +Consequences: A client that caches a CRL sees a revocation within a week. A client tries the URLs +in order, so one that cannot reach the status port falls back to the Manager's. The files are +reachable where the firewall opens those ports: `web.listen` and the Manager's `listen` decide. +The URLs are fixed in a certificate when it is signed, so a change of the ports or of +`wan.local_fqdn` applies to certificates signed afterwards. A `pki.publish` of an earlier version +is left out when the settings are read. ## ADR-29: Site-to-site connections authenticate with a pre-shared key or certificates diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b3cc89..3b17ff7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,41 @@ # Changelog +## 0.44.0 - 2026-11-24 18:06:34 +0100 + +feature: the CA certificates and CRLs are always published over HTTP and HTTPS on the status and +Manager ports, the Shell page is an entry of the page menu, and the web interface passes its lint. + +- pki.publish is gone: Caddy serves /pki/ on web.port while the status web service is enabled, on + the Manager's port, ahead of its redirect to HTTPS, and while HTTPS is on on https.manager_port + and https.web_port, with the content types application/pkix-cert and application/pkix-crl. +- Certificates signed from now on name http://:/pki/, while the status + web service is enabled, and http://:/pki/ for their issuer's + certificate and CRL. +- Ports 80 and 443 no longer serve /pki/; certificates signed with those URLs need to be issued + again to name the new ones. +- A pki.publish in linux-manager.json is left out when the settings are read. +- The PKI settings dialog has no publishing endpoints, and the General panel of the Certificates + page no longer shows them. +- The page menu of an administrator lists Shell, after Docker, and names it while it is shown. +- The terminal icon of the header is gone; the editor icon of the Shell page stays left of the + user's name. +- With Open the shell in a new tab in the settings, the page menu opens the Shell page in a tab of + its own. +- The pages read the server without a second render at their first read, and show busy from the + start until the first answer. +- The Logs tab and the Files tab of the Web Sites page show that they are reading until the log or + the folder just chosen is read. +- The Root CA panel of the Certificates page keys the state chip of its rows. +- The helpers and constants the pages share are in modules of their own, so that hot reload keeps + the state of a page during development. +- npm run lint in web/ reports no warnings. +- The test configurations in tests/remote/configs/ leave HTTPS on and give only settings that + differ from the defaults; pki-offline.json and pki-simple-ca.json, which no scenario used, are + gone. +- The development VM of lm-dev-vm.py is reached on ports 7443 and 7444 too, the Manager and the + status web service over HTTPS, and is configured with tests/remote/configs/dev.json, named + lm-dev.test, instead of the lab's core.json. + ## 0.43.1 - 2026-11-24 14:37:02 +0100 fix: build.py and publish.py print their usage for --help instead of building or publishing. diff --git a/README.md b/README.md index 37a3090..27d4ce8 100644 --- a/README.md +++ b/README.md @@ -176,7 +176,6 @@ must have the type shown below; an unknown section or setting is an error. | `pki` | `key` | string | `rsa-4096` | Key of the root and the issuing CAs: `rsa-2048`, `rsa-3072`, `rsa-4096`, `ec-p256` or `ec-p384` | | `pki` | `crl_days` | integer | `7` | Days the CRLs of the issuing CAs are valid | | `pki` | `root_crl_days` | integer | `180` | Days the root CRL is valid, when the server signs it | -| `pki` | `publish` | list | `http` | Where the CA certificates and CRLs are published: `http`, `http-80`, `https`, `https-default` (see Certificates) | | `pki` | `p2s_name` | string | `Linux Manager VPN CA` | Common name of the P2S issuing CA; fixed once the CA exists, from when the VPN is first on | | `pki` | `s2s_name` | string | `Linux Manager Site-to-Site CA` | Common name of the site-to-site issuing CA; fixed once the CA exists, from when the router is first on | | `pki` | `servers_name` | string | `Linux Manager Servers CA` | Common name of the Servers Issuing CA; fixed by the first setup, which creates the CA | @@ -639,21 +638,22 @@ certificate is revoked by removing the user, and an issuing CA by removing it fr ### Published certificates and CRLs -Every certificate names its issuer's certificate (AIA) and CRL (CRL distribution point) at each -endpoint of `pki.publish`, in that order. They are served, without authentication, as DER at -`/pki/.crt` and `/pki/.crl`, the root as `root`, from copies in -`/var/lib/linux-manager/pki-publish`: +Caddy serves the CA certificates and CRLs, without authentication, as DER at `/pki/.crt` +(`application/pkix-cert`) and `/pki/.crl` (`application/pkix-crl`), the root as `root`, from +copies in `/var/lib/linux-manager/pki-publish`, over plain HTTP on `web.port` while `web.enabled` +and on the Manager's port, and while HTTPS is on also on `https.manager_port` and, while +`web.enabled` or an issuing CA has ACME, on `https.web_port`. On the Manager's plain HTTP port, +`/pki/` is answered before the redirect to HTTPS. -| Endpoint | URL | Served by | -|---|---|---| -| `http` | `http://:/pki/` | the status web service; needs `web.enabled` | -| `http-80` | `http:///pki/` | Caddy, on port 80, open on both interfaces; needs `https.enabled` | -| `https` | `https://:/pki/` | Caddy; needs `https.enabled` | -| `https-default` | `https:///pki/` | Caddy, on port 443, open on both interfaces; needs `https.enabled` | +Every certificate names its issuer's certificate (AIA) and CRL (CRL distribution point) at the +plain HTTP URLs, in this order: -The URLs are written into a certificate when it is signed, so a change of `pki.publish` or of the -names applies to the certificates signed afterwards. An empty `pki.publish` leaves the extensions -out. +- `http://:/pki/`, while `web.enabled`; +- `http://:/pki/`. + +The URLs are written into a certificate when it is signed, so a change of the ports or of +`wan.local_fqdn` applies to the certificates signed afterwards. Without `wan.local_fqdn` the +extensions are left out. The CRLs of the issuing CAs are valid for `pki.crl_days`, and the root CRL, when the server signs it, for `pki.root_crl_days`. A CRL is signed again at every revocation and, once half of its @@ -1700,9 +1700,8 @@ reloads it when the file changes. Caddy listens on every address, and the firewall decides who reaches it: `web.port` is open on the interfaces `web.listen` names, the Manager's port on those of its `listen`, and `metrics.port` on those of `metrics.listen`, where `internal` is the external interface without the router. Port -80 is open on the external interface while ACME needs it, the HTTPS ports on the internal and the -external interface, and ports 80 and 443 on both when `pki.publish` has `http-80` and -`https-default`, on which Caddy serves only the CA files (see Certificates). +80 is open on the external interface while ACME needs it, and the HTTPS ports on the internal and +the external interface. Caddy calls the services on `127.0.0.1`: the status web service on port 7091, the Manager on 7090, the metrics service on 9474 and WebDAV on 7446, and passes the client's address in @@ -2240,10 +2239,9 @@ the Overview, Metrics, Logs, Backup and System tabs), Identities (`/user-manager Accounts tabs), Connectivity (`/site-to-site-manager`: the Status, Network and Connections tabs), Remote Access (`/remote-access-manager`: the IKEv2, OpenVPN and WireGuard tabs), Certificates (`/ca-manager`), Web Sites (`/sites-manager`: the Sites and Files tabs), DNS (`/dns-manager`, while the name -server is on) and Docker (`/docker-manager`) with the page menu at the -right end of the header, a button naming the page shown. The button with the signed-in user's -name, left of Sign out, opens the account page, and the terminal icon left of it the Shell -(`/shell`); pressed on its page, each returns to the page it was opened from. +server is on), Docker (`/docker-manager`) and Shell (`/shell`) with the page menu at the right end +of the header, a button naming the page shown. The button with the signed-in user's name, left of +Sign out, opens the account page; pressed on it, it returns to the page it was opened from. - **Help** (the question mark in the header between the theme switcher and the page menu, for every signed-in user): a panel on the right, under @@ -2258,8 +2256,8 @@ name, left of Sign out, opens the account page, and the terminal icon left of it on their own, kept in the browser's localStorage, so each browser has its own. Each tab reads manually, or every 5, 10 or 30 seconds, 1, 5 or 15 minutes; the Overview tab every 10 seconds and the Metrics tab every minute by default. Manual reads when the tab opens and on Refresh. **Open - the shell in a new tab**, off by default, makes the shell button open the shell in a tab of its - own, which stays open while the first tab opens other pages. A change applies at once, also in + the shell in a new tab**, off by default, makes the page menu open the Shell page in a tab of + its own, which stays open while the first tab opens other pages. A change applies at once, also in the browser's other tabs; Defaults sets them back. - **Account** (`/user`): the Account and the Passkeys panel side by side, with One-time passwords @@ -2438,7 +2436,7 @@ name, left of Sign out, opens the account page, and the terminal icon left of it the ports exposed on the external interface and the rules of the `LINUX-MANAGER-DOCKER` chain, from the server's `/status/full` and `/config`. The page menu leaves the page out while `/config` says Docker is not installed, and the page itself then says so. -- **Shell** (`/shell`, the terminal icon in the header): a login shell on the server in xterm.js, the terminal of VS Code, as the +- **Shell** (`/shell`, in the page menu of administrators): a login shell on the server in xterm.js, the terminal of VS Code, as the signed-in user's console account, the user's own LDAP POSIX account or a local account. Opening it asks for the password and the code again, or Open with a passkey takes one of the user's passkeys, unlocked with the device's PIN or biometrics, unless the user used a shell within the @@ -2447,7 +2445,7 @@ name, left of Sign out, opens the account page, and the terminal icon left of it on the server with `linux-manager-config-edit`, and closes it after `web.shell_idle_minutes` without a keystroke; the page then shows the reason and keeps the terminal readable. - **Editor:** `lme FILE...` (`linux-manager-editor`) in the shell opens the files in a Monaco editor on the page, one tab per file, and returns at once. The server names each file in a text message of the shell's WebSocket, and the page reads and saves it through `/api/shell/editor//`, as the console account. Saves have a body limit of 2 MiB plus 64 KiB, for a file of up to 1 MiB escaped in JSON; other calls keep 64 KiB. - - **Editor icon:** while a file is open, an icon left of the shell icon switches the page between the terminal and the editor, and the shell keeps running. A button left of Save shows or hides the minimap, remembered by the browser. Save or Ctrl+S writes the file; a file changed on the server since it was read offers Reload or Overwrite. Closing a tab with unsaved changes asks first, and the icon goes when the last tab closes or the shell ends. + - **Editor icon:** while a file is open, an icon left of the user's name in the header switches the page between the terminal and the editor, and the shell keeps running. A button left of Save shows or hides the minimap, remembered by the browser. Save or Ctrl+S writes the file; a file changed on the server since it was read offers Reload or Overwrite. Closing a tab with unsaved changes asks first, and the icon goes when the last tab closes or the shell ends. - **Loading:** Monaco is bundled with the page, without its language services, and loaded only when the first file opens. - **Backup**: the server's backups, from its `/backup`: - **Settings:** whether scheduled backups run, the schedule (hourly, daily or weekly), the target and whether the metrics database is included. For a local folder it also shows the folder, the archives kept and the cloud copy with rclone; for a Proxmox Backup Server, the repository, whether the token secret is set, the fingerprint, the namespace and the encryption key file. diff --git a/bin/lm-dev-vm.py b/bin/lm-dev-vm.py index 9b0eb2d..4105d3f 100755 --- a/bin/lm-dev-vm.py +++ b/bin/lm-dev-vm.py @@ -10,15 +10,15 @@ password of .lm-dev-config/vm-PROJECT-VM.json, and a TOTP token, the key VM-admi engine made from the file's otp_url, unless --no-otp is given; lm-dev-otp-code.py prints its codes. A password or otp_url the file lacks, or all of them when there is no file, is generated and kept in the file, so a VM made again has the same password and token until they are deleted from the file. -The VM gets a configuration from tests/remote/configs/ (--config, core.json by default), whose @ETH0@ is the +The VM gets a configuration from tests/remote/configs/ (--config, dev.json by default), whose @ETH0@ is the interface of its default route, @CIDR0@ its network and @PSK@ a generated key. The VM gets an AppRole of its own in the project's Vault (lm_dev.enrol_instance), with which it reads the debconf preseed with the admin's password and the configuration with its key, kept there as VM/preseed and VM/config, and its TOTP key, generated or from otp_url; no secret is an argument or on standard input, so create needs a project with a Vault (lm-dev-lxd-project.py vault create). The admin's password is also kept there as VM/admin. -The VM's leased address is pinned on its NIC, and ports 7080 and 7081 of a listen address lead to -the same ports of the VM, and port 2222 to its SSH port. In a test project the listen address is a +The VM's leased address is pinned on its NIC, and ports 7080, 7081, 7443 and 7444 of a listen address +lead to the same ports of the VM, and port 2222 to its SSH port. In a test project the listen address is a network forward's on the project's WAN, --forward-address (LXD_FORWARD_ADDRESS) or else one allocated from its uplink's routes; elsewhere NAT proxy devices listen on the host address --listen (LXD_LISTEN, by default the IPv4 address of the host of @@ -41,8 +41,9 @@ from lm_dev import HANDOVER_DIR, PROJECT, VM, ROOT, TESTS, VAULT_MOUNT, MissingS credentials_path, enrol_instance, enrol_otp, forget_instance, hand_over, host_address, lxc_exec, newest_deb, \ setting, store_secret, vault_state, write_private -# The listen port and the VM port of each forward or proxy: the Manager, the status web service and SSH. -PORTS = ((7080, 7080), (7081, 7081), (2222, 22)) +# The listen port and the VM port of each forward or proxy: the Manager and the status web service over HTTP and +# HTTPS, and SSH. +PORTS = ((7080, 7080), (7081, 7081), (7443, 7443), (7444, 7444), (2222, 22)) def main(): @@ -54,8 +55,8 @@ def main(): parser.add_argument('--vm', default=VM, help=f'the name of the VM (default {VM})') parser.add_argument('--image', default=setting('LXD_IMAGE', 'ubuntu:26.04'), help='the image of the VM (LXD_IMAGE, default ubuntu:26.04)') - parser.add_argument('--config', default='core.json', - help='the configuration from tests/remote/configs/ (default core.json)') + parser.add_argument('--config', default='dev.json', + help='the configuration from tests/remote/configs/ (default dev.json)') parser.add_argument('--listen', default=setting('LXD_LISTEN', None), help="outside a test project, the LXD host address the proxies listen on (LXD_LISTEN, " "default the IPv4 address of the remote URL's host)") @@ -247,7 +248,8 @@ def main(): if not args.no_otp: print(f'administrator TOTP: otp_url in {credentials}; codes: bin/lm-dev-otp-code.py --project {args.project} ' f'--vm {args.vm}') - print(f'manager: http://{args.listen}:7080/ status: http://{args.listen}:7081/ ssh: {args.listen} port 2222') + print(f'manager: https://{args.listen}:7443/ status: https://{args.listen}:7444/ and http://{args.listen}:7081/ ' + f'ssh: {args.listen} port 2222') print(f'shell: lxc exec {args.remote}:{args.vm} --project {args.project} -- su -l') print(f'remove: {sys.argv[0]} remove --remote {args.remote} --project {args.project} --vm {args.vm}') diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager.py b/debian-package/src/usr/lib/linux-manager/linuxmanager.py index 93c354a..9d0f96d 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager.py @@ -87,7 +87,7 @@ SCHEMA = { 'sites': {'enabled': False, 'upload_max_mb': 512, 'webdav': False, 'webdav_port': 7445}, 'dns': {'enabled': False, 'secondary': '', 'listen': 'external', 'ttl': 300}, 'pki': {'root_name': 'Linux Manager Root CA', 'root_days': 7300, 'ca_days': 3650, 'key': 'rsa-4096', - 'crl_days': 7, 'root_crl_days': 180, 'publish': ['http'], 'p2s_name': 'Linux Manager VPN CA', + 'crl_days': 7, 'root_crl_days': 180, 'p2s_name': 'Linux Manager VPN CA', 's2s_name': 'Linux Manager Site-to-Site CA', 'servers_name': 'Linux Manager Servers CA', 'issuing_cas': {}, 'templates': {}, 'extended_key_usages': {}, 'root': 'local', 'simple_ca_url': ''}, @@ -148,7 +148,7 @@ PBS_NAMESPACE = re.compile(r'^[A-Za-z0-9_][A-Za-z0-9._-]*(/[A-Za-z0-9_][A-Za-z0- #: The port of Let's Encrypt's HTTP challenge, which Caddy answers while HTTPS is on. ACME_HTTP_PORT = 80 -#: The default port of HTTPS, where Caddy publishes the CA files when pki.publish has https-default. +#: The default port of HTTPS. HTTPS_DEFAULT_PORT = 443 #: The most files web.log_files lists. @@ -171,8 +171,9 @@ COMPONENTS = { UPLOAD_MAX_MB = 10240 #: Settings that no longer exist, section -> options, left out when the file is read so that a file of an earlier -#: version loads: the name server is wan.local_fqdn and a site chooses the address of its records. -RETIRED = {'dns': ('nameserver', 'addresses')} +#: version loads: the name server is wan.local_fqdn, a site chooses the address of its records, and the CA certificates +#: and CRLs are always published. +RETIRED = {'dns': ('nameserver', 'addresses'), 'pki': ('publish',)} #: The shortest and the longest dns.ttl, in seconds. DNS_TTL_RANGE = (60, 86400) @@ -212,9 +213,6 @@ PKI_KEYS = ('rsa-2048', 'rsa-3072', 'rsa-4096', 'ec-p256', 'ec-p384') #: Where the root CA comes from, pki.root: the server creates it, an offline CA, or a Simple CA service. PKI_ROOTS = ('local', 'offline', 'simple-ca') -#: Where the CA certificates and CRLs are published, pki.publish, as the URLs in the certificates list them. -PKI_PUBLISH = ('http', 'http-80', 'https', 'https-default') - #: The key usages a template may give, as the arguments of cryptography's KeyUsage. KEY_USAGES = ('digital_signature', 'content_commitment', 'key_encipherment', 'data_encipherment', 'key_agreement') @@ -749,18 +747,6 @@ def validate(cfg): raise ConfigError('pki.simple_ca_url must be an https:// URL without a query or a fragment') if _get(cfg, 'pki', 'key') not in PKI_KEYS: raise ConfigError(f'pki.key: {_get(cfg, "pki", "key")!r} is not one of {", ".join(PKI_KEYS)}') - publish = _get_list(cfg, 'pki', 'publish') - for item in publish: - if item not in PKI_PUBLISH: - raise ConfigError(f'pki.publish: {item!r} is not one of {", ".join(PKI_PUBLISH)}') - if len(set(publish)) != len(publish): - raise ConfigError('pki.publish names an endpoint twice') - if publish and not _get(cfg, 'wan', 'local_fqdn'): - raise ConfigError('pki.publish needs wan.local_fqdn, the name in the published URLs') - if 'http' in publish and not _get(cfg, 'web', 'enabled'): - raise ConfigError('pki.publish: http is served by the web service, which needs web.enabled') - if set(publish) - {'http'} and not _get(cfg, 'https', 'enabled'): - raise ConfigError('pki.publish: http-80, https and https-default are served by Caddy, which needs https.enabled') for name, oid in cfg['pki']['extended_key_usages'].items(): prefix = f'pki.extended_key_usages.{name}' if not EKU_NAME.match(name) or name in EXTENDED_KEY_USAGES: @@ -833,13 +819,6 @@ def validate(cfg): if port in taken: raise ConfigError(f'{taken[port]}: {port} is the port of {owner}') taken[port] = owner - if 'https-default' in publish: - if HTTPS_DEFAULT_PORT in taken: - raise ConfigError(f'pki.publish: https-default takes port {HTTPS_DEFAULT_PORT}, the port of ' - f'{taken[HTTPS_DEFAULT_PORT]}') - if _get(cfg, 'openvpn', 'protocol') == 'tcp' and _get(cfg, 'openvpn', 'port') == HTTPS_DEFAULT_PORT: - raise ConfigError(f'pki.publish: https-default takes port {HTTPS_DEFAULT_PORT}, the port of openvpn.port') - taken[HTTPS_DEFAULT_PORT] = 'pki.publish https-default' for section_name, option in (('metrics', 'port'), ('metrics', 'https_port'), ('sites', 'webdav_port')): port = _get(cfg, section_name, option) if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535: @@ -920,7 +899,7 @@ def validate(cfg): weight += 2 if ':' in item else 1 first, _, last = item.partition(':') caddy_ports = (web_port, manager_port(), _get(cfg, 'metrics', 'port'), - *((ACME_HTTP_PORT, *https_ports, *([HTTPS_DEFAULT_PORT] if 'https-default' in publish else [])) + *((ACME_HTTP_PORT, *https_ports) if _get(cfg, 'https', 'enabled') else ())) for port in caddy_ports: if int(first) <= port <= int(last or first): @@ -963,15 +942,14 @@ def issuing_cas(cfg): def pki_base_urls(cfg): - """The base URLs, ending in /, under which the CA certificates and CRLs are published, in the order of pki.publish.""" + """The plain HTTP base URLs, ending in /, under which Caddy publishes the CA certificates and CRLs and the + certificates name them: the status web service's web.port while it is enabled, then the Manager's port; none without + wan.local_fqdn.""" fqdn = _get(cfg, 'wan', 'local_fqdn') - bases = { - 'http': f'http://{fqdn}:{_get(cfg, "web", "port")}/pki/', - 'http-80': f'http://{fqdn}/pki/', - 'https': f'https://{fqdn}:{_get(cfg, "https", "web_port")}/pki/', - 'https-default': f'https://{fqdn}/pki/', - } - return [bases[item] for item in _get_list(cfg, 'pki', 'publish') if item in bases] if fqdn else [] + if not fqdn: + return [] + ports = [*([_get(cfg, 'web', 'port')] if _get(cfg, 'web', 'enabled') else []), manager_port()] + return [f'http://{fqdn}:{port}/pki/' for port in ports] def manager_port(): @@ -1211,7 +1189,6 @@ def build_context(cfg, public_ip=None): 'https_zerossl_api_key': _get(cfg, 'https', 'zerossl_api_key'), 'https_web_port': _get(cfg, 'https', 'web_port'), 'https_manager_port': _get(cfg, 'https', 'manager_port'), - 'pki_publish': _get_list(cfg, 'pki', 'publish'), 'pki_acme': [name for name, authority in issuing_cas(cfg).items() if authority['acme']], 'metrics_enabled': _get(cfg, 'metrics', 'enabled'), 'metrics_port': _get(cfg, 'metrics', 'port'), diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_pki.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_pki.py index adb071b..26276d6 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_pki.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_pki.py @@ -20,8 +20,8 @@ The root comes from one of ROOT_SOURCES, pki.root, fixed once the root exists: issuing CAs, the upstream CA, kept on cn=root; the upstream CA's certificate and CRL are the entry cn=upstream, and it stands between the root and the issuing CAs in every chain. -The certificates carry the URLs of pki.publish for their issuer's certificate (AIA) and CRL (CRL distribution point); -PUBLISH_DIR holds the DER copies served there. distribute writes the files strongSwan, OpenVPN and the system's trust +The certificates carry the URLs of linuxmanager.pki_base_urls for their issuer's certificate (AIA) and CRL (CRL +distribution point); PUBLISH_DIR holds the DER copies Caddy serves there. distribute writes the files strongSwan, OpenVPN and the system's trust store read. Callers hold locked() around every operation that writes, which is the lock of the user module's sessions too. A request diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/__init__.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/__init__.py index 1f47971..280f9a3 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/__init__.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/__init__.py @@ -30,9 +30,6 @@ Pages: /ca the PKI: its settings, the root and issuing CAs, the certificates issued; change the settings, issue and revoke certificates, and take the certificate of an issuing CA and a root CRL signed offline (see ca()) - /pki/.crt, /pki/.crl - the DER certificate and CRL of the root (root) and of each issuing CA, which the - certificates name in their AIA and CRL distribution points; no authentication /shell while web.shell is true, a login shell of the user's console account on a terminal, for a member of admins whose console login is on and who has a TOTP token: POST signs the user in again, with the password and the TOTP code or with a passkey whose proof POST /shell/passkey begins, diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/handler.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/handler.py index fd1b7ef..11ae2c7 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/handler.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/handler.py @@ -8,11 +8,9 @@ from http.server import BaseHTTPRequestHandler import ldap -import linuxmanager import linuxmanager_auth import linuxmanager_net import linuxmanager_oidc -import linuxmanager_pki import linuxmanager_sites from .auth import auth, auth_wait, refusal @@ -25,7 +23,7 @@ from .identities import account, groups, service_accounts, users from .logs import logs from .https import PATHS as HTTPS_PATHS, https from .metrics import metrics_history, metrics_settings -from .pki import PUBLISHED, ca +from .pki import ca from .shell import EDITOR_BODY_LIMIT, shell, shell_editor, shell_passkey, shell_ticket from .sites import SITE_FILES, site_files, sites from .status import cached, details, html_of, postgresql_databases, shown, text_of @@ -182,9 +180,6 @@ class Handler(BaseHTTPRequestHandler): extra += headers elif self.command not in ('GET', 'HEAD'): body, kind, code = b'Method not allowed\n', 'text/plain; charset=utf-8', 405 - elif path.startswith('/pki/') and linuxmanager.PKI_NAME.match(path[5:-4]) and path[-4:] in PUBLISHED and \ - (linuxmanager_pki.PUBLISH_DIR / path[5:]).is_file(): - body, kind, code = (linuxmanager_pki.PUBLISH_DIR / path[5:]).read_bytes(), PUBLISHED[path[-4:]], 200 elif path in ('/status', '/'): document = shown(cached(), section(read_json(CONFIG_FILE), 'web').get('status_content'), self.client()) agent = self.headers.get('User-Agent', '').lower() diff --git a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/pki.py b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/pki.py index f2b1760..d530ffa 100644 --- a/debian-package/src/usr/lib/linux-manager/linuxmanager_web/pki.py +++ b/debian-package/src/usr/lib/linux-manager/linuxmanager_web/pki.py @@ -1,4 +1,4 @@ -"""The PKI: /ca, and the certificates and CRLs /pki/ serves without authentication.""" +"""The PKI: /ca.""" import ldap @@ -7,9 +7,6 @@ import linuxmanager_pki from .common import PKI_STATUS -#: A file /pki/ serves: the certificate or the CRL of a CA, and its content type. -PUBLISHED = {'.crt': 'application/pkix-cert', '.crl': 'application/pkix-crl'} - def ca(method, path, body): """Answer a /ca request with linuxmanager_pki: the HTTP status and the JSON document. diff --git a/debian-package/src/usr/lib/linux-manager/setup b/debian-package/src/usr/lib/linux-manager/setup index 89043eb..d993dee 100755 --- a/debian-package/src/usr/lib/linux-manager/setup +++ b/debian-package/src/usr/lib/linux-manager/setup @@ -293,22 +293,18 @@ def filter_block(ctx): lines += ['', '# METRICS RULES START', *opened(ctx['metrics_listen'], ctx['metrics_port']), '# METRICS RULES END'] - # The ACME CA reaches the HTTP challenge on the external interface while it issues the server's certificate, and - # the CA files published on port 80 are read on both; the HTTPS ports are open on both. + # The ACME CA reaches the HTTP challenge on the external interface while it issues the server's certificate; the + # HTTPS ports are open on both. if linuxmanager.https_ready(ctx) and interfaces: - publish = ctx['pki_publish'] - ports = [port for wanted, port in ((ctx['web_enabled'] or 'https' in publish or ctx['pki_acme'], - ctx['https_web_port']), + ports = [port for wanted, port in ((ctx['web_enabled'] or ctx['pki_acme'], ctx['https_web_port']), (True, ctx['https_manager_port']), (linuxmanager.metrics_ready(ctx), ctx['metrics_https_port']), - (linuxmanager.webdav_ready(ctx), ctx['webdav_port']), - ('http-80' in publish, linuxmanager.ACME_HTTP_PORT), - ('https-default' in publish, linuxmanager.HTTPS_DEFAULT_PORT)) if wanted] + (linuxmanager.webdav_ready(ctx), ctx['webdav_port'])) if wanted] lines += [ '', '# HTTPS RULES START', *([f'-A ufw-before-input -i {ctx["wan_iface"]} -p tcp --dport {linuxmanager.ACME_HTTP_PORT} -j ACCEPT'] - if ctx['wan_iface'] and 'http-80' not in publish and ctx['https_certificate'] == 'acme' else []), + if ctx['wan_iface'] and ctx['https_certificate'] == 'acme' else []), *(f'-A ufw-before-input -i {name} -p tcp --dport {port} -j ACCEPT' for name in interfaces for port in ports), '# HTTPS RULES END', ] @@ -757,8 +753,9 @@ def manage_caddy(cfg, ctx): its service on its loopback port. The certificate comes from the ACME CA of https.acme_provider, the global issuer, with https.certificate acme, and otherwise is the one linuxmanager_pki.https_files gives, written to CADDY_HTTPS_DIR; while that cannot be read, the HTTPS sites are left out, so that no ACME CA is asked for it. It - also serves the CA files of linuxmanager_pki.PUBLISH_DIR at /pki/ on the endpoints of pki.publish that are Caddy's, - and an ACME server at /acme// on https.web_port for each issuing CA with acme and a certificate. + also serves the CA files of linuxmanager_pki.PUBLISH_DIR at /pki/ on web.port, the Manager's port, https.web_port + and https.manager_port, ahead of the redirect to HTTPS, and an ACME server at /acme// on https.web_port for + each issuing CA with acme and a certificate. It serves each site of ctx's sites from its folder, with the TLS of the site: an issuing CA of tls ca issues its certificates, and the certificate and key of tls file are written to CADDY_SITES_DIR/. The certificates and diff --git a/debian-package/src/usr/share/doc/linux-manager/linux-manager.json.example b/debian-package/src/usr/share/doc/linux-manager/linux-manager.json.example index 3686e51..0d218d0 100644 --- a/debian-package/src/usr/share/doc/linux-manager/linux-manager.json.example +++ b/debian-package/src/usr/share/doc/linux-manager/linux-manager.json.example @@ -106,7 +106,6 @@ "key": "rsa-4096", "crl_days": 7, "root_crl_days": 180, - "publish": ["http"], "p2s_name": "Linux Manager VPN CA", "s2s_name": "Linux Manager Site-to-Site CA", "issuing_cas": { diff --git a/debian-package/src/usr/share/linux-manager/templates/Caddyfile.j2 b/debian-package/src/usr/share/linux-manager/templates/Caddyfile.j2 index b686b1d..0254196 100644 --- a/debian-package/src/usr/share/linux-manager/templates/Caddyfile.j2 +++ b/debian-package/src/usr/share/linux-manager/templates/Caddyfile.j2 @@ -33,23 +33,40 @@ } {%- endif %} } +{#- The CA certificates and CRLs of directory at /pki/, as DER with the content types of RFC 5280. #} +{%- macro pki_files(directory) %} + handle_path /pki/* { + @crt path *.crt + @crl path *.crl + header @crt Content-Type application/pkix-cert + header @crl Content-Type application/pkix-crl + root * {{ directory }} + file_server + } +{%- endmacro %} {% if web_enabled %} http://:{{ web_port }} { header -Server - reverse_proxy {{ loopback }}:{{ web_loopback_port }} { - header_down -Server +{{- pki_files(pki_publish_dir) }} + handle { + reverse_proxy {{ loopback }}:{{ web_loopback_port }} { + header_down -Server + } } } {% endif %} http://:{{ manager_port }} { header -Server +{{- pki_files(pki_publish_dir) }} + handle { {%- if redirect %} - redir https://{{ local_fqdn }}:{{ https_manager_port }}{uri} 308 + redir https://{{ local_fqdn }}:{{ https_manager_port }}{uri} 308 {%- else %} - reverse_proxy {{ loopback }}:{{ manager_loopback_port }} { - header_down -Server - } + reverse_proxy {{ loopback }}:{{ manager_loopback_port }} { + header_down -Server + } {%- endif %} + } } {% if metrics_enabled %} http://:{{ metrics_port }} { @@ -59,18 +76,13 @@ http://:{{ metrics_port }} { } } {% endif %} -{%- if https and (web_enabled or 'https' in pki_publish or acme_cas) %} +{%- if https and (web_enabled or acme_cas) %} {{ local_fqdn }}:{{ https_web_port }} { header -Server {%- if https_tls %} tls {{ https_tls.cert }} {{ https_tls.key }} {%- endif %} -{%- if 'https' in pki_publish %} - handle_path /pki/* { - root * {{ pki_publish_dir }} - file_server - } -{%- endif %} +{{- pki_files(pki_publish_dir) }} {%- for ca in acme_cas %} handle /acme/{{ ca }}/* { acme_server { @@ -89,41 +101,17 @@ http://:{{ metrics_port }} { } } {% endif %} -{%- if https and 'http-80' in pki_publish %} -http://{{ local_fqdn }} { - header -Server - handle_path /pki/* { - root * {{ pki_publish_dir }} - file_server - } - handle { - respond 404 - } -} -{% endif %} -{%- if https and 'https-default' in pki_publish %} -{{ local_fqdn }}:443 { - header -Server -{%- if https_tls %} - tls {{ https_tls.cert }} {{ https_tls.key }} -{%- endif %} - handle_path /pki/* { - root * {{ pki_publish_dir }} - file_server - } - handle { - respond 404 - } -} -{% endif %} {%- if https %} {{ local_fqdn }}:{{ https_manager_port }} { header -Server {%- if https_tls %} tls {{ https_tls.cert }} {{ https_tls.key }} {%- endif %} - reverse_proxy {{ loopback }}:{{ manager_loopback_port }} { - header_down -Server +{{- pki_files(pki_publish_dir) }} + handle { + reverse_proxy {{ loopback }}:{{ manager_loopback_port }} { + header_down -Server + } } } {% endif %} diff --git a/docs/certificates.md b/docs/certificates.md index c24d46a..7e75e4d 100644 --- a/docs/certificates.md +++ b/docs/certificates.md @@ -11,7 +11,7 @@ Issue and Settings are on every tab but Server. - **Issue:** a certificate from a CSR, saved with its chain, or with a key the server makes, saved as a PFX file protected by a password; the server keeps no copy of the key. - **Settings:** the names of the P2S and S2S CAs while they do not exist yet, the lifetimes, key - type, CRL validity, publishing endpoints and, with a Simple CA root, the URL of the service. + type, CRL validity and, with a Simple CA root, the URL of the service. - **Warnings:** what needs attention, such as a CRL about to expire. ## Tabs diff --git a/docs/index.md b/docs/index.md index 1b2a27b..d3163ac 100644 --- a/docs/index.md +++ b/docs/index.md @@ -23,16 +23,14 @@ Back returns to the previous topic and the house icon to this one. | Certificates | [Certificates](certificates.md) | | Web Sites | [Sites](sites.md), [Files](site-files.md), [DNS](dns.md) | | Docker | [Docker](docker.md) | -| Header | [Shell](shell.md), [Account](account.md) | +| Shell | [Shell](shell.md) | +| Header | [Account](account.md) | ## Header - **Page menu** (right end): switches between the pages; its button names the page shown. - **Help** (question mark, left of the page menu): opens and closes this panel; the page moves left while it is open. -- **Shell** (terminal icon, administrators): a shell on the server; pressed on the Shell page, it - returns to the page it was opened from. With **Open the shell in a new tab** in the settings, - it opens the shell in a tab of its own. - **Your name**: opens your account; pressed there, it returns to the page it was opened from. - **Sign out**, **Settings** (gear, but not on the account page) and **Theme** (light, dark or the system's). diff --git a/docs/shell.md b/docs/shell.md index c14ea3d..aaf2e8d 100644 --- a/docs/shell.md +++ b/docs/shell.md @@ -9,8 +9,8 @@ a local account root chose. [Account](account.md)). - **Closing:** the server ends the shell after `web.shell_idle_minutes` without a keystroke; the page shows the reason and keeps the terminal readable. Leaving the page ends the shell too; - with **Open the shell in a new tab** in the [settings](index.md#settings), the shell button opens - it in a tab of its own, which other pages leave alone. + with **Open the shell in a new tab** in the [settings](index.md#settings), the page menu opens + the Shell page in a tab of its own, which other pages leave alone. ## Editor @@ -23,8 +23,8 @@ lme /etc/hosts ~/notes.txt - **Tabs:** each file has a tab with its name, and its path as the tooltip. A dot marks unsaved changes, and the cross closes the tab, asking first when there are unsaved changes. -- **Editor icon** (left of the shell icon): shown while a file is open. It switches between the - terminal and the editor; the shell keeps running. +- **Editor icon** (left of your name in the header): shown while a file is open. It switches + between the terminal and the editor; the shell keeps running. - **Minimap button** (left of Save): shows or hides the minimap at the right edge of the editor. This browser remembers the choice. - **Save** (or Ctrl+S): writes the file on the server, as your console account. When the file diff --git a/tests/remote/README.md b/tests/remote/README.md index 9bc7830..1d314b4 100644 --- a/tests/remote/README.md +++ b/tests/remote/README.md @@ -126,7 +126,7 @@ it running. The VM is created in a project, the test project `lm-dev` by default project's default profile, and takes its address from DHCP. It gets the package with the administrator `admin`, whose password and TOTP token, unless `--no-otp` is given, are `password` and `otp_url` of `.lm-dev-config/vm--.json`, and a configuration from `configs/`, -`core.json` by default; `@ETH0@` is the interface of the VM's default route. A password or +`dev.json` by default; `@ETH0@` is the interface of the VM's default route. A password or `otp_url` the file lacks, or both when there is no file, is generated and kept in the file, so a VM made again has the same password and token; delete one from the file to have a new one made. @@ -135,8 +135,8 @@ repository, so later dev builds reach it as updates; in another project it insta else the package built last, in `out/` or `out/dev/`. The leased address is pinned on the VM's NIC, and these ports lead to the VM: -- `7080` to the Manager; -- `7081` to the status web service; +- `7080` and `7443` to the Manager, over HTTP and HTTPS; +- `7081` and `7444` to the status web service, over HTTP and HTTPS; - `2222` to SSH, port `22`. In a test project they lead through a network forward on the project's `wan`, whose listen address @@ -168,7 +168,7 @@ generate it. `remove` deletes the VM, its forward and what the Vault keeps for i | `--project` | `LXD_PROJECT` | `lm-dev` | The project of the VM | | `--vm` | | `router` | The name of the VM; it must not exist for `create` | | `--image` | `LXD_IMAGE` | `ubuntu:26.04` | The image of the VM | -| `--config` | | `core.json` | The configuration from `configs/` | +| `--config` | | `dev.json` | The configuration from `configs/` | | `--listen` | `LXD_LISTEN` | the remote URL's host | Outside a test project, the address the proxies listen on | | `--forward-address` | `LXD_FORWARD_ADDRESS` | allocated | In a test project, the forward's listen address, one of the uplink's routes, so a recreated VM keeps it | | `--no-otp` | | off | With `create`, enrol no TOTP token for `admin` | diff --git a/tests/remote/configs/core.json b/tests/remote/configs/core.json index 435505e..bbc13c3 100644 --- a/tests/remote/configs/core.json +++ b/tests/remote/configs/core.json @@ -1,8 +1,5 @@ { - "general": {"platform": "generic", "mode": "manual"}, - "router": {"enabled": false}, - "vpn": {"enabled": false}, + "general": {"platform": "generic"}, "interfaces": {"external": "@ETH0@"}, - "wan": {"local_fqdn": "lm-core.test"}, - "https": {"enabled": false} + "wan": {"local_fqdn": "lm-core.test"} } diff --git a/tests/remote/configs/dev.json b/tests/remote/configs/dev.json new file mode 100644 index 0000000..54c4d1f --- /dev/null +++ b/tests/remote/configs/dev.json @@ -0,0 +1,5 @@ +{ + "general": {"platform": "generic"}, + "interfaces": {"external": "@ETH0@"}, + "wan": {"local_fqdn": "lm-dev.test"} +} diff --git a/tests/remote/configs/nat-off.json b/tests/remote/configs/nat-off.json index 9394be0..f985de5 100644 --- a/tests/remote/configs/nat-off.json +++ b/tests/remote/configs/nat-off.json @@ -1,11 +1,6 @@ { - "general": {"platform": "generic", "mode": "manual"}, - "router": {"enabled": false}, - "vpn": {"enabled": false}, + "general": {"platform": "generic"}, "interfaces": {"external": "@ETH0@"}, "wan": {"local_fqdn": "lm-nat.test"}, - "local": {"cidrs": ["@CIDR0@"]}, - "wireguard": {"enabled": false, "address": "10.66.0.1/24", "listen_port": 51820}, - "openvpn": {"enabled": false, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"}, - "https": {"enabled": false} + "local": {"cidrs": ["@CIDR0@"]} } diff --git a/tests/remote/configs/nat.json b/tests/remote/configs/nat.json index c548b7f..7c60b8e 100644 --- a/tests/remote/configs/nat.json +++ b/tests/remote/configs/nat.json @@ -1,11 +1,9 @@ { - "general": {"platform": "generic", "mode": "manual"}, - "router": {"enabled": false}, + "general": {"platform": "generic"}, "vpn": {"enabled": true}, "interfaces": {"external": "@ETH0@"}, "wan": {"local_fqdn": "lm-nat.test"}, "local": {"cidrs": ["@CIDR0@"]}, - "wireguard": {"enabled": true, "address": "10.66.0.1/24", "listen_port": 51820}, - "openvpn": {"enabled": true, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"}, - "https": {"enabled": false} + "wireguard": {"enabled": true, "address": "10.66.0.1/24"}, + "openvpn": {"enabled": true, "address_pool": "10.67.0.0/24"} } diff --git a/tests/remote/configs/oidc.json b/tests/remote/configs/oidc.json index db3fd74..2e74624 100644 --- a/tests/remote/configs/oidc.json +++ b/tests/remote/configs/oidc.json @@ -1,9 +1,6 @@ { - "general": {"platform": "generic", "mode": "manual"}, - "router": {"enabled": false}, - "vpn": {"enabled": false}, + "general": {"platform": "generic"}, "interfaces": {"external": "@ETH0@"}, "wan": {"local_fqdn": "lm-oidc.test"}, - "https": {"enabled": true, "certificate": "ca"}, "oidc": {"enabled": true} } diff --git a/tests/remote/configs/pki-offline.json b/tests/remote/configs/pki-offline.json deleted file mode 100644 index e401b1d..0000000 --- a/tests/remote/configs/pki-offline.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "general": {"platform": "generic", "mode": "manual"}, - "router": {"enabled": false}, - "vpn": {"enabled": true}, - "interfaces": {"external": "@ETH0@"}, - "wan": {"local_fqdn": "lm-offline.test"}, - "local": {"cidrs": ["@CIDR0@"]}, - "openvpn": {"enabled": true, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"}, - "pki": {"root": "offline"}, - "https": {"enabled": false} -} diff --git a/tests/remote/configs/pki-simple-ca.json b/tests/remote/configs/pki-simple-ca.json deleted file mode 100644 index e82137f..0000000 --- a/tests/remote/configs/pki-simple-ca.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "general": {"platform": "generic", "mode": "manual"}, - "router": {"enabled": false}, - "vpn": {"enabled": true}, - "interfaces": {"external": "@ETH0@"}, - "wan": {"local_fqdn": "lm-simple-ca.test"}, - "local": {"cidrs": ["@CIDR0@"]}, - "openvpn": {"enabled": true, "address_pool": "10.67.0.0/24", "port": 1194, "protocol": "udp"}, - "pki": {"root": "simple-ca", "simple_ca_url": "https://10.188.96.4:8443"}, - "https": {"enabled": false} -} diff --git a/tests/remote/configs/s2s-a-router-off.json b/tests/remote/configs/s2s-a-router-off.json index a9b87bc..5ebe17c 100644 --- a/tests/remote/configs/s2s-a-router-off.json +++ b/tests/remote/configs/s2s-a-router-off.json @@ -1,14 +1,12 @@ { - "general": {"platform": "generic", "mode": "manual"}, - "router": {"enabled": false}, + "general": {"platform": "generic"}, "vpn": {"enabled": true}, "interfaces": {"external": "@ETH0@"}, "wan": {"local_fqdn": "lm-s2s-a.test"}, "local": {"cidrs": ["172.31.31.0/24"]}, "site_to_site": { "to-b": {"addrs": ["172.31.20.20"], "id": "lm-s2s-b.test", "cidrs": ["172.31.32.0/24"], - "local_cidrs": ["172.31.31.0/24"], "local_id_mode": "fqdn", "auth": "psk", "psk": "@PSK@"} + "local_cidrs": ["172.31.31.0/24"], "psk": "@PSK@"} }, - "wireguard": {"enabled": true, "address": "10.66.0.1/24", "listen_port": 51820}, - "https": {"enabled": false} + "wireguard": {"enabled": true, "address": "10.66.0.1/24"} } diff --git a/tests/remote/configs/s2s-a.json b/tests/remote/configs/s2s-a.json index 2e05fd8..6d019d3 100644 --- a/tests/remote/configs/s2s-a.json +++ b/tests/remote/configs/s2s-a.json @@ -1,5 +1,5 @@ { - "general": {"platform": "generic", "mode": "manual"}, + "general": {"platform": "generic"}, "router": {"enabled": true}, "vpn": {"enabled": true}, "interfaces": {"external": "@ETH0@", "internal": "@ETH1@"}, @@ -7,8 +7,7 @@ "local": {"cidrs": ["172.31.31.0/24"], "int_addr": "172.31.21.10", "int_gateway_ip": "172.31.21.20"}, "site_to_site": { "to-b": {"addrs": ["172.31.20.20"], "id": "lm-s2s-b.test", "cidrs": ["172.31.32.0/24"], - "local_cidrs": ["172.31.31.0/24"], "local_id_mode": "fqdn", "auth": "psk", "psk": "@PSK@"} + "local_cidrs": ["172.31.31.0/24"], "psk": "@PSK@"} }, - "wireguard": {"enabled": true, "address": "10.66.0.1/24", "listen_port": 51820}, - "https": {"enabled": false} + "wireguard": {"enabled": true, "address": "10.66.0.1/24"} } diff --git a/tests/remote/configs/s2s-b.json b/tests/remote/configs/s2s-b.json index eb272ff..7ae1992 100644 --- a/tests/remote/configs/s2s-b.json +++ b/tests/remote/configs/s2s-b.json @@ -1,13 +1,11 @@ { - "general": {"platform": "generic", "mode": "manual"}, + "general": {"platform": "generic"}, "router": {"enabled": true}, - "vpn": {"enabled": false}, "interfaces": {"external": "@ETH0@", "internal": "@ETH1@"}, "wan": {"local_fqdn": "lm-s2s-b.test"}, "local": {"cidrs": ["172.31.32.0/24"], "int_addr": "172.31.22.10", "int_gateway_ip": "172.31.22.20"}, "site_to_site": { "to-a": {"addrs": ["172.31.20.10"], "id": "lm-s2s-a.test", "cidrs": ["172.31.31.0/24"], - "local_cidrs": ["172.31.32.0/24"], "local_id_mode": "fqdn", "auth": "psk", "psk": "@PSK@"} - }, - "https": {"enabled": false} + "local_cidrs": ["172.31.32.0/24"], "psk": "@PSK@"} + } } diff --git a/web/src/AccountPanel.tsx b/web/src/AccountPanel.tsx index 8a6d706..58d920d 100644 --- a/web/src/AccountPanel.tsx +++ b/web/src/AccountPanel.tsx @@ -11,7 +11,8 @@ import { useEffect, useState, type FormEvent } from 'react' import OtpDialog from './OtpDialog.tsx' import PasskeyDialog from './PasskeyDialog.tsx' import ProfileDialog from './ProfileDialog.tsx' -import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx' +import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx' +import { useBoard } from './useBoard.ts' import Toolbar from './Toolbar.tsx' import { ACCOUNT_SHAPE, CODE_PATTERN, USER_SHAPE, request, type Account, type User } from './api.ts' diff --git a/web/src/AcmeSettingsDialog.tsx b/web/src/AcmeSettingsDialog.tsx index d29216e..9c30e58 100644 --- a/web/src/AcmeSettingsDialog.tsx +++ b/web/src/AcmeSettingsDialog.tsx @@ -1,13 +1,7 @@ import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, MenuItem, Stack, Switch, TextField, Typography } from '@mui/material' import { useState, type FormEvent } from 'react' import { ACME_PROVIDERS, type AcmeProvider, type HttpsChange, type HttpsSettings } from './api.ts' - -/** The labels of the ACME providers. */ -export const PROVIDER_LABELS: Record = { - letsencrypt: 'Let\'s Encrypt', - zerossl: 'ZeroSSL', - custom: 'Custom directory URL', -} +import { PROVIDER_LABELS } from './https.ts' /** The problem of a custom ACME directory URL, or ''. */ function urlProblem(value: string) { diff --git a/web/src/App.tsx b/web/src/App.tsx index aea6054..e3bdbf4 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -2,7 +2,6 @@ import AccountCircle from '@mui/icons-material/AccountCircle' import EditNote from '@mui/icons-material/EditNote' import HelpOutline from '@mui/icons-material/HelpOutlineOutlined' import Logout from '@mui/icons-material/Logout' -import Terminal from '@mui/icons-material/Terminal' import { Box, Button, CircularProgress, Container, IconButton, Link, Stack, Tab, Tabs, Tooltip, Typography } from '@mui/material' import { useCallback, useEffect, useState } from 'react' import AccountPanel from './AccountPanel.tsx' @@ -44,7 +43,7 @@ type SitesView = 'sites' | 'files' /** The help topic of each tab of the Web Sites page. */ const SITES_TOPICS: Record = { sites: 'sites.md', files: 'site-files.md' } -/** The prefix of the sessionStorage keys of the pages the account and the shell page were opened from, by their paths. */ +/** The prefix of the sessionStorage key of the page the account page was opened from, by its path. */ const RETURN_KEY = 'linux-manager-ui.return:' /** The pages of an administrator besides Router, which every other path shows. */ @@ -71,11 +70,10 @@ const HELP_KEY = 'linux-manager-ui.help' * WireGuard access; at CA_PATH its certificates; at SITES_PATH its web * sites and the files of a site, opened from the sites too; at DNS_PATH its name server, while it is on; at DOCKER_PATH the state of Docker; at SHELL_PATH a shell on the server; otherwise the state of the server, with the update information of its packages in * the Status panel, its metrics, its logs, its backups or the updates of its system's packages. A page shows one tab at a time, each read only while shown. An - * administrator switches pages with the page menu at the right end of the header; the button with the user's name, - * left of Sign out, opens the user's own account, and an administrator's shell button, left of it, the shell; pressed - * on their page, each returns to the page it was opened from; with the browser setting shellNewTab the shell button opens - * the shell in a new tab instead. While files are open in the shell's editor, the editor - * button left of the shell button switches the Shell page between the terminal and the editor. The help button, between the theme switcher and the page menu, opens or closes the help on + * administrator switches pages with the page menu at the right end of the header, whose Shell entry opens the shell in + * a new tab with the browser setting shellNewTab; the button with the user's name, left of Sign out, opens the user's + * own account, and pressed on it returns to the page it was opened from. While files are open in the shell's editor, the + * editor button left of the user's name switches the Shell page between the terminal and the editor. The help button, between the theme switcher and the page menu, opens or closes the help on * the right (HelpPanel) at the topic of the page and tab shown (HELP_TOPICS), the page moving left; the browser keeps * whether it is open. A call answered 401 ends the session and asks for a sign-in again. */ @@ -219,18 +217,6 @@ export default function App(props: { info: Info }) { )} - {session && admin && ( - - (shellNewTab && page !== SHELL_PATH ? window.open(SHELL_PATH, '_blank') : toggle(SHELL_PATH))} - sx={page === SHELL_PATH ? { bgcolor: 'action.selected' } : undefined} - > - - - - )} {session && ( <> {error && {error}} {kind === 'file' && sources && sources.files.length === 0 && No log files are configured.} - + ) } diff --git a/web/src/MetricsPanel.tsx b/web/src/MetricsPanel.tsx index c12aa74..b4b5b5c 100644 --- a/web/src/MetricsPanel.tsx +++ b/web/src/MetricsPanel.tsx @@ -4,8 +4,9 @@ import { Alert, Box, Button, Stack, ToggleButton, ToggleButtonGroup, Typography import { LineChart } from '@mui/x-charts/LineChart' import { useCallback, useEffect, useState } from 'react' import MetricsSettingsDialog from './MetricsSettingsDialog.tsx' -import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx' -import { bytes } from './ServerPanel.tsx' +import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx' +import { useBoard } from './useBoard.ts' +import { bytes } from './format.ts' import { METRICS_RANGES, METRICS_SETTINGS_SHAPE, METRICS_SHAPE, request, type Aggregate, type MetricsHistory, type MetricsRange, type MetricsSettings, @@ -74,6 +75,8 @@ export default function MetricsPanel() { const [error, setError] = useState(null) const [reading, setReading] = useState(true) const [at, setAt] = useState(null) + // The end of the axis until the first read answers. + const [opened] = useState(() => new Date()) const [hidden, setHidden] = useState>(readHidden) const [settings, setSettings] = useState<(MetricsSettings & { otlp_password_set: boolean }) | null>(null) const [opening, setOpening] = useState(false) @@ -99,24 +102,31 @@ export default function MetricsPanel() { }) } - const refresh = useCallback(async () => { - setReading(true) - try { - setHistory(await request('GET', `/metrics/history?range=${range}`, METRICS_SHAPE)) - setError(null) - } catch (caught) { - setError(`The server did not give its metrics: ${(caught as Error).message}`) - } - setAt(new Date()) - setReading(false) + /** Reads the metrics of the view; the state changes only once the server answers. */ + const read = useCallback(async () => { + await request('GET', `/metrics/history?range=${range}`, METRICS_SHAPE) + .then((found) => { + setHistory(found) + setError(null) + }, (caught) => setError(`The server did not give its metrics: ${(caught as Error).message}`)) + .finally(() => { + setAt(new Date()) + setReading(false) + }) }, [range]) + /** Reads the metrics again, reading until the server answers. */ + const refresh = useCallback(() => { + setReading(true) + return read() + }, [read]) + // A read at once and on every change of the view, then every metricsRefresh seconds of the browser's settings, unless // it is manual (0). const { metricsRefresh } = useBrowserSettings() useEffect(() => { - void refresh() - }, [refresh]) + void read() + }, [read]) useEffect(() => { if (metricsRefresh === 0) { return @@ -133,7 +143,7 @@ export default function MetricsPanel() { const tunnels = [...new Set(points.flatMap((point) => Object.keys(point.site_to_site)))].sort() const format = new Intl.DateTimeFormat(undefined, RANGES[range].format) // The axis spans the whole view, whatever part of it has data. - const end = at ?? new Date() + const end = at ?? opened const start = RANGES[range].start(end) const percent = (value: number) => `${value.toFixed(1)} %` @@ -226,7 +236,12 @@ export default function MetricsPanel() { return ( - next && setRange(next)}> + { + if (next) { + setReading(true) + setRange(next) + } + }}> {METRICS_RANGES.map((name) => {RANGES[name].label})} next && setConsolidation(next)}> diff --git a/web/src/NetworkPanel.tsx b/web/src/NetworkPanel.tsx index 6f152f2..c350007 100644 --- a/web/src/NetworkPanel.tsx +++ b/web/src/NetworkPanel.tsx @@ -1,7 +1,9 @@ import Refresh from '@mui/icons-material/Refresh' import { Alert, Box, Button } from '@mui/material' -import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx' -import { Grid, Pairs, text } from './ServerPanel.tsx' +import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx' +import { useBoard } from './useBoard.ts' +import { Grid, Pairs } from './ServerPanel.tsx' +import { text } from './format.ts' import Toolbar from './Toolbar.tsx' import { DETAILS_SHAPE, request, type RouterDetails } from './api.ts' import { useRead } from './useRead.ts' diff --git a/web/src/PageMenu.tsx b/web/src/PageMenu.tsx index 35ff99e..061c36c 100644 --- a/web/src/PageMenu.tsx +++ b/web/src/PageMenu.tsx @@ -6,6 +6,7 @@ import People from '@mui/icons-material/People' import Public from '@mui/icons-material/Public' import ViewInAr from '@mui/icons-material/ViewInAr' import Router from '@mui/icons-material/Router' +import Terminal from '@mui/icons-material/Terminal' import VerifiedUser from '@mui/icons-material/VerifiedUser' import VpnKey from '@mui/icons-material/VpnKey' import { Button, ListItemIcon, ListItemText, Menu, MenuItem } from '@mui/material' @@ -35,7 +36,7 @@ export const SITES_PATH = '/sites-manager' /** The path of the DNS page: the name server's settings, domains and records. */ export const DNS_PATH = '/dns-manager' -/** The path of the shell page: a login shell on the server, opened with the shell button of the header, not the menu. */ +/** The path of the Shell page: a login shell on the server. */ export const SHELL_PATH = '/shell' /** The pages of an administrator in the menu: path, label and icon. */ @@ -48,13 +49,15 @@ const PAGES: { path: string; label: string; icon: ReactNode }[] = [ { path: SITES_PATH, label: 'Web Sites', icon: }, { path: DNS_PATH, label: 'DNS', icon: }, { path: DOCKER_PATH, label: 'Docker', icon: }, + { path: SHELL_PATH, label: 'Shell', icon: }, ] /** - * A button naming the page shown, or Pages on the account and the shell page, whose menu opens the pages of an - * administrator but those of hidden, the pages of a component switched off or of software the server does not have. + * A button naming the page shown, or Pages on the account page, whose menu opens the pages of an administrator but + * those of hidden, the pages of a component switched off or of software the server does not have; the pages of newTab + * open in a new tab. */ -export default function PageMenu(props: { path: string; hidden: string[] }) { +export default function PageMenu(props: { path: string; hidden: string[]; newTab: string[] }) { const [anchor, setAnchor] = useState(null) const current = PAGES.find((page) => page.path === props.path) ?? { path: props.path, label: 'Pages', icon: } return ( @@ -72,7 +75,13 @@ export default function PageMenu(props: { path: string; hidden: string[] }) { setAnchor(null)}> {PAGES.filter((page) => !props.hidden.includes(page.path)).map((page) => ( - + {page.icon} {page.label} diff --git a/web/src/PanelBoard.tsx b/web/src/PanelBoard.tsx index be9ede5..201e3b8 100644 --- a/web/src/PanelBoard.tsx +++ b/web/src/PanelBoard.tsx @@ -13,7 +13,8 @@ import { import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from '@dnd-kit/core' import { SortableContext, arrayMove, rectSortingStrategy, sortableKeyboardCoordinates, useSortable } from '@dnd-kit/sortable' import { CSS } from '@dnd-kit/utilities' -import { useState, type ReactNode } from 'react' +import type { ReactNode } from 'react' +import type { BoardState, Layout } from './useBoard.ts' /** Colours of the panel titles: brown in the light scheme, gold in the dark one. */ const TITLE_LIGHT = '#8b4513' @@ -25,44 +26,6 @@ const TITLE_DARK = '#d4af37' */ export type BoardPanel = { id: string; title: string; actions?: ReactNode; content: ReactNode; wide?: boolean; fixed?: boolean } -/** The layout of a board: the order of the panel ids, the width chosen for a panel, and the hidden and the folded panels. */ -export type Layout = { order: string[]; widths: Record; hidden: string[]; folded: string[] } - -const EMPTY: Layout = { order: [], widths: {}, hidden: [], folded: [] } - -/** The layout kept in localStorage under key, or an empty one when there is none or it cannot be read. */ -function readLayout(key: string): Layout { - try { - const value: unknown = JSON.parse(window.localStorage.getItem(key) ?? 'null') - if (value !== null && typeof value === 'object') { - const stored = value as Partial - const strings = (items: unknown) => (Array.isArray(items) ? items.filter((item): item is string => typeof item === 'string') : []) - return { - order: strings(stored.order), - widths: stored.widths !== null && typeof stored.widths === 'object' ? stored.widths : {}, - hidden: strings(stored.hidden), - folded: strings(stored.folded), - } - } - } catch { - // A layout that cannot be read is replaced by the default. - } - return EMPTY -} - -/** The layout of a board kept in the browser's localStorage under key, and a function that changes and keeps it. */ -export function useLayout(key: string): [Layout, (change: (current: Layout) => Layout) => void] { - const [layout, setLayout] = useState(() => readLayout(key)) - function update(change: (current: Layout) => Layout) { - setLayout((current) => { - const next = change(current) - window.localStorage.setItem(key, JSON.stringify(next)) - return next - }) - } - return [layout, update] -} - /** The panels in the order of the layout; a panel the layout does not know yet comes after the known ones, in the given order. */ function ordered(panels: BoardPanel[], layout: Layout) { const rank = (panel: BoardPanel) => { @@ -230,16 +193,6 @@ export function PanelsDialog(props: { open: boolean; panels: BoardPanel[]; layou ) } -/** The state of a page's board: its layout kept in the browser under key, whether it is edited, and the Panels dialog. */ -export type BoardState = ReturnType - -export function useBoard(key: string) { - const [layout, setLayout] = useLayout(key) - const [editing, setEditing] = useState(false) - const [choosing, setChoosing] = useState(false) - return { layout, setLayout, editing, setEditing, choosing, setChoosing } -} - /** The buttons of a board: Edit layout, Done while editing, and Panels, which opens the Panels dialog. */ export function BoardButtons(props: { board: BoardState }) { const { editing, setEditing, setChoosing } = props.board diff --git a/web/src/PkiSettingsDialog.tsx b/web/src/PkiSettingsDialog.tsx index 32e1da2..023f5a3 100644 --- a/web/src/PkiSettingsDialog.tsx +++ b/web/src/PkiSettingsDialog.tsx @@ -1,72 +1,15 @@ import { - Alert, Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, MenuItem, Stack, TextField, - Typography, + Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography, } from '@mui/material' import { useState, type FormEvent } from 'react' -import { PKI_KEYS, PKI_PUBLISH, type Pki, type PkiAuthority, type PkiRootSource, type PkiSettings, type PkiTemplate } from './api.ts' - -/** The labels of the publishing endpoints. */ -export const PUBLISH_LABELS: Record = { - http: 'HTTP on the status port, served by the web service', - 'http-80': 'HTTP on port 80, served by Caddy', - https: 'HTTPS on the HTTPS status port, served by Caddy', - 'https-default': 'HTTPS on port 443, served by Caddy', -} - -/** The labels of the sources of the root CA. */ -export const ROOT_SOURCE_LABELS: Record = { - local: 'Created by the server', - offline: 'Offline', - 'simple-ca': 'Simple CA', -} - -/** The name of an issuing CA or a template, as the server accepts it. */ -export const NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}$/ - -/** The names the issuing CAs of pki.issuing_cas cannot have. */ -export const RESERVED = ['root', 'upstream', 'p2s', 's2s', 'servers'] - -/** The longest common name of a CA, in characters. */ -const CA_NAME_MAX = 64 - -/** The longest lifetime the server accepts, in days. */ -const DAYS_MAX = 36500 - -/** A new template's options. */ -export const NEW_TEMPLATE: PkiTemplate = { - key: 'rsa-3072', days: 365, key_usage: ['digital_signature'], extended_key_usage: [], subject: 'name', sans: [], policies: [], -} - -/** Whether an issuing CA has its certificate or its CSR, which fix its common name. */ -export function made(authority: PkiAuthority) { - return authority.state === 'active' || authority.state === 'pending' -} - -/** A common name's problem, or ''. */ -export function nameProblem(value: string) { - return value.trim() === '' || value.trim().length > CA_NAME_MAX ? `1 to ${CA_NAME_MAX} characters.` : '' -} - -/** The problem of the URL of a Simple CA service, or ''. */ -export function urlProblem(value: string) { - try { - const url = new URL(value.trim()) - return url.protocol === 'https:' && url.hostname !== '' && url.search === '' && url.hash === '' ? '' : 'An https:// URL.' - } catch { - return 'An https:// URL.' - } -} - -/** A lifetime's problem, or ''. */ -export function daysProblem(value: number) { - return !Number.isInteger(value) || value < 1 || value > DAYS_MAX ? `1 to ${DAYS_MAX} days.` : '' -} +import { PKI_KEYS, type Pki, type PkiSettings } from './api.ts' +import { ROOT_SOURCE_LABELS, daysProblem, made, nameProblem, urlProblem } from './pki.ts' /** * A dialog that edits the server's pki section but the general-purpose issuing CAs, the templates and the custom * extended key usages, which IssuingCaDialog, TemplateDialog and EkuDialog edit: the names of the P2S and site-to-site - * CAs, the lifetimes and key type of the CAs, the validity of the CRLs, where certificates and CRLs are published and, - * with a Simple CA root, the URL of the service. The source of the root is shown and not edited, as it is fixed once + * CAs, the lifetimes and key type of the CAs, the validity of the CRLs and, with a Simple CA root, the URL of the + * service. The source of the root is shown and not edited, as it is fixed once * the root exists. The root and the Servers CA are made by the first setup, so their names are not shown; the P2S and * site-to-site CAs are made when the VPN and the router are switched on, and their names are fixed from then on. The * server applies the lifetimes and key type when it creates a CA. onSave sends the settings; the dialog closes when it @@ -188,24 +131,6 @@ export default function PkiSettingsDialog(props: { onChange={(event) => change({ root_crl_days: number(event.target.value) })} /> - Published certificates and CRLs - - {PKI_PUBLISH.map((item) => ( - change({ - publish: PKI_PUBLISH.filter((name) => (name === item ? event.target.checked : settings.publish.includes(name))), - })} - /> - } - label={PUBLISH_LABELS[item]} - /> - ))} - diff --git a/web/src/RemoteAccessPanel.tsx b/web/src/RemoteAccessPanel.tsx index 37d1926..70743da 100644 --- a/web/src/RemoteAccessPanel.tsx +++ b/web/src/RemoteAccessPanel.tsx @@ -3,12 +3,15 @@ import Edit from '@mui/icons-material/Edit' import Refresh from '@mui/icons-material/Refresh' import { Alert, Box, Button, Chip, Stack } from '@mui/material' import { useCallback, useEffect, useState } from 'react' -import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx' +import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx' +import { useBoard } from './useBoard.ts' import RemoteAccessDialog from './RemoteAccessDialog.tsx' import Toolbar from './Toolbar.tsx' import WireGuardConfigDialog from './WireGuardConfigDialog.tsx' import WireGuardPeers from './WireGuardPeers.tsx' -import { Copyable, Grid, IPSEC_HEADS, Pairs, bytes, ipsecRows, text } from './ServerPanel.tsx' +import { Copyable, Grid, Pairs } from './ServerPanel.tsx' +import { bytes, text } from './format.ts' +import { IPSEC_HEADS, ipsecRows } from './ipsec.ts' import { DETAILS_SHAPE, REMOTE_ACCESS_LABELS, REMOTE_ACCESS_SECTION_SHAPES, REMOTE_ACCESS_SHAPE, STATUS_SHAPE, USERS_SHAPE, request, type RemoteAccess, type RemoteAccessSystem, type RouterDetails, type RouterStatus, type Users, @@ -41,7 +44,7 @@ export default function RemoteAccessPanel(props: { system: RemoteAccessSystem }) const [access, setAccess] = useState(null) const [status, setStatus] = useState(null) const [error, setError] = useState(null) - const [busy, setBusy] = useState(false) + const [busy, setBusy] = useState(true) const [editing, setEditing] = useState(false) const [showConfig, setShowConfig] = useState(false) const board = useBoard(LAYOUT_KEYS[props.system]) @@ -52,30 +55,33 @@ export default function RemoteAccessPanel(props: { system: RemoteAccessSystem }) // IKEv2's: the server's details with its IPsec SAs and connections, those of IKEv2 access being all but site to site. const ikev2 = props.system === 'p2s' - const refresh = useCallback(async () => { - setBusy(true) - try { - const [nextAccess, nextStatus, nextUsers, nextDetails] = await Promise.all([ - request('GET', '/remote-access', REMOTE_ACCESS_SHAPE), - request('GET', '/status/full', STATUS_SHAPE), - wireguard ? request('GET', '/users', USERS_SHAPE) : null, - wireguard || ikev2 ? request('GET', '/config', DETAILS_SHAPE) : null, - ]) - setAccess(nextAccess) - setStatus(nextStatus) - setUsers(nextUsers) - setDetails(nextDetails) - setError(null) - } catch (caught) { - setError((caught as Error).message) - } finally { - setBusy(false) - } + /** Reads the access of the system with what it shows; the state changes only once the server answers. */ + const read = useCallback(async () => { + await Promise.all([ + request('GET', '/remote-access', REMOTE_ACCESS_SHAPE), + request('GET', '/status/full', STATUS_SHAPE), + wireguard ? request('GET', '/users', USERS_SHAPE) : null, + wireguard || ikev2 ? request('GET', '/config', DETAILS_SHAPE) : null, + ]) + .then(([nextAccess, nextStatus, nextUsers, nextDetails]) => { + setAccess(nextAccess) + setStatus(nextStatus) + setUsers(nextUsers) + setDetails(nextDetails) + setError(null) + }, (caught) => setError((caught as Error).message)) + .finally(() => setBusy(false)) }, [wireguard, ikev2]) + /** Reads the access again, busy until the server answers. */ + const refresh = useCallback(() => { + setBusy(true) + return read() + }, [read]) + useEffect(() => { - void refresh() - }, [refresh]) + void read() + }, [read]) async function save(settings: Record) { await request('PUT', `/remote-access/${props.system}`, REMOTE_ACCESS_SECTION_SHAPES[props.system], settings) diff --git a/web/src/SearchField.tsx b/web/src/SearchField.tsx index 4f03fbb..d0efee8 100644 --- a/web/src/SearchField.tsx +++ b/web/src/SearchField.tsx @@ -14,9 +14,3 @@ export default function SearchField(props: { value: string; onChange: (value: st /> ) } - -/** Whether any of the texts contains the search, ignoring case; an empty search matches everything. */ -export function matches(search: string, texts: (string | null | undefined)[]) { - const wanted = search.trim().toLowerCase() - return wanted === '' || texts.some((text) => text?.toLowerCase().includes(wanted)) -} diff --git a/web/src/ServerCertificatePanel.tsx b/web/src/ServerCertificatePanel.tsx index 64348b7..4f274ca 100644 --- a/web/src/ServerCertificatePanel.tsx +++ b/web/src/ServerCertificatePanel.tsx @@ -1,12 +1,15 @@ import Settings from '@mui/icons-material/Settings' import { Alert, Box, Button, Chip, IconButton, Stack, Tooltip, Typography } from '@mui/material' import { useCallback, useEffect, useState, type ReactNode } from 'react' -import AcmeSettingsDialog, { PROVIDER_LABELS } from './AcmeSettingsDialog.tsx' -import { when } from './BackupSummary.tsx' -import HttpsSettingsDialog, { CERTIFICATE_LABELS } from './HttpsSettingsDialog.tsx' +import AcmeSettingsDialog from './AcmeSettingsDialog.tsx' +import { PROVIDER_LABELS } from './https.ts' +import { when } from './format.ts' +import HttpsSettingsDialog from './HttpsSettingsDialog.tsx' +import { CERTIFICATE_LABELS } from './https.ts' import ImportDialog from './ImportDialog.tsx' import PfxDialog from './PfxDialog.tsx' -import { Pairs, Section, text } from './ServerPanel.tsx' +import { Pairs, Section } from './ServerPanel.tsx' +import { text } from './format.ts' import { saveFile } from './saveFile.ts' import { DETAILS_SHAPE, HTTPS_CSR_SHAPE, HTTPS_IMPORTED_SHAPE, HTTPS_SETTINGS_SHAPE, request, type HttpsCertificate, type HttpsChange, @@ -31,26 +34,29 @@ export default function ServerCertificatePanel() { const [settings, setSettings] = useState<{ dialog: 'https' | 'acme'; settings: HttpsSettings } | null>(null) const [importing, setImporting] = useState<'certificate' | 'pfx' | null>(null) - const refresh = useCallback(async () => { - setReading(true) - try { - const [nextDetails, nextHttps] = await Promise.all([ - request('GET', '/config', DETAILS_SHAPE), - request<{ certificate?: HttpsCertificate }>('GET', '/https/settings', HTTPS_SETTINGS_SHAPE), - ]) - setDetails(nextDetails) - setCertificate(nextHttps.certificate ?? null) - setError(null) - } catch (caught) { - setError(`The server did not give its HTTPS settings: ${(caught as Error).message}`) - } finally { - setReading(false) - } + /** Reads the server's details and HTTPS certificate; the state changes only once the server answers. */ + const read = useCallback(async () => { + await Promise.all([ + request('GET', '/config', DETAILS_SHAPE), + request<{ certificate?: HttpsCertificate }>('GET', '/https/settings', HTTPS_SETTINGS_SHAPE), + ]) + .then(([nextDetails, nextHttps]) => { + setDetails(nextDetails) + setCertificate(nextHttps.certificate ?? null) + setError(null) + }, (caught) => setError(`The server did not give its HTTPS settings: ${(caught as Error).message}`)) + .finally(() => setReading(false)) }, []) + /** Reads the details and the certificate again, reading until the server answers. */ + const refresh = useCallback(() => { + setReading(true) + return read() + }, [read]) + useEffect(() => { - void refresh() - }, [refresh]) + void read() + }, [read]) /** Reads the server's https section from /https/settings and opens HttpsSettingsDialog or AcmeSettingsDialog with it. */ async function open(dialog: 'https' | 'acme') { diff --git a/web/src/ServerPanel.tsx b/web/src/ServerPanel.tsx index 3095f87..8fe7439 100644 --- a/web/src/ServerPanel.tsx +++ b/web/src/ServerPanel.tsx @@ -3,14 +3,17 @@ import PlayArrow from '@mui/icons-material/PlayArrow' import Refresh from '@mui/icons-material/Refresh' import { Alert, Box, Button, Chip, IconButton, Link, Paper, Stack, Table, TableBody, TableCell, TableHead, TableRow, Tooltip, Typography } from '@mui/material' import { Fragment, useCallback, useEffect, useState, type ReactNode } from 'react' -import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx' +import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx' +import { useBoard } from './useBoard.ts' import UpdatesNotice from './UpdatesNotice.tsx' -import { BackupChip, backupRows } from './BackupSummary.tsx' +import { BackupChip } from './BackupSummary.tsx' +import { backupRows } from './backup.ts' import { ApiError, BACKUP_SHAPE, DETAILS_SHAPE, INFO_SHAPE, POSTGRESQL_SHAPE, STARTED_SHAPE, STATUS_SHAPE, request, type Backup, type Info, type PostgresqlDatabases, type RouterDetails, type RouterStatus, } from './api.ts' +import { bytes, text } from './format.ts' import { useBrowserSettings } from './settings.ts' /** The localStorage key of the tab's layout. */ @@ -44,10 +47,10 @@ export default function ServerPanel() { const board = useBoard(LAYOUT_KEY) const [busy, setBusy] = useState(false) - const refresh = useCallback(async () => { - setReading(true) + /** Reads the server's state; the state changes only once the server answers. */ + const read = useCallback(async () => { const found: { status?: string; details?: string; databases?: string; backup?: string } = {} - const [nextStatus, nextDetails, nextDatabases, nextBackup, nextInfo] = await Promise.all([ + await Promise.all([ request('GET', '/status/full', STATUS_SHAPE).catch((error: Error) => { found.status = `The server did not give its status: ${error.message}` return null @@ -67,24 +70,31 @@ export default function ServerPanel() { return null }), request('GET', '/info', INFO_SHAPE).catch(() => null), - ]) - setManager(nextInfo?.manager ?? null) - setStatus(nextStatus) - setDetails(nextDetails) - setDatabases(nextDatabases) - setBackup(nextBackup) - setProblems(found) - setReading(false) + ]).then(([nextStatus, nextDetails, nextDatabases, nextBackup, nextInfo]) => { + setManager(nextInfo?.manager ?? null) + setStatus(nextStatus) + setDetails(nextDetails) + setDatabases(nextDatabases) + setBackup(nextBackup) + setProblems(found) + setReading(false) + }) }, []) + /** Reads the server's state again, reading until the server answers. */ + const refresh = useCallback(() => { + setReading(true) + return read() + }, [read]) + // A read at once and when a check for updates, an upgrade or a reboot ends, then every routerRefresh seconds of the // browser's settings, unless it is manual (0); nothing is read while one of them runs (busy). const { routerRefresh } = useBrowserSettings() useEffect(() => { if (!busy) { - void refresh() + void read() } - }, [refresh, busy]) + }, [read, busy]) useEffect(() => { if (routerRefresh === 0 || busy) { return @@ -347,14 +357,6 @@ export default function ServerPanel() { ) } -/** A value as text: lists joined with commas, an empty value as a dash. */ -export function text(value: unknown): string { - if (Array.isArray(value)) { - return value.length === 0 ? '-' : value.join(', ') - } - return value === undefined || value === null || value === '' ? '-' : String(value) -} - /** The names shown for the server's systemd units; a unit not listed is shown by its unit name. */ const UNIT_LABELS: Record = { 'linux-manager-setup': 'Linux Manager Setup', @@ -364,7 +366,6 @@ const UNIT_LABELS: Record = { slapd: 'OpenLDAP', } - /** Colours of the panel titles: brown in the light scheme, gold in the dark one. */ const TITLE_LIGHT = '#8b4513' const TITLE_DARK = '#d4af37' @@ -474,7 +475,6 @@ function Addressed(props: { text: string }) { }) } - /** Whether a configuration section is in use: not switched off, and with at least one value set. */ /** The headings of the sections of the configuration; a section not listed is headed by its name. */ const SECTION_LABELS: Record = { @@ -507,86 +507,3 @@ function Links(props: { urls: string[] }) { function sectionConfigured(values: Record) { return values.enabled !== false && Object.values(values).some((value) => text(value) !== '-') } - -/** The column titles of the IPsec tables of ipsecRows. */ -export const IPSEC_HEADS = { - sas: ['Connection', 'State', 'Local', 'Remote', 'Algorithms', 'Up'], - childSas: ['Child SA', 'State', 'Traffic selectors', 'In', 'Out', 'Up'], - connections: ['Connection', 'Version', 'Local address', 'Local identity', 'Remote address', 'Remote identity', 'Authentication'], - children: ['Child', 'Mode', 'Local traffic selectors', 'Remote traffic selectors'], -} - -/** - * The rows of the IPsec tables of the server's /config for the connections whose names keep accepts: the IKE SAs, their - * child SAs, the connections and their children; undefined where the server could not list them. - */ -export function ipsecRows(details: RouterDetails | null, keep: (name: string) => boolean) { - const sas = details?.ipsec.sas?.filter((sa) => keep(sa.name)) - const connections = details?.ipsec.connections?.filter((connection) => keep(connection.name)) - return { - sas: sas?.map((sa) => [ - sa.name, - sa.state, - `${sa['local-id']} @ ${sa['local-host']}`, - `${sa['remote-id']} @ ${sa['remote-host']}`, - [`${text(sa['encr-alg'])}-${text(sa['encr-keysize'])}`, sa['integ-alg'], sa['dh-group']].filter(Boolean).join(', '), - sa.established === undefined ? '-' : duration(Number(sa.established)), - ]), - childSas: sas?.flatMap((sa) => - Object.values(sa['child-sas'] ?? {}).map((child) => [ - `${sa.name}/${child.name}`, - `${child.state}, ${child.mode}`, - `${child['local-ts'].join(', ')} <-> ${child['remote-ts'].join(', ')}`, - `${bytes(Number(child['bytes-in']))}, ${child['packets-in']} packets`, - `${bytes(Number(child['bytes-out']))}, ${child['packets-out']} packets`, - child['install-time'] === undefined ? '-' : duration(Number(child['install-time'])), - ]), - ), - connections: connections?.map((connection) => { - const local = authOf(connection, 'local') - const remote = authOf(connection, 'remote') - return [ - connection.name, - connection.version, - text(connection.local_addrs), - text(local.id), - text(connection.remote_addrs), - text(remote.id), - local.class === remote.class ? text(local.class) : `${text(local.class)} / ${text(remote.class)}`, - ] - }), - children: connections?.flatMap((connection) => - Object.entries(connection.children ?? {}).map(([name, child]) => [ - `${connection.name}/${name}`, - child.mode, - child['local-ts'].join(', '), - child['remote-ts'].join(', '), - ]), - ), - } -} - -/** The authentication round of one side of a connection: swanctl names them local-1, remote-1 and so on. */ -function authOf(connection: Record, side: 'local' | 'remote'): { class?: string; id?: string } { - const round = Object.entries(connection).find(([key, value]) => key.startsWith(`${side}-`) && typeof value === 'object' && value !== null) - return (round?.[1] ?? {}) as { class?: string; id?: string } -} - -/** Seconds as "1h 2m 3s". */ -export function duration(seconds: number) { - const h = Math.floor(seconds / 3600) - const m = Math.floor((seconds % 3600) / 60) - return [h && `${h}h`, (h || m) && `${m}m`, `${seconds % 60}s`].filter(Boolean).join(' ') -} - -/** Bytes in B, KiB, MiB or GiB. */ -export function bytes(count: number) { - const units = ['B', 'KiB', 'MiB', 'GiB'] - let value = count - let unit = 0 - while (value >= 1024 && unit < units.length - 1) { - value /= 1024 - unit += 1 - } - return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}` -} diff --git a/web/src/ServiceAccountsPanel.tsx b/web/src/ServiceAccountsPanel.tsx index 66c2cf9..28ee177 100644 --- a/web/src/ServiceAccountsPanel.tsx +++ b/web/src/ServiceAccountsPanel.tsx @@ -10,7 +10,8 @@ import { Alert, Box, Button, IconButton, Table, TableBody, TableCell, TableHead, import { useCallback, useEffect, useState } from 'react' import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx' import { Section } from './ServerPanel.tsx' -import SearchField, { matches } from './SearchField.tsx' +import SearchField from './SearchField.tsx' +import { matches } from './search.ts' import ServiceAccountDialog from './ServiceAccountDialog.tsx' import Toolbar from './Toolbar.tsx' import UserDialog from './UserDialog.tsx' @@ -57,40 +58,45 @@ export default function ServiceAccountsPanel() { const [users, setUsers] = useState([]) const [error, setError] = useState(null) const [unavailable, setUnavailable] = useState(false) - const [busy, setBusy] = useState(false) + const [busy, setBusy] = useState(true) const [adding, setAdding] = useState(false) const [editing, setEditing] = useState(null) const [password, setPassword] = useState(null) const [confirm, setConfirm] = useState(null) const [search, setSearch] = useState('') - const refresh = useCallback(async () => { - setBusy(true) - try { - const [found, groupList, userList] = await Promise.all([ - request('GET', '/service-accounts', SERVICE_ACCOUNTS_SHAPE), - request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE), - request<{ users: User[] }>('GET', '/users', USERS_SHAPE), - ]) - setAccounts(found.service_accounts) - setOidc(found.oidc) - setGroups(groupList.groups.map((group) => group.name)) - setUsers(userList.users.map((user) => user.name)) - setError(null) - setUnavailable(false) - } catch (caught) { - const failure = caught as ApiError - setAccounts(null) - setUnavailable(failure.status === 404) - setError(failure.message) - } finally { - setBusy(false) - } + /** Reads the service accounts with the groups and users; the state changes only once the server answers. */ + const read = useCallback(async () => { + await Promise.all([ + request('GET', '/service-accounts', SERVICE_ACCOUNTS_SHAPE), + request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE), + request<{ users: User[] }>('GET', '/users', USERS_SHAPE), + ]) + .then(([found, groupList, userList]) => { + setAccounts(found.service_accounts) + setOidc(found.oidc) + setGroups(groupList.groups.map((group) => group.name)) + setUsers(userList.users.map((user) => user.name)) + setError(null) + setUnavailable(false) + }, (caught) => { + const failure = caught as ApiError + setAccounts(null) + setUnavailable(failure.status === 404) + setError(failure.message) + }) + .finally(() => setBusy(false)) }, []) + /** Reads the service accounts again, busy until the server answers. */ + const refresh = useCallback(() => { + setBusy(true) + return read() + }, [read]) + useEffect(() => { - void refresh() - }, [refresh]) + void read() + }, [read]) /** Runs a change of an account, then reads the list again; a failure is shown above the list. */ async function change(work: () => Promise) { diff --git a/web/src/SettingsButton.tsx b/web/src/SettingsButton.tsx index 62b1b0c..950efd4 100644 --- a/web/src/SettingsButton.tsx +++ b/web/src/SettingsButton.tsx @@ -5,8 +5,8 @@ import { DEFAULT_SETTINGS, REFRESH_CHOICES, refreshLabel, saveBrowserSettings, u /** * An icon button that opens the settings of this browser: how often the Overview and the Metrics tab read the server on - * their own, or manual, when they read only when opened and on Refresh, and whether the shell button opens the shell in - * a new tab. A change applies at once and is kept in the browser; Defaults sets every setting back. + * their own, or manual, when they read only when opened and on Refresh, and whether the page menu opens the Shell page + * in a new tab. A change applies at once and is kept in the browser; Defaults sets every setting back. */ export default function SettingsButton() { const [open, setOpen] = useState(false) diff --git a/web/src/ShellPanel.tsx b/web/src/ShellPanel.tsx index 9a846e8..4a6e617 100644 --- a/web/src/ShellPanel.tsx +++ b/web/src/ShellPanel.tsx @@ -69,16 +69,17 @@ export default function ShellPanel(props: { editorShown: boolean; onFiles: (coun } }, []) + // The account, then a ticket when its console login is usable. useEffect(() => { - request('GET', '/account', ACCOUNT_SHAPE).then(setAccount).catch((caught: Error) => setError(caught.message)) - }, []) - - const enabled = login !== null - useEffect(() => { - if (enabled) { - void reopen() - } - }, [enabled, reopen]) + request('GET', '/account', ACCOUNT_SHAPE) + .then((found) => { + setAccount(found) + if (found.console?.enabled && found.otp) { + void reopen() + } + }) + .catch((caught: Error) => setError(caught.message)) + }, [reopen]) useEffect(() => { opened.current = props.onOpened diff --git a/web/src/SiteFiles.tsx b/web/src/SiteFiles.tsx index c8d3b4c..ed1f6e4 100644 --- a/web/src/SiteFiles.tsx +++ b/web/src/SiteFiles.tsx @@ -13,7 +13,8 @@ import { } from '@mui/material' import { useCallback, useEffect, useState, type DragEvent, type FormEvent } from 'react' import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx' -import { Section, bytes } from './ServerPanel.tsx' +import { Section } from './ServerPanel.tsx' +import { bytes } from './format.ts' import Toolbar from './Toolbar.tsx' import { ApiError, SITES_SHAPE, SITE_FILES_SHAPE, SITE_FOLDER_SHAPE, SITE_PATH_SHAPE, download, encodedPath, request, upload, @@ -77,7 +78,7 @@ export default function SiteFiles(props: { site: string | null; onSite: (name: s const [path, setPath] = useState('') const [folder, setFolder] = useState(null) const [error, setError] = useState(null) - const [busy, setBusy] = useState(false) + const [working, setWorking] = useState(false) const [progress, setProgress] = useState<{ name: string; share: number } | null>(null) const [extract, setExtract] = useState(true) const [creating, setCreating] = useState(false) @@ -91,29 +92,43 @@ export default function SiteFiles(props: { site: string | null; onSite: (name: s request('GET', '/sites', SITES_SHAPE).then(setSites).catch((caught) => setError((caught as ApiError).message)) }, []) - const refresh = useCallback(async () => { - if (!site) { + // The address of the folder shown, null without a site, and the one whose answer is shown. + const address = site ? `${base}/${encodedPath(path)}` : null + const [shown, setShown] = useState(null) + const busy = working || (address !== null && shown !== address) + + /** Reads the folder; the state changes only once the server answers. */ + const read = useCallback(async () => { + if (address === null) { return } - setBusy(true) - try { - setFolder(await request('GET', `${base}/${encodedPath(path)}`, SITE_FOLDER_SHAPE)) - setError(null) - } catch (caught) { - setFolder(null) - setError((caught as Error).message) - } finally { - setBusy(false) - } - }, [site, base, path]) + await request('GET', address, SITE_FOLDER_SHAPE) + .then((found) => { + setFolder(found) + setError(null) + }, (caught) => { + setFolder(null) + setError((caught as Error).message) + }) + .finally(() => { + setShown(address) + setWorking(false) + }) + }, [address]) + + /** Reads the folder again, busy until the server answers. */ + const refresh = useCallback(() => { + setWorking(true) + return read() + }, [read]) useEffect(() => { - void refresh() - }, [refresh]) + void read() + }, [read]) /** Runs a change of the files, then reads the folder again; a failure is shown above the list. */ async function change(work: () => Promise) { - setBusy(true) + setWorking(true) let failure: string | null = null try { await work() @@ -130,7 +145,7 @@ export default function SiteFiles(props: { site: string | null; onSite: (name: s async function send(files: File[]) { const limit = (sites?.settings.upload_max_mb ?? 0) * 1024 * 1024 const failures: string[] = [] - setBusy(true) + setWorking(true) for (const file of files) { if (limit && file.size > limit) { failures.push(`${file.name}: larger than ${sites?.settings.upload_max_mb} MiB.`) @@ -146,7 +161,7 @@ export default function SiteFiles(props: { site: string | null; onSite: (name: s } } setProgress(null) - setBusy(false) + setWorking(false) await refresh() setError(failures.length ? failures.join('\n') : null) } diff --git a/web/src/SiteToSitePanel.tsx b/web/src/SiteToSitePanel.tsx index 9e1f209..89bac1b 100644 --- a/web/src/SiteToSitePanel.tsx +++ b/web/src/SiteToSitePanel.tsx @@ -30,31 +30,36 @@ export default function SiteToSitePanel() { const [error, setError] = useState(null) const [unavailable, setUnavailable] = useState(false) const [note, setNote] = useState(null) - const [busy, setBusy] = useState(false) + const [busy, setBusy] = useState(true) const [adding, setAdding] = useState(false) const [editing, setEditing] = useState(null) const [confirm, setConfirm] = useState(null) - const refresh = useCallback(async () => { - setBusy(true) - try { - const found = await request<{ connections: SiteToSiteConnection[] }>('GET', '/site-to-site', SITE_TO_SITE_SHAPE) - setConnections(found.connections) - setError(null) - setUnavailable(false) - } catch (caught) { - const failure = caught as ApiError - setConnections(null) - setUnavailable(failure.status === 404) - setError(failure.message) - } finally { - setBusy(false) - } + /** Reads the connections; the state changes only once the server answers. */ + const read = useCallback(async () => { + await request<{ connections: SiteToSiteConnection[] }>('GET', '/site-to-site', SITE_TO_SITE_SHAPE) + .then((found) => { + setConnections(found.connections) + setError(null) + setUnavailable(false) + }, (caught) => { + const failure = caught as ApiError + setConnections(null) + setUnavailable(failure.status === 404) + setError(failure.message) + }) + .finally(() => setBusy(false)) }, []) + /** Reads the connections again, busy until the server answers. */ + const refresh = useCallback(() => { + setBusy(true) + return read() + }, [read]) + useEffect(() => { - void refresh() - }, [refresh]) + void read() + }, [read]) function remove(connection: SiteToSiteConnection) { setConfirm({ diff --git a/web/src/SiteToSiteStatusPanel.tsx b/web/src/SiteToSiteStatusPanel.tsx index 1db1676..89f27e9 100644 --- a/web/src/SiteToSiteStatusPanel.tsx +++ b/web/src/SiteToSiteStatusPanel.tsx @@ -1,7 +1,10 @@ import Refresh from '@mui/icons-material/Refresh' import { Alert, Box, Button } from '@mui/material' -import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx' -import { Grid, IPSEC_HEADS, duration, ipsecRows, text } from './ServerPanel.tsx' +import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx' +import { useBoard } from './useBoard.ts' +import { Grid } from './ServerPanel.tsx' +import { duration, text } from './format.ts' +import { IPSEC_HEADS, ipsecRows } from './ipsec.ts' import Toolbar from './Toolbar.tsx' import { DETAILS_SHAPE, request, type RouterDetails } from './api.ts' import { useRead } from './useRead.ts' diff --git a/web/src/SitesPanel.tsx b/web/src/SitesPanel.tsx index 1592a63..ab31ef3 100644 --- a/web/src/SitesPanel.tsx +++ b/web/src/SitesPanel.tsx @@ -9,9 +9,11 @@ import Settings from '@mui/icons-material/Settings' import { Alert, Box, Button, Checkbox, Chip, FormControlLabel, IconButton, Link, Stack, Table, TableBody, TableCell, TableHead, TableRow, Tooltip } from '@mui/material' import { useCallback, useEffect, useState, type ReactNode } from 'react' import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx' -import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx' +import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx' +import { useBoard } from './useBoard.ts' import { Copyable, Pairs } from './ServerPanel.tsx' -import SearchField, { matches } from './SearchField.tsx' +import SearchField from './SearchField.tsx' +import { matches } from './search.ts' import SiteDialog, { type SiteSettings } from './SiteDialog.tsx' import SitesSettingsDialog from './SitesSettingsDialog.tsx' import Toolbar from './Toolbar.tsx' @@ -44,7 +46,7 @@ export default function SitesPanel(props: { onOpenFiles: (name: string) => void const [groups, setGroups] = useState([]) const [error, setError] = useState(null) const [unavailable, setUnavailable] = useState(false) - const [busy, setBusy] = useState(false) + const [busy, setBusy] = useState(true) const [adding, setAdding] = useState(false) const [editing, setEditing] = useState(null) const [settings, setSettings] = useState(false) @@ -52,35 +54,40 @@ export default function SitesPanel(props: { onOpenFiles: (name: string) => void const [search, setSearch] = useState('') const board = useBoard(LAYOUT_KEY) - const refresh = useCallback(async () => { - setBusy(true) - try { - const [found, groupList, details] = await Promise.all([ - request('GET', '/sites', SITES_SHAPE), - request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE), - request('GET', '/config', DETAILS_SHAPE), - ]) - setSites(found) - setGroups(groupList.groups.map((group) => group.name)) - const wan = details.configuration.wan ?? {} - const pki = details.configuration.pki ?? {} - setFqdn(typeof wan.local_fqdn === 'string' ? wan.local_fqdn : '') - setCas(typeof pki.issuing_cas === 'object' && pki.issuing_cas !== null ? Object.keys(pki.issuing_cas) : []) - setError(null) - setUnavailable(false) - } catch (caught) { - const failure = caught as ApiError - setSites(null) - setUnavailable(failure.status === 404) - setError(failure.message) - } finally { - setBusy(false) - } + /** Reads the sites with the groups and the server's details; the state changes only once the server answers. */ + const read = useCallback(async () => { + await Promise.all([ + request('GET', '/sites', SITES_SHAPE), + request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE), + request('GET', '/config', DETAILS_SHAPE), + ]) + .then(([found, groupList, details]) => { + setSites(found) + setGroups(groupList.groups.map((group) => group.name)) + const wan = details.configuration.wan ?? {} + const pki = details.configuration.pki ?? {} + setFqdn(typeof wan.local_fqdn === 'string' ? wan.local_fqdn : '') + setCas(typeof pki.issuing_cas === 'object' && pki.issuing_cas !== null ? Object.keys(pki.issuing_cas) : []) + setError(null) + setUnavailable(false) + }, (caught) => { + const failure = caught as ApiError + setSites(null) + setUnavailable(failure.status === 404) + setError(failure.message) + }) + .finally(() => setBusy(false)) }, []) + /** Reads the sites again, busy until the server answers. */ + const refresh = useCallback(() => { + setBusy(true) + return read() + }, [read]) + useEffect(() => { - void refresh() - }, [refresh]) + void read() + }, [read]) /** Runs a change of a site, then reads the list again; a failure is shown above the list. */ async function change(work: () => Promise) { diff --git a/web/src/SystemPanel.tsx b/web/src/SystemPanel.tsx index a4b8b6b..97491b4 100644 --- a/web/src/SystemPanel.tsx +++ b/web/src/SystemPanel.tsx @@ -1,6 +1,7 @@ import { Box } from '@mui/material' import ComponentsPanel from './ComponentsPanel.tsx' -import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx' +import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx' +import { useBoard } from './useBoard.ts' import Toolbar from './Toolbar.tsx' import UpdatesNotice from './UpdatesNotice.tsx' diff --git a/web/src/TemplateDialog.tsx b/web/src/TemplateDialog.tsx index 525eeb5..9988b1d 100644 --- a/web/src/TemplateDialog.tsx +++ b/web/src/TemplateDialog.tsx @@ -2,7 +2,7 @@ import { Alert, Autocomplete, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography, } from '@mui/material' import { useState, type FormEvent } from 'react' -import { NAME_PATTERN, NEW_TEMPLATE, daysProblem } from './PkiSettingsDialog.tsx' +import { daysProblem, NAME_PATTERN, NEW_TEMPLATE } from './pki.ts' import { BUILTIN_TEMPLATES, KEY_USAGES, OID_PATTERN, PKI_KEYS, SAN_TYPES, TEMPLATE_SUBJECTS, type Pki, type PkiTemplate, } from './api.ts' diff --git a/web/src/UpdatesNotice.tsx b/web/src/UpdatesNotice.tsx index 9ecd8dc..a5ec49a 100644 --- a/web/src/UpdatesNotice.tsx +++ b/web/src/UpdatesNotice.tsx @@ -50,16 +50,13 @@ export default function UpdatesNotice(props: { onBusy?: (busy: boolean) => void; const [rebooting, setRebooting] = useState(false) const read = useCallback(async () => { - try { - const next = await request('GET', upgradePath, UPGRADE_SHAPE) + await request('GET', upgradePath, UPGRADE_SHAPE).then((next) => { setUpgrade(next) setUnreachable(false) if (next.state !== 'running') { request('GET', updatesPath, UPDATES_SHAPE).then(setUpdates, (caught: Error) => setError(caught.message)) } - } catch { - setUnreachable(true) - } + }, () => setUnreachable(true)) }, [updatesPath, upgradePath]) useEffect(() => { diff --git a/web/src/UsersPanel.tsx b/web/src/UsersPanel.tsx index 0ab9f9b..f241cd3 100644 --- a/web/src/UsersPanel.tsx +++ b/web/src/UsersPanel.tsx @@ -20,7 +20,8 @@ import OtpDialog from './OtpDialog.tsx' import PersonDialog from './PersonDialog.tsx' import ProfileDialog from './ProfileDialog.tsx' import { Section } from './ServerPanel.tsx' -import SearchField, { matches } from './SearchField.tsx' +import SearchField from './SearchField.tsx' +import { matches } from './search.ts' import Toolbar from './Toolbar.tsx' import UserDialog from './UserDialog.tsx' import { @@ -54,7 +55,7 @@ export default function UsersPanel() { const [users, setUsers] = useState(null) const [error, setError] = useState(null) const [unavailable, setUnavailable] = useState(false) - const [busy, setBusy] = useState(false) + const [busy, setBusy] = useState(true) const [adding, setAdding] = useState(false) const [password, setPassword] = useState(null) const [details, setDetails] = useState(null) @@ -66,8 +67,8 @@ export default function UsersPanel() { const [search, setSearch] = useState('') const [kind, setKind] = useState('all') - const refresh = useCallback(async () => { - setBusy(true) + /** Reads the users; the state changes only once the server answers. */ + const read = useCallback(async () => { // The status has openvpn and p2s while the server runs OpenVPN and IKEv2, which the profiles need; null while it is // not known. request('GET', '/status/full', STATUS_SHAPE) @@ -79,23 +80,29 @@ export default function UsersPanel() { setOpenvpn(null) setP2s(null) }) - try { - setUsers((await request<{ users: User[] }>('GET', '/users', USERS_SHAPE)).users) - setError(null) - setUnavailable(false) - } catch (caught) { - const failure = caught as ApiError - setUsers(null) - setUnavailable(failure.status === 404) - setError(failure.message) - } finally { - setBusy(false) - } + await request<{ users: User[] }>('GET', '/users', USERS_SHAPE) + .then((found) => { + setUsers(found.users) + setError(null) + setUnavailable(false) + }, (caught) => { + const failure = caught as ApiError + setUsers(null) + setUnavailable(failure.status === 404) + setError(failure.message) + }) + .finally(() => setBusy(false)) }, []) + /** Reads the users again, busy until the server answers. */ + const refresh = useCallback(() => { + setBusy(true) + return read() + }, [read]) + useEffect(() => { - void refresh() - }, [refresh]) + void read() + }, [read]) /** Runs a change of a user, then reads the list again; a failure is shown above the list after the reading. */ async function change(work: () => Promise) { diff --git a/web/src/api.ts b/web/src/api.ts index 6d0e34c..75a485a 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -346,9 +346,6 @@ export type Backup = { /** The key types of the CAs and of the templates. */ export const PKI_KEYS = ['rsa-2048', 'rsa-3072', 'rsa-4096', 'ec-p256', 'ec-p384'] as const -/** Where the CA certificates and CRLs are published, in the order the certificates list the URLs. */ -export const PKI_PUBLISH = ['http', 'http-80', 'https', 'https-default'] as const - /** The key usages a template may give. */ export const KEY_USAGES = ['digital_signature', 'content_commitment', 'key_encipherment', 'data_encipherment', 'key_agreement'] as const @@ -391,7 +388,6 @@ export type PkiSettings = { key: string crl_days: number root_crl_days: number - publish: string[] p2s_name: string s2s_name: string servers_name: string @@ -977,7 +973,6 @@ const PKI_SETTINGS: Check = object({ key: string, crl_days: number, root_crl_days: number, - publish: list(string), p2s_name: string, s2s_name: string, servers_name: string, diff --git a/web/src/backup.ts b/web/src/backup.ts new file mode 100644 index 0000000..8878917 --- /dev/null +++ b/web/src/backup.ts @@ -0,0 +1,31 @@ +import type { Backup } from './api.ts' +import { bytes, when } from './format.ts' + +/** The labels of the backup targets. */ +export const TARGET_LABELS: Record = { local: 'Local folder', pbs: 'Proxmox Backup Server' } + +/** The schedule, the next run (as systemd shows it) and the last run of the server's backups, as rows of Pairs. */ +export function backupRows(backup: Backup): [string, string][] { + const { settings, state } = backup + const rows: [string, string][] = [ + ['Backups', settings.enabled ? `${settings.schedule}, to ${TARGET_LABELS[settings.target] ?? settings.target}` : 'off'], + ['Next run', backup.next ?? '-'], + ] + if (!state) { + return [...rows, ['Last run', 'none']] + } + rows.push( + ['Last run', `${when(state.started)}${state.finished ? ` to ${new Date(state.finished).toLocaleTimeString()}` : ''}`], + ['Last result', state.result], + ) + if (state.archive ?? state.snapshot) { + rows.push(['Last backup', `${state.archive ?? state.snapshot}${state.size === null ? '' : `, ${bytes(state.size)}`}`]) + } + if (state.cloud) { + rows.push(['Cloud copy', `${state.cloud.mode} to ${state.cloud.remote}: ${state.cloud.error ?? state.cloud.result}`]) + } + if (state.error) { + rows.push(['Error', state.error]) + } + return rows +} diff --git a/web/src/format.ts b/web/src/format.ts new file mode 100644 index 0000000..418effb --- /dev/null +++ b/web/src/format.ts @@ -0,0 +1,31 @@ +/** A time of the server in the browser's format, or a dash. */ +export function when(time: string | null | undefined) { + return time ? new Date(time).toLocaleString() : '-' +} + +/** A value as text: lists joined with commas, an empty value as a dash. */ +export function text(value: unknown): string { + if (Array.isArray(value)) { + return value.length === 0 ? '-' : value.join(', ') + } + return value === undefined || value === null || value === '' ? '-' : String(value) +} + +/** Seconds as "1h 2m 3s". */ +export function duration(seconds: number) { + const h = Math.floor(seconds / 3600) + const m = Math.floor((seconds % 3600) / 60) + return [h && `${h}h`, (h || m) && `${m}m`, `${seconds % 60}s`].filter(Boolean).join(' ') +} + +/** Bytes in B, KiB, MiB or GiB. */ +export function bytes(count: number) { + const units = ['B', 'KiB', 'MiB', 'GiB'] + let value = count + let unit = 0 + while (value >= 1024 && unit < units.length - 1) { + value /= 1024 + unit += 1 + } + return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}` +} diff --git a/web/src/https.ts b/web/src/https.ts new file mode 100644 index 0000000..3f32d58 --- /dev/null +++ b/web/src/https.ts @@ -0,0 +1,16 @@ +import type { AcmeProvider, HttpsCertificateSource } from './api.ts' + +/** The labels of the sources of the server's certificate. */ +export const CERTIFICATE_LABELS: Record = { + acme: 'ACME', + 'self-signed': 'Self-signed', + ca: 'Servers Issuing CA of the server\'s PKI', + external: 'Another CA: a CSR signed there, or a PFX', +} + +/** The labels of the ACME providers. */ +export const PROVIDER_LABELS: Record = { + letsencrypt: 'Let\'s Encrypt', + zerossl: 'ZeroSSL', + custom: 'Custom directory URL', +} diff --git a/web/src/ipsec.ts b/web/src/ipsec.ts new file mode 100644 index 0000000..d1ad164 --- /dev/null +++ b/web/src/ipsec.ts @@ -0,0 +1,66 @@ +import type { RouterDetails } from './api.ts' +import { bytes, duration, text } from './format.ts' + +/** The column titles of the IPsec tables of ipsecRows. */ +export const IPSEC_HEADS = { + sas: ['Connection', 'State', 'Local', 'Remote', 'Algorithms', 'Up'], + childSas: ['Child SA', 'State', 'Traffic selectors', 'In', 'Out', 'Up'], + connections: ['Connection', 'Version', 'Local address', 'Local identity', 'Remote address', 'Remote identity', 'Authentication'], + children: ['Child', 'Mode', 'Local traffic selectors', 'Remote traffic selectors'], +} + +/** + * The rows of the IPsec tables of the server's /config for the connections whose names keep accepts: the IKE SAs, their + * child SAs, the connections and their children; undefined where the server could not list them. + */ +export function ipsecRows(details: RouterDetails | null, keep: (name: string) => boolean) { + const sas = details?.ipsec.sas?.filter((sa) => keep(sa.name)) + const connections = details?.ipsec.connections?.filter((connection) => keep(connection.name)) + return { + sas: sas?.map((sa) => [ + sa.name, + sa.state, + `${sa['local-id']} @ ${sa['local-host']}`, + `${sa['remote-id']} @ ${sa['remote-host']}`, + [`${text(sa['encr-alg'])}-${text(sa['encr-keysize'])}`, sa['integ-alg'], sa['dh-group']].filter(Boolean).join(', '), + sa.established === undefined ? '-' : duration(Number(sa.established)), + ]), + childSas: sas?.flatMap((sa) => + Object.values(sa['child-sas'] ?? {}).map((child) => [ + `${sa.name}/${child.name}`, + `${child.state}, ${child.mode}`, + `${child['local-ts'].join(', ')} <-> ${child['remote-ts'].join(', ')}`, + `${bytes(Number(child['bytes-in']))}, ${child['packets-in']} packets`, + `${bytes(Number(child['bytes-out']))}, ${child['packets-out']} packets`, + child['install-time'] === undefined ? '-' : duration(Number(child['install-time'])), + ]), + ), + connections: connections?.map((connection) => { + const local = authOf(connection, 'local') + const remote = authOf(connection, 'remote') + return [ + connection.name, + connection.version, + text(connection.local_addrs), + text(local.id), + text(connection.remote_addrs), + text(remote.id), + local.class === remote.class ? text(local.class) : `${text(local.class)} / ${text(remote.class)}`, + ] + }), + children: connections?.flatMap((connection) => + Object.entries(connection.children ?? {}).map(([name, child]) => [ + `${connection.name}/${name}`, + child.mode, + child['local-ts'].join(', '), + child['remote-ts'].join(', '), + ]), + ), + } +} + +/** The authentication round of one side of a connection: swanctl names them local-1, remote-1 and so on. */ +function authOf(connection: Record, side: 'local' | 'remote'): { class?: string; id?: string } { + const round = Object.entries(connection).find(([key, value]) => key.startsWith(`${side}-`) && typeof value === 'object' && value !== null) + return (round?.[1] ?? {}) as { class?: string; id?: string } +} diff --git a/web/src/pki.ts b/web/src/pki.ts new file mode 100644 index 0000000..a6a7fbc --- /dev/null +++ b/web/src/pki.ts @@ -0,0 +1,50 @@ +import type { PkiAuthority, PkiRootSource, PkiTemplate } from './api.ts' + +/** The labels of the sources of the root CA. */ +export const ROOT_SOURCE_LABELS: Record = { + local: 'Created by the server', + offline: 'Offline', + 'simple-ca': 'Simple CA', +} + +/** The name of an issuing CA or a template, as the server accepts it. */ +export const NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}$/ + +/** The names the issuing CAs of pki.issuing_cas cannot have. */ +export const RESERVED = ['root', 'upstream', 'p2s', 's2s', 'servers'] + +/** The longest common name of a CA, in characters. */ +const CA_NAME_MAX = 64 + +/** The longest lifetime the server accepts, in days. */ +const DAYS_MAX = 36500 + +/** A new template's options. */ +export const NEW_TEMPLATE: PkiTemplate = { + key: 'rsa-3072', days: 365, key_usage: ['digital_signature'], extended_key_usage: [], subject: 'name', sans: [], policies: [], +} + +/** Whether an issuing CA has its certificate or its CSR, which fix its common name. */ +export function made(authority: PkiAuthority) { + return authority.state === 'active' || authority.state === 'pending' +} + +/** A common name's problem, or ''. */ +export function nameProblem(value: string) { + return value.trim() === '' || value.trim().length > CA_NAME_MAX ? `1 to ${CA_NAME_MAX} characters.` : '' +} + +/** The problem of the URL of a Simple CA service, or ''. */ +export function urlProblem(value: string) { + try { + const url = new URL(value.trim()) + return url.protocol === 'https:' && url.hostname !== '' && url.search === '' && url.hash === '' ? '' : 'An https:// URL.' + } catch { + return 'An https:// URL.' + } +} + +/** A lifetime's problem, or ''. */ +export function daysProblem(value: number) { + return !Number.isInteger(value) || value < 1 || value > DAYS_MAX ? `1 to ${DAYS_MAX} days.` : '' +} diff --git a/web/src/search.ts b/web/src/search.ts new file mode 100644 index 0000000..3ea2e60 --- /dev/null +++ b/web/src/search.ts @@ -0,0 +1,5 @@ +/** Whether any of the texts contains the search, ignoring case; an empty search matches everything. */ +export function matches(search: string, texts: (string | null | undefined)[]) { + const wanted = search.trim().toLowerCase() + return wanted === '' || texts.some((text) => text?.toLowerCase().includes(wanted)) +} diff --git a/web/src/settings.ts b/web/src/settings.ts index 85b5234..240e1d7 100644 --- a/web/src/settings.ts +++ b/web/src/settings.ts @@ -3,7 +3,7 @@ import { useSyncExternalStore } from 'react' /** * The settings of this browser: the seconds between the automatic reads of the Overview and the Metrics tab, 0 for * manual, whether the WireGuard configuration dialog leaves out the lines a client fills in (wireguardPrefilled), and - * whether the shell button opens the shell in a new tab (shellNewTab). + * whether the page menu opens the Shell page in a new tab (shellNewTab). */ export type BrowserSettings = { routerRefresh: number; metricsRefresh: number; wireguardPrefilled: boolean; shellNewTab: boolean } diff --git a/web/src/useBoard.ts b/web/src/useBoard.ts new file mode 100644 index 0000000..c9fb46c --- /dev/null +++ b/web/src/useBoard.ts @@ -0,0 +1,49 @@ +import { useState } from 'react' + +/** The layout of a board: the order of the panel ids, the width chosen for a panel, and the hidden and the folded panels. */ +export type Layout = { order: string[]; widths: Record; hidden: string[]; folded: string[] } + +const EMPTY: Layout = { order: [], widths: {}, hidden: [], folded: [] } + +/** The layout kept in localStorage under key, or an empty one when there is none or it cannot be read. */ +function readLayout(key: string): Layout { + try { + const value: unknown = JSON.parse(window.localStorage.getItem(key) ?? 'null') + if (value !== null && typeof value === 'object') { + const stored = value as Partial + const strings = (items: unknown) => (Array.isArray(items) ? items.filter((item): item is string => typeof item === 'string') : []) + return { + order: strings(stored.order), + widths: stored.widths !== null && typeof stored.widths === 'object' ? stored.widths : {}, + hidden: strings(stored.hidden), + folded: strings(stored.folded), + } + } + } catch { + // A layout that cannot be read is replaced by the default. + } + return EMPTY +} + +/** The layout of a board kept in the browser's localStorage under key, and a function that changes and keeps it. */ +function useLayout(key: string): [Layout, (change: (current: Layout) => Layout) => void] { + const [layout, setLayout] = useState(() => readLayout(key)) + function update(change: (current: Layout) => Layout) { + setLayout((current) => { + const next = change(current) + window.localStorage.setItem(key, JSON.stringify(next)) + return next + }) + } + return [layout, update] +} + +/** The state of a page's board: its layout kept in the browser under key, whether it is edited, and the Panels dialog. */ +export type BoardState = ReturnType + +export function useBoard(key: string) { + const [layout, setLayout] = useLayout(key) + const [editing, setEditing] = useState(false) + const [choosing, setChoosing] = useState(false) + return { layout, setLayout, editing, setEditing, choosing, setChoosing } +} diff --git a/web/src/useRead.ts b/web/src/useRead.ts index 8f6caf4..dace31a 100644 --- a/web/src/useRead.ts +++ b/web/src/useRead.ts @@ -8,23 +8,26 @@ import { useCallback, useEffect, useState } from 'react' export function useRead(load: () => Promise) { const [data, setData] = useState(null) const [error, setError] = useState(null) - const [busy, setBusy] = useState(false) + const [busy, setBusy] = useState(true) - const refresh = useCallback(async () => { - setBusy(true) - try { - setData(await load()) - setError(null) - } catch (caught) { - setError((caught as Error).message) - } finally { - setBusy(false) - } + // The state changes only once load answers. + const read = useCallback(async () => { + await load() + .then((answer) => { + setData(answer) + setError(null) + }, (caught) => setError((caught as Error).message)) + .finally(() => setBusy(false)) }, [load]) + const refresh = useCallback(() => { + setBusy(true) + return read() + }, [read]) + useEffect(() => { - void refresh() - }, [refresh]) + void read() + }, [read]) return { data, error, busy, refresh } }