From 34293fb8e5af5dbdd22586c303e6c968c5fe5aa4 Mon Sep 17 00:00:00 2001 From: Aemeath <35622087+tickcount@users.noreply.github.com> Date: Fri, 16 Oct 2026 02:12:50 +0300 Subject: [PATCH] Dawnline 0.4.0 - Components tab replaces Updates: Dawnline, the AmneziaWG build for this firmware (Slava-Shchipunov 2.0 or 2Grey 3.1, Russian translation) and the system packages Dawnline adds, each checked, installed, reinstalled or rolled back in place, with What's new, versions and an activity log - Automatic updates: daily check, install at a set time or right away, per component; AmneziaWG is left out by default and an automatic run never switches its build or generation - Downloads verified against GitHub's sha256; mirrors are used only when GitHub is unreachable and the hash is known - New installer: checks firmware, clock, space and DNS, lets you pick a release, shows the plan and asks first; --dry-run - New uninstaller removes everything Dawnline added (cron, nft, firewall, routing, interfaces, packages it installed); --dry-run - Works without AmneziaWG on the router: Overview, the setup wizard, Health and Components say what is missing and offer to install it - Overview shows failed health checks as notices with their fix - People list no longer reads the config from the browser: private keys stay on the router; personal links are fetched on demand - Config changes are serialized under one lock, the nft table loads atomically and fails closed, and Dawnline never touches network sections it did not create - The portal never opens system ports, keeps disabled devices disabled, rate-limits per address and counts days by the router's clock - Settings and Diagnostics load their heavy parts in the background - Release notes are written from the commits since the previous release - Backend and admin UI split into small single-purpose modules --- .github/workflows/build.yml | 35 +- .github/workflows/ci.yml | 7 + README.md | 85 +- install.sh | 1382 +++++++++++++++-- package/luci-app-dawnline/Makefile | 13 +- .../luci-static/resources/dawnline/app.js | 35 +- .../root/lib/upgrade/keep.d/dawnline-data | 1 + .../luci-app-dawnline/root/usr/bin/dawnline | 91 +- .../root/usr/libexec/dawnline/agent | 218 ++- .../root/usr/libexec/dawnline/updater | 698 +++------ .../share/dawnline/portal/assets/portal.js | 12 +- .../share/dawnline/portal/www/cgi-bin/portal | 379 +---- .../share/luci/menu.d/luci-app-dawnline.json | 2 +- .../share/rpcd/acl.d/luci-app-dawnline.json | 16 +- .../root/usr/share/rpcd/ucode/luci.dawnline | 1366 +--------------- .../root/usr/share/ucode/dawnline/access.uc | 57 +- .../root/usr/share/ucode/dawnline/apply.uc | 767 ++------- .../root/usr/share/ucode/dawnline/awg.uc | 493 ++++++ .../usr/share/ucode/dawnline/awg_builds.uc | 55 + .../root/usr/share/ucode/dawnline/backup.uc | 285 ++++ .../root/usr/share/ucode/dawnline/core.uc | 422 ++--- .../root/usr/share/ucode/dawnline/devices.uc | 115 ++ .../root/usr/share/ucode/dawnline/fw.uc | 177 +++ .../root/usr/share/ucode/dawnline/github.uc | 226 +++ .../root/usr/share/ucode/dawnline/health.uc | 433 ++++++ .../root/usr/share/ucode/dawnline/live.uc | 92 +- .../root/usr/share/ucode/dawnline/lookup.uc | 98 ++ .../root/usr/share/ucode/dawnline/loop.uc | 178 +-- .../root/usr/share/ucode/dawnline/migrate.uc | 64 + .../root/usr/share/ucode/dawnline/net.uc | 42 +- .../root/usr/share/ucode/dawnline/netifd.uc | 125 ++ .../root/usr/share/ucode/dawnline/nft.uc | 225 +++ .../root/usr/share/ucode/dawnline/ops.uc | 689 -------- .../root/usr/share/ucode/dawnline/pkg.uc | 120 ++ .../root/usr/share/ucode/dawnline/portal.uc | 463 ++++++ .../usr/share/ucode/dawnline/portalcert.uc | 116 ++ .../root/usr/share/ucode/dawnline/resolver.uc | 99 ++ .../usr/share/ucode/dawnline/rpc/common.uc | 83 + .../root/usr/share/ucode/dawnline/rpc/home.uc | 214 +++ .../usr/share/ucode/dawnline/rpc/maint.uc | 89 ++ .../usr/share/ucode/dawnline/rpc/people.uc | 164 ++ .../usr/share/ucode/dawnline/rpc/servers.uc | 531 +++++++ .../usr/share/ucode/dawnline/rpc/settings.uc | 150 ++ .../usr/share/ucode/dawnline/rpc/status.uc | 230 +++ .../usr/share/ucode/dawnline/rpc/updates.uc | 139 ++ .../root/usr/share/ucode/dawnline/schema.uc | 254 +++ .../root/usr/share/ucode/dawnline/store.uc | 43 + .../root/usr/share/ucode/dawnline/upd_app.uc | 135 ++ .../root/usr/share/ucode/dawnline/upd_awg.uc | 231 +++ .../root/usr/share/ucode/dawnline/upd_pkgs.uc | 92 ++ .../root/usr/share/ucode/dawnline/updates.uc | 228 +++ .../root/usr/share/ucode/dawnline/util.uc | 173 ++- .../root/usr/share/ucode/dawnline/view.uc | 21 +- .../root/usr/share/ucode/dawnline/watchdog.uc | 50 +- scripts/check-ucode.sh | 8 +- scripts/lint-ucode.py | 104 +- scripts/release-notes.sh | 72 + uninstall.sh | 771 +++++++++ web/.prettierignore | 1 + web/package-lock.json | 4 +- web/package.json | 2 +- web/src/admin/access.ts | 202 ++- web/src/admin/api.ts | 118 +- web/src/admin/charts.ts | 96 -- web/src/admin/cores/awg.ts | 389 +++++ web/src/admin/cores/common.ts | 41 + web/src/admin/cores/index.ts | 21 + web/src/admin/css.d.ts | 5 + web/src/admin/device.ts | 375 +++-- web/src/admin/disguise.ts | 17 +- web/src/admin/events/csv.ts | 12 + web/src/admin/events/model.ts | 74 + web/src/admin/events/render.ts | 256 +++ web/src/admin/interfaces.ts | 98 +- web/src/admin/invite.ts | 52 +- web/src/admin/logs.ts | 100 +- web/src/admin/luci.d.ts | 5 - web/src/admin/main.ts | 25 +- web/src/admin/pages/components/activity.ts | 50 + web/src/admin/pages/components/awg.ts | 172 ++ web/src/admin/pages/components/hero.ts | 294 ++++ web/src/admin/pages/components/index.ts | 254 +++ web/src/admin/pages/components/packages.ts | 93 ++ web/src/admin/pages/diagnostics.ts | 94 -- web/src/admin/pages/diagnostics/health.ts | 211 +++ web/src/admin/pages/diagnostics/index.ts | 119 ++ .../pages/{activity.ts => diagnostics/log.ts} | 93 +- web/src/admin/pages/maintenance.ts | 484 ------ web/src/admin/pages/overview.ts | 456 +----- web/src/admin/pages/people.ts | 439 +++--- web/src/admin/pages/person.ts | 1105 ------------- web/src/admin/pages/person/activity.ts | 151 ++ web/src/admin/pages/person/devices.ts | 97 ++ web/src/admin/pages/person/dialogs.ts | 128 ++ web/src/admin/pages/person/header.ts | 73 + web/src/admin/pages/person/index.ts | 189 +++ web/src/admin/pages/person/limits.ts | 293 ++++ web/src/admin/pages/person/pickers.ts | 228 +++ web/src/admin/pages/server.ts | 527 +++---- web/src/admin/pages/settings.ts | 765 --------- web/src/admin/{ => pages/settings}/backups.ts | 31 +- web/src/admin/pages/settings/common.ts | 61 + web/src/admin/pages/settings/danger.ts | 54 + web/src/admin/pages/settings/defaults.ts | 55 + web/src/admin/pages/settings/index.ts | 90 ++ web/src/admin/pages/settings/logs.ts | 177 +++ web/src/admin/pages/settings/map.ts | 35 + web/src/admin/pages/settings/portal.ts | 400 +++++ web/src/admin/pages/settings/updates.ts | 121 ++ web/src/admin/pkgs.ts | 65 +- web/src/admin/state/poller.ts | 73 + web/src/admin/state/scope.ts | 39 + web/src/admin/styles.ts | 1123 -------------- web/src/admin/styles/access.css | 46 + web/src/admin/styles/base.css | 115 ++ web/src/admin/styles/components.css | 87 ++ web/src/admin/styles/controls.css | 119 ++ web/src/admin/styles/dialogs.css | 47 + web/src/admin/styles/disguise.css | 33 + web/src/admin/styles/drawer.css | 52 + web/src/admin/styles/health.css | 55 + web/src/admin/styles/index.ts | 53 + web/src/admin/styles/layout.css | 48 + web/src/admin/styles/map.css | 65 + web/src/admin/styles/overview.css | 187 +++ web/src/admin/styles/people.css | 46 + web/src/admin/styles/person.css | 145 ++ web/src/admin/styles/portal-settings.css | 68 + web/src/admin/styles/settings.css | 64 + web/src/admin/ui.ts | 316 ---- web/src/admin/ui/badges.ts | 63 + web/src/admin/ui/button.ts | 53 + web/src/admin/ui/controls.ts | 118 ++ web/src/admin/ui/drawer.ts | 57 + web/src/admin/ui/files.ts | 63 + web/src/admin/{kit.ts => ui/layout.ts} | 58 +- web/src/admin/ui/menu.ts | 74 + web/src/admin/ui/modal.ts | 65 + web/src/admin/ui/nav.ts | 8 + web/src/admin/ui/toast.ts | 56 + web/src/admin/ui/tooltip.ts | 37 + web/src/admin/updater/jobs.ts | 79 + web/src/admin/updater/markdown.ts | 94 ++ web/src/admin/updater/notes.ts | 37 + web/src/admin/updater/operation.ts | 235 +++ web/src/admin/widgets/access-picker.ts | 37 + web/src/admin/widgets/health.ts | 87 ++ web/src/admin/widgets/spark.ts | 33 + web/src/admin/widgets/tiles.ts | 114 ++ web/src/portal/main.ts | 129 +- web/src/shared/chart.ts | 26 - web/src/shared/format.ts | 90 +- web/src/shared/types.ts | 34 +- web/tests/events.test.ts | 64 + web/tests/fakedom.ts | 30 + web/tests/format.test.ts | 52 + web/tests/updater.test.ts | 75 + web/tsup.config.ts | 31 +- 158 files changed, 17418 insertions(+), 10022 deletions(-) create mode 100644 package/luci-app-dawnline/root/lib/upgrade/keep.d/dawnline-data create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg_builds.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/fw.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/github.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/lookup.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/migrate.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/netifd.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/nft.uc delete mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/ops.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/portalcert.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/resolver.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/common.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/home.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/maint.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/settings.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/status.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/updates.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/store.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_app.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_pkgs.uc create mode 100644 package/luci-app-dawnline/root/usr/share/ucode/dawnline/updates.uc create mode 100755 scripts/release-notes.sh create mode 100755 uninstall.sh delete mode 100644 web/src/admin/charts.ts create mode 100644 web/src/admin/cores/awg.ts create mode 100644 web/src/admin/cores/common.ts create mode 100644 web/src/admin/cores/index.ts create mode 100644 web/src/admin/css.d.ts create mode 100644 web/src/admin/events/csv.ts create mode 100644 web/src/admin/events/model.ts create mode 100644 web/src/admin/events/render.ts create mode 100644 web/src/admin/pages/components/activity.ts create mode 100644 web/src/admin/pages/components/awg.ts create mode 100644 web/src/admin/pages/components/hero.ts create mode 100644 web/src/admin/pages/components/index.ts create mode 100644 web/src/admin/pages/components/packages.ts delete mode 100644 web/src/admin/pages/diagnostics.ts create mode 100644 web/src/admin/pages/diagnostics/health.ts create mode 100644 web/src/admin/pages/diagnostics/index.ts rename web/src/admin/pages/{activity.ts => diagnostics/log.ts} (56%) delete mode 100644 web/src/admin/pages/maintenance.ts delete mode 100644 web/src/admin/pages/person.ts create mode 100644 web/src/admin/pages/person/activity.ts create mode 100644 web/src/admin/pages/person/devices.ts create mode 100644 web/src/admin/pages/person/dialogs.ts create mode 100644 web/src/admin/pages/person/header.ts create mode 100644 web/src/admin/pages/person/index.ts create mode 100644 web/src/admin/pages/person/limits.ts create mode 100644 web/src/admin/pages/person/pickers.ts delete mode 100644 web/src/admin/pages/settings.ts rename web/src/admin/{ => pages/settings}/backups.ts (86%) create mode 100644 web/src/admin/pages/settings/common.ts create mode 100644 web/src/admin/pages/settings/danger.ts create mode 100644 web/src/admin/pages/settings/defaults.ts create mode 100644 web/src/admin/pages/settings/index.ts create mode 100644 web/src/admin/pages/settings/logs.ts create mode 100644 web/src/admin/pages/settings/map.ts create mode 100644 web/src/admin/pages/settings/portal.ts create mode 100644 web/src/admin/pages/settings/updates.ts create mode 100644 web/src/admin/state/poller.ts create mode 100644 web/src/admin/state/scope.ts delete mode 100644 web/src/admin/styles.ts create mode 100644 web/src/admin/styles/access.css create mode 100644 web/src/admin/styles/base.css create mode 100644 web/src/admin/styles/components.css create mode 100644 web/src/admin/styles/controls.css create mode 100644 web/src/admin/styles/dialogs.css create mode 100644 web/src/admin/styles/disguise.css create mode 100644 web/src/admin/styles/drawer.css create mode 100644 web/src/admin/styles/health.css create mode 100644 web/src/admin/styles/index.ts create mode 100644 web/src/admin/styles/layout.css create mode 100644 web/src/admin/styles/map.css create mode 100644 web/src/admin/styles/overview.css create mode 100644 web/src/admin/styles/people.css create mode 100644 web/src/admin/styles/person.css create mode 100644 web/src/admin/styles/portal-settings.css create mode 100644 web/src/admin/styles/settings.css delete mode 100644 web/src/admin/ui.ts create mode 100644 web/src/admin/ui/badges.ts create mode 100644 web/src/admin/ui/button.ts create mode 100644 web/src/admin/ui/controls.ts create mode 100644 web/src/admin/ui/drawer.ts create mode 100644 web/src/admin/ui/files.ts rename web/src/admin/{kit.ts => ui/layout.ts} (51%) create mode 100644 web/src/admin/ui/menu.ts create mode 100644 web/src/admin/ui/modal.ts create mode 100644 web/src/admin/ui/nav.ts create mode 100644 web/src/admin/ui/toast.ts create mode 100644 web/src/admin/ui/tooltip.ts create mode 100644 web/src/admin/updater/jobs.ts create mode 100644 web/src/admin/updater/markdown.ts create mode 100644 web/src/admin/updater/notes.ts create mode 100644 web/src/admin/updater/operation.ts create mode 100644 web/src/admin/widgets/access-picker.ts create mode 100644 web/src/admin/widgets/health.ts create mode 100644 web/src/admin/widgets/spark.ts create mode 100644 web/src/admin/widgets/tiles.ts delete mode 100644 web/src/shared/chart.ts create mode 100644 web/tests/events.test.ts create mode 100644 web/tests/fakedom.ts create mode 100644 web/tests/format.test.ts create mode 100644 web/tests/updater.test.ts diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 834f725..ec6fe68 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -3,14 +3,17 @@ name: Build packages # A tag vX.Y.Z builds luci-app-dawnline as .ipk (OpenWrt 24.10, opkg) and .apk # (OpenWrt 25.12, apk) with the OpenWrt SDK and publishes a GitHub release with # both packages and sha256sums.txt, the files install.sh and the in-app updater -# download. Run it by hand to get the packages as workflow artifacts only. +# download. The release notes list what changed since the previous tag, from the +# commits (scripts/release-notes.sh). Run it by hand to get the packages as +# workflow artifacts only. on: push: tags: ['v*'] workflow_dispatch: +# Read-only by default; only the release job may write (publish the release). permissions: - contents: write + contents: read jobs: version: @@ -21,6 +24,8 @@ jobs: steps: - name: Checkout uses: actions/checkout@v5 + with: + persist-credentials: false - name: Read and check the version id: version @@ -49,6 +54,8 @@ jobs: steps: - name: Checkout uses: actions/checkout@v5 + with: + persist-credentials: false - name: Setup Node.js uses: actions/setup-node@v5 @@ -82,7 +89,21 @@ jobs: runs-on: ubuntu-24.04 needs: [version, build] if: github.ref_type == 'tag' + permissions: + contents: write steps: + # The whole history and the tags: the notes list the commits since the previous tag. + - name: Checkout + uses: actions/checkout@v5 + with: + persist-credentials: false + fetch-depth: 0 + + - name: Release notes + run: | + sh scripts/release-notes.sh "${GITHUB_REF_NAME}" "${GITHUB_REPOSITORY}" > notes.md + cat notes.md + - name: Download packages uses: actions/download-artifact@v4 with: @@ -102,12 +123,4 @@ jobs: name: Dawnline ${{ github.ref_name }} tag_name: ${{ github.ref_name }} files: release/* - generate_release_notes: true - body: | - Install or upgrade on the router (OpenWrt 24.10 with opkg, or 25.12 with apk): - - ```sh - sh -c "$(wget -qO- https://raw.githubusercontent.com/${{ github.repository }}/main/install.sh)" - ``` - - Or upgrade from LuCI → Network → Dawnline → Updates. + body_path: notes.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b15e48e..9e64e30 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,8 @@ jobs: steps: - name: Checkout uses: actions/checkout@v5 + with: + persist-credentials: false - name: Setup Node.js uses: actions/setup-node@v5 @@ -78,12 +80,15 @@ jobs: steps: - name: Checkout uses: actions/checkout@v5 + with: + persist-credentials: false - name: ShellCheck run: | shellcheck --version shellcheck -S warning \ install.sh \ + uninstall.sh \ package/luci-app-dawnline/root/etc/init.d/dawnline \ package/luci-app-dawnline/root/etc/uci-defaults/90_dawnline \ package/luci-app-dawnline/root/etc/hotplug.d/iface/95-dawnline \ @@ -96,6 +101,8 @@ jobs: steps: - name: Checkout uses: actions/checkout@v5 + with: + persist-credentials: false - name: Use before definition run: python3 scripts/lint-ucode.py diff --git a/README.md b/README.md index aa7dee4..0212983 100644 --- a/README.md +++ b/README.md @@ -36,9 +36,11 @@ limits, live traffic and a LuCI admin that follows a modern design. accounts, no sessions, and a new link locks the old one out at once. People add, rename and remove their devices and get each one as a QR code, "Open in AmneziaVPN" (`vpn://`), a key or a `.conf` file. They cannot change - access or limits. Links work on 443 with a Let's Encrypt certificate (via - ACME), several addresses at once (a Cloudflare-proxied name, a plain IP), the - same link at home, and wrong links can redirect to your website. + access or limits. Links work on the portal's own port with a Let's Encrypt + certificate (via ACME), several addresses at once (a Cloudflare-proxied name, + a plain IP), the same link at home, and wrong links can redirect to your + website. Behind Cloudflare, pick a port it proxies (2053, 2083, 2087, 2096 or + 8443). - **Access per person**, enforced in an `inet dawnline` nftables table on the tunnel interface: home network only, internet only, or both, and optionally only some home networks or home services (picked from the devices the router @@ -88,17 +90,45 @@ On the router: sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)" ``` -The installer checks the firmware, installs AmneziaWG for it if needed, then -downloads the Dawnline package for your package manager from the latest -release, checks it against `sha256sums.txt` and installs it with its -dependencies. Then open **LuCI → Network → Dawnline** and run the setup wizard. +The installer checks the firmware, the clock, free space and DNS, lets you pick +a release (the latest is the default), shows the plan and asks before it +changes anything. It downloads the Dawnline package for your package manager, +checks it against `sha256sums.txt`, installs AmneziaWG built for your firmware +if it is missing, then installs Dawnline with its dependencies and checks that +LuCI can reach it. Then open **LuCI → Network → Dawnline** and run the setup +wizard. -Options: +Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}` +and the service state to `/etc/dawnline/installer-backups/` (the newest three +are kept); if a step fails, it puts them back. Packages are not rolled back: to +return to an older release, run the installer with `--tag`. Everything it does +is logged to `/tmp/dawnline-install.log`. + +With options, download it first: ```sh -sh install.sh 0.1.0 # a given release -DAWNLINE_AWG=grey sh install.sh # AmneziaWG from 2Grey (default: Slava-Shchipunov, then 2Grey) -DAWNLINE_AWG=skip sh install.sh # never install AmneziaWG +wget -O /tmp/dawnline-install.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh +sh /tmp/dawnline-install.sh --dry-run # check everything, change nothing +sh /tmp/dawnline-install.sh -y --tag 0.3.1 # a given release, no questions +sh /tmp/dawnline-install.sh --awg grey # AmneziaWG from 2Grey +``` + +| Option | | +|---|---| +| `-y`, `--yes` | No questions: the latest release (or `--tag`) and the recommended choices | +| `-n`, `--dry-run` | Check the system, resolve, download and verify the release; change nothing | +| `-v`, `--verbose` / `-q`, `--quiet` | More detail / only warnings and errors | +| `--tag X.Y.Z` | A given release (`sh install.sh 0.3.1` works too) | +| `--awg auto\|slava\|grey\|skip` | Where AmneziaWG comes from when it is missing: [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt), then [2Grey](https://github.com/2Grey/awg-openwrt) (`auto`, the default), only one of them, or not at all (install it later from **Dawnline → Updates**). `DAWNLINE_AWG` does the same | +| `--no-awg` | Same as `--awg skip` | + +When GitHub is slow or blocked, the installer retries downloads through +`ghfast.top` and `gh-proxy.com` on its own. To fetch the installer itself +through a mirror: + +```sh +sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.sh)" +sh -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)" ``` By hand, from a [release](https://github.com/tickcount/luci-app-dawnline/releases): @@ -111,8 +141,32 @@ apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # Open **Upgrade** from **Dawnline → Updates**, or run the installer again. Settings, keys and history are kept, and a backup is made first. -**Remove**: **Settings → Remove Dawnline from this router** (keeps a backup), -then `opkg remove luci-app-dawnline` or `apk del luci-app-dawnline`. +**Remove** on the router: + +```sh +sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)" +``` + +It backs up the configuration to `/etc/dawnline/backups`, runs Dawnline's own +removal (the same as **Settings → Remove Dawnline from this router**), removes +the package and cleans up what is left. AmneziaWG stays installed, since other +tunnels may use it. After installing Dawnline again, restore the backup in +**Settings → Backups**. With options, download it first: + +```sh +wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh +sh /tmp/dawnline-uninstall.sh --dry-run +``` + +| Option | | +|---|---| +| `-y`, `--yes` | Do not ask for confirmation | +| `-p`, `--purge` | Also delete the configuration, keys, history and every backup (`/etc/config/dawnline`, `/etc/dawnline`); no backup is made | +| `--remove-awg` | Also remove AmneziaWG, unless another interface still uses it (`--keep-awg`, the default, keeps it) | +| `-n`, `--dry-run` | Show what would be removed; change nothing | + +By hand: **Settings → Remove Dawnline from this router** (keeps a backup), then +`opkg remove luci-app-dawnline` or `apk del luci-app-dawnline`. ## What Dawnline changes on the router @@ -133,10 +187,11 @@ are kept in `/var/run/dawnline` and flushed to flash at most hourly. ``` package/luci-app-dawnline/ - root/usr/share/ucode/dawnline/ ucode library (model, apply, live, ops, view, loop) + root/usr/share/ucode/dawnline/ ucode library: model (core), AmneziaWG (awg), apply, live, + ops, view, loop, portal root/usr/share/rpcd/ucode/ luci.dawnline RPC object root/usr/libexec/dawnline/ agent (usage, limits, presence) and updater - root/usr/share/dawnline/portal/ portal CGI and its (minified) assets + root/usr/share/dawnline/portal/ portal CGI wrapper and its (minified) assets root/usr/bin/dawnline command line (`dawnline help`) htdocs/ LuCI views and the generated module dawnline/app.js web/ TypeScript sources of the admin UI and the portal diff --git a/install.sh b/install.sh index 46ffa38..cd704f7 100755 --- a/install.sh +++ b/install.sh @@ -4,178 +4,1352 @@ # Dawnline installer for OpenWrt 24.10+ (opkg) and 25.12+ (apk). # # sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)" -# sh install.sh [version] a given release instead of the latest # -# Environment: -# DAWNLINE_REPO=owner/name GitHub repository with the releases -# DAWNLINE_AWG=auto|slava|grey|skip where AmneziaWG comes from if it is missing -# (auto: Slava-Shchipunov, then 2Grey) +# wget -O /tmp/dawnline-install.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh +# sh /tmp/dawnline-install.sh [options] [version] # # Installs AmneziaWG built for this firmware when it is missing, then the # Dawnline package with its dependencies from the OpenWrt feeds. Settings and -# keys survive reinstalls and upgrades. - -set -eu +# keys survive reinstalls and upgrades. A recovery snapshot of the configs it +# may touch is taken first and restored if anything fails. `--help` lists the +# options. +INSTALLER_VERSION="1.0.0" REPO="${DAWNLINE_REPO:-tickcount/luci-app-dawnline}" +PKG_NAME="luci-app-dawnline" +AWG_PKGS="kmod-amneziawg amneziawg-tools luci-proto-amneziawg" + +CONNECT_TIMEOUT=15 +METADATA_TIMEOUT=60 +DOWNLOAD_TIMEOUT=300 +APK_LOCK_WAIT=120 +UBUS_WAIT=15 +REQUIRED_OVERLAY_KB=2048 +TMP_HEADROOM_KB=4096 + +LOG_FILE="/tmp/dawnline-install.log" +LOCK_DIR="/tmp/dawnline.install.lock.d" +DATA_DIR="/etc/dawnline" +SNAPSHOT_ROOT="$DATA_DIR/installer-backups" +# Everything Dawnline (or its postinst) may change: restored on failure. +SNAPSHOT_CONFIGS="dawnline network firewall dhcp uhttpd" +MIRRORS="https://ghfast.top/ https://gh-proxy.com/" +UPDATE_JOB="/var/run/dawnline/update-job.json" +UPDATE_LOCK="/var/run/dawnline/update.lock" + +ASSUME_YES=0 +DRY_RUN=0 +VERBOSE=0 +QUIET=0 +TAG="" AWG_SOURCE="${DAWNLINE_AWG:-auto}" -VERSION="${1:-}" -TMP="/tmp/dawnline-install" -REQUIRED_KB=2048 +LOG_READY=0 +TMP_DIR="" +LOCK_HELD=0 +FETCHER="" +PKG_MANAGER="" PKG_IS_APK=0 -command -v apk >/dev/null 2>&1 && PKG_IS_APK=1 -EXT=ipk -[ "$PKG_IS_APK" -eq 1 ] && EXT=apk +EXT="ipk" +OWRT_RELEASE="" +OWRT_ARCH="" +OWRT_TARGET="" -msg() { printf '\033[32;1m%s\033[0m\n' "$*"; } -note() { printf '%s\n' "$*"; } -die() { - printf '\033[31;1m%s\033[0m\n' "$*" >&2 +VERSION="" +ASSET="" +ASSET_BASE="" +DOWNLOAD_BYTES=0 +ASSET_FILE="" + +WAS_INSTALLED=0 +WAS_VERSION="" +WAS_ENABLED=0 +WAS_RUNNING=0 +MODE="install" + +AWG_ACTION="keep" +AWG_CANDIDATES="" +AWG_REPO="" +AWG_FILES="" + +SNAPSHOT_DIR="" +TX_ACTIVE=0 +TX_COMMITTED=0 +_STREAM_PID="" +_STREAM_STOP="" +NO_STREAM=0 + +ESC="$(printf '\033')" +if [ -t 1 ] 2>/dev/null && [ "${TERM:-dumb}" != "dumb" ]; then + C_RESET="${ESC}[0m" + C_BOLD="${ESC}[1m" + C_RED="${ESC}[31;1m" + C_GREEN="${ESC}[32;1m" + C_YELLOW="${ESC}[33;1m" + C_CYAN="${ESC}[36;1m" +else + C_RESET="" + C_BOLD="" + C_RED="" + C_GREEN="" + C_YELLOW="" + C_CYAN="" +fi + +START_TS="$(date +%s 2>/dev/null || echo 0)" + +# ---------- output ---------- + +ts_elapsed() { + _now="$(date +%s 2>/dev/null || echo "$START_TS")" + _el=$((_now - START_TS)) + [ "$_el" -ge 0 ] 2>/dev/null || _el=0 + printf '+%02d:%02d' $((_el / 60)) $((_el % 60)) +} + +log_line() { + [ "$LOG_READY" -eq 1 ] || return 0 + printf '[%s %s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S' 2>/dev/null)" "$(ts_elapsed)" "$1" >>"$LOG_FILE" 2>/dev/null || true +} + +msg() { + log_line "INFO $1" + [ "$QUIET" -eq 1 ] || printf ' [%s] %s%s%s\n' "$(ts_elapsed)" "$C_CYAN" "$1" "$C_RESET" +} + +ok() { + log_line "OK $1" + [ "$QUIET" -eq 1 ] || printf ' [%s] %s%s✓%s %s\n' "$(ts_elapsed)" "$C_GREEN" "$C_BOLD" "$C_RESET" "$1" +} + +warn() { + log_line "WARN $1" + printf ' [%s] %s%s⚠%s %s\n' "$(ts_elapsed)" "$C_YELLOW" "$C_BOLD" "$C_RESET" "$1" >&2 +} + +err() { + log_line "ERROR $1" + printf ' [%s] %s%s✗%s %s\n' "$(ts_elapsed)" "$C_RED" "$C_BOLD" "$C_RESET" "$1" >&2 +} + +debug() { + log_line "DEBUG $1" + [ "$VERBOSE" -eq 1 ] || return 0 + printf ' [%s] [debug] %s\n' "$(ts_elapsed)" "$1" >&2 +} + +dry() { + msg "[dry-run] would $1" +} + +fail() { + err "$1" + [ "$LOG_READY" -eq 1 ] && err "Installer log: $LOG_FILE" exit 1 } -cleanup() { rm -rf "$TMP"; } -trap cleanup EXIT INT TERM +prompt() { + printf ' [%s] %s' "$(ts_elapsed)" "$1" +} -fetch() { - # fetch URL FILE: a few attempts, a non-empty file or failure - attempt=1 - while [ "$attempt" -le 3 ]; do - if wget -q -T 30 -O "$2" "$1" 2>/dev/null && [ -s "$2" ]; then +banner() { + [ "$QUIET" -eq 1 ] && return 0 + printf '\n %s%sDawnline Installer%s v%s\n' "$C_CYAN" "$C_BOLD" "$C_RESET" "$INSTALLER_VERSION" + printf ' AmneziaWG access server for OpenWrt: install, upgrade, repair\n\n' +} + +usage() { + cat </dev/null 2>&1; } + +acquire_lock() { + if mkdir "$LOCK_DIR" 2>/dev/null; then + echo "$$" >"$LOCK_DIR/pid" + LOCK_HELD=1 + return 0 + fi + _old="$(cat "$LOCK_DIR/pid" 2>/dev/null)" + if [ -n "$_old" ] && kill -0 "$_old" 2>/dev/null; then + err "Another Dawnline installer or uninstaller is running (pid $_old)" + return 1 + fi + warn "Removing a stale installer lock${_old:+ (pid $_old)}" + rm -rf "$LOCK_DIR" 2>/dev/null + mkdir "$LOCK_DIR" 2>/dev/null || { + err "Cannot create the lock $LOCK_DIR" + return 1 + } + echo "$$" >"$LOCK_DIR/pid" + LOCK_HELD=1 +} + +release_lock() { + [ "$LOCK_HELD" -eq 1 ] || return 0 + [ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$$" ] && rm -rf "$LOCK_DIR" 2>/dev/null + LOCK_HELD=0 +} + +init_tmp_dir() { + TMP_DIR="$(mktemp -d /tmp/dawnline-installer.XXXXXX 2>/dev/null)" + if [ -z "$TMP_DIR" ]; then + TMP_DIR="/tmp/dawnline-installer.$$" + mkdir -p "$TMP_DIR" || return 1 + fi + chmod 700 "$TMP_DIR" 2>/dev/null + return 0 +} + +# Command output streamed to the console as it arrives ("[tag] line"), with a +# heartbeat while a command is silent; the log gets the whole output after. +_NL=' +' + +_stream_poll() { + _ssize="$(wc -c <"$_sf" 2>/dev/null | tr -d " ")" + case "$_ssize" in '' | *[!0-9]*) _ssize=0 ;; esac + [ "$_ssize" -gt "$_spos" ] || return 0 + _sbuf="$_sbuf$(tail -c +$((_spos + 1)) "$_sf" 2>/dev/null)$_NL" + # tail through $(…) drops the trailing newline: put it back, then hold + # back a last line that is still being written. + _spos="$_ssize" + case "$(tail -c 1 "$_sf" 2>/dev/null)" in + '') ;; + *) _sbuf="${_sbuf%"$_NL"}" ;; + esac + while :; do + case "$_sbuf" in + *"$_NL"*) ;; + *) break ;; + esac + _sline="${_sbuf%%"$_NL"*}" + _sbuf="${_sbuf#*"$_NL"}" + [ -n "$_sline" ] && printf ' [%s] [%s] %s\n' "$(ts_elapsed)" "$_stag" "$_sline" + done + return 0 +} + +_stream_loop() { + _sf="$1" + _stag="$2" + _sstop="$3" + _sparent="$4" + _spos=0 + _sbuf="" + _sidle=0 + while :; do + [ -e "$_sstop" ] && break + kill -0 "$_sparent" 2>/dev/null || break + _spre="$_spos" + _stream_poll + if [ "$_spos" -eq "$_spre" ]; then + _sidle=$((_sidle + 1)) + [ $((_sidle % 10)) -eq 0 ] && printf ' [%s] [%s] … still running (%ss)\n' "$(ts_elapsed)" "$_stag" "$_sidle" + else + _sidle=0 + fi + sleep 1 + done + _stream_poll + [ -n "$_sbuf" ] && printf ' [%s] [%s] %s\n' "$(ts_elapsed)" "$_stag" "$_sbuf" + return 0 +} + +stream_start() { + [ "$QUIET" -eq 1 ] || [ "$NO_STREAM" -eq 1 ] && return 0 + _STREAM_STOP="$1.stop" + rm -f "$_STREAM_STOP" + _stream_loop "$1" "$2" "$_STREAM_STOP" "$$" & + _STREAM_PID=$! +} + +stream_stop() { + [ -n "$_STREAM_PID" ] || return 0 + : >"$_STREAM_STOP" 2>/dev/null + wait "$_STREAM_PID" 2>/dev/null + _STREAM_PID="" + rm -f "$_STREAM_STOP" 2>/dev/null + return 0 +} + +# run_logged TAG COMMAND...: runs in the foreground (Ctrl-C reaches it), +# streams its output and keeps a full copy in the log. +run_logged() { + _tag="$1" + shift + _out="$TMP_DIR/cmd.$$.out" + log_line "EXEC [$_tag] $*" + : >"$_out" + stream_start "$_out" "$_tag" + "$@" >"$_out" 2>&1 &2 + fi + rm -f "$_out" + return "$_rc" +} + +# ---------- environment ---------- + +detect_fetcher() { + for _f in curl wget uclient-fetch; do + if command_exists "$_f"; then + FETCHER="$_f" + debug "Downloads with $FETCHER" return 0 fi - rm -f "$2" - attempt=$((attempt + 1)) + done + err "curl, wget or uclient-fetch is required" + return 1 +} + +detect_package_manager() { + if command_exists apk; then + PKG_MANAGER="apk" + PKG_IS_APK=1 + EXT="apk" + elif command_exists opkg; then + PKG_MANAGER="opkg" + PKG_IS_APK=0 + EXT="ipk" + else + err "Neither apk nor opkg is available" + return 1 + fi + debug "Package manager: $PKG_MANAGER (.$EXT)" +} + +check_tools() { + _missing="" + for _t in jsonfilter sha256sum tar ubus uci; do + command_exists "$_t" || _missing="$_missing $_t" + done + [ -z "$_missing" ] && return 0 + err "Missing tools:$_missing" + return 1 +} + +# ---------- downloads ---------- + +# fetch_once URL FILE [SECONDS] +fetch_once() { + _fu="$1" + _fd="$2" + _ft="${3:-$DOWNLOAD_TIMEOUT}" + rm -f "$_fd" + case "$FETCHER" in + curl) + run_logged download curl -fsSL --connect-timeout "$CONNECT_TIMEOUT" --max-time "$_ft" \ + --speed-limit 1024 --speed-time 30 -o "$_fd" "$_fu" + ;; + *) run_logged download "$FETCHER" -q -T "$CONNECT_TIMEOUT" -O "$_fd" "$_fu" ;; + esac + _frc=$? + [ "$_frc" -eq 0 ] && [ -s "$_fd" ] && return 0 + rm -f "$_fd" + return 1 +} + +host_of() { + printf '%s' "$1" | sed 's#^[a-z]*://\([^/]*\).*#\1#' +} + +# Release metadata from the GitHub API (log only, no console noise for a +# 404). Only ever asked directly: the checksums it carries are what makes a +# file from a mirror trustworthy. +fetch_meta() { + debug "GET $1" + NO_STREAM=1 + fetch_once "$1" "$2" "$METADATA_TIMEOUT" || { sleep 2 + fetch_once "$1" "$2" "$METADATA_TIMEOUT" + } + _frc=$? + NO_STREAM=0 + return "$_frc" +} + +# The sha256 GitHub publishes for a release file, from release JSON (empty if unknown). +asset_digest() { + [ -s "$1" ] || return 0 + jsonfilter -i "$1" -e "@.assets[@.name='$2'].digest" 2>/dev/null | head -n 1 | sed -n 's/^sha256:\([0-9a-f]\{64\}\)$/\1/p' +} + +# download URL FILE LABEL [SHA256]: direct, then (only when the sha256 is +# known) two mirrors, then direct again. A file whose sha256 doesn't match is +# thrown away and the next source is tried; without a sha256 only GitHub +# itself is used. +download() { + _du="$1" + _dd="$2" + _dl="$3" + _dw="${4:-}" + set -- "$_du" + if [ -n "$_dw" ]; then + for _m in $MIRRORS; do set -- "$@" "$_m$_du"; done + fi + set -- "$@" "$_du" + _n=0 + _total=$# + for _try in "$@"; do + _n=$((_n + 1)) + if [ "$_n" -eq 1 ]; then + msg "Downloading $_dl" + else + sleep 2 + msg "Downloading $_dl via $(host_of "$_try") (attempt $_n/$_total)" + fi + if fetch_once "$_try" "$_dd"; then + if [ -n "$_dw" ] && [ "$(sha256sum "$_dd" 2>/dev/null | awk '{ print $1 }')" != "$_dw" ]; then + warn "$(host_of "$_try") sent a file that doesn't match GitHub's sha256: discarded" + rm -f "$_dd" + continue + fi + _kb=$((($(wc -c <"$_dd") + 1023) / 1024)) + debug "$_dl: $_kb KB from $(host_of "$_try")" + return 0 + fi done return 1 } -pkg_update() { - if [ "$PKG_IS_APK" -eq 1 ]; then apk update >/dev/null; else opkg update >/dev/null; fi +verify_archive() { + _af="$1" + _an="$(basename "$_af")" + _sz="$(wc -c <"$_af" 2>/dev/null | tr -d " ")" + case "$_sz" in "" | *[!0-9]*) _sz=0 ;; esac + [ "$_sz" -gt 1024 ] || { + err "$_an is suspiciously small ($_sz bytes)" + return 1 + } + _magic="$(head -c 4 "$_af" 2>/dev/null)" + case "$_magic" in + '!/dev/null 2>&1 && return 0 + err "$_an is not a valid .$EXT package" + return 1 } -pkg_installed() { +free_kb() { + df -Pk "$1" 2>/dev/null | awk 'NR == 2 { print $4 }' +} + +# ---------- packages ---------- + +pkg_is_installed() { if [ "$PKG_IS_APK" -eq 1 ]; then apk info -e "$1" >/dev/null 2>&1 else - opkg list-installed "$1" 2>/dev/null | grep -q "^$1 " + opkg status "$1" 2>/dev/null | grep -q '^Status: .* installed' fi } +# Installed version without the -rN release suffix. +pkg_version() { + if [ "$PKG_IS_APK" -eq 1 ]; then + _pv="$(apk list --installed "$1" 2>/dev/null | sed -n "s/^$1-\([^ ]*\) .*/\1/p" | head -n 1)" + else + _pv="$(opkg status "$1" 2>/dev/null | sed -n 's/^Version: *//p' | head -n 1)" + fi + printf '%s' "${_pv%-r*}" +} + +# Succeeds when version $1 >= $2 (X.Y.Z, numeric per part). +version_ge() { + _va="${1#v}" + _vb="${2#v}" + _i=0 + while [ "$_i" -lt 3 ]; do + _pa="${_va%%.*}" + _pb="${_vb%%.*}" + [ "$_pa" = "$_va" ] && _va="" || _va="${_va#*.}" + [ "$_pb" = "$_vb" ] && _vb="" || _vb="${_vb#*.}" + case "$_pa" in '' | *[!0-9]*) _pa=0 ;; esac + case "$_pb" in '' | *[!0-9]*) _pb=0 ;; esac + [ "$_pa" -gt "$_pb" ] && return 0 + [ "$_pa" -lt "$_pb" ] && return 1 + _i=$((_i + 1)) + done + return 0 +} + +wait_opkg_lock() { + [ "$PKG_IS_APK" -eq 0 ] || return 0 + _w=0 + while pidof opkg >/dev/null 2>&1; do + [ "$_w" -eq 0 ] && msg "Waiting for another opkg to finish" + _w=$((_w + 1)) + [ "$_w" -ge 60 ] && { + warn "opkg is still busy after 60s" + return 0 + } + sleep 1 + done + return 0 +} + +apk_cmd() { + _tag="$1" + shift + if apk --help 2>&1 | grep -q -- '--wait'; then + run_logged "$_tag" apk --wait "$APK_LOCK_WAIT" "$@" + else + run_logged "$_tag" apk "$@" + fi +} + +pkg_refresh() { + if [ "$DRY_RUN" -eq 1 ]; then + dry "refresh the $PKG_MANAGER package lists" + return 0 + fi + msg "Refreshing $PKG_MANAGER package lists" + if [ "$PKG_IS_APK" -eq 1 ]; then + apk_cmd apk-update update + else + wait_opkg_lock + run_logged opkg-update opkg update + fi +} + +# pkg_install_files TAG FORCE FILE...: FORCE=1 reinstalls the same version or +# goes back to an older one (opkg; apk takes a given file as it is). pkg_install_files() { + _tag="$1" + _force="$2" + shift 2 if [ "$PKG_IS_APK" -eq 1 ]; then # Packages from GitHub releases are not signed with the feed key. - apk add --allow-untrusted "$@" + apk_cmd "$_tag" add --allow-untrusted "$@" else - opkg install "$@" + wait_opkg_lock + if [ "$_force" -eq 1 ]; then + run_logged "$_tag" opkg install --force-reinstall --force-downgrade "$@" + else + run_logged "$_tag" opkg install "$@" + fi + fi +} + +# ---------- checks ---------- + +sync_time() { + _year="$(date +%Y 2>/dev/null)" + case "$_year" in '' | *[!0-9]*) _year=0 ;; esac + [ "$_year" -ge 2024 ] && return 0 + warn "The system clock is wrong ($(date 2>/dev/null)); HTTPS needs the right time" + if [ "$DRY_RUN" -eq 1 ]; then + dry "set the clock with ntpd" + return 0 + fi + if command_exists ntpd; then + msg "Setting the clock with ntpd (up to 20s)" + # ntpd -q waits for an answer for as long as it takes: bound it. + ntpd -n -q -p 216.239.35.0 -p 162.159.200.1 -p 216.239.35.4 >>"$LOG_FILE" 2>&1 & + _np=$! + _i=0 + while kill -0 "$_np" 2>/dev/null && [ "$_i" -lt 20 ]; do + sleep 1 + _i=$((_i + 1)) + done + kill "$_np" 2>/dev/null + wait "$_np" 2>/dev/null + fi + _year="$(date +%Y 2>/dev/null)" + case "$_year" in '' | *[!0-9]*) _year=0 ;; esac + if [ "$_year" -ge 2024 ]; then + ok "Clock set: $(date 2>/dev/null)" + else + warn "The clock is still wrong: downloads may fail (set it in System → System → Sync with NTP server)" fi } check_system() { - [ "$(id -u)" = 0 ] || die "Run this as root." - [ -f /etc/openwrt_release ] || die "This is not OpenWrt." + msg "Checking system requirements" + [ -r /etc/openwrt_release ] || { + err "This installer supports OpenWrt only" + return 1 + } # shellcheck disable=SC1091 . /etc/openwrt_release - RELEASE="${DISTRIB_RELEASE:-}" - ARCH="${DISTRIB_ARCH:-}" - TARGET="${DISTRIB_TARGET:-}" - msg "OpenWrt $RELEASE · $TARGET · $ARCH" - - major="${RELEASE%%.*}" - case "$major" in - '' | *[!0-9]*) note "Snapshot or unknown release: continuing." ;; - *) [ "$major" -ge 24 ] || die "Dawnline needs OpenWrt 24.10 or newer." ;; + OWRT_RELEASE="${DISTRIB_RELEASE:-}" + OWRT_ARCH="${DISTRIB_ARCH:-}" + OWRT_TARGET="${DISTRIB_TARGET:-}" + _major="${OWRT_RELEASE%%.*}" + case "$_major" in + '' | *[!0-9]*) + warn "OpenWrt ${OWRT_RELEASE:-?} is a snapshot or unknown release: continuing" + ;; + *) + [ "$_major" -ge 24 ] || { + err "Dawnline needs OpenWrt 24.10 or newer (this is $OWRT_RELEASE)" + return 1 + } + ;; esac + ok "OpenWrt $OWRT_RELEASE · $OWRT_TARGET · $OWRT_ARCH · $PKG_MANAGER" - free_kb="$(df -k /overlay 2>/dev/null | awk 'NR==2 {print $4}')" - if [ -n "$free_kb" ] && [ "$free_kb" -lt "$REQUIRED_KB" ]; then - die "Not enough flash: $((free_kb / 1024)) MB free, $((REQUIRED_KB / 1024)) MB needed." + _overlay="$(free_kb /overlay)" + [ -n "$_overlay" ] || _overlay="$(free_kb /)" + if [ -n "$_overlay" ]; then + [ "$_overlay" -ge "$REQUIRED_OVERLAY_KB" ] || { + err "Not enough flash: $((_overlay / 1024)) MiB free, $((REQUIRED_OVERLAY_KB / 1024)) MiB needed" + return 1 + } + debug "Flash: $((_overlay / 1024)) MiB free" fi - nslookup github.com >/dev/null 2>&1 || die "DNS does not work: github.com does not resolve." + # The in-app updater (Dawnline → Components) uses the same package manager. + # The updater holds this lock for a whole job; holding it here keeps an + # automatic update from starting while the installer works. + if command_exists flock && mkdir -p /var/run/dawnline 2>/dev/null; then + exec 8>>"$UPDATE_LOCK" + flock -n 8 || { + err "An update started from Dawnline → Components is running: wait for it to finish" + return 1 + } + elif [ -r "$UPDATE_JOB" ]; then + _js="$(jsonfilter -i "$UPDATE_JOB" -e '@.state' 2>/dev/null)" + _jp="$(jsonfilter -i "$UPDATE_JOB" -e '@.pid' 2>/dev/null)" + if [ "$_js" = running ] && [ -n "$_jp" ] && kill -0 "$_jp" 2>/dev/null; then + err "An update started from Dawnline → Components is running (pid $_jp): wait for it to finish" + return 1 + fi + fi +} + +check_dns() { + command_exists nslookup || return 0 + nslookup github.com >/dev/null 2>&1 && return 0 + err "github.com does not resolve: DNS on the router does not work" + err "Check the WAN link, or point dnsmasq at a reachable resolver" + err "(Network → DHCP and DNS → Forwards, e.g. 1.1.1.1), then run the installer again." + return 1 +} + +record_state() { + pkg_is_installed "$PKG_NAME" && WAS_INSTALLED=1 + [ "$WAS_INSTALLED" -eq 1 ] || return 0 + WAS_VERSION="$(pkg_version "$PKG_NAME")" + ls /etc/rc.d/S*dawnline >/dev/null 2>&1 && WAS_ENABLED=1 + _r="$(ubus call service list '{"name":"dawnline"}' 2>/dev/null | jsonfilter -q -e '@.dawnline.instances.agent.running' 2>/dev/null)" + [ "$_r" = true ] && WAS_RUNNING=1 + debug "Installed: $WAS_VERSION, enabled=$WAS_ENABLED, running=$WAS_RUNNING" +} + +# ---------- release ---------- + +is_interactive() { + [ "$ASSUME_YES" -eq 0 ] && [ -t 0 ] +} + +valid_version() { + printf '%s\n' "$1" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$' +} + +select_release() { + [ -z "$TAG" ] || return 0 + is_interactive || return 0 + msg "Fetching the release list" + _rl="$TMP_DIR/releases.json" + fetch_meta "https://api.github.com/repos/$REPO/releases?per_page=30" "$_rl" || { + warn "The release list is not available; using the latest release" + return 0 + } + _tags="$(jsonfilter -i "$_rl" -e '@[@.draft=false && @.prerelease=false].tag_name' 2>/dev/null)" + [ -n "$_tags" ] || _tags="$(jsonfilter -i "$_rl" -e '@[*].tag_name' 2>/dev/null)" + _tags="$(printf '%s\n' "$_tags" | sed 's/^v//' | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | + sort -t. -k1,1nr -k2,2nr -k3,3nr | uniq | head -n 10)" + _count=0 + for _t in $_tags; do _count=$((_count + 1)); done + [ "$_count" -gt 1 ] || return 0 + [ "$QUIET" -eq 1 ] || printf '\n' + printf ' Select the Dawnline release:\n' + _i=1 + for _t in $_tags; do + _note="" + [ "$_i" -eq 1 ] && _note=" (recommended)" + [ "$_t" = "$WAS_VERSION" ] && _note="$_note (installed)" + printf ' %2d) %s%s\n' "$_i" "$_t" "$_note" + _i=$((_i + 1)) + done + printf '\n' + prompt "Choice [1]: " + read -r _answer || _answer="" + case "$_answer" in + '') _answer=1 ;; + *[!0-9]*) + warn "Unknown choice; using the latest release" + return 0 + ;; + esac + if [ "$_answer" -lt 1 ] || [ "$_answer" -gt "$_count" ]; then + warn "Choice out of range; using the latest release" + return 0 + fi + _i=1 + for _t in $_tags; do + [ "$_i" -eq "$_answer" ] && TAG="$_t" + _i=$((_i + 1)) + done + log_line "INFO Selected release: $TAG" +} + +latest_via_redirect() { + # Without the API (rate limit): github.com//releases/latest redirects + # to …/tag/vX.Y.Z. Only curl reports where a redirect ended. + [ "$FETCHER" = curl ] || return 1 + _u="$(curl -fsSIL -o /dev/null -w '%{url_effective}' --connect-timeout "$CONNECT_TIMEOUT" \ + --max-time "$METADATA_TIMEOUT" "https://github.com/$REPO/releases/latest" 2>/dev/null)" + _v="${_u##*/}" + _v="${_v#v}" + valid_version "$_v" || return 1 + printf '%s' "$_v" +} + +resolve_release() { + _rj="$TMP_DIR/release.json" + if [ -n "$TAG" ]; then + msg "Looking up release $TAG" + if fetch_meta "https://api.github.com/repos/$REPO/releases/tags/v$TAG" "$_rj"; then + _t="$(jsonfilter -i "$_rj" -e '@.tag_name' 2>/dev/null)" + [ "${_t#v}" = "$TAG" ] || { + err "GitHub returned release ${_t:-?} for $TAG" + return 1 + } + else + warn "GitHub API did not answer (rate limit?); trying the release files directly" + rm -f "$_rj" + fi + VERSION="$TAG" + else + msg "Looking up the latest release" + if fetch_meta "https://api.github.com/repos/$REPO/releases/latest" "$_rj"; then + VERSION="$(jsonfilter -i "$_rj" -e '@.tag_name' 2>/dev/null)" + VERSION="${VERSION#v}" + else + rm -f "$_rj" + VERSION="$(latest_via_redirect)" || { + err "Cannot reach the GitHub API (or its rate limit is hit: try again in a few minutes," + err "or name the release: --tag X.Y.Z)" + return 1 + } + fi + valid_version "$VERSION" || { + err "Cannot determine the latest Dawnline release (got '${VERSION:-nothing}')" + return 1 + } + fi + + ASSET="$PKG_NAME-$VERSION.$EXT" + ASSET_BASE="https://github.com/$REPO/releases/download/v$VERSION" + if [ -s "$_rj" ]; then + _size="$(jsonfilter -i "$_rj" -e "@.assets[@.name='$ASSET'].size" 2>/dev/null | head -n 1)" + [ -n "$_size" ] || { + err "Release $VERSION has no $ASSET" + return 1 + } + [ -n "$(jsonfilter -i "$_rj" -e "@.assets[@.name='sha256sums.txt'].name" 2>/dev/null)" ] || { + err "Release $VERSION has no sha256sums.txt" + return 1 + } + DOWNLOAD_BYTES=$((DOWNLOAD_BYTES + _size)) + ok "Release $VERSION ($ASSET)" + else + DOWNLOAD_BYTES=$((DOWNLOAD_BYTES + 1048576)) + msg "Release $VERSION ($ASSET, not confirmed by the API yet)" + fi + + if [ "$WAS_INSTALLED" -eq 0 ]; then + MODE="install" + elif [ "$WAS_VERSION" = "$VERSION" ]; then + MODE="reinstall" + elif version_ge "$VERSION" "$WAS_VERSION"; then + MODE="upgrade" + else + MODE="downgrade" + fi } # AmneziaWG packages are built per firmware version and target by the # awg-openwrt projects: _v___. -install_awg() { - if pkg_installed kmod-amneziawg && pkg_installed amneziawg-tools; then - note "AmneziaWG is already installed." +awg_postfix() { + printf '_v%s_%s_%s.%s' "$OWRT_RELEASE" "$OWRT_ARCH" "$(printf '%s' "$OWRT_TARGET" | tr '/' '_')" "$EXT" +} + +awg_repo() { + case "$1" in + slava) printf 'Slava-Shchipunov/awg-openwrt' ;; + grey) printf '2Grey/awg-openwrt' ;; + esac +} + +resolve_awg() { + if pkg_is_installed kmod-amneziawg && pkg_is_installed amneziawg-tools; then + AWG_ACTION="keep" + ok "AmneziaWG is installed ($(pkg_version amneziawg-tools))" return 0 fi - [ "$AWG_SOURCE" = skip ] && die "AmneziaWG is missing and DAWNLINE_AWG=skip." - + if [ "$AWG_SOURCE" = skip ]; then + AWG_ACTION="skip" + warn "AmneziaWG is not installed and --awg skip is set" + return 0 + fi + AWG_ACTION="install" case "$AWG_SOURCE" in - slava) sources="Slava-Shchipunov/awg-openwrt" ;; - grey) sources="2Grey/awg-openwrt" ;; - *) sources="Slava-Shchipunov/awg-openwrt 2Grey/awg-openwrt" ;; + slava) _srcs="slava" ;; + grey) _srcs="grey" ;; + *) _srcs="slava grey" ;; esac + msg "AmneziaWG is not installed: looking for a build for OpenWrt $OWRT_RELEASE ($OWRT_TARGET)" + _pf="$(awg_postfix)" + AWG_CANDIDATES="" + for _s in $_srcs; do + _repo="$(awg_repo "$_s")" + _aj="$TMP_DIR/awg-$_s.json" + if fetch_meta "https://api.github.com/repos/$_repo/releases/tags/v$OWRT_RELEASE" "$_aj"; then + _names="$(jsonfilter -i "$_aj" -e '@.assets[*].name' 2>/dev/null)" + _have=1 + for _p in $AWG_PKGS; do + printf '%s\n' "$_names" | grep -qxF "$_p$_pf" || _have=0 + done + if [ "$_have" -eq 1 ]; then + for _p in $AWG_PKGS; do + _s1="$(jsonfilter -i "$_aj" -e "@.assets[@.name='$_p$_pf'].size" 2>/dev/null | head -n 1)" + DOWNLOAD_BYTES=$((DOWNLOAD_BYTES + ${_s1:-0})) + done + AWG_CANDIDATES="$AWG_CANDIDATES $_s" + debug "$_repo has a build for this firmware" + # The first source that has it is the one used. + break + fi + debug "$_repo has no build for v$OWRT_RELEASE ($OWRT_ARCH, $OWRT_TARGET)" + else + # Unknown (API unavailable): try it when downloading. + AWG_CANDIDATES="$AWG_CANDIDATES $_s" + DOWNLOAD_BYTES=$((DOWNLOAD_BYTES + 1048576)) + fi + done + AWG_CANDIDATES="${AWG_CANDIDATES# }" + [ -n "$AWG_CANDIDATES" ] && return 0 + err "No AmneziaWG build for OpenWrt $OWRT_RELEASE ($OWRT_ARCH, $OWRT_TARGET) in: $(for _s in $_srcs; do awg_repo "$_s"; printf ' '; done)" + err "Install kmod-amneziawg, amneziawg-tools and luci-proto-amneziawg by hand, then run" + err "this again, or install Dawnline without it: --awg skip" + return 1 +} - postfix="_v${RELEASE}_${ARCH}_$(echo "$TARGET" | tr '/' '_').$EXT" - for src in $sources; do - msg "Downloading AmneziaWG for OpenWrt $RELEASE from $src" - ok=1 - files="" - for name in kmod-amneziawg amneziawg-tools luci-proto-amneziawg; do - file="$TMP/${name}${postfix}" - if fetch "https://github.com/$src/releases/download/v$RELEASE/${name}${postfix}" "$file"; then - files="$files $file" +check_tmp_space() { + _tf="$(free_kb /tmp)" + [ -n "$_tf" ] || return 0 + _need=$(((DOWNLOAD_BYTES + 1023) / 1024 + TMP_HEADROOM_KB)) + debug "/tmp: $((_tf / 1024)) MiB free, about $((_need / 1024)) MiB needed" + [ "$_tf" -ge "$_need" ] && return 0 + err "Not enough RAM in /tmp: $((_tf / 1024)) MiB free, about $((_need / 1024)) MiB needed" + return 1 +} + +print_plan() { + msg "Plan" + case "$MODE" in + install) msg " Dawnline: install $VERSION" ;; + upgrade) msg " Dawnline: upgrade $WAS_VERSION → $VERSION (a backup is made first)" ;; + reinstall) msg " Dawnline: reinstall $VERSION (a backup is made first)" ;; + downgrade) msg " Dawnline: downgrade $WAS_VERSION → $VERSION (a backup is made first)" ;; + esac + msg " Package manager: $PKG_MANAGER ($ASSET)" + case "$AWG_ACTION" in + keep) msg " AmneziaWG: keep the installed one" ;; + skip) msg " AmneziaWG: skip (install it later from Dawnline → Components)" ;; + install) + _l="" + for _s in $AWG_CANDIDATES; do _l="${_l:+$_l, then }$(awg_repo "$_s")"; done + msg " AmneziaWG: install from $_l" + ;; + esac + msg " Recovery snapshot: $SNAPSHOT_ROOT/" +} + +confirm() { + [ "$DRY_RUN" -eq 1 ] && return 0 + is_interactive || return 0 + prompt "Continue? [Y/n] " + # Ctrl-D (end of input) cancels, like n. + if read -r _answer; then + case "$_answer" in + '' | y | Y | yes | Yes | YES) return 0 ;; + esac + else + printf '\n' + fi + msg "Cancelled: nothing was changed" + exit 0 +} + +# ---------- download phase ---------- + +download_dawnline() { + _sums="$TMP_DIR/sha256sums.txt" + ASSET_FILE="$TMP_DIR/$ASSET" + # The checksum: GitHub's own (API), else the release's sha256sums.txt straight from github.com. + _want="$(asset_digest "$TMP_DIR/release.json" "$ASSET")" + if [ -z "$_want" ]; then + download "$ASSET_BASE/sha256sums.txt" "$_sums" sha256sums.txt || { + err "Download failed: sha256sums.txt (does release $VERSION exist?)" + return 1 + } + _want="$(awk -v f="$ASSET" '$2 == f || $2 == "*" f { print $1; exit }' "$_sums")" + [ -n "$_want" ] || { + err "sha256sums.txt has no entry for $ASSET: not installing an unverified package" + return 1 + } + fi + download "$ASSET_BASE/$ASSET" "$ASSET_FILE" "$ASSET" "$_want" || { + err "Download failed: $ASSET" + return 1 + } + verify_archive "$ASSET_FILE" || return 1 + ok "$ASSET verified (sha256, package format)" +} + +download_awg() { + [ "$AWG_ACTION" = install ] || return 0 + _pf="$(awg_postfix)" + for _s in $AWG_CANDIDATES; do + _repo="$(awg_repo "$_s")" + _files="" + _okd=1 + for _p in $AWG_PKGS; do + _f="$TMP_DIR/$_p$_pf" + # Verified when GitHub publishes the file's sha256 (then mirrors may serve it). + _want="$(asset_digest "$TMP_DIR/awg-$_s.json" "$_p$_pf")" + if download "https://github.com/$_repo/releases/download/v$OWRT_RELEASE/$_p$_pf" "$_f" "$_p ($_repo)" "$_want" && + verify_archive "$_f"; then + _files="$_files $_f" else - ok=0 + _okd=0 break fi done - if [ "$ok" -eq 1 ]; then - msg "Installing AmneziaWG" - # shellcheck disable=SC2086 - pkg_install_files $files || die "AmneziaWG installation failed." + if [ "$_okd" -eq 1 ]; then + AWG_REPO="$_repo" + AWG_FILES="${_files# }" + ok "AmneziaWG packages from $_repo verified ($([ -n "$_want" ] && printf 'sha256, ')package format)" return 0 fi - note "No build for OpenWrt $RELEASE ($TARGET) in $src." + warn "No usable AmneziaWG build for OpenWrt $OWRT_RELEASE in $_repo" done - die "No AmneziaWG build for OpenWrt $RELEASE ($TARGET). Install kmod-amneziawg, amneziawg-tools and luci-proto-amneziawg by hand, then run this again." + err "No AmneziaWG build for OpenWrt $OWRT_RELEASE ($OWRT_ARCH, $OWRT_TARGET) could be downloaded." + err "Install kmod-amneziawg, amneziawg-tools and luci-proto-amneziawg by hand, then run" + err "this again, or install Dawnline without it: --awg skip" + return 1 +} + +# ---------- transaction ---------- + +prune_snapshots() { + _keep="${DAWNLINE_SNAPSHOT_KEEP:-3}" + case "$_keep" in '' | *[!0-9]*) _keep=3 ;; esac + [ "$_keep" -ge 1 ] || _keep=1 + # Names are YYYYmmdd-HHMMSS: a reverse string sort is newest first. + ls -1d "$SNAPSHOT_ROOT"/*/ 2>/dev/null | sort -r | tail -n "+$((_keep + 1))" | + while IFS= read -r _d; do + [ -n "$_d" ] && rm -rf "$_d" + done + return 0 +} + +snapshot_create() { + _stamp="$(date +%Y%m%d-%H%M%S 2>/dev/null || echo "$$")" + if [ "$DRY_RUN" -eq 1 ]; then + dry "save /etc/config/{$(echo "$SNAPSHOT_CONFIGS" | tr ' ' ',')} and the service state to $SNAPSHOT_ROOT/$_stamp" + return 0 + fi + msg "Creating a recovery snapshot" + mkdir -p "$DATA_DIR" && chmod 700 "$DATA_DIR" 2>/dev/null + SNAPSHOT_DIR="$SNAPSHOT_ROOT/$_stamp" + [ -d "$SNAPSHOT_DIR" ] && SNAPSHOT_DIR="$SNAPSHOT_DIR-$$" + mkdir -p "$SNAPSHOT_DIR" || return 1 + chmod 700 "$SNAPSHOT_ROOT" "$SNAPSHOT_DIR" 2>/dev/null + for _c in $SNAPSHOT_CONFIGS; do + [ -f "/etc/config/$_c" ] || continue + cp -p "/etc/config/$_c" "$SNAPSHOT_DIR/$_c" || return 1 + done + printf 'installed=%s\nversion=%s\nenabled=%s\nrunning=%s\ntarget=%s\n' \ + "$WAS_INSTALLED" "$WAS_VERSION" "$WAS_ENABLED" "$WAS_RUNNING" "$VERSION" >"$SNAPSHOT_DIR/state" || return 1 + chmod 600 "$SNAPSHOT_DIR"/* 2>/dev/null + TX_ACTIVE=1 + prune_snapshots + ok "Recovery snapshot: $SNAPSHOT_DIR" +} + +dawnline_backup() { + [ "$WAS_INSTALLED" -eq 1 ] && [ -x /usr/bin/dawnline ] || return 0 + if [ "$DRY_RUN" -eq 1 ]; then + dry "run 'dawnline backup --reason pre-update'" + return 0 + fi + msg "Making a Dawnline backup before the $MODE" + _bn="$(/usr/bin/dawnline backup --reason pre-update 2>>"$LOG_FILE")" + if [ -n "$_bn" ] && [ -f "$DATA_DIR/backups/$_bn" ]; then + ok "Backup: $DATA_DIR/backups/$_bn" + else + warn "dawnline backup failed (the recovery snapshot still has the config)" + fi +} + +install_awg() { + [ "$AWG_ACTION" = install ] || return 0 + if [ "$DRY_RUN" -eq 1 ]; then + dry "install AmneziaWG from $AWG_REPO: $AWG_PKGS" + return 0 + fi + msg "Installing AmneziaWG from $AWG_REPO" + # shellcheck disable=SC2086 + pkg_install_files awg 0 $AWG_FILES || { + err "AmneziaWG installation failed" + return 1 + } + ok "AmneziaWG $(pkg_version amneziawg-tools) installed" } install_dawnline() { - if [ -z "$VERSION" ]; then - fetch "https://api.github.com/repos/$REPO/releases/latest" "$TMP/release.json" || - die "Cannot reach GitHub (or its rate limit is hit: try again in a few minutes)." - VERSION="$(jsonfilter -i "$TMP/release.json" -e '@.tag_name' | sed 's/^v//')" - fi - VERSION="${VERSION#v}" - [ -n "$VERSION" ] || die "Cannot determine the latest Dawnline release." - - asset="luci-app-dawnline-$VERSION.$EXT" - base="https://github.com/$REPO/releases/download/v$VERSION" - msg "Downloading Dawnline $VERSION" - fetch "$base/$asset" "$TMP/$asset" || die "Download failed: $asset" - fetch "$base/sha256sums.txt" "$TMP/sha256sums.txt" || die "Download failed: sha256sums.txt" - - want="$(awk -v f="$asset" '$2 == f || $2 == "*" f {print $1}' "$TMP/sha256sums.txt")" - got="$(sha256sum "$TMP/$asset" | awk '{print $1}')" - [ -n "$want" ] && [ "$want" = "$got" ] || die "Checksum mismatch for $asset." - - if [ -x /usr/bin/dawnline ]; then - msg "Dawnline is installed: upgrading (a backup is made first)" - /usr/bin/dawnline backup --reason pre-update >/dev/null 2>&1 || true + _force=0 + case "$MODE" in reinstall | downgrade) _force=1 ;; esac + if [ "$DRY_RUN" -eq 1 ]; then + dry "$MODE Dawnline $VERSION ($ASSET)" + return 0 fi msg "Installing Dawnline $VERSION" - pkg_install_files "$TMP/$asset" || die "Dawnline installation failed." + pkg_install_files dawnline "$_force" "$ASSET_FILE" +} + +healthcheck() { + [ "$DRY_RUN" -eq 1 ] && return 0 + msg "Running the healthcheck" + pkg_is_installed "$PKG_NAME" || { + err "$PKG_NAME is not registered with $PKG_MANAGER" + return 1 + } + [ -x /usr/bin/dawnline ] || { + err "/usr/bin/dawnline is missing" + return 1 + } + _pv="$(pkg_version "$PKG_NAME")" + [ "$_pv" = "$VERSION" ] || { + err "$PKG_MANAGER reports $PKG_NAME $_pv, expected $VERSION" + return 1 + } + _rv="$(/usr/bin/dawnline version 2>&1)" + [ "$_rv" = "$VERSION" ] || { + err "dawnline version reports '$_rv', expected $VERSION" + return 1 + } + _w=0 + until ubus list luci.dawnline >/dev/null 2>&1; do + _w=$((_w + 1)) + if [ "$_w" -eq "$UBUS_WAIT" ]; then + warn "rpcd has not loaded the Dawnline backend yet; restarting rpcd" + /etc/init.d/rpcd restart >/dev/null 2>&1 + fi + [ "$_w" -ge $((UBUS_WAIT + 10)) ] && { + err "The LuCI backend does not answer (ubus list luci.dawnline)" + return 1 + } + sleep 1 + done + _r="$(ubus call service list '{"name":"dawnline"}' 2>/dev/null | jsonfilter -q -e '@.dawnline.instances.agent.running' 2>/dev/null)" + if [ "$_r" != true ]; then + warn "The Dawnline agent is not running yet (see Dawnline → Diagnostics)" + fi + ok "Healthcheck passed: $PKG_NAME $VERSION, LuCI backend answers" +} + +# An upgrade keeps a service the user had disabled disabled (the package's +# postinst always enables and starts it). +keep_service_intent() { + [ "$DRY_RUN" -eq 0 ] && [ "$WAS_INSTALLED" -eq 1 ] && [ "$WAS_ENABLED" -eq 0 ] || return 0 + [ -x /etc/init.d/dawnline ] || return 0 + msg "Dawnline was disabled before the $MODE: keeping it disabled and stopped" + /etc/init.d/dawnline disable >/dev/null 2>&1 + /etc/init.d/dawnline stop >/dev/null 2>&1 + return 0 +} + +commit_transaction() { + TX_COMMITTED=1 + TX_ACTIVE=0 + [ -n "$SNAPSHOT_DIR" ] && echo "$VERSION" >"$SNAPSHOT_DIR/installed-release" 2>/dev/null + return 0 +} + +restore_snapshot() { + [ "$TX_ACTIVE" -eq 1 ] && [ "$TX_COMMITTED" -eq 0 ] || return 0 + [ -n "$SNAPSHOT_DIR" ] && [ -d "$SNAPSHOT_DIR" ] || return 0 + TX_ACTIVE=0 + warn "Restoring the configuration from $SNAPSHOT_DIR" + _changed="" + for _c in $SNAPSHOT_CONFIGS; do + [ -f "$SNAPSHOT_DIR/$_c" ] || continue + cmp -s "$SNAPSHOT_DIR/$_c" "/etc/config/$_c" && continue + cp -p "$SNAPSHOT_DIR/$_c" "/etc/config/$_c" 2>/dev/null && _changed="$_changed $_c" + done + [ -f /etc/config/dawnline ] && chmod 600 /etc/config/dawnline 2>/dev/null + for _c in $_changed; do + log_line "INFO restored /etc/config/$_c" + case "$_c" in + network) ubus call network reload >/dev/null 2>&1 ;; + firewall) /etc/init.d/firewall reload >/dev/null 2>&1 ;; + dhcp) /etc/init.d/dnsmasq reload >/dev/null 2>&1 ;; + uhttpd) /etc/init.d/uhttpd reload >/dev/null 2>&1 ;; + esac + done + if [ -x /etc/init.d/dawnline ]; then + if [ "$WAS_INSTALLED" -eq 1 ]; then + if [ "$WAS_ENABLED" -eq 1 ]; then + /etc/init.d/dawnline enable >/dev/null 2>&1 + else + /etc/init.d/dawnline disable >/dev/null 2>&1 + fi + if [ "$WAS_RUNNING" -eq 1 ]; then + /etc/init.d/dawnline restart >/dev/null 2>&1 + else + /etc/init.d/dawnline stop >/dev/null 2>&1 + fi + else + /etc/init.d/dawnline stop >/dev/null 2>&1 + /etc/init.d/dawnline disable >/dev/null 2>&1 + fi + fi + if [ -n "$_changed" ]; then + warn "Restored:$_changed; service state as before" + else + warn "No config had changed; service state as before" + fi + warn "Packages are not rolled back." + if [ "$WAS_INSTALLED" -eq 1 ] && [ -n "$WAS_VERSION" ] && [ "$WAS_VERSION" != "$VERSION" ]; then + warn "To go back to Dawnline $WAS_VERSION: sh install.sh --tag $WAS_VERSION" + elif [ "$WAS_INSTALLED" -eq 0 ] && [ -x /etc/init.d/dawnline ]; then + warn "Dawnline is installed but stopped: fix the cause and run the installer again," + warn "or remove it with uninstall.sh" + fi +} + +cleanup() { + _rc=$? + trap '' HUP INT TERM + stream_stop + restore_snapshot + [ -n "$TMP_DIR" ] && rm -rf "$TMP_DIR" 2>/dev/null + release_lock + return "$_rc" +} + +on_hup() { exit 129; } +on_int() { exit 130; } +on_term() { exit 143; } +# stdout or stderr closed: ignore further SIGPIPE so the EXIT cleanup runs. +on_pipe() { + trap '' PIPE + exit 141 +} + +lan_url() { + _ip="$(uci -q get network.lan.ipaddr 2>/dev/null | cut -d/ -f1 | awk '{ print $1 }')" + [ -n "$_ip" ] || _ip="192.168.1.1" + printf 'http://%s/cgi-bin/luci/admin/network/dawnline/server' "$_ip" } main() { - rm -rf "$TMP" - mkdir -p "$TMP" - check_system - msg "Updating package lists" - pkg_update || die "Package lists could not be updated." - install_awg - install_dawnline + trap cleanup EXIT + trap on_hup HUP + trap on_int INT + trap on_term TERM + trap on_pipe PIPE - lan="$(uci -q get network.lan.ipaddr 2>/dev/null | cut -d/ -f1)" - msg "Done." - note "Open LuCI → Network → Dawnline${lan:+ (http://$lan/cgi-bin/luci/admin/network/dawnline/server)} and run the setup wizard." + parse_args "$@" || exit 2 + + [ "$(id -u 2>/dev/null || echo 1)" = 0 ] || fail "Run the installer as root" + acquire_lock || exit 1 + # A dry run keeps the log of the last real install. + [ "$DRY_RUN" -eq 1 ] && LOG_FILE="/tmp/dawnline-install.dry.log" + : >"$LOG_FILE" 2>/dev/null && chmod 600 "$LOG_FILE" 2>/dev/null && LOG_READY=1 + log_line "INFO Dawnline Installer $INSTALLER_VERSION: $0 $*" + init_tmp_dir || fail "Cannot create a temporary directory in /tmp" + detect_fetcher || fail "No download tool" + detect_package_manager || fail "No supported package manager" + banner + [ "$DRY_RUN" -eq 1 ] && msg "Dry run: nothing on the router is changed" + + sync_time + check_system || fail "The system does not meet the requirements" + check_tools || fail "Required tools are missing" + check_dns || fail "Name resolution does not work" + record_state + + select_release + resolve_release || fail "Could not resolve the Dawnline release" + resolve_awg || fail "AmneziaWG is not available for this firmware" + check_tmp_space || fail "Not enough free memory for the downloads" + print_plan + confirm + + msg "Downloading release files" + download_dawnline || fail "Download or verification failed" + download_awg || fail "AmneziaWG download failed" + + pkg_refresh || fail "The package lists could not be updated" + snapshot_create || fail "Could not create the recovery snapshot" + # From here on an SSH drop must not kill the package manager half-way: + # the install finishes (or rolls back) on its own, the log has the rest. + trap '' HUP + dawnline_backup + install_awg || fail "AmneziaWG installation failed" + install_dawnline || fail "Dawnline installation failed" + healthcheck || fail "The installed Dawnline did not pass the healthcheck" + keep_service_intent + commit_transaction + trap on_hup HUP + + _took=$(($(date +%s 2>/dev/null || echo "$START_TS") - START_TS)) + if [ "$DRY_RUN" -eq 1 ]; then + ok "Dry run finished in ${_took}s: the plan is valid, nothing was changed" + msg "Log: $LOG_FILE" + return 0 + fi + case "$MODE" in + upgrade | downgrade) ok "Dawnline $VERSION installed in ${_took}s (was $WAS_VERSION)" ;; + *) ok "Dawnline $VERSION installed in ${_took}s" ;; + esac + [ "$AWG_ACTION" = skip ] && warn "AmneziaWG is not installed: add it in Dawnline → Components before creating a server" + msg "Log: $LOG_FILE" + msg "Recovery snapshot: $SNAPSHOT_DIR" + if [ "$MODE" = install ]; then + msg "Open LuCI → Network → Dawnline and run the setup wizard:" + else + msg "Open LuCI → Network → Dawnline:" + fi + msg " $(lan_url)" } main "$@" diff --git a/package/luci-app-dawnline/Makefile b/package/luci-app-dawnline/Makefile index ef74411..5b208c4 100644 --- a/package/luci-app-dawnline/Makefile +++ b/package/luci-app-dawnline/Makefile @@ -6,13 +6,13 @@ include $(TOPDIR)/rules.mk PKG_NAME:=luci-app-dawnline -PKG_VERSION:=0.3.1 +PKG_VERSION:=0.4.0 PKG_RELEASE:=1 PKG_LICENSE:=MIT LUCI_TITLE:=Dawnline - AmneziaWG access server # AmneziaWG itself (kmod-amneziawg, amneziawg-tools, luci-proto-amneziawg) is not -# in the OpenWrt feeds: install.sh and the Updates page install a build made for +# in the OpenWrt feeds: install.sh and the Components page install a build made for # the router's firmware. The portal's HTTPS needs any libustream TLS module and # openssl-util; Settings offers to install them when the portal is turned on. # Runtime dependencies only (control file Depends): the package ships scripts @@ -34,6 +34,10 @@ define Package/luci-app-dawnline/conffiles /etc/config/dawnline endef +# /etc/dawnline (keys, backups, usage, history) survives a sysupgrade too: +# root/lib/upgrade/keep.d/dawnline-data (the package's own keep.d file is +# generated from conffiles). + define Package/luci-app-dawnline/prerm #!/bin/sh [ -n "$${IPKG_INSTROOT}" ] && exit 0 @@ -41,6 +45,11 @@ define Package/luci-app-dawnline/prerm [ "$$1" = "upgrade" ] && exit 0 /etc/init.d/dawnline stop 2>/dev/null /usr/bin/dawnline teardown 2>/dev/null +# The heartbeat check would point at a removed file. +grep -qs /usr/libexec/dawnline/ /etc/crontabs/root && { + sed -i '\#/usr/libexec/dawnline/#d' /etc/crontabs/root + /etc/init.d/cron restart 2>/dev/null +} exit 0 endef diff --git a/package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/app.js b/package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/app.js index 7625dc3..746ad3f 100644 --- a/package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/app.js +++ b/package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/app.js @@ -2,19 +2,28 @@ 'use strict'; 'require baseclass'; 'require dom'; -'require form'; 'require poll'; 'require rpc'; -'require uci'; 'require ui'; -var An=Object.create;var Qt=Object.defineProperty;var Pn=Object.getOwnPropertyDescriptor;var Nn=Object.getOwnPropertyNames;var zn=Object.getPrototypeOf,Rn=Object.prototype.hasOwnProperty;var Hn=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports);var In=(i,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Nn(t))!Rn.call(i,s)&&s!==n&&Qt(i,s,{get:()=>t[s],enumerable:!(a=Pn(t,s))||a.enumerable});return i};var Bn=(i,t,n)=>(n=i!=null?An(zn(i)):{},In(t||!i||!i.__esModule?Qt(n,"default",{value:i,enumerable:!0}):n,i));var nn=Hn((en,tn)=>{"use strict";var Xt=(function(){var i=function(_,N){var C=236,D=17,$=_,A=n[N],m=null,h=0,P=null,f=[],S={},j=function(M,E){h=$*4+17,m=(function(w){for(var y=new Array(w),T=0;T=7&&X(M),P==null&&(P=De($,A,f)),ie(P,E)},W=function(M,E){for(var w=-1;w<=7;w+=1)if(!(M+w<=-1||h<=M+w))for(var y=-1;y<=7;y+=1)E+y<=-1||h<=E+y||(0<=w&&w<=6&&(y==0||y==6)||0<=y&&y<=6&&(w==0||w==6)||2<=w&&w<=4&&2<=y&&y<=4?m[M+w][E+y]=!0:m[M+w][E+y]=!1)},v=function(){for(var M=0,E=0,w=0;w<8;w+=1){j(!0,w);var y=s.getLostPoint(S);(w==0||M>y)&&(M=y,E=w)}return E},U=function(){for(var M=8;M>w&1)==1;m[Math.floor(w/3)][w%3+h-8-3]=y}for(var w=0;w<18;w+=1){var y=!M&&(E>>w&1)==1;m[w%3+h-8-3][Math.floor(w/3)]=y}},le=function(M,E){for(var w=A<<3|E,y=s.getBCHTypeInfo(w),T=0;T<15;T+=1){var B=!M&&(y>>T&1)==1;T<6?m[T][8]=B:T<8?m[T+1][8]=B:m[h-15+T][8]=B}for(var T=0;T<15;T+=1){var B=!M&&(y>>T&1)==1;T<8?m[8][h-T-1]=B:T<9?m[8][15-T-1+1]=B:m[8][15-T-1]=B}m[h-8][8]=!M},ie=function(M,E){for(var w=-1,y=h-1,T=7,B=0,Y=s.getMaskFunction(E),F=h-1;F>0;F-=2)for(F==6&&(F-=1);;){for(var ae=0;ae<2;ae+=1)if(m[y][F-ae]==null){var de=!1;B>>T&1)==1);var J=Y(y,F-ae);J&&(de=!de),m[y][F-ae]=de,T-=1,T==-1&&(B+=1,T=7)}if(y+=w,y<0||h<=y){y-=w,w=-w;break}}},me=function(M,E){for(var w=0,y=0,T=0,B=new Array(E.length),Y=new Array(E.length),F=0;F=0?Yt.getAt(Vt):0}}for(var Jt=0,J=0;JF*8)throw"code length overflow. ("+T.getLengthInBits()+">"+F*8+")";for(T.getLengthInBits()+4<=F*8&&T.put(0,4);T.getLengthInBits()%8!=0;)T.putBit(!1);for(;!(T.getLengthInBits()>=F*8||(T.put(C,8),T.getLengthInBits()>=F*8));)T.put(D,8);return me(T,y)};S.addData=function(M,E){E=E||"Byte";var w=null;switch(E){case"Numeric":w=p(M);break;case"Alphanumeric":w=u(M);break;case"Byte":w=c(M);break;case"Kanji":w=x(M);break;default:throw"mode:"+E}f.push(w),P=null},S.isDark=function(M,E){if(M<0||h<=M||E<0||h<=E)throw M+","+E;return m[M][E]},S.getModuleCount=function(){return h},S.make=function(){if($<1){for(var M=1;M<40;M++){for(var E=l.getRSBlocks(M,A),w=d(),y=0;y"u"?M*4:E;var w="";w+='";for(var T=0;T';w+=""}return w+="",w+="
",w},S.createSvgTag=function(M,E,w,y){var T={};typeof arguments[0]=="object"&&(T=arguments[0],M=T.cellSize,E=T.margin,w=T.alt,y=T.title),M=M||2,E=typeof E>"u"?M*4:E,w=typeof w=="string"?{text:w}:w||{},w.text=w.text||null,w.id=w.text?w.id||"qrcode-description":null,y=typeof y=="string"?{text:y}:y||{},y.text=y.text||null,y.id=y.text?y.id||"qrcode-title":null;var B=S.getModuleCount()*M+E*2,Y,F,ae,de,J="",ge;for(ge="l"+M+",0 0,"+M+" -"+M+",0 0,-"+M+"z ",J+=''+H(y.text)+"":"",J+=w.text?''+H(w.text)+"":"",J+='',J+='"u"?M*4:E;var w=S.getModuleCount()*M+E*2,y=E,T=w-E;return I(w,w,function(B,Y){if(y<=B&&B"u"?M*4:E;var y=S.getModuleCount()*M+E*2,T="";return T+="",T};var H=function(M){for(var E="",w=0;w":E+=">";break;case"&":E+="&";break;case'"':E+=""";break;default:E+=y;break}}return E},re=function(M){var E=1;M=typeof M>"u"?E*2:M;var w=S.getModuleCount()*E+M*2,y=M,T=w-M,B,Y,F,ae,de,J={"██":"█","█ ":"▀"," █":"▄"," ":" "},ge={"██":"▀","█ ":"▀"," █":" "," ":" "},fe="";for(B=0;B=T?ge[de]:J[de];fe+=` -`}return w%2&&M>0?fe.substring(0,fe.length-w-1)+Array(w+1).join("▀"):fe.substring(0,fe.length-1)};return S.createASCII=function(M,E){if(M=M||1,M<2)return re(E);M-=1,E=typeof E>"u"?M*2:E;var w=S.getModuleCount()*M+E*2,y=E,T=w-E,B,Y,F,ae,de=Array(M+1).join("██"),J=Array(M+1).join(" "),ge="",fe="";for(B=0;B>>8),A.push(P&255)):A.push(D)}}return A}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},s=(function(){var _=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],N=1335,C=7973,D=21522,$={},A=function(m){for(var h=0;m!=0;)h+=1,m>>>=1;return h};return $.getBCHTypeInfo=function(m){for(var h=m<<10;A(h)-A(N)>=0;)h^=N<=0;)h^=C<5&&(P+=3+j-5)}for(var f=0;f=256;)$-=255;return _[$]},D})();function r(_,N){if(typeof _.length>"u")throw _.length+"/"+N;var C=(function(){for(var $=0;$<_.length&&_[$]==0;)$+=1;for(var A=new Array(_.length-$+N),m=0;m<_.length-$;m+=1)A[m]=_[m+$];return A})(),D={};return D.getAt=function($){return C[$]},D.getLength=function(){return C.length},D.multiply=function($){for(var A=new Array(D.getLength()+$.getLength()-1),m=0;m"u")throw"bad rs block @ typeNumber:"+$+"/errorCorrectionLevel:"+A;for(var h=m.length/3,P=[],f=0;f>>7-D%8&1)==1},C.put=function(D,$){for(var A=0;A<$;A+=1)C.putBit((D>>>$-A-1&1)==1)},C.getLengthInBits=function(){return N},C.putBit=function(D){var $=Math.floor(N/8);_.length<=$&&_.push(0),D&&(_[$]|=128>>>N%8),N+=1},C},p=function(_){var N=t.MODE_NUMBER,C=_,D={};D.getMode=function(){return N},D.getLength=function(m){return C.length},D.write=function(m){for(var h=C,P=0;P+2>>8&255)*192+(f&255),m.put(f,13),P+=2}if(P>>8)},N.writeBytes=function(C,D,$){D=D||0,$=$||C.length;for(var A=0;A<$;A+=1)N.writeByte(C[A+D])},N.writeString=function(C){for(var D=0;D0&&(C+=","),C+=_[D];return C+="]",C},N},k=function(){var _=0,N=0,C=0,D="",$={},A=function(h){D+=String.fromCharCode(m(h&63))},m=function(h){if(!(h<0)){if(h<26)return 65+h;if(h<52)return 97+(h-26);if(h<62)return 48+(h-52);if(h==62)return 43;if(h==63)return 47}throw"n:"+h};return $.writeByte=function(h){for(_=_<<8|h&255,N+=8,C+=1;N>=6;)A(_>>>N-6),N-=6},$.flush=function(){if(N>0&&(A(_<<6-N),_=0,N=0),C%3!=0)for(var h=3-C%3,P=0;P=N.length){if($==0)return-1;throw"unexpected end of file./"+$}var h=N.charAt(C);if(C+=1,h=="=")return $=0,-1;if(h.match(/^\s$/))continue;D=D<<6|m(h.charCodeAt(0)),$+=6}var P=D>>>$-8&255;return $-=8,P};var m=function(h){if(65<=h&&h<=90)return h-65;if(97<=h&&h<=122)return h-97+26;if(48<=h&&h<=57)return h-48+52;if(h==43)return 62;if(h==47)return 63;throw"c:"+h};return A},K=function(_,N){var C=_,D=N,$=new Array(_*N),A={};A.setPixel=function(f,S,j){$[S*C+f]=j},A.write=function(f){f.writeString("GIF87a"),f.writeShort(C),f.writeShort(D),f.writeByte(128),f.writeByte(0),f.writeByte(0),f.writeByte(0),f.writeByte(0),f.writeByte(0),f.writeByte(255),f.writeByte(255),f.writeByte(255),f.writeString(","),f.writeShort(0),f.writeShort(0),f.writeShort(C),f.writeShort(D),f.writeByte(0);var S=2,j=h(S);f.writeByte(S);for(var W=0;j.length-W>255;)f.writeByte(255),f.writeBytes(j,W,255),W+=255;f.writeByte(j.length-W),f.writeBytes(j,W,j.length-W),f.writeByte(0),f.writeString(";")};var m=function(f){var S=f,j=0,W=0,v={};return v.write=function(U,q){if(U>>>q)throw"length over";for(;j+q>=8;)S.writeByte(255&(U<>>=8-j,W=0,j=0;W=U<0&&S.writeByte(W)},v},h=function(f){for(var S=1<>6,128|o&63):o<55296||o>=57344?a.push(224|o>>12,128|o>>6&63,128|o&63):(s++,o=65536+((o&1023)<<10|n.charCodeAt(s)&1023),a.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63))}return a}return t(i)}})();(function(i){typeof define=="function"&&define.amd?define([],i):typeof en=="object"&&(tn.exports=i())})(function(){return Xt})});function Et(i,t){return i==null||i===!1||i===""||(Array.isArray(i)?i.forEach(n=>Et(n,t)):t.push(i instanceof Node?i:String(i))),t}function e(i,t,n){let a=window.E,s=t!=null&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Node);return!s&&n===void 0?a(i,{},Et(t,[])):a(i,s?t:{},Et(n,[]))}function V(i,t=[]){let n=rpc.declare({object:"luci.dawnline",method:i,params:t});return async(...a)=>{let s=await n(...a);if(s&&typeof s=="object"&&typeof s.error=="string")throw new Error(s.error);return s}}var jn=V("logs_clear",["person","device","category","older_days"]),On=(i={})=>jn(i.person??"",i.device??"",i.category??"",i.older_days??""),Un=rpc.declare({object:"luci.dawnline",method:"person_update",params:["id","name","access","device_limit","expires","expire_action","expire_warn","quota_gb","quota_period","bonus_gb","hours","note","dns_mode","paused","services","circle","home_nets"]});async function qn(i,t){let a=[i,...["name","access","device_limit","expires","expire_action","expire_warn","quota_gb","quota_period","bonus_gb","hours","note","dns_mode"].map(o=>t[o]),t.paused,t.services,t.circle,t.home_nets],s=await Un(...a);if(s&&typeof s.error=="string")throw new Error(s.error);return s}var Wn=V("status",["days"]),Gn=0;async function Fn(i){let t=await Wn(i);return Gn=Date.now(),t}var z={personUpdate:qn,settingsGet:V("settings_get"),settingsUpdate:V("settings_update",["values"]),serviceSet:V("service_set",["id","name","address","ports"]),serviceDelete:V("service_delete",["id"]),geoClear:V("geo_clear"),events:V("events",["limit"]),logsClear:On,interfaces:V("interfaces",["id"]),serverInterfaces:V("server_interfaces",["id","auto_wan","wan_device","auto_lan","lan_devices","lan_like","device_mesh","mesh"]),circleSet:V("circle_set",["id","server","name","color","members"]),circleDelete:V("circle_delete",["id"]),accessCheck:V("access_check",["from","to"]),homeHosts:V("home_hosts",["id"]),usageClear:V("usage_clear",["scope","id"]),uninstall:V("uninstall",["confirm"]),status:Fn,setupDefaults:V("setup_defaults"),serverCreate:V("server_create",["id","name","ifname","port","subnet","endpoint","mtu","preset","lan_zone","wan_zone","lan_like","portal_enabled","portal_port"]),serverObfuscation:V("server_obfuscation",["id","preset"]),serverUpdate:V("server_update",["id","values"]),serverDelete:V("server_delete",["id"]),personCreate:V("person_create",["name","slug","server","access","device_limit","expires","quota_gb","quota_period"]),personPause:V("person_pause",["id","paused"]),personRegen:V("person_regen",["id"]),personDelete:V("person_delete",["id"]),personUsage:V("person_usage",["id","days"]),pauseAll:V("pause_all",["paused"]),deviceCreate:V("device_create",["person","name","kind"]),deviceConfig:V("device_config",["id"]),deviceUpdate:V("device_update",["id","name","disabled"]),deviceDelete:V("device_delete",["id"]),deviceRotate:V("device_rotate",["id"]),apply:V("apply"),health:V("health"),healthFix:V("health_fix",["id"]),serviceLog:V("service_log"),serviceLogClear:V("service_log_clear",["older_days"]),backupList:V("backup_list"),backupCreate:V("backup_create"),backupRestore:V("backup_restore",["name"]),backupDelete:V("backup_delete",["name"]),backupRead:V("backup_read",["name"]),backupUpload:V("backup_upload",["data"]),exportJson:V("export"),importJson:V("import",["data"]),updatesStatus:V("updates_status"),updatesRun:V("updates_run",["what"])};var Zt={phone:'',computer:'',tablet:'',router:'',other:'',ethernet:'',bridge:'',wifi:'',tunnel:'',plus:'',chart:'',reset:'',package:'',code:'',plug:'',sunrise:'',refresh:'',archive:'',qr:'',copy:'',download:'',link:'',trash:'',edit:'',pause:'',play:'',key:'',out:'',admin:'',shield:'',shieldplus:'',lock:'',zap:'',check:'',alert:'',x:'',globe:'',home:'',open:'',file:'',network:'',moon:'',chevron:'',clock:'',calendar:'',minus:'',more:'',pin:'',activity:''};function Tt(i,t="dl-icon"){let n=Zt[i]??Zt.phone;return``}function b(i,t="dl-icon"){let n=document.createElement("span");return n.className="dl-icon-wrap",n.innerHTML=Tt(i,t),n}function R(i,t,n="neutral",a={}){let{disabled:s,...o}=a,r=e("button",{class:`cbi-button cbi-button-${n}`,type:"button",...o,click:async l=>{if(l.preventDefault(),l.stopPropagation(),!r.disabled){r.disabled=!0,r.classList.add("spinning");try{await t(l)}catch(d){te(Ct(d),"error")}finally{r.disabled=!1,r.classList.remove("spinning")}}}},i);return r.disabled=!!s,r}function ke(i,t,n,a="neutral",s=""){return R([b(i),e("span",{class:"dl-btn-label"},t)],n,a,{title:t,class:`cbi-button cbi-button-${a} dl-icon-btn ${s}`.trim()})}function te(i,t="info",n=0){let a=document.querySelector(".dl-toasts");a||(a=e("div",{class:"dl-toasts dl-root",role:"status","aria-live":"polite"}),document.body.appendChild(a));let s=t==="error"?"x":t==="warning"?"alert":t==="success"?"check":null,o=()=>{r.classList.remove("show"),setTimeout(()=>r.remove(),200)},r=e("div",{class:`dl-toast ${t}`},[s?b(s):"",e("span",{},i),t==="error"?e("button",{type:"button","aria-label":"Close",click:o},b("x")):""]);a.appendChild(r),requestAnimationFrame(()=>r.classList.add("show")),setTimeout(o,n||(t==="error"?8e3:t==="warning"?5e3:2600))}function Ct(i){return i instanceof Error?i.message:String(i)}async function O(i,t){try{let n=await i();return t&&te(t,"success",3500),n}catch(n){te(Ct(n),"error",1e4);return}}function ne(i,t,n,a=""){ui.showModal(i,[e("div",{class:`dl-modal ${a}`},t),e("div",{class:"button-row"},n)])}function Z(){ui.hideModal()}function oe(i,t,n="Confirm",a=!1){return new Promise(s=>{ne(i,t,[e("button",{class:"cbi-button cbi-button-neutral",type:"button",click:()=>{Z(),s(!1)}},"Cancel")," ",e("button",{class:`cbi-button ${a?"cbi-button-negative":"cbi-button-positive"}`,type:"button",click:()=>{Z(),s(!0)}},n)])})}async function pe(i,t="Copied to clipboard"){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(i);else{let n=e("textarea",{style:"position:fixed;opacity:0"},i);document.body.appendChild(n),n.select(),document.execCommand("copy"),n.remove()}te(t,"success",2500)}catch(n){te(Ct(n),"error")}}function ve(i,t,n="text/plain"){let a=globalThis,s=typeof t=="string"?new a.Blob([t],{type:n}):t,o=URL.createObjectURL(s),r=e("a",{href:o,download:i,style:"display:none"});document.body.appendChild(r),r.click(),setTimeout(()=>{URL.revokeObjectURL(o),r.remove()},1e3)}function Ae(i,t){let n={ok:"success",warn:"warning",error:"error",info:"notice"}[i];return e("div",{class:`alert-message ${n}`},t)}function Pe(i,t=""){let n=e("div",{class:t});return n.innerHTML=i,n}function Dt(i,t){return new Promise(n=>{let a=e("input",{type:"file",accept:i,style:"display:none"});a.addEventListener("cancel",()=>{a.remove(),n(null)}),a.addEventListener("change",()=>{let s=a.files?.[0];if(a.remove(),!s)return n(null);let o=new FileReader;o.onload=()=>{let r=String(o.result??"");n({name:s.name,data:t==="base64"?r.replace(/^data:[^,]*,/,""):r})},o.onerror=()=>n(null),t==="base64"?o.readAsDataURL(s):o.readAsText(s)}),document.body.appendChild(a),a.click()})}function we(i,t){let n=document.querySelector(".dl-dd");if(n&&(n.dlClose?n.dlClose():n.remove(),n.dlAnchor===i))return;let a=e("div",{class:"dl-dd dl-root",role:"menu"},t.map(u=>u?e("button",{type:"button",role:"menuitem",class:u.danger?"danger":u.warn?"warn":"",click:()=>{p(),u.run()}},[u.icon??"",e("span",{},u.label)]):e("hr")));document.body.appendChild(a);let s=i.getBoundingClientRect(),o=a.offsetWidth,r=a.offsetHeight;a.style.top=`${s.bottom+6+r>window.innerHeight-8&&s.top-6-r>8?s.top-6-r:s.bottom+6}px`,a.style.left=`${Math.max(8,Math.min(s.right-o,window.innerWidth-o-8))}px`;let l=u=>{!a.contains(u.target)&&!i.contains(u.target)&&p()},d=u=>{u.key==="Escape"&&p()};a.dlAnchor=i,a.dlClose=p;function p(){a.remove(),document.removeEventListener("mousedown",l,!0),document.removeEventListener("keydown",d,!0),window.removeEventListener("scroll",p,!0)}setTimeout(()=>{document.addEventListener("mousedown",l,!0),document.addEventListener("keydown",d,!0),window.addEventListener("scroll",p,!0)}),a.querySelector("button")?.focus({preventScroll:!0})}var an=Bn(nn(),1),Kn='';function Oe(i,t=3,n=!0){let a=(0,an.default)(0,i.length>300?"Q":"H");a.addData(i,"Byte"),a.make();let s=a.getModuleCount(),o=s+t*2,r=n?Math.round(s*.22):0;r&&(s-r)%2&&r++;let l=(s-r)/2,d=l+r,p=(x,g)=>r>0&&x>=l&&x=l&&g${Kn}`}return`${c}`}var Yn={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Vn={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function Jn(i){let t={};for(let[n,a]of Object.entries(Vn))i[n]!=null&&i[n]!==""&&(t[a]=String(i[n]));return t}function Qn(i,t){let n=i.amnezia,a=n.obfuscation??{},s=d=>a[d]!=null&&a[d]!==""?String(a[d]):Yn[d],o=n.host.replace(/^\[(.*)\]$/,"$1"),r={H1:s("h1"),H2:s("h2"),H3:s("h3"),H4:s("h4"),I1:s("i1"),I2:s("i2"),I3:s("i3"),I4:s("i4"),I5:s("i5"),Jc:s("jc"),Jmin:s("jmin"),Jmax:s("jmax"),S1:s("s1"),S2:s("s2"),S3:s("s3"),S4:s("s4"),...Jn(a),allowed_ips:n.allowed_ips,client_ip:n.client_ip,client_priv_key:n.client_priv_key,client_pub_key:n.client_pub_key,config:i.conf.replace(/\r?\n/g,`\r -`),hostName:o,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(r),port:String(n.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:o};return n.dns[0]&&(l.dns1=n.dns[0]),n.dns[1]&&(l.dns2=n.dns[1]),l}function Zn(i){let t="";for(let n=0;n"u")return null;try{let n=new t.Blob([i]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(n).arrayBuffer()),s=new Uint8Array(4+a.length);return new DataView(s.buffer).setUint32(0,i.length,!1),s.set(a,4),s}catch{return null}}async function sn(i,t,n=!0){let a=new TextEncoder().encode(JSON.stringify(Qn(i,t))),s=n?await Xn(a):null;return`vpn://${Zn(s??a)}`}function Q(i){if(!i||i<0)return"0 B";let t=["B","KB","MB","GB","TB"],n=0,a=i;for(;a>=1024&&n=100||n===0?Math.round(a):a.toFixed(1)} ${t[n]}`}function $e(i){let t=i*8;return t<1e3?`${Math.round(t)} bit/s`:t<1e6?`${(t/1e3).toFixed(t<1e4?1:0)} kbit/s`:t<1e9?`${(t/1e6).toFixed(t<1e7?1:0)} Mbit/s`:`${(t/1e9).toFixed(1)} Gbit/s`}function he(i,t=Date.now()/1e3){if(!i)return"never";let n=Math.max(0,Math.round(t-i));return n<60?"just now":n<3600?`${Math.floor(n/60)} min ago`:n<86400?`${Math.floor(n/3600)} h ago`:n<86400*30?`${Math.floor(n/86400)} d ago`:new Date(i*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function on(i){if(!i||i<0)return"—";let t=Math.floor(i/86400),n=Math.floor(i%86400/3600),a=Math.floor(i%3600/60);return t?`${t}d ${n}h`:n?`${n}h ${a}m`:`${a}m`}function Ne(i){let t=new Date(i*1e3),n=new Date,a=t.toDateString()===n.toDateString(),s=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});return a?s:`${t.toLocaleDateString("en-GB",{day:"numeric",month:"short"})} ${s}`}function _e(i){if(!i)return"";let[t,n,a]=i.split("-").map(Number);return new Date(t,n-1,a).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function ze(i,t=Date.now()){if(!i)return null;let[n,a,s]=i.split("-").map(Number),o=new Date(n,a-1,s,23,59,59).getTime();return Math.ceil((o-t)/864e5)}var Ue={lan:"Home network",internet:"Internet",both:"Home network + Internet"};var rn=["computer","phone","tablet","router","other"],Se={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},At={active:"Active",paused:"Paused",paused_all:"Paused (everyone)",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server"};function Re(i){let t=i.trim().split(/\s+/).filter(Boolean);if(!t.length)return"?";let n=t[0][0]??"",a=t.length>1?t[t.length-1][0]??"":t[0][1]??"";return(n+a).toUpperCase()}function rt(i){let t=n=>n.disabled?3:n.online?0:n.handshake?1:2;return i.map((n,a)=>[n,a]).sort((n,a)=>t(n[0])-t(a[0])||n[1]-a[1]).map(([n])=>n)}var ln="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl",ea="https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",ta="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",na={online:0,"24h":86400,"7d":7*86400,"30d":30*86400},Je=null;function aa(i){let t=window;return i.appendChild(e("link",{rel:"stylesheet",href:`${ln}.css`})),t.maplibregl?Promise.resolve(t.maplibregl):Je||(Je=new Promise((n,a)=>{let s=e("script",{src:`${ln}.js`});s.onload=()=>t.maplibregl?n(t.maplibregl):a(new Error("MapLibre failed to load")),s.onerror=()=>{Je=null,a(new Error("Could not load the map library (no internet access from this browser?)"))},i.appendChild(s)}),Je)}function lt(){let i=document.documentElement.getAttribute("data-darkmode");return i!=null?i==="true":window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1}function sa(i,t,n=48){let a=(i[0]+t[0])/2,s=(i[1]+t[1])/2,o=t[0]-i[0],r=t[1]-i[1],l=Math.hypot(o,r)||1,d=Math.min(.25*l,12),p=a-r/l*d,u=s+o/l*d,c=[];for(let x=0;x<=n;x++){let g=x/n,k=1-g;c.push([k*k*i[0]+2*k*g*p+g*g*t[0],k*k*i[1]+2*k*g*u+g*g*t[1]])}return c}function ia(i,t){let n=new Map;for(let a of i.geo.points){if(i.person&&a.person!==i.person||(t==="online"?!a.online:i.now-a.ts>na[t]))continue;let s=n.get(a.device);(!s||a.online&&!s.online||a.online===s.online&&a.ts>s.ts)&&n.set(a.device,a)}return[...n.values()]}var qe=class{constructor(t,n="online",a=380){this.cb=t;this.map=null;this.gl=null;this.markers=[];this.popup=null;this.anim=0;this.data=null;this.fitted=!1;this.range=n,this.status=e("div",{class:"dl-map-status"}),this.el=e("div",{class:"dl-geomap",style:`height:${a}px`},this.status)}async mount(t){this.data=t;try{this.gl=await aa(this.el)}catch(n){this.status.textContent=n.message;return}this.map=new this.gl.Map({container:this.el,style:lt()?ea:ta,center:[t.geo.home?.lon??20,t.geo.home?.lat??50],zoom:3,attributionControl:{compact:!0},dragRotate:!1,pitchWithRotate:!1,cooperativeGestures:!0}),this.map.addControl(new this.gl.NavigationControl({showCompass:!1}),"bottom-right"),this.map.on("load",()=>{this.map.addSource("dl-areas",{type:"geojson",data:{type:"FeatureCollection",features:[]}}),this.map.addLayer({id:"dl-area",type:"circle",source:"dl-areas",paint:{"circle-radius":["interpolate",["exponential",2],["zoom"],2,6,6,26,9,140,12,900],"circle-color":["case",["get","online"],"#40c977",lt()?"#ededed":"#0d0d0d"],"circle-opacity":["case",["get","online"],.12,.06],"circle-stroke-width":1,"circle-stroke-color":["case",["get","online"],"#40c977",lt()?"#ededed":"#0d0d0d"],"circle-stroke-opacity":["case",["get","online"],.35,.15]}}),this.map.addSource("dl-arcs",{type:"geojson",data:{type:"FeatureCollection",features:[]}}),this.map.addLayer({id:"dl-arc-recent",type:"line",source:"dl-arcs",filter:["==",["get","online"],!1],layout:{"line-cap":"round"},paint:{"line-color":lt()?"#ededed":"#0d0d0d","line-opacity":.35,"line-width":1.5,"line-dasharray":[2,3]}}),this.map.addLayer({id:"dl-arc-glow",type:"line",source:"dl-arcs",filter:["==",["get","online"],!0],layout:{"line-cap":"round"},paint:{"line-color":"#40c977","line-opacity":.18,"line-width":7}}),this.map.addLayer({id:"dl-arc-live",type:"line",source:"dl-arcs",filter:["==",["get","online"],!0],layout:{"line-cap":"round"},paint:{"line-color":"#40c977","line-width":2}}),this.map.addLayer({id:"dl-arc-flow",type:"line",source:"dl-arcs",filter:["==",["get","online"],!0],layout:{"line-cap":"round"},paint:{"line-color":"#ffffff","line-width":2,"line-opacity":.8,"line-dasharray":[0,4,3]}}),this.animate(),this.draw()})}setRange(t){this.range=t,this.fitted=!1,this.draw()}update(t){this.data=t,this.draw()}destroy(){cancelAnimationFrame(this.anim),this.map?.remove(),this.map=null}animate(){let t=[[0,4,3],[.5,4,2.5],[1,4,2],[1.5,4,1.5],[2,4,1],[2.5,4,.5],[3,4,0],[0,.5,3,3.5],[0,1,3,3],[0,1.5,3,2.5],[0,2,3,2],[0,2.5,3,1.5],[0,3,3,1],[0,3.5,3,.5]],n=-1,a=0,s=o=>{this.map&&(o-a>70&&(a=o,n=(n+1)%t.length,this.map.getLayer("dl-arc-flow")&&this.map.setPaintProperty("dl-arc-flow","line-dasharray",t[n])),this.anim=requestAnimationFrame(s))};this.anim=requestAnimationFrame(s)}groups(t){let n=new Map;for(let a of t){let s=`${a.asn||a.org||a.ip}|${a.city}|${a.cc}`,o=n.get(s);o||(o={key:s,lat:a.lat,lon:a.lon,city:a.city,country:a.country,cc:a.cc,asn:a.asn,org:a.org,online:!1,ts:0,points:[]},n.set(s,o)),o.points.push(a),o.online||(o.online=a.online),o.ts=Math.max(o.ts,a.ts)}return[...n.values()]}draw(){if(!this.map||!this.data||!this.map.getSource("dl-arcs"))return;let t=this.data,n=this.groups(ia(t,this.range)),a=t.geo.home;for(let r of this.markers)r.remove();this.markers=[];let s=new Map,o=n.map(r=>{let l=`${r.lat.toFixed(2)},${r.lon.toFixed(2)}`,d=s.get(l)??0;return s.set(l,d+1),{g:r,at:[r.lon+d*.25,r.lat]}});if(this.map.getSource("dl-areas").setData({type:"FeatureCollection",features:o.map(({g:r,at:l})=>({type:"Feature",properties:{online:r.online},geometry:{type:"Point",coordinates:l}}))}),this.map.getSource("dl-arcs").setData({type:"FeatureCollection",features:a?o.map(({g:r,at:l})=>({type:"Feature",properties:{online:r.online},geometry:{type:"LineString",coordinates:sa([a.lon,a.lat],l)}})):[]}),a){let r=e("div",{class:"dl-mk-home",title:`Home router${a.city?` · ${a.city}`:""}${a.org?` · ${a.org}`:""}`});r.innerHTML=Tt("home","dl-mk-home-ic"),this.markers.push(new this.gl.Marker({element:r}).setLngLat([a.lon,a.lat]).addTo(this.map))}for(let{g:r,at:l}of o){let d=r.points.length,p=e("button",{type:"button",class:`dl-mk${r.online?" online":""}${d>1?" multi":""}`,"aria-label":`${d} device${d===1?"":"s"} via ${r.org||"unknown network"} in ${r.city||"unknown city"}`},d>1?e("span",{class:"dl-mk-count"},String(d)):e("span",{class:"dl-mk-dot"})),c=!!a&&Math.abs(l[0]-a.lon)<.02&&Math.abs(l[1]-a.lat)<.02?[22,-16]:[0,0];p.addEventListener("click",x=>{x.stopPropagation(),this.openPopup(r,l,c)}),this.markers.push(new this.gl.Marker({element:p,offset:c}).setLngLat(l).addTo(this.map))}if(!this.fitted){let r=o.map(l=>l.at);a&&(r.length===0||this.range!=="online"||o.some(l=>l.g.online))&&r.push([a.lon,a.lat]),this.fit(r),this.fitted=!0}this.status.textContent=o.length||a?"":"No locations yet",this.status.style.display=this.status.textContent?"":"none"}fit(t){if(!t.length)return;let n=(d,p)=>{let u=Math.PI/180,c=(p[1]-d[1])*u,x=(p[0]-d[0])*u,g=Math.sin(c/2)**2+Math.cos(d[1]*u)*Math.cos(p[1]*u)*Math.sin(x/2)**2;return 12742*Math.asin(Math.sqrt(g))},a=[t.reduce((d,p)=>d+p[0],0)/t.length,t.reduce((d,p)=>d+p[1],0)/t.length],s=t;if(t.length>=5){let d=[...t].sort((p,u)=>n(a,p)-n(a,u));s=d.slice(0,Math.ceil(d.length*.9))}if(Math.max(...s.map(d=>n(a,d)))<25){this.map.jumpTo({center:a,zoom:9.5});return}let r=new this.gl.LngLatBounds(s[0],s[0]);s.forEach(d=>r.extend(d));let l=this.el.clientHeight||380;this.map.fitBounds(r,{padding:{top:Math.min(90,l/4),bottom:Math.min(70,l/5),left:60,right:60},maxZoom:9,duration:0})}openPopup(t,n,a=[0,0]){let s=this.data;this.popup?.remove();let o=[t.city,t.cc||t.country].filter(Boolean).join(", "),r=[...new Set(t.points.map(u=>u.person))],l=t.points.sort((u,c)=>Number(c.online)-Number(u.online)||c.ts-u.ts).map(u=>{let c=s.people.find(g=>g.id===u.person),x=c?.devices.find(g=>g.id===u.device);return e("button",{type:"button",class:"dl-pop-row",click:()=>this.cb.openDevice(u.person,u.device)},[e("span",{class:`dl-pop-dot${u.online?" on":""}`}),e("span",{class:"dl-pop-name"},[e("b",{},c?.name??u.person),` · ${x?.name??"device"}`]),e("span",{class:"dl-faint dl-nowrap"},u.online?"now":he(u.ts,s.now))])}),d=e("div",{class:"dl-pop"},[e("div",{class:"dl-pop-head"},[e("span",{class:"dl-pop-net"},b("globe")),e("div",{class:"dl-stack"},[e("strong",{},t.org||"Unknown network"),e("span",{class:"dl-faint"},[t.asn?`AS${t.asn} · `:"",o?`${o} · approximate`:"approximate location"])])]),e("div",{class:"dl-pop-list"},l),r.length===1?e("div",{class:"dl-pop-actions"},[e("button",{type:"button",class:"cbi-button cbi-button-positive important",click:()=>this.cb.openPerson(r[0])},`Open ${s.people.find(u=>u.id===r[0])?.name??"person"}`)]):""]),p=this.el.clientHeight||380;this.map.easeTo({center:n,offset:[0,Math.min(140,p*.32)],duration:300}),this.popup=new this.gl.Popup({offset:[a[0],a[1]-18],anchor:"bottom",closeButton:!1,focusAfterOpen:!1,maxWidth:"300px",className:"dl-popup"}).setLngLat(n).setDOMContent(d).addTo(this.map)}};function dt(i,t,n=!0){let a=[["online","Online now"],["24h","24h"],["7d","7 days"],["30d","30 days"]],s=e("div",{class:"dl-seg",role:"tablist"});for(let[o,r]of a)o==="online"&&!n||s.appendChild(e("button",{type:"button",role:"tab",class:o===i?"on":"","data-v":o,click:()=>{s.querySelectorAll("button").forEach(l=>l.classList.toggle("on",l.dataset.v===o)),t(o)}},r));return s}var He=null;function ce(i,t){let n=a=>{He??(He=document.body.appendChild(e("div",{class:"dl-tip dl-tip-float dl-root"}))),He.replaceChildren(...t().map(s=>typeof s=="string"?document.createTextNode(s):s)),He.style.display="",He.style.left=`${a.clientX}px`,He.style.top=`${a.clientY-10}px`};i.addEventListener("mouseenter",n),i.addEventListener("mousemove",n),i.addEventListener("mouseleave",()=>He&&(He.style.display="none"))}function dn(i,t=120,n=26){let a=Math.max(1,...i),s=e("div",{class:"dl-spark"});s.style.width=`${t}px`,s.style.height=`${n}px`;let o=Date.now();return i.forEach((r,l)=>{let d=e("i");d.style.height=`${Math.max(6,r/a*100)}%`,r||d.classList.add("zero");let p=i.length-1-l,u=new Date(o-p*864e5);ce(d,()=>[e("div",{class:"dl-tip-title"},p===0?"Today":p===1?"Yesterday":u.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})),e("div",{class:"dl-muted"},Q(r))]),s.appendChild(d)}),s}var pn=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"standard",title:"Standard",ic:"shield",stealth:2,speed:4,text:"Junk packets and random headers. Gets through most VPN blocking with no speed cost.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"strong",title:"Strong",ic:"shieldplus",stealth:3,speed:3,text:"More and larger junk packets for networks that block VPNs aggressively. Connects a little slower.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],We=i=>pn.find(t=>t.id===i),oa={v2:"Needs AmneziaWG 1.5 or newer on the router.",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."};function cn(i,t){return e("span",{class:"dl-dots",title:`${t}: ${i} of 4`},[e("span",{class:"dl-dots-label"},t),e("span",{class:"dl-dots-row"},[0,1,2,3].map(n=>e("i",{class:ndom.content(s,pn.map(r=>{let l=!r.needs||i[r.needs],d=r.id===t;return e("button",{type:"button",role:"radio","aria-checked":d?"true":"false","aria-disabled":l?null:"true",class:`dl-method${d?" on":""}${l?"":" off"}`,click:()=>{!l||d||(t=r.id,o(),n(r.id))}},[e("div",{class:"dl-method-head"},[e("span",{class:"dl-method-ic"},b(r.ic)),e("b",{},r.title),r.id===a?e("span",{class:"dl-pill ok"},"Current"):""]),e("p",{},r.text),e("div",{class:"dl-method-meters"},[cn(r.stealth,"Stealth"),cn(r.speed,"Speed")]),e("div",{class:"dl-method-foot"},l?[b("phone"),e("span",{},r.apps)]:[b("alert"),e("span",{},oa[r.needs])])])}));return o(),s}function Qe(i){return`${L.url("admin/network/dawnline/server")}?${i?`server=${encodeURIComponent(i)}&`:""}section=people`}function be(i,t){return`${L.url("admin/network/dawnline/person")}?id=${encodeURIComponent(i)}${t?`&device=${encodeURIComponent(t)}`:""}`}var ra={connect:"ok",disconnect:"",roam:"",device_added:"ok",device_removed:"",person_added:"",person_removed:"",paused:"warn",resumed:"ok",paused_all:"warn",resumed_all:"ok",portal_blocked:"bad",person_changed:"",devices_removed:"warn"},la={devices_removed:"trash",link_changed:"link",person_added:"plus",person_removed:"trash",person_changed:"edit",paused:"pause",resumed:"play",paused_all:"pause",resumed_all:"play"};function da(i,t){return t.device?i.people.flatMap(a=>a.devices).find(a=>a.id===t.device)?.kind??t.dkind??"other":la[t.type]??"activity"}var ca=["person_added","person_removed","person_changed","paused_all","resumed_all"];function xe(i){return i.by?i.by:ca.includes(i.type)||i.detail==="by admin"||i.detail?.endsWith(" (admin)")?"admin":i.detail?.endsWith(" (portal)")?"portal":null}function pa(i){return(i.detail??"").replace(/ \((admin|portal)\)$/,"").replace(/^by admin$/,"")}function Nt(i,t){let n=i.people.find(k=>k.id===t.person),a=n?.name??t.pname??t.person??"",s=n?.devices.find(k=>k.id===t.device)?.name??t.dname??"",o=k=>e("b",{},k),r=k=>e("span",{class:"dl-muted"},k),l=k=>e("span",{class:"dl-mono"},k),d=k=>t.hosts?.[k]?[e("span",{class:"dl-ev-host"},[e("b",{},t.hosts[k]),e("span",{class:"dl-faint"},` (${k})`)])]:[l(k)],p=k=>e("span",{class:"dl-ev-kind"},`${k} `),u=s?`${a} · ${s}`:a,c=pa(t),x=c||s||"a device",g=k=>[e("span",{class:"dl-you"},"You"),r(` ${k} `)];if(xe(t)==="admin")switch(t.type){case"device_added":return[...g("added"),p("device"),o(x),r(" for "),o(a)];case"device_removed":return[...g("removed"),p("device"),o(x),r(" from "),o(a)];case"paused":return[...g("paused"),p("person"),o(a)];case"resumed":return[...g("resumed"),p("person"),o(a)];case"device_changed":{let k=c.startsWith("renamed from ");return[...g(k?"renamed":c),p("device"),o(s||"a device"),r(" of "),o(a),...k?[r(` · was ${c.slice(13)}`)]:[]]}case"device_keys":return[...g("issued new keys for"),p("device"),o(x),r(" of "),o(a),r(" · it needs its new configuration")];case"link_changed":return[...g("issued a new link for"),p("person"),o(a),r(" · the old link stopped working")];case"paused_all":return[e("span",{class:"dl-you"},"You"),r(" paused everyone")];case"resumed_all":return[e("span",{class:"dl-you"},"You"),r(" resumed everyone")]}switch(t.type){case"connect":return[p("Device"),o(u),r(" connected"),...t.detail?[r(" from "),...d(t.detail)]:[],...t.where?[r(` · ${t.where}`)]:[]];case"disconnect":return[p("Device"),o(u),r(" went offline")];case"roam":return[p("Device"),o(u),r(" changed network "),...(t.detail??"").split(" → ").flatMap((k,G)=>G?[r(" → "),...d(k)]:d(k))];case"device_added":return[p("Person"),o(a),r(" added "),p("device"),o(x),...xe(t)==="portal"?[r(" on their portal")]:[]];case"device_removed":return[p("Person"),o(a),r(" removed "),p("device"),o(x),...xe(t)==="portal"?[r(" on their portal")]:[]];case"device_keys":return[p("Person"),o(a),r(" issued new keys for "),p("device"),o(x),r(" on their portal")];case"person_added":return[...g("added"),p("person"),o(t.detail??a)];case"person_removed":return[...g("removed"),p("person"),o(t.detail??a)];case"person_changed":return[...g("changed"),p("person"),o(a),...c?[r(` · ${c.replace(/_/g," ")}`)]:[]];case"paused":return[p("Person"),o(a),r(` paused — ${t.detail??""}`)];case"resumed":return[p("Person"),o(a),r(" resumed"),...t.detail&&t.detail!=="active"?[r(` — ${t.detail}`)]:[]];case"paused_all":return[r("Everyone paused")];case"resumed_all":return[r("Everyone resumed")];case"portal_blocked":return[e("b",{class:"dl-sys-src"},"Personal portal"),r(" blocked "),l(t.detail??""),r(" for 15 min after too many wrong codes")];case"devices_removed":return[p("Person"),o(a),r(" — all devices removed, end date reached")];default:return[r(`${t.type}${t.detail?`: ${t.detail}`:""}`)]}}var ha={portal_blocked:["globe","bad"]};function ua(i,t){if(i.servers.length<2||!t.person)return"";let n=i.people.find(s=>s.id===t.person),a=n&&i.servers.find(s=>s.id===n.server);return a?e("span",{class:"dl-ev-srv",title:"Server"},a.name):""}function Ie(i,t,n={}){let a=ha[t.type],s=xe(t);return e("div",{class:`dl-row${s==="admin"?" dl-ev-by-admin":a?` dl-ev-by-system ${a[1]}`:""}`},[s==="admin"?e("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},b("admin")):a?e("span",{class:"dl-ev-tile sys"},b(a[0])):e("span",{class:`dl-ev-tile ev ${ra[t.type]??""}`},b(da(i,t))),e("span",{class:"dl-row-main"},Nt(i,t)),n.server===!1?"":ua(i,t),e("span",{class:"dl-faint dl-nowrap",title:new Date(t.ts*1e3).toLocaleString()},he(t.ts,i.now))])}function ma(i){let t=[],n=(s,o)=>e("a",{href:s},o);for(let s of i.servers)s.enabled&&!s.up&&t.push({tone:"bad",text:[`Tunnel ${s.ifname} is down. `,n(L.url("admin/network/dawnline/diagnostics"),"Open Diagnostics")]});i.settings.paused_all&&t.push({tone:"warn",text:["Everyone is paused."]});for(let s of i.people)if(s.state==="quota")t.push({tone:"warn",text:[n(be(s.id),s.name)," reached the data limit."]});else if(s.state==="expired")t.push({tone:"warn",text:[n(be(s.id),s.name),"’s access has ended."]});else{let o=ze(s.expires);o!=null&&o>=0&&o<=Math.max(s.expire_warn,3)&&t.push({tone:"",text:[n(be(s.id),s.name),`’s access ends in ${o} day${o===1?"":"s"}.`]}),s.quota_limit&&s.quota_used>=s.quota_limit*.9&&t.push({tone:"",text:[n(be(s.id),s.name)," has used 90% of the data limit."]})}let a=i.people.flatMap(s=>s.devices.filter(o=>o.config_stale).map(o=>[s,o]));return a.length&&t.push({tone:"warn",text:a.length===1?[n(be(a[0][0].id,a[0][1].id),`${a[0][0].name} · ${a[0][1].name}`)," needs its configuration again."]:[`${a.length} devices need their configuration again (networks or DNS changed).`]}),i.servers.some(s=>s.lan_like)&&i.like_home.error&&t.push({tone:"warn",text:[`Internet through the LAN is off: ${i.like_home.error} `,n(L.url("admin/network/dawnline/diagnostics"),"Details")]}),i.settings.portal_enabled||t.push({tone:"",text:["The personal portal is off. ",n(L.url("admin/network/dawnline/settings"),"Turn on")]}),t}function ct(i,t){let n=i.servers.find(d=>d.id===t)??i.servers[0],a=i.people.filter(d=>d.server===n.id),s=new Set(a.map(d=>d.id)),o=a.flatMap(d=>d.devices),r=d=>a.reduce((p,u)=>{let c=d(u);return[p[0]+c[0],p[1]+c[1]]},[0,0]),l=n.series?.[n.series.length-1];return{...i,servers:[n],people:a,series:n.series??i.series,events:i.events.filter(d=>d.person?s.has(d.person):!0),geo:{...i.geo,points:i.geo.points.filter(d=>s.has(d.person))},totals:{people:a.length,devices:o.length,online:o.filter(d=>d.online).length,active:a.filter(d=>d.state==="active").length,today:l?[l.rx,l.tx]:[0,0],month:r(d=>d.month)}}}var pt=class{constructor(t,n){this.srvId=t;this.go=n;this.el=e("div",{class:"dl-srvov"});this.map=null;this.range="online";this.parts={};this.healthAt=0}mount(t){this.st=ct(t,this.srvId);for(let n of["health","bento","side","activity"])this.parts[n]=e("div",{});return dom.content(this.el,[this.parts.health,this.parts.bento,this.mapCard(),e("div",{class:"dl-grid2"},[this.parts.activity,this.parts.side])]),this.paint(),this.loadHealth(),this.el}update(t){this.st=ct(t,this.srvId),this.paint(),this.map?.update(this.mapData()),Date.now()-this.healthAt>6e4&&this.loadHealth()}async loadHealth(){this.healthAt=Date.now();let t=await z.health().catch(()=>null);if(!t)return;let n=t.checks.filter(o=>o.status==="warn"||o.status==="error");if(!n.length){dom.content(this.parts.health,"");return}let a=n.filter(o=>o.status==="error").length,s=`${n.length} ${a?n.length===1?"problem":"problems":n.length===1?"warning":"warnings"}`;dom.content(this.parts.health,e("div",{class:`dl-healthstrip ${a?"bad":"warn"}`},[e("span",{class:"dl-healthstrip-title"},[b("alert"),s]),...n.slice(0,3).map(o=>{let r=e("span",{class:"dl-healthstrip-item"},o.title);return ce(r,()=>[e("div",{class:"dl-tip-title"},o.title),e("div",{class:"dl-muted"},o.detail)]),r}),n.length>3?e("span",{class:"dl-sub"},`+${n.length-3} more`):"",e("a",{href:L.url("admin/network/dawnline/diagnostics")},n.some(o=>o.fix)?"Fix in Diagnostics →":"Open Diagnostics →")]))}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now}}mapCard(){let t=this.st,n=e("div",{class:"dl-panel-head pad"},[e("div",{class:"dl-stack"},[e("h3",{},"Where people connect from"),e("span",{class:"dl-sub"},"City-level, from the client IP · locations cached on the router")]),e("span",{class:"dl-spacer"}),dt(this.range,o=>{this.range=o,this.map?.setRange(o)})]);if(!t.geo.enabled)return e("div",{class:"dl-panel flush"},[n,e("div",{class:"dl-map-off"},["Locations are off. ",e("a",{href:L.url("admin/network/dawnline/settings")},"Turn them on in Settings"),"."])]);this.map=new qe({openPerson:o=>location.href=be(o),openDevice:(o,r)=>location.href=be(o,r)},this.range);let a=e("div",{class:"dl-map-legend"},[e("span",{},[e("i",{class:"dot ok"}),"Online"]),e("span",{},[e("i",{class:"dot"}),"Seen recently"]),e("span",{},[e("i",{class:"line"}),"Live tunnel"])]),s=e("div",{class:"dl-map-wrap"},[this.map.el,a]);return requestAnimationFrame(()=>this.map.mount(this.mapData())),e("div",{class:"dl-panel flush"},[n,s])}paint(){let t=this.st,n=t.servers[0],a=t.people.reduce((l,d)=>l+Math.max(0,d.device_limit-d.devices.length),0),s=t.people.flatMap(l=>l.devices.filter(d=>d.online));dom.content(this.parts.bento,e("div",{class:"dl-bento"},[this.onlineTile(s),this.speedTile(),this.disguiseTile(n),this.monthTile(a)]));let o=ma(t);dom.content(this.parts.side,e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Needs attention"),e("span",{class:"dl-spacer"}),e("a",{href:L.url("admin/network/dawnline/diagnostics")},"Health")]),o.length?o.slice(0,8).map(l=>e("div",{class:"dl-attn-item dl-row"},[e("span",{class:`dl-ev-dot ${l.tone}`}),e("span",{},l.text)])):e("div",{class:"dl-row dl-muted"},[b("check"),"All good. Nothing needs you right now."])]));let r=[...t.events].reverse().slice(0,8);dom.content(this.parts.activity,e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-spacer"}),e("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},"View all")]),r.length?r.map(l=>Ie(t,l)):e("div",{class:"dl-row dl-muted"},"Nothing yet. Connections, new devices and pauses appear here.")]))}onlineTile(t){let n=this.st,a=12,s=I=>I.spark[I.spark.length-1]??0,o=I=>n.geo.points.find(_=>_.device===I.id&&_.city)?.city,r=I=>/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(I.endpoint??""),l=I=>(r(I)?"home":o(I))??"",d=I=>[...n.events].reverse().find(_=>_.type==="connect"&&_.device===I.id)?.ts??0,p=n.people.map(I=>({p:I,devs:I.devices.filter(_=>_.online).sort((_,N)=>s(N)-s(_))})).filter(I=>I.devs.length).sort((I,_)=>_.devs.reduce((N,C)=>N+s(C),0)-I.devs.reduce((N,C)=>N+s(C),0)),u=p.length<=2,c=({p:I,devs:_})=>{let N=_.map(d).filter(Boolean),C=N.length?Math.min(...N):0,D=(I.rate??[]).slice(-15),$=D[D.length-1],A=$&&n.now-$[0]<180?$:null,m=200,h=30,P=Math.max(1,...D.map(v=>Math.max(v[1],v[2]))),f=v=>D.map((U,q)=>`${D.length>1?q/(D.length-1)*m:m},${h-2-U[v]/P*(h-6)}`),S=D.length>1?Pe(``):"",j=!A||A[1]<64&&A[2]<64,W=I.access==="both"?["home","globe"]:I.access==="lan"?["home"]:["globe"];return[e("div",{class:"dl-hc"},[e("div",{class:"dl-hc-head"},[e("span",{class:"dl-onl-av sm"},Re(I.name)),e("span",{class:"dl-stack"},[e("b",{},I.name),e("span",{class:"dl-hc-since"},C?`online for ${he(C,n.now).replace(" ago","")}`:"online")]),e("span",{class:"dl-hc-reach"},W.map(v=>e("span",{class:`dl-ibadge ${v==="home"?"lan":"inet"}`},b(v))))]),e("div",{class:"dl-hc-speed"},[e("div",{class:"dl-hc-speed-row"},j?[e("span",{class:"dl-faint"},"Idle right now")]:[e("span",{},[e("span",{class:"dl-dn"},"↓"),` ${$e(A[2])}`]),e("span",{},[e("span",{class:"dl-up"},"↑"),` ${$e(A[1])}`]),e("span",{class:"dl-spacer"}),e("span",{class:"dl-faint"},"15 min")]),S]),e("div",{class:"dl-hc-devs"},_.map(v=>e("span",{class:"dl-hc-dev"},[b(v.kind),[v.name,l(v)].filter(Boolean).join(" · ")]))),e("div",{class:"dl-hc-foot"},[e("span",{class:"dl-faint"},`${Q(_.reduce((v,U)=>v+s(U),0))} today · ${Q(I.month[0]+I.month[1])} this month`)])])]},x=I=>{let{p:_,devs:N}=I,C=e("span",{class:"dl-onl-dev"},N.length>1?String(N.length):b(N[0].kind)),D=e("a",{class:`dl-onl-p${u?"":" sm"}`,href:be(_.id),"aria-label":`${_.name}, online`},[e("span",{class:"dl-onl-av"},[Re(_.name),C]),u?e("span",{class:"dl-onl-name"},_.name):"",u?e("span",{class:"dl-onl-meta"},[...N.slice(0,3).map($=>b($.kind)),N.length>3?`+${N.length-3}`:"",l(N[0])?e("span",{},` · ${l(N[0])}`):""]):""]);return ce(D,()=>c(I)),D},g=e("b",{class:`dl-onl-count${p.length?"":" none"}`},String(p.length)),k=p.reduce((I,_)=>I+_.devs.length,0);p.length&&ce(g,()=>[`${p.length} ${p.length===1?"person":"people"} · ${k} device${k===1?"":"s"}`]);let G=p.length>a?p.slice(0,a-1):p,K=n.people.flatMap(I=>I.devices.map(_=>({p:I,d:_}))).filter(I=>I.d.handshake).sort((I,_)=>_.d.handshake-I.d.handshake)[0];return e("div",{class:"dl-bento-tile online"},[e("div",{class:"dl-bento-head"},[e("span",{class:"dl-metric-label"},"Online"),g]),p.length?e("div",{class:`dl-onl-row${u?"":" grid"}`},[...G.map(x),p.length>a?e("a",{class:"dl-onl-p sm more",href:`${L.url("admin/network/dawnline/server")}?server=${encodeURIComponent(this.srvId)}§ion=people&filter=online`,title:"Everyone online",click:I=>{this.go&&(I.preventDefault(),this.go("people","online"))}},[e("span",{class:"dl-onl-av"},`+${p.length-G.length}`)]):""]):e("div",{class:"dl-onl-empty"},[e("span",{},"Nobody is connected"),K?e("span",{class:"dl-sub"},`Last: ${K.p.name}, ${he(K.d.handshake,n.now)}`):e("span",{class:"dl-sub"},"No device has connected yet")])])}speedTile(){return zt(this.st.servers[0]?.rate??[],this.st.now,this.st.totals.today)}disguiseTile(t){let n=We(t.preset),a=t.obf??{},s=(l,d)=>e("span",{class:`dl-segs ${d}`},[0,1,2,3].map(p=>e("i",{class:p+a[l]).map(l=>`${l.toUpperCase()} ${a[l]}`);return r.length&&o.push(r.slice(0,2).join(" · ")+(r.length>2?` +${r.length-2}`:"")),["h1","h2","h3","h4"].some(l=>a[l]&&a[l]!==String(["h1","h2","h3","h4"].indexOf(l)+1))&&o.push("H1–H4 random"),a.i1&&o.push(a.i1.includes("0x8580")?"DNS-like first packet":"Signature packets"),a.header_protection_key&&o.push("Encrypted headers"),o.length||o.push(n?.id==="off"?"Plain WireGuard":"No values yet"),e("div",{class:"dl-bento-tile dl-disg"},[e("div",{class:"dl-bento-head"},[e("span",{class:"dl-metric-label"},"Disguise"),e("a",{href:`${L.url("admin/network/dawnline/server")}?server=${encodeURIComponent(t.id)}§ion=disguise`},"Change")]),e("div",{class:"dl-disg-id"},[e("span",{class:"dl-disg-ic"},b(n?.ic??"shield")),e("span",{class:"dl-stack"},[e("b",{},n?n.title:"Custom"),e("span",{class:"dl-sub"},n?n.short:"Set by hand")])]),n?e("div",{class:"dl-disg-meters"},[e("span",{},"Stealth"),s(n.stealth,"acc"),e("span",{},"Speed"),s(n.speed,"ok")]):"",e("div",{class:"dl-disg-chips"},o.map(l=>e("span",{},l)))])}monthTile(t){let n=this.st.totals,a=this.st.people.filter(s=>s.state!=="active").length;return Rt(this.st.series,`${n.people} ${n.people===1?"person":"people"}${a?` · ${a} paused`:""} · ${t} device slot${t===1?"":"s"} free`)}};function zt(i,t,n){let a=i.slice(-15),s=a[a.length-1],o=s&&t-s[0]<180,r=o?s[2]:0,l=o?s[1]:0,[d,p]=n,u=200,c=40,x=Math.max(1,...a.map(_=>Math.max(_[1],_[2]))),g=_=>a.map((N,C)=>`${a.length>1?C/(a.length-1)*u:u},${c-2-N[_]/x*(c-6)}`),k=g(2),G=g(1),K=a.length>1?Pe(``):e("div",{class:"dl-speed-wait"},[e("i"),e("span",{},"Collecting… 1 point a minute")]),I=(_,N,C,D)=>e("div",{class:"dl-speed-col"},[e("span",{class:"dl-sub"},[e("span",{class:C},N),` ${_}`]),e("span",{class:"dl-speed-val"},$e(D))]);return a.length>1&&ce(K,()=>{let _=a[a.length-1];return[e("div",{class:"dl-tip-title"},new Date(_[0]*1e3).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})),e("div",{},`↓ ${$e(_[2])} · ↑ ${$e(_[1])}`)]}),e("div",{class:"dl-bento-tile"},[e("div",{class:"dl-bento-head"},[e("span",{class:"dl-metric-label"},"Speed now"),e("span",{class:"dl-sub"},"last 15 min")]),e("div",{class:"dl-speed-cols"},[I("Download","↓","dl-dn",r),I("Upload","↑","dl-up",l)]),K,e("div",{class:"dl-speed-today"},[e("span",{},["Today ",e("b",{},Q(d+p))]),e("span",{},[e("span",{class:"dl-dn"},"↓"),` ${Q(p)} `,e("span",{class:"dl-up"},"↑"),` ${Q(d)}`])])])}function Rt(i,t){let n=i.slice(-30),a=n.map(p=>p.rx+p.tx),s=Math.max(1,...a),o=a.reduce((p,u)=>p+u,0),r=a.reduce((p,u,c)=>u>a[p]?c:p,0),l=p=>new Date(`${p}T12:00:00`).toLocaleDateString("en-GB",{day:"numeric",month:"short"}),d=e("div",{class:"dl-bento-bars"},n.map((p,u)=>{let c=a[u],x=e("i",{class:u===n.length-1?"hi":"",style:`height:${Math.max(4,c/s*100)}%`});return ce(x,()=>[e("div",{class:"dl-tip-title"},u===n.length-1?`Today · ${l(p.day)}`:l(p.day)),e("div",{},Q(c)),e("div",{class:"dl-muted dl-mono"},`↓ ${Q(p.tx)} ↑ ${Q(p.rx)}`)]),x}));return e("div",{class:"dl-bento-tile month"},[e("div",{class:"dl-bento-head"},[e("span",{},[e("span",{class:"dl-metric-label"},"Last 30 days"),e("b",{class:"dl-bento-total"},Q(o))]),a[r]>0?e("span",{class:"dl-sub"},`peak ${Q(a[r])} · ${l(n[r].day)}`):""]),n.length?d:e("p",{class:"dl-muted"},"No traffic yet."),e("div",{class:"dl-bento-head"},[e("span",{class:"dl-sub"},n.length?l(n[0].day):""),e("span",{class:"dl-sub"},t),e("span",{class:"dl-sub"},"today")])])}var ga={connect:"connections",disconnect:"connections",roam:"connections",device_added:"people",device_removed:"people",devices_removed:"people",device_changed:"people",device_keys:"people",link_changed:"people",person_added:"people",person_removed:"people",person_changed:"people",paused:"people",resumed:"people",paused_all:"people",resumed_all:"people",portal_blocked:"problems"},Ze=["connections","people","problems"],Ge={connections:"Connections",people:"People",problems:"Problems"},hn={connections:"Connects, disconnects and IP changes",people:"People and their devices added, changed, paused, removed",problems:"Blocked portal sign-ins (tunnels and services are in the service log)"},ht=i=>ga[i]??"problems";function fa(i){let t=new Map(i.people.map(a=>[a.id,a.name])),n=new Map(i.people.flatMap(a=>a.devices.map(s=>[s.id,s.name])));return{people:t,devices:n}}function va(i){let t=i==null?"":String(i);return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}var ut={awg:"AmneziaWG",dawnline:"Dawnline",portal:"Portal"};function Le(i,t,n,a="",s=[]){let o=fa(i),r=[...t.map(c=>({ts:c.ts,category:ht(c.type),type:c.type,person:c.person?o.people.get(c.person)??c.pname??c.person:"",device:c.device?o.devices.get(c.device)??c.dname??c.device:"",detail:c.detail??"",where:c.where??"",by:xe(c)??""})),...s.map(c=>({ts:c.ts,category:"system",type:`${c.src}.${c.level}`,person:"",device:"",detail:`${c.who?`${c.who} `:""}${c.msg}${c.detail?` -${c.detail}`:""}`,where:ut[c.src]??c.src,by:""}))].sort((c,x)=>c.ts-x.ts).map(({ts:c,...x})=>({time:new Date(c*1e3).toISOString(),...x})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${a?`-${a}`:""}-${l}.${n}`;if(n==="json"){ve(d,JSON.stringify(r,null,2),"application/json");return}let p=["time","category","type","person","device","detail","where","by"],u=[p.join(","),...r.map(c=>p.map(x=>va(c[x])).join(","))].join(` -`);ve(d,u,"text/csv")}var ba=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]];function Te(i,t,n,a,s,o=!1){let r=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...Ze.map(d=>e("option",{value:d,selected:d===s?"selected":null},Ge[d])),o?e("option",{value:"system",selected:s==="system"?"selected":null},"System"):""]),l=e("select",{class:"cbi-input-select"},ba.map(([d,p])=>e("option",{value:d},p)));ne(i,[e("p",{class:"dl-muted"},`${t} This cannot be undone; export first if you want a copy.`),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Category"),r]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Which events"),l])],[e("button",{class:"cbi-button cbi-button-neutral",click:Z},"Cancel")," ",R("Clear",async()=>{let d=await O(async()=>{let p=o&&(r.value==="system"||r.value==="")?await z.serviceLogClear(l.value):{removed:0},u=r.value==="system"?{removed:0}:await z.logsClear({...n,category:r.value,older_days:l.value});return{removed:p.removed+u.removed}});d&&(Z(),te(d.removed?`${d.removed} event${d.removed===1?"":"s"} removed`:"Nothing matched","success",3e3),a())},"negative")])}function Fe(i,t,n,a){let s=i==="device"?`Clears ${n}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:i==="person"?`Clears ${n}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";ne(i==="all"?"Reset all traffic history?":`Reset traffic history for ${n}?`,[e("p",{class:"dl-muted"},s)],[e("button",{class:"cbi-button cbi-button-neutral",click:Z},"Cancel")," ",R("Reset",async()=>{await O(()=>z.usageClear(i,t),"Traffic history reset")&&(Z(),a())},"negative")])}var mt=null;function xa(i){return i?new Date(i*1e3).toLocaleString("en-GB",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function un(i,t,n=!1){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},i),e("button",{type:"button",class:`dl-kvrow-v copy${n?" dl-mono":""}`,title:"Copy",click:()=>pe(t,`${i} copied`)},[e("span",{},t),b("copy")])])}function gt(i,t){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},i),e("span",{class:"dl-kvrow-v"},t)])}function mn(i,t){if(/^\s*\[.+\]\s*$/.test(i))return e("span",{class:"dl-conf-sec"},i);let n=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(i);if(!n)return document.createTextNode(i);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(i);return e("span",{},[e("span",{class:"dl-conf-k"},n[1])," ",a&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):n[2]])}function wa(i){let t=!1,n=e("pre",{class:"dl-conf"}),a=()=>dom.content(n,i.conf.split(` -`).flatMap((r,l)=>l?[` -`,mn(r,t)]:[mn(r,t)])),s=e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),t=!t,dom.content(s,[b(t?"x":"key"),t?"Hide key":"Show key"]),a()}},[b("key"),"Show key"]);a();let o=new Blob([i.conf]).size;return e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-filecard"},[e("span",{class:"dl-filecard-ic"},".conf"),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono dl-ellipsis"},i.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${o} bytes · import it in the app`)]),R([b("download")," Download"],()=>ve(i.filename,i.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[b("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),s,e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),pe(i.conf,"Configuration copied")}},[b("copy"),"Copy"])]),n])])}async function Ht(i,t="file"){if(!i.has_private_key)return e("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let n=await sn(i,`${i.server} · ${i.person} · ${i.name}`),a={qr:()=>e("div",{class:"dl-qr-pane"},[Pe(Oe(i.conf),"dl-qr"),e("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-linkbox"},[e("span",{class:"dl-mono"},n),R("Copy",()=>pe(n,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>wa(i)},s=e("div",{class:"dl-connect-body"}),o=e("div",{class:"dl-seg"}),r=l=>{o.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(s,a[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])o.appendChild(e("button",{type:"button","data-id":l,click:()=>r(l)},d));return r(t),e("div",{class:"dl-stack gap12"},[o,s])}function ya(i,t,n,a){mt?.close();let s=e("aside",{class:"dl-drawer",role:"dialog","aria-modal":"true"},[e("div",{class:"dl-drawer-head"},[i,e("button",{type:"button",class:"dl-drawer-x","aria-label":"Close",click:()=>l()},b("x"))]),e("div",{class:"dl-drawer-body"},t),n?e("div",{class:"dl-drawer-foot"},n):""]),o=e("div",{class:"dl-drawer-overlay dl-root",click:p=>{p.target===o&&l()}},s),r=p=>{p.key==="Escape"&&!document.body.classList.contains("modal-overlay-active")&&l()};function l(){document.removeEventListener("keydown",r),o.classList.remove("open"),setTimeout(()=>o.remove(),220),mt===d&&(mt=null),a()}let d={close:l,panel:s};return document.addEventListener("keydown",r),document.body.appendChild(o),requestAnimationFrame(()=>o.classList.add("open")),mt=d,d}var gn={connect:["ok","Connected","plug"],disconnect:["","Went offline","plug"],roam:["","Changed network","network"],device_added:["ok","Added","plus"],device_removed:["","Removed","trash"],device_keys:["","New keys","reset"]};function ka(i,t){let n=i.filter(a=>a.device===t&&gn[a.type]).reverse().slice(0,12);return n.length?e("div",{class:"dl-dev-log"},n.map(a=>{let[s,o,r]=gn[a.type],l=a.type==="connect"?[a.detail?e("span",{class:"dl-muted"},` from ${a.detail}`):"",a.where?e("span",{class:"dl-muted"},` · ${a.where}`):""]:a.type==="roam"?[e("span",{class:"dl-muted"},` · ${a.detail??""}`)]:a.type==="device_added"||a.type==="device_removed"||a.type==="device_keys"?[e("span",{class:"dl-muted"},xe(a)==="portal"?" on the portal":xe(a)==="admin"?" by you":"")]:[],d=new Date(a.ts*1e3);return e("div",{class:`dl-dev-log-row${xe(a)==="admin"?" dl-ev-by-admin":""}`},[xe(a)==="admin"?e("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},b("admin")):e("span",{class:`dl-ev-tile ev ${s}`},b(r)),e("span",{class:"dl-row-main"},[e("span",{},o),...l]),e("span",{class:"dl-faint dl-nowrap",title:d.toLocaleString()},he(a.ts))])})):e("div",{class:"dl-sub"},"No activity yet.")}function $a(i){return i.disabled?e("span",{class:"dl-dstat"},"Disabled"):i.online?e("span",{class:"dl-dstat ok"},"Connected"):i.handshake?e("span",{class:"dl-dstat"},`Last seen ${he(i.handshake)}`):e("span",{class:"dl-dstat warn"},"Waiting for the first connection")}async function Ce(i,t,n,a){let s=await O(()=>z.deviceConfig(t.id));if(!s)return;let o=t,r=i,l=await Ht(s),d=e("div",{class:"dl-drawer-title"}),p=e("div",{}),u=e("div",{}),c=e("div",{},e("div",{class:"dl-sub"},"Loading…")),x=[],g=async()=>{let h=await z.events(5e3).catch(()=>null);h&&(x=h.events.filter(P=>P.device===o.id),dom.content(c,ka(h.events,o.id)))},k=()=>{let h=a?.points.find(f=>f.device===o.id&&f.ip===o.endpoint);dom.content(d,[e("span",{class:`dl-dcard-ic${o.online?" on":""}`},b(o.kind)),e("div",{class:"dl-stack"},[e("div",{class:"dl-title-row"},[e("h3",{},o.name),R([b("edit")],()=>K(),"neutral",{title:"Rename",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),e("span",{class:"dl-sub"},[`${r.name} · ${Se[o.kind]}`])])]);let P=o.spark.reduce((f,S)=>f+S,0);dom.content(p,e("div",{class:"dl-dstats"},[e("div",{class:"dl-dstats-cell wide"},[e("span",{class:"dl-metric-label"},"Status"),$a(o)]),e("div",{class:"dl-dstats-cell"},[e("span",{class:"dl-metric-label"},"This month"),e("b",{},Q(o.month[0]+o.month[1])),e("span",{class:"dl-sub dl-mono"},`↓ ${Q(o.month[1])} ↑ ${Q(o.month[0])}`)]),e("div",{class:"dl-dstats-cell"},[e("span",{class:"dl-metric-label"},"Last 7 days"),e("b",{},Q(P)),dn(o.spark,120,22)])])),dom.content(u,e("div",{class:"dl-kv2"},[un("Tunnel address",o.address),o.hostname&&r.access!=="internet"?un("Local address",o.hostname):"",o.endpoint?gt("Client IP",e("span",{},[o.endpoint,h?e("span",{class:"dl-muted"},` · ${[h.city,h.org].filter(Boolean).join(" · ")}`):""])):"",gt("Total",e("span",{class:"dl-kv-act"},[`↓ ${Q(o.total[1])} · ↑ ${Q(o.total[0])}`,e("button",{type:"button",class:"dl-linkbtn danger",click:()=>Fe("device",o.id,o.name,()=>setTimeout(G,300))},"Reset")])),gt("Added",`${xa(o.created)} · ${o.created_by==="portal"?"from the portal":"by you"}`),gt("Public key",e("span",{class:"dl-mono dl-faint"},s.amnezia.client_pub_key?`${s.amnezia.client_pub_key.slice(0,16)}…`:"—"))])),dom.content(I,[R([b(o.disabled?"play":"pause"),o.disabled?" Enable":" Disable"],async()=>{await O(()=>z.deviceUpdate(o.id,void 0,!o.disabled),o.disabled?"Device enabled":"Device disabled")&&await G()},"neutral",o.disabled?{}:{class:"cbi-button cbi-button-neutral dl-btn-warn"}),R([b("key")," New keys"],async()=>{if(!await oe("Generate new keys?","The current configuration on this device stops working until it is imported again.","Generate",!0))return;if(await O(()=>z.deviceRotate(o.id),"New keys generated")){n(),m.close();let S=await z.status(1),j=S.people.find(v=>v.id===r.id),W=j?.devices.find(v=>v.id===o.id);j&&W&&Ce(j,W,n,S.geo)}}),e("span",{class:"dl-spacer"}),R([b("trash")," Remove"],async()=>{await oe(`Remove ${o.name}?`,"The device is disconnected immediately and its configuration stops working.","Remove",!0)&&await O(()=>z.deviceDelete(o.id),"Device removed")&&(m.close(),n())},"negative")])},G=async()=>{let h=await z.status(1).catch(()=>null),P=h?.people.find(S=>S.id===r.id),f=P?.devices.find(S=>S.id===o.id);!h||!P||!f||(r=P,o=f,a=h.geo,k(),n())},K=()=>{let h=e("input",{type:"text",class:"cbi-input-text",value:o.name,maxlength:48});ne(`Rename ${o.name}`,[e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},"Name"),e("div",{class:"cbi-value-field"},h)])],[e("button",{class:"cbi-button cbi-button-neutral",click:Z},"Cancel")," ",R("Save",async()=>{await O(()=>z.deviceUpdate(o.id,h.value,void 0),"Renamed")&&(Z(),await G())},"positive")]),setTimeout(()=>h.select(),50)},I=e("div",{class:"dl-drawer-actions"}),_=e("section",{class:"dl-dsec"},[e("div",{class:"dl-dsec-head"},[e("h4",{},"Connect")]),o.config_stale?e("div",{class:"dl-note warn"},[b("alert"),e("span",{},"This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below.")]):"",l]),N=e("section",{class:"dl-dsec"},[e("div",{class:"dl-dsec-head"},[e("h4",{},"Activity"),e("div",{class:"dl-dsec-actions"},[e("button",{type:"button",class:"dl-linkbtn",click:()=>Le({people:[r]},x,"csv",o.id)},"Export"),e("button",{type:"button",class:"dl-linkbtn danger",click:()=>Te(`Clear ${o.name}'s activity`,`Removes events about ${o.name}.`,{device:o.id},g)},"Clear"),e("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},"All activity")])]),c]),C=e("section",{class:"dl-dsec"},[e("div",{class:"dl-dsec-head"},e("h4",{},"Details")),u]),D=!o.handshake||o.config_stale,$=e("div",{class:"dl-stack gap16"},D?[p,_,C,N]:[p,C,N,_]);g();let A=window.setInterval(()=>{G(),g()},8e3),m=ya(d,$,I,()=>clearInterval(A));k()}function Ke(i,t){let n=e("input",{type:"text",class:"cbi-input-text",placeholder:Se.phone,maxlength:48}),a="phone",s=e("div",{class:"dl-kinds",role:"radiogroup","aria-label":"Type"},rn.map(r=>e("button",{type:"button",role:"radio",class:r===a?"on":"","aria-checked":r===a?"true":"false","data-kind":r,click:()=>{a=r,s.querySelectorAll("button").forEach(l=>{let d=l.dataset.kind===r;l.classList.toggle("on",d),l.setAttribute("aria-checked",d?"true":"false")}),n.placeholder=Se[r]}},[b(r),e("span",{},Se[r])]))),o=i.devices.length>=i.device_limit;ne(`Add a device for ${i.name}`,[o?e("p",{class:"dl-hint"},`${i.name} already has ${i.devices.length} of ${i.device_limit} devices. As admin you can still add one.`):"",e("div",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Type"),s]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Name"),n])],[e("button",{class:"cbi-button cbi-button-neutral",click:Z},"Cancel")," ",R("Add device",async()=>{let r=n.value.trim()||n.placeholder.replace(/^e\.g\. /,""),l=await O(()=>z.deviceCreate(i.id,r,a));if(!l)return;Z(),te(`${r} added`,"success",3e3),t();let d=await z.status(1),p=d.people.find(c=>c.id===i.id),u=p?.devices.find(c=>c.id===l.id);p&&u&&Ce(p,u,t,d.geo)},"positive")]),setTimeout(()=>n.focus(),50)}var Me=1080,et=1512,ye=96,_a="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",Sa="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",Xe=i=>i.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]);function La(i,t,n){let a=new URL(n),s=a.pathname.slice(1),o=Math.min(92,Math.floor((Me-2*ye)/(.58*(4+i.name.length)))),r=Me-2*ye,l=392,d=40,p=Oe(n,2).replace("`${G}`;return``+u(ye+82,ye+42,36,"#a3a3a3",Xe(t))+u(ye,276,o,"#ffffff",`Hi, ${Xe(i.name)}`,'font-weight="600"')+u(ye,340,40,"#8a8a8a",`Scan to connect to ${Xe(t)}`)+``+p+`${Xe(s)}`+u(Me/2,l+r+156,34,"#737373",Xe(a.host),'text-anchor="middle"')+""}async function Ma(i){let t=new Image;t.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(i)}`,await t.decode();let n=document.createElement("canvas");return n.width=Me,n.height=et,n.getContext("2d").drawImage(t,0,0,Me,et),new Promise((a,s)=>n.toBlob(o=>o?a(o):s(new Error("Could not draw the card")),"image/png"))}async function tt(i,t,n={}){if(!i.link){te("The personal portal is off. Turn it on in Settings.","warning");return}let a=i.link,s=await O(()=>Ma(La(i,t,a)));if(!s)return;let o=new File([s],`${i.id}-invite.png`,{type:"image/png"}),r=URL.createObjectURL(s),l=navigator,d=!!l.canShare?.({files:[o]}),p=()=>{URL.revokeObjectURL(r),Z()},u=d?R([b("link")," Share card"],async()=>{try{await l.share({files:[o],title:`Invite ${i.name}`})}catch{}},"positive"):R([b("download")," Download card"],()=>ve(o.name,s),"positive");ne(n.title??`Invite ${i.name}`,e("div",{class:"dl-invite"},[e("img",{src:r,alt:`Invite card for ${i.name}`}),e("div",{class:"dl-invite-side"},[e("p",{class:"dl-muted"},n.lead??`Send ${i.name} the card or the link. They open it, add their devices and connect — no account needed.`),e("button",{type:"button",class:"dl-invite-link",title:"Copy link",click:()=>pe(a,"Personal link copied")},[e("span",{},a.replace(/^https:\/\//,"")),b("copy")]),...(i.links??[]).filter(c=>c!==a).map(c=>e("button",{type:"button",class:"dl-invite-link alt",title:"Copy this link",click:()=>pe(c,"Link copied")},[e("span",{},c.replace(/^https?:\/\//,"")),e("span",{class:`dl-pill ${c.startsWith("http:")?"warn":""}`},c.startsWith("http:")?"HTTP":"Also"),b("copy")])),e("ol",{class:"dl-invite-steps"},[e("li",{},["Install ",e("b",{},"AmneziaVPN")," on the device"]),e("li",{},"Open the link or scan the code"),e("li",{},"Add the device and connect")]),e("div",{class:"dl-invite-actions"},[u,R([b("copy")," Copy link"],()=>pe(a,"Personal link copied"))])])]),[e("button",{class:"cbi-button cbi-button-neutral",click:p},"Done")],"wide")}var Ea={active:"",paused:"pause",paused_all:"pause",expired:"calendar",quota:"chart",hours:"clock",no_server:"alert"};function It(i){if(i.state==="active")return"";let t=e("span",{class:`dl-ibadge ${Da(i)}`,"aria-label":At[i.state]},b(Ea[i.state]||"alert"));return ce(t,()=>[e("div",{class:"dl-tip-title"},At[i.state])]),t}function Ta(i){let t=i.devices.length,n=Math.max(1,i.device_limit,t),a=Math.min(160,n*22+(n-1)*3);return e("div",{class:"dl-slotbar",title:`${t} of ${i.device_limit} devices`},[e("span",{class:"dl-slotbar-segs",style:`width: ${a}px`},Array.from({length:n},(s,o)=>e("i",{class:o>=i.device_limit?"over":oe("span",{class:`dl-ibadge ${a}`},b(a==="lan"?"home":"globe"))));return ce(n,()=>[e("div",{class:"dl-tip-title"},Ue[i.access]),i.access==="lan"&&i.services?.length?e("div",{class:"dl-muted"},`${i.services.length} home service${i.services.length===1?"":"s"} only`):""]),n}function Da(i){return i.state==="active"?"ok":i.state==="quota"||i.state==="expired"?"bad":"warn"}function Aa(i,t){let n=i,s=e("div",{class:"dl-choices"},[{v:"internet",ic:"globe",text:"Browse the internet through your router. No access to devices at home."},{v:"lan",ic:"home",text:"Reach devices at home (NAS, printer, cameras). Internet stays on their own connection."},{v:"both",ic:"shield",text:"Home devices and the internet, all through your router."}].map(o=>e("button",{type:"button",class:`dl-choice${o.v===n?" selected":""}`,"data-v":o.v,click:()=>{n=o.v,s.querySelectorAll(".dl-choice").forEach(r=>r.classList.toggle("selected",r.dataset.v===o.v)),t?.(o.v)}},[e("span",{class:"dl-choice-title"},[b(o.ic),Ue[o.v]]),e("span",{class:"dl-choice-text"},o.text)])));return{el:s,get:()=>n}}function Pa(i){return`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")}`}function fn(i){let t=ze(i.expires);return i.state==="quota"||i.state==="expired"||t!=null&&t<=Math.max(i.expire_warn,3)||!!i.quota_limit&&i.quota_used>=i.quota_limit*.9}function Na(i){let t=i?new Date(`${i}T12:00:00`):new Date,n=t.getTime()t===new URLSearchParams(location.search).get("filter"))??"all";this.sort="seen";this.noFooter=!0;this.serverId=null;this.polling=!1;this.el=null;this.statusSeq=0;this.statusShown=0}async load(){return z.status(30)}scope(t){return this.serverId?ct(t,this.serverId):t}embed(t,n){return this.serverId=n,this.render(t)}person(t){return this.st.people.find(n=>n.id===t)}async latestStatus(){let t=++this.statusSeq,n=await z.status(30).catch(()=>null);return!n||te("em",{},n.servers.length?"No people yet. Add someone and send them their personal link.":"Set up the server first, then add people."),a.serverId&&(r.filter=l=>a.st.people.some(d=>d.id===l)),r.handleAdd=()=>a.openCreate(),r.handleRemove=l=>a.remove(l),r.renderRowActions=()=>e("div",{class:"dl-none"}),s=r.option(form.DummyValue,"_card"),s.modalonly=!1,s.textvalue=l=>a.renderCard(e("div",{class:"dl-card",id:`dl-card-${l}`}),l),o.render().then(l=>{l.classList.add("dl-map","dl-root");let d=e("select",{class:"dl-select","aria-label":"Sort",change:u=>{a.sort=u.target.value,a.decorate()}},[e("option",{value:"seen"},"Last seen"),e("option",{value:"name"},"Name"),e("option",{value:"usage"},"Usage")]),p=e("div",{class:"dl-root"},[a.serverId?"":e("div",{class:"dl-pagehead"},[e("div",{class:"dl-stack"},[e("h2",{class:"dl-h1"},"People"),e("span",{class:"dl-muted",id:"dl-people-count"},this.countText())]),n.servers.length?R([b("plus")," Add person"],()=>a.openCreate(),"add"):""]),n.servers.length?"":e("div",{class:"alert-message warning"},["No server yet. ",e("a",{href:L.url("admin/network/dawnline/server")},"Run the setup wizard")," before adding people."]),e("div",{class:"dl-toolbar"},[e("div",{class:"dl-seg",id:"dl-people-tabs",role:"tablist"}),e("div",{class:"dl-toolbar-end"},[d,a.serverId?R([b("plus")," Add person"],()=>a.openCreate(),"add"):""])]),l]);return this.el=p,requestAnimationFrame(()=>this.decorate()),this.polling||(this.polling=!0,poll.add(()=>a.el?.isConnected?a.poll():Promise.resolve(),10)),!vn&&new URLSearchParams(location.search).get("add")&&(vn=!0,setTimeout(()=>a.openCreate(),100)),p})}countText(){let t=this.st.totals;return`${t.people} ${t.people===1?"person":"people"} · ${t.devices} device${t.devices===1?"":"s"} · ${t.online} online`}decorate(){let t=document.getElementById("dl-people-count");t&&(t.textContent=this.countText());let n=this.st.people,a={all:n.length,online:n.filter(c=>c.online>0).length,attention:n.filter(fn).length,paused:n.filter(c=>c.state!=="active"&&c.state!=="quota"&&c.state!=="expired").length},s=document.getElementById("dl-people-tabs");if(s){let c={all:"All",online:"Online",attention:"Needs attention",paused:"Paused"};dom.content(s,Object.keys(c).map(x=>e("button",{type:"button",role:"tab",class:x===this.filter?"on":"",click:()=>{this.filter=x,this.decorate()}},[c[x],e("b",{class:x==="attention"&&a[x]?"warn":""},String(a[x]))])))}let o=c=>!(this.filter==="online"&&!c.online||this.filter==="attention"&&!fn(c)||this.filter==="paused"&&!(c.state!=="active"&&c.state!=="quota"&&c.state!=="expired")),r=[...n].sort((c,x)=>this.sort==="name"?c.name.localeCompare(x.name):this.sort==="usage"?x.month[0]+x.month[1]-(c.month[0]+c.month[1]):x.online-c.online||x.last_seen-c.last_seen),l=null,d=0;for(let c of r){let g=document.getElementById(`dl-card-${c.id}`)?.closest(".cbi-section-table-row");if(!g)continue;l??(l=g.parentElement),l?.appendChild(g),g.classList.toggle("dl-off",c.state!=="active"),g.classList.toggle("dl-attn-row",c.state==="quota"||c.state==="expired");let k=o(c);g.classList.toggle("dl-filtered",!k),k&&d++}let p=l?.closest(".cbi-section-table")??l,u=document.getElementById("dl-people-none");p&&n.length&&!d?(u??(u=e("div",{id:"dl-people-none",class:"dl-empty"})),dom.content(u,e("p",{},"No one here right now.")),u.parentElement!==p.parentElement&&p.after(u)):u?.remove()}async poll(){let t=await this.latestStatus();if(!t)return;let n=this.scope(t);this.st=n,this.paintCards(),this.decorate()}async quick(t,n,a){await O(()=>z.personUpdate(t.id,n),a)&&await this.poll()}renderCard(t,n){let a=this.person(n);if(!a)return dom.content(t,e("em",{},"Not saved yet — use “Save & Apply”.")),t;let s=ze(a.expires),o=Math.max(0,a.device_limit-a.devices.length),r=[];if(a.expires){let c=s!=null&&s>=0&&s<=Math.max(a.expire_warn,3),x=s!=null&&s<0;r.push(e("span",{class:`dl-pill-ic${x?" bad":c?" warn":""}`,title:`Access ends ${_e(a.expires)}`},[b("calendar"),x?`ended ${_e(a.expires)}`:c?`ends in ${s} day${s===1?"":"s"}`:`until ${_e(a.expires)}`]))}a.hours&&r.push(e("span",{class:"dl-pill-ic",title:"Allowed hours"},[b("clock"),a.hours.replace("-","–")]));let l=rt(a.devices).map(c=>e("button",{type:"button",class:`dl-chip${c.disabled?" disabled":""}${c.online?" live":""}`,title:`${Se[c.kind]} · ${c.address}${c.online?` · online from ${c.endpoint}`:c.handshake?` · seen ${he(c.handshake,this.st.now)}`:""}`,click:x=>{x.preventDefault(),Ce(a,c,()=>this.refresh(),this.st.geo)}},[b(c.kind),e("span",{class:"dl-chip-name"},c.name),!c.handshake&&!c.disabled?e("span",{class:"dl-chip-tag"},"not set up"):""]));l.push(e("button",{type:"button",class:"dl-chip add","aria-label":"Add device",title:o>0?"Add device":"Add device · over the limit, admins can still add",click:c=>{c.preventDefault(),Ke(a,()=>this.refresh())}},b("plus")));let d=[];a.state==="quota"&&a.quota_period==="month"&&d.push(e("button",{type:"button",class:"dl-fix",click:()=>this.quick(a,{bonus_gb:String((a.bonus_gb||0)+10)},"+10 GB this month")},"+10 GB this month")),a.expires&&s!=null&&s<=Math.max(a.expire_warn,3)&&d.push(e("button",{type:"button",class:"dl-fix",click:()=>this.quick(a,{expires:Na(a.expires)},"Extended by 1 month")},"Extend 1 month"));let p=ke("more","More",c=>we(c.currentTarget,[{label:"Open",icon:b("open"),run:()=>{location.href=be(a.id)}},a.link?{label:"Invite card",icon:b("qr"),run:()=>tt(a,this.st.servers.find(x=>x.id===a.server)?.name??"Home")}:null,o>0?{label:"Add device",icon:b("plus"),run:()=>Ke(a,()=>this.refresh())}:null,null,{label:a.paused?"Resume":"Pause",icon:b(a.paused?"play":"pause"),warn:!a.paused,run:()=>this.togglePause(a)},{label:"Delete",icon:b("trash"),danger:!0,run:()=>this.remove(a.id)}].filter((x,g,k)=>x||g>0&&k[g-1])),"neutral","dl-icon-only"),u=e("div",{class:"dl-pcard-actions"},[a.link?ke("link","Copy link",()=>pe(a.link,"Personal link copied"),"neutral","dl-icon-only"):"",p]);return dom.content(t,e("div",{class:"dl-pcard"},[e("div",{class:"dl-pcard-main"},[e("div",{class:"dl-pcard-top"},[e("span",{class:`dl-avatar${a.online?" online":""}`},Re(a.name)),e("div",{class:"dl-pcard-who"},[e("div",{class:"dl-card-head"},[e("a",{class:"dl-card-name",href:be(a.id)},a.name),It(a),Ca(a),...r]),Ta(a)])]),e("div",{class:"dl-chips"},l),d.length?e("div",{class:"dl-fixes"},d):""]),this.usageSide(a,u)])),t}usageSide(t,n){let a=t.quota_used||t.month[0]+t.month[1],s=t.quota_limit?Math.min(100,t.quota_used/t.quota_limit*100):0,o=t.devices.reduce((u,c)=>u+(c.spark[c.spark.length-1]??0),0),r=t.rate?.[t.rate.length-1],l=t.online&&r&&this.st.now-r[0]<180,d=e("div",{class:`dl-usebar${s>=100?" bad":s>=90?" warn":""}`});if(t.quota_limit){let u=e("i",{class:"fill"});u.style.width=`${s}%`,d.appendChild(u),ce(d,()=>[e("div",{class:"dl-tip-title"},`${s.toFixed(1)}% used`),e("div",{class:"dl-muted"},`${Q(t.quota_used)} of ${Q(t.quota_limit)} · ${Q(Math.max(0,t.quota_limit-t.quota_used))} left`),e("div",{class:"dl-faint"},t.quota_period==="total"?"In total":`This month${t.bonus_gb?` · includes +${t.bonus_gb} GB extra`:""}`)])}else{let u=t.devices.map(c=>({d:c,v:c.month[0]+c.month[1]})).filter(c=>c.v>0).sort((c,x)=>x.v-c.v);u.forEach((c,x)=>{let g=e("i",{class:`c${Math.min(x,4)}`});g.style.flexGrow=String(c.v),d.appendChild(g)}),u.length&&ce(d,()=>[e("div",{class:"dl-tip-title"},"This month by device"),...u.map((c,x)=>e("div",{class:"dl-tip-row"},[e("span",{class:`dl-swatch c${Math.min(x,4)}`}),e("span",{},c.d.name),e("b",{},Q(c.v))]))])}let p=t.quota_limit?`${Q(Math.max(0,t.quota_limit-t.quota_used))} left`:"no limit";return e("div",{class:"dl-pside"},[e("div",{class:"dl-pside-top"},[l?e("span",{class:"dl-pside-state live"},"Online"):e("span",{class:"dl-pside-state"},t.online?"Online":t.last_seen?"Offline":"Never connected"),n]),e("div",{class:"dl-use-num"},[e("b",{class:a?"":"dl-faint"},Q(a)),e("span",{class:"dl-faint"},t.quota_limit?`of ${Q(t.quota_limit)}`:t.quota_period==="total"&&t.quota_gb?"in total":"this month")]),d,l?e("div",{class:"dl-use-live",title:"Right now"},[`↓ ${$e(r[2])}`,e("span",{class:"dl-faint"},`↑ ${$e(r[1])}`)]):e("div",{class:"dl-faint dl-pside-foot"},o?`today ${Q(o)} · ${p}`:p)])}async togglePause(t){await O(()=>z.personPause(t.id,!t.paused),t.paused?`${t.name} resumed`:`${t.name} paused`)&&await this.refresh()}async remove(t){let n=this.person(t);await oe(`Remove ${n?.name??t}?`,`All ${n?.devices.length??0} devices are disconnected immediately and the personal link stops working. Usage history is kept in backups.`,"Remove",!0)&&await O(()=>z.personDelete(t),"Person removed")&&await this.refresh()}openCreate(){let t=this.st;if(!t.servers.length){te("Set up the server first.","warning");return}let n=e("input",{type:"text",class:"cbi-input-text",placeholder:"e.g. Myata",maxlength:48}),a=Aa("internet"),s=e("input",{type:"number",class:"cbi-input-text",min:1,max:32,value:t.settings.default_device_limit}),o=e("input",{type:"date",class:"cbi-input-text"}),r=e("input",{type:"number",class:"cbi-input-text",min:0,step:"any",placeholder:"Unlimited"}),l=(c,x)=>e("button",{type:"button",class:"cbi-button cbi-button-neutral",click:()=>{if(!x)o.value="";else{let g=new Date;g.setMonth(g.getMonth()+x),o.value=Pa(g)}}},c),d=t.servers[0],p=!this.serverId&&t.servers.length>1?e("select",{class:"cbi-input-select"},t.servers.map(c=>e("option",{value:c.id},c.name))):null,u=(c,x,g)=>e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},c),e("div",{class:"cbi-value-field"},[x,g?e("div",{class:"cbi-value-description"},g):""])]);ne("Add person",[u("Name",n),p?u("Server",p):"",e("div",{class:"cbi-value dl-block"},[e("label",{class:"cbi-value-title"},"Access"),e("div",{class:"cbi-value-field"},a.el)]),u("Devices",s,"How many devices they can add themselves."),u("End date",e("div",{class:"dl-actions"},[o,l("1 month",1),l("3 months",3),l("1 year",12),l("None",0)]),"Optional."),u("Monthly data (GB)",r,"Optional. They are paused when it runs out and resumed next month.")],[e("button",{class:"cbi-button cbi-button-neutral",click:Z},"Cancel")," ",R("Create and copy link",async()=>{let c=await O(()=>z.personCreate(n.value.trim(),"",p?.value??d.id,a.get(),Number(s.value)||t.settings.default_device_limit,o.value,Number(r.value)||0,"month"));c&&(c.link&&await pe(c.link,"Personal link copied"),this.showCreated(c.id,n.value.trim(),c.link,t.servers.find(x=>x.id===(p?.value??d.id))?.name??d.name),await this.refresh())},"positive")]),setTimeout(()=>n.focus(),50)}showCreated(t,n,a,s){if(a){tt({id:t,name:n,link:a},s,{title:`${n} is ready`,lead:`Send ${n} the card or the link. They open it, add their devices and connect — no account needed.`});return}ne(`${n} is ready`,[e("p",{},"Created. Turn on the personal portal in Settings to get a link, or add devices for them here.")],[e("button",{class:"cbi-button cbi-button-positive",click:Z},"Done")])}};function Ee(i,t,n){let a=e("button",{type:"button",role:"switch",class:`dl-switch${i?" on":""}`,"aria-checked":i?"true":"false","aria-label":t,click:()=>{let s=!a.classList.contains("on");a.classList.toggle("on",s),a.setAttribute("aria-checked",s?"true":"false"),n?.(s)}},e("i"));return a}var Ye=i=>i.classList.contains("on");function se(i,t={}){return e("input",{type:"text",class:"cbi-input-text",value:i,...t})}function ee(i,t,n){return e("div",{class:"dl-setrow"},[e("div",{class:"dl-stack"},[e("span",{class:"dl-setrow-label"},i),n?e("span",{class:"dl-sub"},n):""]),e("div",{class:"dl-setrow-ctl"},t)])}function nt(i,t,n,a=""){return e("section",{class:`dl-setsec ${a}`},[e("div",{class:"dl-setsec-body"},[i?e("h3",{},i):"",...t]),n.length?e("div",{class:"dl-setsec-foot"},n):""])}function ue(i,t,n,a){return e("div",{class:"dl-group"},[e("div",{class:"dl-group-head"},[e("span",{class:"dl-group-ic"},b(i)),e("span",{class:"dl-stack"},[e("b",{},t),n?e("span",{class:"dl-sub"},n):""])]),e("div",{class:"dl-group-body"},a.filter(s=>s!==""))])}var ft=["#3a83f7","#a78bfa","#f472b6","#f59e0b","#10b981","#22d3ee","#ef4444","#84cc16"],bt=i=>e("i",{class:"dl-circle-dot",style:`background:${ft[i?.color??0]??ft[0]}`}),Ve=i=>i.access==="both"||i.access==="lan"&&!i.services?.length;function bn(i,t,n){let a=se(i?.name??t.name??"",{placeholder:"NAS"}),s=se(i?.address??t.address??"",{placeholder:"192.168.1.10",class:"cbi-input-text dl-mono"}),o=se((i?.ports??t.ports??[]).join(", "),{placeholder:"All ports, or e.g. 445, 5000",class:"cbi-input-text dl-mono"}),r=(l,d)=>e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},l),e("div",{class:"cbi-value-field"},d)]);ne(i?`Edit ${i.name}`:"Add service",[r("Name",a),r("Address",s),r("Ports",o)],[e("button",{class:"cbi-button cbi-button-neutral",click:Z},"Cancel")," ",R("Save",async()=>{let l=o.value.split(/[ ,]+/).filter(Boolean);await O(()=>z.serviceSet(i?.id??"",a.value,s.value,l),"Saved")&&(Z(),n())},"positive")])}var za={_smb:"SMB",_afpovertcp:"AFP",_http:"Web",_https:"Web",_ssh:"SSH",_sftp:"SFTP","_sftp-ssh":"SFTP",_ipp:"Printer",_ipps:"Printer",_printer:"Printer","_pdl-datastream":"Printer",_airplay:"AirPlay",_raop:"AirPlay",_rfb:"Screen sharing",_googlecast:"Cast",_hap:"HomeKit",_rdp:"Remote desktop",_ftp:"FTP"},Ra=[["Web",["80","443"]],["SMB",["445"]],["SSH",["22"]]];function Ha(i){let t=new Map;for(let n of i.services){let a=za[n.type.split(".")[0]];!a||!n.port||(t.get(a)??t.set(a,new Set).get(a)).add(String(n.port))}return t.size?[...t].map(([n,a])=>[n,[...a].sort((s,o)=>+s-+o)]):Ra}function xn(i,t,n){let a=i.services,s=e("div",{class:"dl-stack gap8"},e("span",{class:"dl-sub"},"Looking for devices at home…")),o=a.length?a.map(d=>e("div",{class:"dl-row"},[b("home"),e("span",{class:"dl-row-main dl-stack"},[e("b",{},d.name),e("span",{class:"dl-mono dl-faint"},`${d.address}${d.ports.length?` · ports ${d.ports.join(", ")}`:" · all ports"}`)]),R("Edit",()=>bn(d,{},n)),R([b("trash")],async()=>{await oe(`Remove ${d.name}?`,"People limited to this service lose access to it.","Remove",!0)&&await O(()=>z.serviceDelete(d.id),"Removed")&&n()},"neutral",{title:"Remove","aria-label":`Remove ${d.name}`})])):[e("div",{class:"dl-row dl-muted"},"No services yet: pick ports of a device below.")];async function r(d,p){let u=a.find(x=>x.address===d.address);(p===null?u&&await O(()=>z.serviceDelete(u.id),`${u.name} removed`):await O(()=>z.serviceSet(u?.id??"",u?.name??(d.name||d.address),d.address,p),u?`${u.name} updated`:`${d.name||d.address} added`))&&n()}function l(d){let p=a.find(g=>g.address===d.address),u=!!p&&!p.ports.length,c=new Set(p?.ports??[]),x=(g,k,G)=>e("button",{type:"button",class:`dl-chipbtn${k?" on":""}`,"aria-pressed":k?"true":"false",click:G},g);return e("div",{class:"dl-row"},[b(d.services.some(g=>g.type.startsWith("_ipp")||g.type.startsWith("_printer"))?"file":"computer"),e("span",{class:"dl-row-main dl-stack"},[e("b",{},d.name||d.address),e("span",{class:"dl-mono dl-faint"},d.address)]),e("div",{class:"dl-chips-row dl-host-ports"},[x("All ports",u,()=>r(d,u?null:[])),...Ha(d).map(([g,k])=>{let G=!u&&k.every(K=>c.has(K));return x(`${g} ${k.join(", ")}`,G,()=>{let K=new Set(u?[]:c);for(let I of k)G?K.delete(I):K.add(I);r(d,K.size?[...K]:null)})})])])}return z.homeHosts(t).then(d=>{let p=d.hosts.some(u=>a.some(c=>c.address===u.address))&&!a.length;dom.content(s,d.hosts.length?e("details",{class:"dl-params",open:p?"":null},[e("summary",{},[b("chevron"),e("span",{},"Add from devices at home"),e("span",{class:"dl-pcount"},String(d.hosts.length))]),e("div",{class:"dl-params-body"},[e("span",{class:"dl-sub"},d.mdns?"Ports they announce over Bonjour. Pick what to open, or all ports.":"Devices that got an address from this router. Pick the ports to open, or all ports."),e("div",{class:"dl-list"},d.hosts.map(l))])]):e("span",{class:"dl-sub"},"No devices found in the home network right now."))}).catch(()=>dom.content(s,e("span",{class:"dl-sub"},"Couldn't read the devices at home."))),e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-iflead"},[e("div",{class:"dl-iflead-row"},[e("b",{},"Home services"),R([b("plus")," Add service"],()=>bn(null,{},n))]),e("span",{class:"dl-sub"},"Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers.")]),e("div",{class:"dl-list"},o),s])}function vt(i,t,n,a){let s=new Set(i.circles.filter(g=>g.server===t).map(g=>g.color)),o=n?.color??ft.findIndex((g,k)=>!s.has(k));o<0&&(o=0);let r=se(n?.name??"",{placeholder:"Family"}),l=i.people.filter(g=>g.server===t).sort((g,k)=>g.name.localeCompare(k.name)),d=new Set(l.filter(g=>n&&g.circle===n.id).map(g=>g.id)),p=e("div",{class:"dl-swatches",role:"radiogroup","aria-label":"Colour"}),u=()=>dom.content(p,ft.map((g,k)=>e("button",{type:"button",role:"radio",class:`dl-swatch${k===o?" on":""}`,style:`--sw:${g}`,"aria-checked":k===o?"true":"false","aria-label":`Colour ${k+1}`,click:()=>{o=k,u()}})));u();let c=e("div",{class:"dl-chips-row"},l.map(g=>{let k=g.circle&&g.circle!==n?.id?i.circles.find(G=>G.id===g.circle):void 0;return e("button",{type:"button",class:`dl-chipbtn${d.has(g.id)?" on":""}`,title:Ve(g)?k?`Now in ${k.name}`:"":`${g.name} has no home access: their devices aren't reachable anyway`,click:G=>{d.delete(g.id)||d.add(g.id),G.currentTarget.classList.toggle("on",d.has(g.id))}},[g.name,Ve(g)?k?e("b",{},k.name):"":e("b",{},"internet")])})),x=(g,k)=>e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},g),e("div",{class:"cbi-value-field"},k)]);ne(n?`Edit ${n.name}`:"New circle",[x("Name",r),x("Colour",p),x("People",c),e("p",{class:"dl-sub"},"Devices of people in one circle reach each other. A person is in one circle at a time.")],[n?R("Delete",async()=>{await O(()=>z.circleDelete(n.id),`${n.name} deleted`)&&(Z(),a())},"negative"):"",e("span",{class:"dl-spacer"}),e("button",{class:"cbi-button cbi-button-neutral",click:Z},"Cancel")," ",R("Save",async()=>{await O(()=>z.circleSet(n?.id??"",t,r.value,o,[...d]),"Saved")&&(Z(),a())},"positive")],"dl-circle-modal")}function wn(i,t,n){let a=i.circles.filter(s=>s.server===t);return e("div",{class:"dl-chips-row dl-circles"},[...a.map(s=>{let o=i.people.filter(r=>r.circle===s.id).map(r=>r.name);return e("button",{type:"button",class:"dl-chip",title:`Edit ${s.name}`,click:()=>vt(i,t,s,n)},[bt(s),e("b",{},s.name),e("span",{class:"dl-faint"},o.length?o.join(", "):"nobody yet")])}),e("button",{type:"button",class:"dl-chip add",title:"New circle","aria-label":"New circle",click:()=>vt(i,t,null,n)},b("plus"))])}function yn(i,t){let n=i.people.filter(u=>u.server===t.id),a=(u="")=>e("span",{class:"dl-yes"},[b("check"),u]),s=()=>e("span",{class:"dl-faint"},"—"),o=u=>{let c=new Set(u.map(x=>x.access==="lan"&&x.services?.length?"services":x.home_nets?.length?"some":"all"));return c.size||c.add("all"),a([...c].map(x=>({all:"all networks",some:"their networks",services:"services"})[x]).join(" / "))},r=()=>t.mesh==="off"?s():t.mesh==="circles"?a("circle"):a(),l=t.lan_like?"like home":"direct",d=(u,c,x)=>e("tr",{},[e("td",{},[e("b",{},u),e("div",{class:"dl-sub"},`${c.length} ${c.length===1?"person":"people"}`)]),...x.map(g=>e("td",{},g))]),p=u=>n.filter(c=>c.access===u);return e("section",{class:"dl-setsec"},[e("div",{class:"dl-setsec-body"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Who reaches what"),e("span",{class:"dl-spacer"}),e("span",{class:"dl-sub"},"From the rules on this server")]),e("div",{class:"dl-reach-wrap"},e("table",{class:"dl-table dl-reach"},[e("tr",{},["","Internet","Home","This router","Each other"].map(u=>e("th",{},u))),d("Internet",p("internet"),[a(l),s(),e("span",{class:"dl-faint"},"DNS"),s()]),d("Home",p("lan"),[e("span",{class:"dl-faint"},"their own"),o(p("lan")),a(),r()]),d("Both",p("both"),[a(l),o(p("both")),a(),r()])])),e("p",{class:"dl-sub"},"Home devices reach the devices of people with home access, on the networks those people reach. Paused, ended and over-the-limit people reach nothing.")])])}function kn(i,t){let n=i.people.filter(p=>p.server===t.id).flatMap(p=>p.devices.map(u=>({id:u.id,label:`${p.name} · ${u.name}`}))).sort((p,u)=>p.label.localeCompare(u.label)),a="@addr",s=(p,u)=>{let c=e("select",{class:"cbi-input-select","aria-label":p},[...n.map(G=>e("option",{value:G.id,selected:G.id===u?"selected":null},G.label)),e("option",{value:a,selected:u===a?"selected":null},"Address")]),x=se("",{placeholder:p,class:"cbi-input-text dl-mono"}),g=e("div",{class:"dl-check-end"},[c,x]),k=()=>x.hidden=c.value!==a;return c.addEventListener("change",k),k(),{el:g,value:()=>c.value===a?x.value.trim():c.value}},o=s("10.0.1.11",n[0]?.id??a),r=s("10.0.1.20:445",a),l=e("div",{class:"dl-stack gap8"}),d=async()=>{let p=await O(()=>z.accessCheck(o.value(),r.value()));if(!p)return;let u=p.steps.findIndex(c=>!c.ok);dom.content(l,[e("div",{class:`dl-verdict ${p.ok?"ok":"bad"}`},[e("b",{},p.ok?"Allowed":"Blocked"),e("span",{class:"dl-sub"},p.ok?"Every step lets it through":`Stops at step ${u+1} of ${p.steps.length}`)]),e("ul",{class:"dl-checks"},p.steps.map(c=>e("li",{},[e("span",{class:`dl-check-icon ${c.ok?"ok":"error"}`},b(c.ok?"check":"x")),e("div",{class:"dl-check-body"},[e("div",{class:"dl-check-title"},c.title),c.detail?e("div",{class:"dl-check-detail"},c.detail):""])])))])};return e("section",{class:"dl-setsec"},[e("div",{class:"dl-setsec-body"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Check access"),e("span",{class:"dl-spacer"}),e("span",{class:"dl-sub"},"Why something does or does not connect")]),e("div",{class:"dl-check-form"},[o.el,e("span",{class:"dl-faint"},"→"),r.el,R("Check",d)]),l])])}var Ia={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link"},Ba=300*1e3;async function at(i,t,n){if(!t.length)return!0;if(!await oe(`Install ${Ia[i]}?`,`${t.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,"Install"))return!1;let s=(await z.updatesStatus().catch(()=>null))?.job?.started??0;if(!await O(()=>z.updatesRun(`pkgs:${t.join(",")}`)))return!1;te(`Installing ${t.join(", ")}…`,"info",4e3);let o=Date.now()+Ba;for(;Date.now()setTimeout(d,2e3));let l=(await z.updatesStatus().catch(()=>null))?.job;if(!(!l||l.started===s||l.state==="running"))return l.state==="done"?(te(`${t.join(", ")} installed`,"success"),setTimeout(()=>n?.(),4e3),!0):(te(l.error??"Installation failed","error"),!1)}return te("Still installing: see Updates for the log.","warning"),!1}async function $n(i,t){let n=await O(()=>z.updatesStatus());return n?at(i,n.needs?.[i]??[],t):!1}var ja=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],Oa={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Bt(i,t,n){let a=e("button",{type:"button",role:"switch",class:`dl-switch${i?" on":""}`,"aria-checked":i?"true":"false","aria-label":t,click:()=>{let s=!a.classList.contains("on");a.classList.toggle("on",s),a.setAttribute("aria-checked",s?"true":"false"),n(s)}},e("i"));return a}function _n(i,t,n){let a=i.id,s=e("div",{class:"dl-stack gap16"},e("section",{class:"dl-setsec"},e("div",{class:"dl-setsec-body"},e("p",{class:"dl-muted"},"Loading interfaces…")))),o,r=!0,l="",d=!0,p=!0,u="all",c=!1,x=xn(t,a,n),g=new Set,k="",G=()=>JSON.stringify([p,r,r?"":l,d,[...g].sort()]),K=()=>o.detected.lan||o.saved.lan||"",I=()=>(r?o.detected.wan||o.saved.wan:l)||"",_=()=>new Map(o.devices.map(v=>[v.name,v])),N=()=>{let v=_();return[...d&&K()?[K()]:[],...[...g].filter(q=>q!==K())].filter(q=>q!==I()).map(q=>v.get(q)??{name:q,nets:[],missing:!0})},C=(v,U)=>{o=v,U&&(r=v.config.auto_wan,l=v.config.wan_device||v.detected.wan||v.saved.wan||"",d=v.config.auto_lan,p=v.config.lan_like,u=v.config.mesh??(v.config.device_mesh?"all":"off"),g=new Set(v.config.lan_devices),k=G()),j()},D=async v=>{let U=await z.interfaces(a).catch(q=>(te(q.message,"error"),null));U&&C(U,v)};function $(v){let U=d&&v.name===K(),q=!!v.own||!!v.master||v.name===I()||U;return U||g.has(v.name)||!q&&(v.nets.length>0||!!v.missing)}function A(v){let U=d&&v.name===K(),q=v.name===I(),X=!U&&g.has(v.name),ie=!(!!v.own||!!v.master||q||U)&&(v.nets.length>0||X||!!v.missing),me=(X||U)&&!v.zone&&!v.missing,De=v.missing?"Not present right now":v.own?"This server":v.master?`Port of ${v.master}`:q?`Internet${v.zone?` · zone ${v.zone}`:""}`:v.nets.length?v.nets.join(", "):"No IPv4 network",H=e("button",{type:"button",class:`dl-if${X?" sel":""}${U?" auto":""}${!ie&&!X&&!U?" off":""}${me?" warn":""}`,"aria-pressed":X||U?"true":"false","aria-disabled":ie?null:"true",click:()=>{ie&&(g.has(v.name)?g.delete(v.name):g.add(v.name),j())}},[e("span",{class:"dl-if-ic"},b(Oa[v.kind]??"link")),e("span",{class:"dl-if-main"},[e("span",{class:"dl-if-name"},v.name),e("span",{class:"dl-if-sub"},De)]),U?e("span",{class:"dl-if-badge ok"},"Auto"):X?e("span",{class:"dl-if-check"},b("check")):""]);return ce(H,()=>[e("div",{class:"dl-tip-title"},v.name),e("div",{class:"dl-muted"},[v.logical?`Interface ${v.logical}`:"No netifd interface",v.zone?` · zone ${v.zone}`:" · no firewall zone"]),v.members.length?e("div",{class:"dl-muted"},`Ports: ${v.members.join(", ")}`):"",v.nets.length?e("div",{class:"dl-mono"},v.nets.join(", ")):"",me?e("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",v.master?e("div",{class:"dl-muted"},`Choose ${v.master} to include it.`):""]),H}function m(){let v=o.like_home;return!p||!o.config.lan_like?"":!o.needs?.length&&v.active&&v.bridged?"ok":"warn"}function h(){let v=o.like_home;return p?o.needs?.length?[e("span",{class:"dl-warn"},`Needs ${o.needs.join(" and ")}.`)," Until they are installed, internet traffic goes straight to the WAN."]:o.config.lan_like?v.active&&v.bridged?["Internet traffic enters ",e("span",{class:"dl-mono"},v.dev??"")," as ",e("span",{class:"dl-mono"},v.address??""),", so whatever handles home traffic (proxies, filters, DNS) handles it too."]:[e("span",{class:"dl-warn"},`Not working: ${v.error??"the link is down"}`)," Internet traffic goes straight to the WAN for now."]:["Internet traffic will enter the router from your LAN, so it is handled like any home device. Save to turn on."]:["Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router."]}let P={off:"Devices of different people never reach each other; a person's own devices don't either.",all:"Devices of people with home access reach each other, like home devices do. Internet-only people never.",circles:"Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never."};function f(v,U,q,X,le="",ie){return e("div",{class:ie?"dl-setrow head":"dl-setrow"},[e("div",{class:"dl-lh-main"},[e("span",{class:`dl-need-ic ${le}`},b(v)),e("div",{class:"dl-stack"},[e("span",{class:"dl-setrow-label"},U),e("span",{class:"dl-sub"},q),ie??""])]),e("div",{class:"dl-setrow-ctl"},X)])}let S=(v,U)=>{let q=X=>e("span",{class:"dl-mono"},X);return v?e("span",{},[" Now: ",q(v),...U&&U!==v?[", was ",q(U)]:[],"."]):e("span",{},U?[" Not found now: using ",q(U),"."]:[" Not found."])};function j(){let v=e("select",{class:"cbi-input-select","aria-label":"Internet interface",change:y=>{l=y.target.value,j()}},o.devices.filter(y=>!y.own&&!y.master&&y.zone&&!y.missing).map(y=>e("option",{value:y.name,selected:y.name===l?"selected":null},`${y.name} · zone ${y.zone}`))),q=N().flatMap(y=>y.nets.map(T=>[T,y.name])),X=JSON.parse(G()),le=JSON.parse(k),ie=(...y)=>y.some(T=>JSON.stringify(X[T])!==JSON.stringify(le[T])),me=ie(0,1,2),De=ie(3,4),H=y=>R("Save",async()=>{let T=await O(()=>z.serverInterfaces(a,r,r?"":l,d,[...g],p,u!=="off",u),"Access saved");T&&(C(T,!0),T.nets_changed&&T.lan_only&&te(`${T.lan_only} ${T.lan_only===1?"person has":"people have"} Home-only access: their devices need the configuration again to reach the new networks.`,"warning",1e4))},"positive",{disabled:!y}),re=e("section",{class:"dl-setsec dl-ifcard"},[e("div",{class:"dl-setsec-body"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Internet"),e("span",{class:"dl-spacer"}),e("span",{class:"dl-sub"},"People with Internet or Both")]),f("home","Internet like a home device",h(),[p&&o.needs?.length?R("Install",()=>at("home",o.needs,()=>D(!1)),"positive"):"",Bt(p,"Internet like a home device",y=>{p=y,j()})],m()),f("globe","Auto-detect WAN",["The interface with the default route: the server port opens there and Internet access leaves through it.",S(o.detected.wan,o.saved.wan)],[r?"":v,Bt(r,"Auto-detect WAN",y=>{r=y,j()})])]),e("div",{class:"dl-setsec-foot"},[e("span",{class:"dl-sub"},p?["Internet like a home device",I()?[" · leaves through ",e("span",{class:"dl-mono"},I())]:""]:I()?["Internet straight to ",e("span",{class:"dl-mono"},I())]:"No WAN found"),H(me)])]),M=e("div",{class:"dl-seg sm",role:"radiogroup","aria-label":"Devices reach each other"},[["off","Off"],["all","Everyone"],["circles","Circles"]].map(([y,T])=>e("button",{type:"button",role:"radio",class:u===y?"on":"","aria-checked":u===y?"true":"false",click:async()=>{u!==y&&await O(()=>z.serverUpdate(a,{mesh:y}),`Devices reach each other: ${T}`)&&n()}},T))),E=e("section",{class:"dl-setsec dl-ifcard"},[e("div",{class:"dl-setsec-body"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Home network"),e("span",{class:"dl-spacer"}),e("span",{class:"dl-sub"},"People with Home or Both"),R([b("reset")," Rescan"],()=>D(!1),"neutral",{title:"Read the interfaces again"})]),f("network","Networks","Everyone with home access reaches these, unless their page leaves one out; their devices can be reached from here too. Click one to add or remove it.","","",W()),f("link","Devices reach each other",P[u],M,"",u==="circles"?wn(t,a,n):void 0),x]),e("div",{class:"dl-setsec-foot"},[e("span",{class:"dl-sub dl-if-summary"},q.length?["Home access reaches ",...q.flatMap(([y,T],B)=>[B?", ":"",e("span",{class:"dl-mono"},y),` (${T})`])]:"No home network: Home access reaches nothing but this router."),H(De)])]),w=window.scrollY;s.style.minHeight=`${s.offsetHeight}px`,dom.content(s,[re,E]),s.style.minHeight="",window.scrollTo({top:w})}function W(){let v=o.devices.filter($),U=o.devices.filter(q=>!$(q));return e("div",{class:"dl-stack gap8 dl-netpick"},[v.length?e("div",{class:"dl-ifgrid"},v.map(A)):e("span",{class:"dl-warn"},"No home network: Home access reaches nothing but this router."),e("label",{class:"dl-boxrow"},[e("span",{class:"dl-stack"},[e("span",{},"Auto-detect LAN"),e("span",{class:"dl-sub"},["Adds the LAN this router uses.",S(o.detected.lan,o.saved.lan)])]),Bt(d,"Auto-detect LAN",q=>{d=q,j()})]),U.length?e("details",{class:"dl-params",open:c?"":null,toggle:q=>c=q.currentTarget.open},[e("summary",{},[b("chevron"),e("span",{},"Other interfaces"),e("span",{class:"dl-pcount"},String(U.length))]),e("div",{class:"dl-params-body"},[e("span",{class:"dl-sub"},"The WAN, this server, ports and Wi-Fi of a bridge (they come with it) and interfaces without an IPv4 network."),...ja.map(([q,X])=>{let le=U.filter(ie=>ie.category===q);return le.length?e("div",{class:"dl-ifgroup"},[e("h4",{},X),e("div",{class:"dl-ifgrid"},le.map(A))]):""})])]):""])}return D(!0),s}var Sn=[["overview","Overview"],["people","People"],["connection","Connection"],["access","Access"],["disguise","Disguise"],["tunnel","Tunnel"]],Ua={general:"connection",network:"connection",interfaces:"access",advanced:"tunnel"},Ln=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function qa(i){let t=p=>i[p]!=null&&i[p]!=="",n=Ln.filter(([p])=>t(p));if(!n.length)return null;let a=(p,u)=>e("span",{class:"dl-pv"},[e("i",{},u),e("b",{},p==="header_protection_key"?`${i[p].slice(0,6)}••••`:i[p])]),s=(p,u,c,x)=>{let g=Ln.filter(([k])=>x.includes(k)&&t(k));return g.length?e("div",{class:"dl-pgroup"},[e("div",{class:"dl-pgroup-head"},[b(u),e("b",{},p)]),e("p",{},c),e("div",{class:"dl-pvals"},g.map(([k,G])=>a(k,G)))]):""},o=Number(i.jc||0),r=(i.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=n.map(([p,u])=>`${u} = ${i[p]}`).join(` -`),d=e("div",{class:"dl-pgrid"},[s("Junk packets","zap",o?`${o} random packet${o===1?"":"s"} of ${i.jmin}–${i.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),s("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),s("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),s("Signatures","globe",r,["i1","i2","i3","i4","i5"]),s("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),s("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return e("details",{class:"dl-params"},[e("summary",{},[b("chevron"),e("span",{},"Current parameters"),e("span",{class:"dl-pcount"},String(n.length)),e("span",{class:"dl-spacer"}),e("button",{type:"button",class:"dl-linkbtn",click:p=>{p.preventDefault(),pe(l,"Parameters copied")}},"Copy as config")]),d])}var jt=(i,t)=>{let n=new URLSearchParams;i&&n.set("server",i),t&&t!=="overview"&&n.set("section",t);let a=n.toString();return`${L.url("admin/network/dawnline/server")}${a?`?${a}`:""}`},st=class{constructor(){this.noFooter=!0;this.root=e("div",{class:"dl-root"});this.section="overview";this.srvId="";this.ov={};this.pp={};this.tabsEl=e("div",{});this.headEl=e("div",{});this.secEl=e("div",{});this.bodyEl=e("div",{class:"dl-srvbody"})}async load(){let t=await z.status(31),n=t.servers.length?null:await z.setupDefaults();return[t,n]}render([t,n]){if(this.st=t,!t.servers.length&&n)return this.wizard(n);let a=new URLSearchParams(location.search),s=a.get("section")??"",o=Ua[s]??s;return Sn.some(([r])=>r===o)&&(this.section=o),this.srvId=(t.servers.find(r=>r.id===a.get("server"))??t.servers[0]).id,dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint(),poll.add(async()=>{if(this.section!=="overview")return;let r=await z.status(31).catch(()=>null);if(!r||!r.servers.length)return;this.st=r;let l=this.current();dom.content(this.headEl,this.head(l)),this.paintTabs(),this.ov[l.id]?.update(r)},10),this.root}current(){return this.st.servers.find(t=>t.id===this.srvId)??this.st.servers[0]}async refresh(){let t=await z.status(31).catch(()=>null);t&&(this.st=t,t.servers.length?this.paint():location.href=jt())}paint(){this.paintTabs(),dom.content(this.headEl,this.head(this.current())),this.paintSections(),this.showSection(this.section)}paintTabs(){let t=this.current();dom.content(this.tabsEl,e("div",{class:"dl-srvtabs",role:"tablist","aria-label":"Servers"},[...this.st.servers.map(n=>e("button",{type:"button",role:"tab",class:`dl-srvtab${n.id===t.id?" on":""}`,"aria-selected":n.id===t.id?"true":"false",click:()=>{n.id!==this.srvId&&(this.srvId=n.id,this.paint())}},[e("i",{class:`dot ${n.up?"ok":"bad"}`}),e("b",{},n.name),e("span",{class:"dl-mono dl-faint"},`:${n.port}`)])),e("button",{type:"button",class:"dl-srvtab add",click:()=>this.addServer()},[b("plus"),"Add server"])]))}paintSections(){dom.content(this.secEl,e("div",{class:"dl-seg dl-srvsections",role:"tablist","aria-label":"Server"},Sn.map(([t,n])=>e("button",{type:"button",role:"tab","data-section":t,class:t===this.section?"on":"","aria-selected":t===this.section?"true":"false",click:()=>this.showSection(t)},n))))}go(t,n){let a=this.pp[this.current().id];if(n&&a)a.filter=n,a.el&&a.decorate();else if(n){let s=this.pp[this.current().id]=new Be;s.filter=n}this.showSection(t),window.scrollTo({top:0,behavior:"smooth"})}detachKept(){let t=[...Object.values(this.ov).map(n=>n.el),...Object.values(this.pp).map(n=>n.el)];for(let n of t)n&&this.bodyEl.contains(n)&&n.remove()}showSection(t){this.section=t,this.secEl.querySelectorAll("[data-section]").forEach(r=>{let l=r.dataset.section===t;r.classList.toggle("on",l),r.setAttribute("aria-selected",l?"true":"false")});let n=this.st,a=this.current(),o={overview:()=>{let r=this.ov[a.id];return r?(r.update(n),r.el):(this.ov[a.id]=new pt(a.id,(l,d)=>this.go(l,d))).mount(n)},people:()=>{var p,u;let r=this.pp[a.id];if(r?.el)return r.poll(),r.el;let l=e("div",{},e("p",{class:"dl-muted"},"Loading people…"));return((p=this.pp)[u=a.id]??(p[u]=new Be)).embed(n,a.id).then(c=>{l.isConnected?dom.content(l,c):l.replaceChildren(c)}),l},connection:()=>this.connection(a),access:()=>this.access(a),disguise:()=>this.disguise(a),tunnel:()=>this.tunnel(a)}[t]();this.detachKept(),dom.content(this.bodyEl,o)}head(t){let n=this.st,a=(l,d)=>e("span",{class:"dl-addrbar-seg"},[b(l),...d]),s=`${t.endpoint||"—"}:${t.port}`,o=!t.enabled||n.settings.paused_all,r=e("div",{class:"dl-actions"},[o?R([b("play")," Turn on"],async()=>{n.settings.paused_all&&!await O(()=>z.pauseAll(!1))||(t.enabled?await this.refresh():await this.save(t,{enabled:"1"},"Server turned on"))},"positive"):""]);return e("div",{class:"dl-srvpagehead"},[e("div",{class:"dl-title-row"},[e("h2",{class:"dl-h1"},t.name),e("span",{class:`dl-pill ${t.enabled?t.up?"ok":"bad":"off"}`},t.enabled?t.up?"Running":"Not running":"Turned off"),n.settings.paused_all&&t.enabled?e("span",{class:"dl-pill warn"},"Off"):"",e("span",{class:"dl-spacer"}),r]),e("div",{class:"dl-addrbar"},[e("button",{type:"button",class:"dl-addrbar-seg main",title:"Copy address and port",click:()=>pe(s,"Address copied")},[b("globe"),e("span",{class:"dl-mono"},s),b("copy")]),a("tunnel",[e("span",{class:"dl-mono"},t.ifname)]),a("network",[e("span",{class:"dl-mono"},t.subnet)]),t.up?a("clock",[`up ${on(t.uptime)}`]):""])])}async save(t,n,a="Saved"){await O(()=>z.serverUpdate(t.id,n),a)&&await this.refresh()}connection(t){let n=se(t.name,{placeholder:"Home"}),a=se(t.endpoint,{placeholder:"vpn.example.com",class:"cbi-input-text dl-mono"}),s=se(String(t.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),o=se(t.dns.join(", "),{placeholder:"This router (recommended)",class:"cbi-input-text dl-mono"}),r=se(String(t.mtu??""),{placeholder:"1380",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),l=se(String(t.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"});return nt("Connection",[e("p",{class:"dl-muted"},"How devices find this server, and what goes into their configuration."),ue("router","Server","What people see",[ee("Name",n,"Shown to people in their portal.")]),ue("globe","Devices connect to","Where the tunnel answers from the internet",[ee("Public address",a,"Hostname or IP of the router on the internet. A DDNS name keeps links working when your IP changes."),ee("UDP port",s,"Opened on the WAN firewall automatically.")]),ue("file","In every device configuration","Changing these marks devices “Update config” until they import again",[ee("DNS for devices",o,"Empty = this router, which sends each query where your home network would."),ee("MTU",r,"Lower it if some sites hang on mobile networks."),ee("Keep-alive",l,"Seconds between packets devices send to keep NAT open. 0 = off.")])],[e("span"),R("Save",()=>this.save(t,{name:n.value,endpoint:a.value,port:s.value,dns:o.value,mtu:r.value,keepalive:l.value}),"positive")])}access(t){let n=()=>this.refresh();return e("div",{class:"dl-stack gap16"},[_n(t,this.st,n),e("div",{class:"dl-health-cols"},[yn(this.st,t),kn(this.st,t)])])}disguise(t){let n=We(t.preset)?t.preset:void 0,a=n??"standard",s=R("",()=>this.applyDisguise(t,a,a===n),"positive"),o=()=>{dom.content(s,a===n?[b("reset")," Generate new values"]:`Switch to ${We(a).title}`)};o();let r=qa(t.obf??{});return nt("Disguise",[e("p",{class:"dl-muted"},"AmneziaWG reshapes the tunnel so networks that block VPNs do not recognise it. Every device gets these settings in its configuration."),Pt(this.st.awg,a,l=>{a=l,o()},n),this.st.awg.v3?"":Ae("info",["This router runs an older AmneziaWG. ",e("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]),r??""],[e("span",{class:"dl-sub"},"Applies at once. Every device on this server must import its configuration again."),s])}async applyDisguise(t,n,a){let s=We(n),r=this.st.people.filter(d=>d.server===t.id).reduce((d,p)=>d+p.devices.length,0);await oe(a?"Generate new disguise values?":`Switch to ${s.title}?`,`${r} device${r===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${n==="max"?" They need an app with AmneziaWG 3.1.":""}`,a?"Generate and apply":"Switch and apply",!0)&&await O(()=>z.serverObfuscation(t.id,n),a?"New values applied":`${s.title} applied`)&&(te("Devices are marked “Update config” until they import again.","info",6e3),await this.refresh())}tunnel(t){let n=this.st.people.filter(s=>s.server===t.id).length,a=R(t.enabled?"Turn off":"Turn on",async()=>{t.enabled&&!await oe(`Turn off ${t.name}?`,`The tunnel stops and ${n} ${n===1?"person is":"people are"} disconnected until you turn it back on. Nothing is deleted.`,"Turn off",!0)||await this.save(t,{enabled:t.enabled?"0":"1"},t.enabled?"Server turned off":"Server turned on")},t.enabled?"negative":"positive");return e("div",{class:"dl-stack gap16"},[nt("Tunnel",[e("p",{class:"dl-muted"},"Technical details. They are set when the server is created and rarely change."),ee("Interface",e("span",{class:"dl-mono"},`${t.ifname} · router ${t.address}`)),ee("Tunnel subnet",e("span",{class:"dl-mono"},t.subnet),"Device addresses come from it."),ee("Server public key",e("span",{class:"dl-keyrow"},[e("code",{class:"dl-mono"},t.public_key),R([b("copy")],()=>pe(t.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))],[]),nt("Danger zone",[e("div",{class:"dl-setrow"},[e("div",{class:"dl-stack"},[e("span",{class:"dl-setrow-label"},t.enabled?"Turn off this server":"This server is off"),e("span",{class:"dl-sub"},t.enabled?"Stops the tunnel and disconnects everyone on it. Settings and people are kept.":"Nobody can connect. Turn it on to bring the tunnel back.")]),e("div",{class:"dl-setrow-ctl"},a)]),e("div",{class:"dl-setrow"},[e("div",{class:"dl-stack"},[e("span",{class:"dl-setrow-label"},"Remove server"),e("span",{class:"dl-sub"},`Removes the tunnel, its firewall rules and ${n} ${n===1?"person":"people"} with all their devices. A backup is made first.`)]),e("div",{class:"dl-setrow-ctl"},R([b("trash")," Remove"],()=>this.remove(t),"negative"))])],[],"danger")])}async addServer(){let t=await O(()=>z.setupDefaults());t&&dom.content(this.root,this.wizard(t,!0,()=>{dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint()}))}async remove(t){let n=this.st.people.filter(a=>a.server===t.id);ne(`Remove ${t.name}?`,[e("p",{},`This removes the tunnel, its firewall rules and ${n.length} ${n.length===1?"person":"people"} with all their devices. A backup is made first.`)],[e("button",{class:"cbi-button cbi-button-neutral",click:Z},"Cancel")," ",R("Remove",async()=>{Z(),await O(()=>z.serverDelete(t.id),"Server removed")&&setTimeout(()=>{location.href=jt()},800)},"negative")])}wizard(t,n=!1,a){let s={id:t.id,name:t.name,endpoint:t.endpoint,port:t.port,subnet:t.subnet,preset:"standard",portal:!1,portal_port:t.portal_port||8443,lan_like:!0,lan_zone:t.lan_zone,wan_zone:t.wan_zone},o=0,r=e("div",{class:"dl-wizard"}),l=(c,x={})=>{let g=se(String(s[c]),x);return g.addEventListener("input",()=>{s[c]=c==="port"||c==="portal_port"?Number(g.value):g.value.trim()}),g},d=n?["Connection","Disguise"]:["Connection","Disguise","Portal"],p=[()=>e("div",{class:"dl-wizard-groups"},[e("p",{class:"dl-muted"},"Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes."),ue("router","Server","What people see",[ee("Name",l("name"),"Shown to people in their portal.")]),ue("globe","Devices connect to","Where the tunnel answers from the internet",[ee("Public address",l("endpoint",{placeholder:"vpn.example.com",class:"cbi-input-text dl-mono"}),"Hostname or IP address of your router on the internet."),ee("UDP port",l("port",{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),"Opened on the WAN firewall automatically. A random high port is fine.")]),ue("network","Tunnel network","Addresses devices get inside the tunnel",[ee("Tunnel subnet",l("subnet",{class:"cbi-input-text dl-mono"}),`Must not overlap your networks (${t.taken.join(", ")||"none found"}).`)])]),()=>e("div",{},[e("p",{},"AmneziaWG reshapes the tunnel so networks that block VPNs do not recognise it. Every device gets these settings automatically; you can change the method later."),Pt(t.awg,s.preset,c=>s.preset=c)]),()=>{let c=l("portal_port",{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),x=ee("Listening port",c,"TCP port on WAN for the portal; the whole port belongs to it.");x.hidden=!s.portal;let g=e("div",{class:"dl-seg",role:"radiogroup","aria-label":"Personal portal"},["off","on"].map(k=>e("button",{type:"button",role:"radio",class:k==="on"===s.portal?"on":"","aria-checked":k==="on"===s.portal?"true":"false",click:G=>{s.portal=k==="on",x.hidden=!s.portal,g.querySelectorAll("button").forEach(K=>{let I=K===G.currentTarget;K.classList.toggle("on",I),K.setAttribute("aria-checked",I?"true":"false")})}},k==="on"?"On":"Off")));return e("div",{class:"dl-wizard-groups"},[ue("home","Internet like a home device","How devices reach the internet",[ee("Through the home network",Ee(s.lan_like,"Internet like a home device",k=>s.lan_like=k),"Whatever handles home traffic on this router (proxies, filters, DNS) handles theirs too. Change it later under Servers → Access.")]),ue("link","Personal portal","A page where each person adds their own devices with their personal link",[ee("Portal",g,"Off: only you add devices, from LuCI. On: people manage their devices within the limits you set."),x])])}],u=()=>{dom.content(r,[e("h2",{},n?"Add a server":"Set up Dawnline"),e("div",{class:"dl-steps"},d.map((c,x)=>e("span",{class:`dl-step${x===o?" current":x0?R("Back",()=>{o--,u()}):a?R("Cancel",a):"",e("span",{class:"dl-spacer"}),o{if(o===0&&(!s.endpoint||!s.port||!s.subnet)){te("Fill in the public address, port and subnet.","warning");return}o++,u()},"positive"):R("Create server",async()=>{let c=await O(()=>z.serverCreate(s.id,s.name,t.ifname,s.port,s.subnet,s.endpoint,t.mtu,s.preset,s.lan_zone,s.wan_zone,s.lan_like,n?void 0:s.portal,n?void 0:s.portal_port),"Server created");c&&setTimeout(()=>{location.href=jt(c.id)},1500)},"positive")])])};return u(),r}};var xt=300,Wa=["all","connections","people","system","problems"],Ga={info:"",up:"ok",down:"warn",repair:"warn",error:"bad"},Fa={awg:"tunnel",dawnline:"sunrise",portal:"globe"};function Ka(i){let t=new Date(i*1e3),n=new Date,a=new Date;return a.setDate(n.getDate()-1),t.toDateString()===n.toDateString()?"Today":t.toDateString()===a.toDateString()?"Yesterday":t.toLocaleDateString("en-GB",{weekday:"long",day:"numeric",month:"long"})}function Ot(i){let t=i.keep_days>0?`${i.keep_days} day${i.keep_days===1?"":"s"}`:"no age limit",n=i.persist==="off"?"kept in memory only (lost on reboot)":`saved to flash ${i.persist==="10min"?"every 10 minutes":"hourly"}`;return`Kept for ${t}, up to ${i.max.toLocaleString("en-GB")} events, ${n}.`}var Ut=i=>i.sys?["error","repair","down"].includes(i.sys.level):ht(i.ev.type)==="problems";function qt(i,t,n,a){let s=i.by==="admin",o=e("div",{class:`dl-row dl-slog-row ${s?"dl-ev-by-admin":`dl-ev-by-system ${Ga[i.level]??""}`}${i.detail?" has-detail":""}`},[s?e("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},b("admin")):e("span",{class:"dl-ev-tile sys",title:i.level},b(Fa[i.src]??"zap")),e("span",{class:"dl-row-main"},s?[e("span",{class:"dl-you"},"You"),e("span",{class:"dl-muted"},` ${i.msg} `),i.kind?e("span",{class:"dl-ev-kind"},`${i.kind} `):"",i.who?e("b",{},i.who):"",i.note?e("span",{class:"dl-muted"},` · ${i.note}`):"",i.detail?e("span",{class:`dl-slog-more${t?" open":""}`},b("chevron")):"",i.detail&&t?e("pre",{class:"dl-slog-detail"},i.detail):""]:[i.src==="awg"&&i.who&&i.who!=="AmneziaWG"?e("span",{class:"dl-ev-kind"},"Server "):"",e("b",{class:"dl-sys-src",title:ut[i.src]??i.src},i.who??ut[i.src]??i.src)," ",e("span",{class:"dl-muted"},i.msg),i.detail?e("span",{class:`dl-slog-more${t?" open":""}`},b("chevron")):"",i.detail&&t?e("pre",{class:"dl-slog-detail"},i.detail):""]),e("span",{class:"dl-faint dl-nowrap",title:new Date(i.ts*1e3).toLocaleString()},a)]);return i.detail&&o.addEventListener("click",r=>{r.target.closest("pre")||n()}),o}var wt=class{constructor(t,n,a){this.events=[];this.system=[];this.kind="all";this.shown=xt;this.open=new Set;this.list=e("div",{});this.sub="";this.tabs=e("div",{class:"dl-seg",role:"tablist"});this.st=t,this.take(n),this.system=a,this.el=e("div",{},[e("div",{class:"dl-toolbar"},[this.tabs]),this.list]),this.paint()}actions(){let t=()=>this.kind==="all"?"":this.kind,n=o=>()=>{let r=this.filtered().reverse();Le(this.st,r.filter(l=>l.ev).map(l=>l.ev),o,t(),r.filter(l=>l.sys).map(l=>l.sys))},a=R([b("download")," Export"],()=>we(a,[{label:"CSV (spreadsheet)",icon:b("download"),run:n("csv")},{label:"JSON",icon:b("download"),run:n("json")}])),s=R([b("trash")," Clear"],()=>Te("Clear the log","Removes events from the log on the router.",{},()=>this.reload(),this.kind==="all"?void 0:this.kind,!0));return[a,s]}take(t){this.events=t.events,this.policy=t.policy;let n=Ze.filter(a=>!t.policy.categories.includes(a));this.sub=`${Ot(t.policy)}${n.length?` Not recorded: ${n.map(a=>Ge[a].toLowerCase()).join(", ")}.`:""}`}async reload(){let[t,n]=await Promise.all([z.events(2e4).catch(()=>null),z.serviceLog().catch(()=>null)]);t&&this.take(t),n&&(this.system=n.log),this.paint()}items(){return[...this.events.map(t=>({ts:t.ts,ev:t})),...this.system.map(t=>({ts:t.ts,sys:t}))].sort((t,n)=>n.ts-t.ts)}matches(t,n){return n==="all"?!0:n==="problems"?Ut(t):n==="system"?!!t.sys:!!t.ev&&ht(t.ev.type)===n}filtered(){return this.items().filter(t=>this.matches(t,this.kind))}paintTabs(t){dom.content(this.tabs,Wa.map(n=>e("button",{type:"button",role:"tab",class:n===this.kind?"on":"","aria-selected":n===this.kind?"true":"false",click:()=>this.show(n)},[n==="all"?"All":n==="system"?"System":Ge[n],e("b",{},String(t.filter(a=>this.matches(a,n)).length))])))}show(t){this.kind=t,this.shown=xt,this.paint()}paint(){this.paintTabs(this.items());let t=this.filtered();if(!t.length){dom.content(this.list,e("div",{class:"dl-empty"},[e("p",{},this.events.length||this.system.length?"No events match.":"The log is empty.")]));return}let n=[],a="",s=null;for(let o of t.slice(0,this.shown)){let r=Ka(o.ts);r!==a&&(a=r,s=e("div",{class:"dl-panel flush"},e("div",{class:"dl-panel-head pad"},e("h3",{},r))),n.push(s));let l=new Date(o.ts*1e3).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});if(o.sys){let d=`${o.sys.ts}|${o.sys.msg}`;s.appendChild(qt(o.sys,this.open.has(d),()=>{this.open.delete(d)||this.open.add(d),this.paint()},l))}else{let d=Ie(this.st,o.ev);d.lastElementChild.textContent=l,s.appendChild(d)}}t.length>this.shown&&n.push(e("div",{class:"dl-more-row"},R(`Show ${Math.min(xt,t.length-this.shown)} more of ${t.length-this.shown}`,()=>{this.shown+=xt,this.paint()}))),dom.content(this.list,n)}};var Ya={manual:"Manual",auto:"Nightly","pre-restore":"Before restore","pre-import":"Before import","pre-delete":"Before removing a server","pre-update":"Before update"},Mn=3;function Wt(i){let t=new Date(i*1e3),n=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),a=Math.round((new Date(new Date().toDateString()).getTime()-new Date(t.toDateString()).getTime())/864e5);return`${a===0?"Today":a===1?"Yesterday":t.toLocaleDateString("en-GB",{day:"numeric",month:"short"})}, ${n}`}async function Va(i){let t=await O(()=>z.backupRead(i.name));if(!t)return;let n=atob(t.data),a=new Uint8Array(n.length);for(let o=0;oVa(i),"neutral","dl-icon-only"),ke("more","More",n=>we(n.currentTarget,[{label:"Restore",icon:b("reset"),run:async()=>{await oe("Restore this backup?",`Everything returns to ${Wt(i.created)}. The current state is backed up first.`,"Restore",!0)&&await O(()=>z.backupRestore(i.name),"Restored")&&t()}},{label:"Delete",icon:b("trash"),danger:!0,run:async()=>{await oe("Delete this backup?",`The backup from ${Wt(i.created)} is removed from the router.`,"Delete",!0)&&await O(()=>z.backupDelete(i.name),"Backup deleted")&&t()}}]),"neutral","dl-icon-only")])])}function Gt(i,t){let n=i.slice(0,Mn).map(d=>En(d,t)),a=i.slice(Mn),s=i.length?e("div",{class:"dl-list"},[...n,a.length?e("details",{class:"dl-bk-older"},[e("summary",{},[b("chevron"),`${a.length} older backup${a.length===1?"":"s"}`]),...a.map(d=>En(d,t))]):""]):e("div",{class:"dl-list"},[e("div",{class:"dl-row dl-muted"},"No backups yet.")]),o=R("Restore from file",async()=>{let d=await Dt(".tar.gz,.tgz,application/gzip","base64");if(!d)return;await oe("Restore from file?",`Replace the current Dawnline configuration with ${d.name}? The current state is backed up first.`,"Restore",!0)&&await O(()=>z.backupUpload(d.data),"Restored")&&t()}),r=R("Export JSON",async()=>{let d=await O(()=>z.exportJson());d&&ve(`dawnline-export-${new Date().toISOString().slice(0,10)}.json`,JSON.stringify(d,null,2),"application/json")}),l=R("Import JSON",async()=>{let d=await Dt(".json,application/json","text");if(!d)return;let p;try{p=JSON.parse(d.data)}catch{te("Not a JSON file.","error");return}await oe("Import?","This replaces the whole Dawnline configuration on this router. The current state is backed up first.","Import",!0)&&await O(()=>z.importJson(p),"Imported")&&t()});return e("section",{class:"dl-setsec",id:"dl-set-backups"},[e("div",{class:"dl-setsec-body"},[e("div",{class:"dl-setsec-head"},[e("div",{class:"dl-stack"},[e("h3",{},"Backups"),e("span",{class:"dl-sub"},"Nightly when something changed, and before every restore, import or update. The last 10 are kept.")]),e("span",{class:"dl-spacer"}),R([b("plus")," Back up now"],async()=>{await O(()=>z.backupCreate(),"Backup created")&&t()},"positive")]),s]),e("div",{class:"dl-setsec-foot"},[e("span",{class:"dl-sub"},"Backups contain private keys: keep downloads safe. JSON moves everything except usage history to another router."),e("span",{class:"dl-row-actions dl-bk-actions"},[o,r,l])])])}function it(i,t,n){i.some(([o])=>o===t)||(i=[...i,[t,t]]);let a=e("div",{class:"dl-seg sm",role:"radiogroup","aria-label":n,"data-value":t}),s=()=>dom.content(a,i.map(([o,r])=>e("button",{type:"button",role:"radio",class:o===a.dataset.value?"on":"","aria-checked":o===a.dataset.value?"true":"false",click:()=>{a.dataset.value=o,s()}},r)));return s(),a}function Ft(i,t,n=`${t}s`){return`${i.toLocaleString("en-GB")} ${i===1?t:n}`}function yt(i){return i<1024?`${i} B`:i<1048576?`${(i/1024).toFixed(i<10240?1:0)} KB`:`${(i/1048576).toFixed(1)} MB`}var kt=class{constructor(){this.root=e("div",{class:"dl-settings-main"});this.backups=[]}load(){return z.settingsGet()}render(t){return this.d=t,this.paint(),this.loadBackups().then(()=>{new URLSearchParams(location.search).get("section")==="backups"&&document.getElementById("dl-set-backups")?.scrollIntoView({block:"start"})}),e("div",{},[e("div",{class:"dl-pagehead"},[e("h2",{class:"dl-h1"},"Settings")]),this.root])}async save(t,n="Saved"){let a=await O(()=>z.settingsUpdate(t),n);a&&(this.d=a,this.paint())}section(t,n,a,s,o="",r=[]){return e("section",{class:`dl-setsec ${o}`,id:`dl-set-${t}`},[e("div",{class:"dl-setsec-body"},[r.length?e("div",{class:"dl-setsec-head"},[e("h3",{},n),e("span",{class:"dl-spacer"}),...r]):e("h3",{},n),...a]),s.length?e("div",{class:"dl-setsec-foot"},s):""])}portalSection(){let t=this.d.settings,n=this.d.effective,a=this.d.cert,s=this.d.portal_candidates??[],o=this.d.portal_checks??[],r=Ee(n.portal_enabled,"Enable portal"),l=se(t.portal_port,{placeholder:"8443",inputmode:"numeric",class:"cbi-input-text dl-w-port"}),d=Ee(n.portal_443,"Standard ports",()=>D()),p=se(t.portal_title,{placeholder:"Dawnline"}),u=se(t.portal_redirect,{placeholder:"Show “Not found”",class:"cbi-input-text dl-mono"}),c=se("",{placeholder:"vpn.example.com or an IP","aria-label":"Other address"}),x=H=>/^\d{1,3}(\.\d{1,3}){3}$/.test(H),g=[n.portal_host,...n.portal_alt??[]].filter((H,re,M)=>H&&M.indexOf(H)===re);!g.length&&s[0]&&(g=[s[0].host]);let k=[...s],G=H=>{H&&!k.some(re=>re.host===H)&&k.push({host:H,kind:x(H)?"ip":"name",ips:[],here:!1,cloudflare:!1,cert:!1})};g.forEach(G);let K=H=>H.kind==="ip"?e("span",{class:"dl-addr-warn"},[b("alert"),"Plain HTTP: the link and VPN keys travel unencrypted"]):e("span",{class:"dl-sub"},H.cloudflare?"Behind Cloudflare · often stalls in Russia":H.ips.length?H.here?`Points at this router${H.cert?" · Let’s Encrypt certificate":" · no certificate yet"}`:`Points at ${H.ips.join(", ")}, not this router`:"Your address"),I=e("div",{class:"dl-addr-opts",role:"group","aria-label":"Portal addresses"}),_=H=>{g.includes(H)?g.length>1&&(g=g.filter(re=>re!==H)):g=[...g,H],N(),D()},N=()=>dom.content(I,[...k.map(H=>{let re=g.includes(H.host),M=g[0]===H.host;return e("div",{class:`dl-addr-opt${re?" on":""}`,role:"checkbox","aria-checked":re?"true":"false",tabindex:"0",click:()=>_(H.host),keydown:E=>{(E.key===" "||E.key==="Enter")&&(E.preventDefault(),_(H.host))}},[e("i",{class:"dl-addr-check"},re?b("check"):""),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono"},H.host),K(H)]),M?e("span",{class:"dl-pill info"},"Main"):re?e("button",{type:"button",class:"dl-linkbtn",click:E=>{E.stopPropagation(),g=[H.host,...g.filter(w=>w!==H.host)],N(),D()}},"Make main"):H.cloudflare?e("span",{class:"dl-pill warn"},"Cloudflare"):H.kind==="ip"?e("span",{class:"dl-pill"},"IP"):H.here&&H.cert?e("span",{class:"dl-pill ok"},"Recommended"):""])}),e("div",{class:"dl-addr-opt other"},[e("i",{class:"dl-addr-check"},b("plus")),c,R("Add",()=>{let H=c.value.trim().toLowerCase();H&&(G(H),g.includes(H)||(g=[...g,H]),c.value="",N(),D())})])]);c.addEventListener("keydown",H=>{H.key==="Enter"&&(H.preventDefault(),c.nextElementSibling?.click())});let C=e("div",{class:"dl-links"}),D=()=>{let H=Ye(d),re=Number(l.value)||n.portal_port;dom.content(C,g.map((M,E)=>{let w=x(M),y=w?H?80:re+1:H&&!this.d.wan443_taken?443:re,T=`${w?"http":"https"}://${M}${y===(w?80:443)?"":`:${y}`}/`;return e("div",{class:"dl-link-row"},[e("span",{class:`dl-link-ic ${w?"warn":"ok"}`},b(w?"alert":"lock")),e("span",{class:"dl-mono dl-link-url"},[T,e("b",{},"kamiro-telosu-bavine")]),E===0?e("span",{class:"dl-pill info"},"Main"):w?e("span",{class:"dl-pill warn"},"HTTP"):""])}))};N(),D(),l.addEventListener("input",()=>D());let $={portal:"Portal running",portal_dns:"Points here",portal_reply:"Answers reach visitors",portal_443:"Port 443",portal_lan:"Works at home",portal_http:"Plain HTTP",cert:"Certificate"},A=o.filter(H=>H.status!=="skip"),m=A.filter(H=>H.status==="error"||H.status==="warn"),h=A.some(H=>H.status==="error")?"error":m.length?"warn":"ok",P=e("div",{class:"dl-ready-details",hidden:!0},A.map(H=>e("div",{class:`dl-ready-item ${H.status}`},[b(H.status==="ok"?"check":"alert"),e("span",{class:"dl-stack"},[e("span",{},H.title),e("span",{class:"dl-sub"},H.detail)])]))),f=e("div",{class:"dl-stack gap8"},[e("div",{class:`dl-ready-sum ${h}`},[b(h==="ok"?"check":"alert"),e("span",{class:"dl-stack"},[e("b",{},h==="ok"?`All ${A.length} checks passed`:`${A.length-m.length} of ${A.length} checks passed`),m.length?e("span",{class:"dl-sub"},m.map(H=>H.detail).join(" ")):e("span",{class:"dl-sub"},"Links will open for the people you send them to.")]),e("button",{type:"button",class:"dl-linkbtn",click:H=>{P.hidden=!P.hidden,H.currentTarget.textContent=P.hidden?"Details":"Hide"}},"Details")]),e("div",{class:"dl-chips-row"},A.map(H=>e("span",{class:`dl-check-chip ${H.status}`,title:H.detail},[b(H.status==="ok"?"check":"alert"),$[H.id]??H.title]))),P]),S=a&&!a.self_signed&&a.expires?new Date(a.expires).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}):"",j=ee("Standard ports",d,this.d.wan443_taken?"Port 443 is already forwarded to another device, so HTTPS links keep the listening port.":"Links without a port: 443 for names, 80 for IP addresses. Mobile networks often drop other ports. From the internet these reach only the portal; LuCI stays closed."),W=ee("Listening port",l,this.d.port_owners.length?`Port ${n.portal_port} is used by ${this.d.port_owners.join(", ")}.`:`Where the portal runs on the router: HTTPS here, plain HTTP for IP addresses on ${n.portal_port+1}.`),v=!!(t.portal_cert&&t.portal_key),U=a?v?"Your files":a.self_signed?"Self-signed":"Let’s Encrypt":"Portal is off",q=()=>{let H=se(t.portal_cert,{placeholder:"/etc/ssl/…/fullchain.crt"}),re=se(t.portal_key,{placeholder:"/etc/ssl/…/key"});ne("Use your own certificate",[e("p",{class:"dl-muted"},"Paths on the router. Leave both empty to pick a certificate automatically."),ee("Certificate file",H),ee("Key file",re)],[e("button",{class:"cbi-button cbi-button-neutral",click:Z},"Cancel")," ",R("Save",()=>{Z(),this.save({portal_cert:H.value.trim(),portal_key:re.value.trim()},"Certificate saved")},"positive")])},X=this.d.needs??{https:[],acme:[],home:[]},le=(H,re,M,E,w,y)=>e("div",{class:`dl-row dl-need-row ${re}`},[re?e("span",{class:"dl-need-ic"},b(H)):b(H),e("span",{class:"dl-row-main dl-stack"},[e("b",{},M),e("span",{class:"dl-sub"},E)]),R(y,()=>at(w,X[w],()=>this.reload()),"positive")]),ie=X.https.length?le("lock","bad","HTTPS isn’t available on this router",`The portal needs ${X.https.join(" and ")}. It can’t start without them.`,"https","Install"):"",me=X.acme.length&&(!a||a.self_signed)?le("lock","","Free certificate from Let’s Encrypt",`ACME isn’t installed. With it the router gets a certificate${t.portal_host?` for ${t.portal_host}`:""} and browsers stop warning.`,"acme","Install ACME"):"",De=[e("div",{class:"dl-row"},[b("lock"),e("span",{class:"dl-row-main dl-stack"},[e("b",{},[U,S?e("span",{class:"dl-faint"},` · until ${S}`):""]),e("span",{class:"dl-sub dl-ellipsis",title:a?.path??""},a?a.self_signed?"Made by the router: browsers warn until a certificate covers the address.":`${v?"Your files":"Found automatically"} · ${a.path}`:"Turn the portal on to see its certificate.")])]),e("div",{class:"dl-row"},[b("file"),e("span",{class:"dl-row-main dl-stack"},[e("b",{},"Your own files"),e("span",{class:"dl-sub"},v?`${t.portal_cert} · ${t.portal_key}`:"Not set: the certificate is picked automatically.")]),v?R("Reset",()=>this.save({portal_cert:"",portal_key:""},"Automatic certificate"),"negative"):"",R(v?"Change":"Use files",q)]),me];return this.section("portal","Personal portal",[e("span",{class:"dl-muted"},"A page where each person adds and manages their devices with their personal link."),ie?e("div",{class:"dl-list"},[ie]):"",ue("network","Ports","How the portal listens",[j,W]),ue("edit","Appearance","What people see",[ee("Title",p,"Shown at the top of the portal."),ee("Unknown links",u,"Where a wrong or old link goes, for example your website. Empty shows a plain “Not found”.")]),ue("link","Addresses","Pick one or more; the first is the main link",[I,e("div",{class:"dl-stack gap8"},[C,e("span",{class:"dl-sub"},"Example code; each person gets their own three words.")])]),ue("lock","Certificate","Used for HTTPS links",De),n.portal_enabled&&A.length?ue("check","Ready to share","The portal’s checks from Health",[f]):""],[e("span"),R("Save",()=>this.save({portal_enabled:Ye(r)?"1":"0",portal_443:Ye(d)?"1":"0",portal_host:g[0]??"",portal_alt:g.slice(1),portal_port:l.value,portal_title:p.value,portal_redirect:u.value.trim()}),"positive")],"",[n.portal_enabled?X.https.length?e("span",{class:"dl-pill bad"},"Can’t start"):e("span",{class:`dl-pill ${h==="ok"?"ok":h==="error"?"bad":"warn"}`},h==="error"?"Needs attention":"Ready"):"",r])}paint(){let t=this.d.settings,n=this.d.effective,a=this.portalSection(),s=se(t.default_device_limit,{placeholder:"3",inputmode:"numeric",class:"cbi-input-text dl-w-port"}),o=Ee(n.hostnames,"Device hostnames"),r=se(t.domain,{placeholder:"lan",class:"cbi-input-text dl-w-port"}),l=se(t.home_dns_fallback==="none"?"":t.home_dns_fallback||n.home_dns_fallback||"",{placeholder:"None",inputmode:"decimal",class:"cbi-input-text dl-w-ip dl-mono"}),d=this.section("defaults","Defaults",[ee("Devices per person",s,"Pre-filled when you add someone."),ee("Device hostnames",e("div",{class:"dl-hostport"},[o,e("span",{class:"dl-faint dl-mono"},"phone.myata."),r]),"Name devices in your home DNS."),ee("Fallback DNS",l,"For Home-only devices using home names: the second DNS server, used by the device when the tunnel is down. Empty = none.")],[e("span"),R("Save",()=>this.save({default_device_limit:s.value,hostnames:Ye(o)?"1":"0",domain:r.value,home_dns_fallback:l.value}),"positive")]),p=Ee(n.geo_enabled,"Locations"),u=e("select",{class:"cbi-input-select"},[e("option",{value:"ipwho.is",selected:n.geo_provider!=="ipapi.co"?"selected":null},"ipwho.is (fallback: ipapi.co)"),e("option",{value:"ipapi.co",selected:n.geo_provider==="ipapi.co"?"selected":null},"ipapi.co (fallback: ipwho.is)")]),c=this.section("map","Map & locations",[e("div",{class:"dl-setrow head"},[e("span",{class:"dl-muted"},"Show where people connect from on the Overview and person pages, at city level."),p]),ee("Provider",u)],[e("span",{class:"dl-sub"},"The router sends each new client IP to the provider once and caches the city. Map tiles load in your browser from CARTO; people never see the map."),R("Save",()=>this.save({geo_enabled:Ye(p)?"1":"0",geo_provider:u.value}),"positive")]),x=this.logsSection(),g=this.section("danger","Remove Dawnline from this router",[e("p",{class:"dl-muted"},"Deletes the tunnel, firewall rules, access table and hostnames Dawnline created, and stops the service. People and keys are kept in a backup.")],[e("span"),R("Remove",()=>this.uninstall(),"negative")],"danger"),k=Gt(this.backups,()=>{this.reload(),this.loadBackups()});dom.content(this.root,[a,d,c,x,k,g])}logsSection(){let t=this.d.logs,n=t.policy,a=it([["7","7 days"],["30","30 days"],["90","90 days"],["365","1 year"],["0","No limit"]],String(n.keep_days),"Keep activity"),s=it([["500","500"],["2000","2,000"],["5000","5,000"],["20000","20,000"]],String(n.max),"Maximum events"),o=it([["10min","Every 10 min"],["hourly","Hourly"],["off","Memory only"]],n.persist,"Save to flash"),r=it([["31","1 month"],["62","2 months"],["180","6 months"],["365","1 year"],["730","2 years"]],String(n.usage_days),"Daily traffic"),l=it([["12","1 year"],["24","2 years"],["60","5 years"],["120","10 years"]],String(n.usage_months),"Monthly traffic"),d=new Set(n.categories),p=e("div",{class:"dl-chips-row"},Ze.map(k=>{let G=e("button",{type:"button",class:`dl-chipbtn${d.has(k)?" on":""}`,title:hn[k],click:()=>{d.has(k)?d.delete(k):d.add(k),G.classList.toggle("on",d.has(k))}},[Ge[k],e("b",{},String(t.by_category[k]??0))]);return G})),u=k=>new Date(k).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}),c=t.oldest?u(new Date(t.oldest*1e3)):"",x=(k,G,K,I)=>e("div",{class:"dl-row"},[b(k),e("span",{class:"dl-row-main dl-stack"},[e("b",{},G),e("span",{class:"dl-sub"},K)]),...I]),g=k=>R(k.toUpperCase(),async()=>{let[G,K]=await Promise.all([z.status(1),z.events(2e4)]);Le(G,K.events,k)},"neutral",{title:`Download the log as ${k.toUpperCase()}`});return this.section("logs","Logs & history",[e("p",{class:"dl-muted"},Ot(n)),ee("Keep activity",a,"Older events are removed automatically."),ee("Maximum size",s,"Newest events are kept when the log is full."),ee("Record",p,"Switched-off categories are not logged from now on."),ee("Save to flash",o,"The log lives in memory and is copied to flash. Memory only saves flash writes but is lost on reboot."),ee("Daily traffic",r,"Per-day history behind the charts."),ee("Monthly traffic",l,"Per-month totals; data limits use the current month."),e("h4",{class:"dl-setsub"},"Stored data"),e("div",{class:"dl-list"},[x("activity","Activity log",t.events?`${Ft(t.events,"event")} since ${c} · ${yt(t.log_ram)} in memory${n.persist==="off"?"":`, ${yt(t.log_flash)} on flash`}`:"Empty",[g("csv"),g("json"),R("Clear",()=>Te("Clear activity","Removes events from the log on the router.",{},()=>this.reload()),"negative")]),x("chart","Traffic history",t.usage_days?`${Ft(t.usage_days,"day")} since ${u(t.usage_since)} · ${yt(t.usage_flash)} on flash`:"Empty",[R("Reset",()=>Fe("all","","",()=>setTimeout(()=>this.reload(),300)),"negative")]),x("pin","Location cache",`${Ft(this.d.geo_cached,"address","addresses")} · ${yt(t.geo_flash)} on flash`,[R("Clear",async()=>{await O(()=>z.geoClear(),"Location cache cleared")&&this.reload()},"negative")])])],[e("span",{class:"dl-sub"},"Clear one person or device from their own page."),R("Save",()=>this.save({log_keep_days:a.dataset.value,log_max:s.dataset.value,log_persist:o.dataset.value,usage_keep_days:r.dataset.value,usage_keep_months:l.dataset.value,log_category:[...d]}),"positive")])}async loadBackups(){let t=await z.backupList().catch(()=>null);if(t){this.backups=t.backups;let n=document.getElementById("dl-set-backups");n&&n.replaceWith(Gt(this.backups,()=>{this.reload(),this.loadBackups()}))}}async reload(){let t=await z.settingsGet().catch(()=>null);t&&(this.d=t,this.paint())}uninstall(){let t=se("",{placeholder:"remove"});ne("Remove Dawnline?",[e("p",{},"Everyone is disconnected and the tunnel, firewall rules and portal are removed. A backup is made first. Type “remove” to confirm."),t],[e("button",{class:"cbi-button cbi-button-neutral",click:Z},"Cancel")," ",R("Remove Dawnline",async()=>{await O(()=>z.uninstall(t.value.trim()),"Dawnline removed")&&(Z(),setTimeout(()=>location.reload(),800))},"negative")])}};var Ja={ok:"check",warn:"alert",error:"x",skip:"pause"},Tn={apply:"Repair",sync:"Reload devices",restart:"Restart service",updates:"Open updates"},$t=class{constructor(t,n,a,s){this.el=e("div",{});this.wdEl=e("div",{});this.checksEl=e("div",{class:"dl-panel"});this.recentEl=e("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=e("div",{});this.open=new Set;this.st=t,this.sl=n,this.events=a,this.toLog=s,dom.content(this.el,[this.summary,this.wdEl,e("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(n,a)}async run(t){let n=t?await O(()=>z.healthFix(t),"Done"):await z.health().catch(()=>null);n&&this.take(n)}take(t){this.checks=t.checks,this.paintChecks(),this.paintLive(t,this.events)}paintChecks(){let t=this.checks;if(!t){dom.content(this.summary,""),dom.content(this.checksEl,[e("div",{class:"dl-panel-head"},[e("h3",{},"Checks")]),e("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let n=t.filter(r=>r.status==="error").length,a=t.filter(r=>r.status==="warn").length;dom.content(this.summary,n?Ae("error",`${n} problem${n>1?"s":""} need attention.`):a?Ae("warn",`${a} warning${a>1?"s":""}.`):Ae("ok","All checks passed."));let s=new Map;for(let r of this.sl.watchdog.repairs)s.set(r.id,Math.max(s.get(r.id)??0,r.ts));let o=()=>this.run();dom.content(this.checksEl,[e("div",{class:"dl-panel-head"},[e("h3",{},"Checks"),e("span",{class:"dl-spacer"}),R("Run again",o)]),e("ul",{class:"dl-checks"},t.map(r=>e("li",{},[e("span",{class:`dl-check-icon ${r.status}`},b(Ja[r.status])),e("div",{class:"dl-check-body"},[e("div",{class:"dl-check-title"},r.title),e("div",{class:"dl-check-detail"},r.detail),s.has(r.id)?e("div",{class:"dl-check-repaired"},`Repaired by the watchdog at ${Ne(s.get(r.id))}`):""]),r.fix?r.fix.startsWith("install:")?R("Install",()=>$n(r.fix.slice(8),o),"action"):r.fix==="updates"?e("a",{class:"cbi-button cbi-button-action",href:L.url("admin/network/dawnline/updates")},Tn.updates):R(Tn[r.fix]??"Fix",()=>this.run(r.fix),"action"):""])))])}paintLive(t,n){this.sl=t,this.events=n;let a=t.watchdog,s=a.beat!=null&&a.now-a.beat>180,o=a.repairs.filter(d=>a.now-d.ts<86400),r=o[o.length-1],l=Ee(a.enabled,"Watchdog repairs",async d=>{await O(()=>z.settingsUpdate({watchdog:d?"1":"0"}),d?"Watchdog on":"Watchdog off")||l.classList.toggle("on",!d);let u=await z.serviceLog().catch(()=>null);u&&this.paintLive(u,this.events)});dom.content(this.wdEl,e("div",{class:"dl-panel dl-wd"},[e("div",{class:"dl-wd-head"},[e("span",{class:`dl-wd-tile${a.enabled?"":" off"}`},b("shield")),e("div",{class:"dl-stack"},[e("span",{class:"dl-wd-title"},"Watchdog"),e("span",{class:"dl-sub"},a.enabled?"Every minute it checks the tunnels and services and repairs what it can on its own.":"Off: problems are only written to the log. Nothing is repaired on its own.")]),e("span",{class:"dl-spacer"}),l]),e("div",{class:"dl-wd-foot"},[e("div",{class:"dl-wd-chips"},a.targets.map(d=>e("span",{class:`dl-check-chip${d.ok?"":" error"}`,title:d.ok?"OK":`Not working${d.tries?` · ${d.tries} repair${d.tries>1?"s":""}`:""}`},[b(d.ok?"check":"x"),d.name]))),e("span",{class:`dl-sub${s?" dl-warn-text":""}`},s?`The agent has not checked in for ${Math.round((a.now-a.beat)/60)} min; cron restarts it after 5.`:[a.last?`Looked ${he(a.last,a.now)}`:"Starts within a minute"," · ",o.length?`${o.length} repair${o.length>1?"s":""} today, last ${r.name} at ${Ne(r.ts)}`:"no repairs today"])])])),this.paintRecent()}paintRecent(){let t=Date.now()/1e3-604800,n=[...this.events.map(s=>({ts:s.ts,ev:s})),...this.sl.log.map(s=>({ts:s.ts,sys:s}))].filter(s=>s.ts>=t&&Ut(s)).sort((s,o)=>o.ts-s.ts),a=e("div",{class:"dl-panel-head pad"},[e("h3",{},"Recent problems"),e("span",{class:"dl-spacer"}),n.length?e("a",{href:"#",click:s=>(s.preventDefault(),this.toLog())},"All in Log →"):""]);if(!n.length){dom.content(this.recentEl,[a,e("div",{class:"dl-recent-empty"},[e("span",{class:"dl-check-icon ok"},b("check")),"No problems in the last 7 days."])]);return}dom.content(this.recentEl,[a,...n.slice(0,8).map(s=>{if(s.sys){let r=s.sys,l=`${r.ts}|${r.msg}`;return qt(r,this.open.has(l),()=>{this.open.delete(l)||this.open.add(l),this.paintRecent()},Ne(r.ts))}let o=Ie(this.st,s.ev);return o.lastElementChild.textContent=Ne(s.ts),o})])}},Qa=[{title:"ip-full · veth",sub:"Policy routing and the home-like link",pkgs:["ip-full","kmod-veth"],feature:"home"},{title:"OpenSSL",sub:"HTTPS for the personal portal",pkgs:["libustream-openssl","openssl-util"],feature:"https"},{title:"ACME",sub:"Let’s Encrypt certificate for the portal",pkgs:["acme","acme-acmesh-dnsapi"],feature:"acme",optional:!0}],_t=class{constructor(){this.running=!1}load(){return z.updatesStatus()}render(t){return this.root=e("div",{class:"dl-root dl-upd"}),this.paint(t),poll.add(async()=>{let n=await z.updatesStatus().catch(()=>null);n&&n.job?.state==="running"?this.paint(n):n&&this.running&&(this.running=!1,this.paint(n),n.job?.component==="app"&&n.job.state==="done"&&(ui.menu?.flushCache(),setTimeout(()=>location.reload(),1500)))},3),this.root}paint(t){let n=t.job;this.running=n?.state==="running";let a=t.check?.components??{},s=t.firmware,o=a.app,r=a.amneziawg,l=a.packages,d={disabled:this.running},p=(f,S)=>e("span",{class:`dl-pill ${f}`},S),u=(f,S,j)=>e("div",{class:"dl-upd-row"},[e("span",{class:"dl-stack"},[e("span",{class:"dl-upd-name"},f),e("span",{class:"dl-sub"},S)]),j]),c=(f,S,j,W,v=[])=>e("section",{class:"dl-setsec dl-upd-sec"},[e("div",{class:"dl-upd-head"},[e("span",{class:"dl-group-ic"},b(f)),e("span",{class:"dl-stack"},[e("b",{},S),e("span",{class:"dl-sub"},j)]),W]),...v]),x=f=>f?new Date(f).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}):"",g=c("sunrise","Dawnline",o?.repo?`${t.version} · ${o.repo}`:t.version,o?o.update?R(`Update to ${o.latest}`,()=>this.run("app"),"positive",d):o.latest?p("ok","Up to date"):p("","No releases yet"):p("","Not checked")),k=r?.sources??{},K=Object.keys(k).map(f=>{let S=k[f],j=r?.current===f,W=[S.version?`${S.tag} build${S.date?` · ${x(S.date)}`:""} · ${S.gen==="3.1"?"devices need AmneziaVPN with 3.1":"works with every AmneziaWG app"}`:`No build for OpenWrt ${s?.version??""}`],v=S.version?j?r?.update?R("Update",()=>this.runAwg(f,!!r.ru,S.gen),"positive",d):p("ok","Installed"):R("Switch",()=>this.runAwg(f,!!r?.ru,S.gen),"neutral",d):p("","No build");return u([S.gen?`AmneziaWG ${S.gen}`:"AmneziaWG",e("span",{class:"dl-faint"},` · ${S.label}`)],W,v)});r?.current&&k[r.current]?.version&&K.push(u("Russian translation","LuCI pages for AmneziaWG in Russian",R(r.ru?"Remove":"Add",()=>this.runAwg(r.current,!r.ru,r.gen),"neutral",d)));let I=c("shield","AmneziaWG",r?.installed?`${r.gen?`${r.gen} · `:""}${r.installed} · changing it restarts every tunnel`:"Not installed",r?"":p("","Not checked"),K.length?K:[u("Builds for this router","Check for updates to see them.","")]),_=l?.pkgs??{},N=[],C=Qa.filter(f=>f.feature==="home"?t.home:t.portal);for(let f of C){let S=f.pkgs.filter(v=>_[v]?.installed),j=[...new Set(S.flatMap(v=>[..._[v]?.latest?[v]:[],..._[v]?.with??[]]))],W=t.needs?.[f.feature]??f.pkgs.filter(v=>!_[v]?.installed);if(W.length)N.push(u(f.title,f.optional?`Not installed · ${f.sub}`:e("span",{class:"dl-upd-bad"},`Missing ${W.join(", ")} · ${f.sub}`),R("Install",()=>this.runPkgs(W,f.title),"neutral",d)));else if(j.length){let v=S.find(X=>_[X]?.latest),U=v?[e("span",{class:"dl-mono"},[`${_[v].installed} → `,e("b",{},_[v].latest)])]:[],q=j.filter(X=>X!==v);q.length&&U.push(`${v?" · ":""}${q.length<=2?`${v?"with ":""}${q.join(", ")}`:`${v?"+":""}${q.length} related packages`}`),N.push(u(f.title,U,R("Update",()=>this.runPkgs(S.filter(X=>_[X]?.latest||_[X]?.with?.length),f.title,j),"neutral",d)))}else N.push(u(f.title,f.sub,p("ok","Up to date")))}let D=C.flatMap(f=>f.pkgs).filter(f=>_[f]?.installed),$=[...new Set(D.flatMap(f=>[..._[f].latest?[f]:[],..._[f].with??[]]))],A=c("package","System packages",l?$.length?`${$.length} update${$.length===1?"":"s"} from the OpenWrt ${s?.version?.replace(/\.\d+$/,"")??""} feeds`:"What Dawnline adds to OpenWrt is current":"What Dawnline adds to OpenWrt",l?$.length?R("Update all",()=>this.runPkgs(D.filter(f=>_[f].latest||_[f].with?.length),"all packages",$),"positive",d):"":p("","Not checked"),l?N:[]),m=n?e("details",{class:"dl-params dl-upd-job",open:this.running?"open":null},[e("summary",{},[b("chevron"),e("span",{},"Last job"),p(n.state==="done"?"ok":n.state==="failed"?"bad":"warn",n.state==="running"?n.phase||"Running":n.state==="done"?"Finished":"Failed"),e("span",{class:"dl-sub"},`${n.action==="check"?"check":n.component??""} · ${Ne(n.started)}${n.finished?` · ${n.finished-n.started} s`:""}`)]),n.error?Ae("error",n.error):"",e("pre",{class:"dl-log"},n.log.join(` -`))]):"",h=$.length+(o?.update?1:0)+(r?.update?1:0),P=[s?.version?`OpenWrt ${s.version} · ${s.target}`:"",t.check?h?`${h} update${h===1?"":"s"} ready`:"everything is current":"not checked yet",t.check?`checked ${Ne(t.check.time)}`:""].filter(Boolean).join(" · ");dom.content(this.root,[e("div",{class:"dl-pagehead"},[e("div",{class:"dl-stack"},[e("h2",{class:"dl-h1"},"Updates"),e("span",{class:"dl-faint"},P)]),R([b("refresh")," Check now"],()=>this.run("check"),"neutral",d)]),g,I,A,m])}async runAwg(t,n,a){await oe(a?`Install AmneziaWG ${a}?`:"Install AmneziaWG?","Every AmneziaWG tunnel on the router restarts for a few seconds, HomeTunnel too. Devices stay configured.","Install")&&this.start(`amneziawg:${t}${n?":ru":""}`)}async runPkgs(t,n,a=t){await oe(`Update ${n}?`,`${a.join(", ")} from the OpenWrt feeds. Services that use them restart for a moment.`,"Update")&&this.start(`pkgs:${t.join(",")}`)}async run(t){t!=="check"&&!await oe(`Update ${t==="app"?"Dawnline":t}?`,"A backup is made first. The page reloads when it finishes.","Update")||this.start(t)}async start(t){if(await O(()=>z.updatesRun(t))){this.running=!0;let n=await z.updatesStatus().catch(()=>null);n&&this.paint(n)}}};function Kt(i){return`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")}`}function Za(i,t,n,a=30){let s=i?new Date(`${i}T12:00:00`):new Date;return t==="day"?s.setDate(s.getDate()+n):t==="week"?s.setDate(s.getDate()+7*n):t==="month"?s.setMonth(s.getMonth()+n):t==="year"?s.setFullYear(s.getFullYear()+n):s.setDate(s.getDate()+a*n),Kt(s)}var Xa={internet:"Browse the internet through your router. No access to devices at home, and home cannot reach theirs.",lan:"Reach devices at home, and home reaches theirs. Internet stays on their own connection.",both:"Home devices and the internet, all through your router. Home reaches their devices too."},St=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.refreshSeq=0;this.refreshShown=0}async load(){this.id=new URLSearchParams(location.search).get("id")??"";let[t,n,a]=await Promise.all([z.status(30),z.events(5e3).catch(()=>({events:[]})),z.personUsage(this.id,30).catch(()=>null)]);return this.series=a?.person??[],this.devSeries=a?.devices??{},[t,n.events]}render([t,n]){this.st=t,this.events=n;let a=t.people.find(l=>l.id===this.id);if(!a)return e("div",{class:"dl-empty"},[e("h3",{},"Person not found"),e("p",{},"They may have been removed."),e("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=a;for(let l of["head","devices","traffic","places","activity","limits"])this.parts[l]=e("div",{});this.parts.devices.className="dl-person-devices";let s=e("div",{},[e("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[e("a",{href:Qe(a.server)},t.servers.find(l=>l.id===a.server)?.name??"Servers"),e("span",{},"/"),e("a",{href:Qe(a.server)},"People"),e("span",{},"/"),e("span",{},a.name)]),this.parts.head,e("div",{class:"dl-grid-person"},[e("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),e("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let o=new URLSearchParams(location.search),r=o.get("device")&&a.devices.find(l=>l.id===o.get("device"));return r?setTimeout(()=>Ce(this.p,r,()=>this.refresh(),this.st.geo),50):o.get("add")&&setTimeout(()=>Ke(this.p,()=>this.refresh()),50),poll.add(()=>this.refresh(!0),15),s}async refresh(t=!1){let n=++this.refreshSeq,[a,s,o]=await Promise.all([z.status(30).catch(()=>null),z.events(5e3).catch(()=>null),z.personUsage(this.id,30).catch(()=>null)]);if(!a||nl.id===this.id);if(!r){t||(location.href=Qe(this.p?.server));return}this.p=r,this.paint(),this.map?.update(this.mapData())}async patch(t,n){var o;let a=await O(()=>z.personUpdate(this.p.id,t),n);if(!a)return;let s=this.st.people.findIndex(r=>r.id===this.p.id);(o=a.person).rate??(o.rate=this.p.rate),s>=0&&(this.st.people[s]=a.person),this.p=a.person,this.paint()}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}mapCard(){let t=e("div",{class:"dl-panel-head pad"},[e("h3",{},"Locations"),e("span",{class:"dl-spacer"}),this.st.geo.enabled?dt("30d",n=>this.map?.setRange(n),!1):"",R("Hide",()=>{this.mapOpen=!1,this.map?.destroy(),this.map=null,this.paintPlaces()},"neutral")]);return this.st.geo.enabled?(this.map=new qe({openPerson:()=>{},openDevice:(n,a)=>{let s=this.p.devices.find(o=>o.id===a);s&&Ce(this.p,s,()=>this.refresh(),this.st.geo)}},"30d",280),requestAnimationFrame(()=>this.map.mount(this.mapData())),e("div",{class:"dl-panel flush"},[t,this.map.el])):e("div",{class:"dl-panel flush"},[t,e("div",{class:"dl-map-off"},["Locations are off. ",e("a",{href:L.url("admin/network/dawnline/settings")},"Turn them on in Settings"),"."])])}paint(){let t=this.p,n=this.st,a=t.online?"online now":t.last_seen?`last seen ${he(t.last_seen,n.now)}`:"never connected",s=this.series.find(c=>c.day===Kt(new Date));dom.content(this.parts.traffic,e("div",{class:`dl-person-live${t.online?"":" solo"}`},[t.online?zt(t.rate??[],n.now,s?[s.rx,s.tx]:[0,0]):"",Rt(this.series,`${Q(t.month[0]+t.month[1])} this month`)]));let o=t.created?`Added ${_e(Kt(new Date(t.created*1e3)))}`:"",r=[{label:"Rename",icon:b("edit"),run:()=>this.rename()},{label:t.note?"Edit note":"Add note",icon:b("file"),run:()=>this.editNote()},...t.link?[null,{label:"Invite card",icon:b("qr"),run:()=>this.invite()},{label:"New link",icon:b("key"),run:()=>this.newLink()}]:[],null,{label:t.paused?"Resume":"Pause",icon:b(t.paused?"play":"pause"),warn:!t.paused,run:()=>this.patch({paused:!t.paused},t.paused?"Resumed":"Paused")},{label:"Delete",icon:b("trash"),danger:!0,run:()=>this.remove()}];dom.content(this.parts.head,e("div",{class:"dl-person-head"},[e("div",{class:"dl-pagehead"},[e("div",{class:"dl-person-id"},[e("span",{class:`dl-avatar lg${t.online?" online":""}`},Re(t.name)),e("div",{class:"dl-stack"},[e("div",{class:"dl-title-row"},[e("h2",{class:"dl-h1"},t.name),It(t)]),e("span",{class:"dl-faint",title:o},`${t.devices.length} of ${t.device_limit} devices · ${a}`)])]),e("div",{class:"dl-pcard-actions"},[t.link?ke("link","Copy link",()=>pe(t.link,"Personal link copied"),"neutral","dl-icon-only"):"",ke("more","More",c=>we(c.currentTarget,r),"neutral","dl-icon-only")])]),t.note?e("button",{type:"button",class:"dl-pnote",title:"Edit note",click:()=>this.editNote()},[b("file"),e("span",{},t.note)]):""])),this.paintDevices(),this.paintLimits(),this.paintPlaces();let l=this.events.filter(c=>c.person===t.id),d=[],p=[...l].reverse();for(let c=0;c1){let G=k.querySelector(".dl-row-main");dom.content(G,[...Nt(n,x).slice(0,3),e("span",{class:"dl-muted"},`${g} times`)]),G.title=p.slice(c,c+g).map(K=>K.detail??"").join(` -`)}d.push(k),c+=g-1}let u=R([b("more")],()=>we(u,[{label:"Export CSV",icon:b("download"),run:()=>Le(this.st,l,"csv",t.id)},{label:"Export JSON",icon:b("download"),run:()=>Le(this.st,l,"json",t.id)},null,{label:`Clear ${t.name}'s activity`,icon:b("trash"),danger:!0,run:()=>Te(`Clear ${t.name}'s activity`,`Removes events about ${t.name} and their devices.`,{person:t.id},()=>this.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});dom.content(this.parts.activity,e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-sub"},l.length>10?`latest 10 of ${l.length}`:""),e("span",{class:"dl-spacer"}),u]),d.length?d:e("div",{class:"dl-row dl-muted"},"Nothing yet.")]))}deviceStatus(t){return t.disabled?e("span",{class:"dl-dstat"},"Disabled"):t.online?e("span",{class:"dl-dstat ok"},"Connected"):t.handshake?e("span",{class:"dl-dstat"},`Last seen ${he(t.handshake,this.st.now)}`):e("span",{class:"dl-dstat warn",title:"Waiting for the first connection"},"Not set up yet")}deviceBars(t){let n=(this.devSeries[t]??[]).slice(-30),a=n.map(r=>r.rx+r.tx),s=Math.max(1,...a),o=r=>new Date(`${r}T12:00:00`).toLocaleDateString("en-GB",{day:"numeric",month:"short"});return e("div",{class:"dl-dbars"},n.map((r,l)=>{let d=e("i",{class:`${a[l]?"":"zero"}${l===n.length-1?" hi":""}`});return d.style.height=`${Math.max(8,a[l]/s*100)}%`,ce(d,()=>[e("div",{class:"dl-tip-title"},l===n.length-1?`Today · ${o(r.day)}`:o(r.day)),e("div",{},Q(a[l]))]),d}))}paintDevices(){let t=this.p,n=()=>this.refresh(),a=rt(t.devices).map(o=>{let r=()=>Ce(t,o,n,this.st.geo);return e("article",{class:`dl-dcard${o.online?" online":""}${o.disabled?" off":""}`},[e("div",{class:"dl-dcard-head"},[e("span",{class:"dl-dcard-ic"},b(o.kind)),e("button",{type:"button",class:"dl-dcard-title",click:r},[e("b",{},o.name),this.deviceStatus(o),o.config_stale?e("span",{class:"dl-pill warn dl-stale"},"Update config"):""]),R([b("more")],r,"neutral",{title:`${o.name}: connect, rename, keys, remove`,class:"cbi-button cbi-button-neutral dl-icon-only"})]),o.handshake?e("div",{class:"dl-dcard-trend"},[e("div",{class:"dl-stack"},[e("b",{},Q(o.month[0]+o.month[1])),e("span",{class:"dl-sub"},"this month")]),this.deviceBars(o.id)]):o.disabled?e("div",{class:"dl-sub"},`${Se[o.kind]} · created ${he(o.created,this.st.now)} ${o.created_by==="portal"?"in the portal":"by you"}.`):e("div",{class:"dl-chips-row"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>this.showDeviceQr(o)},[b("qr"),"Show QR"]),e("button",{type:"button",class:"dl-chipbtn",click:()=>this.downloadConfig(o)},[b("download"),"Config"])])])}),s=t.devices.length>=t.device_limit;a.push(e("button",{type:"button",class:"dl-dslot add",click:()=>Ke(t,n)},[e("span",{class:"dl-dslot-ic"},b("plus")),e("span",{class:"dl-stack"},[e("b",{},"Add device"),s?e("span",{class:"dl-sub"},`Over the limit · ${t.devices.length} of ${t.device_limit}`):""])])),dom.content(this.parts.devices,e("section",{class:"dl-devsec"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Devices"),e("span",{class:"dl-sub"},`${t.online} online`)]),e("div",{class:"dl-dgrid"},a)]))}paintLimits(){let t=this.p,n=e("div",{class:"dl-seg wide",role:"radiogroup","aria-label":"Access"},["internet","lan","both"].map(m=>e("button",{type:"button",role:"radio",class:t.access===m?"on":"","aria-checked":t.access===m?"true":"false",click:()=>t.access!==m&&this.patch({access:m},`Access: ${Ue[m]}`)},[b(m==="internet"?"globe":m==="lan"?"home":"shield"),m==="internet"?"Internet":m==="lan"?"Home":"Both"]))),a=ze(t.expires),s=e("input",{type:"date",class:"dl-date-hidden",value:t.expires,tabindex:"-1","aria-hidden":"true"});s.addEventListener("change",()=>s.value&&this.patch({expires:s.value},`Access until ${_e(s.value)}`));let o=(m,h,P)=>{let f=Za(t.expires&&(a??-1)>=0?t.expires:"",m,h);return this.patch({expires:f},`Access until ${_e(f)}`),P},r=[["week",1,"+1 week"],["month",1,"+1 month"],["month",3,"+3 months"],["year",1,"+1 year"]].map(([m,h,P])=>e("button",{type:"button",class:"dl-chipbtn",click:()=>o(m,h,P)},P)),l=e("span",{class:"dl-datechip"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>{try{s.showPicker()}catch{s.focus()}}},[b("calendar"),t.expires?_e(t.expires):"Date"]),s]),d={pause:"pause access",notify:"keep access",remove:"remove their devices"}[t.expire_action],p=e("div",{class:"dl-tile2"},[e("div",{class:"dl-tile2-label"},[e("span",{},"Access ends"),t.expires?e("span",{class:a!=null&&a<0?"dl-bad":a!=null&&a<=t.expire_warn?"dl-warn":"dl-ok"},a!=null&&a<0?"ended":`${a} day${a===1?"":"s"} left`):e("span",{class:"dl-faint"},"no end date")]),e("div",{class:"dl-chips-row"},[...r,l,t.expires?e("button",{type:"button",class:"dl-chipbtn",click:()=>this.patch({expires:""},"No end date")},"No end"):""]),e("div",{class:"dl-tile2-foot"},[e("span",{class:"dl-muted"},`When it ends: ${d}${t.expire_warn?`, warn ${t.expire_warn} day${t.expire_warn===1?"":"s"} before`:""}`),e("a",{href:"#",click:m=>{m.preventDefault(),this.endSettings()}},"Change")])]),u=t.quota_used||t.month[0]+t.month[1],c=t.quota_limit?Math.min(100,t.quota_used/t.quota_limit*100):0,x=e("div",{class:`dl-meter${c>=100?" bad":c>=90?" warn":""}`},[e("i"),t.quota_limit?e("span",{class:"mark",title:"Alert at 90%"}):""]);x.firstChild.style.width=`${c}%`,t.quota_limit&&ce(x,()=>[e("div",{class:"dl-tip-title"},`${c.toFixed(1)}% used`),e("div",{class:"dl-muted"},`${Q(t.quota_used)} of ${Q(t.quota_limit)} · ${Q(Math.max(0,t.quota_limit-t.quota_used))} left`),e("div",{class:"dl-faint"},"Alert at 90%")]);let g=e("div",{class:"dl-seg sm"},["month","total"].map(m=>e("button",{type:"button",class:t.quota_period===m?"on":"",click:()=>t.quota_period!==m&&this.patch({quota_period:m})},m==="month"?"Monthly":"Total"))),k=[10,50,100].map(m=>e("button",{type:"button",class:`dl-chipbtn${t.quota_gb===m?" on":""}`,click:()=>this.patch({quota_gb:String(m)},`Data limit ${m} GB`)},`${m} GB`));k.push(e("button",{type:"button",class:`dl-chipbtn${t.quota_gb?"":" on"}`,click:()=>this.patch({quota_gb:""},"No data limit")},"Unlimited")),k.push(e("button",{type:"button",class:"dl-chipbtn",click:()=>{let m=prompt("Data limit in GB",t.quota_gb?String(t.quota_gb):"");m!=null&&m.trim()!==""&&Number(m)>0&&this.patch({quota_gb:m.trim()},`Data limit ${m.trim()} GB`)}},"Custom"));let G=e("div",{class:"dl-tile2"},[e("div",{class:"dl-tile2-label"},[e("span",{},"Data"),g]),e("div",{class:"dl-tile2-row"},[e("span",{class:"dl-tile2-value"},[Q(u),t.quota_limit?e("span",{class:"dl-faint"},` of ${Q(t.quota_limit)}`):e("span",{class:"dl-faint"}," · no limit")]),t.quota_period==="month"?e("span",{class:"dl-sub"},"resets on the 1st"):""]),t.quota_limit?x:"",e("div",{class:"dl-chips-row"},k),t.quota_gb&&t.quota_period==="month"?e("div",{class:"dl-tile2-foot"},[e("span",{class:"dl-muted"},t.bonus_gb?`Includes +${t.bonus_gb} GB extra this month`:"Need a little more this month?"),e("a",{href:"#",click:m=>{m.preventDefault(),this.patch({bonus_gb:String((t.bonus_gb||0)+10)},"+10 GB this month")}},"+10 GB this month")]):"",e("div",{class:"dl-tile2-foot"},[e("span",{class:"dl-muted"},`${Q(t.total[0]+t.total[1])} in total`),e("button",{type:"button",class:"dl-linkbtn danger",click:()=>Fe("person",t.id,t.name,()=>setTimeout(()=>this.refresh(),300))},"Reset usage")])]),K=!!t.hours,[I,_]=(t.hours||"07:00-23:00").split("-"),N=e("input",{type:"time",class:"cbi-input-text",value:I}),C=e("input",{type:"time",class:"cbi-input-text",value:_}),D=()=>this.patch({hours:`${N.value}-${C.value}`},`Allowed ${N.value}–${C.value}`);N.addEventListener("change",D),C.addEventListener("change",D);let $=e("button",{type:"button",role:"switch","aria-checked":K?"true":"false",class:`dl-switch${K?" on":""}`,"aria-label":"Limit hours",click:()=>this.patch({hours:K?"":"07:00-23:00"},K?"Any time":"Allowed 07:00–23:00")},e("i")),A=e("div",{class:"dl-tile2"},[e("div",{class:"dl-tile2-row"},[e("div",{class:"dl-stack"},[e("span",{class:"dl-tile2-label"},"Allowed hours"),e("span",{},K?`${I} – ${_} (router time)`:"Any time")]),$]),K?e("div",{class:"dl-tile2-row"},[N,e("span",{class:"dl-faint"},"to"),C]):""]);dom.content(this.parts.limits,e("section",{class:"dl-devsec","aria-label":"Access and limits"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Access & limits")]),e("div",{class:"dl-panel"},[e("div",{class:"dl-stack gap8"},[e("span",{class:"dl-tile2-label"},"Can reach"),n,e("span",{class:"dl-sub"},Xa[t.access]),t.access==="lan"&&this.st.services.length?this.servicesPicker():"",Ve(t)?this.netsPicker():"",t.access==="lan"?this.dnsPicker():""]),e("div",{class:"dl-tiles2"},[this.devTile(),this.circleTile(),p,G,A])])]))}dnsPicker(){let t=this.p,n=e("div",{class:"dl-seg sm",role:"radiogroup","aria-label":"DNS"},[["device","Device’s own DNS"],["home","Home names"]].map(([s,o])=>e("button",{type:"button",role:"radio",class:t.dns_mode===s?"on":"","aria-checked":t.dns_mode===s?"true":"false",click:()=>t.dns_mode!==s&&this.patch({dns_mode:s},s==="home"?"Home names on — devices need their configuration again":"Device DNS — devices need their configuration again")},o))),a=this.st.settings.home_dns_fallback;return e("div",{class:"dl-stack gap4 dl-dnspick"},[e("div",{class:"dl-row-actions"},[e("span",{class:"dl-sub"},"DNS"),n]),e("span",{class:"dl-sub"},t.dns_mode==="home"?["Names like ",e("span",{class:"dl-mono"},`nas.${this.st.settings.domain}`)," work. Internet names are resolved at home, so they depend on the tunnel",a?[" (",e("span",{class:"dl-mono"},a)," takes over when it is down)."]:" — with no fallback set, they stop when it is down."]:"Internet keeps working exactly as without the VPN. Reach home devices by IP address.")])}netsPicker(){let t=this.p,a=this.st.servers.find(o=>o.id===t.server)?.home??[];if(a.length<2)return"";let s=new Set(t.home_nets?.length?t.home_nets:a.map(o=>o.dev));return e("div",{class:"dl-stack gap4"},[e("div",{class:"dl-chips-row"},a.map(o=>e("button",{type:"button",class:`dl-chipbtn${s.has(o.dev)?" on":""}`,"aria-pressed":s.has(o.dev)?"true":"false",title:o.nets.join(", "),click:()=>{let r=new Set(s);if(r.delete(o.dev)||r.add(o.dev),!r.size)return te("Keep at least one network, or choose Internet only.","warning",5e3);let l=r.size===a.length?[]:[...r];this.patch({home_nets:l},l.length?`${t.name} reaches ${l.join(", ")}`:`${t.name} reaches every home network`)}},o.dev))),e("span",{class:"dl-sub"},t.home_nets?.length?`Home networks ${t.name} reaches. Networks added to the server later stay out.`:`Home networks ${t.name} reaches: all of them. Untick one to keep ${t.name} out of it.`)])}circleTile(){let t=this.p;if(this.st.servers.find(l=>l.id===t.server)?.mesh!=="circles"||!Ve(t))return"";let a=this.st.circles.filter(l=>l.server===t.server),s=a.find(l=>l.id===t.circle),o=s?this.st.people.filter(l=>l.id!==t.id&&l.circle===s.id&&Ve(l)).map(l=>l.name):[],r=R("Change",()=>we(r,[...a.map(l=>({label:l.name,icon:bt(l),run:()=>l.id!==t.circle&&this.patch({circle:l.id},`${t.name} is in ${l.name}`)})),t.circle?{label:"No circle",icon:b("x"),run:()=>this.patch({circle:""},`${t.name} is in no circle`)}:null,{label:"New circle",icon:b("plus"),run:()=>vt(this.st,t.server,null,()=>this.refresh())}]));return e("div",{class:"dl-tile2"},[e("span",{class:"dl-tile2-label"},["Devices see each other",e("span",{class:"dl-faint dl-w400"},"circle")]),e("div",{class:"dl-tile2-row"},[e("span",{class:"dl-circle-name"},s?[bt(s),s.name]:e("span",{class:"dl-muted"},"No circle")),r]),e("span",{class:"dl-sub"},s?o.length?`${t.name}'s devices and ${o.join(", ")}'s see each other. Others don't.`:`Nobody else in ${s.name} yet: only ${t.name}'s own devices see each other.`:`Only ${t.name}'s own devices see each other.`)])}servicesPicker(){let t=new Set(this.p.services??[]);return e("div",{class:"dl-stack gap4"},[e("div",{class:"dl-chips-row"},this.st.services.map(n=>e("button",{type:"button",class:`dl-chipbtn${t.has(n.id)?" on":""}`,title:`${n.address}${n.ports.length?` · ${n.ports.join(", ")}`:""}`,click:()=>{t.has(n.id)?t.delete(n.id):t.add(n.id),this.patch({services:[...t]},t.size?"Home services updated":"Whole home network")}},n.name))),e("span",{class:"dl-sub"},t.size?"Only the selected services at home.":"Whole home network. Pick services to narrow it down.")])}devTile(){let t=this.p,n=e("div",{class:"dl-slots"});for(let o=0;o=t.device_limit,d=e("i",{class:l?"over":r?"used":""});ce(d,()=>[e("div",{class:"dl-tip-title"},r?`${r.name}${l?" · over the limit":""}`:"Free slot"),e("div",{class:"dl-muted"},r?r.online?"Connected":r.handshake?`Last seen ${he(r.handshake,this.st.now)}`:"Not set up yet":"They can add a device here")]),n.appendChild(d)}let a=Math.max(1,t.devices.length),s=e("button",{type:"button","aria-label":"Allow fewer devices",disabled:t.device_limit<=a?"disabled":null,click:()=>this.patch({device_limit:String(t.device_limit-1)})},"−");return t.device_limit<=a&&t.devices.length>1&&ce(s,()=>[e("div",{class:"dl-tip-title"},`${t.devices.length} devices in use`),e("div",{class:"dl-muted"},"Remove a device first to lower the limit")]),e("div",{class:"dl-tile2"},[e("div",{class:"dl-tile2-label"},"Devices"),e("div",{class:"dl-tile2-row"},[e("span",{class:"dl-tile2-value"},[String(t.devices.length),e("span",{class:"dl-faint"},` / ${t.device_limit}`)]),e("div",{class:"dl-stepper"},[s,e("button",{type:"button","aria-label":"Allow more devices",disabled:t.device_limit>=32?"disabled":null,click:()=>this.patch({device_limit:String(t.device_limit+1)})},"+")])]),n])}paintPlaces(){let t=this.st;if(!t.geo.enabled){dom.content(this.parts.places,e("div",{class:"dl-places"},[b("pin"),e("div",{class:"dl-stack"},[e("span",{},"Locations are off"),e("span",{class:"dl-sub"},"City-level, from the client IP")]),e("span",{class:"dl-spacer"}),e("a",{class:"cbi-button cbi-button-neutral",href:L.url("admin/network/dawnline/settings")},"Turn on")]));return}if(this.mapOpen){(!this.map||!this.parts.places.contains(this.map.el))&&dom.content(this.parts.places,this.mapCard());return}let n=t.now-30*86400,a=t.geo.points.filter(r=>r.person===this.p.id&&r.ts>=n).sort((r,l)=>l.ts-r.ts),s=[...new Set(a.map(r=>r.city||r.country).filter(Boolean))],o=a[0];dom.content(this.parts.places,e("div",{class:"dl-places"},[b("pin"),e("div",{class:"dl-stack"},[e("span",{},o?o.city||o.country:"No locations yet"),e("span",{class:"dl-sub"},o?`${s.length} place${s.length===1?"":"s"} in 30 days${o.org?` · ${o.org}`:""}`:"Shown after a device connects")]),e("span",{class:"dl-spacer"}),a.length?R("Show map",()=>{this.mapOpen=!0,this.paintPlaces()},"neutral"):""]))}invite(){let t=this.st.servers.find(n=>n.id===this.p.server)?.name??"Home";tt(this.p,t)}showQr(){let t=this.p;t.link&&ne(`${t.name}’s link`,[e("div",{class:"dl-qr-pane"},[Pe(Oe(t.link),"dl-qr"),e("div",{class:"dl-hint"},"Scan with the phone camera to open the portal.")])],[e("button",{class:"cbi-button",click:Z},"Close")])}async newLink(){let t=this.p;if(!await oe("Create a new link?","The old link stops working right away.","Create new link",!0))return;let n=await O(()=>z.personRegen(t.id),"New link created");n?.link&&(t.link=n.link,pe(n.link,"New link copied"),this.paint())}async showDeviceQr(t){let n=await O(()=>z.deviceConfig(t.id));n&&ne(`Set up ${t.name}`,[await Ht(n,"qr")],[e("button",{class:"cbi-button",click:Z},"Close")])}async downloadConfig(t){let n=await O(()=>z.deviceConfig(t.id));if(n){if(!n.has_private_key){te("This device made its own keys in the browser; its configuration only exists there.","warning");return}ve(n.filename,n.conf,"application/octet-stream")}}editNote(){let t=e("textarea",{class:"cbi-input-textarea dl-note-input",rows:3,maxlength:500,placeholder:"Only you see this"},this.p.note??"");ne("Note",[t],[e("button",{class:"cbi-button cbi-button-neutral",click:Z},"Cancel")," ",R("Save",async()=>{Z(),await this.patch({note:t.value.trim()},t.value.trim()?"Note saved":"Note removed")},"positive")]),setTimeout(()=>t.focus(),50)}endSettings(){let t=this.p,n=e("select",{class:"cbi-input-select"},[e("option",{value:"pause",selected:t.expire_action==="pause"?"selected":null},"Pause access"),e("option",{value:"notify",selected:t.expire_action==="notify"?"selected":null},"Keep access"),e("option",{value:"remove",selected:t.expire_action==="remove"?"selected":null},"Remove their devices")]),a=e("select",{class:"cbi-input-select"},[0,1,3,7,14].map(s=>e("option",{value:s,selected:t.expire_warn===s?"selected":null},s?`${s} day${s===1?"":"s"} before`:"Don’t warn")));ne("When access ends",[e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},"Then"),e("div",{class:"cbi-value-field"},n)]),e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},"Warn"),e("div",{class:"cbi-value-field"},[a,e("div",{class:"cbi-value-description"},"Shown in their portal and on the Overview.")])])],[e("button",{class:"cbi-button cbi-button-neutral",click:Z},"Cancel")," ",R("Save",async()=>{Z(),await this.patch({expire_action:n.value,expire_warn:a.value},"Saved")},"positive")])}rename(){let t=e("input",{type:"text",class:"cbi-input-text",value:this.p.name,maxlength:48});ne("Rename",[e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},"Name"),e("div",{class:"cbi-value-field"},t)])],[e("button",{class:"cbi-button cbi-button-neutral",click:Z},"Cancel")," ",R("Save",async()=>{Z(),await this.patch({name:t.value},"Renamed")},"positive")]),setTimeout(()=>t.select(),50)}async remove(){let t=this.p;await oe(`Delete ${t.name}?`,`All ${t.devices.length} devices are disconnected immediately and the personal link stops working.`,"Delete",!0)&&await O(()=>z.personDelete(t.id),"Deleted")&&(location.href=Qe(t.server))}};var es=[["health","Health"],["log","Log"]],Lt=class{constructor(){this.tab=new URLSearchParams(location.search).get("tab")==="log"?"log":"health";this.segEl=e("div",{class:"dl-seg dl-srvsections dl-diag-tabs",role:"tablist","aria-label":"Diagnostics"});this.subEl=e("span",{class:"dl-muted"});this.actionsEl=e("div",{class:"dl-row-actions"});this.bodyEl=e("div",{})}load(){return Promise.all([z.status(1),z.events(2e4),z.serviceLog(),this.tab==="health"?z.health().catch(()=>null):Promise.resolve(null)])}render([t,n,a,s]){return this.log=new wt(t,n,a.log),this.health=new $t(t,a,n.events,()=>{this.show("log"),this.log.show("problems")}),s&&this.health.take(s),this.show(this.tab),poll.add(async()=>{if(!this.bodyEl.isConnected)return;let[o,r]=await Promise.all([z.serviceLog().catch(()=>null),z.events(2e4).catch(()=>null)]);r&&this.log.take(r),o&&(this.log.system=o.log),o&&this.health.paintLive(o,r?.events??this.health.events),this.tab==="log"&&(o||r)&&this.log.paint()},10),e("div",{},[e("div",{class:"dl-pagehead"},[e("div",{class:"dl-stack"},[e("h2",{class:"dl-h1"},"Diagnostics"),this.subEl]),this.actionsEl]),this.segEl,this.bodyEl])}show(t){this.tab=t;let n=new URL(location.href);t==="log"?n.searchParams.set("tab","log"):n.searchParams.delete("tab"),history.replaceState(null,"",n),dom.content(this.segEl,es.map(([a,s])=>e("button",{type:"button",role:"tab",class:a===t?"on":"","aria-selected":a===t?"true":"false",click:()=>a!==this.tab&&this.show(a)},s))),this.bodyEl.replaceChildren(t==="log"?this.log.el:this.health.el),this.subEl.textContent=t==="log"?this.log.sub:"Everything Dawnline depends on, checked live. The watchdog repairs what it can on its own.",dom.content(this.actionsEl,t==="log"?this.log.actions():""),t==="log"?this.log.paint():this.health.checks||this.health.run()}};var ts=`:root{--dl-card: var(--panel-bg, var(--background-color-high, transparent));--dl-elevated: var(--elevated, var(--background-color-high, Canvas));--dl-line: var(--border, var(--border-color-medium, color-mix(in srgb, currentColor 14%, transparent)));--dl-soft: var(--muted, color-mix(in srgb, currentColor 5%, transparent));--dl-soft-hover: var(--soft-hover, color-mix(in srgb, currentColor 10%, transparent));--dl-fg: var(--foreground, var(--text-color-highest, inherit));--dl-fg-muted: var(--muted-foreground, color-mix(in srgb, currentColor 65%, transparent));--dl-fg-faint: var(--text-tertiary, color-mix(in srgb, currentColor 50%, transparent));--dl-accent: var(--accent, #3a83f7);--dl-ok: var(--success, #00a240);--dl-warn: var(--warning, #e25507);--dl-bad: var(--danger, #e02e2a);--dl-ok-wash: var(--success-a15, color-mix(in srgb, #00a240 15%, transparent));--dl-warn-wash: var(--warning-a15, color-mix(in srgb, #e25507 15%, transparent));--dl-bad-wash: var(--destructive-a15, color-mix(in srgb, #e02e2a 15%, transparent));--dl-info-wash: var(--info-a15, color-mix(in srgb, #3a83f7 15%, transparent));--dl-info: var(--info, #2c67c5);--dl-track: var(--foreground-a10, color-mix(in srgb, currentColor 10%, transparent));--dl-chart-1: var(--chart-blue, #3a83f7);--dl-chart-2: var(--chart-green, #00a240);--dl-ring: var(--ring, #3a83f7);--dl-primary: var(--primary, #0d0d0d);--dl-primary-fg: var(--primary-foreground, #fff);--dl-mono: var(--font-mono, ui-monospace, Menlo, Consolas, monospace);--dl-shadow: var(--shadow-sm, none);--dl-radius: 16px}.dl-icon-wrap{display:inline-flex;align-items:center;justify-content:center;line-height:0}.dl-icon{width:16px;height:16px}.dl-icon-btn{display:inline-flex!important;align-items:center;gap:6px}.dl-muted{color:var(--dl-fg-muted)}.dl-faint,.dl-sep{color:var(--dl-fg-faint)}.dl-nowrap{white-space:nowrap}.dl-mono{font-family:var(--dl-mono);font-size:13px}.dl-spacer{flex:1}.dl-pill{display:inline-flex;align-items:center;gap:4px;height:20px;padding:0 8px;border-radius:999px;font-size:12px;line-height:20px;font-weight:500;white-space:nowrap;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pill.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-pill.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-pill.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-pill.accent{background:var(--dl-info-wash);color:var(--dl-info)}.dl-pill.off{opacity:.75}.dl-panel{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);padding:16px;margin:0 0 16px;min-width:0;box-shadow:var(--dl-shadow)}.dl-panel-head{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;margin:0 0 12px}.dl-panel-head h3{margin:0!important;padding:0;font-size:16px;line-height:24px;font-weight:500;border:0;background:none}.dl-tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin:0 0 16px}.dl-tile{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);padding:14px 16px;min-width:0;box-shadow:var(--dl-shadow)}.dl-tile-label{font-size:12px;line-height:16px;font-weight:500;color:var(--dl-fg-faint)}.dl-tile-value{font-size:24px;line-height:32px;font-weight:500;margin-top:4px;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;letter-spacing:-.01em}.dl-tile-sub{font-size:12px;line-height:16px;color:var(--dl-fg-muted);margin-top:2px;font-variant-numeric:tabular-nums}.dl-grid2{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(0,1fr);gap:0 16px}@media(max-width:960px){.dl-grid2{grid-template-columns:minmax(0,1fr)}}.dl-chart{display:block;width:100%;height:120px}.dl-bar-down{fill:var(--dl-chart-1)}.dl-bar-up{fill:var(--dl-chart-2);opacity:.8}.dl-legend{display:flex;gap:16px;font-size:12px;color:var(--dl-fg-muted);margin-top:8px}.dl-legend i{display:inline-block;width:8px;height:8px;border-radius:999px;margin-right:6px;vertical-align:0}.dl-legend .down{background:var(--dl-chart-1)}.dl-legend .up{background:var(--dl-chart-2)}.dl-events{list-style:none;margin:0;padding:0}.dl-events li{display:flex;gap:12px;align-items:baseline;padding:8px 0;border-top:1px solid var(--dl-line);font-size:14px;line-height:20px;min-width:0}.dl-events li:first-child{border-top:0;padding-top:0}.dl-ev-time{flex:0 0 88px;color:var(--dl-fg-faint);font-variant-numeric:tabular-nums;white-space:nowrap;font-size:13px}.dl-ev-dot{flex:0 0 auto;width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);transform:translateY(-2px)}.dl-ev-dot.ok{background:var(--dl-ok)}.dl-ev-dot.warn{background:var(--dl-warn)}.dl-ev-dot.bad{background:var(--dl-bad)}.dl-ev-dot.accent{background:var(--dl-accent)}.dl-row>.dl-ev-dot,.dl-dev-log-row>.dl-ev-dot{margin:0 4px}.dl-ev-tile{flex:none;display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;margin:-2px -4px;border-radius:7px;background:color-mix(in srgb,var(--dl-accent) 16%,transparent);color:var(--dl-accent);align-self:center}.dl-ev-tile .dl-icon-wrap{display:inline-flex}.dl-ev-tile .dl-icon{width:14px;height:14px}.dl-row.dl-ev-by-admin{background:color-mix(in srgb,var(--dl-accent) 6%,transparent)}.dl-you{color:var(--dl-accent);font-weight:500}.dl-ev-kind{color:var(--dl-fg-faint)}.dl-slotbar{display:flex;align-items:center;gap:8px;margin:8px 0 0 44px}.dl-slotbar-segs{display:flex;gap:3px;flex:none;max-width:100%}.dl-slotbar-segs i{flex:1;min-width:2px;display:block;height:4px;border-radius:2px;background:var(--dl-soft-hover)}.dl-slotbar-segs i.used{background:var(--dl-fg-muted)}.dl-slotbar-text{font-size:12px;color:var(--dl-fg-faint);font-variant-numeric:tabular-nums}.dl-slotbar-segs i.over{background:color-mix(in srgb,var(--dl-warn) 80%,transparent)}.dl-ev-srv{flex:none;font-size:11px;line-height:18px;padding:0 8px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted);white-space:nowrap}.dl-ev-by-system{--sys: var(--dl-fg-muted)}.dl-ev-by-system.ok{--sys: var(--dl-ok)}.dl-ev-by-system.warn{--sys: var(--dl-warn)}.dl-ev-by-system.bad{--sys: var(--dl-bad)}.dl-ev-tile.ev{background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-ev-tile.ev.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-ev-tile.ev.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-ev-tile.ev.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-ev-tile.ev.accent{background:color-mix(in srgb,var(--dl-accent) 16%,transparent);color:var(--dl-accent)}.dl-ev-tile.sys{background:color-mix(in srgb,var(--sys) 16%,transparent);color:var(--sys)}.dl-row.dl-ev-by-system{background:color-mix(in srgb,var(--sys) 6%,transparent)}.dl-sys-src{color:var(--sys)}.dl-ev-by-system:not(.ok):not(.warn):not(.bad) .dl-sys-src{color:var(--dl-fg)}.dl-ev-text{min-width:0;overflow-wrap:anywhere}.dl-server{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px}.dl-server-name{font-size:16px;line-height:24px;font-weight:500}.dl-kv{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:6px 24px;margin:12px 0 0;font-size:14px;line-height:20px}.dl-kv dt{color:var(--dl-fg-muted);font-weight:400;margin:0}.dl-kv dd{margin:0;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.dl-map .cbi-section,.dl-map .cbi-section-node{border:0!important;background:none!important;box-shadow:none!important;padding:0!important}.dl-map .table.cbi-section-table,.dl-map .cbi-section-table>.tbody,.dl-map .cbi-section-table>tbody{display:block!important;width:100%;border:0!important;background:none!important;box-shadow:none!important;border-radius:0!important}.dl-map .cbi-section-table-titles,.dl-map .cbi-section-table-descr,.dl-map .thead{display:none!important}.dl-map .cbi-section-table-row{display:flex!important;flex-wrap:wrap;align-items:flex-start;gap:12px 16px;margin:0 0 12px;padding:16px!important;background:var(--dl-card)!important;border:1px solid var(--dl-line)!important;border-radius:var(--dl-radius)!important;box-shadow:var(--dl-shadow)}.dl-map .cbi-section-table-row.dl-filtered{display:none!important}.dl-map .cbi-section-table-row:hover{background:var(--dl-card)!important}.dl-map .cbi-section-table-row>.td{display:block!important;border:0!important;padding:0!important;background:none!important;width:auto!important}.dl-map .cbi-section-table-row>.td:first-child{flex:1 1 26em;min-width:0}.dl-map .cbi-section-table-row>.td.cbi-section-actions{flex:0 0 auto;margin-left:auto}.dl-map .cbi-section-table-row>.td.cbi-section-actions>div{display:flex;flex-wrap:nowrap;gap:6px;justify-content:flex-end}.dl-map .cbi-section-table-row>.td.cbi-section-actions>div>*{margin:0!important;flex:0 0 auto}.dl-map .cbi-section-table-row>.td:before{display:none!important}.dl-map .cbi-section-table-row.placeholder{color:var(--dl-fg-muted);display:flex!important;justify-content:center;align-items:center;min-height:0!important;height:auto!important;padding:28px 16px!important;text-align:center}.dl-map .cbi-section-table-row.placeholder>*{position:static!important;padding:0!important;margin:0!important;border:0!important;flex:0 1 auto!important}.dl-map .cbi-section-table-row.dl-off .dl-card-name,.dl-map .cbi-section-table-row.dl-off .dl-avatar{opacity:.6}.dl-card-head{display:flex;align-items:center;flex-wrap:wrap;gap:6px 8px}.dl-avatar{flex:0 0 auto;width:32px;height:32px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;font-size:12px;font-weight:600;color:var(--dl-fg);background:var(--dl-soft);position:relative;margin-right:4px;letter-spacing:.02em}.dl-avatar.online:after{content:"";position:absolute;right:-1px;bottom:-1px;width:9px;height:9px;border-radius:50%;background:var(--dl-ok);box-shadow:0 0 0 2px var(--dl-card)}.dl-card-name{font-size:16px;line-height:24px;font-weight:500}.dl-card-slug{font-size:13px;color:var(--dl-fg-faint);font-family:var(--dl-mono)}.dl-quota{margin:8px 0 0 44px;max-width:320px;height:6px;border-radius:999px;background:var(--dl-track);overflow:hidden}.dl-quota>i{display:block;height:100%;background:var(--dl-accent);border-radius:999px}.dl-quota.warn>i{background:var(--dl-warn)}.dl-quota.bad>i{background:var(--dl-bad)}.dl-chips{display:flex;flex-wrap:wrap;gap:6px;margin:12px 0 0 44px}.dl-chip{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:6px;max-width:240px;height:28px;padding:0 12px 0 10px;border-radius:999px;font-size:13px;background:var(--dl-soft);color:var(--dl-fg);transition:background .15s}.dl-chip:hover{background:var(--dl-soft-hover)}.dl-chip:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-chip .dl-icon{width:14px;height:14px;color:var(--dl-fg-muted)}.dl-chip.add{background:transparent;box-shadow:inset 0 0 0 1px var(--dl-line);color:var(--dl-fg-muted);aspect-ratio:1;padding:0;justify-content:center}.dl-chip.add:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-chip.disabled .dl-chip-name{text-decoration:line-through;color:var(--dl-fg-faint)}.dl-chip-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-dot{flex:0 0 auto;width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);opacity:.6}.dl-dot.online{background:var(--dl-ok);opacity:1;box-shadow:0 0 0 3px var(--dl-ok-wash)}.dl-empty{text-align:center;padding:40px 16px;background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius)}.dl-empty .dl-icon-wrap{width:40px;height:40px;border-radius:12px;background:var(--dl-soft);margin-bottom:12px}.dl-empty .dl-icon{width:20px;height:20px}.dl-empty h3{margin:0 0 4px!important;font-size:16px;font-weight:500}.dl-empty p{margin:0 0 16px;color:var(--dl-fg-muted);font-size:14px}.dl-toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px;margin:0 0 16px}.dl-toolbar .dl-muted{font-size:13px}@media(max-width:640px){.dl-map .cbi-section-table-row>.td.cbi-section-actions{margin-left:0;width:100%!important}.dl-map .cbi-section-table-row>.td.cbi-section-actions>div{justify-content:flex-start;flex-wrap:wrap}.dl-slotbar,.dl-chips,.dl-quota{margin-left:0}.dl-btn-label{display:none}}.cbi-value.dl-block{display:block!important}.cbi-value.dl-block>.cbi-value-title{display:block;width:auto;float:none;text-align:left;padding:0 0 8px}.cbi-value.dl-block>.cbi-value-field{display:block;width:100%;margin:0}#modal_overlay{z-index:1100!important}.dl-dd{position:fixed;z-index:1200;min-width:200px;padding:4px;border-radius:12px;background:var(--dl-elevated);border:1px solid var(--dl-line);box-shadow:0 12px 32px #0000004d;display:flex;flex-direction:column}.dl-dd button{all:unset;cursor:pointer;display:flex;align-items:center;gap:10px;padding:7px 10px;border-radius:8px;font-size:13px;color:var(--dl-fg)}.dl-dd button .dl-icon{width:15px;height:15px;color:var(--dl-fg-muted)}.dl-dd button:hover,.dl-dd button:focus-visible{background:var(--dl-soft)}.dl-dd button.danger,.dl-dd button.danger .dl-icon{color:var(--dl-bad, #e5484d)}.dl-dd button.warn,.dl-dd button.warn .dl-icon{color:var(--dl-warn)}.dl-dd hr{border:0;border-top:1px solid var(--dl-line);margin:4px 0}.dl-chipbtn b{font-weight:500;font-size:11px;margin-left:6px;opacity:.6}.dl-setsub{margin:20px 0 8px!important;font-size:13px;font-weight:500;color:var(--dl-fg)}.dl-row-actions{display:flex;flex-wrap:wrap;gap:8px;align-items:center}.dl-more-row{display:flex;justify-content:center;padding:8px 0 16px}.dl-dsec-actions{display:flex;align-items:center;gap:12px}.dl-kv-act{display:inline-flex;align-items:center;gap:12px;flex-wrap:wrap}.dl-linkbtn,.dl-bento-head a,.dl-bento-foot a,.dl-panel-head a,.dl-dsec-head a,.dl-tile2-foot a{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:4px;height:26px;padding:0 9px;margin:-4px -6px;border-radius:8px;font-size:12px;font-weight:500;color:var(--dl-fg-muted);text-decoration:none!important;white-space:nowrap;transition:background .12s,color .12s}.dl-bento-head a,.dl-bento-foot a,.dl-panel-head a,.dl-dsec-head a,.dl-tile2-foot a{color:var(--dl-accent)}.dl-linkbtn:hover,.dl-bento-head a:hover,.dl-bento-foot a:hover,.dl-panel-head a:hover,.dl-dsec-head a:hover,.dl-tile2-foot a:hover{background:var(--dl-soft);color:var(--dl-fg);text-decoration:none!important}.dl-bento-head a:hover,.dl-bento-foot a:hover,.dl-panel-head a:hover,.dl-dsec-head a:hover,.dl-tile2-foot a:hover{background:color-mix(in srgb,var(--dl-accent) 12%,transparent);color:var(--dl-accent)}.dl-linkbtn:focus-visible,.dl-bento-head a:focus-visible,.dl-bento-foot a:focus-visible,.dl-panel-head a:focus-visible{outline:2px solid var(--dl-ring);outline-offset:1px}.dl-linkbtn.danger:hover{color:var(--dl-bad);background:var(--dl-bad-wash)}.dl-ifcards{display:flex;flex-direction:column;gap:20px;margin:24px 0}.dl-ifcard .dl-setsec-body{gap:14px}.dl-iflead{display:flex;flex-direction:column;gap:2px;padding-top:14px;border-top:1px solid var(--dl-line)}.dl-iflead b{font-size:14px;font-weight:500}.dl-ifgroup h4{margin:0 0 8px!important;padding:0!important;font-size:11px!important;font-weight:500!important;letter-spacing:.06em;text-transform:uppercase;color:var(--dl-fg-muted);border:0!important;background:none!important}.dl-ifgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:8px}.dl-if{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:10px;min-height:52px;padding:8px 12px 8px 10px;min-width:0;border:1px solid var(--dl-line);border-radius:10px;background:var(--dl-card);transition:background .15s,border-color .15s}.dl-if:hover{background:var(--dl-soft)}.dl-if:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-if-ic{width:30px;height:30px;border-radius:8px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-if-ic .dl-icon{width:16px;height:16px}.dl-if-main{display:flex;flex-direction:column;min-width:0;flex:1}.dl-if-name{font-size:13.5px;font-weight:500;color:var(--dl-fg);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-if-sub{font:11px/16px var(--dl-mono);color:var(--dl-fg-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-if.sel{border-color:var(--dl-accent);background:color-mix(in srgb,var(--dl-accent) 9%,transparent)}.dl-if.sel .dl-if-ic{background:color-mix(in srgb,var(--dl-accent) 18%,transparent);color:var(--dl-accent)}.dl-if-check{color:var(--dl-accent);display:inline-flex}.dl-if-check .dl-icon{width:16px;height:16px}.dl-if.auto{border-color:color-mix(in srgb,var(--dl-ok) 55%,transparent);background:var(--dl-ok-wash);cursor:default}.dl-if.auto .dl-if-ic{background:color-mix(in srgb,var(--dl-ok) 18%,transparent);color:var(--dl-ok)}.dl-if-badge{display:inline-flex;align-items:center;gap:5px;font-size:10.5px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;flex:0 0 auto}.dl-if-badge.ok{color:var(--dl-ok)}.dl-if.off{cursor:default;opacity:.5}.dl-if.off:hover{background:var(--dl-card)}.dl-if.warn{border-color:color-mix(in srgb,var(--dl-warn) 60%,transparent)}.dl-if-wanctl{gap:10px;align-items:center}.dl-if-wanctl select{max-width:240px}.dl-if-summary{min-width:0;line-height:18px}.dl-w-ip{width:160px}.dl-dnspick{padding-top:8px;border-top:1px solid var(--dl-line)}.dl-dnspick .dl-row-actions{gap:10px}.dl-note{display:flex;gap:8px;align-items:flex-start;padding:10px 12px;border-radius:10px;font-size:12.5px;line-height:18px;margin:0 0 10px;background:var(--dl-soft)}.dl-note.warn{background:var(--dl-warn-wash, color-mix(in srgb, var(--dl-warn) 14%, transparent))}.dl-note .dl-icon{width:15px;height:15px;flex:0 0 auto;margin-top:1px;color:var(--dl-warn)}.dl-stale{align-self:flex-start;margin-top:4px;font-size:10.5px}.dl-root .cbi-button.dl-btn-warn,.dl-btn-warn.cbi-button{background:var(--dl-warn-wash)!important;color:var(--dl-warn)!important;border-color:color-mix(in srgb,var(--dl-warn) 35%,transparent)!important}.dl-root .cbi-button.dl-btn-warn:hover,.dl-btn-warn.cbi-button:hover{background:color-mix(in srgb,var(--dl-warn) 24%,transparent)!important}.dl-btn-warn .dl-icon{color:var(--dl-warn)}.dl-srvtabs{display:flex;flex-wrap:wrap;gap:6px;padding:4px;margin:0 0 20px;border-radius:12px;background:var(--dl-soft);width:fit-content;max-width:100%}.dl-srvtab{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:8px;height:34px;padding:0 14px;border-radius:9px;font-size:13px;color:var(--dl-fg-muted);text-decoration:none!important;white-space:nowrap}.dl-srvtab b{font-weight:500}.dl-srvtab i.dot{width:7px;height:7px;border-radius:50%;background:var(--dl-fg-faint);flex:0 0 auto}.dl-srvtab i.dot.ok{background:var(--dl-ok);animation:dl-srv-pulse 2s ease-out infinite}.dl-srvtab i.dot.bad{background:var(--dl-bad)}@keyframes dl-srv-pulse{0%{box-shadow:0 0 color-mix(in srgb,var(--dl-ok) 55%,transparent)}70%,to{box-shadow:0 0 0 6px transparent}}@media(prefers-reduced-motion:reduce){.dl-srvtab i.dot.ok{animation:none}}.dl-srvtab:hover{color:var(--dl-fg);background:var(--dl-soft-hover)}.dl-srvtab.on{background:var(--dl-card);color:var(--dl-fg);box-shadow:0 1px 2px #0000002e,inset 0 0 0 1px var(--dl-line)}.dl-srvtab:focus-visible{outline:2px solid var(--dl-ring);outline-offset:1px}.dl-srvtab.add{color:var(--dl-fg-muted)}.dl-srvtab.add .dl-icon{width:14px;height:14px}.dl-srvhead{display:flex;flex-direction:column;gap:14px;margin:0 0 20px}.dl-srvhead .dl-title-row{display:flex;align-items:center;gap:10px}.dl-srvhead .dl-h1{margin:0!important}.dl-metrics.compact .dl-metric{padding:14px 18px}.dl-metrics.compact .dl-metric-value{display:flex;align-items:center;gap:6px;font-size:18px;line-height:26px;min-width:0}.dl-metrics.compact .dl-metric-value>span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.dl-metrics.compact .dl-metric-value .dl-mono{font-size:15px}.dl-metrics.compact .cbi-button{flex:0 0 auto}.dl-srvsections{margin:0 0 16px}.dl-srvbody>.dl-setsec,.dl-srvbody>.dl-ifcards{margin:0}.dl-srvbody .dl-ifcards{margin:0}.dl-metric-ic{display:inline-flex;align-items:center;gap:8px;font-size:16px}.dl-metric-ic .dl-icon{width:18px;height:18px;color:var(--dl-accent)}.dl-keyrow{display:inline-flex;align-items:center;gap:8px;min-width:0}.dl-keyrow code{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;background:none;padding:0}.dl-params{border:1px solid var(--dl-line);border-radius:12px;background:var(--dl-card)}.dl-params>summary{list-style:none;cursor:pointer;display:flex;align-items:center;gap:8px;padding:10px 14px;font-size:13px;color:var(--dl-fg);user-select:none}.dl-params>summary::-webkit-details-marker{display:none}.dl-params>summary>.dl-icon-wrap{display:inline-flex;color:var(--dl-fg-muted);transition:transform .15s}.dl-params>summary>.dl-icon-wrap .dl-icon{width:15px;height:15px}.dl-params[open]>summary>.dl-icon-wrap{transform:rotate(90deg)}.dl-params>summary:focus{outline:none}.dl-params>summary:focus-visible{outline:2px solid var(--dl-ring);outline-offset:-2px;border-radius:12px}.dl-params>summary:hover{background:var(--dl-soft);border-radius:12px}.dl-pcount{font-size:11px;padding:0 6px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:10px;padding:4px 14px 14px}.dl-pgroup{display:flex;flex-direction:column;gap:6px;padding:12px;border-radius:10px;background:var(--dl-soft);min-width:0}.dl-pgroup-head{display:flex;align-items:center;gap:8px;font-size:13px}.dl-pgroup-head b{font-weight:500}.dl-pgroup-head .dl-icon{width:14px;height:14px;color:var(--dl-fg-muted)}.dl-pgroup p{margin:0!important;font-size:12px;line-height:17px;color:var(--dl-fg-muted)}.dl-pvals{display:flex;flex-wrap:wrap;gap:4px;margin-top:2px}.dl-pv{display:inline-flex;align-items:stretch;max-width:100%;border-radius:6px;overflow:hidden;font:500 11.5px/22px var(--dl-mono);box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-pv i{font-style:normal;padding:0 6px;background:var(--dl-card);color:var(--dl-fg-faint)}.dl-pv b{font-weight:500;padding:0 7px;color:var(--dl-fg);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.dl-methods{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:10px}.dl-method{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;gap:10px;padding:14px;border-radius:12px;border:1px solid var(--dl-line);background:var(--dl-card);transition:border-color .15s,background .15s;min-width:0}.dl-method:hover{background:var(--dl-soft)}.dl-method:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-method.on{border-color:var(--dl-accent);background:color-mix(in srgb,var(--dl-accent) 8%,transparent);box-shadow:inset 0 0 0 1px var(--dl-accent)}.dl-method.off{cursor:not-allowed;opacity:.55}.dl-method.off:hover{background:var(--dl-card)}.dl-method-head{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px}.dl-method-head .dl-pill{flex:none}.dl-method-head b{font-weight:500;font-size:14.5px;flex:1}.dl-method-ic{width:32px;height:32px;border-radius:9px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;color:var(--dl-fg-muted);flex:0 0 auto}.dl-method-ic .dl-icon{width:17px;height:17px}.dl-method.on .dl-method-ic{background:color-mix(in srgb,var(--dl-accent) 18%,transparent);color:var(--dl-accent)}.dl-method p{margin:0!important;font-size:12.5px;line-height:18px;color:var(--dl-fg-muted);flex:1}.dl-method-meters{display:flex;gap:16px}.dl-dots{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--dl-fg-faint)}.dl-dots-row{display:inline-flex;gap:3px}.dl-dots-row i{width:6px;height:6px;border-radius:50%;background:var(--dl-line)}.dl-dots-row i.on{background:var(--dl-fg-muted)}.dl-method.on .dl-dots-row i.on{background:var(--dl-accent)}.dl-method-foot{display:flex;align-items:center;gap:6px;font-size:11.5px;color:var(--dl-fg-faint);padding-top:8px;border-top:1px solid var(--dl-line)}.dl-method-foot .dl-icon{width:13px;height:13px;flex:0 0 auto}.dl-method.off .dl-method-foot{color:var(--dl-warn)}.dl-ibadge{display:inline-flex;align-items:center;gap:3px;height:22px;padding:0 6px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted);flex:0 0 auto}.dl-ibadge .dl-icon{width:13px;height:13px}.dl-ibadge.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-ibadge.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-access{display:inline-flex;gap:4px;flex:0 0 auto}.dl-ibadge.lan{background:color-mix(in srgb,var(--dl-accent) 16%,transparent);color:var(--dl-accent)}.dl-ibadge.inet{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-addrbar{display:inline-flex;align-items:stretch;flex-wrap:nowrap;max-width:100%;margin-top:4px;border:1px solid var(--dl-line);border-radius:10px;background:var(--dl-card);overflow:hidden}.dl-addrbar-seg{all:unset;box-sizing:border-box;display:inline-flex;align-items:center;gap:7px;padding:6px 12px;font-size:13px;color:var(--dl-fg-muted);border-left:1px solid var(--dl-line);white-space:nowrap;min-width:0}.dl-addrbar-seg:first-child{border-left:0}.dl-addrbar-seg .dl-icon{width:14px;height:14px;color:var(--dl-fg-faint);flex:0 0 auto}.dl-addrbar-seg .dl-mono{font-size:12.5px}.dl-addrbar-seg.main{cursor:pointer;color:var(--dl-fg)}.dl-addrbar-seg.main:hover{background:var(--dl-soft)}.dl-addrbar-seg.main:focus-visible{outline:2px solid var(--dl-ring);outline-offset:-2px}.dl-addrbar-seg.main>.dl-icon-wrap:last-child .dl-icon{opacity:.7}.dl-bento{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));grid-template-rows:auto auto;gap:10px;margin:0 0 20px}.dl-person-devices{margin-bottom:16px}.dl-person-head{display:flex;flex-direction:column;margin:0 0 20px}.dl-person-head>.dl-pagehead{margin-bottom:0;align-items:flex-start}.dl-pnote{all:unset;box-sizing:border-box;cursor:pointer;align-self:flex-start;display:inline-flex;align-items:flex-start;gap:6px;margin:10px 0 0 62px;max-width:60ch;padding:6px 12px 6px 10px;border-radius:10px;font-size:13px;line-height:18px;white-space:pre-line;background:var(--dl-soft);color:var(--dl-fg);box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-pnote:hover{background:var(--dl-soft-hover)}.dl-pnote .dl-icon{width:14px;height:14px;flex:none;margin-top:2px;color:var(--dl-fg-muted)}.dl-note-input{width:100%;box-sizing:border-box;min-height:80px;resize:vertical}.dl-dcard-trend{display:flex;align-items:flex-end;gap:12px;min-width:0}.dl-dcard-trend>.dl-stack{flex:none}.dl-dcard-trend b{font-size:16px;font-weight:500;font-variant-numeric:tabular-nums}.dl-dbars{flex:1;min-width:0;height:32px;display:flex;align-items:flex-end;gap:2px}.dl-dbars i{flex:1;min-width:0;border-radius:2px;background:var(--dl-chart-1);opacity:.55}.dl-dbars i.zero{background:var(--dl-track);opacity:1}.dl-dbars i.hi{opacity:1}.dl-dbars i:hover{opacity:1;filter:brightness(1.2)}.dl-datechip{position:relative;display:inline-flex}.dl-date-hidden{position:absolute!important;left:0;bottom:0;width:1px!important;min-width:0!important;height:1px!important;opacity:0;pointer-events:none;border:0!important;padding:0!important;margin:0!important}.dl-chipbtn .dl-icon{width:13px;height:13px}.dl-chipbtn:has(.dl-icon){display:inline-flex;align-items:center;gap:5px}.dl-places{display:flex;align-items:center;gap:12px;padding:12px 16px;border:1px solid var(--dl-line);border-radius:var(--dl-radius);background:var(--dl-card);font-size:14px}.dl-places>.dl-icon{width:18px;height:18px;color:var(--dl-fg-muted);flex:none}.dl-person-live{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:10px}.dl-person-live .dl-bento-head{flex-wrap:nowrap;white-space:nowrap;min-width:0}.dl-person-live .dl-bento-head>*{min-width:0;overflow:hidden;text-overflow:ellipsis}.dl-person-live .dl-bento-head>:first-child{flex:none}.dl-person-live.solo{grid-template-columns:minmax(0,1fr)}.dl-person-live:not(.solo) .dl-bento-tile.month>.dl-bento-head:first-child{flex-wrap:wrap;row-gap:2px}.dl-person-live:not(.solo) .dl-bento-tile.month>.dl-bento-head:first-child>.dl-sub{flex-basis:100%}.dl-person-live>.dl-bento-tile,.dl-person-live>.dl-bento-tile.month{grid-column:auto;grid-row:auto}@media(max-width:760px){.dl-person-live{grid-template-columns:minmax(0,1fr)}}.dl-bento-tile{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);padding:14px 16px;display:flex;flex-direction:column;gap:10px;min-width:0;box-shadow:var(--dl-shadow)}.dl-bento-tile.month{grid-column:1 / -1}.dl-onl-count{font-size:13px;line-height:22px;min-width:22px;padding:0 8px;border-radius:999px;background:var(--dl-soft);text-align:center;font-weight:500;font-variant-numeric:tabular-nums}.dl-onl-count.none{color:var(--dl-fg-faint)}.dl-onl-row{flex:1;display:flex;align-items:center;justify-content:center;gap:12px;min-width:0}.dl-onl-p{display:flex;flex-direction:column;align-items:center;gap:5px;width:104px;min-width:0;padding:6px 2px;border-radius:12px;color:var(--dl-fg)!important;text-decoration:none!important}.dl-onl-p:hover{background:var(--dl-soft)}.dl-onl-av{position:relative;width:42px;height:42px;border-radius:50%;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;font-size:13px;font-weight:500;box-shadow:0 0 0 2px var(--dl-ok)}.dl-onl-p.more .dl-onl-av{box-shadow:0 0 0 1px var(--dl-line);color:var(--dl-fg-muted)}.dl-onl-dev{position:absolute;right:-5px;bottom:-5px;width:20px;height:20px;border-radius:7px;background:var(--dl-card);box-shadow:0 0 0 1.5px var(--dl-card);display:inline-flex;align-items:center;justify-content:center;font-size:10px;color:var(--dl-fg-muted)}.dl-onl-dev .dl-icon-wrap{display:inline-flex}.dl-onl-dev .dl-icon{width:12px;height:12px}.dl-onl-name{font-size:12.5px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-onl-p .dl-sub{font-size:11px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-onl-row.grid{flex-wrap:wrap;align-content:center;gap:10px 8px;max-height:108px;overflow:hidden}.dl-onl-p.sm{width:auto;padding:4px}.dl-onl-p.sm .dl-onl-av{width:36px;height:36px;font-size:11.5px}.dl-onl-meta{display:inline-flex;align-items:center;gap:3px;font-size:11px;color:var(--dl-fg-faint);max-width:100%;white-space:nowrap;overflow:hidden}.dl-onl-meta .dl-icon-wrap{display:inline-flex}.dl-onl-meta .dl-icon{width:12px;height:12px}.dl-onl-av.sm{width:34px;height:34px;font-size:11.5px}.dl-tip-float:has(.dl-hc){padding:0;white-space:normal;border-radius:16px}.dl-hc{width:280px;padding:14px;display:flex;flex-direction:column;gap:10px}.dl-hc-head{display:flex;align-items:center;gap:10px}.dl-hc-head .dl-stack{flex:1;min-width:0}.dl-hc-head b{font-size:14px;font-weight:500}.dl-hc-since{font-size:11.5px;color:var(--dl-ok)}.dl-hc-reach{display:inline-flex;gap:4px}.dl-hc-speed{border-radius:12px;background:var(--dl-soft);padding:10px 12px;display:flex;flex-direction:column;gap:6px}.dl-hc-speed-row{display:flex;align-items:baseline;gap:12px;font-size:13px;font-variant-numeric:tabular-nums}.dl-hc-chart{display:block;width:100%;height:30px}.dl-hc-chart .area{fill:color-mix(in srgb,var(--dl-chart-1) 16%,transparent)}.dl-hc-chart .dn{fill:none;stroke:var(--dl-chart-1);stroke-width:1.5;vector-effect:non-scaling-stroke}.dl-hc-chart .up{fill:none;stroke:var(--dl-ok);stroke-width:1.2;vector-effect:non-scaling-stroke}.dl-hc-devs{display:flex;flex-wrap:wrap;gap:6px}.dl-hc-dev{display:inline-flex;align-items:center;gap:5px;height:24px;padding:0 9px;border-radius:999px;background:var(--dl-soft);font-size:11.5px}.dl-hc-dev .dl-icon-wrap{display:inline-flex}.dl-hc-dev .dl-icon{width:12px;height:12px;color:var(--dl-fg-muted)}.dl-hc-foot{display:flex;align-items:center;gap:8px;font-size:11.5px}.dl-disg-id{display:flex;align-items:center;gap:10px}.dl-disg-id b{font-size:16px;font-weight:500}.dl-disg-ic{width:36px;height:36px;border-radius:11px;background:color-mix(in srgb,var(--dl-accent) 14%,transparent);color:var(--dl-accent);display:inline-flex;align-items:center;justify-content:center;flex:none}.dl-disg-ic .dl-icon-wrap{display:inline-flex}.dl-disg-ic .dl-icon{width:18px;height:18px}.dl-disg-meters{display:grid;grid-template-columns:auto 1fr;gap:6px 10px;align-items:center;font-size:12px;color:var(--dl-fg-muted)}.dl-segs{display:inline-flex;gap:3px}.dl-segs i{width:18px;height:5px;border-radius:3px;background:var(--dl-track)}.dl-segs.acc i.on{background:var(--dl-accent)}.dl-segs.ok i.on{background:var(--dl-ok)}.dl-disg-chips{margin-top:auto;display:flex;flex-wrap:wrap;gap:5px}.dl-disg-chips span{font:11px/20px var(--dl-mono);padding:0 8px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted);white-space:nowrap}.dl-onl-empty{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;font-size:13px;text-align:center}.dl-bento-head{display:flex;align-items:center;justify-content:space-between;gap:10px;min-width:0}.dl-bento-head.start{justify-content:flex-start}.dl-bento-big{font-family:inherit;font-size:28px;line-height:34px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-bento-big small{font-size:13px;font-weight:400;color:var(--dl-fg-faint);letter-spacing:0}.dl-avstack{display:inline-flex}.dl-avstack .dl-avatar{margin-left:-7px;box-shadow:0 0 0 2px var(--dl-card)}.dl-avstack .dl-avatar:first-child{margin-left:0}.dl-avatar.more{background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-bento-list{display:flex;flex-direction:column;gap:2px}.dl-bento-row{display:flex;align-items:center;gap:10px;padding:8px;margin:0 -8px;border-radius:10px;color:var(--dl-fg)!important;text-decoration:none!important;min-width:0;transition:background .12s}.dl-bento-row:hover{background:var(--dl-soft)}.dl-bento-row:hover b{text-decoration:none}.dl-bento-row:focus-visible{outline:2px solid var(--dl-ring);outline-offset:-2px}.dl-bento-row-main{display:flex;flex-direction:column;gap:1px;flex:1;min-width:0}.dl-bento-row-main b{font-weight:500;font-size:13.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-bento-row-main .dl-sub{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-bento-row.off b{color:var(--dl-fg-muted);font-weight:400}.dl-bento-row-val{display:flex;flex-direction:column;align-items:flex-end;font-size:13px;font-variant-numeric:tabular-nums;white-space:nowrap}.dl-bento-row-val small{font-size:11px;color:var(--dl-fg-faint)}.dl-bento-sep{font-size:11px;color:var(--dl-fg-faint);padding:12px 0 4px}.dl-bento-devs{display:inline-flex;gap:3px;color:var(--dl-fg-faint)}.dl-bento-devs .dl-icon{width:13px;height:13px}.dl-bento-devs .on{color:var(--dl-ok)}.dl-bento-foot{display:flex;align-items:center;gap:10px;margin-top:auto;padding-top:10px;border-top:1px solid var(--dl-line);color:var(--dl-fg)!important;text-decoration:none!important}.dl-bento-foot.split,.dl-bento-foot.end{justify-content:space-between}.dl-bento-foot.end>a:only-child{margin-left:auto}.dl-bento-empty{display:flex;align-items:center;gap:10px;padding:14px 0;font-size:13.5px;color:var(--dl-fg-muted)}.dl-bento-empty .dl-icon{width:18px;height:18px}.dl-split{display:flex;height:6px;border-radius:3px;overflow:hidden;background:var(--dl-soft)}.dl-split i{display:block;height:100%}.dl-split i.dn{background:var(--dl-accent)}.dl-split i.up{background:var(--dl-ok)}.dl-dn{color:var(--dl-accent)}.dl-up{color:var(--dl-ok)}.dl-bento-method{display:flex;align-items:center;gap:8px;font-size:18px;font-weight:500}.dl-bento-method .dl-icon{width:20px;height:20px;color:var(--dl-accent)}.dl-meter{display:inline-flex;gap:3px}.dl-meter i{width:16px;height:4px;border-radius:2px;background:var(--dl-line)}.dl-meter i.on{background:var(--dl-accent)}.dl-bento-total{font-size:16px;font-weight:500;margin-left:8px}.dl-bento-bars{display:flex;align-items:flex-end;gap:3px;height:54px}.dl-bento-bars i{flex:1;min-width:0;border-radius:3px 3px 0 0;background:var(--dl-soft-hover);transition:background .15s}.dl-bento-bars i.future{height:4px;background:var(--dl-soft)}.dl-bento-bars i:hover{background:var(--dl-fg-faint)}.dl-bento-bars i.hi{background:var(--dl-accent)}@media(max-width:700px){.dl-addrbar{flex-wrap:wrap}}@media(max-width:900px){.dl-bento{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}.dl-bento-tile.online{grid-column:span 2}}@media(max-width:560px){.dl-bento{grid-template-columns:minmax(0,1fr)}.dl-bento-tile.online,.dl-bento-tile.month{grid-column:auto}}.dl-srvpagehead{display:flex;flex-direction:column;align-items:flex-start;gap:10px;margin:0 0 20px}.dl-srvpagehead>.dl-title-row{display:flex;align-items:center;gap:10px;width:100%;flex-wrap:wrap}.dl-srvpagehead .dl-actions{margin:0;flex-wrap:wrap}.dl-toolbar-end{display:flex;align-items:center;gap:8px;margin-left:auto;flex-wrap:nowrap;min-width:0}@media(max-width:640px){.dl-toolbar-end{flex-wrap:wrap;width:100%}}.dl-healthstrip{display:flex;align-items:center;gap:8px 16px;flex-wrap:wrap;padding:9px 14px;margin:0 0 12px;border-radius:12px;border:1px solid color-mix(in srgb,var(--dl-warn) 45%,transparent);background:var(--dl-warn-wash);font-size:13px;color:var(--dl-fg-muted)}.dl-healthstrip.bad{border-color:color-mix(in srgb,var(--dl-bad) 45%,transparent);background:var(--dl-bad-wash)}.dl-healthstrip-title{display:inline-flex;align-items:center;gap:6px;font-weight:500;color:var(--dl-warn)}.dl-healthstrip.bad .dl-healthstrip-title{color:var(--dl-bad)}.dl-healthstrip-title .dl-icon{width:15px;height:15px}.dl-healthstrip-item{cursor:default}.dl-healthstrip a{margin-left:auto;font-size:12px;font-weight:500;color:var(--dl-fg);text-decoration:none;padding:3px 9px;border-radius:8px}.dl-healthstrip a:hover{background:var(--dl-soft)}.dl-speed-cols{display:grid;grid-template-columns:1fr 1fr;gap:12px}.dl-speed-col{display:flex;flex-direction:column;gap:2px;min-width:0}.dl-speed-val{font-size:20px;line-height:26px;font-weight:500;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-speed-today{display:flex;justify-content:space-between;gap:10px;font-size:12px;color:var(--dl-fg-muted);white-space:nowrap;font-variant-numeric:tabular-nums}.dl-speed-today b{font-weight:500;color:var(--dl-fg)}.dl-speed-chart{display:block;width:100%;height:44px}.dl-speed-chart .area{fill:color-mix(in srgb,var(--dl-accent) 16%,transparent)}.dl-speed-chart .line{fill:none;stroke:var(--dl-accent);stroke-width:1.5;vector-effect:non-scaling-stroke}.dl-speed-chart .line.up{stroke:var(--dl-ok);stroke-width:1.2;opacity:.85}.dl-speed-wait{height:44px;display:flex;flex-direction:column;justify-content:flex-end;gap:6px;font-size:11px;color:var(--dl-fg-faint)}.dl-speed-wait i{display:block;height:1px;background:var(--dl-line);order:2}.dl-fld{display:flex;flex-direction:column;gap:8px;margin:0 0 16px}.dl-fld-label{font-size:13px;font-weight:500;color:var(--dl-fg)}.dl-fld .cbi-input-text{width:100%;box-sizing:border-box}.dl-kinds{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:6px}.dl-kinds button{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;height:68px;border-radius:10px;border:1px solid var(--dl-line);color:var(--dl-fg-muted);font-size:12px;font-weight:500;text-align:center;min-width:0}.dl-kinds button .dl-icon{width:20px;height:20px}.dl-kinds button:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-kinds button:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-kinds button.on{border-color:var(--dl-accent);color:var(--dl-fg);background:color-mix(in srgb,var(--dl-accent) 10%,transparent);box-shadow:inset 0 0 0 1px var(--dl-accent)}.dl-kinds button.on .dl-icon{color:var(--dl-accent)}.dl-choices{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:8px}.dl-choice{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;gap:4px;padding:12px 14px;border-radius:12px;background:var(--dl-card);box-shadow:inset 0 0 0 1px var(--dl-line);transition:background .15s,box-shadow .15s}.dl-choice:hover{background:var(--dl-soft)}.dl-choice:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-choice.selected{box-shadow:inset 0 0 0 2px var(--dl-accent);background:var(--accent-a10, color-mix(in srgb, var(--dl-accent) 8%, transparent))}.dl-choice-title{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:500;color:var(--dl-fg)}.dl-choice-text{font-size:12px;line-height:16px;color:var(--dl-fg-muted)}.dl-steps{display:flex;align-items:center;gap:8px;margin:0 0 16px;flex-wrap:wrap}.dl-step{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:500;color:var(--dl-fg-faint)}.dl-step b{display:inline-flex;width:24px;height:24px;align-items:center;justify-content:center;border-radius:50%;background:var(--dl-soft);font-size:12px;font-weight:600}.dl-step.current{color:var(--dl-fg)}.dl-step.current b{background:var(--dl-primary);color:var(--dl-primary-fg)}.dl-step.done{color:var(--dl-fg-muted)}.dl-step.done b{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-step+.dl-step:before{content:"";width:24px;height:1px;background:var(--dl-line)}.dl-wizard .dl-panel>div{display:flex;flex-direction:column;gap:16px}.dl-wizard .dl-panel>div>p{margin:0!important;color:var(--dl-fg-muted)}.dl-wizard .dl-panel>div>.cbi-value{margin:0}.dl-wizard h4{font-size:14px;font-weight:500;margin:8px 0 -6px!important}.dl-wizard h4:first-child{margin-top:0!important}.dl-modal .cbi-tabmenu{margin-bottom:16px}.dl-invite{display:grid;grid-template-columns:250px minmax(0,1fr);gap:22px;align-items:start}.dl-invite img{display:block;width:100%;border-radius:18px;box-shadow:0 0 0 1px var(--dl-line)}.dl-invite-side{display:flex;flex-direction:column;gap:14px;min-width:0}.dl-invite-side>p{margin:0!important}.dl-invite-link{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:10px;min-width:0;padding:11px 14px;border-radius:12px;background:var(--dl-soft);font:13px/18px var(--dl-mono);color:var(--dl-fg)}.dl-invite-link>span:first-child{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-invite-link>.dl-icon-wrap{flex:none;display:inline-flex}.dl-invite-link .dl-icon{width:15px;height:15px;color:var(--dl-fg-muted);flex:none}.dl-invite-link:hover{background:var(--dl-soft-hover)}.dl-invite-link.alt{padding:8px 14px;font-size:12px;color:var(--dl-fg-muted)}.dl-invite-link>.dl-pill{flex:none}.dl-invite-steps{margin:0;padding-left:20px;list-style:decimal!important;font-size:13px;line-height:24px;color:var(--dl-fg-muted)}.dl-invite-steps b{color:var(--dl-fg);font-weight:500}.dl-invite-steps li{display:list-item!important;list-style:inherit!important;padding-left:4px}.dl-invite-actions{display:flex;gap:8px;flex-wrap:wrap}.modal:has(.dl-modal.wide){max-width:min(760px,94vw)!important;width:100%!important}@media(max-width:640px){.dl-invite{grid-template-columns:minmax(0,1fr)}.dl-invite img{max-width:260px;margin:0 auto}}.dl-toasts{position:fixed;left:50%;bottom:max(24px,env(safe-area-inset-bottom));transform:translate(-50%);z-index:100000;display:flex;flex-direction:column;align-items:center;gap:8px;pointer-events:none}.dl-toast{pointer-events:auto;display:inline-flex;align-items:center;gap:8px;max-width:min(520px,92vw);padding:10px 16px;border-radius:999px;background:var(--dl-fg);color:var(--dl-card);font-size:13px;line-height:18px;box-shadow:0 10px 30px #0000004d;opacity:0;transform:translateY(12px);transition:opacity .18s,transform .18s}.dl-toast.show{opacity:1;transform:none}.dl-toast .dl-icon-wrap{display:inline-flex}.dl-toast .dl-icon{width:15px;height:15px}.dl-toast.success .dl-icon{color:var(--dl-ok)}.dl-toast.error{background:var(--dl-bad);color:#fff}.dl-toast.error .dl-icon{color:#fff}.dl-toast.warning{background:var(--dl-warn);color:#111}.dl-toast.warning .dl-icon{color:#111}.dl-toast button{all:unset;cursor:pointer;display:inline-flex;margin-left:4px;opacity:.8}.dl-toast button:hover{opacity:1}.dl-setblock{display:flex;flex-direction:column;gap:8px;margin:0}.dl-addr-opts{display:flex;flex-direction:column;gap:6px}.dl-addr-opt{all:unset;box-sizing:border-box;cursor:pointer;display:grid;grid-template-columns:16px minmax(0,1fr) auto;gap:12px;align-items:center;padding:10px 14px;border-radius:12px;box-shadow:inset 0 0 0 1px var(--dl-line);min-width:0}.dl-addr-opt:hover{background:var(--dl-soft)}.dl-addr-opt.on{box-shadow:inset 0 0 0 1.5px var(--dl-accent);background:color-mix(in srgb,var(--dl-accent) 7%,transparent)}.dl-addr-opt .dl-mono{font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-addr-opt .dl-stack{min-width:0}.dl-addr-opt input{width:100%}.dl-addr-opt.other{cursor:default}.dl-addr-opt.other:hover{background:none}.dl-addr-opt.other input{width:100%}.dl-addr-check{width:16px;height:16px;border-radius:5px;box-shadow:inset 0 0 0 1.5px var(--dl-fg-faint);display:inline-flex;align-items:center;justify-content:center}.dl-addr-check .dl-icon-wrap{display:inline-flex}.dl-addr-check .dl-icon{width:12px;height:12px}.dl-addr-opt.on .dl-addr-check{background:var(--dl-accent);box-shadow:none;color:#fff}.dl-addr-opt.other .dl-addr-check{box-shadow:none;color:var(--dl-fg-muted)}.dl-addr-warn{display:inline-flex;align-items:center;gap:5px;font-size:12px;line-height:17px;color:var(--dl-warn)}.dl-addr-warn .dl-icon-wrap{display:inline-flex}.dl-addr-warn .dl-icon{width:13px;height:13px}.dl-pill.info{background:color-mix(in srgb,var(--dl-accent) 14%,transparent);color:var(--dl-accent)}.dl-links{border-radius:12px;background:var(--dl-soft);overflow:hidden}.dl-link-row{display:grid;grid-template-columns:18px minmax(0,1fr) auto;gap:10px;align-items:center;padding:11px 14px}.dl-link-row+.dl-link-row{border-top:1px solid var(--dl-line)}.dl-link-ic{display:inline-flex}.dl-link-ic .dl-icon{width:15px;height:15px}.dl-link-ic.ok .dl-icon{color:var(--dl-ok)}.dl-link-ic.warn .dl-icon{color:var(--dl-warn)}.dl-link-url{font-size:13px;color:var(--dl-fg-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-link-url b{font-weight:500;color:var(--dl-accent)}@media(max-width:640px){.dl-link-url,.dl-addr-opt .dl-mono,.dl-filecard .dl-ellipsis,.dl-invite-link>span:first-child{white-space:normal;overflow-wrap:anywhere}}.dl-ready-sum{display:flex;align-items:center;gap:12px;padding:12px 14px;border-radius:12px}.dl-ready-sum>.dl-icon-wrap{display:inline-flex}.dl-ready-sum>.dl-icon-wrap .dl-icon{width:18px;height:18px}.dl-ready-sum .dl-stack{flex:1;min-width:0}.dl-ready-sum b{font-weight:500;font-size:13px}.dl-ready-sum.ok{background:var(--dl-ok-wash)}.dl-ready-sum.ok b,.dl-ready-sum.ok .dl-icon{color:var(--dl-ok)}.dl-ready-sum.warn{background:var(--dl-warn-wash)}.dl-ready-sum.warn b,.dl-ready-sum.warn .dl-icon{color:var(--dl-warn)}.dl-ready-sum.error{background:var(--dl-bad-wash)}.dl-ready-sum.error b,.dl-ready-sum.error .dl-icon{color:var(--dl-bad)}.dl-check-chip{display:inline-flex;align-items:center;gap:5px;height:26px;padding:0 10px;border-radius:999px;background:var(--dl-soft);font-size:12px;color:var(--dl-fg-muted)}.dl-check-chip .dl-icon-wrap{display:inline-flex}.dl-check-chip .dl-icon{width:13px;height:13px;color:var(--dl-ok)}.dl-check-chip.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-check-chip.warn .dl-icon{color:var(--dl-warn)}.dl-check-chip.error{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-check-chip.error .dl-icon{color:var(--dl-bad)}.dl-ready-details{display:flex;flex-direction:column;gap:8px;padding:4px 2px}.dl-ready-details[hidden]{display:none}.dl-ready-item{display:flex;align-items:flex-start;gap:8px;font-size:13px;line-height:18px;min-width:0}.dl-ready-item .dl-icon-wrap{display:inline-flex;margin-top:1px}.dl-ready-item .dl-icon{width:15px;height:15px}.dl-ready-item.ok .dl-icon{color:var(--dl-ok)}.dl-ready-item.warn .dl-icon{color:var(--dl-warn)}.dl-ready-item.error .dl-icon{color:var(--dl-bad)}.dl-params-body{display:flex;flex-direction:column;gap:14px;padding:6px 14px 14px}.dl-params-body>.dl-setrow{margin:0;padding:0}.dl-pgrid.flush{padding:0;grid-template-columns:repeat(2,minmax(0,1fr))}@media(max-width:640px){.dl-pgrid.flush{grid-template-columns:minmax(0,1fr)}}.dl-qr-pane{display:flex;flex-direction:column;align-items:center;gap:8px;text-align:center}.dl-qr{width:min(280px,72vw);aspect-ratio:1;background:#fff;padding:8px;border-radius:12px;box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-qr svg{display:block;width:100%;height:100%}.dl-filecard{display:flex;align-items:center;gap:12px;padding:12px;border-radius:14px;background:var(--dl-soft);min-width:0}.dl-filecard>.dl-stack{flex:1;min-width:0}.dl-filecard-ic{width:40px;height:46px;border-radius:8px;flex:none;display:inline-flex;align-items:center;justify-content:center;font:10px var(--dl-mono);color:var(--dl-fg-muted);background:var(--dl-card);box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-params>.dl-conf{margin:0;border-top:1px solid var(--dl-line);border-radius:0 0 12px 12px;background:none}.dl-conf-sec{color:var(--dl-accent)}.dl-conf-k{color:var(--dl-fg-faint)}.dl-conf-mask{padding:0 6px;border-radius:4px;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-params>summary .dl-chipbtn{height:26px;font-size:12px}.dl-conf{white-space:pre-wrap;word-break:break-all;max-height:22em;overflow:auto;font-family:var(--dl-mono);font-size:12px;line-height:18px;margin:0;padding:12px;border-radius:12px;background:var(--dl-soft)}.dl-key{width:100%;box-sizing:border-box;font-family:var(--dl-mono);font-size:12px;word-break:break-all;min-height:7em}.dl-actions{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin:12px 0 0}.dl-link-box{display:flex;gap:6px;align-items:center;flex-wrap:wrap}.dl-link-box input{flex:1 1 18em;min-width:0;font-family:var(--dl-mono);font-size:12px}.dl-hint{font-size:12px;line-height:16px;color:var(--dl-fg-muted);margin:8px 0}.dl-divider{border:0;border-top:1px solid var(--dl-line);margin:16px 0}.dl-checks{list-style:none;margin:0;padding:0}.dl-checks li{display:flex;align-items:center;gap:12px;padding:12px 0;border-top:1px solid var(--dl-line)}.dl-checks li:first-child{border-top:0;padding-top:0}.dl-checks li:last-child{padding-bottom:0}.dl-check-icon{flex:0 0 auto;width:28px;height:28px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center}.dl-check-icon .dl-icon{width:14px;height:14px}.dl-check-icon.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-check-icon.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-check-icon.error{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-check-icon.skip{background:var(--dl-soft);color:var(--dl-fg-faint)}.dl-check-body{flex:1;min-width:0}.dl-check-title{font-size:14px;line-height:20px;font-weight:500}.dl-check-detail{font-size:12px;line-height:16px;color:var(--dl-fg-muted);overflow-wrap:anywhere}.dl-check-repaired{margin-top:2px;font-size:12px;line-height:16px;color:var(--dl-warn)}.dl-wd{margin:0 0 16px;display:flex;flex-direction:column;gap:14px}.dl-wd-head{display:flex;align-items:center;gap:12px;min-width:0}.dl-wd-head>.dl-stack{min-width:0}.dl-wd-title{font-size:16px;line-height:24px;font-weight:500}.dl-wd-tile{flex:none;width:36px;height:36px;border-radius:10px;display:inline-flex;align-items:center;justify-content:center;background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-wd-tile.off{background:var(--dl-soft);color:var(--dl-fg-faint)}.dl-wd-tile .dl-icon{width:18px;height:18px}.dl-wd-foot{display:flex;align-items:center;flex-wrap:wrap;gap:8px 16px;padding-top:14px;border-top:1px solid var(--dl-line)}.dl-wd-chips{display:flex;flex-wrap:wrap;gap:6px;flex:1 1 auto;min-width:0}.dl-wd-chips .dl-check-chip.error .dl-icon{color:var(--dl-bad)}.dl-warn-text{color:var(--dl-warn)!important}.dl-health-cols{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(440px,100%),1fr));gap:16px;align-items:start}.dl-health-cols>.dl-panel{margin:0;min-width:0}.dl-recent{display:flex;flex-direction:column}.dl-recent .dl-panel-head a{font-size:13px}.dl-recent-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:32px 16px;color:var(--dl-fg-muted);font-size:13px;border-top:1px solid var(--dl-line)}.dl-loading{margin:0;font-size:13px}.dl-diag-tabs{margin:0 0 16px}.dl-row.dl-slog-row{align-items:baseline}.dl-slog-row .dl-ev-tile{align-self:flex-start;margin-top:-1px}.dl-slog-row.has-detail{cursor:pointer}.dl-row.dl-slog-row.has-detail:hover{background:color-mix(in srgb,var(--sys) 11%,transparent)}.dl-slog-more{display:inline-flex;vertical-align:-2px;margin-left:6px;color:var(--dl-fg-faint);transform:rotate(90deg);transition:transform .15s}.dl-slog-more .dl-icon{width:14px;height:14px}.dl-slog-more.open{transform:rotate(-90deg)}.dl-slog-detail{margin:8px 0 2px;padding:8px 10px;border-radius:8px;background:var(--dl-soft);font-family:var(--dl-mono);font-size:12px;line-height:17px;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--dl-fg-muted);cursor:text}} .dl-table{width:100%;border-collapse:collapse;font-size:14px;line-height:20px}.dl-table th{text-align:left;font-weight:500;color:var(--dl-fg-faint);padding:0 8px 8px;border-bottom:1px solid var(--dl-line)}.dl-table td{padding:10px 8px;border-bottom:1px solid var(--dl-line);vertical-align:middle}.dl-table th:first-child,.dl-table td:first-child{padding-left:0}.dl-table th:last-child,.dl-table td:last-child{padding-right:0}.dl-table tr:last-child td{border-bottom:0}.dl-table .dl-right{text-align:right;white-space:nowrap}.dl-log{max-height:18em;overflow:auto;font-family:var(--dl-mono);font-size:12px;line-height:18px;margin:8px 0 0;padding:12px;white-space:pre-wrap;border-radius:12px;background:var(--dl-soft)}.dl-pagehead{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;flex-wrap:wrap;margin:0 0 20px}.dl-h1{margin:0!important;padding:0!important;font-size:24px!important;line-height:32px!important;font-weight:500!important;border:0!important}.dl-title-row{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.dl-stack{display:flex;flex-direction:column;gap:2px;min-width:0}.dl-stack.gap4{gap:4px}.dl-stack.gap8{gap:8px}.dl-sub{font-size:12px;line-height:16px;color:var(--dl-fg-muted)}.dl-ok{color:var(--dl-ok)}.dl-warn{color:var(--dl-warn)}.dl-bad{color:var(--dl-bad)}.dl-icon-only{width:auto!important;min-width:0!important;aspect-ratio:1 / 1;padding:0!important;justify-content:center;display:inline-flex!important;align-items:center;border-radius:999px!important}.dl-panel.flush{padding:0;overflow:hidden}.dl-panel-head.pad{padding:16px 16px 12px;margin:0}.dl-col{display:flex;flex-direction:column;gap:16px;min-width:0}.dl-col>.dl-panel,.dl-col>section.dl-panel{margin:0}.dl-crumbs{display:flex;gap:8px;align-items:center;font-size:14px;margin:0 0 16px;color:var(--dl-fg-faint)}.dl-crumbs a{color:var(--dl-fg-faint)}.dl-crumbs a:hover{color:var(--dl-fg)}.dl-crumbs span:last-child{color:var(--dl-fg)}.dl-metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);margin:0 0 16px;box-shadow:var(--dl-shadow)}.dl-metric{display:flex;flex-direction:column;gap:4px;padding:16px 20px;min-width:0}.dl-metric+.dl-metric{border-left:1px solid var(--dl-line)}.dl-metric-label{font-size:12px;font-weight:500;color:var(--dl-fg-faint)}.dl-metric-value{font-size:28px;line-height:36px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums;white-space:nowrap}.dl-metric-value .dl-faint{font-size:16px}.dl-metric-sub{font-size:12px;color:var(--dl-fg-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}@media(max-width:900px){.dl-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.dl-metric:nth-child(3){border-left:0}.dl-metric:nth-child(n+3){border-top:1px solid var(--dl-line)}}.dl-seg{display:inline-flex;gap:2px;padding:3px;border-radius:999px;background:var(--dl-soft);flex-wrap:wrap}.dl-seg button{all:unset;cursor:pointer;display:inline-flex;align-items:center;gap:6px;padding:4px 12px;border-radius:999px;font-size:13px;font-weight:500;color:var(--dl-fg-muted);white-space:nowrap}.dl-seg button:hover{color:var(--dl-fg)}.dl-seg button.on{background:var(--dl-soft-hover);color:var(--dl-fg)}.dl-seg.dl-srvsections{flex-wrap:nowrap;max-width:100%;overflow-x:auto;scrollbar-width:none}.dl-seg.dl-srvsections::-webkit-scrollbar{display:none}.dl-seg.dl-srvsections button{flex:none;white-space:nowrap}.dl-seg button:focus-visible{outline:2px solid var(--dl-ring)}.dl-seg button b{font-weight:500;font-size:11px;padding:0 6px;border-radius:999px;background:var(--dl-soft)}.dl-seg button b.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-seg.sm button{padding:2px 9px;font-size:11px}.dl-seg.wide{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));border-radius:12px;padding:4px}.dl-seg.wide button{flex-direction:column;justify-content:center;padding:8px 6px;border-radius:9px;gap:3px}.dl-seg.wide button.on{background:var(--dl-primary);color:var(--dl-primary-fg)}.dl-geomap{position:relative;border-top:1px solid var(--dl-line);background:var(--dl-soft)}.dl-map-status{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:var(--dl-fg-muted);font-size:13px;z-index:1;pointer-events:none}.dl-map-wrap{position:relative}.dl-map-legend{position:absolute;left:12px;bottom:12px;display:flex;gap:12px;align-items:center;padding:6px 12px;border-radius:999px;font-size:12px;background:color-mix(in srgb,var(--dl-card) 88%,transparent);border:1px solid var(--dl-line);backdrop-filter:blur(6px);z-index:2}.dl-map-legend span{display:inline-flex;align-items:center;gap:6px;color:var(--dl-fg-muted)}.dl-map-legend i.dot{width:8px;height:8px;border-radius:50%;background:var(--dl-fg-faint)}.dl-map-legend i.dot.ok{background:var(--dl-ok)}.dl-map-legend i.line{width:14px;height:2px;border-radius:2px;background:var(--dl-ok)}.dl-map-off{padding:32px 16px;text-align:center;color:var(--dl-fg-muted);border-top:1px solid var(--dl-line)}.dl-mk{all:unset;cursor:pointer;width:18px;height:18px;display:inline-flex;align-items:center;justify-content:center;position:relative}.dl-mk-dot{width:12px;height:12px;border-radius:50%;background:#8f8f8f;box-shadow:0 0 0 3px #0000008c}.dl-mk.online .dl-mk-dot{width:14px;height:14px;background:#40c977}.dl-mk.online:before{content:"";position:absolute;inset:-9px;border-radius:50%;background:#40c97747;animation:dl-pulse 2s ease-out infinite}@keyframes dl-pulse{0%{transform:scale(.5);opacity:1}to{transform:scale(1.4);opacity:0}}@media(prefers-reduced-motion:reduce){.dl-mk.online:before{animation:none}}.dl-mk-home{width:22px;height:22px;border-radius:7px;background:#ededed;display:flex;align-items:center;justify-content:center;box-shadow:0 0 0 4px #ededed2e,0 2px 6px #00000080;color:#131313}.dl-mk-home-ic{width:13px;height:13px}.dl-popup{z-index:4}.dl-popup .maplibregl-popup-content{background:var(--dl-elevated);color:var(--dl-fg);border:1px solid var(--dl-line);border-radius:12px;padding:12px;box-shadow:var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4));font:inherit}.dl-popup .maplibregl-popup-tip{border-top-color:var(--dl-elevated)!important;border-bottom-color:var(--dl-elevated)!important}.dl-pop{display:flex;flex-direction:column;gap:4px;font-size:12px;line-height:18px;min-width:210px}.dl-pop-head{display:flex;align-items:center;gap:8px;font-size:13px;margin-bottom:2px}.dl-mk.multi{width:26px;height:26px}.dl-mk-count{min-width:22px;height:22px;padding:0 6px;border-radius:999px;background:#8f8f8f;color:#0a0a0a;font:600 11px/22px var(--dl-mono);text-align:center;box-shadow:0 0 0 3px #0000008c;box-sizing:border-box}.dl-mk.online .dl-mk-count{background:#40c977}.dl-pop-net{width:30px;height:30px;border-radius:9px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-pop-list{display:flex;flex-direction:column;margin:6px -4px 0}.dl-pop-row{all:unset;cursor:pointer;display:flex;align-items:center;gap:8px;padding:5px 4px;border-radius:6px}.dl-pop-row:hover{background:var(--dl-soft)}.dl-pop-row:focus{outline:none}.dl-pop-row:focus-visible{outline:2px solid var(--dl-ring)}.dl-pop-name{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-pop-name b{font-weight:500}.dl-pop-dot{width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);flex:0 0 auto}.dl-pop-dot.on{background:var(--dl-ok);box-shadow:0 0 0 3px var(--dl-ok-wash)}.dl-pop-actions{display:flex;gap:6px;margin-top:8px;padding-top:8px;border-top:1px solid var(--dl-line)}.dl-pop-actions .cbi-button{flex:1;height:28px!important;font-size:12px!important;justify-content:center}.maplibregl-ctrl-attrib{font-size:10px}.dl-chartbox{position:relative}.dl-bars{display:flex;align-items:flex-end;gap:4px;border-bottom:1px solid var(--dl-line)}.dl-bar{flex:1;height:100%;display:flex;flex-direction:column-reverse;gap:1px;cursor:default;min-width:3px}.dl-bar i{display:block;border-radius:3px 3px 0 0}.dl-bar i.down{background:var(--dl-chart-1)}.dl-bar i.up{background:var(--dl-chart-2);opacity:.75;border-radius:3px 3px 0 0}.dl-bar:hover i{filter:brightness(1.25)}.dl-bar.empty{background:linear-gradient(to top,var(--dl-line) 2px,transparent 2px)}.dl-tip{position:absolute;top:-8px;transform:translate(-50%,-100%);padding:8px 10px;border-radius:10px;font-size:12px;line-height:18px;white-space:nowrap;background:var(--dl-elevated);border:1px solid var(--dl-line);box-shadow:var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4));pointer-events:none;z-index:3}.dl-tip-title{font-weight:500}.dl-tip-float{position:fixed;z-index:2000;color:var(--dl-fg)}.dl-spark i:hover{opacity:1;filter:brightness(1.25)}.dl-meter,.dl-slots{cursor:default}.dl-axis{display:flex;justify-content:space-between;font-size:12px;color:var(--dl-fg-faint);margin-top:6px}.dl-legend i.down{background:var(--dl-chart-1)}.dl-legend i.up{background:var(--dl-chart-2)}.dl-spark{display:flex;align-items:flex-end;gap:2px;flex:0 0 auto}.dl-spark i{flex:1;display:block;border-radius:2px 2px 0 0;background:var(--dl-chart-1);opacity:.85}.dl-spark i.zero{opacity:.22}.dl-row{display:flex;align-items:center;gap:12px;padding:12px 16px;border-top:1px solid var(--dl-line);font-size:14px;line-height:20px;min-width:0}.dl-row.link{color:inherit;text-decoration:none}.dl-row.link:hover{background:var(--dl-soft)}.dl-row-main{flex:1;min-width:0;overflow-wrap:anywhere}.dl-row-main b{font-weight:500}.dl-attn{display:flex;flex-direction:column;gap:10px;padding:16px;border-top:1px solid var(--dl-line)}.dl-attn-item{display:flex;gap:10px;align-items:baseline;font-size:13px;color:var(--dl-fg-muted)}.dl-avatar.sm{width:26px;height:26px;font-size:10px;margin:0}.dl-avatar.lg{width:48px;height:48px;font-size:15px;margin:0}.dl-avatar.lg.online:after{width:12px;height:12px}.dl-list{border:1px solid var(--dl-line);border-radius:12px;overflow:hidden}.dl-list>.dl-row:first-child{border-top:0}.dl-ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.dl-row-main.dl-stack{min-width:0}.dl-person-id{display:flex;align-items:center;gap:14px;min-width:0}.dl-grid-person{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);gap:16px;align-items:start}@media(max-width:1000px){.dl-grid-person{grid-template-columns:minmax(0,1fr)}}.dl-devsec{display:flex;flex-direction:column;gap:12px}.dl-devsec .dl-panel-head{margin:0}.dl-dgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.dl-dcard>.dl-dcard-head+*{margin-top:auto}@media(max-width:700px){.dl-dgrid{grid-template-columns:minmax(0,1fr)}}.dl-dgrid>.dl-dslot.add:only-child{grid-column:1 / -1}.dl-dcard{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:14px;padding:14px;display:flex;flex-direction:column;gap:12px;min-width:0;box-shadow:var(--dl-shadow)}.dl-dcard.online{border-color:color-mix(in srgb,var(--dl-ok) 35%,transparent)}.dl-dcard.off{opacity:.7}.dl-dcard-head{display:flex;align-items:center;gap:12px}.dl-dcard-ic{width:40px;height:40px;border-radius:12px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-dcard-ic .dl-icon{width:20px;height:20px}.dl-dcard.online .dl-dcard-ic{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-dcard-title{all:unset;cursor:pointer;flex:1;min-width:0;display:flex;flex-direction:column}.dl-dcard-title b{font-weight:500;font-size:15px}.dl-dstat{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--dl-fg-muted);white-space:nowrap;min-width:0}.dl-dstat i.dot{flex:none}.dl-dstat.ok{color:var(--dl-ok)}.dl-dstat.warn{color:var(--dl-warn)}.dl-dstat i.dot,.dl-savebar i.dot{width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint)}.dl-dstat i.dot.ok{background:var(--dl-ok);box-shadow:0 0 0 3px var(--dl-ok-wash)}.dl-dstat i.dot.warn{background:var(--dl-warn)}.dl-dcard-use{display:flex;align-items:flex-end;justify-content:space-between;gap:12px}.dl-dcard-foot{padding-top:10px;border-top:1px solid var(--dl-line);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-dslot.add{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:14px;min-height:0;border:1px dashed color-mix(in srgb,currentColor 18%,transparent);border-radius:14px;text-align:center;color:var(--dl-fg-muted);transition:background .15s,border-color .15s,color .15s}.dl-dslot.add .dl-stack{align-items:center}.dl-dslot.add:hover{border-color:color-mix(in srgb,currentColor 35%,transparent);color:var(--dl-fg)}.dl-dslot.add:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-dslot.add b{font-weight:500}.dl-dslot.add:hover{background:var(--dl-soft)}.dl-dslot-ic{width:36px;height:36px;border-radius:999px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-dslot.add:hover .dl-dslot-ic{background:var(--dl-primary);color:var(--dl-primary-fg)}.dl-tiles2{display:grid;gap:10px;margin-top:16px}.dl-tile2{border:1px solid var(--dl-line);border-radius:14px;padding:14px;display:flex;flex-direction:column;gap:10px;min-width:0}.dl-tile2-label{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:12px;font-weight:500;color:var(--dl-fg-faint)}.dl-tile2-row{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}.dl-tile2-value{font-size:20px;line-height:28px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums}.dl-tile2-value .dl-faint{font-size:14px;font-weight:400}.dl-tile2-foot{display:flex;align-items:center;justify-content:space-between;gap:12px;padding-top:10px;border-top:1px solid var(--dl-line);font-size:12px}.dl-stepper{display:inline-flex;align-items:stretch;height:32px;border:1px solid var(--input, var(--dl-line));border-radius:8px;overflow:hidden}.dl-stepper button{all:unset;cursor:pointer;width:32px;display:inline-flex;align-items:center;justify-content:center;font-size:16px;color:var(--dl-fg)}.dl-stepper button:hover{background:var(--dl-soft)}.dl-stepper button[disabled]{opacity:.35;cursor:not-allowed}.dl-stepper+.dl-stepper{margin-left:4px}.dl-step-select{border:0!important;border-left:1px solid var(--input, var(--dl-line))!important;border-right:1px solid var(--input, var(--dl-line))!important;border-radius:0!important;background:transparent!important;color:inherit;font:500 13px inherit;padding:0 10px!important;height:100%!important;min-width:0!important}.dl-slots{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(0,1fr);gap:3px}.dl-slots i{height:4px;border-radius:999px;background:var(--dl-track);display:block}.dl-slots i.used{background:var(--dl-fg)}.dl-slots i.over{background:color-mix(in srgb,var(--dl-warn) 80%,transparent)}.dl-date{display:flex;align-items:center;gap:8px;flex:1 1 150px;min-width:0;box-sizing:border-box;height:34px;padding:0 10px;border:1px solid var(--input, var(--dl-line));border-radius:8px;color:var(--dl-fg-faint)}.dl-date input{border:0!important;background:transparent!important;box-shadow:none!important;padding:0!important;height:32px!important;color:var(--dl-fg);flex:1;min-width:0!important;width:100%!important}.dl-meter{position:relative;height:6px;border-radius:999px;background:var(--dl-track)}.dl-meter>i{display:block;height:100%;border-radius:999px;background:var(--dl-accent)}.dl-meter.warn>i{background:var(--dl-warn)}.dl-meter.bad>i{background:var(--dl-bad)}.dl-meter .mark{position:absolute;left:90%;top:-3px;width:1px;height:12px;background:var(--dl-warn)}.dl-meter.sm{height:4px}.dl-chips-row{display:flex;flex-wrap:wrap;gap:4px}.dl-chipbtn{all:unset;cursor:pointer;height:26px;padding:0 10px;border-radius:999px;background:var(--dl-soft);font-size:12px;font-weight:500;display:inline-flex;align-items:center}.dl-chipbtn:hover{background:var(--dl-soft-hover)}.dl-chipbtn.on{background:var(--dl-primary);color:var(--dl-primary-fg)}.dl-switch{all:unset;cursor:pointer;position:relative;width:32px;height:20px;border-radius:999px;background:var(--switch-off, var(--dl-track));flex:0 0 auto;transition:background .15s}.dl-switch i{position:absolute;left:2px;top:2px;width:16px;height:16px;border-radius:50%;background:#fff;transition:left .15s;box-shadow:0 1px 2px #0000004d}.dl-switch.on{background:var(--dl-accent)}.dl-switch.on i{left:14px}.dl-switch:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-linkbox{display:flex;align-items:center;gap:8px;height:36px;padding:0 4px 0 12px;border:1px solid var(--input, var(--dl-line));border-radius:8px;background:var(--input-bg, transparent)}.dl-linkbox .dl-mono{flex:1;min-width:0;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--dl-fg-muted)}.dl-linkbox .cbi-button{height:28px!important}.dl-map .cbi-section-create,.dl-map>.cbi-section>.cbi-button-add{display:none!important}.dl-pcard{display:grid;grid-template-columns:minmax(0,1fr) 260px;gap:20px;align-items:stretch;min-width:0}.dl-pcard-main{min-width:0}.dl-pcard-top{display:flex;align-items:center;gap:12px;min-width:0}.dl-pcard-top .dl-avatar{margin-right:0}.dl-pcard-who{flex:1;min-width:0}.dl-pcard-who .dl-slotbar{margin:3px 0 0}.dl-pside{display:flex;flex-direction:column;justify-content:space-between;gap:8px;padding-left:20px;border-left:1px solid var(--dl-line);min-width:0}.dl-pside-top{display:flex;align-items:center;justify-content:space-between;gap:8px}.dl-pside-state{display:inline-flex;align-items:center;gap:6px;font-size:13px;color:var(--dl-fg-muted)}.dl-pside-state.live{color:var(--dl-ok)}.dl-pside-foot{font-size:12px}.dl-pside .dl-use-num b{font-size:20px}.dl-map .cbi-section-table-row>.td:has(.dl-pcard){flex:1 1 100%;max-width:none!important;width:100%!important;margin:0!important}.dl-none{display:none!important}.dl-pcard-actions{display:flex;gap:6px;flex:0 0 auto}.dl-pcard-actions .cbi-button{height:32px!important}.dl-icon-only .dl-btn-label{display:none}.dl-pill-ic{display:inline-flex;align-items:center;gap:4px;height:22px;padding:0 8px;border-radius:999px;font-size:12px;white-space:nowrap;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pill-ic .dl-icon{width:12px;height:12px}.dl-pill-ic.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-pill-ic.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-use-num{display:flex;align-items:baseline;gap:6px;white-space:nowrap}.dl-use-num b{font-size:15px;font-weight:500}.dl-use-live{display:flex;align-items:center;gap:8px;font-size:12px;font-variant-numeric:tabular-nums}.dl-usebar{display:flex;gap:2px;height:6px;border-radius:999px;overflow:hidden;background:var(--dl-track)}.dl-usebar i{display:block;height:100%;min-width:3px;flex:0 1 0}.dl-usebar i.fill{flex:none;min-width:0;border-radius:999px;background:var(--dl-accent)}.dl-usebar.warn i.fill{background:var(--dl-warn)}.dl-usebar.bad i.fill{background:var(--dl-bad)}.dl-usebar .c0,.dl-swatch.c0{background:var(--dl-chart-1)}.dl-usebar .c1,.dl-swatch.c1{background:#8b7cf6}.dl-usebar .c2,.dl-swatch.c2{background:#2fb889}.dl-usebar .c3,.dl-swatch.c3{background:#d9a03f}.dl-usebar .c4,.dl-swatch.c4{background:var(--dl-fg-faint)}.dl-tip-row{display:flex;align-items:center;gap:8px;min-width:160px}.dl-tip-row b{margin-left:auto;font-weight:500}.dl-swatch{width:8px;height:8px;border-radius:2px;flex:none}.dl-card-name{color:var(--dl-fg)!important;text-decoration:none}.dl-card-name:hover{text-decoration:underline}.dl-chip-tag{font-size:11px;line-height:18px;padding:0 6px;border-radius:999px;background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-chip.live{background:var(--dl-ok-wash);color:color-mix(in srgb,var(--dl-ok) 35%,var(--dl-fg))}.dl-chip.live:hover{background:color-mix(in srgb,var(--dl-ok) 22%,transparent)}.dl-chip.live .dl-icon{color:var(--dl-ok)}.dl-fixes{display:flex;gap:6px;flex-wrap:wrap;margin:10px 0 0 44px}.dl-fix{all:unset;cursor:pointer;height:26px;padding:0 10px;border-radius:999px;background:var(--dl-info-wash);color:var(--dl-info);font-size:12px;font-weight:500;display:inline-flex;align-items:center}.dl-fix:hover{filter:brightness(1.15)}.dl-map .cbi-section-table-row.dl-attn-row{border-color:color-mix(in srgb,var(--dl-warn) 35%,transparent)!important}@media(max-width:760px){.dl-pcard{grid-template-columns:1fr}.dl-pside{padding:12px 0 0;border-left:0;border-top:1px solid var(--dl-line)}.dl-fixes{margin-left:0}}.dl-select{height:34px!important;border-radius:999px!important;min-width:136px!important;width:auto!important;padding:0 34px 0 14px!important;appearance:none!important;-webkit-appearance:none!important;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238b8f98' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")!important;background-repeat:no-repeat!important;background-position:right 12px center!important;background-size:14px!important}.dl-savebar{position:fixed;left:50%;bottom:24px;transform:translate(-50%,160%);opacity:0;transition:transform .25s cubic-bezier(.2,.8,.2,1),opacity .2s;display:flex;align-items:center;gap:10px;padding:8px 8px 8px 18px;border-radius:999px;background:var(--dl-elevated);border:1px solid var(--dl-line);box-shadow:var(--shadow-2xl, 0 16px 32px -8px rgba(0,0,0,.5));z-index:60;pointer-events:none}.dl-savebar.show{transform:translate(-50%);opacity:1;pointer-events:auto}.dl-savebar-text{display:inline-flex;align-items:center;gap:8px;font-size:13px;font-weight:500}.dl-toast strong{display:block;font-weight:500}.dl-toast div{opacity:.8;font-size:13px}.dl-drawer-overlay{position:fixed;inset:0;z-index:900;display:flex;justify-content:flex-end;background:transparent;transition:background .2s}.dl-drawer-overlay.open{background:var(--scrim, rgba(0,0,0,.45))}.dl-drawer{width:min(520px,100%);height:100%;display:flex;flex-direction:column;background:var(--dialog-bg, var(--dl-elevated));color:var(--dl-fg);border-left:1px solid var(--dl-line);box-shadow:var(--shadow-2xl, -16px 0 32px -8px rgba(0,0,0,.5));transform:translate(100%);transition:transform .22s cubic-bezier(.2,.8,.2,1)}.dl-drawer-overlay.open .dl-drawer{transform:none}.dl-drawer-head{display:flex;align-items:center;gap:12px;padding:16px 20px;border-bottom:1px solid var(--dl-line)}.dl-drawer-title{flex:1;min-width:0;display:flex;align-items:center;gap:12px}.dl-drawer-title h3{margin:0!important;padding:0!important;border:0!important;font-size:18px!important;line-height:26px;font-weight:500!important}.dl-drawer-x{all:unset;cursor:pointer;width:32px;height:32px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;color:var(--dl-fg-muted)}.dl-drawer-x:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-drawer-body{flex:1;overflow:auto;padding:20px}.dl-drawer-foot{padding:12px 20px;border-top:1px solid var(--dl-line)}.dl-drawer-actions{display:flex;align-items:center;gap:8px}.dl-dcard-ic.on{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-icon-only.sm{width:28px;height:28px!important}.dl-stack.gap12{gap:12px}.dl-stack.gap16{gap:16px}.dl-dstats{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));border:1px solid var(--dl-line);border-radius:14px;overflow:hidden}.dl-dstats-cell{display:flex;flex-direction:column;gap:4px;padding:12px 14px;min-width:0}.dl-dstats-cell.wide{grid-column:span 2;border-bottom:1px solid var(--dl-line)}.dl-dstats-cell+.dl-dstats-cell:not(.wide):last-child{border-left:1px solid var(--dl-line)}.dl-dstats-cell b{font-size:16px;font-weight:500;font-variant-numeric:tabular-nums}.dl-dstats-cell .dl-dstat{font-size:14px}.dl-dsec{border:1px solid var(--dl-line);border-radius:14px;padding:16px;display:flex;flex-direction:column;gap:12px}.dl-dsec-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.dl-dsec-head h4{margin:0!important;padding:0!important;font-size:14px!important;font-weight:500!important;border:0!important}.dl-dstat i.dot{width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);display:inline-block}.dl-connect-body{min-height:60px}.dl-connect-body .dl-qr{width:min(240px,70vw)}.dl-kv2{display:flex;flex-direction:column}.dl-kvrow{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:9px 0;border-top:1px solid var(--dl-line);font-size:13px;min-width:0}.dl-kvrow:first-child{border-top:0;padding-top:0}.dl-kvrow-k{color:var(--dl-fg-muted);flex:0 0 auto}.dl-kvrow-v{min-width:0;text-align:right;overflow-wrap:anywhere}.dl-kvrow-v.copy{all:unset;cursor:pointer;display:inline-flex;align-items:center;gap:6px;min-width:0;color:var(--dl-fg)}.dl-kvrow-v.copy span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-kvrow-v.copy .dl-icon{width:13px;height:13px;color:var(--dl-fg-faint)}.dl-kvrow-v.copy:hover .dl-icon{color:var(--dl-fg)}@media(max-width:560px){.dl-drawer{width:100%}.dl-dstats{grid-template-columns:minmax(0,1fr)}.dl-dstats-cell.wide{grid-column:auto}.dl-dstats-cell+.dl-dstats-cell:not(.wide):last-child{border-left:0;border-top:1px solid var(--dl-line)}}.dl-dev-log{display:flex;flex-direction:column}.dl-dev-log-row{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid var(--dl-line);font-size:13px;line-height:20px;min-width:0}.dl-dev-log-row:first-child{border-top:0;padding-top:0}.dl-dev-log-row .dl-row-main{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-settings-main{min-width:0;display:flex;flex-direction:column;gap:20px}.dl-setsec{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);overflow:hidden;scroll-margin-top:88px;box-shadow:var(--dl-shadow)}.dl-setsec-body{padding:20px;display:flex;flex-direction:column;gap:14px}.dl-setsec-body h3{margin:0!important;padding:0!important;font-size:18px!important;line-height:26px;font-weight:500!important;border:0!important}.dl-setsec-body p{margin:0}.dl-setsec-head{display:flex;align-items:center;gap:10px}.dl-group{border:1px solid var(--dl-line);border-radius:14px;padding:2px 16px}.dl-group-head{display:flex;align-items:center;gap:12px;padding:14px 0 10px}.dl-group-head b{font-size:15px;font-weight:500}.dl-group-ic{width:32px;height:32px;border-radius:10px;background:var(--dl-soft);color:var(--dl-fg-muted);display:inline-flex;align-items:center;justify-content:center;flex:none}.dl-group-ic .dl-icon-wrap{display:inline-flex}.dl-group-ic .dl-icon{width:16px;height:16px}.dl-group-body>*{padding:12px 0;margin:0!important}.dl-group-body>*+*{border-top:1px solid var(--dl-line)}.dl-group-body>.dl-row{border-left:0;border-right:0;border-bottom:0;padding-left:0;padding-right:0;background:none}.dl-group-body>.dl-row:first-child{border-top:0}.dl-setsec-foot{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:10px 16px;padding:12px 20px;border-top:1px solid var(--dl-line);background:var(--dl-soft)}.dl-setsec.danger{border-color:color-mix(in srgb,var(--dl-bad) 40%,transparent)}.dl-setsec.danger .dl-setsec-foot{background:color-mix(in srgb,var(--dl-bad) 6%,transparent)}.dl-setrow{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,420px);align-items:center;gap:8px 24px}.dl-setrow.head{display:flex;justify-content:space-between;gap:16px}.dl-setrow-label{font-size:14px;font-weight:500}.dl-setrow-ctl{display:flex;justify-content:flex-end;min-width:0}.dl-setrow-ctl .dl-chips-row{justify-content:flex-end}.dl-setrow-ctl>input{width:100%}.dl-hostport{display:flex;align-items:center;gap:8px;flex:1;min-width:0;justify-content:flex-end}.dl-hostport input{flex:1;min-width:0}.dl-root input.dl-w-port,.dl-hostport input.dl-w-port{flex:0 0 90px;width:90px}.dl-more summary{cursor:pointer;color:var(--dl-fg-muted);font-size:13px;margin-bottom:10px}.dl-more .dl-setrow+.dl-setrow{margin-top:10px}@media(max-width:760px){.dl-setrow:not(.head){grid-template-columns:minmax(0,1fr)}.dl-setrow-ctl,.dl-setrow-ctl .dl-chips-row{justify-content:flex-start}}.dl-need-ic{width:30px;height:30px;border-radius:9px;background:var(--dl-soft);color:var(--dl-fg-muted);display:inline-flex;align-items:center;justify-content:center;flex:none}.dl-need-ic .dl-icon-wrap{display:inline-flex}.dl-need-ic .dl-icon{width:15px;height:15px}.dl-need-row.bad .dl-need-ic,.dl-need-ic.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-need-row.warn .dl-need-ic,.dl-need-ic.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-need-ic.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-lh-main{display:flex;align-items:flex-start;gap:12px;min-width:0}.dl-lh-main>.dl-need-ic{margin-top:1px}.dl-sub .dl-mono{font-size:.92em}.dl-need-row>.cbi-button{flex:none}.dl-bk-row .dl-group-ic{width:30px;height:30px}.dl-bk-older>summary{list-style:none;cursor:pointer;display:flex;align-items:center;gap:8px;padding:11px 16px;border-top:1px solid var(--dl-line);font-size:13px;color:var(--dl-fg-muted);user-select:none}.dl-bk-older>summary::-webkit-details-marker{display:none}.dl-bk-older>summary:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-bk-older>summary .dl-icon-wrap{display:inline-flex;transition:transform .15s}.dl-bk-older>summary .dl-icon{width:14px;height:14px}.dl-bk-older[open]>summary .dl-icon-wrap{transform:rotate(90deg)}#dl-set-backups .dl-setsec-head h3+.dl-sub{margin-top:2px}#dl-set-backups .dl-setsec-foot>.dl-sub{flex:1 1 260px}.dl-bk-actions{flex:0 1 auto;justify-content:flex-end}@media(max-width:640px){#dl-set-backups .dl-setsec-foot>.dl-sub{flex-basis:100%}.dl-bk-actions{justify-content:flex-start}}.dl-upd{display:flex;flex-direction:column;gap:16px}.dl-upd>.dl-pagehead{margin:0 0 4px}.dl-upd-head{display:flex;align-items:center;gap:12px;padding:16px 20px}.dl-upd-head>.dl-stack{flex:1;min-width:0}.dl-upd-head>.dl-stack>b{font-size:15px;font-weight:500}.dl-upd-row{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:12px 20px;border-top:1px solid var(--dl-line);min-height:40px}.dl-upd-row>.dl-stack{min-width:0}.dl-upd-name{font-size:14px}.dl-upd-row .dl-mono{font-size:11px}.dl-upd-row .dl-mono b{color:var(--dl-fg);font-weight:500}.dl-upd-row>.dl-pill,.dl-upd-row>button,.dl-upd-head>.dl-pill,.dl-upd-head>button{flex:none}.dl-upd-bad{color:var(--dl-bad)}.dl-upd-job>.dl-log,.dl-upd-job>.alert-message{margin:0 14px 14px}.dl-chip.static{cursor:default}.dl-chip.static:hover{background:var(--dl-soft)}.dl-chip.static .dl-chip-name{font-weight:500}.dl-setrow.head .dl-chips-row{margin-top:8px}.dl-setrow.head>.dl-lh-main,.dl-setrow.head>.dl-lh-main>.dl-stack{flex:1 1 auto;min-width:0}.dl-setrow.head>.dl-setrow-ctl:empty{display:none}.dl-setrow.head:has(>.dl-lh-main){align-items:flex-start}.dl-setrow.head>.dl-setrow-ctl{align-items:center;min-height:30px}.dl-netpick{margin-top:10px}.dl-boxrow{display:flex;align-items:center;justify-content:space-between;gap:16px;margin:0;padding:10px 14px;border:1px solid var(--dl-line);border-radius:12px;font-size:13px;cursor:pointer}.dl-boxrow>.dl-switch{flex:none}.dl-ifpick{display:flex;flex-direction:column;gap:12px;padding:14px;border:1px solid var(--dl-line);border-radius:14px}.dl-iflead-row{display:flex;align-items:center;justify-content:space-between;gap:12px}.dl-host-ports{justify-content:flex-end}@media(max-width:760px){.dl-host-ports{justify-content:flex-start}}.dl-circle-dot{display:inline-block;width:8px;height:8px;border-radius:50%;flex:none}.dl-circles .dl-chip b{font-weight:500}.dl-circle-name{display:inline-flex;align-items:center;gap:8px;font-size:14px;font-weight:500}.dl-w400{font-weight:400}.dl-swatches{display:flex;flex-wrap:wrap;gap:8px}.dl-swatch{all:unset;cursor:pointer;width:22px;height:22px;border-radius:50%;background:var(--sw);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dl-fg) 12%,transparent)}.dl-swatch.on{box-shadow:0 0 0 2px var(--dl-card),0 0 0 4px var(--sw)}.dl-swatch:focus-visible{outline:2px solid var(--dl-ring);outline-offset:3px}.dl-circle-modal .dl-chipbtn b{margin-left:6px;font-weight:500;font-size:11px;opacity:.6}.dl-reach td:first-child b{font-weight:500}.dl-ev-host{white-space:nowrap}.dl-ev-host b{font-weight:500;color:var(--dl-fg)}.dl-reach{font-size:13px}.dl-reach th,.dl-reach td{white-space:nowrap;padding-left:6px;padding-right:6px}.dl-reach-wrap{overflow-x:auto}.dl-yes{display:inline-flex;align-items:center;gap:4px;color:var(--dl-ok)}.dl-yes .dl-icon-wrap{display:inline-flex}.dl-yes .dl-icon{width:14px;height:14px}.dl-check-form{display:grid;grid-template-columns:minmax(0,1fr) auto minmax(0,1fr) auto;align-items:start;gap:8px}.dl-check-form>.dl-faint{line-height:36px}.dl-check-end{display:flex;flex-direction:column;gap:6px;min-width:0}.dl-check-end>*{width:100%!important;min-width:0}@media(max-width:560px){.dl-check-form{grid-template-columns:minmax(0,1fr)}.dl-check-form>.dl-faint{display:none}}.dl-verdict{display:flex;align-items:baseline;gap:10px;padding:10px 12px;border-radius:12px}.dl-verdict b{font-weight:500}.dl-verdict.ok{background:var(--dl-ok-wash)}.dl-verdict.ok b{color:var(--dl-ok)}.dl-verdict.bad{background:var(--dl-bad-wash)}.dl-verdict.bad b{color:var(--dl-bad)}`;function Cn(){let i=document.createElement("style");return i.dataset.dawnline="1",i.textContent=ts,i}function je(i,t){return()=>{let n=new i,a={load:()=>n.load(),render:async s=>{let o=await n.render(s),r=document.createElement("div");return r.className="dl-root",r.append(Cn(),o),r},addFooter(){return n.noFooter?document.createElement("div"):this.super("addFooter",[])}};return t||Object.assign(a,{handleSave:null,handleSaveApply:null,handleReset:null}),a}}var Xo=je(st,!1),er=je(Be,!0),tr=je(st,!1),nr=je(kt,!1),ar=je(St,!1),sr=je(Lt,!1),ir=je(_t,!1);function Dn(i){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${i?`?tab=${i}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var or=Dn(""),rr=Dn("log");return baseclass.extend({ activity: rr, diagnostics: sr, health: or, overview: Xo, people: er, person: ar, server: tr, settings: nr, updates: ir }); +var Ra=Object.create;var jn=Object.defineProperty;var Ha=Object.getOwnPropertyDescriptor;var Ia=Object.getOwnPropertyNames;var Ba=Object.getPrototypeOf,Oa=Object.prototype.hasOwnProperty;var ja=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var Ua=(n,t,o,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ia(t))!Oa.call(n,r)&&r!==o&&jn(n,r,{get:()=>t[r],enumerable:!(a=Ha(t,r))||a.enumerable});return n};var Wa=(n,t,o)=>(o=n!=null?Ra(Ba(n)):{},Ua(t||!n||!n.__esModule?jn(o,"default",{value:n,enumerable:!0}):o,n));var Qn=ja((Vn,Yn)=>{"use strict";var Jn=(function(){var n=function(w,H){var S=236,T=17,b=w,A=o[H],u=null,f=0,N=null,P=[],I={},J=function(M,_){f=b*4+17,u=(function(k){for(var z=new Array(k),y=0;y=7&&Q(M),N==null&&(N=me(b,A,P)),O(N,_)},W=function(M,_){for(var k=-1;k<=7;k+=1)if(!(M+k<=-1||f<=M+k))for(var z=-1;z<=7;z+=1)_+z<=-1||f<=_+z||(0<=k&&k<=6&&(z==0||z==6)||0<=z&&z<=6&&(k==0||k==6)||2<=k&&k<=4&&2<=z&&z<=4?u[M+k][_+z]=!0:u[M+k][_+z]=!1)},q=function(){for(var M=0,_=0,k=0;k<8;k+=1){J(!0,k);var z=r.getLostPoint(I);(k==0||M>z)&&(M=z,_=k)}return _},C=function(){for(var M=8;M>k&1)==1;u[Math.floor(k/3)][k%3+f-8-3]=z}for(var k=0;k<18;k+=1){var z=!M&&(_>>k&1)==1;u[k%3+f-8-3][Math.floor(k/3)]=z}},de=function(M,_){for(var k=A<<3|_,z=r.getBCHTypeInfo(k),y=0;y<15;y+=1){var B=!M&&(z>>y&1)==1;y<6?u[y][8]=B:y<8?u[y+1][8]=B:u[f-15+y][8]=B}for(var y=0;y<15;y+=1){var B=!M&&(z>>y&1)==1;y<8?u[8][f-y-1]=B:y<9?u[8][15-y-1+1]=B:u[8][15-y-1]=B}u[f-8][8]=!M},O=function(M,_){for(var k=-1,z=f-1,y=7,B=0,Y=r.getMaskFunction(_),V=f-1;V>0;V-=2)for(V==6&&(V-=1);;){for(var ce=0;ce<2;ce+=1)if(u[z][V-ce]==null){var be=!1;B>>y&1)==1);var ee=Y(z,V-ce);ee&&(be=!be),u[z][V-ce]=be,y-=1,y==-1&&(B+=1,y=7)}if(z+=k,z<0||f<=z){z-=k,k=-k;break}}},F=function(M,_){for(var k=0,z=0,y=0,B=new Array(_.length),Y=new Array(_.length),V=0;V<_.length;V+=1){var ce=_[V].dataCount,be=_[V].totalCount-ce;z=Math.max(z,ce),y=Math.max(y,be),B[V]=new Array(ce);for(var ee=0;ee=0?In.getAt(Bn):0}}for(var On=0,ee=0;ee<_.length;ee+=1)On+=_[ee].totalCount;for(var hn=new Array(On),Nt=0,ee=0;eeV*8)throw"code length overflow. ("+y.getLengthInBits()+">"+V*8+")";for(y.getLengthInBits()+4<=V*8&&y.put(0,4);y.getLengthInBits()%8!=0;)y.putBit(!1);for(;!(y.getLengthInBits()>=V*8||(y.put(S,8),y.getLengthInBits()>=V*8));)y.put(T,8);return F(y,z)};I.addData=function(M,_){_=_||"Byte";var k=null;switch(_){case"Numeric":k=p(M);break;case"Alphanumeric":k=c(M);break;case"Byte":k=m(M);break;case"Kanji":k=v(M);break;default:throw"mode:"+_}P.push(k),N=null},I.isDark=function(M,_){if(M<0||f<=M||_<0||f<=_)throw M+","+_;return u[M][_]},I.getModuleCount=function(){return f},I.make=function(){if(b<1){for(var M=1;M<40;M++){for(var _=l.getRSBlocks(M,A),k=d(),z=0;z"u"?M*4:_;var k="";k+='";for(var y=0;y';k+=""}return k+="",k+="
",k},I.createSvgTag=function(M,_,k,z){var y={};typeof arguments[0]=="object"&&(y=arguments[0],M=y.cellSize,_=y.margin,k=y.alt,z=y.title),M=M||2,_=typeof _>"u"?M*4:_,k=typeof k=="string"?{text:k}:k||{},k.text=k.text||null,k.id=k.text?k.id||"qrcode-description":null,z=typeof z=="string"?{text:z}:z||{},z.text=z.text||null,z.id=z.text?z.id||"qrcode-title":null;var B=I.getModuleCount()*M+_*2,Y,V,ce,be,ee="",Se;for(Se="l"+M+",0 0,"+M+" -"+M+",0 0,-"+M+"z ",ee+=''+re(z.text)+"":"",ee+=k.text?''+re(k.text)+"":"",ee+='',ee+='"u"?M*4:_;var k=I.getModuleCount()*M+_*2,z=_,y=k-_;return j(k,k,function(B,Y){if(z<=B&&B"u"?M*4:_;var z=I.getModuleCount()*M+_*2,y="";return y+="",y};var re=function(M){for(var _="",k=0;k":_+=">";break;case"&":_+="&";break;case'"':_+=""";break;default:_+=z;break}}return _},ge=function(M){var _=1;M=typeof M>"u"?_*2:M;var k=I.getModuleCount()*_+M*2,z=M,y=k-M,B,Y,V,ce,be,ee={"██":"█","█ ":"▀"," █":"▄"," ":" "},Se={"██":"▀","█ ":"▀"," █":" "," ":" "},Ce="";for(B=0;B=y?Se[be]:ee[be];Ce+=` +`}return k%2&&M>0?Ce.substring(0,Ce.length-k-1)+Array(k+1).join("▀"):Ce.substring(0,Ce.length-1)};return I.createASCII=function(M,_){if(M=M||1,M<2)return ge(_);M-=1,_=typeof _>"u"?M*2:_;var k=I.getModuleCount()*M+_*2,z=_,y=k-_,B,Y,V,ce,be=Array(M+1).join("██"),ee=Array(M+1).join(" "),Se="",Ce="";for(B=0;B>>8),A.push(N&255)):A.push(T)}}return A}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var w=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],H=1335,S=7973,T=21522,b={},A=function(u){for(var f=0;u!=0;)f+=1,u>>>=1;return f};return b.getBCHTypeInfo=function(u){for(var f=u<<10;A(f)-A(H)>=0;)f^=H<=0;)f^=S<5&&(N+=3+J-5)}for(var P=0;P=256;)b-=255;return w[b]},T})();function s(w,H){if(typeof w.length>"u")throw w.length+"/"+H;var S=(function(){for(var b=0;b"u")throw"bad rs block @ typeNumber:"+b+"/errorCorrectionLevel:"+A;for(var f=u.length/3,N=[],P=0;P>>7-T%8&1)==1},S.put=function(T,b){for(var A=0;A>>b-A-1&1)==1)},S.getLengthInBits=function(){return H},S.putBit=function(T){var b=Math.floor(H/8);w.length<=b&&w.push(0),T&&(w[b]|=128>>>H%8),H+=1},S},p=function(w){var H=t.MODE_NUMBER,S=w,T={};T.getMode=function(){return H},T.getLength=function(u){return S.length},T.write=function(u){for(var f=S,N=0;N+2>>8&255)*192+(P&255),u.put(P,13),N+=2}if(N>>8)},H.writeBytes=function(S,T,b){T=T||0,b=b||S.length;for(var A=0;A0&&(S+=","),S+=w[T];return S+="]",S},H},x=function(){var w=0,H=0,S=0,T="",b={},A=function(f){T+=String.fromCharCode(u(f&63))},u=function(f){if(!(f<0)){if(f<26)return 65+f;if(f<52)return 97+(f-26);if(f<62)return 48+(f-52);if(f==62)return 43;if(f==63)return 47}throw"n:"+f};return b.writeByte=function(f){for(w=w<<8|f&255,H+=8,S+=1;H>=6;)A(w>>>H-6),H-=6},b.flush=function(){if(H>0&&(A(w<<6-H),w=0,H=0),S%3!=0)for(var f=3-S%3,N=0;N=H.length){if(b==0)return-1;throw"unexpected end of file./"+b}var f=H.charAt(S);if(S+=1,f=="=")return b=0,-1;if(f.match(/^\s$/))continue;T=T<<6|u(f.charCodeAt(0)),b+=6}var N=T>>>b-8&255;return b-=8,N};var u=function(f){if(65<=f&&f<=90)return f-65;if(97<=f&&f<=122)return f-97+26;if(48<=f&&f<=57)return f-48+52;if(f==43)return 62;if(f==47)return 63;throw"c:"+f};return A},$=function(w,H){var S=w,T=H,b=new Array(w*H),A={};A.setPixel=function(P,I,J){b[I*S+P]=J},A.write=function(P){P.writeString("GIF87a"),P.writeShort(S),P.writeShort(T),P.writeByte(128),P.writeByte(0),P.writeByte(0),P.writeByte(0),P.writeByte(0),P.writeByte(0),P.writeByte(255),P.writeByte(255),P.writeByte(255),P.writeString(","),P.writeShort(0),P.writeShort(0),P.writeShort(S),P.writeShort(T),P.writeByte(0);var I=2,J=f(I);P.writeByte(I);for(var W=0;J.length-W>255;)P.writeByte(255),P.writeBytes(J,W,255),W+=255;P.writeByte(J.length-W),P.writeBytes(J,W,J.length-W),P.writeByte(0),P.writeString(";")};var u=function(P){var I=P,J=0,W=0,q={};return q.write=function(C,G){if(C>>>G)throw"length over";for(;J+G>=8;)I.writeByte(255&(C<>>=8-J,W=0,J=0;W=C<0&&I.writeByte(W)},q},f=function(P){for(var I=1<>6,128|i&63):i<55296||i>=57344?a.push(224|i>>12,128|i>>6&63,128|i&63):(r++,i=65536+((i&1023)<<10|o.charCodeAt(r)&1023),a.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63))}return a}return t(n)}})();(function(n){typeof define=="function"&&define.amd?define([],n):typeof Vn=="object"&&(Yn.exports=n())})(function(){return Jn})});function fn(n,t){return n==null||n===!1||n===""||(Array.isArray(n)?n.forEach(o=>fn(o,t)):t.push(n instanceof Node?n:String(n))),t}function e(n,t,o){let a=window.E,r=t!=null&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Node);return!r&&o===void 0?a(n,{},fn(t,[])):a(n,r?t:{},fn(o,[]))}function K(n,t=[]){let o=rpc.declare({object:"luci.dawnline",method:n,params:t});return async(...a)=>{let r=await o(...a);if(r&&typeof r=="object"&&typeof r.error=="string")throw new Error(r.error);return r}}var Ga=K("logs_clear",["person","device","category","older_days"]),qa=(n={})=>Ga(n.person??"",n.device??"",n.category??"",n.older_days??""),Fa=rpc.declare({object:"luci.dawnline",method:"person_update",params:["id","name","access","device_limit","expires","expire_action","expire_warn","quota_gb","quota_period","bonus_gb","hours","note","dns_mode","paused","services","circle","home_nets"]});async function Ka(n,t){let a=[n,...["name","access","device_limit","expires","expire_action","expire_warn","quota_gb","quota_period","bonus_gb","hours","note","dns_mode"].map(i=>t[i]),t.paused,t.services,t.circle,t.home_nets],r=await Fa(...a);if(r&&typeof r.error=="string")throw new Error(r.error);return r}var Ja=K("status",["days"]),E={personUpdate:Ka,settingsGet:K("settings_get"),portalInfo:K("portal_info"),settingsUpdate:K("settings_update",["values"]),serviceSet:K("service_set",["id","name","address","ports"]),serviceDelete:K("service_delete",["id"]),geoClear:K("geo_clear"),events:K("events",["limit"]),logsClear:qa,interfaces:K("interfaces",["id"]),serverInterfaces:K("server_interfaces",["id","auto_wan","wan_device","auto_lan","lan_devices","lan_like","device_mesh","mesh"]),circleSet:K("circle_set",["id","server","name","color","members"]),circleDelete:K("circle_delete",["id"]),accessCheck:K("access_check",["from","to"]),homeHosts:K("home_hosts",["id"]),usageClear:K("usage_clear",["scope","id"]),uninstall:K("uninstall",["confirm"]),status:Ja,setupDefaults:K("setup_defaults"),serverCreate:K("server_create",["id","name","ifname","port","subnet","endpoint","mtu","preset","lan_zone","wan_zone","lan_like","portal_enabled","portal_port"]),serverObfuscation:K("server_obfuscation",["id","preset"]),serverUpdate:K("server_update",["id","values"]),serverDelete:K("server_delete",["id"]),personLinks:K("person_links",["id"]),personCreate:K("person_create",["name","slug","server","access","device_limit","expires","quota_gb","quota_period"]),personPause:K("person_pause",["id","paused"]),personRegen:K("person_regen",["id"]),personDelete:K("person_delete",["id"]),personUsage:K("person_usage",["id","days"]),pauseAll:K("pause_all",["paused"]),deviceCreate:K("device_create",["person","name","kind"]),deviceConfig:K("device_config",["id"]),deviceUpdate:K("device_update",["id","name","disabled"]),deviceDelete:K("device_delete",["id"]),deviceRotate:K("device_rotate",["id"]),apply:K("apply"),health:K("health"),healthFix:K("health_fix",["id"]),serviceLog:K("service_log"),serviceLogClear:K("service_log_clear",["older_days"]),backupList:K("backup_list"),backupCreate:K("backup_create"),backupRestore:K("backup_restore",["name"]),backupDelete:K("backup_delete",["name"]),backupRead:K("backup_read",["name"]),backupUpload:K("backup_upload",["data"]),exportJson:K("export"),importJson:K("import",["data"]),updatesStatus:K("updates_status"),updatesRun:K("updates_run",["what"]),updatesReleases:K("updates_releases",["page"]),updatesNotes:K("updates_notes",["component","tag","build"]),updatesChanges:K("updates_changes",["from","to"])};var Un={phone:'',computer:'',tablet:'',router:'',other:'',ethernet:'',bridge:'',wifi:'',tunnel:'',plus:'',chart:'',reset:'',package:'',code:'',plug:'',sunrise:'',refresh:'',archive:'',qr:'',copy:'',download:'',link:'',trash:'',edit:'',pause:'',play:'',key:'',out:'',admin:'',shield:'',shieldplus:'',lock:'',zap:'',check:'',alert:'',x:'',globe:'',home:'',open:'',file:'',network:'',moon:'',chevron:'',clock:'',calendar:'',minus:'',more:'',pin:'',activity:''};function gn(n,t="dl-icon"){let o=Un[n]??Un.phone;return``}function g(n,t="dl-icon"){let o=document.createElement("span");return o.className="dl-icon-wrap",o.innerHTML=gn(n,t),o}function Z(n,t="info",o=0){let a=document.querySelector(".dl-toasts");a||(a=e("div",{class:"dl-toasts dl-root",role:"status","aria-live":"polite"}),document.body.appendChild(a));let r=t==="error"?"x":t==="warning"?"alert":t==="success"?"check":null,i=()=>{s.classList.remove("show"),setTimeout(()=>s.remove(),200)},s=e("div",{class:`dl-toast ${t}`},[r?g(r):"",e("span",{},n),t==="error"?e("button",{type:"button","aria-label":"Close",click:i},g("x")):""]);a.appendChild(s),requestAnimationFrame(()=>s.classList.add("show")),setTimeout(i,o||(t==="error"?8e3:t==="warning"?5e3:2600))}function ve(n){return n instanceof Error?n.message:String(n)}async function U(n,t){try{let o=await n();return t&&Z(t,"success",3500),o}catch(o){Z(ve(o),"error",1e4);return}}function Wn(n){try{let t=n();t&&typeof t.then=="function"&&t.catch(o=>Z(ve(o),"error"))}catch(t){Z(ve(t),"error")}}function D(n,t,o="neutral",a={}){let{disabled:r,...i}=a,s=e("button",{class:`cbi-button cbi-button-${o}`,type:"button",...i,click:async l=>{if(l.preventDefault(),l.stopPropagation(),!s.disabled){s.disabled=!0,s.classList.add("spinning");try{await t(l)}catch(d){Z(ve(d),"error")}finally{s.disabled=!1,s.classList.remove("spinning")}}}},n);return s.disabled=!!r,s}function ye(n,t,o,a="neutral",r=""){return D([g(n),e("span",{class:"dl-btn-label"},t)],o,a,{title:t,class:`cbi-button cbi-button-${a} dl-icon-btn ${r}`.trim()})}function Ge(n){return document.addEventListener("luci-navigate",n),()=>document.removeEventListener("luci-navigate",n)}var it=null;function vn(n=!1){let t=it;it=null,t?.(n)}function oe(n,t,o,a=""){vn(),ui.showModal(n,[e("div",{class:`dl-modal ${a}`},t),e("div",{class:"button-row"},o)])}function se(){vn(),ui.hideModal()}function ie(n="Cancel",t=!1){return e("button",{class:`cbi-button ${t?"cbi-button-negative":"cbi-button-neutral"}`,type:"button",click:se},n)}function ne(n,t,o="Confirm",a=!1){return new Promise(r=>{oe(n,t,[ie()," ",e("button",{class:`cbi-button ${a?"cbi-button-negative":"cbi-button-positive"}`,type:"button",click:()=>{let i=it;it=null,ui.hideModal(),i?.(!0)}},o)]),it=r})}Ge(()=>{it&&(vn(),ui.hideModal())});async function pe(n,t="Copied to clipboard"){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(n);else{let o=e("textarea",{style:"position:fixed;opacity:0"},n);document.body.appendChild(o),o.select();let a=document.execCommand("copy");if(o.remove(),!a)throw new Error("Copying is blocked here. Select the text and copy it by hand.")}Z(t,"success",2500)}catch(o){Z(ve(o),"error")}}function $e(n,t,o="text/plain"){let a=globalThis,r=typeof t=="string"?new a.Blob([t],{type:o}):t,i=URL.createObjectURL(r),s=e("a",{href:i,download:n,style:"display:none"});document.body.appendChild(s),s.click(),setTimeout(()=>{URL.revokeObjectURL(i),s.remove()},1e3)}function bn(n,t){return new Promise(o=>{let a=e("input",{type:"file",accept:n,style:"display:none"});a.addEventListener("cancel",()=>{a.remove(),o(null)}),a.addEventListener("change",()=>{let r=a.files?.[0];if(a.remove(),!r)return o(null);let i=new FileReader;i.onload=()=>{let s=String(i.result??"");o({name:r.name,data:t==="base64"?s.replace(/^data:[^,]*,/,""):s})},i.onerror=()=>o(null),t==="base64"?i.readAsDataURL(r):i.readAsText(r)}),document.body.appendChild(a),a.click()})}function we(n,t){let o=document.querySelector(".dl-dd");if(o&&(o.dlClose?o.dlClose():o.remove(),o.dlAnchor===n))return;let a=e("div",{class:"dl-dd dl-root",role:"menu"},t.map(m=>m?e("button",{type:"button",role:"menuitem",class:m.danger?"danger":m.warn?"warn":"",click:()=>{c(),Wn(m.run)}},[m.icon??"",e("span",{},m.label)]):e("hr")));document.body.appendChild(a);let r=n.getBoundingClientRect(),i=a.offsetWidth,s=a.offsetHeight;a.style.top=`${r.bottom+6+s>window.innerHeight-8&&r.top-6-s>8?r.top-6-s:r.bottom+6}px`,a.style.left=`${Math.max(8,Math.min(r.right-i,window.innerWidth-i-8))}px`;let l=m=>{!a.contains(m.target)&&!n.contains(m.target)&&c()},d=m=>{m.key==="Escape"&&c()},p=Ge(c);a.dlAnchor=n,a.dlClose=c;function c(){a.remove(),p(),document.removeEventListener("mousedown",l,!0),document.removeEventListener("keydown",d,!0),window.removeEventListener("scroll",c,!0)}setTimeout(()=>{document.addEventListener("mousedown",l,!0),document.addEventListener("keydown",d,!0),window.addEventListener("scroll",c,!0)}),a.querySelector("button")?.focus({preventScroll:!0})}var Ze=null,xn=null,wn=0;function yn(){Ze&&(Ze.style.display="none"),xn=null,clearInterval(wn),wn=0}function ue(n,t){let o=a=>{Ze??(Ze=document.body.appendChild(e("div",{class:"dl-tip dl-tip-float dl-root"}))),Ze.replaceChildren(...t().map(r=>typeof r=="string"?document.createTextNode(r):r)),Ze.style.display="",Ze.style.left=`${a.clientX}px`,Ze.style.top=`${a.clientY-10}px`,xn=n,wn||(wn=window.setInterval(()=>{xn?.isConnected||yn()},400))};n.addEventListener("mouseenter",o),n.addEventListener("mousemove",o),n.addEventListener("mouseleave",yn)}Ge(yn);function te(n){if(!n||n<0)return"0 B";let t=["B","KB","MB","GB","TB"],o=0,a=n;for(;a>=1024&&o=100||o===0?Math.round(a):a.toFixed(1)} ${t[o]}`}function Pe(n){let t=n*8;return t<1e3?`${Math.round(t)} bit/s`:t<1e6?`${(t/1e3).toFixed(t<1e4?1:0)} kbit/s`:t<1e9?`${(t/1e6).toFixed(t<1e7?1:0)} Mbit/s`:`${(t/1e9).toFixed(1)} Gbit/s`}function le(n,t=Date.now()/1e3){if(!n)return"never";let o=Math.max(0,Math.round(t-n));return o<60?"just now":o<3600?`${Math.floor(o/60)} min ago`:o<86400?`${Math.floor(o/3600)} h ago`:o<86400*30?`${Math.floor(o/86400)} d ago`:new Date(n*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function st(n){if(!n||n<0)return"—";let t=Math.floor(n/86400),o=Math.floor(n%86400/3600),a=Math.floor(n%3600/60);return t?`${t}d ${o}h`:o?`${o}h ${a}m`:`${a}m`}function wt(n){let t=new Date(n*1e3),o=new Date,a=t.toDateString()===o.toDateString(),r=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});return a?r:`${t.toLocaleDateString("en-GB",{day:"numeric",month:"short"})} ${r}`}function De(n){return`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`}function lt(n){let[t,o,a]=n.split("-").map(Number);return new Date(t,(o||1)-1,a||1,12)}function Ae(n){return(typeof n=="string"?/^\d{4}-\d{2}-\d{2}$/.test(n)?lt(n):new Date(n):n).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function ze(n){return n?Ae(n):""}function kn(n,t){let o=a=>{let[r,i,s]=a.split("-").map(Number);return Date.UTC(r,i-1,s)};return Math.round((o(n)-o(t))/864e5)}function bt(n,t){let o=lt(n);return o.setDate(o.getDate()+t),De(o)}function xt(n,t){let[o,a,r]=n.split("-").map(Number),i=new Date(o,a-1+t,1,12),s=new Date(i.getFullYear(),i.getMonth()+1,0).getDate();return i.setDate(Math.min(r,s)),De(i)}function Ne(n){return n?.length?n[n.length-1].day:De(new Date)}function Gn(n,t,o,a,r=30){let i=n||a;return t==="day"?bt(i,o):t==="week"?bt(i,7*o):t==="month"?xt(i,o):t==="year"?xt(i,12*o):bt(i,r*o)}function Xe(n,t=Date.now()){if(!n)return null;let o=typeof t=="number"?De(new Date(t)):t,a=kn(n,o);return a>=0?a+1:a}function Rt(n,t,o=`${t}s`){return`${n.toLocaleString("en-GB")} ${n===1?t:o}`}function yt(n){return n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(n<10240?1:0)} KB`:`${(n/1048576).toFixed(1)} MB`}var et={lan:"Home network",internet:"Internet",both:"Home network + Internet"};var qn=["computer","phone","tablet","router","other"],Be={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},$n={active:"Active",paused:"Paused",paused_all:"Paused (everyone)",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server"};function Oe(n){let t=n.trim().split(/\s+/).filter(Boolean);if(!t.length)return"?";let o=t[0][0]??"",a=t.length>1?t[t.length-1][0]??"":t[0][1]??"";return(o+a).toUpperCase()}function Ht(n){let t=o=>o.disabled?3:o.online?0:o.handshake?1:2;return n.map((o,a)=>[o,a]).sort((o,a)=>t(o[0])-t(a[0])||o[1]-a[1]).map(([o])=>o)}function ke(n,t,o){return e("span",{class:`dl-pill ${n}`,title:o??null},t)}var Va={active:"",paused:"pause",paused_all:"pause",expired:"calendar",quota:"chart",hours:"clock",no_server:"alert"};function Ya(n){return n.state==="active"?"ok":n.state==="quota"||n.state==="expired"?"bad":"warn"}function It(n){if(n.state==="active")return"";let t=e("span",{class:`dl-ibadge ${Ya(n)}`,"aria-label":$n[n.state]},g(Va[n.state]||"alert"));return ue(t,()=>[e("div",{class:"dl-tip-title"},$n[n.state])]),t}function Fn(n){let t=n.access==="both"?["lan","inet"]:n.access==="lan"?["lan"]:["inet"],o=e("span",{class:"dl-access","aria-label":et[n.access]},t.map(a=>e("span",{class:`dl-ibadge ${a}`},g(a==="lan"?"home":"globe"))));return ue(o,()=>[e("div",{class:"dl-tip-title"},et[n.access]),n.access==="lan"&&n.services?.length?e("div",{class:"dl-muted"},`${n.services.length} home service${n.services.length===1?"":"s"} only`):""]),o}function Bt(n,t,o="Not set up yet"){return n.disabled?e("span",{class:"dl-dstat"},"Disabled"):n.online?e("span",{class:"dl-dstat ok"},"Connected"):n.handshake?e("span",{class:"dl-dstat"},`Last seen ${le(n.handshake,t)}`):e("span",{class:"dl-dstat warn",title:"Waiting for the first connection"},o)}var Ot=null;function Kn(n,t,o,a){Ot?.close();let r=e("aside",{class:"dl-drawer",role:"dialog","aria-modal":"true"},[e("div",{class:"dl-drawer-head"},[n,e("button",{type:"button",class:"dl-drawer-x","aria-label":"Close",click:()=>p()},g("x"))]),e("div",{class:"dl-drawer-body"},t),o?e("div",{class:"dl-drawer-foot"},o):""]),i=e("div",{class:"dl-drawer-overlay dl-root",click:m=>{m.target===i&&p()}},r),s=m=>{m.key==="Escape"&&!document.body.classList.contains("modal-overlay-active")&&p()},l=!1,d=Ge(()=>p());function p(){l||(l=!0,d(),document.removeEventListener("keydown",s),i.classList.remove("open"),setTimeout(()=>i.remove(),220),Ot===c&&(Ot=null),a())}let c={close:p,panel:r};return document.addEventListener("keydown",s),document.body.appendChild(i),requestAnimationFrame(()=>i.classList.add("open")),Ot=c,c}function X(n,t,o){return e("div",{class:"dl-setrow"},[e("div",{class:"dl-stack"},[e("span",{class:"dl-setrow-label"},n),o?e("span",{class:"dl-sub"},o):""]),e("div",{class:"dl-setrow-ctl"},t)])}function kt(n,t,o,a=""){return e("section",{class:`dl-setsec ${a}`},[e("div",{class:"dl-setsec-body"},[n?e("h3",{},n):"",...t]),o.length?e("div",{class:"dl-setsec-foot"},o):""])}function he(n,t,o,a){return e("div",{class:"dl-group"},[e("div",{class:"dl-group-head"},[e("span",{class:"dl-group-ic"},g(n)),e("span",{class:"dl-stack"},[e("b",{},t),o?e("span",{class:"dl-sub"},o):""])]),e("div",{class:"dl-group-body"},a.filter(r=>r!==""))])}function tt(n,t,o,a,r){return e("div",{class:`dl-row dl-need-row ${t}`},[t?e("span",{class:"dl-need-ic"},g(n)):g(n),e("span",{class:"dl-row-main dl-stack"},[e("b",{},o),e("span",{class:"dl-sub"},a)]),r])}function dt(n,t){let o={ok:"success",warn:"warning",error:"error",info:"notice"}[n];return e("div",{class:`alert-message ${o}`},t)}function qe(n,t=""){let o=e("div",{class:t});return o.innerHTML=n,o}var Zn=Wa(Qn(),1),Qa='';function ct(n,t=3,o=!0){let a=(0,Zn.default)(0,n.length>300?"Q":"H");a.addData(n,"Byte"),a.make();let r=a.getModuleCount(),i=r+t*2,s=o?Math.round(r*.22):0;s&&(r-s)%2&&s++;let l=(r-s)/2,d=l+s,p=(v,h)=>s>0&&v>=l&&v=l&&h${Qa}`}return`${m}`}var Za={connect:"connections",disconnect:"connections",roam:"connections",device_added:"people",device_removed:"people",devices_removed:"people",device_changed:"people",device_keys:"people",link_changed:"people",person_added:"people",person_removed:"people",person_changed:"people",paused:"people",resumed:"people",paused_all:"people",resumed_all:"people",portal_blocked:"problems"},pt=["connections","people","problems"],nt={connections:"Connections",people:"People",problems:"Problems"},Xn={connections:"Connects, disconnects and IP changes",people:"People and their devices added, changed, paused, removed",problems:"Blocked portal sign-ins (tunnels and services are in the service log)"},$t=n=>Za[n]??"problems",_t={awg:"AmneziaWG",dawnline:"Dawnline",portal:"Portal"},Xa=["person_added","person_removed","person_changed","paused_all","resumed_all"];function Le(n){return n.by?n.by:Xa.includes(n.type)||n.detail==="by admin"||n.detail?.endsWith(" (admin)")?"admin":n.detail?.endsWith(" (portal)")?"portal":null}function eo(n){return(n.detail??"").replace(/ \((admin|portal)\)$/,"").replace(/^by admin$/,"")}var jt=n=>n.sys?["error","repair","down"].includes(n.sys.level):$t(n.ev.type)==="problems";function Ut(n){let t=n.keep_days>0?`${n.keep_days} day${n.keep_days===1?"":"s"}`:"no age limit",o=n.persist==="off"?"kept in memory only (lost on reboot)":`saved to flash ${n.persist==="10min"?"every 10 minutes":"hourly"}`;return`Kept for ${t}, up to ${n.max.toLocaleString("en-GB")} events, ${o}.`}function to(n,t=120,o=26,a=De(new Date)){let r=Math.max(1,...n),i=e("div",{class:"dl-spark"});return i.style.width=`${t}px`,i.style.height=`${o}px`,n.forEach((s,l)=>{let d=e("i");d.style.height=`${Math.max(6,s/r*100)}%`,s||d.classList.add("zero");let p=n.length-1-l;ue(d,()=>[e("div",{class:"dl-tip-title"},p===0?"Today":p===1?"Yesterday":lt(bt(a,-p)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})),e("div",{class:"dl-muted"},te(s))]),i.appendChild(d)}),i}function er(n){let t=n==null?"":String(n);return/^[=+\-@\t\r]/.test(t)&&(t=`'${t}`),/[",\r\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function no(n,t){return[n.join(","),...t.map(o=>n.map(a=>er(o[a])).join(","))].join(` +`)}function tr(n){let t=new Map(n.people.map(a=>[a.id,a.name])),o=new Map(n.people.flatMap(a=>a.devices.map(r=>[r.id,r.name])));return{people:t,devices:o}}function je(n,t,o,a="",r=[]){let i=tr(n),s=[...t.map(c=>({ts:c.ts,category:$t(c.type),type:c.type,person:c.person?i.people.get(c.person)??c.pname??c.person:"",device:c.device?i.devices.get(c.device)??c.dname??c.device:"",detail:c.detail??"",where:c.where??"",by:Le(c)??""})),...r.map(c=>({ts:c.ts,category:"system",type:`${c.src}.${c.level}`,person:"",device:"",detail:`${c.who?`${c.who} `:""}${c.msg}${c.detail?` +${c.detail}`:""}`,where:_t[c.src]??c.src,by:""}))].sort((c,m)=>c.ts-m.ts).map(({ts:c,...m})=>({time:new Date(c*1e3).toISOString(),...m})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${a?`-${a}`:""}-${l}.${o}`;if(o==="json"){$e(d,JSON.stringify(s,null,2),"application/json");return}$e(d,no(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var nr=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],oo=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function Fe(n,t,o,a,r,i=!1){let s=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...pt.map(d=>e("option",{value:d,selected:d===r?"selected":null},nt[d])),i?e("option",{value:"system",selected:r==="system"?"selected":null},"System"):""]),l=e("select",{class:"cbi-input-select"},nr.map(([d,p])=>e("option",{value:d},p)));oe(n,[e("p",{class:"dl-muted"},`${t} This cannot be undone; export first if you want a copy.`),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Category"),s]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Which events"),l])],[ie()," ",D("Clear",async()=>{let d=0;if(s.value!=="system")try{d+=(await E.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(p){Z(ve(p),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{d+=(await E.serviceLogClear(l.value)).removed}catch(p){se(),Z(`${s.value==="system"?"":`Activity: ${oo(d).toLowerCase()}. `}The service log was not cleared: ${ve(p)}`,"error",1e4),a();return}se(),Z(oo(d),"success",3e3),a()},"negative")])}function ut(n,t,o,a){let r=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";oe(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[e("p",{class:"dl-muted"},r)],[ie()," ",D("Reset",async()=>{await U(()=>E.usageClear(n,t),"Traffic history reset")&&(se(),a())},"negative")])}function fe(n,t,o){let a=e("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":t,click:()=>{let r=!a.classList.contains("on");_n(a,r),o?.(r)}},e("i"));return a}function _n(n,t){n.classList.toggle("on",t),n.setAttribute("aria-checked",t?"true":"false")}var Ee=n=>n.classList.contains("on");function xe(n,t,o={}){n.some(([i])=>i===t)||(n=[...n,[t,t]]);let a=e("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":t}),r=()=>a.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===a.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)a.appendChild(e("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==a.dataset.value&&(o.optimistic!==!1&&(a.dataset.value=i,r()),o.onChange?.(i))}},s));return r(),a}function Ue(n,t,o,a={}){return e("button",{type:"button",...a,class:`dl-chipbtn${t?" on":""}${a.class?` ${a.class}`:""}`,"aria-pressed":t?"true":"false",click:o},n)}function Wt(n,t){n.classList.toggle("on",t),n.setAttribute("aria-pressed",t?"true":"false")}function ae(n,t={}){return e("input",{type:"text",class:"cbi-input-text",value:n,...t})}var or={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},ar={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function rr(n){let t={};for(let[o,a]of Object.entries(ar))n[o]!=null&&n[o]!==""&&(t[a]=String(n[o]));return t}function ir(n,t){let o=n.amnezia,a=o.obfuscation??{},r=d=>a[d]!=null&&a[d]!==""?String(a[d]):or[d],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...rr(a),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r +`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function sr(n){let t="";for(let o=0;o"u")return null;try{let o=new t.Blob([n]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(o).arrayBuffer()),r=new Uint8Array(4+a.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(a,4),r}catch{return null}}async function En(n,t,o=!0){let a=new TextEncoder().encode(JSON.stringify(ir(n,t))),r=o?await lr(a):null;return`vpn://${sr(r??a)}`}var ro=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"standard",title:"Standard",ic:"shield",stealth:2,speed:4,text:"Junk packets and random headers. Gets through most VPN blocking with no speed cost.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"strong",title:"Strong",ic:"shieldplus",stealth:3,speed:3,text:"More and larger junk packets for networks that block VPNs aggressively. Connects a little slower.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],Et=n=>ro.find(t=>t.id===n),dr={v2:"Needs AmneziaWG 1.5 or newer on the router.",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},cr={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function ao(n,t){return e("span",{class:"dl-dots",title:`${t}: ${n} of 4`},[e("span",{class:"dl-dots-label"},t),e("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>e("i",{class:odom.content(i,ro.map(l=>{let d=!l.needs||n[l.needs],p=l.id===t;return e("button",{type:"button",role:"radio","aria-checked":p?"true":"false","aria-disabled":d?null:"true",class:`dl-method${p?" on":""}${d?"":" off"}`,click:()=>{!d||p||(t=l.id,s(),o(l.id))}},[e("div",{class:"dl-method-head"},[e("span",{class:"dl-method-ic"},g(l.ic)),e("b",{},l.title),l.id===a?e("span",{class:"dl-pill ok"},"Current"):""]),e("p",{},l.text),e("div",{class:"dl-method-meters"},[ao(l.stealth,"Stealth"),ao(l.speed,"Speed")]),e("div",{class:"dl-method-foot"},d?[g("phone"),e("span",{},l.apps)]:[g("alert"),e("span",{},(r?dr:cr)[l.needs])])])}));return s(),i}function io(n,t,o,a){return e("div",{class:"dl-corehead"},[e("h3",{},n),e("span",{class:`dl-pill ${t}`},o),a?e("span",{class:"dl-sub"},a):""])}var so=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function pr(n){let t=p=>n[p]!=null&&n[p]!=="",o=so.filter(([p])=>t(p));if(!o.length)return null;let a=(p,c)=>e("span",{class:"dl-pv"},[e("i",{},c),e("b",{},p==="header_protection_key"?`${n[p].slice(0,6)}••••`:n[p])]),r=(p,c,m,v)=>{let h=so.filter(([x])=>v.includes(x)&&t(x));return h.length?e("div",{class:"dl-pgroup"},[e("div",{class:"dl-pgroup-head"},[g(c),e("b",{},p)]),e("p",{},m),e("div",{class:"dl-pvals"},h.map(([x,R])=>a(x,R)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([p,c])=>`${c} = ${n[p]}`).join(` +`),d=e("div",{class:"dl-pgrid"},[r("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),r("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),r("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),r("Signatures","globe",s,["i1","i2","i3","i4","i5"]),r("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),r("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Current parameters"),e("span",{class:"dl-pcount"},String(o.length)),e("span",{class:"dl-spacer"}),e("button",{type:"button",class:"dl-linkbtn",click:p=>{p.preventDefault(),pe(l,"Parameters copied")}},"Copy as config")]),d])}function lo(n,t){if(/^\s*\[.+\]\s*$/.test(n))return e("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return e("span",{},[e("span",{class:"dl-conf-k"},o[1])," ",a&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function ur(n){let t=!1,o=e("pre",{class:"dl-conf"}),a=()=>dom.content(o,n.conf.split(` +`).flatMap((s,l)=>l?[` +`,lo(s,t)]:[lo(s,t)])),r=e("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),t=!t,dom.content(r,[g(t?"x":"key"),t?"Hide key":"Show key"]),a()}},[g("key"),"Show key"]);a();let i=new Blob([n.conf]).size;return e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-filecard"},[e("span",{class:"dl-filecard-ic"},".conf"),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono dl-ellipsis"},n.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),D([g("download")," Download"],()=>$e(n.filename,n.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),r,e("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),pe(n.conf,"Configuration copied")}},[g("copy"),"Copy"])]),o])])}async function mr(n,t="file"){if(!n.has_private_key)return e("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await En(n,`${n.server} · ${n.person} · ${n.name}`),a={qr:()=>e("div",{class:"dl-qr-pane"},[qe(ct(n.conf),"dl-qr"),e("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-linkbox"},[e("span",{class:"dl-mono"},o),D("Copy",()=>pe(o,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>ur(n)},r=e("div",{class:"dl-connect-body"}),i=e("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,a[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(e("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(t),e("div",{class:"dl-stack gap12"},[i,r])}async function hr(n,t,o,a){let r=Et(o),s=n.st.people.filter(d=>d.server===t.id).reduce((d,p)=>d+p.devices.length,0);await ne(a?"Generate new disguise values?":`Switch to ${r.title}?`,`${s} AmneziaWG device${s===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":""}`,a?"Generate and apply":"Switch and apply",!0)&&await U(()=>E.serverObfuscation(t.id,o),a?"New values applied":`${r.title} applied`)&&(Z("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function fr(n,t){let o=n.st,a=ae(String(t.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=ae(String(t.mtu??""),{placeholder:"1380",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=ae(String(t.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=Et(t.preset)?t.preset:void 0,l=s??"standard",d=D("",()=>hr(n,t,l,l===s),"neutral"),p=()=>dom.content(d,l===s?[g("reset")," Generate new values"]:[`Switch to ${Et(l).title}`]);p();let c=o.people.filter(v=>v.server===t.id).reduce((v,h)=>v+h.devices.length,0),m=o.awg_state?.tools!==!1;return kt("",[io("AmneziaWG",t.up?"ok":"bad",t.up?"Running":"Not running",`${t.ifname} · ${c} device${c===1?"":"s"}`),he("globe","Listening","Where devices reach this core from the internet",[X("UDP port",a,"Opened on the WAN firewall automatically.")]),he("file","In every device configuration","Changing these marks devices “Update config” until they import again",[X("MTU",r,"Lower it if some sites hang on mobile networks."),X("Keep-alive",i,"Seconds between packets devices send to keep NAT open. 0 = off.")]),he("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Gt(o.awg,l,v=>{l=v,p()},s,m),m&&!o.awg.v3?dt("info",["This router runs an older AmneziaWG. ",e("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",pr(t.obf??{})??"",e("div",{class:"dl-row-end"},[e("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Tunnel"),e("span",{class:"dl-pcount"},"3")]),e("div",{class:"dl-params-body"},[X("Interface",e("span",{class:"dl-mono"},`${t.ifname} · router ${t.address}`)),X("Tunnel subnet",e("span",{class:"dl-mono"},t.subnet),"Device addresses come from it."),X("Server public key",e("span",{class:"dl-keyrow"},[e("code",{class:"dl-mono"},t.public_key),D([g("copy")],()=>pe(t.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[e("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),D("Save",()=>n.save({port:a.value,mtu:r.value,keepalive:i.value},"AmneziaWG saved"),"positive")])}function gr(n){let t=Et(n.preset),o=n.obf??{},a=(s,l)=>e("span",{class:`dl-segs ${l}`},[0,1,2,3].map(d=>e("i",{class:d+o[s]).map(s=>`${s.toUpperCase()} ${o[s]}`);return i.length&&r.push(i.slice(0,2).join(" · ")+(i.length>2?` +${i.length-2}`:"")),["h1","h2","h3","h4"].some(s=>o[s]&&o[s]!==String(["h1","h2","h3","h4"].indexOf(s)+1))&&r.push("H1–H4 random"),o.i1&&r.push(o.i1.includes("0x8580")?"DNS-like first packet":"Signature packets"),o.header_protection_key&&r.push("Encrypted headers"),r.length||r.push(t?.id==="off"?"Plain WireGuard":"No values yet"),e("div",{class:"dl-bento-tile dl-disg"},[e("div",{class:"dl-bento-head"},[e("span",{class:"dl-metric-label"},"Disguise"),e("a",{href:`${L.url("admin/network/dawnline/server")}?server=${encodeURIComponent(n.id)}§ion=awg`},"Change")]),e("div",{class:"dl-disg-id"},[e("span",{class:"dl-disg-ic"},g(t?.ic??"shield")),e("span",{class:"dl-stack"},[e("b",{},t?t.title:"Custom"),e("span",{class:"dl-sub"},t?t.short:"Set by hand")])]),t?e("div",{class:"dl-disg-meters"},[e("span",{},"Stealth"),a(t.stealth,"acc"),e("span",{},"Speed"),a(t.speed,"ok")]):"",e("div",{class:"dl-disg-chips"},r.map(s=>e("span",{},s)))])}var Sn={id:"awg",label:"AmneziaWG",settingsCard:fr,overviewTile:gr,connectBlock:mr,qrText:n=>n.conf,appKey:{label:"Copy AmneziaVPN key",make:n=>En(n,`${n.server} · ${n.person} · ${n.name}`)},file:{label:"Download .conf",make:n=>({name:n.filename,text:n.conf})}};var vr={awg:Sn};function Re(n){return vr[n?.core||"awg"]??Sn}function mt(n,t){return Re(n.find(o=>o.id===t))}function br(n){return n?new Date(n*1e3).toLocaleString("en-GB",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function co(n,t,o=!1){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},n),e("button",{type:"button",class:`dl-kvrow-v copy${o?" dl-mono":""}`,title:"Copy",click:()=>pe(t,`${n} copied`)},[e("span",{},t),g("copy")])])}function qt(n,t){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},n),e("span",{class:"dl-kvrow-v"},t)])}var po={connect:["ok","Connected","plug"],disconnect:["","Went offline","plug"],roam:["","Changed network","network"],device_added:["ok","Added","plus"],device_removed:["","Removed","trash"],device_keys:["","New keys","reset"]};function xr(n,t,o){let a=n.filter(r=>r.device===t&&po[r.type]).reverse().slice(0,12);return a.length?e("div",{class:"dl-dev-log"},a.map(r=>{let[i,s,l]=po[r.type],d=r.type==="connect"?[r.detail?e("span",{class:"dl-muted"},` from ${r.detail}`):"",r.where?e("span",{class:"dl-muted"},` · ${r.where}`):""]:r.type==="roam"?[e("span",{class:"dl-muted"},` · ${r.detail??""}`)]:r.type==="device_added"||r.type==="device_removed"||r.type==="device_keys"?[e("span",{class:"dl-muted"},Le(r)==="portal"?" on the portal":Le(r)==="admin"?" by you":"")]:[],p=new Date(r.ts*1e3);return e("div",{class:`dl-dev-log-row${Le(r)==="admin"?" dl-ev-by-admin":""}`},[Le(r)==="admin"?e("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},g("admin")):e("span",{class:`dl-ev-tile ev ${i}`},g(l)),e("span",{class:"dl-row-main"},[e("span",{},s),...d]),e("span",{class:"dl-faint dl-nowrap",title:p.toLocaleString()},le(r.ts,o))])})):e("div",{class:"dl-sub"},"No activity yet.")}async function uo(n,t,o){let a=await E.status(1).catch(()=>null),r=a?.people.find(s=>s.id===n),i=r?.devices.find(s=>s.id===t);a&&r&&i&&He(r,i,{...o,geo:a.geo,now:a.now,today:Ne(a.series),core:mt(a.servers,r.server)})}async function He(n,t,o){let a=await U(()=>E.deviceConfig(t.id));if(!a)return;let r=o.core??Re(null),i=t,s=n,l=o.geo,d=o.now,p=o.today??De(new Date),c=await r.connectBlock(a),m=e("div",{class:"dl-drawer-title"}),v=e("div",{}),h=e("div",{}),x=e("div",{},e("div",{class:"dl-sub"},"Loading…")),R=[],$=q=>{R=q.filter(C=>C.device===i.id),dom.content(x,xr(q,i.id,d))},j=async(q=!1)=>{let C=o.events?.();if(C&&!q)return $(C);let G=await E.events(5e3).catch(()=>null);G&&$(G.events)},w=()=>{let q=l?.points.find(G=>G.device===i.id&&G.ip===i.endpoint);dom.content(m,[e("span",{class:`dl-dcard-ic${i.online?" on":""}`},g(i.kind)),e("div",{class:"dl-stack"},[e("div",{class:"dl-title-row"},[e("h3",{},i.name),D([g("edit")],()=>T(),"neutral",{title:"Rename",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),e("span",{class:"dl-sub"},`${s.name} · ${Be[i.kind]}`)])]);let C=i.spark.reduce((G,Q)=>G+Q,0);dom.content(v,e("div",{class:"dl-dstats"},[e("div",{class:"dl-dstats-cell wide"},[e("span",{class:"dl-metric-label"},"Status"),Bt(i,d,"Waiting for the first connection")]),e("div",{class:"dl-dstats-cell"},[e("span",{class:"dl-metric-label"},"This month"),e("b",{},te(i.month[0]+i.month[1])),e("span",{class:"dl-sub dl-mono"},`↓ ${te(i.month[1])} ↑ ${te(i.month[0])}`)]),e("div",{class:"dl-dstats-cell"},[e("span",{class:"dl-metric-label"},"Last 7 days"),e("b",{},te(C)),to(i.spark,120,22,p)])])),dom.content(h,e("div",{class:"dl-kv2"},[co("Tunnel address",i.address),i.hostname&&s.access!=="internet"?co("Local address",i.hostname):"",i.endpoint?qt("Client IP",e("span",{},[i.endpoint,q?e("span",{class:"dl-muted"},` · ${[q.city,q.org].filter(Boolean).join(" · ")}`):""])):"",qt("Total",e("span",{class:"dl-kv-act"},[`↓ ${te(i.total[1])} · ↑ ${te(i.total[0])}`,e("button",{type:"button",class:"dl-linkbtn danger",click:()=>ut("device",i.id,i.name,()=>setTimeout(S,300))},"Reset")])),qt("Added",`${br(i.created)} · ${i.created_by==="portal"?"from the portal":"by you"}`),qt("Public key",e("span",{class:"dl-mono dl-faint"},a.amnezia.client_pub_key?`${a.amnezia.client_pub_key.slice(0,16)}…`:"—"))])),dom.content(b,[D([g(i.disabled?"play":"pause"),i.disabled?" Enable":" Disable"],async()=>{await U(()=>E.deviceUpdate(i.id,void 0,!i.disabled),i.disabled?"Device enabled":"Device disabled")&&await S()},"neutral",i.disabled?{}:{class:"cbi-button cbi-button-neutral dl-btn-warn"}),D([g("key")," New keys"],async()=>{if(!await ne("Generate new keys?","The current configuration on this device stops working until it is imported again.","Generate",!0))return;await U(()=>E.deviceRotate(i.id),"New keys generated")&&(o.refresh(),W.close(),await uo(s.id,i.id,o))}),e("span",{class:"dl-spacer"}),D([g("trash")," Remove"],async()=>{await ne(`Remove ${i.name}?`,"The device is disconnected immediately and its configuration stops working.","Remove",!0)&&await U(()=>E.deviceDelete(i.id),"Device removed")&&(W.close(),o.refresh())},"negative")])},H=async()=>{let q=await E.status(1).catch(()=>null),C=q?.people.find(Q=>Q.id===s.id),G=C?.devices.find(Q=>Q.id===i.id);!q||!C||!G||(s=C,i=G,l=q.geo,d=q.now,p=Ne(q.series),w())},S=async()=>{await H(),o.refresh()},T=()=>{let q=e("input",{type:"text",class:"cbi-input-text",value:i.name,maxlength:48});oe(`Rename ${i.name}`,[e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},"Name"),e("div",{class:"cbi-value-field"},q)])],[ie()," ",D("Save",async()=>{await U(()=>E.deviceUpdate(i.id,q.value,void 0),"Renamed")&&(se(),await S())},"positive")]),setTimeout(()=>q.select(),50)},b=e("div",{class:"dl-drawer-actions"}),A=e("section",{class:"dl-dsec"},[e("div",{class:"dl-dsec-head"},[e("h4",{},"Connect")]),i.config_stale?e("div",{class:"dl-note warn"},[g("alert"),e("span",{},"This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below.")]):"",c]),u=e("section",{class:"dl-dsec"},[e("div",{class:"dl-dsec-head"},[e("h4",{},"Activity"),e("div",{class:"dl-dsec-actions"},[e("button",{type:"button",class:"dl-linkbtn",click:()=>je({people:[s]},R,"csv",i.id)},"Export"),e("button",{type:"button",class:"dl-linkbtn danger",click:()=>Fe(`Clear ${i.name}'s activity`,`Removes events about ${i.name}.`,{device:i.id},()=>{j(!0),o.refresh()})},"Clear"),e("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},"All activity")])]),x]),f=e("section",{class:"dl-dsec"},[e("div",{class:"dl-dsec-head"},e("h4",{},"Details")),h]),N=!i.handshake||i.config_stale,P=e("div",{class:"dl-stack gap16"},N?[v,A,f,u]:[v,f,u,A]);j();let I=0,J=window.setInterval(()=>{H(),(o.events||++I%4===0)&&j()},8e3),W=Kn(m,P,b,()=>clearInterval(J));w()}function mo(n,t,o,a){let r=a.core??Re(null),i=()=>U(()=>E.deviceConfig(o.id)),s=[{label:"Show QR code",icon:g("qr"),run:async()=>{let l=await i();l&&oe(`${o.name} · QR code`,e("div",{class:"dl-qr-pane"},[qe(ct(r.qrText(l)),"dl-qr"),e("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),ie("Close"))}},{label:r.file.label,icon:g("download"),run:async()=>{let l=await i();if(!l)return;let d=r.file.make(l);$e(d.name,d.text,"application/octet-stream")}},r.appKey?{label:r.appKey.label,icon:g("copy"),run:async()=>{let l=await i();l&&pe(await r.appKey.make(l),"Key copied")}}:null,null,{label:"Rename",icon:g("edit"),run:()=>He(t,o,a)},{label:"New keys",icon:g("key"),run:async()=>{await ne("Generate new keys?","The current configuration on this device stops working until it is imported again.","Generate",!0)&&await U(()=>E.deviceRotate(o.id),"New keys generated")&&a.refresh()}},{label:o.disabled?"Enable":"Disable",icon:g(o.disabled?"play":"pause"),warn:!o.disabled,run:async()=>{await U(()=>E.deviceUpdate(o.id,void 0,!o.disabled),o.disabled?"Device enabled":"Device disabled")&&a.refresh()}},{label:"Delete",icon:g("trash"),danger:!0,run:async()=>{await ne(`Remove ${o.name}?`,"The device is disconnected immediately and its configuration stops working.","Remove",!0)&&await U(()=>E.deviceDelete(o.id),"Device removed")&&a.refresh()}}];we(n,s)}function ot(n,t){let o=e("input",{type:"text",class:"cbi-input-text",placeholder:Be.phone,maxlength:48}),a="phone",r=e("div",{class:"dl-kinds",role:"radiogroup","aria-label":"Type"},qn.map(s=>e("button",{type:"button",role:"radio",class:s===a?"on":"","aria-checked":s===a?"true":"false","data-kind":s,click:()=>{a=s,r.querySelectorAll("button").forEach(l=>{let d=l.dataset.kind===s;l.classList.toggle("on",d),l.setAttribute("aria-checked",d?"true":"false")}),o.placeholder=Be[s]}},[g(s),e("span",{},Be[s])]))),i=n.devices.length>=n.device_limit;oe(`Add a device for ${n.name}`,[i?e("p",{class:"dl-hint"},`${n.name} already has ${n.devices.length} of ${n.device_limit} devices. As admin you can still add one.`):"",e("div",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Type"),r]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Name"),o])],[ie()," ",D("Add device",async()=>{let s=o.value.trim()||o.placeholder.replace(/^e\.g\. /,""),l=await U(()=>E.deviceCreate(n.id,s,a));l&&(se(),Z(`${s} added`,"success",3e3),t.refresh(),await uo(n.id,l.id,t))},"positive")]),setTimeout(()=>o.focus(),50)}var We=1080,Ct=1512,Ie=96,wr="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",yr="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",St=n=>n.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]);function kr(n,t,o){let a=new URL(o),r=a.pathname.slice(1),i=Math.min(92,Math.floor((We-2*Ie)/(.58*(4+n.name.length)))),s=We-2*Ie,l=392,d=40,p=ct(o,2).replace("`${R}`;return``+c(Ie+82,Ie+42,36,"#a3a3a3",St(t))+c(Ie,276,i,"#ffffff",`Hi, ${St(n.name)}`,'font-weight="600"')+c(Ie,340,40,"#8a8a8a",`Scan to connect to ${St(t)}`)+``+p+`${St(r)}`+c(We/2,l+s+156,34,"#737373",St(a.host),'text-anchor="middle"')+""}async function $r(n){let t=new Image;t.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(n)}`,await t.decode();let o=document.createElement("canvas");return o.width=We,o.height=Ct,o.getContext("2d").drawImage(t,0,0,We,Ct),new Promise((a,r)=>o.toBlob(i=>i?a(i):r(new Error("Could not draw the card")),"image/png"))}async function ho(n){let t=await U(()=>E.personLinks(n));return t?t.link?{link:t.link,links:t.links??[]}:(Z("The personal portal is off. Turn it on in Settings.","warning"),null):null}async function Ft(n){let t=await ho(n);t&&await pe(t.link,"Personal link copied")}async function Lt(n,t,o={}){let a=n.link,r=n.links;if(a===void 0){let h=await ho(n.id);if(!h)return;a=h.link,r=h.links}if(!a){Z("The personal portal is off. Turn it on in Settings.","warning");return}let i=a,s=await U(()=>$r(kr(n,t,i)));if(!s)return;let l=new File([s],`${n.id}-invite.png`,{type:"image/png"}),d=URL.createObjectURL(s),p=navigator,c=!!p.canShare?.({files:[l]}),m=()=>{URL.revokeObjectURL(d),se()},v=c?D([g("link")," Share card"],async()=>{try{await p.share({files:[l],title:`Invite ${n.name}`})}catch{}},"positive"):D([g("download")," Download card"],()=>$e(l.name,s),"positive");oe(o.title??`Invite ${n.name}`,e("div",{class:"dl-invite"},[e("img",{src:d,alt:`Invite card for ${n.name}`}),e("div",{class:"dl-invite-side"},[e("p",{class:"dl-muted"},o.lead??`Send ${n.name} the card or the link. They open it, add their devices and connect — no account needed.`),e("button",{type:"button",class:"dl-invite-link",title:"Copy link",click:()=>pe(i,"Personal link copied")},[e("span",{},i.replace(/^https:\/\//,"")),g("copy")]),...(r??[]).filter(h=>h!==i).map(h=>e("button",{type:"button",class:"dl-invite-link alt",title:"Copy this link",click:()=>pe(h,"Link copied")},[e("span",{},h.replace(/^https?:\/\//,"")),e("span",{class:`dl-pill ${h.startsWith("http:")?"warn":""}`},h.startsWith("http:")?"HTTP":"Also"),g("copy")])),e("ol",{class:"dl-invite-steps"},[e("li",{},["Install ",e("b",{},"AmneziaVPN")," on the device"]),e("li",{},"Open the link or scan the code"),e("li",{},"Add the device and connect")]),e("div",{class:"dl-invite-actions"},[v,D([g("copy")," Copy link"],()=>pe(i,"Personal link copied"))])])]),[e("button",{class:"cbi-button cbi-button-neutral",click:m},"Done")],"wide")}function ht(n){return`${L.url("admin/network/dawnline/server")}?${n?`server=${encodeURIComponent(n)}&`:""}section=people`}function Te(n,t){return`${L.url("admin/network/dawnline/person")}?id=${encodeURIComponent(n)}${t?`&device=${encodeURIComponent(t)}`:""}`}function Tt(n,t){let o=n.servers.find(d=>d.id===t)??n.servers[0],a=n.people.filter(d=>d.server===o.id),r=new Set(a.map(d=>d.id)),i=a.flatMap(d=>d.devices),s=d=>a.reduce((p,c)=>{let m=d(c);return[p[0]+m[0],p[1]+m[1]]},[0,0]),l=o.series?.[o.series.length-1];return{...n,servers:[o],people:a,series:o.series??n.series,events:n.events.filter(d=>d.person?r.has(d.person):!0),geo:{...n.geo,points:n.geo.points.filter(d=>r.has(d.person))},totals:{people:a.length,devices:i.length,online:i.filter(d=>d.online).length,active:a.filter(d=>d.state==="active").length,today:l?[l.rx,l.tx]:[0,0],month:s(d=>d.month)}}}var Cn=class{constructor(){this.n=0;this.shown=0}next(){return++this.n}take(t){return t{let i=t.next(),s=await n.fetch().catch(()=>null);return s==null||!t.take(i)?null:(n.apply(s,r),s)},a=()=>n.active?.()??!0?o(!0):Promise.resolve(null);return poll.add(a,n.every),{refresh:o,claim:()=>t.claim(),stop:()=>poll.remove(a)}}function ft(n){let t=document.activeElement;return!!n&&!!t&&t!==document.body&&n.contains(t)}function _e(n,t,o=!1){return o&&ft(n)?!1:(dom.content(n,t),!0)}function fo(n,t){let o=n,r=e("div",{class:"dl-choices"},[{v:"internet",ic:"globe",text:"Browse the internet through your router. No access to devices at home."},{v:"lan",ic:"home",text:"Reach devices at home (NAS, printer, cameras). Internet stays on their own connection."},{v:"both",ic:"shield",text:"Home devices and the internet, all through your router."}].map(i=>e("button",{type:"button",class:`dl-choice${i.v===o?" selected":""}`,"data-v":i.v,click:()=>{o=i.v,r.querySelectorAll(".dl-choice").forEach(s=>s.classList.toggle("selected",s.dataset.v===i.v)),t?.(i.v)}},[e("span",{class:"dl-choice-title"},[g(i.ic),et[i.v]]),e("span",{class:"dl-choice-text"},i.text)])));return{el:r,get:()=>o}}function _r(n){let t=n.devices.length,o=Math.max(1,n.device_limit,t),a=Math.min(160,o*22+(o-1)*3);return e("div",{class:"dl-slotbar",title:`${t} of ${n.device_limit} devices`},[e("span",{class:"dl-slotbar-segs",style:`width: ${a}px`},Array.from({length:o},(r,i)=>e("i",{class:i>=n.device_limit?"over":i=n.quota_limit*.9}function Sr(n,t){return xt(n&&kn(n,t)>=0?n:t,1)}var go=n=>n.people.map(t=>t.id).sort().join(" "),vo=!1,at=class{constructor(){this.list=e("div",{class:"dl-plist",role:"list"});this.filter=["all","online","attention","paused"].find(t=>t===new URLSearchParams(location.search).get("filter"))??"all";this.sort="seen";this.noFooter=!0;this.serverId=null;this.el=null}async load(){return E.status(30)}scope(t){return this.serverId?Tt(t,this.serverId):t}embed(t,o){return this.serverId=o,this.render(t)}person(t){return this.st.people.find(o=>o.id===t)}get today(){return Ne(this.st.series)}deviceOpts(t){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:mt(this.st.servers,t.server)}}take(t,o){let a=this.scope(t),r=go(a)!==go(this.st);this.st=a,r?this.rebuild():(this.paintCards(o),this.decorate(o))}async update(){await this.poller?.refresh()}async refresh(){this.poller?.claim();let t=await E.status(30).catch(()=>null);t&&(this.st=this.scope(t),this.rebuild())}rebuild(){let t=new Map;for(let a of Array.from(this.list.children))a.dataset.sid&&t.set(a.dataset.sid,a);let o=this.st.people.map(a=>{let r=t.get(a.id)??e("div",{class:"dl-card",role:"listitem","data-sid":a.id});return this.renderCard(r,a.id)});dom.content(this.list,o.length?o:e("div",{class:"dl-plist-none"},this.st.servers.length?"No people yet. Add someone and send them their personal link.":"Set up the server first, then add people.")),this.decorate()}paintCards(t=!1){for(let o of this.st.people){let a=this.card(o.id);a&&!(t&&ft(a))&&this.renderCard(a,o.id)}}card(t){return this.list.querySelector(`[data-sid="${CSS.escape(t)}"]`)}render(t){let o=this.scope(t);this.st=o;let a=this,r=e("select",{class:"dl-select","aria-label":"Sort",change:s=>{a.sort=s.target.value,a.decorate()}},[e("option",{value:"seen"},"Last seen"),e("option",{value:"name"},"Name"),e("option",{value:"usage"},"Usage")]),i=e("div",{class:"dl-root"},[a.serverId?"":e("div",{class:"dl-pagehead"},[e("div",{class:"dl-stack"},[e("h2",{class:"dl-h1"},"People"),e("span",{class:"dl-muted dl-people-count"},this.countText())]),o.servers.length?D([g("plus")," Add person"],()=>a.openCreate(),"add"):""]),o.servers.length?"":e("div",{class:"alert-message warning"},["No server yet. ",e("a",{href:L.url("admin/network/dawnline/server")},"Run the setup wizard")," before adding people."]),e("div",{class:"dl-toolbar"},[e("div",{class:"dl-seg dl-people-tabs",role:"tablist"}),e("div",{class:"dl-toolbar-end"},[r,a.serverId?D([g("plus")," Add person"],()=>a.openCreate(),"add"):""])]),this.list]);return this.el=i,this.rebuild(),this.poller??(this.poller=Ke({fetch:()=>E.status(30),every:10,active:()=>!!a.el?.isConnected,apply:(s,l)=>a.take(s,l)})),!vo&&new URLSearchParams(location.search).get("add")&&(vo=!0,setTimeout(()=>a.openCreate(),100)),Promise.resolve(i)}countText(){let t=this.st.totals;return`${t.people} ${t.people===1?"person":"people"} · ${t.devices} device${t.devices===1?"":"s"} · ${t.online} online`}decorate(t=!1){let o=this.el?.querySelector(".dl-people-count");o&&(o.textContent=this.countText());let a=this.st.people,r=this.today,i=v=>Er(v,r),s={all:a.length,online:a.filter(v=>v.online>0).length,attention:a.filter(i).length,paused:a.filter(v=>v.state!=="active"&&v.state!=="quota"&&v.state!=="expired").length},l=this.el?.querySelector(".dl-people-tabs");if(l&&!(t&&ft(l))){let v={all:"All",online:"Online",attention:"Needs attention",paused:"Paused"};dom.content(l,Object.keys(v).map(h=>e("button",{type:"button",role:"tab",class:h===this.filter?"on":"",click:()=>{this.filter=h,this.decorate()}},[v[h],e("b",{class:h==="attention"&&s[h]?"warn":""},String(s[h]))])))}let d=v=>!(this.filter==="online"&&!v.online||this.filter==="attention"&&!i(v)||this.filter==="paused"&&!(v.state!=="active"&&v.state!=="quota"&&v.state!=="expired")),p=[...a].sort((v,h)=>this.sort==="name"?v.name.localeCompare(h.name):this.sort==="usage"?h.month[0]+h.month[1]-(v.month[0]+v.month[1]):h.online-v.online||h.last_seen-v.last_seen),c=0;for(let v of p){let h=this.card(v.id);if(!h)continue;this.list.appendChild(h),h.classList.toggle("dl-off",v.state!=="active"),h.classList.toggle("dl-attn-row",v.state==="quota"||v.state==="expired");let x=d(v);h.classList.toggle("dl-filtered",!x),x&&c++}let m=this.el?.querySelector(".dl-people-none")??null;a.length&&!c?(m??(m=e("div",{class:"dl-empty dl-people-none"},e("p",{},"No one here right now."))),m.previousElementSibling!==this.list&&this.list.after(m)):m?.remove()}async quick(t,o,a){await U(()=>E.personUpdate(t.id,o),a)&&await this.update()}renderCard(t,o){let a=this.person(o);if(!a)return dom.content(t,e("em",{},"This person was just removed.")),t;let r=this.today,i=Xe(a.expires,r),s=Math.max(0,a.device_limit-a.devices.length),l=a.has_link??this.st.settings.portal_enabled,d=[];if(a.expires){let h=i!=null&&i>=0&&i<=Math.max(a.expire_warn,3),x=i!=null&&i<0;d.push(e("span",{class:`dl-pill-ic${x?" bad":h?" warn":""}`,title:`Access ends ${ze(a.expires)}`},[g("calendar"),x?`ended ${ze(a.expires)}`:h?`ends in ${i} day${i===1?"":"s"}`:`until ${ze(a.expires)}`]))}a.hours&&d.push(e("span",{class:"dl-pill-ic",title:"Allowed hours"},[g("clock"),a.hours.replace("-","–")]));let p=Ht(a.devices).map(h=>e("button",{type:"button",class:`dl-chip${h.disabled?" disabled":""}${h.online?" live":""}`,title:`${Be[h.kind]} · ${h.address}${h.online?` · online from ${h.endpoint}`:h.handshake?` · seen ${le(h.handshake,this.st.now)}`:""}`,click:x=>{x.preventDefault(),He(a,h,this.deviceOpts(a))}},[g(h.kind),e("span",{class:"dl-chip-name"},h.name),!h.handshake&&!h.disabled?e("span",{class:"dl-chip-tag"},"not set up"):""]));p.push(e("button",{type:"button",class:"dl-chip add","aria-label":"Add device",title:s>0?"Add device":"Add device · over the limit, admins can still add",click:h=>{h.preventDefault(),ot(a,this.deviceOpts(a))}},g("plus")));let c=[];a.state==="quota"&&a.quota_period==="month"&&c.push(e("button",{type:"button",class:"dl-fix",click:()=>this.quick(a,{bonus_gb:String((a.bonus_gb||0)+10)},"+10 GB this month")},"+10 GB this month")),a.expires&&i!=null&&i<=Math.max(a.expire_warn,3)&&c.push(e("button",{type:"button",class:"dl-fix",click:()=>this.quick(a,{expires:Sr(a.expires,r)},"Extended by 1 month")},"Extend 1 month"));let m=ye("more","More",h=>we(h.currentTarget,[{label:"Open",icon:g("open"),run:()=>{location.href=Te(a.id)}},l?{label:"Invite card",icon:g("qr"),run:()=>Lt(a,this.st.servers.find(x=>x.id===a.server)?.name??"Home")}:null,s>0?{label:"Add device",icon:g("plus"),run:()=>ot(a,this.deviceOpts(a))}:null,null,{label:a.paused?"Resume":"Pause",icon:g(a.paused?"play":"pause"),warn:!a.paused,run:()=>this.togglePause(a)},{label:"Delete",icon:g("trash"),danger:!0,run:()=>this.remove(a.id)}].filter((x,R,$)=>x||R>0&&$[R-1])),"neutral","dl-icon-only"),v=e("div",{class:"dl-pcard-actions"},[l?ye("link","Copy link",()=>Ft(a.id),"neutral","dl-icon-only"):"",m]);return dom.content(t,e("div",{class:"dl-pcard"},[e("div",{class:"dl-pcard-main"},[e("div",{class:"dl-pcard-top"},[e("span",{class:`dl-avatar${a.online?" online":""}`},Oe(a.name)),e("div",{class:"dl-pcard-who"},[e("div",{class:"dl-card-head"},[e("a",{class:"dl-card-name",href:Te(a.id)},a.name),It(a),Fn(a),...d]),_r(a)])]),e("div",{class:"dl-chips"},p),c.length?e("div",{class:"dl-fixes"},c):""]),this.usageSide(a,v)])),t}usageSide(t,o){let a=t.quota_used||t.month[0]+t.month[1],r=t.quota_limit?Math.min(100,t.quota_used/t.quota_limit*100):0,i=t.devices.reduce((c,m)=>c+(m.spark[m.spark.length-1]??0),0),s=t.rate?.[t.rate.length-1],l=t.online&&s&&this.st.now-s[0]<180,d=e("div",{class:`dl-usebar${r>=100?" bad":r>=90?" warn":""}`});if(t.quota_limit){let c=e("i",{class:"fill"});c.style.width=`${r}%`,d.appendChild(c),ue(d,()=>[e("div",{class:"dl-tip-title"},`${r.toFixed(1)}% used`),e("div",{class:"dl-muted"},`${te(t.quota_used)} of ${te(t.quota_limit)} · ${te(Math.max(0,t.quota_limit-t.quota_used))} left`),e("div",{class:"dl-faint"},t.quota_period==="total"?"In total":`This month${t.bonus_gb?` · includes +${t.bonus_gb} GB extra`:""}`)])}else{let c=t.devices.map(m=>({d:m,v:m.month[0]+m.month[1]})).filter(m=>m.v>0).sort((m,v)=>v.v-m.v);c.forEach((m,v)=>{let h=e("i",{class:`c${Math.min(v,4)}`});h.style.flexGrow=String(m.v),d.appendChild(h)}),c.length&&ue(d,()=>[e("div",{class:"dl-tip-title"},"This month by device"),...c.map((m,v)=>e("div",{class:"dl-tip-row"},[e("span",{class:`dl-swatch c${Math.min(v,4)}`}),e("span",{},m.d.name),e("b",{},te(m.v))]))])}let p=t.quota_limit?`${te(Math.max(0,t.quota_limit-t.quota_used))} left`:"no limit";return e("div",{class:"dl-pside"},[e("div",{class:"dl-pside-top"},[l?e("span",{class:"dl-pside-state live"},"Online"):e("span",{class:"dl-pside-state"},t.online?"Online":t.last_seen?"Offline":"Never connected"),o]),e("div",{class:"dl-use-num"},[e("b",{class:a?"":"dl-faint"},te(a)),e("span",{class:"dl-faint"},t.quota_limit?`of ${te(t.quota_limit)}`:t.quota_period==="total"&&t.quota_gb?"in total":"this month")]),d,l?e("div",{class:"dl-use-live",title:"Right now"},[`↓ ${Pe(s[2])}`,e("span",{class:"dl-faint"},`↑ ${Pe(s[1])}`)]):e("div",{class:"dl-faint dl-pside-foot"},i?`today ${te(i)} · ${p}`:p)])}async togglePause(t){await U(()=>E.personPause(t.id,!t.paused),t.paused?`${t.name} resumed`:`${t.name} paused`)&&await this.refresh()}async remove(t){let o=this.person(t);await ne(`Remove ${o?.name??t}?`,`All ${o?.devices.length??0} devices are disconnected immediately and the personal link stops working. Usage history is kept in backups.`,"Remove",!0)&&await U(()=>E.personDelete(t),"Person removed")&&await this.refresh()}openCreate(){let t=this.st;if(!t.servers.length){Z("Set up the server first.","warning");return}let o=e("input",{type:"text",class:"cbi-input-text",placeholder:"e.g. Myata",maxlength:48}),a=fo("internet"),r=e("input",{type:"number",class:"cbi-input-text",min:1,max:32,value:t.settings.default_device_limit}),i=e("input",{type:"date",class:"cbi-input-text"}),s=e("input",{type:"number",class:"cbi-input-text",min:0,step:"any",placeholder:"Unlimited"}),l=(m,v)=>e("button",{type:"button",class:"cbi-button cbi-button-neutral",click:()=>{i.value=v?xt(Ne(t.series),v):""}},m),d=t.servers[0],p=!this.serverId&&t.servers.length>1?e("select",{class:"cbi-input-select"},t.servers.map(m=>e("option",{value:m.id},m.name))):null,c=(m,v,h)=>e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},m),e("div",{class:"cbi-value-field"},[v,h?e("div",{class:"cbi-value-description"},h):""])]);oe("Add person",[c("Name",o),p?c("Server",p):"",e("div",{class:"cbi-value dl-block"},[e("label",{class:"cbi-value-title"},"Access"),e("div",{class:"cbi-value-field"},a.el)]),c("Devices",r,"How many devices they can add themselves."),c("End date",e("div",{class:"dl-actions"},[i,l("1 month",1),l("3 months",3),l("1 year",12),l("None",0)]),"Optional."),c("Monthly data (GB)",s,"Optional. They are paused when it runs out and resumed next month.")],[ie()," ",D("Create and copy link",async()=>{let m=await U(()=>E.personCreate(o.value.trim(),"",p?.value??d.id,a.get(),String(Number(r.value)||t.settings.default_device_limit),i.value,s.value.trim(),"month"));m&&(m.link&&await pe(m.link,"Personal link copied"),this.showCreated(m.id,o.value.trim(),m.link,t.servers.find(v=>v.id===(p?.value??d.id))?.name??d.name),await this.refresh())},"positive")]),setTimeout(()=>o.focus(),50)}showCreated(t,o,a,r){if(a){Lt({id:t,name:o,link:a},r,{title:`${o} is ready`,lead:`Send ${o} the card or the link. They open it, add their devices and connect — no account needed.`});return}oe(`${o} is ready`,[e("p",{},"Created. Turn on the personal portal in Settings to get a link, or add devices for them here.")],[e("button",{class:"cbi-button cbi-button-positive",click:se},"Done")])}};var Kt=["#3a83f7","#a78bfa","#f472b6","#f59e0b","#10b981","#22d3ee","#ef4444","#84cc16"],Ln=n=>e("i",{class:"dl-circle-dot",style:`background:${Kt[n?.color??0]??Kt[0]}`}),Je=n=>n.access==="both"||n.access==="lan"&&!n.services?.length;function bo(n,t,o){let a=ae(n?.name??t.name??"",{placeholder:"NAS"}),r=ae(n?.address??t.address??"",{placeholder:"192.168.1.10",class:"cbi-input-text dl-mono"}),i=ae((n?.ports??t.ports??[]).join(", "),{placeholder:"All ports, or e.g. 445, 5000",class:"cbi-input-text dl-mono"}),s=(l,d)=>e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},l),e("div",{class:"cbi-value-field"},d)]);oe(n?`Edit ${n.name}`:"Add service",[s("Name",a),s("Address",r),s("Ports",i)],[ie()," ",D("Save",async()=>{let l=i.value.split(/[ ,]+/).filter(Boolean);await U(()=>E.serviceSet(n?.id??"",a.value,r.value,l),"Saved")&&(se(),o())},"positive")])}var Cr={_smb:"SMB",_afpovertcp:"AFP",_http:"Web",_https:"Web",_ssh:"SSH",_sftp:"SFTP","_sftp-ssh":"SFTP",_ipp:"Printer",_ipps:"Printer",_printer:"Printer","_pdl-datastream":"Printer",_airplay:"AirPlay",_raop:"AirPlay",_rfb:"Screen sharing",_googlecast:"Cast",_hap:"HomeKit",_rdp:"Remote desktop",_ftp:"FTP"},Lr=[["Web",["80","443"]],["SMB",["445"]],["SSH",["22"]]];function Tr(n){let t=new Map;for(let o of n.services){let a=Cr[o.type.split(".")[0]];!a||!o.port||(t.get(a)??t.set(a,new Set).get(a)).add(String(o.port))}return t.size?[...t].map(([o,a])=>[o,[...a].sort((r,i)=>+r-+i)]):Lr}function xo(n,t,o){let a=n,r=null,i=!1,s=null,l=new Set,d=e("div",{class:"dl-list"}),p=e("div",{class:"dl-stack gap8"},e("span",{class:"dl-sub"},"Looking for devices at home…")),c=()=>{let R=a.services;dom.content(d,R.length?R.map($=>e("div",{class:"dl-row"},[g("home"),e("span",{class:"dl-row-main dl-stack"},[e("b",{},$.name),e("span",{class:"dl-mono dl-faint"},`${$.address}${$.ports.length?` · ports ${$.ports.join(", ")}`:" · all ports"}`)]),D("Edit",()=>bo($,{},o)),D([g("trash")],async()=>{await ne(`Remove ${$.name}?`,"People limited to this service lose access to it.","Remove",!0)&&await U(()=>E.serviceDelete($.id),"Removed")&&await o()},"neutral",{title:"Remove","aria-label":`Remove ${$.name}`})])):[e("div",{class:"dl-row dl-muted"},"No services yet: pick ports of a device below.")])};async function m(R,$){if(!l.has(R.address)){l.add(R.address),h();try{let j=a.services.find(H=>H.address===R.address);($===null?j&&await U(()=>E.serviceDelete(j.id),`${j.name} removed`):await U(()=>E.serviceSet(j?.id??"",j?.name??(R.name||R.address),R.address,$),j?`${j.name} updated`:`${R.name||R.address} added`))&&await o()}finally{l.delete(R.address),h()}}}function v(R){let $=a.services.find(T=>T.address===R.address),j=!!$&&!$.ports.length,w=new Set($?.ports??[]),H=l.has(R.address),S=(T,b,A)=>Ue(T,b,A,{disabled:H?"disabled":null,"aria-busy":H?"true":null});return e("div",{class:"dl-row"},[g(R.services.some(T=>T.type.startsWith("_ipp")||T.type.startsWith("_printer"))?"file":"computer"),e("span",{class:"dl-row-main dl-stack"},[e("b",{},R.name||R.address),e("span",{class:"dl-mono dl-faint"},R.address)]),e("div",{class:"dl-chips-row dl-host-ports"},[S("All ports",j,()=>m(R,j?null:[])),...Tr(R).map(([T,b])=>{let A=!j&&b.every(u=>w.has(u));return S(`${T} ${b.join(", ")}`,A,()=>{let u=new Set(j?[]:w);for(let f of b)A?u.delete(f):u.add(f);m(R,u.size?[...u]:null)})})])])}function h(){if(i)return dom.content(p,e("span",{class:"dl-sub"},"Couldn't read the devices at home."));if(!r)return;let R=r;if(!R.hosts.length)return dom.content(p,e("span",{class:"dl-sub"},"No devices found in the home network right now."));let $=e("details",{class:"dl-params",open:s??!a.services.length?"":null},[e("summary",{},[g("chevron"),e("span",{},"Add from devices at home"),e("span",{class:"dl-pcount"},String(R.hosts.length))]),e("div",{class:"dl-params-body"},[e("span",{class:"dl-sub"},R.mdns?"Ports they announce over Bonjour. Pick what to open, or all ports.":"Devices that got an address from this router. Pick the ports to open, or all ports."),e("div",{class:"dl-list"},R.hosts.map(v))])]);$.addEventListener("toggle",()=>s=$.open),dom.content(p,$)}return E.homeHosts(t).then(R=>{r=R,h()}).catch(()=>{i=!0,h()}),c(),{el:e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-iflead"},[e("div",{class:"dl-iflead-row"},[e("b",{},"Home services"),D([g("plus")," Add service"],()=>bo(null,{},o))]),e("span",{class:"dl-sub"},"Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers.")]),d,p]),update(R){a=R,c(),h()}}}function Jt(n,t,o,a){let r=new Set(n.circles.filter(h=>h.server===t).map(h=>h.color)),i=o?.color??Kt.findIndex((h,x)=>!r.has(x));i<0&&(i=0);let s=ae(o?.name??"",{placeholder:"Family"}),l=n.people.filter(h=>h.server===t).sort((h,x)=>h.name.localeCompare(x.name)),d=new Set(l.filter(h=>o&&h.circle===o.id).map(h=>h.id)),p=e("div",{class:"dl-swatches",role:"radiogroup","aria-label":"Colour"}),c=()=>dom.content(p,Kt.map((h,x)=>e("button",{type:"button",role:"radio",class:`dl-swatch${x===i?" on":""}`,style:`--sw:${h}`,"aria-checked":x===i?"true":"false","aria-label":`Colour ${x+1}`,click:()=>{i=x,c()}})));c();let m=e("div",{class:"dl-chips-row"},l.map(h=>{let x=h.circle&&h.circle!==o?.id?n.circles.find(R=>R.id===h.circle):void 0;return e("button",{type:"button",class:`dl-chipbtn${d.has(h.id)?" on":""}`,title:Je(h)?x?`Now in ${x.name}`:"":`${h.name} has no home access: their devices aren't reachable anyway`,click:R=>{d.delete(h.id)||d.add(h.id),R.currentTarget.classList.toggle("on",d.has(h.id))}},[h.name,Je(h)?x?e("b",{},x.name):"":e("b",{},"internet")])})),v=(h,x)=>e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},h),e("div",{class:"cbi-value-field"},x)]);oe(o?`Edit ${o.name}`:"New circle",[v("Name",s),v("Colour",p),v("People",m),e("p",{class:"dl-sub"},"Devices of people in one circle reach each other. A person is in one circle at a time.")],[o?D("Delete",async()=>{await U(()=>E.circleDelete(o.id),`${o.name} deleted`)&&(se(),a())},"negative"):"",e("span",{class:"dl-spacer"}),ie()," ",D("Save",async()=>{await U(()=>E.circleSet(o?.id??"",t,s.value,i,[...d]),"Saved")&&(se(),a())},"positive")],"dl-circle-modal")}function wo(n,t,o){let a=n.circles.filter(r=>r.server===t);return e("div",{class:"dl-chips-row dl-circles"},[...a.map(r=>{let i=n.people.filter(s=>s.circle===r.id).map(s=>s.name);return e("button",{type:"button",class:"dl-chip",title:`Edit ${r.name}`,click:()=>Jt(n,t,r,o)},[Ln(r),e("b",{},r.name),e("span",{class:"dl-faint"},i.length?i.join(", "):"nobody yet")])}),e("button",{type:"button",class:"dl-chip add",title:"New circle","aria-label":"New circle",click:()=>Jt(n,t,null,o)},g("plus"))])}function Tn(n,t){let o=n.people.filter(c=>c.server===t.id),a=(c="")=>e("span",{class:"dl-yes"},[g("check"),c]),r=()=>e("span",{class:"dl-faint"},"—"),i=c=>{let m=new Set(c.map(v=>v.access==="lan"&&v.services?.length?"services":v.home_nets?.length?"some":"all"));return m.size||m.add("all"),a([...m].map(v=>({all:"all networks",some:"their networks",services:"services"})[v]).join(" / "))},s=()=>t.mesh==="off"?r():t.mesh==="circles"?a("circle"):a(),l=t.lan_like?"like home":"direct",d=(c,m,v)=>e("tr",{},[e("td",{},[e("b",{},c),e("div",{class:"dl-sub"},`${m.length} ${m.length===1?"person":"people"}`)]),...v.map(h=>e("td",{},h))]),p=c=>o.filter(m=>m.access===c);return e("section",{class:"dl-setsec"},[e("div",{class:"dl-setsec-body"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Who reaches what"),e("span",{class:"dl-spacer"}),e("span",{class:"dl-sub"},"From the rules on this server")]),e("div",{class:"dl-reach-wrap"},e("table",{class:"dl-table dl-reach"},[e("tr",{},["","Internet","Home","This router","Each other"].map(c=>e("th",{},c))),d("Internet",p("internet"),[a(l),r(),e("span",{class:"dl-faint"},"DNS"),r()]),d("Home",p("lan"),[e("span",{class:"dl-faint"},"their own"),i(p("lan")),a(),s()]),d("Both",p("both"),[a(l),i(p("both")),a(),s()])])),e("p",{class:"dl-sub"},"Home devices reach the devices of people with home access, on the networks those people reach. Paused, ended and over-the-limit people reach nothing.")])])}function yo(n,t){let o=n.people.filter(p=>p.server===t.id).flatMap(p=>p.devices.map(c=>({id:c.id,label:`${p.name} · ${c.name}`}))).sort((p,c)=>p.label.localeCompare(c.label)),a="@addr",r=(p,c)=>{let m=e("select",{class:"cbi-input-select","aria-label":p},[...o.map(R=>e("option",{value:R.id,selected:R.id===c?"selected":null},R.label)),e("option",{value:a,selected:c===a?"selected":null},"Address")]),v=ae("",{placeholder:p,class:"cbi-input-text dl-mono"}),h=e("div",{class:"dl-check-end"},[m,v]),x=()=>v.hidden=m.value!==a;return m.addEventListener("change",x),x(),{el:h,value:()=>m.value===a?v.value.trim():m.value}},i=r("10.0.1.11",o[0]?.id??a),s=r("10.0.1.20:445",a),l=e("div",{class:"dl-stack gap8"}),d=async()=>{let p=await U(()=>E.accessCheck(i.value(),s.value()));if(!p)return;let c=p.steps.findIndex(m=>!m.ok);dom.content(l,[e("div",{class:`dl-verdict ${p.ok?"ok":"bad"}`},[e("b",{},p.ok?"Allowed":"Blocked"),e("span",{class:"dl-sub"},p.ok?"Every step lets it through":`Stops at step ${c+1} of ${p.steps.length}`)]),e("ul",{class:"dl-checks"},p.steps.map(m=>e("li",{},[e("span",{class:`dl-check-icon ${m.ok?"ok":"error"}`},g(m.ok?"check":"x")),e("div",{class:"dl-check-body"},[e("div",{class:"dl-check-title"},m.title),m.detail?e("div",{class:"dl-check-detail"},m.detail):""])])))])};return e("section",{class:"dl-setsec"},[e("div",{class:"dl-setsec-body"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Check access"),e("span",{class:"dl-spacer"}),e("span",{class:"dl-sub"},"Why something does or does not connect")]),e("div",{class:"dl-check-form"},[i.el,e("span",{class:"dl-faint"},"→"),s.el,D("Check",d)]),l])])}var Vt={app:"Dawnline",amneziawg:"AmneziaWG",packages:"System packages",pkgs:"System packages"};function Ve(n){return(n.startsWith("check")?n.slice(6)||"all":n).split(/[:@ ]/)[0]}function Yt(n){return Ve(n.action==="check"?`check:${n.component??""}`:n.component??"")}function ko(n){return n=Math.max(0,Math.floor(n)),`${Math.floor(n/60)}:${String(n%60).padStart(2,"0")}`}function $o(n,t){return!n?.from&&!n?.to?t:n.from&&n.to&&n.from!==n.to?`${n.from} → ${n.to}`:n.to??n.from??t}function _o(n,t){let o=n.check?.components??{},a=t==="all"?["app","amneziawg","packages"]:[t],r=[],i;for(let l of a){let d=o[l];if(d){if(d.error)return{tone:"warn",text:d.error};l==="packages"&&d.updates?r.push(`${d.updates} system package${d.updates===1?"":"s"}`):l!=="packages"&&d.update&&d.installed&&d.latest&&(r.push(`${Vt[l]} ${d.latest}`),t!=="all"&&(i=d.latest))}}if(r.length)return{tone:"acc",text:`Update available: ${r.join(", ")}`,update:i};let s=a.length===1?o[a[0]]:null;return s?.status==="dev"?{tone:"acc",text:`Installed version is newer than the release (${s.latest})`}:s?.note?{tone:"warn",text:s.note}:{tone:"ok",text:a.length>1?"Everything is up to date":"Latest version is installed"}}function Eo(n,t,o,a){return t?n.id===t:o&&n.id===o?!1:n.state==="running"||a>0&&n.started>=a}var So=n=>new Promise(t=>setTimeout(t,n));async function Mt(n,t,o){let a=o?Yt(o):Ve(n),r=o?o.action==="check":n.startsWith("check"),i=Date.now(),s=e("b",{},Vt[a]??(a==="all"?"All components":"Dawnline")),l=e("span",{class:"dl-pill dl-mono"},t.version??""),d=e("span",{class:"dl-pill info",hidden:!0}),p=e("span",{},"0:00"),c=e("pre",{class:"dl-log"},"Operation started. Waiting for log output…"),m=e("div",{}),v=e("div",{class:"dl-op-actions"}),h=[],x=u=>dom.content(v,u),R=(u=!1)=>ie("Close",u);oe(t.title,e("div",{class:"dl-op"},[e("div",{class:"dl-op-head"},[s,t.version?l:"",d,e("span",{class:"dl-spacer"}),e("span",{class:"dl-faint dl-op-timer"},[g("clock"),p])]),e("div",{class:"dl-op-loghead"},[e("b",{},"Operation log"),ye("copy","Copy log",()=>pe(h.join(` +`),"Log copied"))]),c,m]),[v],"wide"),x([e("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?"Checking…":"Working…")]);let $=o??null,j=o?.id,w,H=0,S=u=>{j!==u.id&&(j=u.id,t.onJob?.(u))};if(o)t.onJob?.(o);else try{let u=await E.updatesStatus().catch(()=>null);w=u?.job?.id,H=u?.now??0;let f=await E.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==w&&($=f.job,S(f.job))}catch(u){return h=[ve(u)],c.textContent=h[0],dom.content(m,e("div",{class:"dl-comp-status warn"},[g("alert"),e("span",{},ve(u))])),x([R(!0)]),Z(ve(u),"error"),null}let T=null,b=0;for(;;){if(await So(1e3),T=await E.updatesStatus().catch(()=>null),!T){if(++b>60)break;continue}b=0;let u=T.job;if(!u||!Eo(u,j,w,H)){if(Date.now()-i>15e3)break;continue}if(S(u),$=u,u.log.length){h=u.log;let f=c.scrollTop+c.clientHeight>=c.scrollHeight-8;c.textContent=h.join(` +`),f&&(c.scrollTop=c.scrollHeight)}if(l.textContent=$o(u,t.version??""),!l.isConnected&&l.textContent&&s.after(l),p.textContent=ko((u.finished??T.now)-u.started),u.state==="running"){d.hidden=!u.phase,d.textContent=u.phase;continue}break}if(c.scrollTop=c.scrollHeight,d.hidden=!1,!$||$.state==="running")return d.className="dl-pill warn",d.textContent="No answer",dom.content(m,e("div",{class:"dl-comp-status warn"},[g("alert"),e("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),x([R()]),t.onDone?.(T),$;if($.state==="failed")return d.className="dl-pill bad",d.textContent="Failed",dom.content(m,e("div",{class:"dl-comp-status bad"},[g("x"),e("span",{},[e("b",{},$.error??"Operation failed"),r?"":". Nothing else was changed."])])),x([D("Copy log",()=>pe(h.join(` +`),"Log copied")),R(!0)]),Z(`${Vt[a]??"Update"}: ${$.error??"failed"}`,"error"),t.onDone?.(T),$;if(d.className="dl-pill ok",d.textContent="Finished",r&&T){let u=_o(T,a);if(dom.content(m,e("div",{class:`dl-comp-status ${u.tone}`},[g(u.tone==="ok"?"check":u.tone==="warn"?"alert":"download"),e("span",{},u.text)])),Z(u.text,u.tone==="warn"?"warning":"success"),t.onDone?.(T),u.update&&t.onUpdate){let f=T;x([R(),D(`Update to ${u.update}`,()=>t.onUpdate(f),"positive")])}else x([R()]),u.tone==="ok"&&setTimeout(()=>m.isConnected&&se(),1200);return $}if(a==="app"&&$.to){let u=$.to,f=e("span",{},"Waiting for the router to restart its services…");dom.content(m,e("div",{class:"dl-comp-status ok"},[g("check"),e("span",{},[e("b",{},`Dawnline ${u} is installed. `),f])]));let N=()=>{ui.menu?.flushCache(),location.reload()};x([R(),D("Reload now",N,"positive")]),Z(`Dawnline updated to ${u}`,"success",6e3);for(let P=1;P<=30;P++)if(f.textContent=`Waiting for the router to restart its services (${P} of 30)…`,await So(1500),(await E.updatesStatus().catch(()=>null))?.version===u)return f.textContent="Services are back. Reloading…",setTimeout(N,800),$;return f.textContent="Services restarted. Reload the page to use the new version.",$}let A=a==="pkgs"?`Updated ${[...$.result?.pkgs?.updated??[],...$.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:a==="amneziawg"?`AmneziaWG${$.to?` ${$.to}`:""} is installed`:"Operation completed";return dom.content(m,e("div",{class:"dl-comp-status ok"},[g("check"),e("span",{},A)])),x([R()]),Z(A,"success"),t.onDone?.(T),$}var Mr={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function Co(n,t,o,a){return!await ne(`Install ${t}?`,o,"Install")||(await Mt(n,{title:`Installing ${t}`}))?.state!=="done"?!1:(setTimeout(()=>a?.(),4e3),!0)}function Qt(n){return Co("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Pt(n,t,o){return n==="awg"?Qt(o):t.length?Co(`pkgs:${t.join(",")}`,Mr[n],`${t.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function Lo(n,t){if(n==="awg")return Qt(t);let o=await U(()=>E.updatesStatus());return o?Pt(n,o.needs?.[n]??[],t):!1}var Pr=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],Dr={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function To(n,t,o){let a=n.id,r=t,i=e("div",{class:"dl-stack gap16"},e("section",{class:"dl-setsec"},e("div",{class:"dl-setsec-body"},e("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,d="",p=!0,c=!0,m="all",v=!1,h=xo(r,a,o),x=new Set,R="",$=()=>JSON.stringify([c,l,l?"":d,p,[...x].sort()]),j=()=>s.detected.lan||s.saved.lan||"",w=()=>(l?s.detected.wan||s.saved.wan:d)||"",H=()=>new Map(s.devices.map(C=>[C.name,C])),S=()=>{let C=H();return[...p&&j()?[j()]:[],...[...x].filter(Q=>Q!==j())].filter(Q=>Q!==w()).map(Q=>C.get(Q)??{name:Q,nets:[],missing:!0})},T=(C,G)=>{s=C,G&&(l=C.config.auto_wan,d=C.config.wan_device||C.detected.wan||C.saved.wan||"",p=C.config.auto_lan,c=C.config.lan_like,m=C.config.mesh??(C.config.device_mesh?"all":"off"),x=new Set(C.config.lan_devices),R=$()),W()},b=async C=>{let G=await E.interfaces(a).catch(Q=>(Z(Q.message,"error"),null));G&&T(G,C)};function A(C){let G=p&&C.name===j(),Q=!!C.own||!!C.master||C.name===w()||G;return G||x.has(C.name)||!Q&&(C.nets.length>0||!!C.missing)}function u(C){let G=p&&C.name===j(),Q=C.name===w(),de=!G&&x.has(C.name),F=!(!!C.own||!!C.master||Q||G)&&(C.nets.length>0||de||!!C.missing),me=(de||G)&&!C.zone&&!C.missing,re=C.missing?"Not present right now":C.own?"This server":C.master?`Port of ${C.master}`:Q?`Internet${C.zone?` · zone ${C.zone}`:""}`:C.nets.length?C.nets.join(", "):"No IPv4 network",ge=e("button",{type:"button",class:`dl-if${de?" sel":""}${G?" auto":""}${!F&&!de&&!G?" off":""}${me?" warn":""}`,"aria-pressed":de||G?"true":"false","aria-disabled":F?null:"true",click:()=>{F&&(x.has(C.name)?x.delete(C.name):x.add(C.name),W())}},[e("span",{class:"dl-if-ic"},g(Dr[C.kind]??"link")),e("span",{class:"dl-if-main"},[e("span",{class:"dl-if-name"},C.name),e("span",{class:"dl-if-sub"},re)]),G?e("span",{class:"dl-if-badge ok"},"Auto"):de?e("span",{class:"dl-if-check"},g("check")):""]);return ue(ge,()=>[e("div",{class:"dl-tip-title"},C.name),e("div",{class:"dl-muted"},[C.logical?`Interface ${C.logical}`:"No netifd interface",C.zone?` · zone ${C.zone}`:" · no firewall zone"]),C.members.length?e("div",{class:"dl-muted"},`Ports: ${C.members.join(", ")}`):"",C.nets.length?e("div",{class:"dl-mono"},C.nets.join(", ")):"",me?e("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",C.master?e("div",{class:"dl-muted"},`Choose ${C.master} to include it.`):""]),ge}function f(){let C=s.like_home;return!c||!s.config.lan_like?"":!s.needs?.length&&C.active&&C.bridged?"ok":"warn"}function N(){let C=s.like_home;return c?s.needs?.length?[e("span",{class:"dl-warn"},`Needs ${s.needs.join(" and ")}.`)," Until they are installed, internet traffic goes straight to the WAN."]:s.config.lan_like?C.active&&C.bridged?["Internet traffic enters ",e("span",{class:"dl-mono"},C.dev??"")," as ",e("span",{class:"dl-mono"},C.address??""),", so whatever handles home traffic (proxies, filters, DNS) handles it too."]:[e("span",{class:"dl-warn"},`Not working: ${C.error??"the link is down"}`)," Internet traffic goes straight to the WAN for now."]:["Internet traffic will enter the router from your LAN, so it is handled like any home device. Save to turn on."]:["Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router."]}let P={off:"Devices of different people never reach each other; a person's own devices don't either.",all:"Devices of people with home access reach each other, like home devices do. Internet-only people never.",circles:"Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never."};function I(C,G,Q,de,O="",F){return e("div",{class:F?"dl-setrow head":"dl-setrow"},[e("div",{class:"dl-lh-main"},[e("span",{class:`dl-need-ic ${O}`},g(C)),e("div",{class:"dl-stack"},[e("span",{class:"dl-setrow-label"},G),e("span",{class:"dl-sub"},Q),F??""])]),e("div",{class:"dl-setrow-ctl"},de)])}let J=(C,G)=>{let Q=de=>e("span",{class:"dl-mono"},de);return C?e("span",{},[" Now: ",Q(C),...G&&G!==C?[", was ",Q(G)]:[],"."]):e("span",{},G?[" Not found now: using ",Q(G),"."]:[" Not found."])};function W(){let C=e("select",{class:"cbi-input-select","aria-label":"Internet interface",change:y=>{d=y.target.value,W()}},s.devices.filter(y=>!y.own&&!y.master&&y.zone&&!y.missing).map(y=>e("option",{value:y.name,selected:y.name===d?"selected":null},`${y.name} · zone ${y.zone}`))),Q=S().flatMap(y=>y.nets.map(B=>[B,y.name])),de=JSON.parse($()),O=JSON.parse(R),F=(...y)=>y.some(B=>JSON.stringify(de[B])!==JSON.stringify(O[B])),me=F(0,1,2),re=F(3,4),ge=y=>D("Save",async()=>{let B=await U(()=>E.serverInterfaces(a,l,l?"":d,p,[...x],c,m!=="off",m),"Access saved");B&&(T(B,!0),B.nets_changed&&B.lan_only&&Z(`${B.lan_only} ${B.lan_only===1?"person has":"people have"} Home-only access: their devices need the configuration again to reach the new networks.`,"warning",1e4))},"positive",{disabled:!y}),M=e("section",{class:"dl-setsec dl-ifcard"},[e("div",{class:"dl-setsec-body"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Internet"),e("span",{class:"dl-spacer"}),e("span",{class:"dl-sub"},"People with Internet or Both")]),I("home","Internet like a home device",N(),[c&&s.needs?.length?D("Install",()=>Pt("home",s.needs,()=>b(!1)),"positive"):"",fe(c,"Internet like a home device",y=>{c=y,W()})],f()),I("globe","Auto-detect WAN",["The interface with the default route: the server port opens there and Internet access leaves through it.",J(s.detected.wan,s.saved.wan)],[l?"":C,fe(l,"Auto-detect WAN",y=>{l=y,W()})])]),e("div",{class:"dl-setsec-foot"},[e("span",{class:"dl-sub"},c?["Internet like a home device",w()?[" · leaves through ",e("span",{class:"dl-mono"},w())]:""]:w()?["Internet straight to ",e("span",{class:"dl-mono"},w())]:"No WAN found"),ge(me)])]),_=xe([["off","Off"],["all","Everyone"],["circles","Circles"]],m,{label:"Devices reach each other",cls:"sm",optimistic:!1,onChange:async y=>{let B={off:"Off",all:"Everyone",circles:"Circles"}[y];await U(()=>E.serverUpdate(a,{mesh:y}),`Devices reach each other: ${B}`)&&(m=y,s.config.mesh=y,W(),await o())}}),k=e("section",{class:"dl-setsec dl-ifcard"},[e("div",{class:"dl-setsec-body"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Home network"),e("span",{class:"dl-spacer"}),e("span",{class:"dl-sub"},"People with Home or Both"),D([g("reset")," Rescan"],()=>b(!1),"neutral",{title:"Read the interfaces again"})]),I("network","Networks","Everyone with home access reaches these, unless their page leaves one out; their devices can be reached from here too. Click one to add or remove it.","","",q()),I("link","Devices reach each other",P[m],_,"",m==="circles"?wo(r,a,o):void 0),h.el]),e("div",{class:"dl-setsec-foot"},[e("span",{class:"dl-sub dl-if-summary"},Q.length?["Home access reaches ",...Q.flatMap(([y,B],Y)=>[Y?", ":"",e("span",{class:"dl-mono"},y),` (${B})`])]:"No home network: Home access reaches nothing but this router."),ge(re)])]),z=window.scrollY;i.style.minHeight=`${i.offsetHeight}px`,dom.content(i,[M,k]),i.style.minHeight="",window.scrollTo({top:z})}function q(){let C=s.devices.filter(A),G=s.devices.filter(Q=>!A(Q));return e("div",{class:"dl-stack gap8 dl-netpick"},[C.length?e("div",{class:"dl-ifgrid"},C.map(u)):e("span",{class:"dl-warn"},"No home network: Home access reaches nothing but this router."),e("label",{class:"dl-boxrow"},[e("span",{class:"dl-stack"},[e("span",{},"Auto-detect LAN"),e("span",{class:"dl-sub"},["Adds the LAN this router uses.",J(s.detected.lan,s.saved.lan)])]),fe(p,"Auto-detect LAN",Q=>{p=Q,W()})]),G.length?e("details",{class:"dl-params",open:v?"":null,toggle:Q=>v=Q.currentTarget.open},[e("summary",{},[g("chevron"),e("span",{},"Other interfaces"),e("span",{class:"dl-pcount"},String(G.length))]),e("div",{class:"dl-params-body"},[e("span",{class:"dl-sub"},"The WAN, this server, ports and Wi-Fi of a bridge (they come with it) and interfaces without an IPv4 network."),...Pr.map(([Q,de])=>{let O=G.filter(F=>F.category===Q);return O.length?e("div",{class:"dl-ifgroup"},[e("h4",{},de),e("div",{class:"dl-ifgrid"},O.map(u))]):""})])]):""])}return b(!0),{el:i,update(C){r=C,h.update(C),s&&W()}}}var Mo="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl",Ar="https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",zr="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",Nr={online:0,"24h":86400,"7d":7*86400,"30d":30*86400},Dt=null;function Rr(n){let t=window;return n.appendChild(e("link",{rel:"stylesheet",href:`${Mo}.css`})),t.maplibregl?Promise.resolve(t.maplibregl):Dt||(Dt=new Promise((o,a)=>{let r=e("script",{src:`${Mo}.js`});r.onload=()=>t.maplibregl?o(t.maplibregl):a(new Error("MapLibre failed to load")),r.onerror=()=>{Dt=null,a(new Error("Could not load the map library (no internet access from this browser?)"))},n.appendChild(r)}),Dt)}function Zt(){let n=document.documentElement.getAttribute("data-darkmode");return n!=null?n==="true":window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1}function Hr(n,t,o=48){let a=(n[0]+t[0])/2,r=(n[1]+t[1])/2,i=t[0]-n[0],s=t[1]-n[1],l=Math.hypot(i,s)||1,d=Math.min(.25*l,12),p=a-s/l*d,c=r+i/l*d,m=[];for(let v=0;v<=o;v++){let h=v/o,x=1-h;m.push([x*x*n[0]+2*x*h*p+h*h*t[0],x*x*n[1]+2*x*h*c+h*h*t[1]])}return m}function Ir(n,t){let o=new Map;for(let a of n.geo.points){if(n.person&&a.person!==n.person||(t==="online"?!a.online:n.now-a.ts>Nr[t]))continue;let r=o.get(a.device);(!r||a.online&&!r.online||a.online===r.online&&a.ts>r.ts)&&o.set(a.device,a)}return[...o.values()]}var gt=class{constructor(t,o="online",a=380){this.cb=t;this.map=null;this.gl=null;this.markers=[];this.popup=null;this.anim=0;this.data=null;this.fitted=!1;this.range=o,this.status=e("div",{class:"dl-map-status"}),this.el=e("div",{class:"dl-geomap",style:`height:${a}px`},this.status)}async mount(t){this.data=t;try{this.gl=await Rr(this.el)}catch(o){this.status.textContent=o.message;return}this.map=new this.gl.Map({container:this.el,style:Zt()?Ar:zr,center:[t.geo.home?.lon??20,t.geo.home?.lat??50],zoom:3,attributionControl:{compact:!0},dragRotate:!1,pitchWithRotate:!1,cooperativeGestures:!0}),this.map.addControl(new this.gl.NavigationControl({showCompass:!1}),"bottom-right"),this.map.on("load",()=>{this.map.addSource("dl-areas",{type:"geojson",data:{type:"FeatureCollection",features:[]}}),this.map.addLayer({id:"dl-area",type:"circle",source:"dl-areas",paint:{"circle-radius":["interpolate",["exponential",2],["zoom"],2,6,6,26,9,140,12,900],"circle-color":["case",["get","online"],"#40c977",Zt()?"#ededed":"#0d0d0d"],"circle-opacity":["case",["get","online"],.12,.06],"circle-stroke-width":1,"circle-stroke-color":["case",["get","online"],"#40c977",Zt()?"#ededed":"#0d0d0d"],"circle-stroke-opacity":["case",["get","online"],.35,.15]}}),this.map.addSource("dl-arcs",{type:"geojson",data:{type:"FeatureCollection",features:[]}}),this.map.addLayer({id:"dl-arc-recent",type:"line",source:"dl-arcs",filter:["==",["get","online"],!1],layout:{"line-cap":"round"},paint:{"line-color":Zt()?"#ededed":"#0d0d0d","line-opacity":.35,"line-width":1.5,"line-dasharray":[2,3]}}),this.map.addLayer({id:"dl-arc-glow",type:"line",source:"dl-arcs",filter:["==",["get","online"],!0],layout:{"line-cap":"round"},paint:{"line-color":"#40c977","line-opacity":.18,"line-width":7}}),this.map.addLayer({id:"dl-arc-live",type:"line",source:"dl-arcs",filter:["==",["get","online"],!0],layout:{"line-cap":"round"},paint:{"line-color":"#40c977","line-width":2}}),this.map.addLayer({id:"dl-arc-flow",type:"line",source:"dl-arcs",filter:["==",["get","online"],!0],layout:{"line-cap":"round"},paint:{"line-color":"#ffffff","line-width":2,"line-opacity":.8,"line-dasharray":[0,4,3]}}),this.animate(),this.draw()})}setRange(t){this.range=t,this.fitted=!1,this.draw()}update(t){this.data=t,this.draw()}destroy(){cancelAnimationFrame(this.anim),this.map?.remove(),this.map=null}animate(){let t=[[0,4,3],[.5,4,2.5],[1,4,2],[1.5,4,1.5],[2,4,1],[2.5,4,.5],[3,4,0],[0,.5,3,3.5],[0,1,3,3],[0,1.5,3,2.5],[0,2,3,2],[0,2.5,3,1.5],[0,3,3,1],[0,3.5,3,.5]],o=-1,a=0,r=i=>{this.map&&(i-a>70&&(a=i,o=(o+1)%t.length,this.map.getLayer("dl-arc-flow")&&this.map.setPaintProperty("dl-arc-flow","line-dasharray",t[o])),this.anim=requestAnimationFrame(r))};this.anim=requestAnimationFrame(r)}groups(t){let o=new Map;for(let a of t){let r=`${a.asn||a.org||a.ip}|${a.city}|${a.cc}`,i=o.get(r);i||(i={key:r,lat:a.lat,lon:a.lon,city:a.city,country:a.country,cc:a.cc,asn:a.asn,org:a.org,online:!1,ts:0,points:[]},o.set(r,i)),i.points.push(a),i.online||(i.online=a.online),i.ts=Math.max(i.ts,a.ts)}return[...o.values()]}draw(){if(!this.map||!this.data||!this.map.getSource("dl-arcs"))return;let t=this.data,o=this.groups(Ir(t,this.range)),a=t.geo.home;for(let s of this.markers)s.remove();this.markers=[];let r=new Map,i=o.map(s=>{let l=`${s.lat.toFixed(2)},${s.lon.toFixed(2)}`,d=r.get(l)??0;return r.set(l,d+1),{g:s,at:[s.lon+d*.25,s.lat]}});if(this.map.getSource("dl-areas").setData({type:"FeatureCollection",features:i.map(({g:s,at:l})=>({type:"Feature",properties:{online:s.online},geometry:{type:"Point",coordinates:l}}))}),this.map.getSource("dl-arcs").setData({type:"FeatureCollection",features:a?i.map(({g:s,at:l})=>({type:"Feature",properties:{online:s.online},geometry:{type:"LineString",coordinates:Hr([a.lon,a.lat],l)}})):[]}),a){let s=e("div",{class:"dl-mk-home",title:`Home router${a.city?` · ${a.city}`:""}${a.org?` · ${a.org}`:""}`});s.innerHTML=gn("home","dl-mk-home-ic"),this.markers.push(new this.gl.Marker({element:s}).setLngLat([a.lon,a.lat]).addTo(this.map))}for(let{g:s,at:l}of i){let d=s.points.length,p=e("button",{type:"button",class:`dl-mk${s.online?" online":""}${d>1?" multi":""}`,"aria-label":`${d} device${d===1?"":"s"} via ${s.org||"unknown network"} in ${s.city||"unknown city"}`},d>1?e("span",{class:"dl-mk-count"},String(d)):e("span",{class:"dl-mk-dot"})),m=!!a&&Math.abs(l[0]-a.lon)<.02&&Math.abs(l[1]-a.lat)<.02?[22,-16]:[0,0];p.addEventListener("click",v=>{v.stopPropagation(),this.openPopup(s,l,m)}),this.markers.push(new this.gl.Marker({element:p,offset:m}).setLngLat(l).addTo(this.map))}if(!this.fitted){let s=i.map(l=>l.at);a&&(s.length===0||this.range!=="online"||i.some(l=>l.g.online))&&s.push([a.lon,a.lat]),this.fit(s),this.fitted=!0}this.status.textContent=i.length||a?"":"No locations yet",this.status.style.display=this.status.textContent?"":"none"}fit(t){if(!t.length)return;let o=(d,p)=>{let c=Math.PI/180,m=(p[1]-d[1])*c,v=(p[0]-d[0])*c,h=Math.sin(m/2)**2+Math.cos(d[1]*c)*Math.cos(p[1]*c)*Math.sin(v/2)**2;return 12742*Math.asin(Math.sqrt(h))},a=[t.reduce((d,p)=>d+p[0],0)/t.length,t.reduce((d,p)=>d+p[1],0)/t.length],r=t;if(t.length>=5){let d=[...t].sort((p,c)=>o(a,p)-o(a,c));r=d.slice(0,Math.ceil(d.length*.9))}if(Math.max(...r.map(d=>o(a,d)))<25){this.map.jumpTo({center:a,zoom:9.5});return}let s=new this.gl.LngLatBounds(r[0],r[0]);r.forEach(d=>s.extend(d));let l=this.el.clientHeight||380;this.map.fitBounds(s,{padding:{top:Math.min(90,l/4),bottom:Math.min(70,l/5),left:60,right:60},maxZoom:9,duration:0})}openPopup(t,o,a=[0,0]){let r=this.data;this.popup?.remove();let i=[t.city,t.cc||t.country].filter(Boolean).join(", "),s=[...new Set(t.points.map(c=>c.person))],l=t.points.sort((c,m)=>Number(m.online)-Number(c.online)||m.ts-c.ts).map(c=>{let m=r.people.find(h=>h.id===c.person),v=m?.devices.find(h=>h.id===c.device);return e("button",{type:"button",class:"dl-pop-row",click:()=>this.cb.openDevice(c.person,c.device)},[e("span",{class:`dl-pop-dot${c.online?" on":""}`}),e("span",{class:"dl-pop-name"},[e("b",{},m?.name??c.person),` · ${v?.name??"device"}`]),e("span",{class:"dl-faint dl-nowrap"},c.online?"now":le(c.ts,r.now))])}),d=e("div",{class:"dl-pop"},[e("div",{class:"dl-pop-head"},[e("span",{class:"dl-pop-net"},g("globe")),e("div",{class:"dl-stack"},[e("strong",{},t.org||"Unknown network"),e("span",{class:"dl-faint"},[t.asn?`AS${t.asn} · `:"",i?`${i} · approximate`:"approximate location"])])]),e("div",{class:"dl-pop-list"},l),s.length===1?e("div",{class:"dl-pop-actions"},[e("button",{type:"button",class:"cbi-button cbi-button-positive important",click:()=>this.cb.openPerson(s[0])},`Open ${r.people.find(c=>c.id===s[0])?.name??"person"}`)]):""]),p=this.el.clientHeight||380;this.map.easeTo({center:o,offset:[0,Math.min(140,p*.32)],duration:300}),this.popup=new this.gl.Popup({offset:[a[0],a[1]-18],anchor:"bottom",closeButton:!1,focusAfterOpen:!1,maxWidth:"300px",className:"dl-popup"}).setLngLat(o).setDOMContent(d).addTo(this.map)}};function Xt(n,t,o=!0){let a=[["online","Online now"],["24h","24h"],["7d","7 days"],["30d","30 days"]],r=e("div",{class:"dl-seg",role:"tablist"});for(let[i,s]of a)i==="online"&&!o||r.appendChild(e("button",{type:"button",role:"tab",class:i===n?"on":"","data-v":i,click:()=>{r.querySelectorAll("button").forEach(l=>l.classList.toggle("on",l.dataset.v===i)),t(i)}},s));return r}var Br={connect:"ok",disconnect:"",roam:"",device_added:"ok",device_removed:"",person_added:"",person_removed:"",paused:"warn",resumed:"ok",paused_all:"warn",resumed_all:"ok",portal_blocked:"bad",person_changed:"",devices_removed:"warn"},Or={devices_removed:"trash",link_changed:"link",person_added:"plus",person_removed:"trash",person_changed:"edit",paused:"pause",resumed:"play",paused_all:"pause",resumed_all:"play"};function jr(n,t){return t.device?n.people.flatMap(a=>a.devices).find(a=>a.id===t.device)?.kind??t.dkind??"other":Or[t.type]??"activity"}function Mn(n,t){let o=n.people.find(x=>x.id===t.person),a=o?.name??t.pname??t.person??"",r=o?.devices.find(x=>x.id===t.device)?.name??t.dname??"",i=x=>e("b",{},x),s=x=>e("span",{class:"dl-muted"},x),l=x=>e("span",{class:"dl-mono"},x),d=x=>t.hosts?.[x]?[e("span",{class:"dl-ev-host"},[e("b",{},t.hosts[x]),e("span",{class:"dl-faint"},` (${x})`)])]:[l(x)],p=x=>e("span",{class:"dl-ev-kind"},`${x} `),c=r?`${a} · ${r}`:a,m=eo(t),v=m||r||"a device",h=x=>[e("span",{class:"dl-you"},"You"),s(` ${x} `)];if(Le(t)==="admin")switch(t.type){case"device_added":return[...h("added"),p("device"),i(v),s(" for "),i(a)];case"device_removed":return[...h("removed"),p("device"),i(v),s(" from "),i(a)];case"paused":return[...h("paused"),p("person"),i(a)];case"resumed":return[...h("resumed"),p("person"),i(a)];case"device_changed":{let x=m.startsWith("renamed from ");return[...h(x?"renamed":m),p("device"),i(r||"a device"),s(" of "),i(a),...x?[s(` · was ${m.slice(13)}`)]:[]]}case"device_keys":return[...h("issued new keys for"),p("device"),i(v),s(" of "),i(a),s(" · it needs its new configuration")];case"link_changed":return[...h("issued a new link for"),p("person"),i(a),s(" · the old link stopped working")];case"paused_all":return[e("span",{class:"dl-you"},"You"),s(" paused everyone")];case"resumed_all":return[e("span",{class:"dl-you"},"You"),s(" resumed everyone")]}switch(t.type){case"connect":return[p("Device"),i(c),s(" connected"),...t.detail?[s(" from "),...d(t.detail)]:[],...t.where?[s(` · ${t.where}`)]:[]];case"disconnect":return[p("Device"),i(c),s(" went offline")];case"roam":return[p("Device"),i(c),s(" changed network "),...(t.detail??"").split(" → ").flatMap((x,R)=>R?[s(" → "),...d(x)]:d(x))];case"device_added":return[p("Person"),i(a),s(" added "),p("device"),i(v),...Le(t)==="portal"?[s(" on their portal")]:[]];case"device_removed":return[p("Person"),i(a),s(" removed "),p("device"),i(v),...Le(t)==="portal"?[s(" on their portal")]:[]];case"device_keys":return[p("Person"),i(a),s(" issued new keys for "),p("device"),i(v),s(" on their portal")];case"person_added":return[...h("added"),p("person"),i(t.detail??a)];case"person_removed":return[...h("removed"),p("person"),i(t.detail??a)];case"person_changed":return[...h("changed"),p("person"),i(a),...m?[s(` · ${m.replace(/_/g," ")}`)]:[]];case"paused":return[p("Person"),i(a),s(` paused — ${t.detail??""}`)];case"resumed":return[p("Person"),i(a),s(" resumed"),...t.detail&&t.detail!=="active"?[s(` — ${t.detail}`)]:[]];case"paused_all":return[s("Everyone paused")];case"resumed_all":return[s("Everyone resumed")];case"portal_blocked":return[e("b",{class:"dl-sys-src"},"Personal portal"),s(" blocked "),l(t.detail??""),s(" for 15 min after too many wrong codes")];case"devices_removed":return[p("Person"),i(a),s(" — all devices removed, end date reached")];default:return[s(`${t.type}${t.detail?`: ${t.detail}`:""}`)]}}var Ur={portal_blocked:["globe","bad"]};function Wr(n,t){if(n.servers.length<2||!t.person)return"";let o=n.people.find(r=>r.id===t.person),a=o&&n.servers.find(r=>r.id===o.server);return a?e("span",{class:"dl-ev-srv",title:"Server"},a.name):""}function Ye(n,t,o={}){let a=Ur[t.type],r=Le(t);return e("div",{class:`dl-row${r==="admin"?" dl-ev-by-admin":a?` dl-ev-by-system ${a[1]}`:""}`},[r==="admin"?e("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},g("admin")):a?e("span",{class:"dl-ev-tile sys"},g(a[0])):e("span",{class:`dl-ev-tile ev ${Br[t.type]??""}`},g(jr(n,t))),e("span",{class:"dl-row-main"},Mn(n,t)),o.server===!1?"":Wr(n,t),e("span",{class:"dl-faint dl-nowrap",title:new Date(t.ts*1e3).toLocaleString()},o.time??le(t.ts,n.now))])}var Gr={info:"",up:"ok",down:"warn",repair:"warn",error:"bad"},qr={awg:"tunnel",dawnline:"sunrise",portal:"globe"};function en(n,t,o,a){let r=n.by==="admin",i=e("div",{class:`dl-row dl-slog-row ${r?"dl-ev-by-admin":`dl-ev-by-system ${Gr[n.level]??""}`}${n.detail?" has-detail":""}`},[r?e("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},g("admin")):e("span",{class:"dl-ev-tile sys",title:n.level},g(qr[n.src]??"zap")),e("span",{class:"dl-row-main"},r?[e("span",{class:"dl-you"},"You"),e("span",{class:"dl-muted"},` ${n.msg} `),n.kind?e("span",{class:"dl-ev-kind"},`${n.kind} `):"",n.who?e("b",{},n.who):"",n.note?e("span",{class:"dl-muted"},` · ${n.note}`):"",n.detail?e("span",{class:`dl-slog-more${t?" open":""}`},g("chevron")):"",n.detail&&t?e("pre",{class:"dl-slog-detail"},n.detail):""]:[n.src==="awg"&&n.who&&n.who!=="AmneziaWG"?e("span",{class:"dl-ev-kind"},"Server "):"",e("b",{class:"dl-sys-src",title:_t[n.src]??n.src},n.who??_t[n.src]??n.src)," ",e("span",{class:"dl-muted"},n.msg),n.detail?e("span",{class:`dl-slog-more${t?" open":""}`},g("chevron")):"",n.detail&&t?e("pre",{class:"dl-slog-detail"},n.detail):""]),e("span",{class:"dl-faint dl-nowrap",title:new Date(n.ts*1e3).toLocaleString()},a)]);return n.detail&&i.addEventListener("click",s=>{s.target.closest("pre")||o()}),i}function Po(n){let t=new Date(n*1e3),o=new Date,a=new Date;return a.setDate(o.getDate()-1),t.toDateString()===o.toDateString()?"Today":t.toDateString()===a.toDateString()?"Yesterday":t.toLocaleDateString("en-GB",{weekday:"long",day:"numeric",month:"long"})}var vt=n=>lt(n).toLocaleDateString("en-GB",{day:"numeric",month:"short"});function tn(n,t,o){let a=n.slice(-15),r=a[a.length-1],i=r&&t-r[0]<180,s=i?r[2]:0,l=i?r[1]:0,[d,p]=o,c=200,m=40,v=Math.max(1,...a.map(w=>Math.max(w[1],w[2]))),h=w=>a.map((H,S)=>`${a.length>1?S/(a.length-1)*c:c},${m-2-H[w]/v*(m-6)}`),x=h(2),R=h(1),$=a.length>1?qe(``):e("div",{class:"dl-speed-wait"},[e("i"),e("span",{},"Collecting… 1 point a minute")]),j=(w,H,S,T)=>e("div",{class:"dl-speed-col"},[e("span",{class:"dl-sub"},[e("span",{class:S},H),` ${w}`]),e("span",{class:"dl-speed-val"},Pe(T))]);return a.length>1&&ue($,()=>{let w=a[a.length-1];return[e("div",{class:"dl-tip-title"},new Date(w[0]*1e3).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})),e("div",{},`↓ ${Pe(w[2])} · ↑ ${Pe(w[1])}`)]}),e("div",{class:"dl-bento-tile"},[e("div",{class:"dl-bento-head"},[e("span",{class:"dl-metric-label"},"Speed now"),e("span",{class:"dl-sub"},"last 15 min")]),e("div",{class:"dl-speed-cols"},[j("Download","↓","dl-dn",s),j("Upload","↑","dl-up",l)]),$,e("div",{class:"dl-speed-today"},[e("span",{},["Today ",e("b",{},te(d+p))]),e("span",{},[e("span",{class:"dl-dn"},"↓"),` ${te(p)} `,e("span",{class:"dl-up"},"↑"),` ${te(d)}`])])])}function nn(n,t){let o=n.slice(-30),a=o.map(d=>d.rx+d.tx),r=Math.max(1,...a),i=a.reduce((d,p)=>d+p,0),s=a.reduce((d,p,c)=>p>a[d]?c:d,0),l=e("div",{class:"dl-bento-bars"},o.map((d,p)=>{let c=a[p],m=e("i",{class:p===o.length-1?"hi":"",style:`height:${Math.max(4,c/r*100)}%`});return ue(m,()=>[e("div",{class:"dl-tip-title"},p===o.length-1?`Today · ${vt(d.day)}`:vt(d.day)),e("div",{},te(c)),e("div",{class:"dl-muted dl-mono"},`↓ ${te(d.tx)} ↑ ${te(d.rx)}`)]),m}));return e("div",{class:"dl-bento-tile month"},[e("div",{class:"dl-bento-head"},[e("span",{},[e("span",{class:"dl-metric-label"},"Last 30 days"),e("b",{class:"dl-bento-total"},te(i))]),a[s]>0?e("span",{class:"dl-sub"},`peak ${te(a[s])} · ${vt(o[s].day)}`):""]),o.length?l:e("p",{class:"dl-muted"},"No traffic yet."),e("div",{class:"dl-bento-head"},[e("span",{class:"dl-sub"},o.length?vt(o[0].day):""),e("span",{class:"dl-sub"},t),e("span",{class:"dl-sub"},"today")])])}function Do(n){let t=n.slice(-30),o=t.map(r=>r.rx+r.tx),a=Math.max(1,...o);return e("div",{class:"dl-dbars"},t.map((r,i)=>{let s=e("i",{class:`${o[i]?"":"zero"}${i===t.length-1?" hi":""}`});return s.style.height=`${Math.max(8,o[i]/a*100)}%`,ue(s,()=>[e("div",{class:"dl-tip-title"},i===t.length-1?`Today · ${vt(r.day)}`:vt(r.day)),e("div",{},te(o[i]))]),s}))}var Ao={apply:"Repair",sync:"Reload devices",restart:"Restart service",netrestart:"Restart network",updates:"Open Components"};async function on(n){return n==="netrestart"&&!await ne("Restart the network?","Every interface restarts. Connections drop for a few seconds.","Restart network")?null:await U(()=>E.healthFix(n),"Done")??null}function Pn(n,t,o,a="action"){let r=n.fix;return r?r.startsWith("install:")?D("Install",()=>Lo(r.slice(8),o),a):r==="updates"?e("a",{class:`cbi-button cbi-button-${a}`,href:L.url("admin/network/dawnline/updates")},Ao.updates):D(Ao[r]??"Fix",()=>t(r),a):""}function Fr(n){return/^(awg|up_|peers_|fw_|reply_|port_|subnet_)/.test(n)?"shield":/^(portal|cert)/.test(n)?"link":/^(ep_|home_|resolver)/.test(n)?"globe":n==="clock"?"clock":n==="agent"?"activity":n==="nft"?"lock":"alert"}function zo(n,t,o,a=3){let r=n.filter(s=>s.status==="error"||s.status==="warn").sort((s,l)=>s.status===l.status?0:s.status==="error"?-1:1);if(!r.length)return"";let i=r.length-a;return e("div",{class:"dl-list dl-notices"},[...r.slice(0,a).map(s=>tt(Fr(s.id),s.status==="error"?"bad":"warn",s.problem??s.title,s.detail,Pn(s,t,o,s.status==="error"?"positive":"neutral"))),i>0?e("a",{class:"dl-row dl-notices-more",href:L.url("admin/network/dawnline/diagnostics")},[`${i} more in Diagnostics`,e("span",{class:"dl-spacer"}),"→"]):""])}function Kr(n){let t=[],o=(s,l)=>e("a",{href:s},l),a=Ne(n.series),r=!!n.awg_state&&!n.awg_state.ok;for(let s of n.servers)s.enabled&&s.blocked?t.push({tone:"bad",text:[`${s.name} ${s.blocked}. `,o(L.url("admin/network/dawnline/diagnostics"),"Open Diagnostics")]}):s.enabled&&!s.up&&!r&&t.push({tone:"bad",text:[`Tunnel ${s.ifname} is down. `,o(L.url("admin/network/dawnline/diagnostics"),"Open Diagnostics")]});n.settings.paused_all&&t.push({tone:"warn",text:["Everyone is paused."]});for(let s of n.people)if(s.state==="quota")t.push({tone:"warn",text:[o(Te(s.id),s.name)," reached the data limit."]});else if(s.state==="expired")t.push({tone:"warn",text:[o(Te(s.id),s.name),"’s access has ended."]});else{let l=Xe(s.expires,a);l!=null&&l>=0&&l<=Math.max(s.expire_warn,3)&&t.push({tone:"",text:[o(Te(s.id),s.name),`’s access ends in ${l} day${l===1?"":"s"}.`]}),s.quota_limit&&s.quota_used>=s.quota_limit*.9&&t.push({tone:"",text:[o(Te(s.id),s.name)," has used 90% of the data limit."]})}let i=n.people.flatMap(s=>s.devices.filter(l=>l.config_stale).map(l=>[s,l]));return i.length&&t.push({tone:"warn",text:i.length===1?[o(Te(i[0][0].id,i[0][1].id),`${i[0][0].name} · ${i[0][1].name}`)," needs its configuration again."]:[`${i.length} devices need their configuration again (networks or DNS changed).`]}),n.servers.some(s=>s.lan_like)&&n.like_home.error&&t.push({tone:"warn",text:[`Internet through the LAN is off: ${n.like_home.error} `,o(L.url("admin/network/dawnline/diagnostics"),"Details")]}),n.settings.portal_enabled||t.push({tone:"",text:["The personal portal is off. ",o(L.url("admin/network/dawnline/settings"),"Turn on")]}),t}var an=class{constructor(t,o){this.srvId=t;this.go=o;this.el=e("div",{class:"dl-srvov"});this.map=null;this.range="online";this.parts={};this.healthAt=0}mount(t){this.st=Tt(t,this.srvId);for(let o of["health","bento","side","activity"])this.parts[o]=e("div",{});return dom.content(this.el,[this.parts.health,this.parts.bento,this.mapCard(),e("div",{class:"dl-grid2"},[this.parts.activity,this.parts.side])]),this.paint(),this.loadHealth(),this.el}update(t,o=!1){this.st=Tt(t,this.srvId),this.paint(o),this.map?.update(this.mapData()),Date.now()-this.healthAt>6e4&&this.loadHealth()}async loadHealth(){this.healthAt=Date.now();let t=await E.health().catch(()=>null);if(!t)return;let o=()=>void this.loadHealth(),a=async r=>{await on(r)&&(o(),r==="netrestart"&&setTimeout(o,5e3))};_e(this.parts.health,zo(t.checks,r=>void a(r),o),!0)}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now}}mapCard(){let t=this.st,o=e("div",{class:"dl-panel-head pad"},[e("div",{class:"dl-stack"},[e("h3",{},"Where people connect from"),e("span",{class:"dl-sub"},"City-level, from the client IP · locations cached on the router")]),e("span",{class:"dl-spacer"}),Xt(this.range,i=>{this.range=i,this.map?.setRange(i)})]);if(!t.geo.enabled)return e("div",{class:"dl-panel flush"},[o,e("div",{class:"dl-map-off"},["Locations are off. ",e("a",{href:L.url("admin/network/dawnline/settings")},"Turn them on in Settings"),"."])]);this.map=new gt({openPerson:i=>location.href=Te(i),openDevice:(i,s)=>location.href=Te(i,s)},this.range);let a=e("div",{class:"dl-map-legend"},[e("span",{},[e("i",{class:"dot ok"}),"Online"]),e("span",{},[e("i",{class:"dot"}),"Seen recently"]),e("span",{},[e("i",{class:"line"}),"Live tunnel"])]),r=e("div",{class:"dl-map-wrap"},[this.map.el,a]);return requestAnimationFrame(()=>this.map.mount(this.mapData())),e("div",{class:"dl-panel flush"},[o,r])}paint(t=!1){let o=this.st,a=o.servers[0],r=o.people.reduce((l,d)=>l+Math.max(0,d.device_limit-d.devices.length),0);_e(this.parts.bento,e("div",{class:"dl-bento"},[this.onlineTile(),this.speedTile(),Re(a).overviewTile(a),this.monthTile(r)]),t);let i=Kr(o);_e(this.parts.side,e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Needs attention"),e("span",{class:"dl-spacer"}),e("a",{href:L.url("admin/network/dawnline/diagnostics")},"Health")]),i.length?i.slice(0,8).map(l=>e("div",{class:"dl-attn-item dl-row"},[e("span",{class:`dl-ev-dot ${l.tone}`}),e("span",{},l.text),l.action??""])):e("div",{class:"dl-row dl-muted"},[g("check"),"All good. Nothing needs you right now."])]),t);let s=[...o.events].reverse().slice(0,8);_e(this.parts.activity,e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-spacer"}),e("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},"View all")]),s.length?s.map(l=>Ye(o,l)):e("div",{class:"dl-row dl-muted"},"Nothing yet. Connections, new devices and pauses appear here.")]),t)}onlineTile(){let t=this.st,o=12,a=$=>$.spark[$.spark.length-1]??0,r=$=>t.geo.points.find(j=>j.device===$.id&&j.city)?.city,i=$=>/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test($.endpoint??""),s=$=>(i($)?"home":r($))??"",l=$=>[...t.events].reverse().find(j=>j.type==="connect"&&j.device===$.id)?.ts??0,d=t.people.map($=>({p:$,devs:$.devices.filter(j=>j.online).sort((j,w)=>a(w)-a(j))})).filter($=>$.devs.length).sort(($,j)=>j.devs.reduce((w,H)=>w+a(H),0)-$.devs.reduce((w,H)=>w+a(H),0)),p=d.length<=2,c=({p:$,devs:j})=>{let w=j.map(l).filter(Boolean),H=w.length?Math.min(...w):0,S=($.rate??[]).slice(-15),T=S[S.length-1],b=T&&t.now-T[0]<180?T:null,A=200,u=30,f=Math.max(1,...S.map(W=>Math.max(W[1],W[2]))),N=W=>S.map((q,C)=>`${S.length>1?C/(S.length-1)*A:A},${u-2-q[W]/f*(u-6)}`),P=S.length>1?qe(``):"",I=!b||b[1]<64&&b[2]<64,J=$.access==="both"?["home","globe"]:$.access==="lan"?["home"]:["globe"];return[e("div",{class:"dl-hc"},[e("div",{class:"dl-hc-head"},[e("span",{class:"dl-onl-av sm"},Oe($.name)),e("span",{class:"dl-stack"},[e("b",{},$.name),e("span",{class:"dl-hc-since"},H?`online for ${le(H,t.now).replace(" ago","")}`:"online")]),e("span",{class:"dl-hc-reach"},J.map(W=>e("span",{class:`dl-ibadge ${W==="home"?"lan":"inet"}`},g(W))))]),e("div",{class:"dl-hc-speed"},[e("div",{class:"dl-hc-speed-row"},I?[e("span",{class:"dl-faint"},"Idle right now")]:[e("span",{},[e("span",{class:"dl-dn"},"↓"),` ${Pe(b[2])}`]),e("span",{},[e("span",{class:"dl-up"},"↑"),` ${Pe(b[1])}`]),e("span",{class:"dl-spacer"}),e("span",{class:"dl-faint"},"15 min")]),P]),e("div",{class:"dl-hc-devs"},j.map(W=>e("span",{class:"dl-hc-dev"},[g(W.kind),[W.name,s(W)].filter(Boolean).join(" · ")]))),e("div",{class:"dl-hc-foot"},[e("span",{class:"dl-faint"},`${te(j.reduce((W,q)=>W+a(q),0))} today · ${te($.month[0]+$.month[1])} this month`)])])]},m=$=>{let{p:j,devs:w}=$,H=e("span",{class:"dl-onl-dev"},w.length>1?String(w.length):g(w[0].kind)),S=e("a",{class:`dl-onl-p${p?"":" sm"}`,href:Te(j.id),"aria-label":`${j.name}, online`},[e("span",{class:"dl-onl-av"},[Oe(j.name),H]),p?e("span",{class:"dl-onl-name"},j.name):"",p?e("span",{class:"dl-onl-meta"},[...w.slice(0,3).map(T=>g(T.kind)),w.length>3?`+${w.length-3}`:"",s(w[0])?e("span",{},` · ${s(w[0])}`):""]):""]);return ue(S,()=>c($)),S},v=e("b",{class:`dl-onl-count${d.length?"":" none"}`},String(d.length)),h=d.reduce(($,j)=>$+j.devs.length,0);d.length&&ue(v,()=>[`${d.length} ${d.length===1?"person":"people"} · ${h} device${h===1?"":"s"}`]);let x=d.length>o?d.slice(0,o-1):d,R=t.people.flatMap($=>$.devices.map(j=>({p:$,d:j}))).filter($=>$.d.handshake).sort(($,j)=>j.d.handshake-$.d.handshake)[0];return e("div",{class:"dl-bento-tile online"},[e("div",{class:"dl-bento-head"},[e("span",{class:"dl-metric-label"},"Online"),v]),d.length?e("div",{class:`dl-onl-row${p?"":" grid"}`},[...x.map(m),d.length>o?e("a",{class:"dl-onl-p sm more",href:`${L.url("admin/network/dawnline/server")}?server=${encodeURIComponent(this.srvId)}§ion=people&filter=online`,title:"Everyone online",click:$=>{this.go&&($.preventDefault(),this.go("people","online"))}},[e("span",{class:"dl-onl-av"},`+${d.length-x.length}`)]):""]):e("div",{class:"dl-onl-empty"},[e("span",{},"Nobody is connected"),R?e("span",{class:"dl-sub"},`Last: ${R.p.name}, ${le(R.d.handshake,t.now)}`):e("span",{class:"dl-sub"},"No device has connected yet")])])}speedTile(){return tn(this.st.servers[0]?.rate??[],this.st.now,this.st.totals.today)}monthTile(t){let o=this.st.totals,a=this.st.people.filter(r=>r.state!=="active").length;return nn(this.st.series,`${o.people} ${o.people===1?"person":"people"}${a?` · ${a} paused`:""} · ${t} device slot${t===1?"":"s"} free`)}};var No=[["overview","Overview"],["people","People"],["connection","Connection"],["access","Access"],["awg",""]],Jr={general:"connection",network:"connection",interfaces:"access",advanced:"awg",disguise:"awg",tunnel:"awg",core:"awg"},Dn=(n,t)=>{let o=new URLSearchParams;n&&o.set("server",n),t&&t!=="overview"&&o.set("section",t);let a=o.toString();return`${L.url("admin/network/dawnline/server")}${a?`?${a}`:""}`},At=class{constructor(){this.noFooter=!0;this.root=e("div",{class:"dl-root"});this.section="overview";this.srvId="";this.ov={};this.pp={};this.tabsEl=e("div",{});this.headEl=e("div",{});this.secEl=e("div",{});this.bodyEl=e("div",{class:"dl-srvbody"})}async load(){let t=await E.status(31),o=t.servers.length?null:await E.setupDefaults();return[t,o]}render([t,o]){if(this.st=t,!t.servers.length&&o)return this.wizard(o);let a=new URLSearchParams(location.search),r=a.get("section")??"",i=Jr[r]??r;return No.some(([s])=>s===i)&&(this.section=i),this.srvId=(t.servers.find(s=>s.id===a.get("server"))??t.servers[0]).id,dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint(),this.poller=Ke({fetch:()=>E.status(31),every:10,active:()=>this.section==="overview"&&this.root.isConnected,apply:(s,l)=>{s.servers.length&&(this.st=s,this.paintHead(l),this.ov[this.current().id]?.update(s,l))}}),this.root}paintHead(t=!1){_e(this.headEl,this.head(this.current()),t),(!t||!ft(this.tabsEl))&&this.paintTabs()}async refreshStatus(){let t=await E.status(31).catch(()=>null);return t?.servers.length?(this.st=t,this.paintHead(),t):null}current(){return this.st.servers.find(t=>t.id===this.srvId)??this.st.servers[0]}async refresh(){let t=await E.status(31).catch(()=>null);t&&(this.st=t,t.servers.length?this.paint():location.href=Dn())}paint(){this.paintTabs(),dom.content(this.headEl,this.head(this.current())),this.paintSections(),this.showSection(this.section)}paintTabs(){let t=this.current();dom.content(this.tabsEl,e("div",{class:"dl-srvtabs",role:"tablist","aria-label":"Servers"},[...this.st.servers.map(o=>e("button",{type:"button",role:"tab",class:`dl-srvtab${o.id===t.id?" on":""}`,"aria-selected":o.id===t.id?"true":"false",click:()=>{o.id!==this.srvId&&(this.srvId=o.id,this.paint())}},[e("i",{class:`dot ${o.up?"ok":"bad"}`}),e("b",{},o.name)])),e("button",{type:"button",class:"dl-srvtab add",click:()=>this.addServer()},[g("plus"),"Add server"])]))}paintSections(){let t=Re(this.current());dom.content(this.secEl,e("div",{class:"dl-seg dl-srvsections",role:"tablist","aria-label":"Server"},No.map(([o,a])=>e("button",{type:"button",role:"tab","data-section":o,class:o===this.section?"on":"","aria-selected":o===this.section?"true":"false",click:()=>this.showSection(o)},o==="awg"?t.label:a))))}go(t,o){let a=this.pp[this.current().id];if(o&&a)a.filter=o,a.el&&a.decorate();else if(o){let r=this.pp[this.current().id]=new at;r.filter=o}this.showSection(t),window.scrollTo({top:0,behavior:"smooth"})}detachKept(){let t=[...Object.values(this.ov).map(o=>o.el),...Object.values(this.pp).map(o=>o.el)];for(let o of t)o&&this.bodyEl.contains(o)&&o.remove()}showSection(t){this.section=t,this.secEl.querySelectorAll("[data-section]").forEach(s=>{let l=s.dataset.section===t;s.classList.toggle("on",l),s.setAttribute("aria-selected",l?"true":"false")});let o=this.st,a=this.current(),i={overview:()=>{let s=this.ov[a.id];return s?(s.update(o),s.el):(this.ov[a.id]=new an(a.id,(l,d)=>this.go(l,d))).mount(o)},people:()=>{var p,c;let s=this.pp[a.id];if(s?.el)return s.update(),s.el;let l=e("div",{},e("p",{class:"dl-muted"},"Loading people…"));return((p=this.pp)[c=a.id]??(p[c]=new at)).embed(o,a.id).then(m=>{l.isConnected?dom.content(l,m):l.replaceChildren(m)}).catch(m=>{delete this.pp[a.id],dom.content(l,e("p",{class:"dl-muted"},`Couldn't show people: ${ve(m)}`))}),l},connection:()=>this.connection(a),access:()=>this.access(a),awg:()=>this.awg(a)}[t]();this.detachKept(),dom.content(this.bodyEl,i)}head(t){let o=this.st,a=(l,d)=>e("span",{class:"dl-addrbar-seg"},[g(l),...d]),r=t.endpoint||"—",i=!t.enabled||o.settings.paused_all,s=e("div",{class:"dl-actions"},[i?D([g("play")," Turn on"],async()=>{o.settings.paused_all&&!await U(()=>E.pauseAll(!1))||(t.enabled?await this.refresh():await this.save(t,{enabled:"1"},"Server turned on"))},"positive"):""]);return e("div",{class:"dl-srvpagehead"},[e("div",{class:"dl-title-row"},[e("h2",{class:"dl-h1"},t.name),e("span",{class:`dl-pill ${t.enabled?t.up?"ok":"bad":"off"}`},t.enabled?t.up?"Running":t.blocked?"Can’t start":"Not running":"Turned off"),o.settings.paused_all&&t.enabled?e("span",{class:"dl-pill warn"},"Off"):"",e("span",{class:"dl-spacer"}),s]),e("div",{class:"dl-addrbar"},[e("button",{type:"button",class:"dl-addrbar-seg main",title:"Copy address",click:()=>pe(r,"Address copied")},[g("globe"),e("span",{class:"dl-mono"},r),g("copy")]),a("tunnel",[e("span",{class:"dl-mono"},`${Re(t).label} :${t.port}`)]),t.up?a("clock",[`up ${st(t.uptime)}`]):""]),t.blocked?e("div",{class:"dl-note warn"},[g("alert"),e("span",{},`${t.name} ${t.blocked}.`)]):""])}async save(t,o,a="Saved"){await U(()=>E.serverUpdate(t.id,o),a)&&await this.refresh()}connection(t){let o=ae(t.name,{placeholder:"Home"}),a=ae(t.endpoint,{placeholder:"vpn.example.com",class:"cbi-input-text dl-mono"}),r=ae(t.dns.join(", "),{placeholder:"This router (recommended)",class:"cbi-input-text dl-mono"}),i=this.st.people.filter(l=>l.server===t.id).length,s=D(t.enabled?"Turn off":"Turn on",async()=>{t.enabled&&!await ne(`Turn off ${t.name}?`,`The tunnel stops and ${i} ${i===1?"person is":"people are"} disconnected until you turn it back on. Nothing is deleted.`,"Turn off",!0)||await this.save(t,{enabled:t.enabled?"0":"1"},t.enabled?"Server turned off":"Server turned on")},t.enabled?"negative":"positive");return e("div",{class:"dl-stack gap16"},[kt("Connection",[e("p",{class:"dl-muted"},"The name people see, where devices find the router, and DNS. The port is on AmneziaWG."),he("router","Server","What people see",[X("Name",o,"Shown to people in their portal and apps.")]),he("globe","Devices connect to","Where the router answers from the internet",[X("Public address",a,"Hostname or IP of the router on the internet. A DDNS name keeps links working when your IP changes. It must not go through Cloudflare: use a DNS-only name or an IP.")]),he("file","For every device","Changing it marks devices “Update config” until they import again",[X("DNS for devices",r,"Empty = this router, which sends each query where your home network would.")])],[e("span"),D("Save",()=>this.save(t,{name:o.value,endpoint:a.value,dns:r.value}),"positive")]),kt("Danger zone",[e("div",{class:"dl-setrow"},[e("div",{class:"dl-stack"},[e("span",{class:"dl-setrow-label"},t.enabled?"Turn off this server":"This server is off"),e("span",{class:"dl-sub"},t.enabled?"Stops the tunnel and disconnects everyone on it. Settings and people are kept.":"Nobody can connect. Turn it on to bring the tunnel back.")]),e("div",{class:"dl-setrow-ctl"},s)]),e("div",{class:"dl-setrow"},[e("div",{class:"dl-stack"},[e("span",{class:"dl-setrow-label"},"Remove server"),e("span",{class:"dl-sub"},`Removes the tunnel, its firewall rules and ${i} ${i===1?"person":"people"} with all their devices. A backup is made first.`)]),e("div",{class:"dl-setrow-ctl"},D([g("trash")," Remove"],()=>this.remove(t),"negative"))])],[],"danger")])}access(t){let o=Tn(this.st,t),a=To(t,this.st,async()=>{let r=await this.refreshStatus();if(!r)return;let i=r.servers.find(l=>l.id===t.id)??t;a.update(r);let s=Tn(r,i);o.replaceWith(s),o=s});return e("div",{class:"dl-stack gap16"},[a.el,e("div",{class:"dl-health-cols"},[o,yo(this.st,t)])])}awg(t){let o={st:this.st,save:(a,r)=>this.save(t,a,r),refresh:()=>this.refresh()};return e("div",{class:"dl-stack gap16"},[Re(t).settingsCard(o,t)])}async addServer(){let t=await U(()=>E.setupDefaults());t&&dom.content(this.root,this.wizard(t,!0,()=>{dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint()}))}async remove(t){let o=this.st.people.filter(a=>a.server===t.id);oe(`Remove ${t.name}?`,[e("p",{},`This removes the tunnel, its firewall rules and ${o.length} ${o.length===1?"person":"people"} with all their devices. A backup is made first.`)],[ie()," ",D("Remove",async()=>{se(),await U(()=>E.serverDelete(t.id),"Server removed")&&setTimeout(()=>{location.href=Dn()},800)},"negative")])}wizard(t,o=!1,a){let r={id:t.id,name:t.name,endpoint:t.endpoint,port:t.port,subnet:t.subnet,preset:"standard",portal:!1,portal_port:t.portal_port||8443,lan_like:!0,lan_zone:t.lan_zone,wan_zone:t.wan_zone},i=0,s=e("div",{class:"dl-wizard"}),l=($,j={})=>{let w=ae(String(r[$]),j);return w.addEventListener("input",()=>{r[$]=$==="port"||$==="portal_port"?Number(w.value):w.value.trim()}),w},d={id:"server",title:"Server",render:()=>e("div",{class:"dl-wizard-groups"},[e("p",{class:"dl-muted"},"Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes."),he("router","Server","What people see",[X("Name",l("name"),"Shown to people in their portal and apps.")]),he("globe","Devices connect to","Where the router answers from the internet",[X("Public address",l("endpoint",{placeholder:"vpn.example.com",class:"cbi-input-text dl-mono"}),"Hostname or IP address of your router on the internet. Not through Cloudflare: use a DNS-only name or an IP.")])]),check:()=>r.endpoint?null:"Fill in the public address."},p={id:"awg",title:"AmneziaWG",render:()=>e("div",{class:"dl-wizard-groups"},[he("globe","Listening","Where devices reach AmneziaWG from the internet",[X("UDP port",l("port",{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),"Opened on the WAN firewall automatically. A random high port is fine.")]),he("network","Tunnel network","Addresses devices get inside the tunnel",[X("Tunnel subnet",l("subnet",{class:"cbi-input-text dl-mono"}),`Must not overlap your networks (${t.taken.join(", ")||"none found"}).`)]),he("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Gt(t.awg,r.preset,$=>r.preset=$,void 0,t.awg_state?.tools!==!1)])]),check:()=>!r.port||!r.subnet?"Fill in the UDP port and subnet.":null},c={id:"portal",title:"Portal",render:()=>{let $=l("portal_port",{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),j=X("Listening port",$,"TCP port on WAN for the portal; the whole port belongs to it.");j.hidden=!r.portal;let w=xe([["off","Off"],["on","On"]],r.portal?"on":"off",{label:"Personal portal",onChange:H=>{r.portal=H==="on",j.hidden=!r.portal}});return e("div",{class:"dl-wizard-groups"},[he("home","Internet like a home device","How devices reach the internet",[X("Through the home network",fe(r.lan_like,"Internet like a home device",H=>r.lan_like=H),"Whatever handles home traffic on this router (proxies, filters, DNS) handles theirs too. Change it later under Servers → Access.")]),he("link","Personal portal","A page where each person adds their own devices with their personal link",[X("Portal",w,"Off: only you add devices, from LuCI. On: people manage their devices within the limits you set."),j])])}},m=()=>[d,p,o?null:c].filter($=>$!=null),v=t.awg_state,h=v?.missing??[],x=h.length?e("div",{class:"dl-list dl-notices"},[tt("shield","bad","AmneziaWG isn’t installed",`The tunnel needs ${h.join(" and ")}. Install the build made for this firmware, then create the server.`,D("Install",()=>Qt(()=>location.reload()),"positive"))]):v&&!v.loaded?e("div",{class:"dl-list dl-notices"},[tt("shield","warn","AmneziaWG’s kernel module doesn’t load on this firmware","Try another build in Components, or update OpenWrt. The server can’t start until it loads.",e("a",{class:"cbi-button cbi-button-neutral",href:L.url("admin/network/dawnline/updates")},"Open Components"))]):"",R=()=>{let $=m();i>=$.length&&(i=$.length-1),dom.content(s,[e("h2",{},o?"Add a server":"Set up Dawnline"),x,e("div",{class:"dl-steps"},$.map((j,w)=>e("span",{class:`dl-step${w===i?" current":w0?D("Back",()=>{i--,R()}):a?D("Cancel",a):"",e("span",{class:"dl-spacer"}),i<$.length-1?D("Next",()=>{let j=$[i].check?.();if(j){Z(j,"warning");return}i++,R()},"positive"):D("Create server",async()=>{for(let w of $){let H=w.check?.();if(H){Z(H,"warning");return}}let j=await U(()=>E.serverCreate(r.id,r.name,t.ifname,r.port,r.subnet,r.endpoint,t.mtu,r.preset,r.lan_zone,r.wan_zone,r.lan_like,o?void 0:r.portal,o?void 0:r.portal_port),"Server created");j&&setTimeout(()=>{location.href=Dn(j.id)},1500)},"positive",{disabled:h.length>0,title:h.length?"Install AmneziaWG first":null})])])};return R(),s}};function Qe(n){let t={el:n(),refresh(){let o=n();t.el.replaceWith(o),t.el=o}};return t}function Me(n,t,o,a,r="",i=[]){return e("section",{class:`dl-setsec ${r}`,id:`dl-set-${n}`},[e("div",{class:"dl-setsec-body"},[i.length?e("div",{class:"dl-setsec-head"},[e("h3",{},t),e("span",{class:"dl-spacer"}),...i]):e("h3",{},t),...o]),a.length?e("div",{class:"dl-setsec-foot"},a):""])}function Ro(n){let t=n.filter(r=>r.status!=="skip"),o=t.filter(r=>r.status==="error"||r.status==="warn"),a=t.some(r=>r.status==="error")?"error":o.length?"warn":"ok";return{bad:o,worst:a}}function Ho(n){let t=n.d.settings,o=n.d.effective,a=n.d.cert,r=fe(o.portal_enabled,"Enable portal"),i=ae(t.portal_port,{placeholder:"8443",inputmode:"numeric",class:"cbi-input-text dl-w-port"}),s=ae(t.portal_title,{placeholder:"Dawnline"}),l=ae(t.portal_redirect,{placeholder:"Show “Not found”",class:"cbi-input-text dl-mono"}),d=ae("",{placeholder:"vpn.example.com or an IP","aria-label":"Other address"}),p=O=>/^\d{1,3}(\.\d{1,3}){3}$/.test(O),c=[o.portal_host,...o.portal_alt??[]].filter((O,F,me)=>O&&me.indexOf(O)===F),m=!!n.portal,v=[],h=O=>{O&&!v.some(F=>F.host===O)&&v.push({host:O,kind:p(O)?"ip":"name",ips:[],here:!1,cloudflare:!1,cert:!1})},x=O=>{v=[...O,...v.filter(F=>!O.some(me=>me.host===F.host))],!c.length&&O[0]&&(c=[O[0].host])};n.portal&&x(n.portal.candidates),c.forEach(h);let R=O=>O.kind==="ip"?e("span",{class:"dl-addr-warn"},[g("alert"),"Plain HTTP: the link and VPN keys travel unencrypted"]):e("span",{class:"dl-sub"},O.cloudflare?"Behind Cloudflare · often stalls in Russia":O.ips.length?O.here?`Points at this router${O.cert?" · Let’s Encrypt certificate":" · no certificate yet"}`:`Points at ${O.ips.join(", ")}, not this router`:m?"Your address":"Checking where it points…"),$=e("div",{class:"dl-addr-opts",role:"group","aria-label":"Portal addresses"}),j=O=>{c.includes(O)?c.length>1&&(c=c.filter(F=>F!==O)):c=[...c,O],w(),S()},w=()=>dom.content($,[...v.map(O=>{let F=c.includes(O.host),me=c[0]===O.host;return e("div",{class:`dl-addr-opt${F?" on":""}`,role:"checkbox","aria-checked":F?"true":"false",tabindex:"0",click:()=>j(O.host),keydown:re=>{(re.key===" "||re.key==="Enter")&&(re.preventDefault(),j(O.host))}},[e("i",{class:"dl-addr-check"},F?g("check"):""),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono"},O.host),R(O)]),me?e("span",{class:"dl-pill info"},"Main"):F?e("button",{type:"button",class:"dl-linkbtn",click:re=>{re.stopPropagation(),c=[O.host,...c.filter(ge=>ge!==O.host)],w(),S()}},"Make main"):O.cloudflare?e("span",{class:"dl-pill warn"},"Cloudflare"):O.kind==="ip"?e("span",{class:"dl-pill"},"IP"):O.here&&O.cert?e("span",{class:"dl-pill ok"},"Recommended"):""])}),e("div",{class:"dl-addr-opt other"},[e("i",{class:"dl-addr-check"},g("plus")),d,D("Add",()=>{let O=d.value.trim().toLowerCase();O&&(h(O),c.includes(O)||(c=[...c,O]),d.value="",w(),S())})])]);d.addEventListener("keydown",O=>{O.key==="Enter"&&(O.preventDefault(),d.nextElementSibling?.click())});let H=e("div",{class:"dl-links"}),S=()=>{let O=Number(i.value)||o.portal_port;dom.content(H,c.map((F,me)=>{let re=p(F),ge=re?O+1:O,M=`${re?"http":"https"}://${F}${ge===(re?80:443)?"":`:${ge}`}/`;return e("div",{class:"dl-link-row"},[e("span",{class:`dl-link-ic ${re?"warn":"ok"}`},g(re?"alert":"lock")),e("span",{class:"dl-mono dl-link-url"},[M,e("b",{},"kamiro-telosu-bavine")]),me===0?e("span",{class:"dl-pill info"},"Main"):re?e("span",{class:"dl-pill warn"},"HTTP"):""])}))};w(),S(),i.addEventListener("input",()=>S());let T={portal:"Portal running",portal_dns:"Points here",portal_reply:"Answers reach visitors",portal_http:"Plain HTTP",cert:"Certificate"},b=n.d.needs??{https:[],acme:[],home:[]},A=O=>{if(!o.portal_enabled)return e("div",{hidden:!0});if(!O)return he("check","Ready to share","The portal’s checks from Health",[e("p",{class:"dl-muted dl-loading"},"Running checks…")]);let F=O.filter(_=>_.status!=="skip");if(!F.length)return e("div",{hidden:!0});let{bad:me,worst:re}=Ro(O),ge=e("div",{class:"dl-ready-details",hidden:!0},F.map(_=>e("div",{class:`dl-ready-item ${_.status}`},[g(_.status==="ok"?"check":"alert"),e("span",{class:"dl-stack"},[e("span",{},_.title),e("span",{class:"dl-sub"},_.detail)])]))),M=e("div",{class:"dl-stack gap8"},[e("div",{class:`dl-ready-sum ${re}`},[g(re==="ok"?"check":"alert"),e("span",{class:"dl-stack"},[e("b",{},re==="ok"?`All ${F.length} checks passed`:`${F.length-me.length} of ${F.length} checks passed`),me.length?e("span",{class:"dl-sub"},me.map(_=>_.detail).join(" ")):e("span",{class:"dl-sub"},"Links will open for the people you send them to.")]),e("button",{type:"button",class:"dl-linkbtn",click:_=>{ge.hidden=!ge.hidden,_.currentTarget.textContent=ge.hidden?"Details":"Hide"}},"Details")]),e("div",{class:"dl-chips-row"},F.map(_=>e("span",{class:`dl-check-chip ${_.status}`,title:_.detail},[g(_.status==="ok"?"check":"alert"),T[_.id]??_.title]))),ge]);return he("check","Ready to share","The portal’s checks from Health",[M])},u=O=>{if(!o.portal_enabled||!O&&!b.https.length)return e("span",{hidden:!0});if(b.https.length)return e("span",{class:"dl-pill bad"},"Can’t start");let{worst:F}=Ro(O);return e("span",{class:`dl-pill ${F==="ok"?"ok":F==="error"?"bad":"warn"}`},F==="error"?"Needs attention":"Ready")},f=A(n.portal?.checks??null),N=u(n.portal?.checks??null);n.portalFill=O=>{m=!0,x(O.candidates),w(),S();let F=A(O.checks);f.replaceWith(F),f=F;let me=u(O.checks);N.replaceWith(me),N=me};let P=a&&!a.self_signed&&a.expires?Ae(a.expires):"",I=X("Listening port",i,n.d.port_owners.length?`Port ${o.portal_port} is used by ${n.d.port_owners.join(", ")}.`:`Where the portal runs on the router: HTTPS here, plain HTTP for IP addresses on ${o.portal_port+1}.`),J=!!(t.portal_cert&&t.portal_key),W=a?J?"Your files":a.self_signed?"Self-signed":"Let’s Encrypt":"Portal is off",q=()=>{let O=ae(t.portal_cert,{placeholder:"/etc/ssl/…/fullchain.crt"}),F=ae(t.portal_key,{placeholder:"/etc/ssl/…/key"});oe("Use your own certificate",[e("p",{class:"dl-muted"},"Paths on the router. Leave both empty to pick a certificate automatically."),X("Certificate file",O),X("Key file",F)],[ie()," ",D("Save",()=>{se(),n.save({portal_cert:O.value.trim(),portal_key:F.value.trim()},"Certificate saved","portal")},"positive")])},C=(O,F,me,re,ge,M)=>tt(O,F,me,re,D(M,()=>Pt(ge,b[ge],()=>n.reload("portal")),"positive")),G=b.https.length?C("lock","bad","HTTPS isn’t available on this router",`The portal needs ${b.https.join(" and ")}. It can’t start without them.`,"https","Install"):"",Q=b.acme.length&&(!a||a.self_signed)?C("lock","","Free certificate from Let’s Encrypt",`ACME isn’t installed. With it the router gets a certificate${t.portal_host?` for ${t.portal_host}`:""} and browsers stop warning.`,"acme","Install ACME"):"",de=[e("div",{class:"dl-row"},[g("lock"),e("span",{class:"dl-row-main dl-stack"},[e("b",{},[W,P?e("span",{class:"dl-faint"},` · until ${P}`):""]),e("span",{class:"dl-sub dl-ellipsis",title:a?.path??""},a?a.self_signed?"Made by the router: browsers warn until a certificate covers the address.":`${J?"Your files":"Found automatically"} · ${a.path}`:"Turn the portal on to see its certificate.")])]),e("div",{class:"dl-row"},[g("file"),e("span",{class:"dl-row-main dl-stack"},[e("b",{},"Your own files"),e("span",{class:"dl-sub"},J?`${t.portal_cert} · ${t.portal_key}`:"Not set: the certificate is picked automatically.")]),J?D("Reset",()=>n.save({portal_cert:"",portal_key:""},"Automatic certificate","portal"),"negative"):"",D(J?"Change":"Use files",q)]),Q];return Me("portal","Personal portal",[e("span",{class:"dl-muted"},"A page where each person adds and manages their devices with their personal link."),G?e("div",{class:"dl-list"},[G]):"",he("network","Port","How the portal listens (80 and 443 stay free)",[I]),he("edit","Appearance","What people see",[X("Title",s,"Shown at the top of the portal."),X("Unknown links",l,"Where a wrong or old link goes, for example your website. Empty shows a plain “Not found”.")]),he("link","Addresses","Pick one or more; the first is the main link",[$,e("div",{class:"dl-stack gap8"},[H,e("span",{class:"dl-sub"},"Example code; each person gets their own three words.")])]),he("lock","Certificate","Used for HTTPS links",de),f],[e("span"),D("Save",()=>n.save({portal_enabled:Ee(r)?"1":"0",portal_host:c[0]??"",portal_alt:c.slice(1),portal_port:i.value,portal_title:s.value,portal_redirect:l.value.trim()},"Saved","portal"),"positive")],"",[N,r])}function Io(n){let t=n.d.settings,o=n.d.effective,a=ae(t.default_device_limit,{placeholder:"3",inputmode:"numeric",class:"cbi-input-text dl-w-port"}),r=fe(o.hostnames,"Device hostnames"),i=ae(t.domain,{placeholder:"lan",class:"cbi-input-text dl-w-port"}),s=ae(t.home_dns_fallback==="none"?"":t.home_dns_fallback||o.home_dns_fallback||"",{placeholder:"None",inputmode:"decimal",class:"cbi-input-text dl-w-ip dl-mono"});return Me("defaults","Defaults",[X("Devices per person",a,"Pre-filled when you add someone."),X("Device hostnames",e("div",{class:"dl-hostport"},[r,e("span",{class:"dl-faint dl-mono"},"phone.myata."),i]),"Name devices in your home DNS."),X("Fallback DNS",s,"For Home-only devices using home names: the second DNS server, used by the device when the tunnel is down. Empty = none.")],[e("span"),D("Save",()=>n.save({default_device_limit:a.value,hostnames:Ee(r)?"1":"0",domain:i.value,home_dns_fallback:s.value},"Saved","defaults"),"positive")])}function Bo(n){let t=n.d.effective,o=fe(t.geo_enabled,"Locations"),a=e("select",{class:"cbi-input-select"},[e("option",{value:"ipwho.is",selected:t.geo_provider!=="ipapi.co"?"selected":null},"ipwho.is (fallback: ipapi.co)"),e("option",{value:"ipapi.co",selected:t.geo_provider==="ipapi.co"?"selected":null},"ipapi.co (fallback: ipwho.is)")]);return Me("map","Map & locations",[e("div",{class:"dl-setrow head"},[e("span",{class:"dl-muted"},"Show where people connect from on the Overview and person pages, at city level."),o]),X("Provider",a)],[e("span",{class:"dl-sub"},"The router sends each new client IP to the provider once and caches the city. Map tiles load in your browser from CARTO; people never see the map."),D("Save",()=>n.save({geo_enabled:Ee(o)?"1":"0",geo_provider:a.value},"Saved","map"),"positive")])}var Vr=[["app","Dawnline"],["amneziawg","AmneziaWG"],["packages","System packages"]];function Oo(n){let t=n.d.effective.updates,o=fe(t.check,"Check automatically",x=>h(x,Ee(r))),a=xe([["6h","Every 6 h"],["12h","Every 12 h"],["1d","Daily"],["7d","Weekly"]],t.interval,{label:"How often",cls:"sm"}),r=fe(t.auto,"Install automatically",x=>h(Ee(o),x)),i=ae(t.time,{placeholder:"04:00",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono","aria-label":"Time"}),s=xe([["scheduled","At a set time"],["immediate","As soon as found"]],t.mode,{label:"When",cls:"sm",onChange:x=>i.hidden=x!=="scheduled"});i.hidden=t.mode!=="scheduled";let l=new Set(t.targets),d=e("div",{class:"dl-chips-row"},Vr.map(([x,R])=>{let $=Ue(R,l.has(x),()=>{l.delete(x)||l.add(x),Wt($,l.has(x))});return $})),p=fe(t.keep,"Keep the previous version"),c=fe(t.mirrors,"GitHub mirrors"),m=X("How often",a),v=[X("When",e("div",{class:"dl-hostport"},[s,i]),"A set time keeps tunnel restarts out of the evening; the run happens within an hour of it."),X("Components",d,"AmneziaWG is off by default: a new kernel module restarts every tunnel.")],h=(x,R)=>{m.hidden=!x;for(let $ of v)$.hidden=!R};return h(t.check,t.auto),Me("updates","Updates",[e("span",{class:"dl-muted"},"How Dawnline keeps its components current. Every Dawnline update makes a backup of the settings first."),X("Check automatically",o,"Looks for new versions in the background; Components shows what it found and the service log names it."),m,X("Install automatically",r,"Downloads and installs new versions of the components below."),...v,X("Keep the previous version",p,"Saves the replaced Dawnline or AmneziaWG package on flash, so Roll back works without internet. Under 1 MB."),X("GitHub mirrors",c,"When GitHub is unreachable, download through mirrors. Checksums are still verified.")],[e("span",{class:"dl-sub"},"Run a check or an update by hand in Components."),D("Save",()=>n.save({update_check:Ee(o)?"1":"0",update_interval:a.dataset.value,update_auto:Ee(r)?"1":"0",update_mode:s.dataset.value,update_time:i.value.trim(),update_targets:[...l],update_keep:Ee(p)?"1":"0",update_mirrors:Ee(c)?"1":"0"},"Saved","updates"),"positive")])}function jo(n){let t=n.d.logs,o=t.policy,a=xe([["7","7 days"],["30","30 days"],["90","90 days"],["365","1 year"],["0","No limit"]],String(o.keep_days),{label:"Keep activity",cls:"sm"}),r=xe([["500","500"],["2000","2,000"],["5000","5,000"],["20000","20,000"]],String(o.max),{label:"Maximum events",cls:"sm"}),i=xe([["10min","Every 10 min"],["hourly","Hourly"],["off","Memory only"]],o.persist,{label:"Save to flash",cls:"sm"}),s=xe([["31","1 month"],["62","2 months"],["180","6 months"],["365","1 year"],["730","2 years"]],String(o.usage_days),{label:"Daily traffic",cls:"sm"}),l=xe([["12","1 year"],["24","2 years"],["60","5 years"],["120","10 years"]],String(o.usage_months),{label:"Monthly traffic",cls:"sm"}),d=new Set(o.categories),p=e("div",{class:"dl-chips-row"},pt.map(h=>{let x=Ue([nt[h],e("b",{},String(t.by_category[h]??0))],d.has(h),()=>{d.delete(h)||d.add(h),Wt(x,d.has(h))},{title:Xn[h]});return x})),c=t.oldest?Ae(new Date(t.oldest*1e3)):"",m=(h,x,R,$)=>e("div",{class:"dl-row"},[g(h),e("span",{class:"dl-row-main dl-stack"},[e("b",{},x),e("span",{class:"dl-sub"},R)]),...$]),v=h=>D(h.toUpperCase(),async()=>{let[x,R]=await Promise.all([E.status(1),E.events(2e4)]);je(x,R.events,h)},"neutral",{title:`Download the log as ${h.toUpperCase()}`});return Me("logs","Logs & history",[e("p",{class:"dl-muted"},Ut(o)),X("Keep activity",a,"Older events are removed automatically."),X("Maximum size",r,"Newest events are kept when the log is full."),X("Record",p,"Switched-off categories are not logged from now on."),X("Save to flash",i,"The log lives in memory and is copied to flash. Memory only saves flash writes but is lost on reboot."),X("Daily traffic",s,"Per-day history behind the charts."),X("Monthly traffic",l,"Per-month totals; data limits use the current month."),e("h4",{class:"dl-setsub"},"Stored data"),e("div",{class:"dl-list"},[m("activity","Activity log",t.events?`${Rt(t.events,"event")} since ${c} · ${yt(t.log_ram)} in memory${o.persist==="off"?"":`, ${yt(t.log_flash)} on flash`}`:"Empty",[v("csv"),v("json"),D("Clear",()=>Fe("Clear activity","Removes events from the log on the router.",{},()=>n.reload("logs")),"negative")]),m("chart","Traffic history",t.usage_days?`${Rt(t.usage_days,"day")} since ${Ae(t.usage_since)} · ${yt(t.usage_flash)} on flash`:"Empty",[D("Reset",()=>ut("all","","",()=>setTimeout(()=>n.reload("logs"),300)),"negative")]),m("pin","Location cache",`${Rt(n.d.geo_cached,"address","addresses")} · ${yt(t.geo_flash)} on flash`,[D("Clear",async()=>{await U(()=>E.geoClear(),"Location cache cleared")&&await n.reload("logs")},"negative")])])],[e("span",{class:"dl-sub"},"Clear one person or device from their own page."),D("Save",()=>n.save({log_keep_days:a.dataset.value,log_max:r.dataset.value,log_persist:i.dataset.value,usage_keep_days:s.dataset.value,usage_keep_months:l.dataset.value,log_category:[...d]},"Saved","logs"),"positive")])}var Yr={manual:"Manual",auto:"Nightly","pre-restore":"Before restore","pre-import":"Before import","pre-delete":"Before removing a server","pre-update":"Before update"},Uo=3;function An(n){let t=new Date(n*1e3),o=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),a=Math.round((new Date(new Date().toDateString()).getTime()-new Date(t.toDateString()).getTime())/864e5);return`${a===0?"Today":a===1?"Yesterday":t.toLocaleDateString("en-GB",{day:"numeric",month:"short"})}, ${o}`}async function Qr(n){let t=await U(()=>E.backupRead(n.name));if(!t)return;let o=atob(t.data),a=new Uint8Array(o.length);for(let i=0;iQr(n),"neutral","dl-icon-only"),ye("more","More",o=>we(o.currentTarget,[{label:"Restore",icon:g("reset"),run:async()=>{await ne("Restore this backup?",`Everything returns to ${An(n.created)}. The current state is backed up first.`,"Restore",!0)&&await U(()=>E.backupRestore(n.name),"Restored")&&t(!0)}},{label:"Delete",icon:g("trash"),danger:!0,run:async()=>{await ne("Delete this backup?",`The backup from ${An(n.created)} is removed from the router.`,"Delete",!0)&&await U(()=>E.backupDelete(n.name),"Backup deleted")&&t()}}]),"neutral","dl-icon-only")])])}function Go(n,t){let o=n.slice(0,Uo).map(d=>Wo(d,t)),a=n.slice(Uo),r=n.length?e("div",{class:"dl-list"},[...o,a.length?e("details",{class:"dl-bk-older"},[e("summary",{},[g("chevron"),`${a.length} older backup${a.length===1?"":"s"}`]),...a.map(d=>Wo(d,t))]):""]):e("div",{class:"dl-list"},[e("div",{class:"dl-row dl-muted"},"No backups yet.")]),i=D("Restore from file",async()=>{let d=await bn(".tar.gz,.tgz,application/gzip","base64");if(!d)return;await ne("Restore from file?",`Replace the current Dawnline configuration with ${d.name}? The current state is backed up first.`,"Restore",!0)&&await U(()=>E.backupUpload(d.data),"Restored")&&t(!0)}),s=D("Export JSON",async()=>{let d=await U(()=>E.exportJson());d&&$e(`dawnline-export-${new Date().toISOString().slice(0,10)}.json`,JSON.stringify(d,null,2),"application/json")}),l=D("Import JSON",async()=>{let d=await bn(".json,application/json","text");if(!d)return;let p;try{p=JSON.parse(d.data)}catch{Z("Not a JSON file.","error");return}await ne("Import?","This replaces the whole Dawnline configuration on this router. The current state is backed up first.","Import",!0)&&await U(()=>E.importJson(p),"Imported")&&t(!0)});return e("section",{class:"dl-setsec",id:"dl-set-backups"},[e("div",{class:"dl-setsec-body"},[e("div",{class:"dl-setsec-head"},[e("div",{class:"dl-stack"},[e("h3",{},"Backups"),e("span",{class:"dl-sub"},"Nightly when something changed, and before every restore, import or update. The last 10 are kept.")]),e("span",{class:"dl-spacer"}),D([g("plus")," Back up now"],async()=>{await U(()=>E.backupCreate(),"Backup created")&&t()},"positive")]),r]),e("div",{class:"dl-setsec-foot"},[e("span",{class:"dl-sub"},"Backups contain private keys: keep downloads safe. JSON moves everything except usage history to another router."),e("span",{class:"dl-row-actions dl-bk-actions"},[i,s,l])])])}function Zr(){let n=ae("",{placeholder:"remove"});oe("Remove Dawnline?",[e("p",{},"Everyone is disconnected and the tunnel, firewall rules and portal are removed. A backup is made first. Type “remove” to confirm."),n],[ie()," ",D("Remove Dawnline",async()=>{await U(()=>E.uninstall(n.value.trim()),"Dawnline removed")&&(se(),setTimeout(()=>location.reload(),800))},"negative")])}function qo(){return Me("danger","Remove Dawnline from this router",[e("p",{class:"dl-muted"},"Deletes the tunnel, firewall rules, access table and hostnames Dawnline created, and stops the service. People and keys are kept in a backup.")],[e("span"),D("Remove",()=>Zr(),"negative")],"danger")}var rn=class{constructor(){this.root=e("div",{class:"dl-settings-main"});this.backups=[];this.portal=null;this.portalSeq=0;this.cards={}}load(){return E.settingsGet()}render(t){this.d=t,this.cards={portal:Qe(()=>Ho(this)),defaults:Qe(()=>Io(this)),map:Qe(()=>Bo(this)),updates:Qe(()=>Oo(this)),logs:Qe(()=>jo(this)),backups:Qe(()=>Go(this.backups,r=>this.loadBackups(r))),danger:Qe(()=>qo())};let o=["portal","defaults","map","updates","logs","backups","danger"];dom.content(this.root,o.map(r=>this.cards[r].el)),this.loadBackups().then(()=>{new URLSearchParams(location.search).get("section")==="backups"&&document.getElementById("dl-set-backups")?.scrollIntoView({block:"start"})}),this.loadPortal();let a=new URLSearchParams(location.search).get("section");return a&&a!=="backups"&&requestAnimationFrame(()=>document.getElementById(`dl-set-${a}`)?.scrollIntoView({block:"start"})),e("div",{},[e("div",{class:"dl-pagehead"},[e("h2",{class:"dl-h1"},"Settings")]),this.root])}async save(t,o,a){let r=await U(()=>E.settingsUpdate(t),o);r&&(this.d=r,this.cards[a].refresh(),a==="portal"&&this.loadPortal())}async loadPortal(){let t=++this.portalSeq,o=await E.portalInfo().catch(()=>null);t===this.portalSeq&&(this.portal=o??this.portal??{candidates:[],checks:[]},this.portalFill?.(this.portal))}async loadBackups(t=!1){t&&await this.reload();let o=await E.backupList().catch(()=>null);o&&(this.backups=o.backups,this.cards.backups?.refresh())}async reload(t){let o=await E.settingsGet().catch(()=>null);if(o){if(this.d=o,t)this.cards[t].refresh();else for(let a of Object.values(this.cards))a.refresh();(!t||t==="portal")&&this.loadPortal()}}};function Fo(n,t=!1){return n&&(t?/^https?:\/\//i:/^https:\/\//i).test(n)?n:null}function Ko(n){let t=[],o=l=>{let d=[],p=/(`[^`]+`)|(\*\*[^*]+\*\*)|(\[[^\]]+\]\((https?:\/\/[^)\s]+)\))|(https?:\/\/[^\s<>()]+[^\s<>().,;:!?])/g,c=0;for(let m;m=p.exec(l);)m.index>c&&d.push(l.slice(c,m.index)),m[1]?d.push(e("code",{},m[1].slice(1,-1))):m[2]?d.push(e("b",{},m[2].slice(2,-2))):m[3]?d.push(e("a",{href:m[4],target:"_blank",rel:"noopener"},m[3].replace(/^\[|\]\(.*$/g,""))):m[5]&&d.push(e("a",{href:m[5],target:"_blank",rel:"noopener"},m[5].replace(/^https?:\/\/(github\.com\/)?/,""))),c=m.index+m[0].length;return c{r.length&&t.push(e("p",{},o(r.join(" ")))),r=[],a=null};for(let l of n.replace(/\r/g,"").split(` +`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(t.push(e("pre",{},i.join(` +`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){s(),i=[];continue}let p=/^(#{1,6})\s+(.*)$/.exec(d),c=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);p?(s(),t.push(e("h5",{},o(p[2])))):c?(r.length&&s(),a||(a=e("ul",{}),t.push(a)),a.appendChild(e("li",{},o(c[1])))):d.trim()?(a&&(a=null),r.push(d.trim())):s()}return i&&t.push(e("pre",{},i.join(` +`))),s(),t}function Jo(n){let t=[],o=!1;for(let a of n.replace(/\r/g,"").split(` +`)){let r=/^#{1,6}\s+(.*)$/.exec(a);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(a)&&(o=!1);o||t.push(a)}return t.join(` +`).replace(/\n{3,}/g,` + +`).trim()}async function zt(n,t,o,a){let r=e("div",{class:"dl-notes"},e("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=e("div",{class:"dl-op-head"}),s="";oe(o,[i,r],[D([g("copy")," Copy"],()=>pe(s,"Release notes copied"))," ",ie("Close")],"wide");try{let l=await E.updatesNotes(n,t,a??"");s=Jo(l.body||"");let d=Fo(l.url);dom.content(i,[l.published?e("span",{class:"dl-pill"},Ae(l.published)):"",l.prerelease?e("span",{class:"dl-pill warn"},"Pre-release"):"",e("span",{class:"dl-spacer"}),d?e("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",g("open")]):""]),dom.content(r,s.trim()?Ko(s):e("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(r,e("p",{class:"dl-muted"},ve(l)))}}var Vo={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},zn=n=>n?Ae(n):"";function Xr(n){let t=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return t||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function Qo(n,t){let o=n.st,a=o.policy,r=o.kept?.app,i=t?.update&&t.tag?t.tag:o.version,s=v=>()=>zt("app",v,`What’s new in Dawnline ${v.replace(/^v/,"")}`),l=t?.tag&&(t.update||t.status==="latest")?ei(n,t.tag,t.update?o.version:""):null,d=t?.tag??i,p=a.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[a.interval]??24)*3600:0,c=(v,h)=>e("div",{class:"dl-stack gap4"},[e("span",{class:"dl-metric-label"},v),e("span",{class:"dl-comp-side-v"},h)]),m=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},r?{label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await ne(`Roll back to Dawnline ${r.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return e("section",{class:"dl-panel flush dl-comp-hero"},[e("div",{class:"dl-comp-hero-main"},[e("div",{class:"dl-comp-hero-head"},[e("span",{class:"dl-group-ic"},g("sunrise")),e("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",t,t?.latest??""),e("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),m,!0)]),e("div",{class:"dl-comp-verrow"},[e("div",{class:"dl-stack"},[e("div",{class:"dl-comp-big"},[o.version,t?.update?e("small",{},`→ ${t.latest}`):t?.status==="dev"&&t.latest?e("small",{class:"dl-faint"},`release ${t.latest}`):""]),e("span",{class:"dl-faint dl-comp-meta"},t?.error?"":t?.update?t.published?`released ${zn(t.published)}`:"":t?.status==="dev"?"ahead of the latest release":t?`latest release${t.published?` · released ${zn(t.published)}`:""}`:"not checked yet")])]),l?.items.length?e("div",{class:"dl-stack gap4"},[e("ul",{class:"dl-comp-bullets"},l.items.map(v=>e("li",{},v))),l.total>l.items.length?e("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(d)},`+${l.total-l.items.length} more in What’s new`):""]):"",t?.error?e("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},t.error):"",t?.update?e("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",ti(n)]),e("div",{class:"dl-comp-hero-side"},[c("Source",[g("globe"),e("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),c("Auto-update",[a.auto?ke("ok","On"):ke("","Off"),e("span",{class:"dl-muted"},a.auto?a.mode==="immediate"?"as soon as found":`${Vo[a.interval]==="weekly"?"weekly":"daily"} at ${a.time}`:a.check?`checks ${Vo[a.interval]}`:"checks off")]),c("Last check",o.check?[le(o.check.time,o.now),p>o.now?e("span",{class:"dl-faint"},`· next in ${st(p-o.now)}`):""]:["Never"]),c("Rollback",r?[e("span",{class:"dl-mono"},r.version),e("span",{class:"dl-faint"},"kept on flash")]:[e("span",{class:"dl-muted"},a.keep?"Kept after the next update":"Off")])])])}function ei(n,t,o){if(n.notes.has(t))return n.notes.get(t)??null;n.notes.set(t,null);let a=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await E.updatesNotes("app",t,"").catch(()=>null))?.body??"").split(` +`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await E.updatesChanges(o,t).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Xr(a(l))),total:i.length};n.notes.set(t,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function ti(n){let t=e("div",{class:"dl-params-body"}),o=e("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[e("summary",{},[g("chevron"),e("span",{},"Versions"),e("span",{class:"dl-sub"},"install any release")]),t]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&sn(n,t)}),n.versOpen&&sn(n,t),o}async function sn(n,t){let o=ae("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),a=c=>{if(c=c.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(c))return Z("Enter a release tag like 0.3.1","warning");Yo(n,c)};o.addEventListener("keydown",c=>{c.key==="Enter"&&(c.preventDefault(),a(o.value))});let r=e("div",{class:"dl-comp-tag"},[o,D("Install",()=>a(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=c=>{n.versPage=Math.max(1,n.versPage+c),sn(n,t)},l=c=>e("div",{class:"dl-comp-pager"},[e("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),e("span",{class:"dl-faint"},`Page ${i}`),e("button",{type:"button",class:"dl-linkbtn",disabled:c?null:"disabled",click:()=>s(1)},"Older →")]),d=n.versCache.get(i);if(!d){dom.content(t,[r,e("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{d=(await E.updatesReleases(i)).releases}catch(c){if(i!==n.versPage||!t.isConnected)return;dom.content(t,[r,e("div",{class:"dl-row-actions"},[e("span",{class:"dl-muted"},`Failed to load versions: ${ve(c)}`),D("Try again",()=>sn(n,t))]),l(!1)]);return}if(n.versCache.set(i,d),i!==n.versPage||!t.isConnected)return}if(!d.length)return dom.content(t,[r,e("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let p=n.st.version;dom.content(t,[r,...d.map(c=>{let m=c.tag.replace(/^v/,"");return e("div",{class:"dl-comp-ver"},[e("span",{class:"dl-mono"},m),e("span",{class:"dl-sub"},zn(c.published)),c.prerelease?ke("warn","Pre-release"):"",e("span",{class:"dl-comp-ic"},ye("file","What’s new",()=>zt("app",c.tag,`What’s new in Dawnline ${m}`))),m===p?ke("ok","Installed"):D("Install",()=>Yo(n,c.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function Yo(n,t){let o=t.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await ne(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${t}`,`Installing Dawnline ${o}`,n.st.version)}function Zo(n,t){let o=n.st,a=o.kept?.amneziawg,r=t?.sources??{},i=Object.keys(r),s=t?.current??null,l=s?r[s]:void 0,d=!!t?.ru,p=o.needs?.awg??[],c=p.length?null:t?.installed??null,m=[];s&&c&&m.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${d?":ru":""}`,"Reinstalling AmneziaWG",c)}),a&&m.push({label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await ne(`Roll back AmneziaWG to ${a.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",c??void 0)}});let v=[t?.release?{label:"What’s new",ic:"file",run:()=>zt("amneziawg",t.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...m.length?[null,...m]:[]].filter((u,f,N)=>u!==null||f>0&&N[f-1]!==null),h=o.tunnels??[],x=h.length?`Switching restarts ${h.length===1?"the tunnel":`${h.length} tunnels`} for a few seconds: ${h.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",R=h.length>1?`${h.slice(0,-1).join(", ")} and ${h[h.length-1]}`:h[0],$=h.length?`Switching restarts ${R} for a few seconds.`:"Switching takes a few seconds.",j=async u=>{let f=r[u];await ne(c?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${x}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,c?"Switch":"Install")&&n.op(`amneziawg:${u}${d?":ru":""}`,c?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",c??void 0)},w=u=>{let f=r[u],N=s===u&&!!c;return e("div",{class:"dl-row"},[e("span",{class:"dl-row-main dl-stack"},[e("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),e("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),e("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),e("span",{class:"dl-comp-bact"},N?ke("ok","Active"):f.version?D(c?"Switch":"Install",()=>j(u),c?"neutral":"positive",{disabled:n.busy}):ke("","No build"))])},H=i.map(u=>r[u]?.newer?`${r[u].label} moves to ${r[u].newer.gen} with OpenWrt ${r[u].newer.tag.replace(/^v/,"")}.`:"").filter(Boolean),S=fe(d,"Russian translation",u=>{s&&n.op(`amneziawg:${s}${u?":ru":""}`,u?"Adding the Russian translation":"Removing the Russian translation",c??void 0)});S.disabled=!s||!c||n.busy;let T=n.awgOpen??!c,b=e("details",{class:"dl-params dl-comp-fold",open:T?"open":null},[e("summary",{},[g("chevron"),e("span",{},"Build and translation")]),e("div",{class:"dl-params-body"},[e("div",{class:"dl-list"},[...i.length?i.map(w):[e("div",{class:"dl-row"},e("span",{class:"dl-sub"},"Check for updates to see the builds for this router."))],e("div",{class:"dl-row"},[e("span",{class:"dl-row-main dl-stack"},[e("b",{},"Russian translation"),e("span",{class:"dl-sub"},"LuCI pages for AmneziaWG")]),e("span",{class:"dl-comp-bact"},S)])]),c&&i.length||H.length?e("div",{class:`dl-comp-status ${c&&i.length?"warn":"acc"}`},[g(c&&i.length?"alert":"download"),e("span",{},[c&&i.length?e("b",{},$):"",...H.map(u=>` ${u}`)])]):""])]);b.addEventListener("toggle",()=>n.awgOpen=b.open);let A=[];return t?.update&&c&&s?A.push(D(`Update to ${t.latest}`,()=>n.op(`amneziawg:${s}${d?":ru":""}`,"Updating AmneziaWG",c),"neutral",{disabled:n.busy})):A.push((t||p.length)&&!c?ke("warn","Not installed"):n.state("amneziawg",t,t?.latest??"")),A.push(n.round(()=>n.op("check:amneziawg","Checking AmneziaWG",c??void 0),v)),[n.row("shield","AmneziaWG",[c?`${c}${t?.release?` · ${t.release} build`:""}`:p.length?`missing ${p.join(", ")}`:t?"not installed":"version not checked"],A),e("div",{class:"dl-comp-foldwrap"},b)]}var ni=[{title:"Home-like link",sub:"Policy routing and the veth pair",pkgs:["ip-full","kmod-veth"],feature:"home"},{title:"HTTPS for the portal",sub:"OpenSSL for uhttpd",pkgs:["libustream-openssl","openssl-util"],feature:"https"},{title:"Certificates (ACME)",sub:"Let’s Encrypt certificate for the portal",pkgs:["acme","acme-acmesh-dnsapi"],feature:"acme",optional:!0}],Nn={home:"network",https:"lock",acme:"file"};function Xo(n,t){let o=n.st,a=t?.pkgs??{},r=ni.filter(p=>p.feature==="home"?o.home:o.portal),i=async(p,c,m=p)=>{await ne(`Update ${c}?`,`${m.join(", ")} from the OpenWrt feeds. Services that use them restart for a moment.`,"Update")&&n.op(`pkgs:${p.join(",")}`,`Updating ${c}`)},s=[{label:"Check system packages",ic:"refresh",run:()=>n.op("check:packages","Checking system packages")},{label:"Open the OpenWrt package list",ic:"globe",run:()=>window.open("https://openwrt.org/packages/start","_blank","noopener")}],l=0;return{rows:r.map(p=>{let c=p.pkgs.filter(R=>a[R]?.installed),m=[...new Set(c.flatMap(R=>[...a[R]?.latest?[R]:[],...a[R]?.with??[]]))],v=o.needs?.[p.feature]??p.pkgs.filter(R=>!a[R]?.installed),h=c.find(R=>a[R]?.latest),x=c.map(R=>`${R} ${a[R]?.installed??""}`).join(", ");return v.length?n.row(Nn[p.feature],p.title,[`${p.optional?"not installed":`missing ${v.join(", ")}`}`],[D("Install",()=>n.op(`pkgs:${v.join(",")}`,`Installing ${p.title}`),p.optional?"neutral":"positive",{disabled:n.busy}),e("span",{class:"dl-comp-ic"},n.more(s))]):t&&m.length?(l++,n.row(Nn[p.feature],p.title,h?[`${a[h].installed} → ${a[h].latest}`,m.length>1?` · +${m.length-1}`:""]:[m.join(", ")],[D("Update",()=>i(c.filter(R=>a[R]?.latest||a[R]?.with?.length),p.title,m),"neutral",{disabled:n.busy}),e("span",{class:"dl-comp-ic"},n.more(s))])):n.row(Nn[p.feature],p.title,[x||p.sub],[n.state("pkgs",t,""),e("span",{class:"dl-comp-ic"},n.more(s))])}),updates:l,total:r.length}}var oi={app:"Dawnline",amneziawg:"AmneziaWG",pkgs:"System packages",all:"Components"};function ea(n){let t=n.st,o=r=>{let i=Ve(r.component??"app"),s=oi[i]??"Components",l=r.auto?"automatically":"by you",d="ok",p="check",c;if(r.kind==="found")d="accent",p="download",c=[e("b",{},(r.items??[]).join(", ")),` found by ${r.auto?"the automatic check":"a check"}`];else if(r.state==="failed")d="bad",p="x",c=[e("b",{},s),` ${r.kind==="install"?"update":"check"} failed${r.error?` · ${r.error}`:""}`];else{let m=r.from&&r.to&&r.from!==r.to?` ${r.from} → ${r.to}`:r.to?` ${r.to}`:"";c=[e("b",{},s),`${m} ${m?"":"updated "}${l}${r.took?` · ${st(r.took)}`:""}`.replace(/\s+/g," ")]}return e("div",{class:"dl-row"},[e("span",{class:`dl-ev-tile ev ${d}`},g(p)),e("span",{class:"dl-row-main"},c),e("span",{class:"dl-faint dl-nowrap",title:new Date(r.ts*1e3).toLocaleString()},le(r.ts,t.now))])},a=t.history??[];return e("section",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-spacer"}),e("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},"All in Log →")]),a.length?e("div",{},a.slice(0,8).map(o)):e("p",{class:"dl-sub dl-comp-empty"},"Updates, and checks that found something, show up here.")])}var ln=class{constructor(){this.root=e("div",{class:"dl-upd"});this.following=null;this.versOpen=!1;this.versPage=1;this.versCache=new Map;this.notes=new Map;this.awgOpen=null}load(){return E.updatesStatus()}render(t){return this.st=t,this.paint(),t.job?.state==="running"&&this.follow(t.job),poll.add(async()=>{if(!this.root.isConnected)return;let o=await E.updatesStatus().catch(()=>null);if(!o)return;let a=this.st;this.st=o,o.job?.state==="running"&&this.following!=="starting"&&o.job.id!==this.following&&this.follow(o.job),(o.job?.id!==a.job?.id||o.job?.state!==a.job?.state||o.job?.phase!==a.job?.phase||o.check?.time!==a.check?.time)&&this.paint()},5),this.root}get busy(){return this.st.job?.state==="running"}async refresh(t){this.st=t??await E.updatesStatus().catch(()=>null)??this.st,this.paint()}async op(t,o,a){if(this.busy||this.following==="starting"){Z("Another component action is already running","warning");return}this.following="starting",this.paint();let r=Ve(t),i=await Mt(t,{title:o,version:a,onJob:s=>this.following=s.id,onDone:s=>this.refresh(s),onUpdate:s=>{let l=s.check?.components??{};r==="amneziawg"&&l.amneziawg?.current?this.op(`amneziawg:${l.amneziawg.current}${l.amneziawg.ru?":ru":""}`,"Updating AmneziaWG",l.amneziawg.installed??void 0):this.op("app","Updating Dawnline",this.st.version)}});this.following==="starting"&&(this.following=i?.id??null),this.refresh()}async follow(t){this.following=t.id;let o=Yt(t),a={app:"Dawnline",amneziawg:"AmneziaWG",pkgs:"system packages",all:"components"}[o]??"components";await Mt(null,{title:`${t.action==="check"?"Checking":t.auto?"Automatic update:":"Updating"} ${a}`,onDone:r=>this.refresh(r)},t)}paint(){let t=this.st,o=t.check?.components??{},a=t.firmware,r=Xo(this,o.packages),i=(t.needs?.awg??[]).length>0,l=(!i&&o.amneziawg?.update&&o.amneziawg.installed?1:0)+r.updates;dom.content(this.root,[e("div",{class:"dl-pagehead"},[e("div",{class:"dl-stack"},[e("h2",{class:"dl-h1"},"Components"),e("span",{class:"dl-faint"},[a?.version?`OpenWrt ${a.version} · ${a.target}`:"",t.check?`checked ${le(t.check.time,t.now)}`:"not checked yet"].filter(Boolean).join(" · "))]),e("div",{class:"dl-row-actions"},[e("a",{class:"cbi-button cbi-button-neutral dl-icon-btn",href:`${L.url("admin/network/dawnline/settings")}?section=updates`},[g("edit")," Settings"]),D([g("refresh")," Check all"],()=>this.op("check","Checking all components"),"neutral",{disabled:this.busy})])]),Qo(this,o.app),e("div",{class:"dl-comp-cols"},[e("section",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Components"),e("span",{class:"dl-spacer"}),e("span",{class:"dl-faint dl-comp-count"},i?l?`AmneziaWG not installed · ${l} update${l===1?"":"s"}`:"AmneziaWG not installed":!o.amneziawg&&!o.packages?"":l?`${l} of ${1+r.total} need${l===1?"s":""} an update`:"Everything is up to date")]),e("div",{},[...Zo(this,o.amneziawg),...r.rows])]),ea(this)])])}state(t,o,a){let r=this.st.job;if(r?.state==="running"){let i=l=>l==="packages"?"pkgs":l,s=r.action==="check"?[i(r.component||"all")]:(r.component??"").split(" ").map(l=>i(Ve(l)));if(s.includes(t)||s.includes("all"))return e("button",{type:"button",class:"dl-pill info dl-comp-run",title:"Show progress",click:()=>this.follow(r)},[r.action==="check"?"Checking":"Updating","…"])}return o?o.error?ke("warn","Check failed",o.error):o.update?ke("info","Update available"):o.status==="dev"?ke("info","Newer than release",`The latest release is ${a}`):ke("ok","Up to date"):ke("","Not checked")}more(t){let o=D([g("more")],()=>we(o,t.filter((a,r,i)=>a!==null||r>0&&ra?{label:a.label,icon:g(a.ic),warn:a.warn,run:a.run}:null)),"neutral",{title:"More","aria-label":"More"});return o}round(t,o,a=!1){let r=this.busy?" is-busy":"",i;return a?i=D([g("refresh")," Check"],t,"neutral",{class:`cbi-button cbi-button-neutral dl-comp-check${r}`,"aria-label":"Check for updates"}):(i=ye("refresh","Check for updates",t,"neutral",r.trim()),i.removeAttribute("title"),i.setAttribute("aria-label","Check for updates"),ue(i,()=>["Check for updates"])),e("span",{class:"dl-comp-ic"},[i,this.more(o)])}row(t,o,a,r){return e("div",{class:"dl-row"},[e("span",{class:"dl-group-ic"},g(t)),e("span",{class:"dl-row-main dl-stack"},[e("b",{},o),e("span",{class:"dl-mono dl-faint dl-comp-sub"},a)]),...r])}};var ta=(n,t)=>e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},n),e("div",{class:"cbi-value-field"},t)]);function na(n){let t=n.st.servers.find(o=>o.id===n.p.server)?.name??"Home";Lt(n.p,t)}async function oa(n){let t=n.p;if(!await ne("Create a new link?","The old link stops working right away.","Create new link",!0))return;let o=await U(()=>E.personRegen(t.id),"New link created");o?.link&&await pe(o.link,"New link copied")}function Rn(n){let t=e("textarea",{class:"cbi-input-textarea dl-note-input",rows:3,maxlength:500,placeholder:"Only you see this"},n.p.note??"");oe("Note",[t],[ie()," ",D("Save",async()=>{se(),await n.patch({note:t.value.trim()},t.value.trim()?"Note saved":"Note removed")},"positive")]),setTimeout(()=>t.focus(),50)}function aa(n){let t=n.p,o=e("select",{class:"cbi-input-select"},[e("option",{value:"pause",selected:t.expire_action==="pause"?"selected":null},"Pause access"),e("option",{value:"notify",selected:t.expire_action==="notify"?"selected":null},"Keep access"),e("option",{value:"remove",selected:t.expire_action==="remove"?"selected":null},"Remove their devices")]),a=e("select",{class:"cbi-input-select"},[0,1,3,7,14].map(r=>e("option",{value:r,selected:t.expire_warn===r?"selected":null},r?`${r} day${r===1?"":"s"} before`:"Don’t warn")));oe("When access ends",[ta("Then",o),e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},"Warn"),e("div",{class:"cbi-value-field"},[a,e("div",{class:"cbi-value-description"},"Shown in their portal and on the Overview.")])])],[ie()," ",D("Save",async()=>{se(),await n.patch({expire_action:o.value,expire_warn:a.value},"Saved")},"positive")])}function ra(n){let t=e("input",{type:"text",class:"cbi-input-text",value:n.p.name,maxlength:48});oe("Rename",[ta("Name",t)],[ie()," ",D("Save",async()=>{se(),await n.patch({name:t.value},"Renamed")},"positive")]),setTimeout(()=>t.select(),50)}async function ia(n){let t=n.p;await ne(`Delete ${t.name}?`,`All ${t.devices.length} devices are disconnected immediately and the personal link stops working.`,"Delete",!0)&&await U(()=>E.personDelete(t.id),"Deleted")&&(location.href=ht(t.server))}function sa(n){let t=n.p,o=n.st,a=t.online?"online now":t.last_seen?`last seen ${le(t.last_seen,o.now)}`:"never connected",r=t.created?`Added ${ze(De(new Date(t.created*1e3)))}`:"",i=t.has_link??o.settings.portal_enabled,s=[{label:"Rename",icon:g("edit"),run:()=>ra(n)},{label:t.note?"Edit note":"Add note",icon:g("file"),run:()=>Rn(n)},...i?[null,{label:"Invite card",icon:g("qr"),run:()=>na(n)},{label:"New link",icon:g("key"),run:()=>oa(n)}]:[],null,{label:t.paused?"Resume":"Pause",icon:g(t.paused?"play":"pause"),warn:!t.paused,run:()=>n.patch({paused:!t.paused},t.paused?"Resumed":"Paused")},{label:"Delete",icon:g("trash"),danger:!0,run:()=>ia(n)}];return e("div",{class:"dl-person-head"},[e("div",{class:"dl-pagehead"},[e("div",{class:"dl-person-id"},[e("span",{class:`dl-avatar lg${t.online?" online":""}`},Oe(t.name)),e("div",{class:"dl-stack"},[e("div",{class:"dl-title-row"},[e("h2",{class:"dl-h1"},t.name),It(t)]),e("span",{class:"dl-faint",title:r},`${t.devices.length} of ${t.device_limit} devices · ${a}`)])]),e("div",{class:"dl-pcard-actions"},[i?ye("link","Copy link",()=>Ft(t.id),"neutral","dl-icon-only"):"",ye("more","More",l=>we(l.currentTarget,s),"neutral","dl-icon-only")])]),t.note?e("button",{type:"button",class:"dl-pnote",title:"Edit note",click:()=>Rn(n)},[g("file"),e("span",{},t.note)]):""])}function la(n){let t=n.p,o=n.series[n.series.length-1];return e("div",{class:`dl-person-live${t.online?"":" solo"}`},[t.online?tn(t.rate??[],n.st.now,o?[o.rx,o.tx]:[0,0]):"",nn(n.series,`${te(t.month[0]+t.month[1])} this month`)])}async function ai(n,t){let o=await U(()=>E.deviceConfig(t.id));o&&oe(`Set up ${t.name}`,[await n.core.connectBlock(o,"qr")],[ie("Close")])}async function ri(n,t){let o=await U(()=>E.deviceConfig(t.id));if(!o)return;if(!o.has_private_key){Z("This device made its own keys in the browser; its configuration only exists there.","warning");return}let a=n.core.file.make(o);$e(a.name,a.text,"application/octet-stream")}function da(n){let t=n.p,o=n.st.now,a=d=>He(t,d,n.deviceOpts()),r=d=>p=>{p.target.closest("button:not(.dl-dcard-title), a")||a(d)},i=d=>D([g("more")],p=>mo(p.currentTarget,t,d,n.deviceOpts()),"neutral",{title:"QR, file, key, rename, new keys, remove",class:"cbi-button cbi-button-neutral dl-icon-only"}),s=Ht(t.devices).map(d=>{let p=e("div",{class:"dl-dcard-head"},[e("span",{class:"dl-dcard-ic"},g(d.kind)),e("button",{type:"button",class:"dl-dcard-title",click:()=>a(d)},[e("b",{},d.name),Bt(d,o),d.config_stale?e("span",{class:"dl-pill warn dl-stale"},"Update config"):""]),i(d)]),c=e("div",{class:"dl-dcard-trend"},[e("div",{class:"dl-stack"},[e("b",{},te(d.month[0]+d.month[1])),e("span",{class:"dl-sub"},"this month")]),Do(n.devSeries[d.id]??[])]);return e("article",{class:`dl-dcard clickable${d.online?" online":""}${d.disabled?" off":""}`,click:r(d)},[p,d.handshake?c:d.disabled?e("div",{class:"dl-sub"},`${Be[d.kind]} · created ${le(d.created,o)} ${d.created_by==="portal"?"in the portal":"by you"}.`):e("div",{class:"dl-chips-row"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>ai(n,d)},[g("qr"),"Show QR"]),e("button",{type:"button",class:"dl-chipbtn",click:()=>ri(n,d)},[g("download"),"Config"])])])}),l=t.devices.length>=t.device_limit;return s.push(e("button",{type:"button",class:"dl-dslot add",click:()=>ot(t,n.deviceOpts())},[e("span",{class:"dl-dslot-ic"},g("plus")),e("span",{class:"dl-stack"},[e("b",{},"Add device"),e("span",{class:"dl-sub"},l?`Over the limit · ${t.devices.length} of ${t.device_limit}`:`${t.devices.length} of ${t.device_limit}`)])])),e("section",{class:"dl-devsec"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Devices"),e("span",{class:"dl-sub"},`${t.online} online`)]),e("div",{class:"dl-dgrid"},s)])}function ca(n){let t=n.p,o=xe([["device","Device’s own DNS"],["home","Home names"]],t.dns_mode,{label:"DNS",cls:"sm",optimistic:!1,onChange:r=>n.patch({dns_mode:r},r==="home"?"Home names on — devices need their configuration again":"Device DNS — devices need their configuration again")}),a=n.st.settings.home_dns_fallback;return e("div",{class:"dl-stack gap4 dl-dnspick"},[e("div",{class:"dl-row-actions"},[e("span",{class:"dl-sub"},"DNS"),o]),e("span",{class:"dl-sub"},t.dns_mode==="home"?["Names like ",e("span",{class:"dl-mono"},`nas.${n.st.settings.domain}`)," work. Internet names are resolved at home, so they depend on the tunnel",a?[" (",e("span",{class:"dl-mono"},a)," takes over when it is down)."]:" — with no fallback set, they stop when it is down."]:"Internet keeps working exactly as without the VPN. Reach home devices by IP address.")])}function pa(n){let t=n.p,a=n.st.servers.find(i=>i.id===t.server)?.home??[];if(a.length<2)return"";let r=new Set(t.home_nets?.length?t.home_nets:a.map(i=>i.dev));return e("div",{class:"dl-stack gap4"},[e("div",{class:"dl-chips-row"},a.map(i=>Ue(i.dev,r.has(i.dev),()=>{let s=new Set(r);if(s.delete(i.dev)||s.add(i.dev),!s.size)return Z("Keep at least one network, or choose Internet only.","warning",5e3);let l=s.size===a.length?[]:[...s];n.patch({home_nets:l},l.length?`${t.name} reaches ${l.join(", ")}`:`${t.name} reaches every home network`)},{title:i.nets.join(", ")}))),e("span",{class:"dl-sub"},t.home_nets?.length?`Home networks ${t.name} reaches. Networks added to the server later stay out.`:`Home networks ${t.name} reaches: all of them. Untick one to keep ${t.name} out of it.`)])}function ua(n){let t=new Set(n.p.services??[]);return e("div",{class:"dl-stack gap4"},[e("div",{class:"dl-chips-row"},n.st.services.map(o=>Ue(o.name,t.has(o.id),()=>{let a=new Set(t);a.delete(o.id)||a.add(o.id),n.patch({services:[...a]},a.size?"Home services updated":"Whole home network")},{title:`${o.address}${o.ports.length?` · ${o.ports.join(", ")}`:""}`}))),e("span",{class:"dl-sub"},t.size?"Only the selected services at home.":"Whole home network. Pick services to narrow it down.")])}function ma(n){let t=n.p,o=n.st;if(o.servers.find(p=>p.id===t.server)?.mesh!=="circles"||!Je(t))return"";let r=o.circles.filter(p=>p.server===t.server),i=r.find(p=>p.id===t.circle),s=i?o.people.filter(p=>p.id!==t.id&&p.circle===i.id&&Je(p)).map(p=>p.name):[],l=e("button",{type:"button",class:"dl-chipbtn",click:()=>we(l,[...r.map(p=>({label:p.name,icon:Ln(p),run:()=>p.id!==t.circle&&n.patch({circle:p.id},`${t.name} is in ${p.name}`)})),t.circle?{label:"No circle",icon:g("x"),run:()=>n.patch({circle:""},`${t.name} is in no circle`)}:null,{label:"New circle",icon:g("plus"),run:()=>Jt(o,t.server,null,()=>n.refresh())}])},"Change"),d=i?o.people.filter(p=>p.circle===i.id&&Je(p)):[t];return e("div",{class:"dl-tile2"},[e("div",{class:"dl-tile2-label"},[e("span",{},"Devices see each other"),l]),e("div",{class:"dl-tile2-row"},[e("span",{class:"dl-tile2-value"},i?i.name:"No circle"),e("span",{class:"dl-avstack",title:d.map(p=>p.name).join(", ")},d.slice(0,5).map(p=>e("span",{class:"dl-avatar sm"},Oe(p.name))))]),e("span",{class:"dl-sub"},i?s.length?[t.name,...s].join(", "):`Nobody else in ${i.name} yet`:`Only ${t.name}'s own devices`)])}function ha(n){let t=n.p,o=n.st.now,a=e("div",{class:"dl-slots"});for(let s=0;s=t.device_limit,p=e("i",{class:d?"over":l?"used":""});ue(p,()=>[e("div",{class:"dl-tip-title"},l?`${l.name}${d?" · over the limit":""}`:"Free slot"),e("div",{class:"dl-muted"},l?l.online?"Connected":l.handshake?`Last seen ${le(l.handshake,o)}`:"Not set up yet":"They can add a device here")]),a.appendChild(p)}let r=Math.max(1,t.devices.length),i=e("button",{type:"button","aria-label":"Allow fewer devices",disabled:t.device_limit<=r?"disabled":null,click:()=>n.patch({device_limit:String(t.device_limit-1)})},"−");return t.device_limit<=r&&t.devices.length>1&&ue(i,()=>[e("div",{class:"dl-tip-title"},`${t.devices.length} devices in use`),e("div",{class:"dl-muted"},"Remove a device first to lower the limit")]),e("div",{class:"dl-tile2"},[e("div",{class:"dl-tile2-label"},"Devices"),e("div",{class:"dl-tile2-row"},[e("span",{class:"dl-tile2-value"},[String(t.devices.length),e("span",{class:"dl-faint"},` / ${t.device_limit}`)]),e("div",{class:"dl-stepper"},[i,e("button",{type:"button","aria-label":"Allow more devices",disabled:t.device_limit>=32?"disabled":null,click:()=>n.patch({device_limit:String(t.device_limit+1)})},"+")])]),a])}var ii={internet:"Browse the internet through your router. No access to devices at home, and home cannot reach theirs.",lan:"Reach devices at home, and home reaches theirs. Internet stays on their own connection.",both:"Home devices and the internet, all through your router. Home reaches their devices too."},fa=/^([01]\d|2[0-3]):[0-5]\d$/;function si(n){let t=n.p,o=n.today,a=Xe(t.expires,o),r=e("input",{type:"date",class:"dl-date-hidden",value:t.expires,tabindex:"-1","aria-hidden":"true"});r.addEventListener("change",()=>r.value&&n.patch({expires:r.value},`Access until ${ze(r.value)}`));let i=(p,c)=>{let m=Gn(t.expires&&(a??-1)>=0?t.expires:"",p,c,o);n.patch({expires:m},`Access until ${ze(m)}`)},s=[["week",1,"+1 week"],["month",1,"+1 month"],["month",3,"+3 months"],["year",1,"+1 year"]].map(([p,c,m])=>e("button",{type:"button",class:"dl-chipbtn",click:()=>i(p,c)},m)),l=e("span",{class:"dl-datechip"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>{r.focus({preventScroll:!0});try{r.showPicker()}catch{}}},[g("calendar"),t.expires?ze(t.expires):"Date"]),r]),d={pause:"pause access",notify:"keep access",remove:"remove their devices"}[t.expire_action];return e("div",{class:"dl-tile2"},[e("div",{class:"dl-tile2-label"},[e("span",{},"Access ends"),t.expires?e("span",{class:a!=null&&a<0?"dl-bad":a!=null&&a<=t.expire_warn?"dl-warn":"dl-ok"},a!=null&&a<0?"ended":`${a} day${a===1?"":"s"} left`):e("span",{class:"dl-faint"},"no end date")]),e("div",{class:"dl-chips-row"},[...s,l,t.expires?e("button",{type:"button",class:"dl-chipbtn",click:()=>n.patch({expires:""},"No end date")},"No end"):""]),e("div",{class:"dl-tile2-foot"},[e("span",{class:"dl-muted"},`When it ends: ${d}${t.expire_warn?`, warn ${t.expire_warn} day${t.expire_warn===1?"":"s"} before`:""}`),e("a",{href:"#",click:p=>{p.preventDefault(),aa(n)}},"Change")])])}function li(n){let t=n.p,o=t.quota_used||t.month[0]+t.month[1],a=t.quota_limit?Math.min(100,t.quota_used/t.quota_limit*100):0,r=e("div",{class:`dl-meter${a>=100?" bad":a>=90?" warn":""}`},[e("i"),t.quota_limit?e("span",{class:"mark",title:"Alert at 90%"}):""]);r.firstChild.style.width=`${a}%`,t.quota_limit&&ue(r,()=>[e("div",{class:"dl-tip-title"},`${a.toFixed(1)}% used`),e("div",{class:"dl-muted"},`${te(t.quota_used)} of ${te(t.quota_limit)} · ${te(Math.max(0,t.quota_limit-t.quota_used))} left`),e("div",{class:"dl-faint"},"Alert at 90%")]);let i=xe([["month","Monthly"],["total","Total"]],t.quota_period,{label:"Data limit period",cls:"sm",optimistic:!1,onChange:l=>n.patch({quota_period:l})}),s=[10,50,100].map(l=>e("button",{type:"button",class:`dl-chipbtn${t.quota_gb===l?" on":""}`,click:()=>n.patch({quota_gb:String(l)},`Data limit ${l} GB`)},`${l} GB`));return s.push(e("button",{type:"button",class:`dl-chipbtn${t.quota_gb?"":" on"}`,click:()=>n.patch({quota_gb:""},"No data limit")},"Unlimited")),s.push(e("button",{type:"button",class:"dl-chipbtn",click:()=>{let l=prompt("Data limit in GB",t.quota_gb?String(t.quota_gb):"");l!=null&&l.trim()!==""&&Number(l)>0&&n.patch({quota_gb:l.trim()},`Data limit ${l.trim()} GB`)}},"Custom")),e("div",{class:"dl-tile2"},[e("div",{class:"dl-tile2-label"},[e("span",{},"Data"),i]),e("div",{class:"dl-tile2-row"},[e("span",{class:"dl-tile2-value"},[te(o),t.quota_limit?e("span",{class:"dl-faint"},` of ${te(t.quota_limit)}`):e("span",{class:"dl-faint"}," · no limit")]),t.quota_period==="month"?e("span",{class:"dl-sub"},"resets on the 1st"):""]),t.quota_limit?r:"",e("div",{class:"dl-chips-row"},s),t.quota_gb&&t.quota_period==="month"?e("div",{class:"dl-tile2-foot"},[e("span",{class:"dl-muted"},t.bonus_gb?`Includes +${t.bonus_gb} GB extra this month`:"Need a little more this month?"),e("a",{href:"#",click:l=>{l.preventDefault(),n.patch({bonus_gb:String((t.bonus_gb||0)+10)},"+10 GB this month")}},"+10 GB this month")]):"",e("div",{class:"dl-tile2-foot"},[e("span",{class:"dl-muted"},`${te(t.total[0]+t.total[1])} in total`),e("button",{type:"button",class:"dl-linkbtn danger",click:()=>ut("person",t.id,t.name,()=>setTimeout(()=>n.refresh(),300))},"Reset usage")])])}function di(n){let t=n.p,o=!!t.hours,[a,r]=(t.hours||"07:00-23:00").split("-"),i=e("input",{type:"time",class:"cbi-input-text",value:a,"aria-label":"From"}),s=e("input",{type:"time",class:"cbi-input-text",value:r,"aria-label":"To"}),l=e("div",{class:"dl-tile2-row"},[i,e("span",{class:"dl-faint"},"to"),s]),d=()=>{let c=`${i.value}-${s.value}`;if(c!==t.hours){if(!fa.test(i.value)||!fa.test(s.value))return Z("Enter both times, like 07:00 and 23:00.","warning");if(i.value===s.value)return Z("The start and the end must differ.","warning");n.patch({hours:c},`Allowed ${i.value}–${s.value}`)}};l.addEventListener("focusout",c=>{l.contains(c.relatedTarget)||d()});for(let c of[i,s])c.addEventListener("keydown",m=>{m.key==="Enter"&&(m.preventDefault(),d())});let p=e("button",{type:"button",role:"switch","aria-checked":o?"true":"false",class:`dl-switch${o?" on":""}`,"aria-label":"Limit hours",click:()=>n.patch({hours:o?"":"07:00-23:00"},o?"Any time":"Allowed 07:00–23:00")},e("i"));return e("div",{class:"dl-tile2"},[e("div",{class:"dl-tile2-row"},[e("div",{class:"dl-stack"},[e("span",{class:"dl-tile2-label"},"Allowed hours"),e("span",{},o?`${a} – ${r} (router time)`:"Any time")]),p]),o?l:""])}function ga(n){let t=n.p,o=xe(["internet","lan","both"].map(a=>[a,[g(a==="internet"?"globe":a==="lan"?"home":"shield"),a==="internet"?"Internet":a==="lan"?"Home":"Both"]]),t.access,{label:"Access",cls:"wide",optimistic:!1,onChange:a=>n.patch({access:a},`Access: ${et[a]}`)});return e("section",{class:"dl-devsec","aria-label":"Access and limits"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Access & limits")]),e("div",{class:"dl-panel"},[e("div",{class:"dl-stack gap8"},[e("span",{class:"dl-tile2-label"},"Can reach"),o,e("span",{class:"dl-sub"},ii[t.access]),t.access==="lan"&&n.st.services.length?ua(n):"",Je(t)?pa(n):"",t.access==="lan"?ca(n):""]),e("div",{class:"dl-tiles2"},[ha(n),ma(n),si(n),li(n),di(n)])])])}function ci(n){let t=n.st,o=e("div",{class:"dl-panel-head pad"},[e("h3",{},"Locations"),e("span",{class:"dl-spacer"}),t.geo.enabled?Xt("30d",r=>n.map?.setRange(r),!1):"",D("Hide",()=>{n.mapOpen=!1,n.map?.destroy(),n.map=null,n.paintPlaces()},"neutral")]);if(!t.geo.enabled)return e("div",{class:"dl-panel flush"},[o,e("div",{class:"dl-map-off"},["Locations are off. ",e("a",{href:L.url("admin/network/dawnline/settings")},"Turn them on in Settings"),"."])]);let a=new gt({openPerson:()=>{},openDevice:(r,i)=>{let s=n.p.devices.find(l=>l.id===i);s&&He(n.p,s,n.deviceOpts())}},"30d",280);return n.map=a,requestAnimationFrame(()=>a.mount(n.mapData())),e("div",{class:"dl-panel flush"},[o,a.el])}function va(n){let t=n.st;if(!t.geo.enabled)return e("div",{class:"dl-places"},[g("pin"),e("div",{class:"dl-stack"},[e("span",{},"Locations are off"),e("span",{class:"dl-sub"},"City-level, from the client IP")]),e("span",{class:"dl-spacer"}),e("a",{class:"cbi-button cbi-button-neutral",href:L.url("admin/network/dawnline/settings")},"Turn on")]);if(n.mapOpen)return n.map&&n.parts.places.contains(n.map.el)?null:ci(n);let o=t.now-30*86400,a=t.geo.points.filter(s=>s.person===n.p.id&&s.ts>=o).sort((s,l)=>l.ts-s.ts),r=[...new Set(a.map(s=>s.city||s.country).filter(Boolean))],i=a[0];return e("div",{class:"dl-places"},[g("pin"),e("div",{class:"dl-stack"},[e("span",{},i?i.city||i.country:"No locations yet"),e("span",{class:"dl-sub"},i?`${r.length} place${r.length===1?"":"s"} in 30 days${i.org?` · ${i.org}`:""}`:"Shown after a device connects")]),e("span",{class:"dl-spacer"}),a.length?D("Show map",()=>{n.mapOpen=!0,n.paintPlaces()},"neutral"):""])}function ba(n){let t=n.p,o=n.st,a=n.events.filter(l=>l.person===t.id),r=[],i=[...a].reverse();for(let l=0;l1){let m=c.querySelector(".dl-row-main");dom.content(m,[...Mn(o,d).slice(0,3),e("span",{class:"dl-muted"},`${p} times`)]),m.title=i.slice(l,l+p).map(v=>v.detail??"").join(` +`)}r.push(c),l+=p-1}let s=D([g("more")],()=>we(s,[{label:"Export CSV",icon:g("download"),run:()=>je(o,a,"csv",t.id)},{label:"Export JSON",icon:g("download"),run:()=>je(o,a,"json",t.id)},null,{label:`Clear ${t.name}'s activity`,icon:g("trash"),danger:!0,run:()=>Fe(`Clear ${t.name}'s activity`,`Removes events about ${t.name} and their devices.`,{person:t.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-sub"},a.length>10?`latest 10 of ${a.length}`:""),e("span",{class:"dl-spacer"}),s]),r.length?r:e("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var dn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(t){let[o,a,r]=await Promise.all([E.status(30),t?E.events(5e3).catch(()=>null):Promise.resolve(null),t?E.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:a?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(t){this.take(t);let o=this.st.people.find(s=>s.id===this.id);if(!o)return e("div",{class:"dl-empty"},[e("h3",{},"Person not found"),e("p",{},"They may have been removed."),e("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["head","devices","traffic","places","activity","limits"])this.parts[s]=e("div",{});this.parts.devices.className="dl-person-devices";let a=e("div",{},[e("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[e("a",{href:ht(o.server)},this.st.servers.find(s=>s.id===o.server)?.name??"Servers"),e("span",{},"/"),e("a",{href:ht(o.server)},"People"),e("span",{},"/"),e("span",{},o.name)]),this.parts.head,e("div",{class:"dl-grid-person"},[e("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),e("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(s=>s.id===r.get("device"));return i?setTimeout(()=>He(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>ot(this.p,this.deviceOpts()),50),this.poller=Ke({fetch:()=>{let s=this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(s)},every:15,active:()=>a.isConnected,apply:(s,l)=>this.apply(s,l)}),a}take(t){this.st=t.st,t.ev&&(this.events=t.ev),t.use&&(this.series=t.use.person,this.devSeries=t.use.devices)}apply(t,o){this.take(t);let a=this.st.people.find(r=>r.id===this.id);if(!a){o||(location.href=ht(this.p?.server));return}this.p=a,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(t,o){var i;this.poller?.claim();let a=await U(()=>E.personUpdate(this.p.id,t),o);if(!a)return;this.poller?.claim();let r=this.st.people.findIndex(s=>s.id===this.p.id);(i=a.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=a.person),this.p=a.person,this.paint()}get today(){return Ne(this.series.length?this.series:this.st.series)}get core(){return mt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}paint(t=!1){_e(this.parts.head,sa(this),t),_e(this.parts.traffic,la(this),t),_e(this.parts.devices,da(this),t),_e(this.parts.limits,ga(this),t),this.paintPlaces(t),_e(this.parts.activity,ba(this),t)}paintPlaces(t=!1){let o=va(this);o&&_e(this.parts.places,o,t&&!this.mapOpen)}};var pi={ok:"check",warn:"alert",error:"x",skip:"pause"},cn=class{constructor(t,o,a,r){this.el=e("div",{});this.wdEl=e("div",{});this.checksEl=e("div",{class:"dl-panel"});this.recentEl=e("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=e("div",{});this.open=new Set;this.st=t,this.sl=o,this.events=a,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,e("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,a)}async run(t){let o=t?await on(t):await E.health().catch(()=>null);o&&(this.take(o),t==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(t){this.checks=t.checks,this.paintChecks(),this.paintLive(t,this.events)}paintChecks(){let t=this.checks;if(!t){dom.content(this.summary,""),dom.content(this.checksEl,[e("div",{class:"dl-panel-head"},[e("h3",{},"Checks")]),e("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=t.filter(s=>s.status==="error").length,a=t.filter(s=>s.status==="warn").length;dom.content(this.summary,o?dt("error",`${o} problem${o>1?"s":""} need attention.`):a?dt("warn",`${a} warning${a>1?"s":""}.`):dt("ok","All checks passed."));let r=new Map;for(let s of this.sl.watchdog.repairs)r.set(s.id,Math.max(r.get(s.id)??0,s.ts));let i=()=>this.run();dom.content(this.checksEl,[e("div",{class:"dl-panel-head"},[e("h3",{},"Checks"),e("span",{class:"dl-spacer"}),D("Run again",i)]),e("ul",{class:"dl-checks"},t.map(s=>e("li",{},[e("span",{class:`dl-check-icon ${s.status}`},g(pi[s.status])),e("div",{class:"dl-check-body"},[e("div",{class:"dl-check-title"},s.title),e("div",{class:"dl-check-detail"},s.detail),r.has(s.id)?e("div",{class:"dl-check-repaired"},`Repaired by the watchdog at ${wt(r.get(s.id))}`):""]),Pn(s,l=>void this.run(l),i)])))])}paintLive(t,o){this.sl=t,this.events=o;let a=t.watchdog,r=a.beat!=null&&a.now-a.beat>180,i=a.repairs.filter(d=>a.now-d.ts<86400),s=i[i.length-1],l=fe(a.enabled,"Watchdog repairs",async d=>{await U(()=>E.settingsUpdate({watchdog:d?"1":"0"}),d?"Watchdog on":"Watchdog off")||_n(l,!d);let c=await E.serviceLog().catch(()=>null);c&&this.paintLive(c,this.events)});dom.content(this.wdEl,e("div",{class:"dl-panel dl-wd"},[e("div",{class:"dl-wd-head"},[e("span",{class:`dl-wd-tile${a.enabled?"":" off"}`},g("shield")),e("div",{class:"dl-stack"},[e("span",{class:"dl-wd-title"},"Watchdog"),e("span",{class:"dl-sub"},a.enabled?"Every minute it checks the tunnels and services and repairs what it can on its own.":"Off: problems are only written to the log. Nothing is repaired on its own.")]),e("span",{class:"dl-spacer"}),l]),e("div",{class:"dl-wd-foot"},[e("div",{class:"dl-wd-chips"},a.targets.map(d=>e("span",{class:`dl-check-chip${d.ok?"":" error"}`,title:d.ok?"OK":`Not working${d.tries?` · ${d.tries} repair${d.tries>1?"s":""}`:""}`},[g(d.ok?"check":"x"),d.name]))),e("span",{class:`dl-sub${r?" dl-warn-text":""}`},r?`The agent has not checked in for ${Math.round((a.now-a.beat)/60)} min; cron restarts it after 5.`:[a.last?`Looked ${le(a.last,a.now)}`:"Starts within a minute"," · ",i.length?`${i.length} repair${i.length>1?"s":""} today, last ${s.name} at ${wt(s.ts)}`:"no repairs today"])])])),this.paintRecent()}paintRecent(){let t=(this.sl.watchdog.now||Date.now()/1e3)-604800,o=[...this.events.map(r=>({ts:r.ts,ev:r})),...this.sl.log.map(r=>({ts:r.ts,sys:r}))].filter(r=>r.ts>=t&&jt(r)).sort((r,i)=>i.ts-r.ts),a=e("div",{class:"dl-panel-head pad"},[e("h3",{},"Recent problems"),e("span",{class:"dl-spacer"}),o.length?e("a",{href:"#",click:r=>(r.preventDefault(),this.toLog())},"All in Log →"):""]);if(!o.length){dom.content(this.recentEl,[a,e("div",{class:"dl-recent-empty"},[e("span",{class:"dl-check-icon ok"},g("check")),"No problems in the last 7 days."])]);return}dom.content(this.recentEl,[a,...o.slice(0,8).map(r=>{if(r.sys){let i=r.sys,s=`${i.ts}|${i.msg}`;return en(i,this.open.has(s),()=>{this.open.delete(s)||this.open.add(s),this.paintRecent()},wt(i.ts))}return Ye(this.st,r.ev,{time:wt(r.ts)})})])}};var pn=300,mi=["all","connections","people","system","problems"],un=class{constructor(t,o,a){this.events=[];this.system=[];this.kind="all";this.shown=pn;this.open=new Set;this.list=e("div",{});this.sub="";this.tabs=e("div",{class:"dl-seg",role:"tablist"});this.st=t,this.take(o),this.system=a,this.el=e("div",{},[e("div",{class:"dl-toolbar"},[this.tabs]),this.list]),this.paint()}actions(){let t=()=>this.kind==="all"?"":this.kind,o=i=>()=>{let s=this.filtered().reverse();je(this.st,s.filter(l=>l.ev).map(l=>l.ev),i,t(),s.filter(l=>l.sys).map(l=>l.sys))},a=D([g("download")," Export"],()=>we(a,[{label:"CSV (spreadsheet)",icon:g("download"),run:o("csv")},{label:"JSON",icon:g("download"),run:o("json")}])),r=D([g("trash")," Clear"],()=>Fe("Clear the log","Removes events from the log on the router.",{},()=>this.reload(),this.kind==="all"?void 0:this.kind,!0));return[a,r]}take(t){this.events=t.events,this.policy=t.policy;let o=pt.filter(a=>!t.policy.categories.includes(a));this.sub=`${Ut(t.policy)}${o.length?` Not recorded: ${o.map(a=>nt[a].toLowerCase()).join(", ")}.`:""}`}async reload(){let[t,o]=await Promise.all([E.events(2e4).catch(()=>null),E.serviceLog().catch(()=>null)]);t&&this.take(t),o&&(this.system=o.log),this.paint()}items(){return[...this.events.map(t=>({ts:t.ts,ev:t})),...this.system.map(t=>({ts:t.ts,sys:t}))].sort((t,o)=>o.ts-t.ts)}matches(t,o){return o==="all"?!0:o==="problems"?jt(t):o==="system"?!!t.sys:!!t.ev&&$t(t.ev.type)===o}filtered(){return this.items().filter(t=>this.matches(t,this.kind))}paintTabs(t){dom.content(this.tabs,mi.map(o=>e("button",{type:"button",role:"tab",class:o===this.kind?"on":"","aria-selected":o===this.kind?"true":"false",click:()=>this.show(o)},[o==="all"?"All":o==="system"?"System":nt[o],e("b",{},String(t.filter(a=>this.matches(a,o)).length))])))}show(t){this.kind=t,this.shown=pn,this.paint()}paint(){this.paintTabs(this.items());let t=this.filtered();if(!t.length){dom.content(this.list,e("div",{class:"dl-empty"},[e("p",{},this.events.length||this.system.length?"No events match.":"The log is empty.")]));return}let o=[],a="",r=null;for(let i of t.slice(0,this.shown)){let s=Po(i.ts);s!==a&&(a=s,r=e("div",{class:"dl-panel flush"},e("div",{class:"dl-panel-head pad"},e("h3",{},s))),o.push(r));let l=new Date(i.ts*1e3).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});if(i.sys){let d=`${i.sys.ts}|${i.sys.msg}`;r.appendChild(en(i.sys,this.open.has(d),()=>{this.open.delete(d)||this.open.add(d),this.paint()},l))}else r.appendChild(Ye(this.st,i.ev,{time:l}))}t.length>this.shown&&o.push(e("div",{class:"dl-more-row"},D(`Show ${Math.min(pn,t.length-this.shown)} more of ${t.length-this.shown}`,()=>{this.shown+=pn,this.paint()}))),dom.content(this.list,o)}};var hi=[["health","Health"],["log","Log"]],Hn=2e4,mn=class{constructor(){this.tab=new URLSearchParams(location.search).get("tab")==="log"?"log":"health";this.segEl=e("div",{class:"dl-seg dl-srvsections dl-diag-tabs",role:"tablist","aria-label":"Diagnostics"});this.subEl=e("span",{class:"dl-muted"});this.actionsEl=e("div",{class:"dl-row-actions"});this.bodyEl=e("div",{});this.eventsAt=0}load(){return this.eventsAt=Date.now(),Promise.all([E.status(1),E.events(Hn),E.serviceLog()])}render([t,o,a]){return this.log=new un(t,o,a.log),this.health=new cn(t,a,o.events,()=>{this.show("log"),this.log.show("problems")}),this.show(this.tab),Ke({fetch:async()=>{let r=this.tab==="log",[i,s]=await Promise.all([E.serviceLog().catch(()=>null),r?E.events(Hn).catch(()=>null):Promise.resolve(null)]);return i||s?{n:i,e:s}:null},every:10,active:()=>this.bodyEl.isConnected,apply:({n:r,e:i})=>this.take(r,i)}),e("div",{},[e("div",{class:"dl-pagehead"},[e("div",{class:"dl-stack"},[e("h2",{class:"dl-h1"},"Diagnostics"),this.subEl]),this.actionsEl]),this.segEl,this.bodyEl])}take(t,o){o&&(this.log.take(o),this.eventsAt=Date.now()),t&&(this.log.system=t.log),t&&this.health.paintLive(t,o?.events??this.health.events),this.tab==="log"&&this.log.paint()}show(t){this.tab=t,dom.content(this.segEl,hi.map(([o,a])=>e("button",{type:"button",role:"tab",class:o===t?"on":"","aria-selected":o===t?"true":"false",click:()=>o!==this.tab&&this.show(o)},a))),this.bodyEl.replaceChildren(t==="log"?this.log.el:this.health.el),this.subEl.textContent=t==="log"?this.log.sub:"Everything Dawnline depends on, checked live. The watchdog repairs what it can on its own.",dom.content(this.actionsEl,t==="log"?this.log.actions():""),t==="log"?(this.log.paint(),Date.now()-this.eventsAt>1e4&&E.events(Hn).then(o=>this.take(null,o)).catch(()=>null)):this.health.checks||this.health.run()}};var xa=":root{--dl-card: var(--panel-bg, var(--background-color-high, transparent));--dl-elevated: var(--elevated, var(--background-color-high, Canvas));--dl-line: var(--border, var(--border-color-medium, color-mix(in srgb, currentColor 14%, transparent)));--dl-soft: var(--muted, color-mix(in srgb, currentColor 5%, transparent));--dl-soft-hover: var(--soft-hover, color-mix(in srgb, currentColor 10%, transparent));--dl-fg: var(--foreground, var(--text-color-highest, inherit));--dl-fg-muted: var(--muted-foreground, color-mix(in srgb, currentColor 65%, transparent));--dl-fg-faint: var(--text-tertiary, color-mix(in srgb, currentColor 50%, transparent));--dl-accent: var(--accent, #3a83f7);--dl-ok: var(--success, #00a240);--dl-warn: var(--warning, #e25507);--dl-bad: var(--danger, #e02e2a);--dl-ok-wash: var(--success-a15, color-mix(in srgb, #00a240 15%, transparent));--dl-warn-wash: var(--warning-a15, color-mix(in srgb, #e25507 15%, transparent));--dl-bad-wash: var(--destructive-a15, color-mix(in srgb, #e02e2a 15%, transparent));--dl-info-wash: var(--info-a15, color-mix(in srgb, #3a83f7 15%, transparent));--dl-info: var(--info, #2c67c5);--dl-track: var(--foreground-a10, color-mix(in srgb, currentColor 10%, transparent));--dl-chart-1: var(--chart-blue, #3a83f7);--dl-chart-2: var(--chart-green, #00a240);--dl-ring: var(--ring, #3a83f7);--dl-primary: var(--primary, #0d0d0d);--dl-primary-fg: var(--primary-foreground, #fff);--dl-mono: var(--font-mono, ui-monospace, Menlo, Consolas, monospace);--dl-shadow: var(--shadow-sm, none);--dl-radius: 16px}.dl-icon-wrap{display:inline-flex;align-items:center;justify-content:center;line-height:0}.dl-icon{width:16px;height:16px}.dl-icon-btn{display:inline-flex!important;align-items:center;gap:6px}.dl-muted{color:var(--dl-fg-muted)}.dl-faint,.dl-sep{color:var(--dl-fg-faint)}.dl-nowrap{white-space:nowrap}.dl-mono{font-family:var(--dl-mono);font-size:13px}.dl-spacer{flex:1}.dl-pill{display:inline-flex;align-items:center;gap:4px;height:20px;padding:0 8px;border-radius:999px;font-size:12px;line-height:20px;font-weight:500;white-space:nowrap;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pill.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-pill.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-pill.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-pill.accent{background:var(--dl-info-wash);color:var(--dl-info)}.dl-pill.off{opacity:.75}.dl-panel{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);padding:16px;margin:0 0 16px;min-width:0;box-shadow:var(--dl-shadow)}.dl-panel-head{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;margin:0 0 12px}.dl-panel-head h3{margin:0!important;padding:0;font-size:16px;line-height:24px;font-weight:500;border:0;background:none}.dl-tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin:0 0 16px}.dl-tile{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);padding:14px 16px;min-width:0;box-shadow:var(--dl-shadow)}.dl-tile-label{font-size:12px;line-height:16px;font-weight:500;color:var(--dl-fg-faint)}.dl-tile-value{font-size:24px;line-height:32px;font-weight:500;margin-top:4px;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;letter-spacing:-.01em}.dl-tile-sub{font-size:12px;line-height:16px;color:var(--dl-fg-muted);margin-top:2px;font-variant-numeric:tabular-nums}.dl-grid2{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(0,1fr);gap:0 16px}@media(max-width:960px){.dl-grid2{grid-template-columns:minmax(0,1fr)}}.dl-chart{display:block;width:100%;height:120px}.dl-bar-down{fill:var(--dl-chart-1)}.dl-bar-up{fill:var(--dl-chart-2);opacity:.8}.dl-legend{display:flex;gap:16px;font-size:12px;color:var(--dl-fg-muted);margin-top:8px}.dl-legend i{display:inline-block;width:8px;height:8px;border-radius:999px;margin-right:6px;vertical-align:0}.dl-legend .down{background:var(--dl-chart-1)}.dl-legend .up{background:var(--dl-chart-2)}.dl-events{list-style:none;margin:0;padding:0}.dl-events li{display:flex;gap:12px;align-items:baseline;padding:8px 0;border-top:1px solid var(--dl-line);font-size:14px;line-height:20px;min-width:0}.dl-events li:first-child{border-top:0;padding-top:0}.dl-ev-time{flex:0 0 88px;color:var(--dl-fg-faint);font-variant-numeric:tabular-nums;white-space:nowrap;font-size:13px}.dl-ev-dot{flex:0 0 auto;width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);transform:translateY(-2px)}.dl-ev-dot.ok{background:var(--dl-ok)}.dl-ev-dot.warn{background:var(--dl-warn)}.dl-ev-dot.bad{background:var(--dl-bad)}.dl-ev-dot.accent{background:var(--dl-accent)}.dl-row>.dl-ev-dot,.dl-dev-log-row>.dl-ev-dot{margin:0 4px}.dl-ev-tile{flex:none;display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;margin:-2px -4px;border-radius:7px;background:color-mix(in srgb,var(--dl-accent) 16%,transparent);color:var(--dl-accent);align-self:center}.dl-ev-tile .dl-icon-wrap{display:inline-flex}.dl-ev-tile .dl-icon{width:14px;height:14px}.dl-row.dl-ev-by-admin{background:color-mix(in srgb,var(--dl-accent) 6%,transparent)}.dl-you{color:var(--dl-accent);font-weight:500}.dl-ev-kind{color:var(--dl-fg-faint)}.dl-slotbar{display:flex;align-items:center;gap:8px;margin:8px 0 0 44px}.dl-slotbar-segs{display:flex;gap:3px;flex:none;max-width:100%}.dl-slotbar-segs i{flex:1;min-width:2px;display:block;height:4px;border-radius:2px;background:var(--dl-soft-hover)}.dl-slotbar-segs i.used{background:var(--dl-fg-muted)}.dl-slotbar-text{font-size:12px;color:var(--dl-fg-faint);font-variant-numeric:tabular-nums}.dl-slotbar-segs i.over{background:color-mix(in srgb,var(--dl-warn) 80%,transparent)}.dl-ev-srv{flex:none;font-size:11px;line-height:18px;padding:0 8px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted);white-space:nowrap}.dl-ev-by-system{--sys: var(--dl-fg-muted)}.dl-ev-by-system.ok{--sys: var(--dl-ok)}.dl-ev-by-system.warn{--sys: var(--dl-warn)}.dl-ev-by-system.bad{--sys: var(--dl-bad)}.dl-ev-tile.ev{background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-ev-tile.ev.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-ev-tile.ev.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-ev-tile.ev.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-ev-tile.ev.accent{background:color-mix(in srgb,var(--dl-accent) 16%,transparent);color:var(--dl-accent)}.dl-ev-tile.sys{background:color-mix(in srgb,var(--sys) 16%,transparent);color:var(--sys)}.dl-row.dl-ev-by-system{background:color-mix(in srgb,var(--sys) 6%,transparent)}.dl-sys-src{color:var(--sys)}.dl-ev-by-system:not(.ok):not(.warn):not(.bad) .dl-sys-src{color:var(--dl-fg)}.dl-ev-text{min-width:0;overflow-wrap:anywhere}.dl-server{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px}.dl-server-name{font-size:16px;line-height:24px;font-weight:500}.dl-kv{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:6px 24px;margin:12px 0 0;font-size:14px;line-height:20px}.dl-kv dt{color:var(--dl-fg-muted);font-weight:400;margin:0}.dl-kv dd{margin:0;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}";var wa='.dl-plist{display:block}.dl-plist>.dl-card{display:block;margin:0 0 12px;padding:16px;min-width:0;background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);box-shadow:var(--dl-shadow)}.dl-plist>.dl-card.dl-filtered{display:none}.dl-plist>.dl-card.dl-off .dl-card-name,.dl-plist>.dl-card.dl-off .dl-avatar{opacity:.6}.dl-plist-none{color:var(--dl-fg-muted);text-align:center;padding:28px 16px;background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius)}.dl-card-head{display:flex;align-items:center;flex-wrap:wrap;gap:6px 8px}.dl-avatar{flex:0 0 auto;width:32px;height:32px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;font-size:12px;font-weight:600;color:var(--dl-fg);background:var(--dl-soft);position:relative;margin-right:4px;letter-spacing:.02em}.dl-avatar.online:after{content:"";position:absolute;right:-1px;bottom:-1px;width:9px;height:9px;border-radius:50%;background:var(--dl-ok);box-shadow:0 0 0 2px var(--dl-card)}.dl-card-name{font-size:16px;line-height:24px;font-weight:500}.dl-card-slug{font-size:13px;color:var(--dl-fg-faint);font-family:var(--dl-mono)}.dl-quota{margin:8px 0 0 44px;max-width:320px;height:6px;border-radius:999px;background:var(--dl-track);overflow:hidden}.dl-quota>i{display:block;height:100%;background:var(--dl-accent);border-radius:999px}.dl-quota.warn>i{background:var(--dl-warn)}.dl-quota.bad>i{background:var(--dl-bad)}.dl-chips{display:flex;flex-wrap:wrap;gap:6px;margin:12px 0 0 44px}.dl-chip{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:6px;max-width:240px;height:28px;padding:0 12px 0 10px;border-radius:999px;font-size:13px;background:var(--dl-soft);color:var(--dl-fg);transition:background .15s}.dl-chip:hover{background:var(--dl-soft-hover)}.dl-chip:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-chip .dl-icon{width:14px;height:14px;color:var(--dl-fg-muted)}.dl-chip.add{background:transparent;box-shadow:inset 0 0 0 1px var(--dl-line);color:var(--dl-fg-muted);aspect-ratio:1;padding:0;justify-content:center}.dl-chip.add:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-chip.disabled .dl-chip-name{text-decoration:line-through;color:var(--dl-fg-faint)}.dl-chip-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-dot{flex:0 0 auto;width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);opacity:.6}.dl-dot.online{background:var(--dl-ok);opacity:1;box-shadow:0 0 0 3px var(--dl-ok-wash)}.dl-empty{text-align:center;padding:40px 16px;background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius)}.dl-empty .dl-icon-wrap{width:40px;height:40px;border-radius:12px;background:var(--dl-soft);margin-bottom:12px}.dl-empty .dl-icon{width:20px;height:20px}.dl-empty h3{margin:0 0 4px!important;font-size:16px;font-weight:500}.dl-empty p{margin:0 0 16px;color:var(--dl-fg-muted);font-size:14px}.dl-toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px;margin:0 0 16px}.dl-toolbar .dl-muted{font-size:13px}@media(max-width:640px){.dl-slotbar,.dl-chips,.dl-quota{margin-left:0}.dl-btn-label{display:none}}.cbi-value.dl-block{display:block!important}.cbi-value.dl-block>.cbi-value-title{display:block;width:auto;float:none;text-align:left;padding:0 0 8px}.cbi-value.dl-block>.cbi-value-field{display:block;width:100%;margin:0}';var ya="#modal_overlay{z-index:1100!important}.dl-dd{position:fixed;z-index:1200;min-width:200px;padding:4px;border-radius:12px;background:var(--dl-elevated);border:1px solid var(--dl-line);box-shadow:0 12px 32px #0000004d;display:flex;flex-direction:column}.dl-dd button{all:unset;cursor:pointer;display:flex;align-items:center;gap:10px;padding:7px 10px;border-radius:8px;font-size:13px;color:var(--dl-fg)}.dl-dd button .dl-icon{width:15px;height:15px;color:var(--dl-fg-muted)}.dl-dd button:hover,.dl-dd button:focus-visible{background:var(--dl-soft)}.dl-dd button.danger,.dl-dd button.danger .dl-icon{color:var(--dl-bad, #e5484d)}.dl-dd button.warn,.dl-dd button.warn .dl-icon{color:var(--dl-warn)}.dl-dd hr{border:0;border-top:1px solid var(--dl-line);margin:4px 0}.dl-chipbtn b{font-weight:500;font-size:11px;margin-left:6px;opacity:.6}.dl-setsub{margin:20px 0 8px!important;font-size:13px;font-weight:500;color:var(--dl-fg)}.dl-row-actions{display:flex;flex-wrap:wrap;gap:8px;align-items:center}.dl-more-row{display:flex;justify-content:center;padding:8px 0 16px}.dl-dsec-actions{display:flex;align-items:center;gap:12px}.dl-kv-act{display:inline-flex;align-items:center;gap:12px;flex-wrap:wrap}.dl-linkbtn,.dl-bento-head a,.dl-bento-foot a,.dl-panel-head a,.dl-dsec-head a,.dl-tile2-foot a{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:4px;height:26px;padding:0 9px;margin:-4px -6px;border-radius:8px;font-size:12px;font-weight:500;color:var(--dl-fg-muted);text-decoration:none!important;white-space:nowrap;transition:background .12s,color .12s}.dl-bento-head a,.dl-bento-foot a,.dl-panel-head a,.dl-dsec-head a,.dl-tile2-foot a{color:var(--dl-accent)}.dl-linkbtn:hover,.dl-bento-head a:hover,.dl-bento-foot a:hover,.dl-panel-head a:hover,.dl-dsec-head a:hover,.dl-tile2-foot a:hover{background:var(--dl-soft);color:var(--dl-fg);text-decoration:none!important}.dl-bento-head a:hover,.dl-bento-foot a:hover,.dl-panel-head a:hover,.dl-dsec-head a:hover,.dl-tile2-foot a:hover{background:color-mix(in srgb,var(--dl-accent) 12%,transparent);color:var(--dl-accent)}.dl-linkbtn:focus-visible,.dl-bento-head a:focus-visible,.dl-bento-foot a:focus-visible,.dl-panel-head a:focus-visible{outline:2px solid var(--dl-ring);outline-offset:1px}.dl-linkbtn.danger:hover{color:var(--dl-bad);background:var(--dl-bad-wash)}.dl-ifcards{display:flex;flex-direction:column;gap:20px;margin:24px 0}.dl-ifcard .dl-setsec-body{gap:14px}.dl-iflead{display:flex;flex-direction:column;gap:2px;padding-top:14px;border-top:1px solid var(--dl-line)}.dl-iflead b{font-size:14px;font-weight:500}.dl-ifgroup h4{margin:0 0 8px!important;padding:0!important;font-size:11px!important;font-weight:500!important;letter-spacing:.06em;text-transform:uppercase;color:var(--dl-fg-muted);border:0!important;background:none!important}.dl-ifgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:8px}.dl-if{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:10px;min-height:52px;padding:8px 12px 8px 10px;min-width:0;border:1px solid var(--dl-line);border-radius:10px;background:var(--dl-card);transition:background .15s,border-color .15s}.dl-if:hover{background:var(--dl-soft)}.dl-if:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-if-ic{width:30px;height:30px;border-radius:8px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-if-ic .dl-icon{width:16px;height:16px}.dl-if-main{display:flex;flex-direction:column;min-width:0;flex:1}.dl-if-name{font-size:13.5px;font-weight:500;color:var(--dl-fg);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-if-sub{font:11px/16px var(--dl-mono);color:var(--dl-fg-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-if.sel{border-color:var(--dl-accent);background:color-mix(in srgb,var(--dl-accent) 9%,transparent)}.dl-if.sel .dl-if-ic{background:color-mix(in srgb,var(--dl-accent) 18%,transparent);color:var(--dl-accent)}.dl-if-check{color:var(--dl-accent);display:inline-flex}.dl-if-check .dl-icon{width:16px;height:16px}.dl-if.auto{border-color:color-mix(in srgb,var(--dl-ok) 55%,transparent);background:var(--dl-ok-wash);cursor:default}.dl-if.auto .dl-if-ic{background:color-mix(in srgb,var(--dl-ok) 18%,transparent);color:var(--dl-ok)}.dl-if-badge{display:inline-flex;align-items:center;gap:5px;font-size:10.5px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;flex:0 0 auto}.dl-if-badge.ok{color:var(--dl-ok)}.dl-if.off{cursor:default;opacity:.5}.dl-if.off:hover{background:var(--dl-card)}.dl-if.warn{border-color:color-mix(in srgb,var(--dl-warn) 60%,transparent)}.dl-if-wanctl{gap:10px;align-items:center}.dl-if-wanctl select{max-width:240px}.dl-if-summary{min-width:0;line-height:18px}.dl-warn{color:var(--dl-warn)}.dl-w-ip{width:160px}.dl-dnspick{padding-top:8px;border-top:1px solid var(--dl-line)}.dl-dnspick .dl-row-actions{gap:10px}.dl-note{display:flex;gap:8px;align-items:flex-start;padding:10px 12px;border-radius:10px;font-size:12.5px;line-height:18px;margin:0 0 10px;background:var(--dl-soft)}.dl-note.warn{background:var(--dl-warn-wash, color-mix(in srgb, var(--dl-warn) 14%, transparent))}.dl-note .dl-icon{width:15px;height:15px;flex:0 0 auto;margin-top:1px;color:var(--dl-warn)}.dl-stale{align-self:flex-start;margin-top:4px;font-size:10.5px}.dl-root .cbi-button.dl-btn-warn,.dl-btn-warn.cbi-button{background:var(--dl-warn-wash)!important;color:var(--dl-warn)!important;border-color:color-mix(in srgb,var(--dl-warn) 35%,transparent)!important}.dl-root .cbi-button.dl-btn-warn:hover,.dl-btn-warn.cbi-button:hover{background:color-mix(in srgb,var(--dl-warn) 24%,transparent)!important}.dl-btn-warn .dl-icon{color:var(--dl-warn)}.dl-srvtabs{display:flex;flex-wrap:wrap;gap:6px;padding:4px;margin:0 0 20px;border-radius:12px;background:var(--dl-soft);width:fit-content;max-width:100%}.dl-srvtab{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:8px;height:34px;padding:0 14px;border-radius:9px;font-size:13px;color:var(--dl-fg-muted);text-decoration:none!important;white-space:nowrap}.dl-srvtab b{font-weight:500}.dl-srvtab i.dot{width:7px;height:7px;border-radius:50%;background:var(--dl-fg-faint);flex:0 0 auto}.dl-srvtab i.dot.ok{background:var(--dl-ok);animation:dl-srv-pulse 2s ease-out infinite}.dl-srvtab i.dot.bad{background:var(--dl-bad)}@keyframes dl-srv-pulse{0%{box-shadow:0 0 color-mix(in srgb,var(--dl-ok) 55%,transparent)}70%,to{box-shadow:0 0 0 6px transparent}}@media(prefers-reduced-motion:reduce){.dl-srvtab i.dot.ok{animation:none}}.dl-srvtab:hover{color:var(--dl-fg);background:var(--dl-soft-hover)}.dl-srvtab.on{background:var(--dl-card);color:var(--dl-fg);box-shadow:0 1px 2px #0000002e,inset 0 0 0 1px var(--dl-line)}.dl-srvtab:focus-visible{outline:2px solid var(--dl-ring);outline-offset:1px}.dl-srvtab.add{color:var(--dl-fg-muted)}.dl-srvtab.add .dl-icon{width:14px;height:14px}.dl-srvhead{display:flex;flex-direction:column;gap:14px;margin:0 0 20px}.dl-srvhead .dl-title-row{display:flex;align-items:center;gap:10px}.dl-srvhead .dl-h1{margin:0!important}.dl-metrics.compact .dl-metric{padding:14px 18px}.dl-metrics.compact .dl-metric-value{display:flex;align-items:center;gap:6px;font-size:18px;line-height:26px;min-width:0}.dl-metrics.compact .dl-metric-value>span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.dl-metrics.compact .dl-metric-value .dl-mono{font-size:15px}.dl-metrics.compact .cbi-button{flex:0 0 auto}.dl-srvsections{margin:0 0 16px}.dl-srvbody>.dl-setsec,.dl-srvbody>.dl-ifcards{margin:0}.dl-srvbody .dl-ifcards{margin:0}.dl-metric-ic{display:inline-flex;align-items:center;gap:8px;font-size:16px}.dl-metric-ic .dl-icon{width:18px;height:18px;color:var(--dl-accent)}.dl-keyrow{display:inline-flex;align-items:center;gap:8px;min-width:0}.dl-keyrow code{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;background:none;padding:0}.dl-params{border:1px solid var(--dl-line);border-radius:12px;background:var(--dl-card)}.dl-params>summary{list-style:none;cursor:pointer;display:flex;align-items:center;gap:8px;padding:10px 14px;font-size:13px;color:var(--dl-fg);user-select:none}.dl-params>summary::-webkit-details-marker{display:none}.dl-params>summary>.dl-icon-wrap{display:inline-flex;color:var(--dl-fg-muted);transition:transform .15s}.dl-params>summary>.dl-icon-wrap .dl-icon{width:15px;height:15px}.dl-params[open]>summary>.dl-icon-wrap{transform:rotate(90deg)}.dl-params>summary:focus{outline:none}.dl-params>summary:focus-visible{outline:2px solid var(--dl-ring);outline-offset:-2px;border-radius:12px}.dl-params>summary:hover{background:var(--dl-soft);border-radius:12px}.dl-pcount{font-size:11px;padding:0 6px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:10px;padding:4px 14px 14px}.dl-pgroup{display:flex;flex-direction:column;gap:6px;padding:12px;border-radius:10px;background:var(--dl-soft);min-width:0}.dl-pgroup-head{display:flex;align-items:center;gap:8px;font-size:13px}.dl-pgroup-head b{font-weight:500}.dl-pgroup-head .dl-icon{width:14px;height:14px;color:var(--dl-fg-muted)}.dl-pgroup p{margin:0!important;font-size:12px;line-height:17px;color:var(--dl-fg-muted)}.dl-pvals{display:flex;flex-wrap:wrap;gap:4px;margin-top:2px}.dl-pv{display:inline-flex;align-items:stretch;max-width:100%;border-radius:6px;overflow:hidden;font:500 11.5px/22px var(--dl-mono);box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-pv i{font-style:normal;padding:0 6px;background:var(--dl-card);color:var(--dl-fg-faint)}.dl-pv b{font-weight:500;padding:0 7px;color:var(--dl-fg);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}";var ka=".dl-methods{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:10px}.dl-method{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;gap:10px;padding:14px;border-radius:12px;border:1px solid var(--dl-line);background:var(--dl-card);transition:border-color .15s,background .15s;min-width:0}.dl-method:hover{background:var(--dl-soft)}.dl-method:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-method.on{border-color:var(--dl-accent);background:color-mix(in srgb,var(--dl-accent) 8%,transparent);box-shadow:inset 0 0 0 1px var(--dl-accent)}.dl-method.off{cursor:not-allowed;opacity:.55}.dl-method.off:hover{background:var(--dl-card)}.dl-method-head{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px}.dl-method-head .dl-pill{flex:none}.dl-method-head b{font-weight:500;font-size:14.5px;flex:1}.dl-method-ic{width:32px;height:32px;border-radius:9px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;color:var(--dl-fg-muted);flex:0 0 auto}.dl-method-ic .dl-icon{width:17px;height:17px}.dl-method.on .dl-method-ic{background:color-mix(in srgb,var(--dl-accent) 18%,transparent);color:var(--dl-accent)}.dl-method p{margin:0!important;font-size:12.5px;line-height:18px;color:var(--dl-fg-muted);flex:1}.dl-method-meters{display:flex;gap:16px}.dl-dots{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--dl-fg-faint)}.dl-dots-row{display:inline-flex;gap:3px}.dl-dots-row i{width:6px;height:6px;border-radius:50%;background:var(--dl-line)}.dl-dots-row i.on{background:var(--dl-fg-muted)}.dl-method.on .dl-dots-row i.on{background:var(--dl-accent)}.dl-method-foot{display:flex;align-items:center;gap:6px;font-size:11.5px;color:var(--dl-fg-faint);padding-top:8px;border-top:1px solid var(--dl-line)}.dl-method-foot .dl-icon{width:13px;height:13px;flex:0 0 auto}.dl-method.off .dl-method-foot{color:var(--dl-warn)}.dl-ibadge{display:inline-flex;align-items:center;gap:3px;height:22px;padding:0 6px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted);flex:0 0 auto}.dl-ibadge .dl-icon{width:13px;height:13px}.dl-ibadge.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-ibadge.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-access{display:inline-flex;gap:4px;flex:0 0 auto}.dl-ibadge.lan{background:color-mix(in srgb,var(--dl-accent) 16%,transparent);color:var(--dl-accent)}.dl-ibadge.inet{background:var(--dl-ok-wash);color:var(--dl-ok)}";var $a=".dl-addrbar{display:inline-flex;align-items:stretch;flex-wrap:nowrap;max-width:100%;margin-top:4px;border:1px solid var(--dl-line);border-radius:10px;background:var(--dl-card);overflow:hidden}.dl-addrbar-seg{all:unset;box-sizing:border-box;display:inline-flex;align-items:center;gap:7px;padding:6px 12px;font-size:13px;color:var(--dl-fg-muted);border-left:1px solid var(--dl-line);white-space:nowrap;min-width:0}.dl-addrbar-seg:first-child{border-left:0}.dl-addrbar-seg .dl-icon{width:14px;height:14px;color:var(--dl-fg-faint);flex:0 0 auto}.dl-addrbar-seg .dl-mono{font-size:12.5px}.dl-addrbar-seg.main{cursor:pointer;color:var(--dl-fg)}.dl-addrbar-seg.main:hover{background:var(--dl-soft)}.dl-addrbar-seg.main:focus-visible{outline:2px solid var(--dl-ring);outline-offset:-2px}.dl-addrbar-seg.main>.dl-icon-wrap:last-child .dl-icon{opacity:.7}.dl-bento{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));grid-template-rows:auto auto;gap:10px;margin:0 0 20px}.dl-person-devices{margin-bottom:16px}.dl-person-head{display:flex;flex-direction:column;margin:0 0 20px}.dl-person-head>.dl-pagehead{margin-bottom:0;align-items:flex-start}.dl-pnote{all:unset;box-sizing:border-box;cursor:pointer;align-self:flex-start;display:inline-flex;align-items:flex-start;gap:6px;margin:10px 0 0 62px;max-width:60ch;padding:6px 12px 6px 10px;border-radius:10px;font-size:13px;line-height:18px;white-space:pre-line;background:var(--dl-soft);color:var(--dl-fg);box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-pnote:hover{background:var(--dl-soft-hover)}.dl-pnote .dl-icon{width:14px;height:14px;flex:none;margin-top:2px;color:var(--dl-fg-muted)}.dl-note-input{width:100%;box-sizing:border-box;min-height:80px;resize:vertical}.dl-dcard-trend{display:flex;align-items:flex-end;gap:12px;min-width:0}.dl-dcard-trend>.dl-stack{flex:none}.dl-dcard-trend b{font-size:16px;font-weight:500;font-variant-numeric:tabular-nums}.dl-dbars{flex:1;min-width:0;height:32px;display:flex;align-items:flex-end;gap:2px}.dl-dbars i{flex:1;min-width:0;border-radius:2px;background:var(--dl-chart-1);opacity:.55}.dl-dbars i.zero{background:var(--dl-track);opacity:1}.dl-dbars i.hi{opacity:1}.dl-dbars i:hover{opacity:1;filter:brightness(1.2)}.dl-datechip{position:relative;display:inline-flex}.dl-date-hidden{position:absolute!important;left:0;bottom:0;width:1px!important;min-width:0!important;height:1px!important;opacity:0;pointer-events:none;border:0!important;padding:0!important;margin:0!important}.dl-chipbtn .dl-icon{width:13px;height:13px}.dl-chipbtn:has(.dl-icon){display:inline-flex;align-items:center;gap:5px}.dl-places{display:flex;align-items:center;gap:12px;padding:12px 16px;border:1px solid var(--dl-line);border-radius:var(--dl-radius);background:var(--dl-card);font-size:14px}.dl-places>.dl-icon{width:18px;height:18px;color:var(--dl-fg-muted);flex:none}.dl-person-live{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:10px}.dl-person-live .dl-bento-head{flex-wrap:nowrap;white-space:nowrap;min-width:0}.dl-person-live .dl-bento-head>*{min-width:0;overflow:hidden;text-overflow:ellipsis}.dl-person-live .dl-bento-head>:first-child{flex:none}.dl-person-live.solo{grid-template-columns:minmax(0,1fr)}.dl-person-live:not(.solo) .dl-bento-tile.month>.dl-bento-head:first-child{flex-wrap:wrap;row-gap:2px}.dl-person-live:not(.solo) .dl-bento-tile.month>.dl-bento-head:first-child>.dl-sub{flex-basis:100%}.dl-person-live>.dl-bento-tile,.dl-person-live>.dl-bento-tile.month{grid-column:auto;grid-row:auto}@media(max-width:760px){.dl-person-live{grid-template-columns:minmax(0,1fr)}}.dl-bento-tile{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);padding:14px 16px;display:flex;flex-direction:column;gap:10px;min-width:0;box-shadow:var(--dl-shadow)}.dl-bento-tile.month{grid-column:1 / -1}.dl-onl-count{font-size:13px;line-height:22px;min-width:22px;padding:0 8px;border-radius:999px;background:var(--dl-soft);text-align:center;font-weight:500;font-variant-numeric:tabular-nums}.dl-onl-count.none{color:var(--dl-fg-faint)}.dl-onl-row{flex:1;display:flex;align-items:center;justify-content:center;gap:12px;min-width:0}.dl-onl-p{display:flex;flex-direction:column;align-items:center;gap:5px;width:104px;min-width:0;padding:6px 2px;border-radius:12px;color:var(--dl-fg)!important;text-decoration:none!important}.dl-onl-p:hover{background:var(--dl-soft)}.dl-onl-av{position:relative;width:42px;height:42px;border-radius:50%;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;font-size:13px;font-weight:500;box-shadow:0 0 0 2px var(--dl-ok)}.dl-onl-p.more .dl-onl-av{box-shadow:0 0 0 1px var(--dl-line);color:var(--dl-fg-muted)}.dl-onl-dev{position:absolute;right:-5px;bottom:-5px;width:20px;height:20px;border-radius:7px;background:var(--dl-card);box-shadow:0 0 0 1.5px var(--dl-card);display:inline-flex;align-items:center;justify-content:center;font-size:10px;color:var(--dl-fg-muted)}.dl-onl-dev .dl-icon-wrap{display:inline-flex}.dl-onl-dev .dl-icon{width:12px;height:12px}.dl-onl-name{font-size:12.5px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-onl-p .dl-sub{font-size:11px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-onl-row.grid{flex-wrap:wrap;align-content:center;gap:10px 8px;max-height:108px;overflow:hidden}.dl-onl-p.sm{width:auto;padding:4px}.dl-onl-p.sm .dl-onl-av{width:36px;height:36px;font-size:11.5px}.dl-onl-meta{display:inline-flex;align-items:center;gap:3px;font-size:11px;color:var(--dl-fg-faint);max-width:100%;white-space:nowrap;overflow:hidden}.dl-onl-meta .dl-icon-wrap{display:inline-flex}.dl-onl-meta .dl-icon{width:12px;height:12px}.dl-onl-av.sm{width:34px;height:34px;font-size:11.5px}.dl-tip-float:has(.dl-hc){padding:0;white-space:normal;border-radius:16px}.dl-hc{width:280px;padding:14px;display:flex;flex-direction:column;gap:10px}.dl-hc-head{display:flex;align-items:center;gap:10px}.dl-hc-head .dl-stack{flex:1;min-width:0}.dl-hc-head b{font-size:14px;font-weight:500}.dl-hc-since{font-size:11.5px;color:var(--dl-ok)}.dl-hc-reach{display:inline-flex;gap:4px}.dl-hc-speed{border-radius:12px;background:var(--dl-soft);padding:10px 12px;display:flex;flex-direction:column;gap:6px}.dl-hc-speed-row{display:flex;align-items:baseline;gap:12px;font-size:13px;font-variant-numeric:tabular-nums}.dl-hc-chart{display:block;width:100%;height:30px}.dl-hc-chart .area{fill:color-mix(in srgb,var(--dl-chart-1) 16%,transparent)}.dl-hc-chart .dn{fill:none;stroke:var(--dl-chart-1);stroke-width:1.5;vector-effect:non-scaling-stroke}.dl-hc-chart .up{fill:none;stroke:var(--dl-ok);stroke-width:1.2;vector-effect:non-scaling-stroke}.dl-hc-devs{display:flex;flex-wrap:wrap;gap:6px}.dl-hc-dev{display:inline-flex;align-items:center;gap:5px;height:24px;padding:0 9px;border-radius:999px;background:var(--dl-soft);font-size:11.5px}.dl-hc-dev .dl-icon-wrap{display:inline-flex}.dl-hc-dev .dl-icon{width:12px;height:12px;color:var(--dl-fg-muted)}.dl-hc-foot{display:flex;align-items:center;gap:8px;font-size:11.5px}.dl-disg-id{display:flex;align-items:center;gap:10px}.dl-disg-id b{font-size:16px;font-weight:500}.dl-disg-ic{width:36px;height:36px;border-radius:11px;background:color-mix(in srgb,var(--dl-accent) 14%,transparent);color:var(--dl-accent);display:inline-flex;align-items:center;justify-content:center;flex:none}.dl-disg-ic .dl-icon-wrap{display:inline-flex}.dl-disg-ic .dl-icon{width:18px;height:18px}.dl-disg-meters{display:grid;grid-template-columns:auto 1fr;gap:6px 10px;align-items:center;font-size:12px;color:var(--dl-fg-muted)}.dl-segs{display:inline-flex;gap:3px}.dl-segs i{width:18px;height:5px;border-radius:3px;background:var(--dl-track)}.dl-segs.acc i.on{background:var(--dl-accent)}.dl-segs.ok i.on{background:var(--dl-ok)}.dl-disg-chips{margin-top:auto;display:flex;flex-wrap:wrap;gap:5px}.dl-disg-chips span{font:11px/20px var(--dl-mono);padding:0 8px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted);white-space:nowrap}.dl-onl-empty{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;font-size:13px;text-align:center}.dl-bento-head{display:flex;align-items:center;justify-content:space-between;gap:10px;min-width:0}.dl-bento-head.start{justify-content:flex-start}.dl-bento-big{font-family:inherit;font-size:28px;line-height:34px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-bento-big small{font-size:13px;font-weight:400;color:var(--dl-fg-faint);letter-spacing:0}.dl-avstack{display:inline-flex}.dl-avstack .dl-avatar{margin-left:-7px;box-shadow:0 0 0 2px var(--dl-card)}.dl-avstack .dl-avatar:first-child{margin-left:0}.dl-avatar.more{background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-bento-list{display:flex;flex-direction:column;gap:2px}.dl-bento-row{display:flex;align-items:center;gap:10px;padding:8px;margin:0 -8px;border-radius:10px;color:var(--dl-fg)!important;text-decoration:none!important;min-width:0;transition:background .12s}.dl-bento-row:hover{background:var(--dl-soft)}.dl-bento-row:hover b{text-decoration:none}.dl-bento-row:focus-visible{outline:2px solid var(--dl-ring);outline-offset:-2px}.dl-bento-row-main{display:flex;flex-direction:column;gap:1px;flex:1;min-width:0}.dl-bento-row-main b{font-weight:500;font-size:13.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-bento-row-main .dl-sub{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-bento-row.off b{color:var(--dl-fg-muted);font-weight:400}.dl-bento-row-val{display:flex;flex-direction:column;align-items:flex-end;font-size:13px;font-variant-numeric:tabular-nums;white-space:nowrap}.dl-bento-row-val small{font-size:11px;color:var(--dl-fg-faint)}.dl-bento-sep{font-size:11px;color:var(--dl-fg-faint);padding:12px 0 4px}.dl-bento-devs{display:inline-flex;gap:3px;color:var(--dl-fg-faint)}.dl-bento-devs .dl-icon{width:13px;height:13px}.dl-bento-devs .on{color:var(--dl-ok)}.dl-bento-foot{display:flex;align-items:center;gap:10px;margin-top:auto;padding-top:10px;border-top:1px solid var(--dl-line);color:var(--dl-fg)!important;text-decoration:none!important}.dl-bento-foot.split,.dl-bento-foot.end{justify-content:space-between}.dl-bento-foot.end>a:only-child{margin-left:auto}.dl-bento-empty{display:flex;align-items:center;gap:10px;padding:14px 0;font-size:13.5px;color:var(--dl-fg-muted)}.dl-bento-empty .dl-icon{width:18px;height:18px}.dl-split{display:flex;height:6px;border-radius:3px;overflow:hidden;background:var(--dl-soft)}.dl-split i{display:block;height:100%}.dl-split i.dn{background:var(--dl-accent)}.dl-split i.up{background:var(--dl-ok)}.dl-dn{color:var(--dl-accent)}.dl-up{color:var(--dl-ok)}.dl-bento-method{display:flex;align-items:center;gap:8px;font-size:18px;font-weight:500}.dl-bento-method .dl-icon{width:20px;height:20px;color:var(--dl-accent)}.dl-meter{display:inline-flex;gap:3px}.dl-meter i{width:16px;height:4px;border-radius:2px;background:var(--dl-line)}.dl-meter i.on{background:var(--dl-accent)}.dl-bento-total{font-size:16px;font-weight:500;margin-left:8px}.dl-bento-bars{display:flex;align-items:flex-end;gap:3px;height:54px}.dl-bento-bars i{flex:1;min-width:0;border-radius:3px 3px 0 0;background:var(--dl-soft-hover);transition:background .15s}.dl-bento-bars i.future{height:4px;background:var(--dl-soft)}.dl-bento-bars i:hover{background:var(--dl-fg-faint)}.dl-bento-bars i.hi{background:var(--dl-accent)}@media(max-width:700px){.dl-addrbar{flex-wrap:wrap}}@media(max-width:900px){.dl-bento{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}.dl-bento-tile.online{grid-column:span 2}}@media(max-width:560px){.dl-bento{grid-template-columns:minmax(0,1fr)}.dl-bento-tile.online,.dl-bento-tile.month{grid-column:auto}}.dl-srvpagehead{display:flex;flex-direction:column;align-items:flex-start;gap:10px;margin:0 0 20px}.dl-srvpagehead>.dl-title-row{display:flex;align-items:center;gap:10px;width:100%;flex-wrap:wrap}.dl-srvpagehead .dl-actions{margin:0;flex-wrap:wrap}.dl-toolbar-end{display:flex;align-items:center;gap:8px;margin-left:auto;flex-wrap:nowrap;min-width:0}@media(max-width:640px){.dl-toolbar-end{flex-wrap:wrap;width:100%}}.dl-notices{margin:0 0 16px}.dl-notices .dl-need-row .dl-sub{overflow-wrap:anywhere}.dl-notices-more{font-size:13px;color:var(--dl-fg-muted);text-decoration:none}.dl-notices-more:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-speed-cols{display:grid;grid-template-columns:1fr 1fr;gap:12px}.dl-speed-col{display:flex;flex-direction:column;gap:2px;min-width:0}.dl-speed-val{font-size:20px;line-height:26px;font-weight:500;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-speed-today{display:flex;justify-content:space-between;gap:10px;font-size:12px;color:var(--dl-fg-muted);white-space:nowrap;font-variant-numeric:tabular-nums}.dl-speed-today b{font-weight:500;color:var(--dl-fg)}.dl-speed-chart{display:block;width:100%;height:44px}.dl-speed-chart .area{fill:color-mix(in srgb,var(--dl-accent) 16%,transparent)}.dl-speed-chart .line{fill:none;stroke:var(--dl-accent);stroke-width:1.5;vector-effect:non-scaling-stroke}.dl-speed-chart .line.up{stroke:var(--dl-ok);stroke-width:1.2;opacity:.85}.dl-speed-wait{height:44px;display:flex;flex-direction:column;justify-content:flex-end;gap:6px;font-size:11px;color:var(--dl-fg-faint)}.dl-speed-wait i{display:block;height:1px;background:var(--dl-line);order:2}.dl-fld{display:flex;flex-direction:column;gap:8px;margin:0 0 16px}.dl-fld-label{font-size:13px;font-weight:500;color:var(--dl-fg)}.dl-fld .cbi-input-text{width:100%;box-sizing:border-box}.dl-kinds{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:6px}.dl-kinds button{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;height:68px;border-radius:10px;border:1px solid var(--dl-line);color:var(--dl-fg-muted);font-size:12px;font-weight:500;text-align:center;min-width:0}.dl-kinds button .dl-icon{width:20px;height:20px}.dl-kinds button:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-kinds button:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-kinds button.on{border-color:var(--dl-accent);color:var(--dl-fg);background:color-mix(in srgb,var(--dl-accent) 10%,transparent);box-shadow:inset 0 0 0 1px var(--dl-accent)}.dl-kinds button.on .dl-icon{color:var(--dl-accent)}.dl-choices{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:8px}.dl-choice{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;gap:4px;padding:12px 14px;border-radius:12px;background:var(--dl-card);box-shadow:inset 0 0 0 1px var(--dl-line);transition:background .15s,box-shadow .15s}.dl-choice:hover{background:var(--dl-soft)}.dl-choice:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-choice.selected{box-shadow:inset 0 0 0 2px var(--dl-accent);background:var(--accent-a10, color-mix(in srgb, var(--dl-accent) 8%, transparent))}.dl-choice-title{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:500;color:var(--dl-fg)}.dl-choice-text{font-size:12px;line-height:16px;color:var(--dl-fg-muted)}.dl-attn-item>.cbi-button{margin-left:auto;flex:none;align-self:center}";var _a='.dl-steps{display:flex;align-items:center;gap:8px;margin:0 0 16px;flex-wrap:wrap}.dl-step{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:500;color:var(--dl-fg-faint)}.dl-step b{display:inline-flex;width:24px;height:24px;align-items:center;justify-content:center;border-radius:50%;background:var(--dl-soft);font-size:12px;font-weight:600}.dl-step.current{color:var(--dl-fg)}.dl-step.current b{background:var(--dl-primary);color:var(--dl-primary-fg)}.dl-step.done{color:var(--dl-fg-muted)}.dl-step.done b{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-step+.dl-step:before{content:"";width:24px;height:1px;background:var(--dl-line)}.dl-wizard .dl-panel>div{display:flex;flex-direction:column;gap:16px}.dl-wizard .dl-panel>div>p{margin:0!important;color:var(--dl-fg-muted)}.dl-wizard .dl-panel>div>.cbi-value{margin:0}.dl-wizard h4{font-size:14px;font-weight:500;margin:8px 0 -6px!important}.dl-wizard h4:first-child{margin-top:0!important}.dl-modal .cbi-tabmenu{margin-bottom:16px}.dl-invite{display:grid;grid-template-columns:250px minmax(0,1fr);gap:22px;align-items:start}.dl-invite img{display:block;width:100%;border-radius:18px;box-shadow:0 0 0 1px var(--dl-line)}.dl-invite-side{display:flex;flex-direction:column;gap:14px;min-width:0}.dl-invite-side>p{margin:0!important}.dl-invite-link{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:10px;min-width:0;padding:11px 14px;border-radius:12px;background:var(--dl-soft);font:13px/18px var(--dl-mono);color:var(--dl-fg)}.dl-invite-link>span:first-child{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-invite-link>.dl-icon-wrap{flex:none;display:inline-flex}.dl-invite-link .dl-icon{width:15px;height:15px;color:var(--dl-fg-muted);flex:none}.dl-invite-link:hover{background:var(--dl-soft-hover)}.dl-invite-link.alt{padding:8px 14px;font-size:12px;color:var(--dl-fg-muted)}.dl-invite-link>.dl-pill{flex:none}.dl-invite-steps{margin:0;padding-left:20px;list-style:decimal!important;font-size:13px;line-height:24px;color:var(--dl-fg-muted)}.dl-invite-steps b{color:var(--dl-fg);font-weight:500}.dl-invite-steps li{display:list-item!important;list-style:inherit!important;padding-left:4px}.dl-invite-actions{display:flex;gap:8px;flex-wrap:wrap}.modal:has(.dl-modal.wide){max-width:min(760px,94vw)!important;width:100%!important}@media(max-width:640px){.dl-invite{grid-template-columns:minmax(0,1fr)}.dl-invite img{max-width:260px;margin:0 auto}}.dl-toasts{position:fixed;left:50%;bottom:max(24px,env(safe-area-inset-bottom));transform:translate(-50%);z-index:100000;display:flex;flex-direction:column;align-items:center;gap:8px;pointer-events:none}.dl-toast{pointer-events:auto;display:inline-flex;align-items:center;gap:8px;max-width:min(520px,92vw);padding:10px 16px;border-radius:999px;background:var(--dl-fg);color:var(--dl-card);font-size:13px;line-height:18px;box-shadow:0 10px 30px #0000004d;opacity:0;transform:translateY(12px);transition:opacity .18s,transform .18s}.dl-toast.show{opacity:1;transform:none}.dl-toast .dl-icon-wrap{display:inline-flex}.dl-toast .dl-icon{width:15px;height:15px}.dl-toast.success .dl-icon{color:var(--dl-ok)}.dl-toast.error{background:var(--dl-bad);color:#fff}.dl-toast.error .dl-icon{color:#fff}.dl-toast.warning{background:var(--dl-warn);color:#111}.dl-toast.warning .dl-icon{color:#111}.dl-toast button{all:unset;cursor:pointer;display:inline-flex;margin-left:4px;opacity:.8}.dl-toast button:hover{opacity:1}';var Ea=".dl-setblock{display:flex;flex-direction:column;gap:8px;margin:0}.dl-addr-opts{display:flex;flex-direction:column;gap:6px}.dl-addr-opt{all:unset;box-sizing:border-box;cursor:pointer;display:grid;grid-template-columns:16px minmax(0,1fr) auto;gap:12px;align-items:center;padding:10px 14px;border-radius:12px;box-shadow:inset 0 0 0 1px var(--dl-line);min-width:0}.dl-addr-opt:hover{background:var(--dl-soft)}.dl-addr-opt.on{box-shadow:inset 0 0 0 1.5px var(--dl-accent);background:color-mix(in srgb,var(--dl-accent) 7%,transparent)}.dl-addr-opt .dl-mono{font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-addr-opt .dl-stack{min-width:0}.dl-addr-opt input{width:100%}.dl-addr-opt.other{cursor:default}.dl-addr-opt.other:hover{background:none}.dl-addr-opt.other input{width:100%}.dl-addr-check{width:16px;height:16px;border-radius:5px;box-shadow:inset 0 0 0 1.5px var(--dl-fg-faint);display:inline-flex;align-items:center;justify-content:center}.dl-addr-check .dl-icon-wrap{display:inline-flex}.dl-addr-check .dl-icon{width:12px;height:12px}.dl-addr-opt.on .dl-addr-check{background:var(--dl-accent);box-shadow:none;color:#fff}.dl-addr-opt.other .dl-addr-check{box-shadow:none;color:var(--dl-fg-muted)}.dl-addr-warn{display:inline-flex;align-items:center;gap:5px;font-size:12px;line-height:17px;color:var(--dl-warn)}.dl-addr-warn .dl-icon-wrap{display:inline-flex}.dl-addr-warn .dl-icon{width:13px;height:13px}.dl-pill.info{background:color-mix(in srgb,var(--dl-accent) 14%,transparent);color:var(--dl-accent)}.dl-links{border-radius:12px;background:var(--dl-soft);overflow:hidden}.dl-link-row{display:grid;grid-template-columns:18px minmax(0,1fr) auto;gap:10px;align-items:center;padding:11px 14px}.dl-link-row+.dl-link-row{border-top:1px solid var(--dl-line)}.dl-link-ic{display:inline-flex}.dl-link-ic .dl-icon{width:15px;height:15px}.dl-link-ic.ok .dl-icon{color:var(--dl-ok)}.dl-link-ic.warn .dl-icon{color:var(--dl-warn)}.dl-link-url{font-size:13px;color:var(--dl-fg-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-link-url b{font-weight:500;color:var(--dl-accent)}@media(max-width:640px){.dl-link-url,.dl-addr-opt .dl-mono,.dl-filecard .dl-ellipsis,.dl-invite-link>span:first-child{white-space:normal;overflow-wrap:anywhere}}.dl-ready-sum{display:flex;align-items:center;gap:12px;padding:12px 14px;border-radius:12px}.dl-ready-sum>.dl-icon-wrap{display:inline-flex}.dl-ready-sum>.dl-icon-wrap .dl-icon{width:18px;height:18px}.dl-ready-sum .dl-stack{flex:1;min-width:0}.dl-ready-sum b{font-weight:500;font-size:13px}.dl-ready-sum.ok{background:var(--dl-ok-wash)}.dl-ready-sum.ok b,.dl-ready-sum.ok .dl-icon{color:var(--dl-ok)}.dl-ready-sum.warn{background:var(--dl-warn-wash)}.dl-ready-sum.warn b,.dl-ready-sum.warn .dl-icon{color:var(--dl-warn)}.dl-ready-sum.error{background:var(--dl-bad-wash)}.dl-ready-sum.error b,.dl-ready-sum.error .dl-icon{color:var(--dl-bad)}.dl-check-chip{display:inline-flex;align-items:center;gap:5px;height:26px;padding:0 10px;border-radius:999px;background:var(--dl-soft);font-size:12px;color:var(--dl-fg-muted)}.dl-check-chip .dl-icon-wrap{display:inline-flex}.dl-check-chip .dl-icon{width:13px;height:13px;color:var(--dl-ok)}.dl-check-chip.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-check-chip.warn .dl-icon{color:var(--dl-warn)}.dl-check-chip.error{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-check-chip.error .dl-icon{color:var(--dl-bad)}.dl-ready-details{display:flex;flex-direction:column;gap:8px;padding:4px 2px}.dl-ready-details[hidden]{display:none}.dl-ready-item{display:flex;align-items:flex-start;gap:8px;font-size:13px;line-height:18px;min-width:0}.dl-ready-item .dl-icon-wrap{display:inline-flex;margin-top:1px}.dl-ready-item .dl-icon{width:15px;height:15px}.dl-ready-item.ok .dl-icon{color:var(--dl-ok)}.dl-ready-item.warn .dl-icon{color:var(--dl-warn)}.dl-ready-item.error .dl-icon{color:var(--dl-bad)}.dl-params-body{display:flex;flex-direction:column;gap:14px;padding:6px 14px 14px}.dl-params-body>.dl-setrow{margin:0;padding:0}.dl-pgrid.flush{padding:0;grid-template-columns:repeat(2,minmax(0,1fr))}@media(max-width:640px){.dl-pgrid.flush{grid-template-columns:minmax(0,1fr)}}.dl-qr-pane{display:flex;flex-direction:column;align-items:center;gap:8px;text-align:center}.dl-qr{width:min(280px,72vw);aspect-ratio:1;background:#fff;padding:8px;border-radius:12px;box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-qr svg{display:block;width:100%;height:100%}.dl-filecard{display:flex;align-items:center;gap:12px;padding:12px;border-radius:14px;background:var(--dl-soft);min-width:0}.dl-filecard>.dl-stack{flex:1;min-width:0}.dl-filecard-ic{width:40px;height:46px;border-radius:8px;flex:none;display:inline-flex;align-items:center;justify-content:center;font:10px var(--dl-mono);color:var(--dl-fg-muted);background:var(--dl-card);box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-params>.dl-conf{margin:0;border-top:1px solid var(--dl-line);border-radius:0 0 12px 12px;background:none}.dl-conf-sec{color:var(--dl-accent)}.dl-conf-k{color:var(--dl-fg-faint)}.dl-conf-mask{padding:0 6px;border-radius:4px;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-params>summary .dl-chipbtn{height:26px;font-size:12px}.dl-conf{white-space:pre-wrap;word-break:break-all;max-height:22em;overflow:auto;font-family:var(--dl-mono);font-size:12px;line-height:18px;margin:0;padding:12px;border-radius:12px;background:var(--dl-soft)}.dl-key{width:100%;box-sizing:border-box;font-family:var(--dl-mono);font-size:12px;word-break:break-all;min-height:7em}.dl-actions{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin:12px 0 0}.dl-link-box{display:flex;gap:6px;align-items:center;flex-wrap:wrap}.dl-link-box input{flex:1 1 18em;min-width:0;font-family:var(--dl-mono);font-size:12px}.dl-hint{font-size:12px;line-height:16px;color:var(--dl-fg-muted);margin:8px 0}.dl-divider{border:0;border-top:1px solid var(--dl-line);margin:16px 0}";var Sa=".dl-checks{list-style:none;margin:0;padding:0}.dl-checks li{display:flex;align-items:center;gap:12px;padding:12px 0;border-top:1px solid var(--dl-line)}.dl-checks li:first-child{border-top:0;padding-top:0}.dl-checks li:last-child{padding-bottom:0}.dl-check-icon{flex:0 0 auto;width:28px;height:28px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center}.dl-check-icon .dl-icon{width:14px;height:14px}.dl-check-icon.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-check-icon.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-check-icon.error{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-check-icon.skip{background:var(--dl-soft);color:var(--dl-fg-faint)}.dl-check-body{flex:1;min-width:0}.dl-check-title{font-size:14px;line-height:20px;font-weight:500}.dl-check-detail{font-size:12px;line-height:16px;color:var(--dl-fg-muted);overflow-wrap:anywhere}.dl-check-repaired{margin-top:2px;font-size:12px;line-height:16px;color:var(--dl-warn)}.dl-wd{margin:0 0 16px;display:flex;flex-direction:column;gap:14px}.dl-wd-head{display:flex;align-items:center;gap:12px;min-width:0}.dl-wd-head>.dl-stack{min-width:0}.dl-wd-title{font-size:16px;line-height:24px;font-weight:500}.dl-wd-tile{flex:none;width:36px;height:36px;border-radius:10px;display:inline-flex;align-items:center;justify-content:center;background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-wd-tile.off{background:var(--dl-soft);color:var(--dl-fg-faint)}.dl-wd-tile .dl-icon{width:18px;height:18px}.dl-wd-foot{display:flex;align-items:center;flex-wrap:wrap;gap:8px 16px;padding-top:14px;border-top:1px solid var(--dl-line)}.dl-wd-chips{display:flex;flex-wrap:wrap;gap:6px;flex:1 1 auto;min-width:0}.dl-wd-chips .dl-check-chip.error .dl-icon{color:var(--dl-bad)}.dl-warn-text{color:var(--dl-warn)!important}.dl-health-cols{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(440px,100%),1fr));gap:16px;align-items:start}.dl-health-cols>.dl-panel{margin:0;min-width:0}.dl-recent{display:flex;flex-direction:column}.dl-recent .dl-panel-head a{font-size:13px}.dl-recent-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:32px 16px;color:var(--dl-fg-muted);font-size:13px;border-top:1px solid var(--dl-line)}.dl-loading{margin:0;font-size:13px}.dl-diag-tabs{margin:0 0 16px}.dl-row.dl-slog-row{align-items:baseline}.dl-slog-row .dl-ev-tile{align-self:flex-start;margin-top:-1px}.dl-slog-row.has-detail{cursor:pointer}.dl-row.dl-slog-row.has-detail:hover{background:color-mix(in srgb,var(--sys) 11%,transparent)}.dl-slog-more{display:inline-flex;vertical-align:-2px;margin-left:6px;color:var(--dl-fg-faint);transform:rotate(90deg);transition:transform .15s}.dl-slog-more .dl-icon{width:14px;height:14px}.dl-slog-more.open{transform:rotate(-90deg)}.dl-slog-detail{margin:8px 0 2px;padding:8px 10px;border-radius:8px;background:var(--dl-soft);font-family:var(--dl-mono);font-size:12px;line-height:17px;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--dl-fg-muted);cursor:text}.dl-table{width:100%;border-collapse:collapse;font-size:14px;line-height:20px}.dl-table th{text-align:left;font-weight:500;color:var(--dl-fg-faint);padding:0 8px 8px;border-bottom:1px solid var(--dl-line)}.dl-table td{padding:10px 8px;border-bottom:1px solid var(--dl-line);vertical-align:middle}.dl-table th:first-child,.dl-table td:first-child{padding-left:0}.dl-table th:last-child,.dl-table td:last-child{padding-right:0}.dl-table tr:last-child td{border-bottom:0}.dl-table .dl-right{text-align:right;white-space:nowrap}.dl-log{max-height:18em;overflow:auto;font-family:var(--dl-mono);font-size:12px;line-height:18px;margin:8px 0 0;padding:12px;white-space:pre-wrap;border-radius:12px;background:var(--dl-soft)}";var Ca=".dl-pagehead{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;flex-wrap:wrap;margin:0 0 20px}.dl-h1{margin:0!important;padding:0!important;font-size:24px!important;line-height:32px!important;font-weight:500!important;border:0!important}.dl-title-row{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.dl-stack{display:flex;flex-direction:column;gap:2px;min-width:0}.dl-stack.gap4{gap:4px}.dl-stack.gap8{gap:8px}.dl-sub{font-size:12px;line-height:16px;color:var(--dl-fg-muted)}.dl-ok{color:var(--dl-ok)}.dl-warn{color:var(--dl-warn)}.dl-bad{color:var(--dl-bad)}.dl-icon-only{width:auto!important;min-width:0!important;aspect-ratio:1 / 1;padding:0!important;justify-content:center;display:inline-flex!important;align-items:center;border-radius:999px!important}.dl-panel.flush{padding:0;overflow:hidden}.dl-panel-head.pad{padding:16px 16px 12px;margin:0}.dl-col{display:flex;flex-direction:column;gap:16px;min-width:0}.dl-col>.dl-panel,.dl-col>section.dl-panel{margin:0}.dl-crumbs{display:flex;gap:8px;align-items:center;font-size:14px;margin:0 0 16px;color:var(--dl-fg-faint)}.dl-crumbs a{color:var(--dl-fg-faint)}.dl-crumbs a:hover{color:var(--dl-fg)}.dl-crumbs span:last-child{color:var(--dl-fg)}.dl-metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);margin:0 0 16px;box-shadow:var(--dl-shadow)}.dl-metric{display:flex;flex-direction:column;gap:4px;padding:16px 20px;min-width:0}.dl-metric+.dl-metric{border-left:1px solid var(--dl-line)}.dl-metric-label{font-size:12px;font-weight:500;color:var(--dl-fg-faint)}.dl-metric-value{font-size:28px;line-height:36px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums;white-space:nowrap}.dl-metric-value .dl-faint{font-size:16px}.dl-metric-sub{font-size:12px;color:var(--dl-fg-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}@media(max-width:900px){.dl-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.dl-metric:nth-child(3){border-left:0}.dl-metric:nth-child(n+3){border-top:1px solid var(--dl-line)}}.dl-seg{display:inline-flex;gap:2px;padding:3px;border-radius:999px;background:var(--dl-soft);flex-wrap:wrap}.dl-seg button{all:unset;cursor:pointer;display:inline-flex;align-items:center;gap:6px;padding:4px 12px;border-radius:999px;font-size:13px;font-weight:500;color:var(--dl-fg-muted);white-space:nowrap}.dl-seg button:hover{color:var(--dl-fg)}.dl-seg button.on{background:var(--dl-soft-hover);color:var(--dl-fg)}.dl-seg.dl-srvsections{flex-wrap:nowrap;max-width:100%;overflow-x:auto;scrollbar-width:none}.dl-seg.dl-srvsections::-webkit-scrollbar{display:none}.dl-seg.dl-srvsections button{flex:none;white-space:nowrap}.dl-seg button:focus-visible{outline:2px solid var(--dl-ring)}.dl-seg button b{font-weight:500;font-size:11px;padding:0 6px;border-radius:999px;background:var(--dl-soft)}.dl-seg button b.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-seg.sm button{padding:2px 9px;font-size:11px}.dl-seg.wide{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));border-radius:12px;padding:4px}.dl-seg.wide button{flex-direction:column;justify-content:center;padding:8px 6px;border-radius:9px;gap:3px}.dl-seg.wide button.on{background:var(--dl-primary);color:var(--dl-primary-fg)}";var La='.dl-geomap{position:relative;border-top:1px solid var(--dl-line);background:var(--dl-soft)}.dl-map-status{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:var(--dl-fg-muted);font-size:13px;z-index:1;pointer-events:none}.dl-map-wrap{position:relative}.dl-map-legend{position:absolute;left:12px;bottom:12px;display:flex;gap:12px;align-items:center;padding:6px 12px;border-radius:999px;font-size:12px;background:color-mix(in srgb,var(--dl-card) 88%,transparent);border:1px solid var(--dl-line);backdrop-filter:blur(6px);z-index:2}.dl-map-legend span{display:inline-flex;align-items:center;gap:6px;color:var(--dl-fg-muted)}.dl-map-legend i.dot{width:8px;height:8px;border-radius:50%;background:var(--dl-fg-faint)}.dl-map-legend i.dot.ok{background:var(--dl-ok)}.dl-map-legend i.line{width:14px;height:2px;border-radius:2px;background:var(--dl-ok)}.dl-map-off{padding:32px 16px;text-align:center;color:var(--dl-fg-muted);border-top:1px solid var(--dl-line)}.dl-mk{all:unset;cursor:pointer;width:18px;height:18px;display:inline-flex;align-items:center;justify-content:center;position:relative}.dl-mk-dot{width:12px;height:12px;border-radius:50%;background:#8f8f8f;box-shadow:0 0 0 3px #0000008c}.dl-mk.online .dl-mk-dot{width:14px;height:14px;background:#40c977}.dl-mk.online:before{content:"";position:absolute;inset:-9px;border-radius:50%;background:#40c97747;animation:dl-pulse 2s ease-out infinite}@keyframes dl-pulse{0%{transform:scale(.5);opacity:1}to{transform:scale(1.4);opacity:0}}@media(prefers-reduced-motion:reduce){.dl-mk.online:before{animation:none}}.dl-mk-home{width:22px;height:22px;border-radius:7px;background:#ededed;display:flex;align-items:center;justify-content:center;box-shadow:0 0 0 4px #ededed2e,0 2px 6px #00000080;color:#131313}.dl-mk-home-ic{width:13px;height:13px}.dl-popup{z-index:4}.dl-popup .maplibregl-popup-content{background:var(--dl-elevated);color:var(--dl-fg);border:1px solid var(--dl-line);border-radius:12px;padding:12px;box-shadow:var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4));font:inherit}.dl-popup .maplibregl-popup-tip{border-top-color:var(--dl-elevated)!important;border-bottom-color:var(--dl-elevated)!important}.dl-pop{display:flex;flex-direction:column;gap:4px;font-size:12px;line-height:18px;min-width:210px}.dl-pop-head{display:flex;align-items:center;gap:8px;font-size:13px;margin-bottom:2px}.dl-mk.multi{width:26px;height:26px}.dl-mk-count{min-width:22px;height:22px;padding:0 6px;border-radius:999px;background:#8f8f8f;color:#0a0a0a;font:600 11px/22px var(--dl-mono);text-align:center;box-shadow:0 0 0 3px #0000008c;box-sizing:border-box}.dl-mk.online .dl-mk-count{background:#40c977}.dl-pop-net{width:30px;height:30px;border-radius:9px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-pop-list{display:flex;flex-direction:column;margin:6px -4px 0}.dl-pop-row{all:unset;cursor:pointer;display:flex;align-items:center;gap:8px;padding:5px 4px;border-radius:6px}.dl-pop-row:hover{background:var(--dl-soft)}.dl-pop-row:focus{outline:none}.dl-pop-row:focus-visible{outline:2px solid var(--dl-ring)}.dl-pop-name{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-pop-name b{font-weight:500}.dl-pop-dot{width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);flex:0 0 auto}.dl-pop-dot.on{background:var(--dl-ok);box-shadow:0 0 0 3px var(--dl-ok-wash)}.dl-pop-actions{display:flex;gap:6px;margin-top:8px;padding-top:8px;border-top:1px solid var(--dl-line)}.dl-pop-actions .cbi-button{flex:1;height:28px!important;font-size:12px!important;justify-content:center}.maplibregl-ctrl-attrib{font-size:10px}.dl-chartbox{position:relative}.dl-bars{display:flex;align-items:flex-end;gap:4px;border-bottom:1px solid var(--dl-line)}.dl-bar{flex:1;height:100%;display:flex;flex-direction:column-reverse;gap:1px;cursor:default;min-width:3px}.dl-bar i{display:block;border-radius:3px 3px 0 0}.dl-bar i.down{background:var(--dl-chart-1)}.dl-bar i.up{background:var(--dl-chart-2);opacity:.75;border-radius:3px 3px 0 0}.dl-bar:hover i{filter:brightness(1.25)}.dl-bar.empty{background:linear-gradient(to top,var(--dl-line) 2px,transparent 2px)}.dl-tip{position:absolute;top:-8px;transform:translate(-50%,-100%);padding:8px 10px;border-radius:10px;font-size:12px;line-height:18px;white-space:nowrap;background:var(--dl-elevated);border:1px solid var(--dl-line);box-shadow:var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4));pointer-events:none;z-index:3}.dl-tip-title{font-weight:500}.dl-tip-float{position:fixed;z-index:2000;color:var(--dl-fg)}.dl-spark i:hover{opacity:1;filter:brightness(1.25)}.dl-meter,.dl-slots{cursor:default}.dl-axis{display:flex;justify-content:space-between;font-size:12px;color:var(--dl-fg-faint);margin-top:6px}.dl-legend i.down{background:var(--dl-chart-1)}.dl-legend i.up{background:var(--dl-chart-2)}.dl-spark{display:flex;align-items:flex-end;gap:2px;flex:0 0 auto}.dl-spark i{flex:1;display:block;border-radius:2px 2px 0 0;background:var(--dl-chart-1);opacity:.85}.dl-spark i.zero{opacity:.22}';var Ta=`.dl-row{display:flex;align-items:center;gap:12px;padding:12px 16px;border-top:1px solid var(--dl-line);font-size:14px;line-height:20px;min-width:0}.dl-row.link{color:inherit;text-decoration:none}.dl-row.link:hover{background:var(--dl-soft)}.dl-row-main{flex:1;min-width:0;overflow-wrap:anywhere}.dl-row-main b{font-weight:500}.dl-attn{display:flex;flex-direction:column;gap:10px;padding:16px;border-top:1px solid var(--dl-line)}.dl-attn-item{display:flex;gap:10px;align-items:baseline;font-size:13px;color:var(--dl-fg-muted)}.dl-avatar.sm{width:26px;height:26px;font-size:10px;margin:0}.dl-avatar.lg{width:48px;height:48px;font-size:15px;margin:0}.dl-avatar.lg.online:after{width:12px;height:12px}.dl-list{border:1px solid var(--dl-line);border-radius:12px;overflow:hidden}.dl-list>.dl-row:first-child{border-top:0}.dl-ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.dl-row-main.dl-stack{min-width:0}.dl-person-id{display:flex;align-items:center;gap:14px;min-width:0}.dl-grid-person{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);gap:16px;align-items:start}@media(max-width:1000px){.dl-grid-person{grid-template-columns:minmax(0,1fr)}}.dl-devsec{display:flex;flex-direction:column;gap:12px}.dl-devsec .dl-panel-head{margin:0}.dl-dgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.dl-dcard>.dl-dcard-head+*{margin-top:auto}@media(max-width:700px){.dl-dgrid{grid-template-columns:minmax(0,1fr)}}.dl-dgrid>.dl-dslot.add:only-child{grid-column:1 / -1}.dl-dcard{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:14px;padding:14px;display:flex;flex-direction:column;gap:12px;min-width:0;box-shadow:var(--dl-shadow)}.dl-dcard.online{border-color:color-mix(in srgb,var(--dl-ok) 35%,transparent)}.dl-dcard.off{opacity:.7}.dl-dcard-head{display:flex;align-items:center;gap:12px}.dl-dcard-ic{width:40px;height:40px;border-radius:12px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-dcard-ic .dl-icon{width:20px;height:20px}.dl-dcard.online .dl-dcard-ic{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-dcard-title{all:unset;cursor:pointer;flex:1;min-width:0;display:flex;flex-direction:column}.dl-dcard-title b{font-weight:500;font-size:15px}.dl-dstat{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--dl-fg-muted);white-space:nowrap;min-width:0}.dl-dstat i.dot{flex:none}.dl-dstat.ok{color:var(--dl-ok)}.dl-dstat.warn{color:var(--dl-warn)}.dl-dstat i.dot,.dl-savebar i.dot{width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint)}.dl-dstat i.dot.ok{background:var(--dl-ok);box-shadow:0 0 0 3px var(--dl-ok-wash)}.dl-dstat i.dot.warn{background:var(--dl-warn)}.dl-dcard-use{display:flex;align-items:flex-end;justify-content:space-between;gap:12px}.dl-dcard-foot{padding-top:10px;border-top:1px solid var(--dl-line);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-dslot.add{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:14px;min-height:0;border:1px dashed color-mix(in srgb,currentColor 18%,transparent);border-radius:14px;text-align:center;color:var(--dl-fg-muted);transition:background .15s,border-color .15s,color .15s}.dl-dslot.add .dl-stack{align-items:center}.dl-dslot.add:hover{border-color:color-mix(in srgb,currentColor 35%,transparent);color:var(--dl-fg)}.dl-dslot.add:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-dslot.add b{font-weight:500}.dl-dslot.add:hover{background:var(--dl-soft)}.dl-dslot-ic{width:36px;height:36px;border-radius:999px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-dslot.add:hover .dl-dslot-ic{background:var(--dl-primary);color:var(--dl-primary-fg)}.dl-tiles2{display:grid;gap:10px;margin-top:16px}.dl-tile2{border:1px solid var(--dl-line);border-radius:14px;padding:14px;display:flex;flex-direction:column;gap:10px;min-width:0}.dl-tile2-label{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:12px;font-weight:500;color:var(--dl-fg-faint)}.dl-tile2-row{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}.dl-tile2-value{font-size:20px;line-height:28px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums}.dl-tile2-value .dl-faint{font-size:14px;font-weight:400}.dl-tile2-foot{display:flex;align-items:center;justify-content:space-between;gap:12px;padding-top:10px;border-top:1px solid var(--dl-line);font-size:12px}.dl-stepper{display:inline-flex;align-items:stretch;height:32px;border:1px solid var(--input, var(--dl-line));border-radius:8px;overflow:hidden}.dl-stepper button{all:unset;cursor:pointer;width:32px;display:inline-flex;align-items:center;justify-content:center;font-size:16px;color:var(--dl-fg)}.dl-stepper button:hover{background:var(--dl-soft)}.dl-stepper button[disabled]{opacity:.35;cursor:not-allowed}.dl-stepper+.dl-stepper{margin-left:4px}.dl-step-select{border:0!important;border-left:1px solid var(--input, var(--dl-line))!important;border-right:1px solid var(--input, var(--dl-line))!important;border-radius:0!important;background:transparent!important;color:inherit;font:500 13px inherit;padding:0 10px!important;height:100%!important;min-width:0!important}.dl-slots{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(0,1fr);gap:3px}.dl-slots i{height:4px;border-radius:999px;background:var(--dl-track);display:block}.dl-slots i.used{background:var(--dl-fg)}.dl-slots i.over{background:color-mix(in srgb,var(--dl-warn) 80%,transparent)}.dl-date{display:flex;align-items:center;gap:8px;flex:1 1 150px;min-width:0;box-sizing:border-box;height:34px;padding:0 10px;border:1px solid var(--input, var(--dl-line));border-radius:8px;color:var(--dl-fg-faint)}.dl-date input{border:0!important;background:transparent!important;box-shadow:none!important;padding:0!important;height:32px!important;color:var(--dl-fg);flex:1;min-width:0!important;width:100%!important}.dl-meter{position:relative;height:6px;border-radius:999px;background:var(--dl-track)}.dl-meter>i{display:block;height:100%;border-radius:999px;background:var(--dl-accent)}.dl-meter.warn>i{background:var(--dl-warn)}.dl-meter.bad>i{background:var(--dl-bad)}.dl-meter .mark{position:absolute;left:90%;top:-3px;width:1px;height:12px;background:var(--dl-warn)}.dl-meter.sm{height:4px}.dl-chips-row{display:flex;flex-wrap:wrap;gap:4px}.dl-chipbtn{all:unset;cursor:pointer;height:26px;padding:0 10px;border-radius:999px;background:var(--dl-soft);font-size:12px;font-weight:500;display:inline-flex;align-items:center}.dl-chipbtn:hover{background:var(--dl-soft-hover)}.dl-chipbtn.on{background:var(--dl-primary);color:var(--dl-primary-fg)}.dl-switch{all:unset;cursor:pointer;position:relative;width:32px;height:20px;border-radius:999px;background:var(--switch-off, var(--dl-track));flex:0 0 auto;transition:background .15s}.dl-switch i{position:absolute;left:2px;top:2px;width:16px;height:16px;border-radius:50%;background:#fff;transition:left .15s;box-shadow:0 1px 2px #0000004d}.dl-switch.on{background:var(--dl-accent)}.dl-switch.on i{left:14px}.dl-switch:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-linkbox{display:flex;align-items:center;gap:8px;height:36px;padding:0 4px 0 12px;border:1px solid var(--input, var(--dl-line));border-radius:8px;background:var(--input-bg, transparent)}.dl-linkbox .dl-mono{flex:1;min-width:0;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--dl-fg-muted)}.dl-linkbox .cbi-button{height:28px!important}.dl-pcard{display:grid;grid-template-columns:minmax(0,1fr) 260px;gap:20px;align-items:stretch;min-width:0}.dl-pcard-main{min-width:0}.dl-pcard-top{display:flex;align-items:center;gap:12px;min-width:0}.dl-pcard-top .dl-avatar{margin-right:0}.dl-pcard-who{flex:1;min-width:0}.dl-pcard-who .dl-slotbar{margin:3px 0 0}.dl-pside{display:flex;flex-direction:column;justify-content:space-between;gap:8px;padding-left:20px;border-left:1px solid var(--dl-line);min-width:0}.dl-pside-top{display:flex;align-items:center;justify-content:space-between;gap:8px}.dl-pside-state{display:inline-flex;align-items:center;gap:6px;font-size:13px;color:var(--dl-fg-muted)}.dl-pside-state.live{color:var(--dl-ok)}.dl-pside-foot{font-size:12px}.dl-pside .dl-use-num b{font-size:20px}.dl-none{display:none!important}.dl-pcard-actions{display:flex;gap:6px;flex:0 0 auto}.dl-pcard-actions .cbi-button{height:32px!important}.dl-icon-only .dl-btn-label{display:none}.dl-pill-ic{display:inline-flex;align-items:center;gap:4px;height:22px;padding:0 8px;border-radius:999px;font-size:12px;white-space:nowrap;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pill-ic .dl-icon{width:12px;height:12px}.dl-pill-ic.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-pill-ic.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-use-num{display:flex;align-items:baseline;gap:6px;white-space:nowrap}.dl-use-num b{font-size:15px;font-weight:500}.dl-use-live{display:flex;align-items:center;gap:8px;font-size:12px;font-variant-numeric:tabular-nums}.dl-usebar{display:flex;gap:2px;height:6px;border-radius:999px;overflow:hidden;background:var(--dl-track)}.dl-usebar i{display:block;height:100%;min-width:3px;flex:0 1 0}.dl-usebar i.fill{flex:none;min-width:0;border-radius:999px;background:var(--dl-accent)}.dl-usebar.warn i.fill{background:var(--dl-warn)}.dl-usebar.bad i.fill{background:var(--dl-bad)}.dl-usebar .c0,.dl-swatch.c0{background:var(--dl-chart-1)}.dl-usebar .c1,.dl-swatch.c1{background:#8b7cf6}.dl-usebar .c2,.dl-swatch.c2{background:#2fb889}.dl-usebar .c3,.dl-swatch.c3{background:#d9a03f}.dl-usebar .c4,.dl-swatch.c4{background:var(--dl-fg-faint)}.dl-tip-row{display:flex;align-items:center;gap:8px;min-width:160px}.dl-tip-row b{margin-left:auto;font-weight:500}.dl-swatch{width:8px;height:8px;border-radius:2px;flex:none}.dl-card-name{color:var(--dl-fg)!important;text-decoration:none}.dl-card-name:hover{text-decoration:underline}.dl-chip-tag{font-size:11px;line-height:18px;padding:0 6px;border-radius:999px;background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-chip.live{background:var(--dl-ok-wash);color:color-mix(in srgb,var(--dl-ok) 35%,var(--dl-fg))}.dl-chip.live:hover{background:color-mix(in srgb,var(--dl-ok) 22%,transparent)}.dl-chip.live .dl-icon{color:var(--dl-ok)}.dl-fixes{display:flex;gap:6px;flex-wrap:wrap;margin:10px 0 0 44px}.dl-fix{all:unset;cursor:pointer;height:26px;padding:0 10px;border-radius:999px;background:var(--dl-info-wash);color:var(--dl-info);font-size:12px;font-weight:500;display:inline-flex;align-items:center}.dl-fix:hover{filter:brightness(1.15)}.dl-plist>.dl-card.dl-attn-row{border-color:color-mix(in srgb,var(--dl-warn) 35%,transparent)}@media(max-width:760px){.dl-pcard{grid-template-columns:1fr}.dl-pside{padding:12px 0 0;border-left:0;border-top:1px solid var(--dl-line)}.dl-fixes{margin-left:0}}.dl-select{height:34px!important;border-radius:999px!important;min-width:136px!important;width:auto!important;padding:0 34px 0 14px!important;appearance:none!important;-webkit-appearance:none!important;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238b8f98' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")!important;background-repeat:no-repeat!important;background-position:right 12px center!important;background-size:14px!important}.dl-savebar{position:fixed;left:50%;bottom:24px;transform:translate(-50%,160%);opacity:0;transition:transform .25s cubic-bezier(.2,.8,.2,1),opacity .2s;display:flex;align-items:center;gap:10px;padding:8px 8px 8px 18px;border-radius:999px;background:var(--dl-elevated);border:1px solid var(--dl-line);box-shadow:var(--shadow-2xl, 0 16px 32px -8px rgba(0,0,0,.5));z-index:60;pointer-events:none}.dl-savebar.show{transform:translate(-50%);opacity:1;pointer-events:auto}.dl-savebar-text{display:inline-flex;align-items:center;gap:8px;font-size:13px;font-weight:500}`;var Ma=".dl-toast strong{display:block;font-weight:500}.dl-toast div{opacity:.8;font-size:13px}.dl-drawer-overlay{position:fixed;inset:0;z-index:900;display:flex;justify-content:flex-end;background:transparent;transition:background .2s}.dl-drawer-overlay.open{background:var(--scrim, rgba(0,0,0,.45))}.dl-drawer{width:min(520px,100%);height:100%;display:flex;flex-direction:column;background:var(--dialog-bg, var(--dl-elevated));color:var(--dl-fg);border-left:1px solid var(--dl-line);box-shadow:var(--shadow-2xl, -16px 0 32px -8px rgba(0,0,0,.5));transform:translate(100%);transition:transform .22s cubic-bezier(.2,.8,.2,1)}.dl-drawer-overlay.open .dl-drawer{transform:none}.dl-drawer-head{display:flex;align-items:center;gap:12px;padding:16px 20px;border-bottom:1px solid var(--dl-line)}.dl-drawer-title{flex:1;min-width:0;display:flex;align-items:center;gap:12px}.dl-drawer-title h3{margin:0!important;padding:0!important;border:0!important;font-size:18px!important;line-height:26px;font-weight:500!important}.dl-drawer-x{all:unset;cursor:pointer;width:32px;height:32px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;color:var(--dl-fg-muted)}.dl-drawer-x:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-drawer-body{flex:1;overflow:auto;padding:20px}.dl-drawer-foot{padding:12px 20px;border-top:1px solid var(--dl-line)}.dl-drawer-actions{display:flex;align-items:center;gap:8px}.dl-dcard-ic.on{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-icon-only.sm{width:28px;height:28px!important}.dl-stack.gap12{gap:12px}.dl-stack.gap16{gap:16px}.dl-dstats{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));border:1px solid var(--dl-line);border-radius:14px;overflow:hidden}.dl-dstats-cell{display:flex;flex-direction:column;gap:4px;padding:12px 14px;min-width:0}.dl-dstats-cell.wide{grid-column:span 2;border-bottom:1px solid var(--dl-line)}.dl-dstats-cell+.dl-dstats-cell:not(.wide):last-child{border-left:1px solid var(--dl-line)}.dl-dstats-cell b{font-size:16px;font-weight:500;font-variant-numeric:tabular-nums}.dl-dstats-cell .dl-dstat{font-size:14px}.dl-dsec{border:1px solid var(--dl-line);border-radius:14px;padding:16px;display:flex;flex-direction:column;gap:12px}.dl-dsec-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.dl-dsec-head h4{margin:0!important;padding:0!important;font-size:14px!important;font-weight:500!important;border:0!important}.dl-dstat i.dot{width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);display:inline-block}.dl-connect-body{min-height:60px}.dl-connect-body .dl-qr{width:min(240px,70vw)}.dl-kv2{display:flex;flex-direction:column}.dl-kvrow{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:9px 0;border-top:1px solid var(--dl-line);font-size:13px;min-width:0}.dl-kvrow:first-child{border-top:0;padding-top:0}.dl-kvrow-k{color:var(--dl-fg-muted);flex:0 0 auto}.dl-kvrow-v{min-width:0;text-align:right;overflow-wrap:anywhere}.dl-kvrow-v.copy{all:unset;cursor:pointer;display:inline-flex;align-items:center;gap:6px;min-width:0;color:var(--dl-fg)}.dl-kvrow-v.copy span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-kvrow-v.copy .dl-icon{width:13px;height:13px;color:var(--dl-fg-faint)}.dl-kvrow-v.copy:hover .dl-icon{color:var(--dl-fg)}@media(max-width:560px){.dl-drawer{width:100%}.dl-dstats{grid-template-columns:minmax(0,1fr)}.dl-dstats-cell.wide{grid-column:auto}.dl-dstats-cell+.dl-dstats-cell:not(.wide):last-child{border-left:0;border-top:1px solid var(--dl-line)}}.dl-dev-log{display:flex;flex-direction:column}.dl-dev-log-row{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid var(--dl-line);font-size:13px;line-height:20px;min-width:0}.dl-dev-log-row:first-child{border-top:0;padding-top:0}.dl-dev-log-row .dl-row-main{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}";var Pa=".dl-settings-main{min-width:0;display:flex;flex-direction:column;gap:20px}.dl-setsec{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);overflow:hidden;scroll-margin-top:88px;box-shadow:var(--dl-shadow)}.dl-setsec-body{padding:20px;display:flex;flex-direction:column;gap:14px}.dl-setsec-body h3{margin:0!important;padding:0!important;font-size:18px!important;line-height:26px;font-weight:500!important;border:0!important}.dl-setsec-body p{margin:0}.dl-setsec-head{display:flex;align-items:center;gap:10px}.dl-group{border:1px solid var(--dl-line);border-radius:14px;padding:2px 16px}.dl-group-head{display:flex;align-items:center;gap:12px;padding:14px 0 10px}.dl-group-head b{font-size:15px;font-weight:500}.dl-group-ic{width:32px;height:32px;border-radius:10px;background:var(--dl-soft);color:var(--dl-fg-muted);display:inline-flex;align-items:center;justify-content:center;flex:none}.dl-group-ic .dl-icon-wrap{display:inline-flex}.dl-group-ic .dl-icon{width:16px;height:16px}.dl-group-body>*{padding:12px 0;margin:0!important}.dl-group-body>*+*:not(.alert-message):not(.dl-params){border-top:1px solid var(--dl-line)}.dl-group-body>.alert-message,.dl-group-body>.dl-params{margin:12px 0!important}.dl-group-body>.alert-message{padding:10px 14px}.dl-group-body>.dl-params{padding:0}.dl-group-body>.alert-message+*,.dl-group-body>.dl-params+*{border-top:0}.dl-group-body>.dl-row{border-left:0;border-right:0;border-bottom:0;padding-left:0;padding-right:0;background:none}.dl-group-body>.dl-row:first-child{border-top:0}.dl-setsec-foot{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:10px 16px;padding:12px 20px;border-top:1px solid var(--dl-line);background:var(--dl-soft)}.dl-setsec.danger{border-color:color-mix(in srgb,var(--dl-bad) 40%,transparent)}.dl-setsec.danger .dl-setsec-foot{background:color-mix(in srgb,var(--dl-bad) 6%,transparent)}.dl-setrow{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,420px);align-items:center;gap:8px 24px}.dl-setrow.head{display:flex;justify-content:space-between;gap:16px}.dl-setrow-label{font-size:14px;font-weight:500}.dl-setrow-ctl{display:flex;justify-content:flex-end;min-width:0}.dl-setrow-ctl .dl-chips-row{justify-content:flex-end}.dl-setrow-ctl>input{width:100%}.dl-hostport{display:flex;align-items:center;gap:8px;flex:1;min-width:0;justify-content:flex-end}.dl-hostport input{flex:1;min-width:0}.dl-root input.dl-w-port,.dl-hostport input.dl-w-port{flex:0 0 90px;width:90px}.dl-more summary{cursor:pointer;color:var(--dl-fg-muted);font-size:13px;margin-bottom:10px}.dl-more .dl-setrow+.dl-setrow{margin-top:10px}@media(max-width:760px){.dl-setrow:not(.head){grid-template-columns:minmax(0,1fr)}.dl-setrow-ctl,.dl-setrow-ctl .dl-chips-row{justify-content:flex-start}}.dl-need-ic{width:30px;height:30px;border-radius:9px;background:var(--dl-soft);color:var(--dl-fg-muted);display:inline-flex;align-items:center;justify-content:center;flex:none}.dl-need-ic .dl-icon-wrap{display:inline-flex}.dl-need-ic .dl-icon{width:15px;height:15px}.dl-need-row.bad .dl-need-ic,.dl-need-ic.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-need-row.warn .dl-need-ic,.dl-need-ic.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-need-ic.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-lh-main{display:flex;align-items:flex-start;gap:12px;min-width:0}.dl-lh-main>.dl-need-ic{margin-top:1px}.dl-sub .dl-mono{font-size:.92em}.dl-need-row>.cbi-button{flex:none}.dl-bk-row .dl-group-ic{width:30px;height:30px}.dl-bk-older>summary{list-style:none;cursor:pointer;display:flex;align-items:center;gap:8px;padding:11px 16px;border-top:1px solid var(--dl-line);font-size:13px;color:var(--dl-fg-muted);user-select:none}.dl-bk-older>summary::-webkit-details-marker{display:none}.dl-bk-older>summary:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-bk-older>summary .dl-icon-wrap{display:inline-flex;transition:transform .15s}.dl-bk-older>summary .dl-icon{width:14px;height:14px}.dl-bk-older[open]>summary .dl-icon-wrap{transform:rotate(90deg)}#dl-set-backups .dl-setsec-head h3+.dl-sub{margin-top:2px}#dl-set-backups .dl-setsec-foot>.dl-sub{flex:1 1 260px}.dl-bk-actions{flex:0 1 auto;justify-content:flex-end}@media(max-width:640px){#dl-set-backups .dl-setsec-foot>.dl-sub{flex-basis:100%}.dl-bk-actions{justify-content:flex-start}}.dl-upd{display:flex;flex-direction:column;gap:16px}.dl-upd>.dl-pagehead{margin:0 0 4px}.dl-upd-bad{color:var(--dl-bad)}";var Da=".dl-comp-hero{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(0,1fr)}.dl-comp-hero-main{padding:20px;display:flex;flex-direction:column;gap:12px;min-width:0}.dl-comp-hero-side{padding:20px;border-left:1px solid var(--dl-line);display:flex;flex-direction:column;gap:14px;min-width:0}.dl-comp-name{font-size:16px;font-weight:500}.dl-comp-hero-head{display:flex;align-items:center;gap:10px;flex-wrap:wrap;min-width:0}.dl-comp-hero-head .dl-spacer{flex:1}.dl-comp-big{font-family:var(--dl-mono);font-size:26px;line-height:34px;letter-spacing:-.02em;display:flex;align-items:baseline;gap:10px}.dl-comp-big small{font-size:14px;color:var(--dl-accent)}.dl-comp-big small.dl-faint{color:var(--dl-fg-faint)}.dl-comp-verrow{display:flex;align-items:center;gap:4px 12px;flex-wrap:wrap;min-width:0}.dl-comp-verrow .dl-spacer{flex:1}.dl-comp-meta{font-size:13px}.dl-comp-bullets{margin:0;padding-left:18px;display:flex;flex-direction:column;gap:4px;color:var(--dl-fg-muted);font-size:13px}.dl-comp-bullets li{list-style:disc}.dl-comp-lead{margin:0}.dl-comp-more{align-self:flex-start;font-size:12px;color:var(--dl-fg-faint);margin-left:18px;padding:0!important}.dl-comp-more:hover{color:var(--dl-accent);background:none!important;text-decoration:underline;text-underline-offset:2px}.dl-comp-hero-main>.dl-comp-vers{margin-top:auto}.dl-comp-btns{display:flex;gap:8px;flex-wrap:nowrap;align-items:center;flex:none}.dl-comp-side-v{display:flex;align-items:center;gap:8px;font-size:14px;min-width:0;flex-wrap:wrap}.dl-comp-side-v .dl-icon{width:15px;height:15px;color:var(--dl-fg-muted)}.dl-comp-side-v a{color:inherit;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-comp-side-v a:hover{color:var(--dl-accent)}.dl-comp-cols{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(0,1fr);gap:16px;align-items:start}.dl-comp-cols>.dl-panel>div>.dl-row:first-child{border-top:1px solid var(--dl-line)}.dl-comp-count{font-size:13px}.dl-comp-sub{font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-comp-ic{display:inline-flex;gap:4px;flex:none}.dl-comp-ic .cbi-button{width:30px;height:30px;padding:0!important;justify-content:center;border-radius:999px!important}.dl-comp-ic .dl-btn-label{display:none}.dl-comp-ic .dl-icon{width:14px;height:14px}.dl-comp-ic .is-busy{pointer-events:none;opacity:.5}.dl-comp-ic .cbi-button.dl-comp-check{width:auto;padding:0 12px 0 10px!important;gap:6px;display:inline-flex;align-items:center;font-size:13px}.dl-row>.dl-pill,.dl-row>.cbi-button,.dl-row>.dl-comp-ic{flex:none}button.dl-pill.dl-comp-run{all:unset;display:inline-flex;align-items:center;height:20px;padding:0 8px;border-radius:999px;font-size:12px;cursor:pointer;background:color-mix(in srgb,var(--dl-accent) 14%,transparent);color:var(--dl-accent)}.dl-comp-foldwrap{padding:0 16px 14px 60px}.dl-comp-fold .dl-params-body{gap:12px}.dl-comp-fold .dl-list>.dl-row{padding:10px 14px}.dl-comp-bver{font-size:12px;width:130px;text-align:right;flex:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-comp-bact{width:84px;flex:none;display:flex;justify-content:flex-end}.dl-comp-warn{display:flex;align-items:flex-start;gap:8px;font-size:12px;line-height:18px;color:var(--dl-fg-muted)}.dl-comp-warn .dl-icon-wrap{display:inline-flex;flex:none;margin-top:2px}.dl-comp-warn .dl-icon{width:14px;height:14px;color:var(--dl-warn)}.dl-comp-empty{margin:0;padding:4px 16px 16px}@media(max-width:760px){.dl-comp-hero,.dl-comp-cols{grid-template-columns:minmax(0,1fr)}.dl-comp-hero-side{border-left:0;border-top:1px solid var(--dl-line)}.dl-comp-foldwrap{padding-left:16px}.dl-comp-bver{display:none}}.dl-comp-status{display:flex;align-items:center;gap:8px;font-size:13px;padding:9px 12px;border-radius:10px;background:var(--dl-soft);min-width:0}.dl-comp-status>.dl-icon-wrap{display:inline-flex;flex:none}.dl-comp-status .dl-icon{width:15px;height:15px}.dl-comp-status.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-comp-status.acc{background:color-mix(in srgb,var(--dl-accent) 12%,transparent);color:var(--dl-accent)}.dl-comp-status.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-comp-status.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-comp-status b{font-weight:600}.dl-comp-vers .dl-params-body{gap:0;padding:4px 14px 12px}.dl-comp-tag{display:flex;gap:6px;padding:6px 0 10px}.dl-comp-tag input{flex:1;min-width:0}.dl-comp-ver{display:flex;align-items:center;gap:8px;padding:7px 0;border-top:1px solid var(--dl-line);font-size:13px}.dl-comp-ver .dl-mono{min-width:52px}.dl-comp-ver .dl-sub{flex:1}.dl-comp-ver .cbi-button:not(.dl-icon-btn){height:26px!important;font-size:12px!important}.dl-comp-pager{display:flex;align-items:center;justify-content:space-between;padding-top:10px;border-top:1px solid var(--dl-line);font-size:12px}.dl-comp-pager .dl-linkbtn[disabled]{opacity:.4;cursor:default}.dl-comp-vers .dl-loading,.dl-comp-vers .dl-params-body>p{padding:6px 0 10px}.dl-op-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:14px}.dl-op-head .dl-spacer{flex:1}.dl-op-timer{display:inline-flex;align-items:center;gap:5px;font-variant-numeric:tabular-nums}.dl-op-timer .dl-icon,.dl-op-head .dl-linkbtn .dl-icon{width:14px;height:14px}.dl-op-loghead{display:flex;align-items:center;justify-content:space-between}.dl-op-loghead b{font-weight:500;font-size:13px}.dl-op .dl-log{max-height:16em;min-height:12em;margin-top:8px}.dl-op .dl-comp-status{margin:14px 0 0}.dl-op-actions{display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap;width:100%}.dl-notes{max-height:55vh;overflow:auto;border-radius:12px;background:var(--dl-soft);padding:14px 16px;font-size:13px;line-height:20px;overflow-wrap:anywhere}.dl-notes h5{margin:10px 0 6px;font-size:14px;font-weight:500}.dl-notes h5:first-child{margin-top:0}.dl-notes p{margin:0 0 8px}.dl-notes ul{margin:0 0 10px;padding-left:18px}.dl-notes li{list-style:disc}.dl-notes code{font-family:var(--dl-mono);font-size:12px;padding:1px 5px;border-radius:6px;background:var(--dl-soft-hover)}.dl-notes pre{font-family:var(--dl-mono);font-size:12px;padding:10px;border-radius:8px;background:var(--dl-soft-hover);white-space:pre-wrap;margin:0 0 10px}.dl-notes a{color:var(--dl-accent)}";var Aa=".dl-chip.static{cursor:default}.dl-chip.static:hover{background:var(--dl-soft)}.dl-chip.static .dl-chip-name{font-weight:500}.dl-setrow.head .dl-chips-row{margin-top:8px}.dl-setrow.head>.dl-lh-main,.dl-setrow.head>.dl-lh-main>.dl-stack{flex:1 1 auto;min-width:0}.dl-setrow.head>.dl-setrow-ctl:empty{display:none}.dl-setrow.head:has(>.dl-lh-main){align-items:flex-start}.dl-setrow.head>.dl-setrow-ctl{align-items:center;min-height:30px}.dl-netpick{margin-top:10px}.dl-boxrow{display:flex;align-items:center;justify-content:space-between;gap:16px;margin:0;padding:10px 14px;border:1px solid var(--dl-line);border-radius:12px;font-size:13px;cursor:pointer}.dl-boxrow>.dl-switch{flex:none}.dl-ifpick{display:flex;flex-direction:column;gap:12px;padding:14px;border:1px solid var(--dl-line);border-radius:14px}.dl-iflead-row{display:flex;align-items:center;justify-content:space-between;gap:12px}.dl-host-ports{justify-content:flex-end}@media(max-width:760px){.dl-host-ports{justify-content:flex-start}}.dl-circle-dot{display:inline-block;width:8px;height:8px;border-radius:50%;flex:none}.dl-circles .dl-chip b{font-weight:500}.dl-circle-name{display:inline-flex;align-items:center;gap:8px;font-size:14px;font-weight:500}.dl-w400{font-weight:400}.dl-swatches{display:flex;flex-wrap:wrap;gap:8px}.dl-swatch{all:unset;cursor:pointer;width:22px;height:22px;border-radius:50%;background:var(--sw);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dl-fg) 12%,transparent)}.dl-swatch.on{box-shadow:0 0 0 2px var(--dl-card),0 0 0 4px var(--sw)}.dl-swatch:focus-visible{outline:2px solid var(--dl-ring);outline-offset:3px}.dl-circle-modal .dl-chipbtn b{margin-left:6px;font-weight:500;font-size:11px;opacity:.6}.dl-reach td:first-child b{font-weight:500}.dl-ev-host{white-space:nowrap}.dl-ev-host b{font-weight:500;color:var(--dl-fg)}.dl-reach{font-size:13px}.dl-reach th,.dl-reach td{white-space:nowrap;padding-left:6px;padding-right:6px}.dl-reach-wrap{overflow-x:auto}.dl-yes{display:inline-flex;align-items:center;gap:4px;color:var(--dl-ok)}.dl-yes .dl-icon-wrap{display:inline-flex}.dl-yes .dl-icon{width:14px;height:14px}.dl-check-form{display:grid;grid-template-columns:minmax(0,1fr) auto minmax(0,1fr) auto;align-items:start;gap:8px}.dl-check-form>.dl-faint{line-height:36px}.dl-check-end{display:flex;flex-direction:column;gap:6px;min-width:0}.dl-check-end>*{width:100%!important;min-width:0}@media(max-width:560px){.dl-check-form{grid-template-columns:minmax(0,1fr)}.dl-check-form>.dl-faint{display:none}}.dl-verdict{display:flex;align-items:baseline;gap:10px;padding:10px 12px;border-radius:12px}.dl-verdict b{font-weight:500}.dl-verdict.ok{background:var(--dl-ok-wash)}.dl-verdict.ok b{color:var(--dl-ok)}.dl-verdict.bad{background:var(--dl-bad-wash)}.dl-verdict.bad b{color:var(--dl-bad)}.dl-corehead{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin:0 0 4px}.dl-corehead h3{margin:0!important}.dl-row-end{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}.dl-dcard.clickable{cursor:pointer}.dl-dcard.clickable:hover{border-color:color-mix(in srgb,var(--dl-fg) 22%,transparent)}";var Mi=[xa,wa,ya,ka,$a,_a,Ea,Sa,Ca,La,Ta,Ma,Pa,Da,Aa].join(` +`);function za(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=Mi,n}function rt(n){return()=>{let t=new n;return Object.assign({load:()=>t.load(),render:async a=>{let r=await t.render(a),i=document.createElement("div");return i.className="dl-root",i.append(za(),r),i},addFooter(){return t.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Df=rt(At),Af=rt(at),zf=rt(At),Nf=rt(rn),Rf=rt(dn),Hf=rt(mn),If=rt(ln);function Na(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var Bf=Na(""),Of=Na("log");return baseclass.extend({ activity: Of, diagnostics: Hf, health: Bf, overview: Df, people: Af, person: Rf, server: zf, settings: Nf, updates: If }); diff --git a/package/luci-app-dawnline/root/lib/upgrade/keep.d/dawnline-data b/package/luci-app-dawnline/root/lib/upgrade/keep.d/dawnline-data new file mode 100644 index 0000000..bd84ad6 --- /dev/null +++ b/package/luci-app-dawnline/root/lib/upgrade/keep.d/dawnline-data @@ -0,0 +1 @@ +/etc/dawnline/ diff --git a/package/luci-app-dawnline/root/usr/bin/dawnline b/package/luci-app-dawnline/root/usr/bin/dawnline index f31da95..24bdcfd 100755 --- a/package/luci-app-dawnline/root/usr/bin/dawnline +++ b/package/luci-app-dawnline/root/usr/bin/dawnline @@ -6,9 +6,15 @@ import * as core from 'dawnline.core'; import * as live from 'dawnline.live'; import * as apply from 'dawnline.apply'; import * as view from 'dawnline.view'; -import * as ops from 'dawnline.ops'; +import * as health from 'dawnline.health'; +import * as backup from 'dawnline.backup'; +import * as pc from 'dawnline.portalcert'; import * as watchdog from 'dawnline.watchdog'; -import { VERSION, slog, sh_out, q, take_iface_intent } from 'dawnline.util'; +import * as awg from 'dawnline.awg'; +import * as store from 'dawnline.store'; +import { + VERSION, slog, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR +} from 'dawnline.util'; const args = ARGV; const cmd = args[0] ?? 'help'; @@ -30,7 +36,7 @@ function help() { Usage: dawnline apply Reconcile router configuration and runtime state - sync Push devices and access rules to the tunnel + sync Push devices and access rules to the tunnels status People and devices with live state (JSON) health Run health checks (JSON) person add [--slug s] [--access lan|internet|both] [--devices n] @@ -38,7 +44,7 @@ Usage: dawnline person link Print the personal portal link person rm Remove a person and their devices device add [--kind phone|computer|tablet|router] - device conf Print a device configuration + device conf Print a device configuration (.conf) device rm Remove a device backup Create a backup in /etc/dawnline/backups portal-cert Print the certificate and key the portal uses @@ -48,9 +54,47 @@ Usage: dawnline version`); } -function commit(c) { - c.commit('dawnline'); - system('chmod 600 /etc/config/dawnline'); +/* + * netifd retries a tunnel that fails to start every few seconds (a kernel + * module that won't load, AmneziaWG removed): one line per interface every + * 10 minutes, with how many attempts failed meanwhile. A start clears it. + */ +const FAILS = `${RUN_DIR}/ifup-failed.json`; +const FAIL_EVERY = 600; + +function ifup_failed(ifname, who) { + let now = time(); + // Attempts since the last line (a quiet spell starts a new count), and over how long. + let r = with_lock('ifup-failed', () => { + let all = read_json(FAILS, {}); + let f = all[ifname]; + if (!f || now - f.last > FAIL_EVERY) + f = all[ifname] = { logged: 0, count: 0, since: now }; + f.count++; + f.last = now; + let out = null; + if (now - f.logged >= FAIL_EVERY) { + out = { n: f.count, mins: int((now - f.since) / 60) }; + f.logged = f.since = now; + f.count = 0; + } + ensure_dir(RUN_DIR); + write_json(FAILS, all, 0o600); + return out; + }); + if (r) + slog('awg', 'error', r.n > 1 ? `couldn't start · ${r.n} failed attempts in ${r.mins} min` : "couldn't start", + watchdog.iface_errors(ifname), who); +} + +function ifup_ok(ifname) { + with_lock('ifup-failed', () => { + let all = read_json(FAILS, {}); + if (all[ifname]) { + delete all[ifname]; + write_json(FAILS, all, 0o600); + } + }); } try { @@ -59,18 +103,16 @@ try { else if (cmd == 'sync') out(apply.sync()); else if (cmd == 'status') { - let m = core.load(), u = core.load_usage(), d = live.dump(), st = view.states(m, u); + let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u); out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true }))); } else if (cmd == 'health') - out(ops.health()); + out(health.health()); else if (cmd == 'person' && args[1] == 'add') { - let c = core.open_cursor(), m = core.load(c); - let id = core.create_person(c, m, { + let id = store.transact((c, m) => core.create_person(c, m, { name: args[2], slug: opt('slug'), access: opt('access', 'internet'), device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'), - }); - commit(c); + })); let m2 = core.load(); out(core.portal_url(m2, m2.people[id]) ?? id); } @@ -80,33 +122,29 @@ try { out(core.portal_url(m, p) ?? 'Set settings.portal_host first.'); } else if (cmd == 'person' && args[1] == 'rm') { - let c = core.open_cursor(), m = core.load(c); - core.delete_person(c, m, args[2]); - commit(c); + store.transact((c, m) => core.delete_person(c, m, args[2])); apply.sync(); } else if (cmd == 'device' && args[1] == 'add') { - let c = core.open_cursor(), m = core.load(c); - let id = core.create_device(c, m, args[2], args[3], opt('kind', 'phone'), { by: 'admin' }); - commit(c); + // Keys first: generating them runs the awg tool, not worth holding the config lock for. + let keys = awg.new_keys(); + let id = store.transact((c, m) => core.create_device(c, m, args[2], args[3], opt('kind', 'phone'), { by: 'admin', keys })); apply.sync(); out(id); } else if (cmd == 'device' && args[1] == 'conf') { let m = core.load(); let d = m.devices[args[2]] ?? die('Unknown device.'); - print(core.client_config(m, d).conf); + print(awg.client_config(m, d).conf); } else if (cmd == 'device' && args[1] == 'rm') { - let c = core.open_cursor(), m = core.load(c); - core.delete_device(c, m, args[2]); - commit(c); + store.transact((c, m) => core.delete_device(c, m, args[2])); apply.sync(); } else if (cmd == 'backup') - out(ops.backup_create(opt('reason'))); + out(backup.backup_create(opt('reason'))); else if (cmd == 'portal-cert') { - let c = ops.portal_cert(core.load().settings); + let c = pc.portal_cert(core.load().settings); out(`${c.cert} ${c.key}`); } else if (cmd == 'portal-http-port') { @@ -137,6 +175,7 @@ try { if (srv.ifname == ifname) who = srv.name; if (args[1] == 'ifup') { + ifup_ok(ifname); let port = sh_out(`awg show ${q(ifname)} listen-port 2>/dev/null`); slog('awg', 'up', port ? `started · accepting connections on port ${port}` : 'started', null, who); } @@ -152,7 +191,7 @@ try { ], (x) => x)), who); } else if (args[1] == 'ifup-failed') - slog('awg', 'error', "couldn't start", watchdog.iface_errors(ifname), who); + ifup_failed(ifname, who); } else if (cmd == 'teardown') apply.teardown(); diff --git a/package/luci-app-dawnline/root/usr/libexec/dawnline/agent b/package/luci-app-dawnline/root/usr/libexec/dawnline/agent index 825d8e9..2b09607 100755 --- a/package/luci-app-dawnline/root/usr/libexec/dawnline/agent +++ b/package/luci-app-dawnline/root/usr/libexec/dawnline/agent @@ -1,6 +1,6 @@ #!/usr/bin/ucode // Dawnline agent (procd instance). Every minute it: -// * folds AmneziaWG counters into usage (tmpfs; flushed to flash hourly) +// * folds the tunnels' counters into usage (tmpfs; flushed to flash hourly) // * saves the activity log to flash as often as Settings says (or never) // * keeps the "like a home device" path and the Home-only resolver up // * logs connects, disconnects and roaming @@ -16,15 +16,19 @@ import { import * as core from 'dawnline.core'; import * as live from 'dawnline.live'; import * as apply from 'dawnline.apply'; -import * as ops from 'dawnline.ops'; +import * as backup from 'dawnline.backup'; +import * as pc from 'dawnline.portalcert'; import * as geo from 'dawnline.geo'; import * as watchdog from 'dawnline.watchdog'; import * as net from 'dawnline.net'; +import * as store from 'dawnline.store'; +import * as upd from 'dawnline.updates'; const TICK = 60 * 1000; const FLUSH_EVERY = 3600; const LOG_FLUSH = { '10min': 600, hourly: 3600 }; const RESYNC_EVERY = 600; +const CONFIG_FILE = '/etc/config/dawnline'; let usage = live.load_usage(); let last_states = null; @@ -36,7 +40,10 @@ let last_endpoint = presence.endpoint ?? {}; let offline_ticks = {}; let last_flush = time(); let last_log_flush = time(); -let last_net = null; +// The network as apply() last saw it (apply.NET_SIG; this when it never ran), +// and a different one seen on the previous tick. +let base_net = null; +let pending_net = null; let rate_prev = null; /** @@ -95,6 +102,7 @@ function record_rate(m) { write_json(`${RUN_DIR}/rate_people.json`, people, 0o644); } let last_sync = 0; +let conf_mtime = null; let cert_mtime = null; const REASON = { @@ -113,12 +121,10 @@ function check_people(m, states, events) { push(events, { type: st == 'active' ? 'resumed' : 'paused', person: id, detail: REASON[st] ?? st }); // "Remove their devices" when the end date passes. if (core.person_expired(p, ts) && p.expire_action == 'remove' && length(p.devices)) { - let c = core.open_cursor(); - let mm = core.load(c); - for (let d in mm.people[id]?.devices ?? []) - core.delete_device(c, mm, d); - c.commit('dawnline'); - system('chmod 600 /etc/config/dawnline'); + store.transact((c, mm) => { + for (let d in mm.people[id]?.devices ?? []) + core.delete_device(c, mm, d); + }); push(events, { type: 'devices_removed', person: id, detail: 'end date reached' }); last_sync = 0; } @@ -217,7 +223,7 @@ function cert_end(path) { function check_cert(m) { if (!m.settings.portal_enabled) return; - let c = ops.portal_cert(m.settings); + let c = pc.portal_cert(m.settings); let mt = stat(c.cert)?.mtime; if (cert_mtime != null && mt != null && mt != cert_mtime) { slog('portal', 'up', `certificate renewed · valid until ${cert_end(c.cert) ?? '?'}`, null, 'Personal portal'); @@ -268,13 +274,22 @@ function nightly_backup() { let st = read_json(`${DATA_DIR}/backup-state.json`, {}); if (sum && sum != st.auto) { try { - ops.backup_create('auto'); + backup.backup_create('auto'); write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600); } catch (e) {} } } +/** + * Settings → Updates: an automatic check or update when one is due. The + * updater does the work in its own process; this only decides when. + */ +function check_updates(m) { + if (upd.due(m.settings.updates, upd.auto_state()) && !upd.busy()) + system('start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- auto'); +} + /** * Traffic history resets requested from LuCI (rpcd cannot touch the * counters this process holds in memory). Applied, then saved to flash. @@ -291,78 +306,131 @@ function check_usage_reset(m) { return true; } +/* + * Push devices and access rules when people's states changed, the config + * file was written (by anyone: rpcd, the portal, the CLI, a restore), or + * every RESYNC_EVERY seconds anyway. apply.sync reads the model again itself. + */ +function sync_runtime(t) { + // uci commits replace the file: a new inode even within the same second. + let st = stat(CONFIG_FILE); + let mt = st ? `${st.mtime}/${st.inode}` : null; + let changed = last_states == null || sprintf('%J', t.states) != sprintf('%J', last_states) || + (conf_mtime != null && mt != conf_mtime); + if (changed || time() - last_sync > RESYNC_EVERY) { + apply.sync(t.m, usage); + last_sync = time(); + } + conf_mtime = mt; + last_states = t.states; +} + +/* + * The router's network changed under us: re-derive everything. Only a change + * seen on two ticks in a row (a bridge recreated or an interface restarting + * passes), compared with what the last apply() used. + */ +function check_network(t) { + let sig = apply.net_signature(t.m); + let applied = readfile(apply.NET_SIG) ?? base_net; + if (applied == null || sig == applied) { + base_net ??= sig; + pending_net = null; + return; + } + if (pending_net != sig) { + pending_net = sig; + return; + } + pending_net = null; + slog('dawnline', 'info', 'network changed — Dawnline set itself up again', null, 'Router'); + apply.apply(); + base_net = readfile(apply.NET_SIG) ?? apply.net_signature(core.load()); +} + +/* + * One tick is a list of steps, each on its own: a failing step is logged + * (each new message once in the service log, every time in syslog) and the + * others still run. Steps that need the model wait for it; the counters and + * the logs are saved at the end whatever happened. + */ +const STEPS = [ + { who: 'Dawnline', run: (t) => { + t.m = core.load(); + t.pol = live.policy(t.m.settings.retention); + } }, + { who: 'Traffic', run: (t) => { + t.reset = check_usage_reset(t.m); + t.dmp = live.dump(t.m); + t.lv = live.collect(t.m, usage, t.dmp); + } }, + { who: 'Speed', quiet: true, run: (t) => record_rate(t.m) }, + // Connects and disconnects only from a complete read of the tunnels. + { who: 'Connections', run: (t) => { + if (t.lv && t.dmp?.ok) + check_devices(t.m, t.lv, t.events); + } }, + { who: 'People', run: (t) => { + t.states = apply.states_for(t.m, usage); + check_people(t.m, t.states, t.events); + } }, + { who: 'Access rules', run: (t) => { + if (t.states) + sync_runtime(t); + } }, + // Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons. + { who: 'Activity', run: (t) => live.add_events(t.events, t.pol) }, + { who: 'Internet like a home device', run: (t) => apply.sync_loop(t.m, usage) }, + { who: 'Router', run: check_network }, + { who: 'Watchdog', run: (t) => watchdog.run(core.load()) }, + { who: 'Personal portal', run: (t) => check_cert(t.m) }, + { who: 'Router', quiet: true, run: (t) => check_wan(t.m) }, + { who: 'Backup', run: (t) => nightly_backup() }, + { who: 'updates', quiet: true, run: (t) => check_updates(t.m) }, + { who: 'geo', quiet: true, run: (t) => check_geo(t.m) }, +]; + +// Step → the last error it logged (cleared when it works again). +let step_err = {}; + +function step(i, s, fn) { + try { + fn(); + delete step_err[i]; + } + catch (e) { + system(`logger -t dawnline-agent ${q(`${s.who}: ${e.message}`)}`); + if (!s.quiet && step_err[i] != e.message) + slog('dawnline', 'error', `failed: ${e.message}`, e.stacktrace?.[0]?.context, s.who); + step_err[i] = e.message; + } +} + function tick() { ensure_dir(RUN_DIR); writefile(watchdog.BEAT, `${time()}`); // A restore or import drops the live counters; start over from flash. if (!stat(`${RUN_DIR}/usage.json`) && usage.updated) usage = live.load_usage(); - let m = core.load(); - let reset = check_usage_reset(m); - let pol = live.policy(m.settings.retention); - let dmp = live.dump(); - let lv = live.collect(m, usage, dmp); - try { - record_rate(m); - } - catch (e) {} - let states = apply.states_for(m, usage); - let events = []; + let t = { m: null, pol: null, reset: false, events: [] }; + for (let i, s in STEPS) + if (i == 0 || t.m) + step(i, s, () => s.run(t)); - check_devices(m, lv, events); - check_people(m, states, events); - // Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons. - - let changed = last_states == null || sprintf('%J', states) != sprintf('%J', last_states); - if (changed || time() - last_sync > RESYNC_EVERY) { - apply.sync(m, usage); - last_sync = time(); - } - last_states = states; - - live.add_events(events, pol); - - let persist = reset || time() - last_flush >= FLUSH_EVERY; - live.save_usage(usage, persist); - slog_trim(persist); - if (persist) - last_flush = time(); - if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) { - live.persist_events(pol); - last_log_flush = time(); - } - try { - apply.sync_loop(m, usage); - // The router's network changed under us: re-derive everything. - let sig = apply.net_signature(m); - if (last_net != null && sig != last_net) { - slog('dawnline', 'info', 'network changed — Dawnline set itself up again', null, 'Router'); - apply.apply(); - sig = apply.net_signature(core.load()); + let persist = t.reset || time() - last_flush >= FLUSH_EVERY; + step('save', { who: 'Traffic' }, () => { + live.save_usage(usage, persist); + if (persist) + last_flush = time(); + }); + step('slog', { who: 'Dawnline', quiet: true }, () => slog_trim(persist)); + step('events', { who: 'Activity' }, () => { + let pol = t.pol ?? live.policy(); + if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) { + live.persist_events(pol); + last_log_flush = time(); } - last_net = sig; - } - catch (e) { - slog('dawnline', 'error', `failed: ${e.message}`, null, 'Internet like a home device'); - } - try { - watchdog.run(core.load()); - } - catch (e) { - slog('dawnline', 'error', `failed: ${e.message}`, null, 'Watchdog'); - } - check_cert(m); - try { - check_wan(m); - } - catch (e) {} - nightly_backup(); - try { - check_geo(m); - } - catch (e) { - system(`logger -t dawnline-agent ${q('geo: ' + e.message)}`); - } + }); } function shutdown() { diff --git a/package/luci-app-dawnline/root/usr/libexec/dawnline/updater b/package/luci-app-dawnline/root/usr/libexec/dawnline/updater index 5054528..ebaed58 100755 --- a/package/luci-app-dawnline/root/usr/libexec/dawnline/updater +++ b/package/luci-app-dawnline/root/usr/libexec/dawnline/updater @@ -1,64 +1,52 @@ #!/usr/bin/ucode -// Dawnline background update worker, started detached by luci.dawnline. +// Dawnline background update worker, started detached by luci.dawnline and +// by the agent (automatic runs). // -// updater check -// updater install app|amneziawg[:slava|grey[:ru]]|pkgs:|all +// updater check [app|amneziawg|packages] +// updater install app | app@ | app:reinstall | app:rollback +// updater install amneziawg[:auto|slava|grey[:ru]] | amneziawg:rollback +// updater install pkgs: +// updater auto (Settings → Updates: check, then install) // -// Progress: /var/run/dawnline/update-job.json; check results: -// /var/run/dawnline/update-check.json. The Updates tab polls both. +// One job at a time: the job holds the update lock (dawnline.updates) until +// it exits. Progress: /var/run/dawnline/update-job.json; check results: +// /var/run/dawnline/update-check.json. The Components tab polls both. The +// components themselves are dawnline.upd_app, upd_awg and upd_pkgs. 'use strict'; import * as fs from 'fs'; -import { cursor } from 'uci'; -import { connect } from 'ubus'; -import { VERSION, REPO, slog, iface_intent } from 'dawnline.util'; +import { slog, read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as upd from 'dawnline.updates'; +import * as app from 'dawnline.upd_app'; +import * as awg from 'dawnline.upd_awg'; +import * as pkgs from 'dawnline.upd_pkgs'; -const STATE_DIR = '/var/run/dawnline'; -const JOB_FILE = `${STATE_DIR}/update-job.json`; -const CHECK_FILE = `${STATE_DIR}/update-check.json`; -const WORK_DIR = '/tmp/dawnline-update'; -// Builds per OpenWrt release (tag = firmware version); the kernel module must match the firmware. -// Which AmneziaWG a build carries (2.0 or 3.1) is read from the package, per firmware. -const AWG_SOURCES = { - slava: { repo: 'Slava-Shchipunov/awg-openwrt', label: 'Slava-Shchipunov' }, - grey: { repo: '2Grey/awg-openwrt', label: '2Grey' }, -}; -const AWG_PKGS = [ 'kmod-amneziawg', 'amneziawg-tools', 'luci-proto-amneziawg' ]; -const AWG_RU = 'luci-i18n-amneziawg-ru'; -// OpenWrt packages Dawnline runs on (the Updates tab groups and names them). -// What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the -// stock system): the home-like link, and HTTPS plus certificates for the personal portal. -const SYS_PKGS = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme' ]; -// Packages released together with each of the above, updated as a set so OpenSSL never ends up -// half old and half new. -const PKG_FAMILY = [ - [ /^ip-full$/, /^ip-/ ], - [ /^(libustream-openssl|openssl-util)$/, /^(libustream-openssl|libopenssl|openssl-util$)/ ], - [ /^(acme|luci-app-acme$)/, /^acme/ ], -]; - -function family(p) { - for (let f in PKG_FAMILY) - if (match(p, f[0])) - return f[1]; - return null; -} +const PID = +split(fs.readfile('/proc/self/stat') ?? '0', ' ')[0]; +const POL = core.load().settings.updates; +const CHECKS = { app: app.check, amneziawg: awg.check, packages: pkgs.check }; +const INSTALLS = { app: app.install, amneziawg: awg.install, pkgs: pkgs.install }; +const WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages', packages: 'System packages' }; let job = { - action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null, - phase: '', log: [], error: null, result: null, + id: `${time()}-${PID}`, action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null, + pid: PID, auto: false, phase: '', from: null, to: null, log: [], error: null, result: null, }; +// An automatic run only shows up as a job once it installs something. +let quiet = ARGV[0] == 'auto'; +// What to restart once the job is over (never in the middle of it). +let after = {}; function save() { - fs.writefile(`${JOB_FILE}.tmp`, sprintf('%J', job)); - fs.rename(`${JOB_FILE}.tmp`, JOB_FILE); + if (!quiet) + write_json(upd.JOB_FILE, job, 0o644); } function log(msg) { let t = localtime(); push(job.log, sprintf('%02d:%02d:%02d %s', t.hour, t.min, t.sec, msg)); - if (length(job.log) > 300) - splice(job.log, 0, length(job.log) - 300); + if (length(job.log) > 400) + splice(job.log, 0, length(job.log) - 400); save(); } @@ -67,475 +55,261 @@ function phase(p) { log(p); } -function q(s) { - return "'" + replace(`${s ?? ''}`, "'", "'\\''") + "'"; -} - +/** A command, its output in the log: { code, out }. */ function run(cmd) { let p = fs.popen(cmd + ' 2>&1', 'r'); if (!p) return { code: 127, out: '' }; let out = p.read('all') ?? ''; - return { code: p.close(), out }; -} - -function run_logged(cmd) { - let r = run(cmd); - for (let line in split(trim(r.out), '\n')) + let r = { code: p.close(), out }; + for (let line in split(trim(out), '\n')) if (length(trim(line))) log(` ${line}`); return r; } -function repo() { - return REPO; +const ctx = { + pol: POL, + work: `/tmp/dawnline-update.${PID}`, + log, phase, run, save, + versions: (from, to) => { + job.from = from; + job.to = to; + save(); + }, + after: (what) => after[what] = true, +}; + +/* ---------- check results ---------- */ + +function checks_file() { + return read_json(upd.CHECK_FILE, null)?.components ?? {}; } -function have_curl() { - return fs.access('/usr/bin/curl', 'x'); +/** Components' results into the check file (the others stay as they were). */ +function save_check(res) { + let c = read_json(upd.CHECK_FILE, null) ?? {}; + c.components ??= {}; + for (let k, v in res) + c.components[k] = { ...v, time: time() }; + c.time = time(); + write_json(upd.CHECK_FILE, c, 0o644); } -function download(url, dest) { - let r = have_curl() - ? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 2 -o ${q(dest)} ${q(url)}`) - : run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(url)}`); - return r.code == 0 && (fs.stat(dest)?.size ?? 0) > 0; +/** What a check found, as short names ("Dawnline 0.3.3", "2 system packages"). */ +function found_in(res) { + let found = []; + if (res.app?.update) + push(found, `Dawnline ${res.app.latest}`); + if (res.amneziawg?.update && res.amneziawg.installed) + push(found, `AmneziaWG ${res.amneziawg.latest}`); + if (res.packages?.updates) + push(found, `${res.packages.updates} system package${res.packages.updates == 1 ? '' : 's'}`); + return found; } -/** Latest release tag; the /releases/latest redirect avoids API rate limits. */ -function latest_tag(rp) { - if (have_curl()) { - let r = run(`curl -sI --connect-timeout 15 --max-time 30 -o /dev/null -w '%{redirect_url}' ${q('https://github.com/' + rp + '/releases/latest')}`); - let m = match(trim(r.out), /\/releases\/tag\/([^\/?#]+)$/); - if (m) - return m[1]; - } - let r = run(`uclient-fetch -q -T 20 -O - ${q('https://api.github.com/repos/' + rp + '/releases/latest')}`); - try { - return json(r.out)?.tag_name; - } - catch (e) { - return null; - } -} - -function version_cmp(a, b) { - let pa = split(replace(`${a}`, /^v/, ''), /[.~+-]/), pb = split(replace(`${b}`, /^v/, ''), /[.~+-]/); - for (let i = 0; i < length(pa) || i < length(pb); i++) { - let x = pa[i] ?? '0', y = pb[i] ?? '0'; - if (match(x, /^[0-9]+$/) && match(y, /^[0-9]+$/)) { - if (int(x) != int(y)) - return int(x) < int(y) ? -1 : 1; +function run_checks(which) { + let res = {}; + for (let name in which) { + phase(`Checking ${WHO[name]}`); + try { + res[name] = CHECKS[name](ctx); } - else if (x != y) - return x < y ? -1 : 1; - } - return 0; -} - -function is_apk() { - return fs.access('/usr/bin/apk', 'x'); -} - -function pkg_version(name) { - let esc = replace(name, /[.+]/g, '\\$&'); - if (is_apk()) { - let m = match(run(`apk list --installed ${q(name)}`).out, regexp(`^${esc}-([^ ]+) `)); - return m ? m[1] : null; - } - // Libraries carry their ABI in the name (libustream-openssl20201210). - let re = regexp(`^${esc}([0-9]+)? - (.+)$`), found = null; - for (let line in split(run('opkg list-installed').out, '\n')) { - let m = match(trim(line), re); - if (m && (found == null || m[1] == null)) - found = m; - } - return found ? trim(found[2]) : null; -} - -function pkg_file_version(path) { - if (match(path, /\.ipk$/)) { - let o = run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out; - return match(o, /(^|\n)Version: *([^\n]+)/)?.[2]; - } - return match(run(`apk adbdump ${q(path)}`).out, /\n *version: *([^\n]+)/)?.[1]; -} - -function workdir() { - run(`rm -rf ${WORK_DIR}`); - fs.mkdir(WORK_DIR, 0o700); -} - -/* ---------- Dawnline itself ---------- */ - -function check_app() { - let rp = repo(); - let tag = latest_tag(rp); - if (!tag) - return { installed: VERSION, latest: null, update: false, note: `No published release in ${rp}` }; - let latest = replace(tag, /^v/, ''); - return { installed: VERSION, latest, tag, repo: rp, update: version_cmp(VERSION, latest) < 0 }; -} - -function install_app() { - let c = check_app(); - if (!c.latest) - die(c.note); - if (!c.update) { - log('Dawnline is up to date'); - return { installed: VERSION }; - } - // Releases carry luci-app-dawnline-.ipk and .apk plus sha256sums.txt. - let asset = `luci-app-dawnline-${c.latest}.${is_apk() ? 'apk' : 'ipk'}`; - let base = `https://github.com/${c.repo}/releases/download/${c.tag}`; - workdir(); - phase(`Downloading ${asset}`); - let f = `${WORK_DIR}/${asset}`, sums = `${WORK_DIR}/sha256sums.txt`; - if (!download(`${base}/${asset}`, f)) - die(`Download failed: ${asset}`); - phase('Verifying package'); - if (!download(`${base}/sha256sums.txt`, sums)) - die('The release has no sha256sums.txt'); - let want = null; - for (let line in split(fs.readfile(sums) ?? '', '\n')) { - let m = match(trim(line), /^([0-9a-f]{64})[ \t]+\*?(\S+)$/); - if (m && m[2] == asset) - want = m[1]; - } - let got = match(run(`sha256sum ${q(f)}`).out, /^([0-9a-f]{64})/)?.[1]; - if (!want || got != want) - die(`Checksum mismatch for ${asset}`); - phase('Backing up configuration'); - run('/usr/bin/dawnline backup --reason pre-update'); - phase('Installing package'); - if (run_logged(is_apk() ? `apk add --allow-untrusted ${q(f)}` : `opkg install ${q(f)}`).code != 0) - die('Installation failed'); - run('rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null'); - // Restart after this job has saved its final state. - run('( sleep 3; /etc/init.d/rpcd reload; /etc/init.d/dawnline restart ) /dev/null 2>&1 &'); - return { installed: c.latest }; -} - -/* ---------- AmneziaWG ---------- */ - -function awg_release() { - let u = connect(); - let b = u?.call('system', 'board') ?? {}; - u?.disconnect(); - let rel = b.release ?? {}; - let target = split(rel.target ?? '', '/'); - let arch = rel.arch ?? trim(run("sed -n \"s/^DISTRIB_ARCH='\\(.*\\)'/\\1/p\" /etc/openwrt_release").out); - if (!rel.version || length(target) != 2 || !arch) - return null; - return { - tag: `v${rel.version}`, - postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`, - ext: is_apk() ? 'apk' : 'ipk', - }; -} - -function awg_download(r, name, rp) { - let file = `${name}${r.postfix}.${r.ext}`; - let dest = `${WORK_DIR}/${replace(rp, '/', '_')}_${file}`; - return download(`https://github.com/${rp}/releases/download/${r.tag}/${file}`, dest) ? dest : null; -} - -/** When the build for this firmware was published (best effort). */ -function release_date(rp, tag) { - let r = run(`uclient-fetch -q -T 20 -O - ${q(`https://api.github.com/repos/${rp}/releases/tags/${tag}`)}`); - try { - return json(r.out)?.published_at ?? null; - } - catch (e) { - return null; - } -} - -/** AmneziaWG generation of a tools version: 3.x packages carry 3.1, older ones (1.0.x) 2.0. */ -function awg_gen(version) { - return version == null ? null : match(version, /^3\./) ? '3.1' : '2.0'; -} - -/** The newest tag of the same OpenWrt series (24.10.x) in a repository, if newer than ours. */ -function newer_series_tag(rp, tag) { - let r = run(`uclient-fetch -q -T 20 -O - ${q(`https://api.github.com/repos/${rp}/releases?per_page=30`)}`); - let series = match(tag, /^v([0-9]+\.[0-9]+)\./)?.[1]; - let best = null; - try { - for (let x in json(r.out) ?? []) { - let t = x.tag_name; - if (series && match(t, regexp(`^v${replace(series, '.', '\\.')}\\.`)) && version_cmp(t, tag) > 0 && (!best || version_cmp(t, best) > 0)) - best = t; + catch (e) { + log(`Error: ${e.message}`); + res[name] = { error: e.message, status: '' }; } } - catch (e) {} - return best; + save_check(res); + return res; } -function awg_installed() { - let r = {}; - for (let p in AWG_PKGS) - r[p] = pkg_version(p); - return r; +/** One line in Activity per new finding (the same finding is not repeated). */ +function note_found(res, st, auto) { + let found = found_in(res); + let sig = join(', ', found); + if (length(found) && sig != st.announced) { + if (auto) + slog('dawnline', 'info', `updates available · ${sig}`, null, 'Components'); + upd.history_add({ kind: 'found', items: found, auto }); + } + st.announced = sig; } -function check_awg() { - let installed = awg_installed(); - let ru = pkg_version(AWG_RU) != null; - let cur = installed['amneziawg-tools']; - let r = awg_release(); - if (!r) - return { installed: cur, gen: awg_gen(cur), packages: installed, current: null, ru, sources: {}, update: false, note: 'Cannot detect the firmware target' }; - workdir(); - let sources = {}; - for (let id, src in AWG_SOURCES) { - let f = awg_download(r, 'amneziawg-tools', src.repo); - let v = f ? pkg_file_version(f) : null; - let s2 = { label: src.label, repo: src.repo, tag: r.tag, version: v, gen: awg_gen(v), date: f ? release_date(src.repo, r.tag) : null }; - // A newer firmware may already get 3.1 from this source. - if (s2.gen != '3.1') { - let nt = newer_series_tag(src.repo, r.tag); - if (nt) { - let nf = awg_download({ ...r, tag: nt, postfix: replace(r.postfix, r.tag, nt) }, 'amneziawg-tools', src.repo); - let nv = nf ? pkg_file_version(nf) : null; - if (awg_gen(nv) == '3.1') - s2.newer = { tag: nt, gen: '3.1' }; - } +/* ---------- installs ---------- */ + +/** A line in the service log for each finished update (Dawnline's own is logged by the new agent). */ +function log_update(name, r) { + let how = job.auto ? ' automatically' : ''; + if (name == 'amneziawg') { + let b = r?.before?.['kmod-amneziawg'], a = r?.after?.['kmod-amneziawg']; + slog('awg', 'up', b && a && b != a ? `updated${how} · ${b} → ${a}` + : `installed the ${r?.build ?? ''} build${a ? ' · ' + a : ''}`, null, 'AmneziaWG'); + } + else if (name == 'pkgs' && length([ ...(r?.updated ?? []), ...(r?.installed ?? []) ])) + slog('dawnline', 'up', `updated${how} · ${join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])}`, null, 'System packages'); +} + +function split_target(w) { + let i = index(w, ':'), at = index(w, '@'); + let cut = i < 0 ? at : at < 0 || i < at ? i : at; + if (cut < 0) + return [ w, null ]; + return [ substr(w, 0, cut), substr(w, cut + (substr(w, cut, 1) == ':' ? 1 : 0)) ]; +} + +function app_status(installed, latest) { + if (!latest) + return 'latest'; + let c = upd.version_cmp(installed, latest); + return c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest'; +} + +function install(what) { + job.result ??= {}; + for (let w in what) { + let t = split_target(w), name = t[0], arg = t[1]; + if (!INSTALLS[name]) + die(`Unknown component ${name}`); + job.current = name; + phase(`Updating ${WHO[name]}`); + let r = INSTALLS[name](ctx, arg); + job.result[name] = r; + log_update(name, r); + // Installed components are current now: no stale "Update available". + let c = checks_file(); + if (name == 'pkgs' && r.check) + save_check({ packages: r.check }); + else if (name == 'app' && r.to && c.app) { + let s = app_status(r.to, c.app.latest); + save_check({ app: { ...c.app, installed: r.to, update: s == 'outdated', status: s } }); } - sources[id] = s2; + else if (name == 'amneziawg' && r.after) + save_check({ amneziawg: { ...(c.amneziawg ?? {}), installed: r.after['amneziawg-tools'], packages: r.after, + current: r.build ?? c.amneziawg?.current, update: false, status: 'latest' } }); + upd.history_add({ kind: 'install', component: w, from: r.from, to: r.to, state: 'done', auto: job.auto, + took: time() - job.started }); + delete job.current; } - // The installed build: the source whose package matches, else the main one. - let current = null; - for (let id, x in sources) - if (!current && cur && x.version == cur) - current = id; - current ??= cur ? 'slava' : null; - let mine = current ? sources[current] : null; - return { installed: cur, gen: awg_gen(cur), packages: installed, current, ru, release: r.tag, sources, - latest: mine?.version ?? null, - update: cur == null || (mine?.version != null && version_cmp(cur, mine.version) < 0), - note: !length(filter(values(sources), (x) => x.version)) ? `No AmneziaWG build for OpenWrt ${substr(r.tag, 1)} yet` : null }; } -function install_awg(arg) { - let parts = split(arg ?? '', ':'); - let id = parts[0] || 'slava'; - let src = AWG_SOURCES[id]; - if (!src) - die(`Unknown AmneziaWG build ${id}`); - let want_ru = parts[1] == 'ru'; - let r = awg_release(); - if (!r) - die('Cannot detect the firmware target'); - let before = awg_installed(); - workdir(); - let files = []; - for (let p in [ ...AWG_PKGS, ...(want_ru ? [ AWG_RU ] : []) ]) { - phase(`Downloading ${p} from ${src.repo}`); - let f = awg_download(r, p, src.repo); - if (!f) - die(`No ${p} build for OpenWrt ${substr(r.tag, 1)} in ${src.repo}`); - push(files, f); - } - phase('Refreshing package lists'); - run_logged(is_apk() ? 'apk update' : 'opkg update'); - phase(`Installing the ${src.label} build`); - let cmd = is_apk() - ? `apk add --allow-untrusted ${join(' ', map(files, q))}` - : `opkg install --force-reinstall --force-downgrade ${join(' ', map(files, q))}`; - if (run_logged(cmd).code != 0) - die('Package installation failed'); - if (!want_ru && pkg_version(AWG_RU)) - run_logged(is_apk() ? `apk del ${AWG_RU}` : `opkg remove ${AWG_RU}`); - let after = awg_installed(); - if (before['kmod-amneziawg'] && before['kmod-amneziawg'] != after['kmod-amneziawg']) { - // New kernel module: every AmneziaWG interface must be re-created. - let ifaces = []; - let c = cursor(); - c.load('network'); - c.foreach('network', 'interface', (s) => { - if (s.proto == 'amneziawg' && s.disabled != '1') - push(ifaces, s['.name']); - }); - phase(`Reloading the kernel module (${length(ifaces)} tunnel(s) restart)`); - for (let i in ifaces) { - iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i); - run(`ifdown ${q(i)}`); - } - run('rmmod amneziawg'); - run_logged('modprobe amneziawg'); - for (let i in ifaces) - run(`ifup ${q(i)}`); - } - run('rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null'); - return { build: id, before, after }; -} - -/* ---------- OpenWrt packages Dawnline uses ---------- */ - -// Installed packages with a newer version in the feeds: { name: latest }. -function upgradable(refresh) { - if (refresh) { - phase('Refreshing package lists'); - run(is_apk() ? 'apk update' : 'opkg update'); - } - let up = {}; - if (is_apk()) { - for (let line in split(run('apk version -l "<"').out, '\n')) { - let m = match(line, /^(\S+?)-([0-9][^ ]*)\s+<\s+(\S+)/); - if (m) - up[m[1]] = m[3]; - } +/** Settings → Updates: check when due, install what is allowed (scheduled or right away). */ +function auto() { + let st = upd.auto_state(); + let what = upd.due(POL, st); + if (!what) + return; + let now = time(); + let res; + if (what == 'check' || now - (st.check ?? 0) >= 3600) { + res = run_checks(upd.TARGETS); + st.check = now; + note_found(res, st, true); } else - for (let line in split(run('opkg list-upgradable').out, '\n')) { - let m = match(line, /^(\S+) - (\S+) - (\S+)/); - if (m) - up[m[1]] = m[3]; - } - return up; + res = checks_file(); + if (what == 'install') + upd.mark_day(POL, st, now); + upd.auto_save(st); + if (!POL.auto || (what != 'install' && POL.mode != 'immediate')) + return; + let todo = []; + // Packages first, Dawnline last: it restarts rpcd and itself. + if (index(POL.targets, 'packages') >= 0 && res.packages?.updates) { + let names = filter(keys(res.packages.pkgs ?? {}), (p) => res.packages.pkgs[p].latest || length(res.packages.pkgs[p].with ?? [])); + if (length(names)) + push(todo, `pkgs:${join(',', names)}`); + } + let a = res.amneziawg; + if (index(POL.targets, 'amneziawg') >= 0 && a?.update && a.installed) { + // Only the same build, same generation: anything else needs a person to decide. + if (a.current && !a.gen_change) + push(todo, `amneziawg:${a.current}${a.ru ? ':ru' : ''}`); + else + slog('awg', 'info', `${a.latest ?? 'a new build'} needs a manual switch in Components`, null, 'AmneziaWG'); + } + if (index(POL.targets, 'app') >= 0 && res.app?.update) + push(todo, 'app'); + if (!length(todo)) + return; + quiet = false; + job.action = 'install'; + job.component = join(' ', todo); + job.auto = true; + job.log = []; + log(`Automatic update: ${join(', ', todo)}`); + install(todo); } -// The packages to update for these names: each one plus its upgradable family. -function with_family(names, up) { - let set = {}; - for (let n in names) { - if (up[n]) - set[n] = true; - let f = family(n); - if (f) - for (let u in keys(up)) - if (match(u, f)) - set[u] = true; - } - return sort(keys(set)); -} - -function check_pkgs(refresh) { - let up = upgradable(refresh ?? true); - let res = {}, all = {}; - for (let p in SYS_PKGS) { - let v = pkg_version(p); - let set = v ? with_family([ p ], up) : []; - res[p] = { installed: v, latest: v && up[p] ? up[p] : null, with: filter(set, (x) => x != p) }; - for (let x in set) - all[x] = true; - } - return { pkgs: res, updates: length(keys(all)) }; -} - -// Before install_pkgs: ucode resolves a name at the point it is used. -function save_check(res, at) { - fs.writefile(CHECK_FILE, sprintf('%J', { time: at ?? time(), components: res })); -} - -function install_pkgs(arg) { - let names = filter(split(arg ?? '', ','), (x) => x != ''); - for (let n in names) - if (index(SYS_PKGS, n) < 0) - die(`${n} is not a package Dawnline manages`); - if (!length(names)) - die('Nothing to install'); - phase('Refreshing package lists'); - run_logged(is_apk() ? 'apk update' : 'opkg update'); - let missing = filter(names, (n) => pkg_version(n) == null); - let have = with_family(filter(names, (n) => pkg_version(n) != null), upgradable(false)); - if (length(have)) { - phase(`Updating ${join(', ', have)}`); - if (run_logged(is_apk() ? `apk upgrade ${join(' ', map(have, q))}` : `opkg upgrade ${join(' ', map(have, q))}`).code != 0) - die('Update failed'); - } - if (length(missing)) { - phase(`Installing ${join(', ', missing)}`); - if (run_logged(is_apk() ? `apk add ${join(' ', map(missing, q))}` : `opkg install ${join(' ', map(missing, q))}`).code != 0) - die('Installation failed'); - } - // Show the new state right away instead of the check from before the update. - try { - let c = json(fs.readfile(CHECK_FILE) ?? '{}') ?? {}; - c.components ??= {}; - c.components.packages = check_pkgs(false); - save_check(c.components, c.time); - } - catch (e) { - log(`Could not refresh the package check: ${e.message}`); - } - // The portal's HTTPS runs in uhttpd. Restart after this job saved its state. - let touched = [ ...names, ...have ]; - // A missing piece arrived: set up what waited for it (the portal, the home-like link). - if (length(missing) && length(filter(missing, (n) => match(n, /^(openssl-util|libustream|ip-full|kmod-veth)/)))) - run('( sleep 3; /usr/bin/dawnline apply; /etc/init.d/uhttpd restart; /etc/init.d/dawnline restart ) /dev/null 2>&1 &'); - else if (length(filter(touched, (n) => match(n, /^(libustream|libopenssl)/)))) - run('( sleep 3; /etc/init.d/uhttpd restart; /etc/init.d/dawnline restart ) /dev/null 2>&1 &'); - return { updated: have, installed: missing }; +/** The restarts the job asked for, in one go, after its final state is saved. */ +function restarts() { + let cmds = []; + if (after.app) + push(cmds, '/etc/init.d/rpcd reload'); + else if (after.apply) + push(cmds, '/usr/bin/dawnline apply'); + if (after.uhttpd) + push(cmds, '/etc/init.d/uhttpd restart'); + if (after.app || after.apply || after.uhttpd) + push(cmds, '/etc/init.d/dawnline restart'); + if (length(cmds)) + system(`( sleep 2; ${join('; ', cmds)} ) /dev/null 2>&1 &`); } /* ---------- main ---------- */ -const CHECKS = { app: check_app, amneziawg: check_awg, packages: check_pkgs }; -const INSTALLS = { app: install_app, amneziawg: install_awg, pkgs: install_pkgs }; -const UPDATE_WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages' }; - -/** A line in the service log for each finished update (nothing when there was nothing to do). */ -function log_update(name, r) { - // Dawnline's own update is logged by the new agent when it starts (also after install.sh). - if (name == 'amneziawg') { - let b = r?.before?.['kmod-amneziawg'], a = r?.after?.['kmod-amneziawg']; - slog('awg', 'up', b && a && b != a ? `updated · ${b} → ${a}` : `installed the ${AWG_SOURCES[r?.build]?.label ?? r?.build} build${a ? ' · ' + a : ''}`, - null, 'AmneziaWG'); - } - else if (name == 'pkgs' && length([ ...(r?.updated ?? []), ...(r?.installed ?? []) ])) - slog('dawnline', 'up', `updated · ${join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])}`, null, 'System packages'); +ensure_dir(RUN_DIR); +// One job at a time (LuCI refuses a second one; an automatic run just skips its turn). +let LOCK = null; +for (let i = 0; i < 10 && !LOCK; i++) { + LOCK = upd.try_lock(); + if (!LOCK) + system('usleep 100000 2>/dev/null || sleep 1'); } - - -if (!fs.access(STATE_DIR)) - fs.mkdir(STATE_DIR, 0o755); +if (!LOCK) + exit(0); +fs.mkdir(ctx.work, 0o700); save(); try { if (job.action == 'check') { - let res = {}; - for (let name, fn in CHECKS) { - phase(`Checking ${name}`); - try { - res[name] = fn(); - } - catch (e) { - res[name] = { error: e.message }; - } - } - save_check(res); - job.result = res; - } - else if (job.action == 'install') { - let what = job.component == 'all' ? [ 'amneziawg', 'app' ] : [ job.component ]; - job.result = {}; - for (let w in what) { - let i = index(w, ':'); - let name = i < 0 ? w : substr(w, 0, i), arg = i < 0 ? null : substr(w, i + 1); - if (!INSTALLS[name]) - die(`Unknown component ${name}`); - phase(`Updating ${name}`); - job.result[name] = INSTALLS[name](arg); - log_update(name, job.result[name]); - } + let which = job.component ? [ job.component ] : upd.TARGETS; + for (let w in which) + if (!CHECKS[w]) + die(`Unknown component ${w}`); + job.result = run_checks(which); + let st = upd.auto_state(); + note_found(job.result, st, false); + if (length(which) == length(upd.TARGETS)) + st.check = time(); + upd.auto_save(st); } + else if (job.action == 'install') + install([ job.component ]); + else if (job.action == 'auto') + auto(); else - die('Usage: updater check | install app|amneziawg[:build[:ru]]|pkgs:|all'); + die('Usage: updater check [app|amneziawg|packages] | install | auto'); job.state = 'done'; phase('Finished'); } catch (e) { + quiet = false; job.state = 'failed'; job.error = e.message; log(`Error: ${e.message}`); - if (job.action == 'install') { - let name = split(job.component, ':')[0]; - slog(name == 'amneziawg' ? 'awg' : 'dawnline', 'error', 'update failed', e.message, UPDATE_WHO[name] ?? 'Dawnline'); + let name = job.current ?? split_target(split(job.component ?? '', ' ')[0])[0]; + if (job.action != 'check') { + slog(name == 'amneziawg' ? 'awg' : 'dawnline', 'error', `${job.auto ? 'automatic ' : ''}update failed`, e.message, WHO[name] ?? 'Dawnline'); + upd.history_add({ kind: 'install', component: name, from: job.from, to: job.to, state: 'failed', auto: job.auto, error: e.message, + took: time() - job.started }); } + else + upd.history_add({ kind: 'error', component: job.component ?? 'all', state: 'failed', error: e.message }); } -run(`rm -rf ${WORK_DIR}`); +system(`rm -rf '${ctx.work}'`); job.finished = time(); +delete job.current; save(); +restarts(); diff --git a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.js b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.js index 6c387e9..9037512 100644 --- a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.js +++ b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.js @@ -1,6 +1,6 @@ -"use strict";(()=>{var rt=Object.create;var Pe=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,ot=Object.prototype.hasOwnProperty;var lt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ct=(t,e,a,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let v of st(e))!ot.call(t,v)&&v!==a&&Pe(t,v,{get:()=>e[v],enumerable:!(i=at(e,v))||i.enumerable});return t};var ut=(t,e,a)=>(a=t!=null?rt(it(t)):{},ct(e||!t||!t.__esModule?Pe(a,"default",{value:t,enumerable:!0}):a,t));var Ge=lt((Ke,Ue)=>{"use strict";var Oe=(function(){var t=function(M,k){var b=236,w=17,l=M,m=a[k],s=null,r=0,y=null,f=[],g={},T=function(c,u){r=l*4+17,s=(function(o){for(var d=new Array(o),p=0;p=7&&z(c),y==null&&(y=tt(l,m,f)),W(y,u)},E=function(c,u){for(var o=-1;o<=7;o+=1)if(!(c+o<=-1||r<=c+o))for(var d=-1;d<=7;d+=1)u+d<=-1||r<=u+d||(0<=o&&o<=6&&(d==0||d==6)||0<=d&&d<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=d&&d<=4?s[c+o][u+d]=!0:s[c+o][u+d]=!1)},P=function(){for(var c=0,u=0,o=0;o<8;o+=1){T(!0,o);var d=v.getLostPoint(g);(o==0||c>d)&&(c=d,u=o)}return u},H=function(){for(var c=8;c>o&1)==1;s[Math.floor(o/3)][o%3+r-8-3]=d}for(var o=0;o<18;o+=1){var d=!c&&(u>>o&1)==1;s[o%3+r-8-3][Math.floor(o/3)]=d}},Q=function(c,u){for(var o=m<<3|u,d=v.getBCHTypeInfo(o),p=0;p<15;p+=1){var x=!c&&(d>>p&1)==1;p<6?s[p][8]=x:p<8?s[p+1][8]=x:s[r-15+p][8]=x}for(var p=0;p<15;p+=1){var x=!c&&(d>>p&1)==1;p<8?s[8][r-p-1]=x:p<9?s[8][15-p-1+1]=x:s[8][15-p-1]=x}s[r-8][8]=!c},W=function(c,u){for(var o=-1,d=r-1,p=7,x=0,C=v.getMaskFunction(u),_=r-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var R=0;R<2;R+=1)if(s[d][_-R]==null){var K=!1;x>>p&1)==1);var L=C(d,_-R);L&&(K=!K),s[d][_-R]=K,p-=1,p==-1&&(x+=1,p=7)}if(d+=o,d<0||r<=d){d-=o,o=-o;break}}},ae=function(c,u){for(var o=0,d=0,p=0,x=new Array(u.length),C=new Array(u.length),_=0;_=0?De.getAt(Be):0}}for(var $e=0,L=0;L_*8)throw"code length overflow. ("+p.getLengthInBits()+">"+_*8+")";for(p.getLengthInBits()+4<=_*8&&p.put(0,4);p.getLengthInBits()%8!=0;)p.putBit(!1);for(;!(p.getLengthInBits()>=_*8||(p.put(b,8),p.getLengthInBits()>=_*8));)p.put(w,8);return ae(p,d)};g.addData=function(c,u){u=u||"Byte";var o=null;switch(u){case"Numeric":o=B(c);break;case"Alphanumeric":o=F(c);break;case"Byte":o=J(c);break;case"Kanji":o=U(c);break;default:throw"mode:"+u}f.push(o),y=null},g.isDark=function(c,u){if(c<0||r<=c||u<0||r<=u)throw c+","+u;return s[c][u]},g.getModuleCount=function(){return r},g.make=function(){if(l<1){for(var c=1;c<40;c++){for(var u=$.getRSBlocks(c,m),o=D(),d=0;d";for(var p=0;p';o+=""}return o+="",o+="",o},g.createSvgTag=function(c,u,o,d){var p={};typeof arguments[0]=="object"&&(p=arguments[0],c=p.cellSize,u=p.margin,o=p.alt,d=p.title),c=c||2,u=typeof u=="undefined"?c*4:u,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||null,o.id=o.text?o.id||"qrcode-description":null,d=typeof d=="string"?{text:d}:d||{},d.text=d.text||null,d.id=d.text?d.id||"qrcode-title":null;var x=g.getModuleCount()*c+u*2,C,_,R,K,L="",Y;for(Y="l"+c+",0 0,"+c+" -"+c+",0 0,-"+c+"z ",L+=''+se(d.text)+"":"",L+=o.text?''+se(o.text)+"":"",L+='',L+='":u+=">";break;case"&":u+="&";break;case'"':u+=""";break;default:u+=d;break}}return u},nt=function(c){var u=1;c=typeof c=="undefined"?u*2:c;var o=g.getModuleCount()*u+c*2,d=c,p=o-c,x,C,_,R,K,L={"██":"█","█ ":"▀"," █":"▄"," ":" "},Y={"██":"▀","█ ":"▀"," █":" "," ":" "},j="";for(x=0;x=p?Y[K]:L[K];j+=` -`}return o%2&&c>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(c,u){if(c=c||1,c<2)return nt(u);c-=1,u=typeof u=="undefined"?c*2:u;var o=g.getModuleCount()*c+u*2,d=u,p=o-u,x,C,_,R,K=Array(c+1).join("██"),L=Array(c+1).join(" "),Y="",j="";for(x=0;x>>8),m.push(y&255)):m.push(w)}}return m}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},a={L:1,M:0,Q:3,H:2},i={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},v=(function(){var M=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],k=1335,b=7973,w=21522,l={},m=function(s){for(var r=0;s!=0;)r+=1,s>>>=1;return r};return l.getBCHTypeInfo=function(s){for(var r=s<<10;m(r)-m(k)>=0;)r^=k<=0;)r^=b<5&&(y+=3+T-5)}for(var f=0;f=256;)l-=255;return M[l]},w})();function A(M,k){if(typeof M.length=="undefined")throw M.length+"/"+k;var b=(function(){for(var l=0;l>>7-w%8&1)==1},b.put=function(w,l){for(var m=0;m>>l-m-1&1)==1)},b.getLengthInBits=function(){return k},b.putBit=function(w){var l=Math.floor(k/8);M.length<=l&&M.push(0),w&&(M[l]|=128>>>k%8),k+=1},b},B=function(M){var k=e.MODE_NUMBER,b=M,w={};w.getMode=function(){return k},w.getLength=function(s){return b.length},w.write=function(s){for(var r=b,y=0;y+2>>8&255)*192+(f&255),s.put(f,13),y+=2}if(y>>8)},k.writeBytes=function(b,w,l){w=w||0,l=l||b.length;for(var m=0;m0&&(b+=","),b+=M[w];return b+="]",b},k},G=function(){var M=0,k=0,b=0,w="",l={},m=function(r){w+=String.fromCharCode(s(r&63))},s=function(r){if(!(r<0)){if(r<26)return 65+r;if(r<52)return 97+(r-26);if(r<62)return 48+(r-52);if(r==62)return 43;if(r==63)return 47}throw"n:"+r};return l.writeByte=function(r){for(M=M<<8|r&255,k+=8,b+=1;k>=6;)m(M>>>k-6),k-=6},l.flush=function(){if(k>0&&(m(M<<6-k),M=0,k=0),b%3!=0)for(var r=3-b%3,y=0;y=k.length){if(l==0)return-1;throw"unexpected end of file./"+l}var r=k.charAt(b);if(b+=1,r=="=")return l=0,-1;if(r.match(/^\s$/))continue;w=w<<6|s(r.charCodeAt(0)),l+=6}var y=w>>>l-8&255;return l-=8,y};var s=function(r){if(65<=r&&r<=90)return r-65;if(97<=r&&r<=122)return r-97+26;if(48<=r&&r<=57)return r-48+52;if(r==43)return 62;if(r==47)return 63;throw"c:"+r};return m},re=function(M,k){var b=M,w=k,l=new Array(M*k),m={};m.setPixel=function(f,g,T){l[g*b+f]=T},m.write=function(f){f.writeString("GIF87a"),f.writeShort(b),f.writeShort(w),f.writeByte(128),f.writeByte(0),f.writeByte(0),f.writeByte(0),f.writeByte(0),f.writeByte(0),f.writeByte(255),f.writeByte(255),f.writeByte(255),f.writeString(","),f.writeShort(0),f.writeShort(0),f.writeShort(b),f.writeShort(w),f.writeByte(0);var g=2,T=r(g);f.writeByte(g);for(var E=0;T.length-E>255;)f.writeByte(255),f.writeBytes(T,E,255),E+=255;f.writeByte(T.length-E),f.writeBytes(T,E,T.length-E),f.writeByte(0),f.writeString(";")};var s=function(f){var g=f,T=0,E=0,P={};return P.write=function(H,q){if(H>>>q)throw"length over";for(;T+q>=8;)g.writeByte(255&(H<>>=8-T,E=0,T=0;E=H<0&&g.writeByte(E)},P},r=function(f){for(var g=1<>6,128|h&63):h<55296||h>=57344?i.push(224|h>>12,128|h>>6&63,128|h&63):(v++,h=65536+((h&1023)<<10|a.charCodeAt(v)&1023),i.push(240|h>>18,128|h>>12&63,128|h>>6&63,128|h&63))}return i}return e(t)}})();(function(t){typeof define=="function"&&define.amd?define([],t):typeof Ke=="object"&&(Ue.exports=t())})(function(){return Oe})});function ie(t){if(!t||t<0)return"0 B";let e=["B","KB","MB","GB","TB"],a=0,i=t;for(;i>=1024&&a=100||a===0?Math.round(i):i.toFixed(1)} ${e[a]}`}function ye(t,e=Date.now()/1e3){if(!t)return"never";let a=Math.max(0,Math.round(e-t));return a<60?"just now":a<3600?`${Math.floor(a/60)} min ago`:a<86400?`${Math.floor(a/3600)} h ago`:a<86400*30?`${Math.floor(a/86400)} d ago`:new Date(t*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function be(t){if(!t)return"";let[e,a,i]=t.split("-").map(Number);return new Date(e,a-1,i).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function we(t,e=Date.now()){if(!t)return null;let[a,i,v]=t.split("-").map(Number),h=new Date(a,i-1,v,23,59,59).getTime();return Math.ceil((h-e)/864e5)}var Se={lan:"Home network",internet:"Internet",both:"Home network + Internet"};var ve={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},Re={active:"Active",paused:"Paused",paused_all:"Paused (everyone)",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server"};function Ne(t){var v,h,A;let e=t.trim().split(/\s+/).filter(Boolean);if(!e.length)return"?";let a=(v=e[0][0])!=null?v:"",i=e.length>1?(h=e[e.length-1][0])!=null?h:"":(A=e[0][1])!=null?A:"";return(a+i).toUpperCase()}function xe(t){let e=a=>a.disabled?3:a.online?0:a.handshake?1:2;return t.map((a,i)=>[a,i]).sort((a,i)=>e(a[0])-e(i[0])||a[1]-i[1]).map(([a])=>a)}var Ie={phone:'',computer:'',tablet:'',router:'',other:'',ethernet:'',bridge:'',wifi:'',tunnel:'',plus:'',chart:'',reset:'',package:'',code:'',plug:'',sunrise:'',refresh:'',archive:'',qr:'',copy:'',download:'',link:'',trash:'',edit:'',pause:'',play:'',key:'',out:'',admin:'',shield:'',shieldplus:'',lock:'',zap:'',check:'',alert:'',x:'',globe:'',home:'',open:'',file:'',network:'',moon:'',chevron:'',clock:'',calendar:'',minus:'',more:'',pin:'',activity:''};function He(t,e="dl-icon"){var i;let a=(i=Ie[t])!=null?i:Ie.phone;return``}var qe=ut(Ge(),1),ft='';function Fe(t,e=3,a=!0){let i=(0,qe.default)(0,t.length>300?"Q":"H");i.addData(t,"Byte"),i.make();let v=i.getModuleCount(),h=v+e*2,A=a?Math.round(v*.22):0;A&&(v-A)%2&&A++;let $=(v-A)/2,D=$+A,B=(U,N)=>A>0&&U>=$&&U=$&&N${ft}`}return`${J}`}var dt={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},ht={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function vt(t){let e={};for(let[a,i]of Object.entries(ht))t[a]!=null&&t[a]!==""&&(e[i]=String(t[a]));return e}function pt(t,e){var D;let a=t.amnezia,i=(D=a.obfuscation)!=null?D:{},v=B=>i[B]!=null&&i[B]!==""?String(i[B]):dt[B],h=a.host.replace(/^\[(.*)\]$/,"$1"),A={H1:v("h1"),H2:v("h2"),H3:v("h3"),H4:v("h4"),I1:v("i1"),I2:v("i2"),I3:v("i3"),I4:v("i4"),I5:v("i5"),Jc:v("jc"),Jmin:v("jmin"),Jmax:v("jmax"),S1:v("s1"),S2:v("s2"),S3:v("s3"),S4:v("s4"),...vt(i),allowed_ips:a.allowed_ips,client_ip:a.client_ip,client_priv_key:a.client_priv_key,client_pub_key:a.client_pub_key,config:t.conf.replace(/\r?\n/g,`\r -`),hostName:h,mtu:a.mtu,persistent_keep_alive:a.persistent_keep_alive,port:Number(a.port),psk_key:a.psk_key,server_pub_key:a.server_pub_key},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(A),port:String(a.port),protocol_version:i.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:h};return a.dns[0]&&($.dns1=a.dns[0]),a.dns[1]&&($.dns2=a.dns[1]),$}function gt(t){let e="";for(let a=0;a{h==null||h===!1||(Array.isArray(h)?h.forEach(v):i.appendChild(typeof h=="string"?document.createTextNode(h):h))};return a.forEach(v),i}function O(t){let e=n("span",{class:"ic"});return e.innerHTML=He(t,"ic-svg"),e}var yt='',Le=document.getElementById("app"),je,pe=(je=Le.dataset.base)!=null?je:"",bt=Le.dataset.title||"Dawnline",Ae=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,Ve=0,wt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(pe)?pe.slice(1):"",_e=class extends Error{constructor(a,i){super(i);this.status=a}};async function ne(t,e){var v;let a=await fetch(`${pe}/api/${t}`,{method:e===void 0?"GET":"POST",credentials:"omit",headers:e===void 0?{}:{"Content-Type":"application/json"},body:e===void 0?void 0:JSON.stringify(e),cache:"no-store"}),i=null;try{i=await a.json()}catch{}if(!a.ok)throw new _e(a.status,(v=i==null?void 0:i.error)!=null?v:`Request failed (${a.status})`);return i}function te(t,e=!1){let a=n("div",{class:`toast${e?" bad":""}`,role:"status"},t);document.body.appendChild(a),requestAnimationFrame(()=>a.classList.add("show")),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>a.remove(),300)},2600)}async function le(t,e="Copied"){try{await navigator.clipboard.writeText(t)}catch{let a=n("textarea",{class:"offscreen"},t);document.body.appendChild(a),a.select(),document.execCommand("copy"),a.remove()}te(e)}function ze(t,e){let a=URL.createObjectURL(new Blob([e],{type:"application/octet-stream"})),i=n("a",{href:a,download:t,class:"offscreen"});document.body.appendChild(i),i.click(),setTimeout(()=>{URL.revokeObjectURL(a),i.remove()},1e3)}var Z=null;function Je(t,e){let a=i=>{Z!=null||(Z=document.body.appendChild(n("div",{class:"tip"}))),Z.replaceChildren(...e().map((v,h)=>n("div",{class:h?"muted":"tip-title"},v))),Z.style.display="",Z.style.left=`${i.clientX}px`,Z.style.top=`${i.clientY-10}px`};t.addEventListener("mouseenter",a),t.addEventListener("mousemove",a),t.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function xt(t){let e=Math.max(1,...t),a=n("div",{class:"spark"});return t.forEach((i,v)=>{let h=n("i",{class:i?"":"zero"});h.style.height=`${Math.max(8,i/e*100)}%`;let A=t.length-1-v,$=new Date(Date.now()-A*864e5);Je(h,()=>[A===0?"Today":A===1?"Yesterday":$.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ie(i)]),a.appendChild(h)}),a}var oe=null,ce=null;function ee(t=!1){if(!oe)return;let e=oe;if(oe=null,document.body.classList.remove("locked"),ce==null||ce(),ce=null,t){e.remove();return}e.classList.remove("open"),setTimeout(()=>e.remove(),250)}function fe(t,e,...a){let i=!!oe;ee(!0);let v=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":t},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},t),e?n("span",{class:"muted s"},e):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},O("x"))),n("div",{class:"sheet-body"},...a)),h=n("div",{class:"sheet",onclick:A=>{A.target===h&&ee()}},v);return document.body.appendChild(h),document.body.classList.add("locked"),i?h.classList.add("open"):requestAnimationFrame(()=>h.classList.add("open")),oe=h,v}document.addEventListener("keydown",t=>{t.key==="Escape"&&(ge(),ee())});var X=null;function ge(){X==null||X.remove(),X=null}document.addEventListener("click",t=>{X&&!X.contains(t.target)&&ge()});function Mt(t,e){ge();let a=n("div",{class:"menu",role:"menu"},e.map(h=>h?n("button",{type:"button",role:"menuitem",class:`menu-item${h.danger?" danger":""}`,onclick:()=>{ge(),h.run()}},O(h.icon),n("span",{},h.label)):n("div",{class:"menu-sep"})));document.body.appendChild(a);let i=t.getBoundingClientRect(),v=230;a.style.left=`${Math.max(8,Math.min(window.innerWidth-v-8,i.right-v))}px`,a.style.top=`${i.bottom+6+window.scrollY}px`,X=a}function Te(...t){Le.replaceChildren(n("header",{class:"top"},n("div",{class:"brand"},(()=>{let e=n("span",{class:"logo"});return e.innerHTML=yt,e})(),n("span",{},(S==null?void 0:S.server.name)||bt),n("span",{class:"faint"},"· Dawnline"))),n("main",{class:"wrap"},...t))}function Qe(){Te(n("div",{class:"card signin"},n("div",{class:"hero-ic"},O("key")),n("h1",{},"This link no longer works"),n("p",{class:"muted"},"Ask for a new personal link.")))}function kt(t){return t.state==="active"?"ok":t.state==="quota"||t.state==="expired"?"bad":"warn"}var At={internet:"The internet, through the router",lan:"Devices at home",both:"Devices at home and the internet, through the router"};function _t(t){let e=t.person,a=e.quota_limit?Math.min(100,e.quota_used/e.quota_limit*100):0,i=n("div",{class:`meter${a>=100?" bad":a>=90?" warn":""}`},n("i"));i.firstChild.style.width=`${a}%`,e.quota_limit&&Je(i,()=>[`${a.toFixed(1)}% used`,`${ie(Math.max(0,e.quota_limit-e.quota_used))} left`]);let v=we(e.expires),h=n("div",{class:"slots"});for(let D=0;D=e.device_limit?"over":D=0?`${v} day${v===1?"":"s"} left`:"ended"):null)),n("span",{class:"faint s"},e.hours?`Available ${e.hours.replace("-","–")} (router time). Need a change? Ask the admin.`:"Need a change? Ask the admin.")))}function Ct(t){return t.disabled?n("span",{class:"dstat"},"Disabled by the admin"):t.online?n("span",{class:"dstat ok"},"Connected"):t.handshake?n("span",{class:"dstat"},`Last connected ${ye(t.handshake)}`):n("span",{class:"dstat warn"},"Not set up yet")}function We(t,e){return t.access!=="internet"&&t.state==="active"&&!e.disabled}function Lt(t,e){let a=xe(t.devices).filter(h=>h.hostname&&We(t,h));if(!a.length)return null;let i=a[0].hostname,v=i.slice(i.indexOf("."));return n("div",{class:"names"},n("div",{class:"names-head"},n("span",{class:"names-ic"},O("home")),n("div",{class:"stack"},n("span",{class:"strong s"},"Names at home"),n("span",{class:"faint s"},e?"Devices at home and on this VPN reach yours as ":"Other devices at home reach yours as ",n("span",{class:"mono"},`name${v}`)))),n("div",{class:"names-list"},a.map(h=>{let A=h.hostname.indexOf(".");return n("button",{type:"button",class:"name-chip",title:h.name,"aria-label":`Copy ${h.hostname}`,onclick:()=>le(h.hostname,"Address copied")},n("span",{class:"mono"},A>0?[h.hostname.slice(0,A),n("span",{class:"faint"},h.hostname.slice(A))]:h.hostname),O("copy"))})))}function Tt(t,e){let a=n("button",{type:"button",class:"icon-btn soft","aria-label":`${t.name} options`},O("more"));a.addEventListener("click",A=>{A.stopPropagation(),Mt(a,[{label:"Show QR code",icon:"qr",run:()=>ue(t,"qr")},{label:"Copy AmneziaVPN key",icon:"key",run:()=>Et(t)},{label:"Download .conf",icon:"download",run:()=>Dt(t)},null,...We(e.person,t)?[{label:"Copy IP address",icon:"copy",run:()=>le(t.address,"IP address copied")},...t.hostname?[{label:"Copy local address",icon:"home",run:()=>le(t.hostname,"Address copied")}]:[],null]:[],{label:"Rename",icon:"edit",run:()=>$t(t)},...t.disabled?[]:[{label:"New keys",icon:"reset",run:()=>Pt(t,e)}],{label:"Remove",icon:"trash",danger:!0,run:()=>St(t)}])});let i=t.spark.reduce((A,$)=>A+$,0),v=!t.handshake&&!t.disabled,h=e.here===t.id;return n("article",{class:`dcard${t.online?" online":""}${t.disabled?" off":""}${h?" here":""}`},n("div",{class:"dhead"},n("span",{class:"dic"},O(t.kind)),n("div",{class:"stack grow"},n("span",{class:"dname"},t.name),h?n("span",{class:"dstat here"},"This device"):Ct(t)),a),v?[n("button",{type:"button",class:"btn primary block",onclick:()=>ue(t)},O(Ae()?"open":"qr"),n("span",{},Ae()?"Open in AmneziaVPN":"Connect this device"))]:n("div",{class:"duse"},n("div",{class:"stack"},n("span",{class:"faint s"},"Last 7 days"),n("span",{class:"mono"},ie(i))),xt(t.spark)),t.config_stale&&!v?n("div",{class:"notice"},O("alert"),n("span",{class:"grow"},"Connection settings changed. Update this device to keep everything working."),n("button",{type:"button",class:"btn small",onclick:()=>ue(t)},"Update")):null)}function de(t){let e=t.person,a=we(e.expires),i=e.state!=="active"?n("div",{class:"notice bad"},O("alert"),n("span",{},e.state==="quota"?"You have used all your data for this period. Your devices are paused until it resets.":e.state==="expired"?"Your access has ended. Ask the admin to extend it.":e.state==="hours"?`Access is available ${e.hours.replace("-","–")} (router time).`:"Your access is paused by the admin.")):a!=null&&a>=0&&a<=Math.max(e.expire_warn,1)?n("div",{class:"notice"},O("alert"),n("span",{},`Your access ends ${a===0?"today":`in ${a} day${a===1?"":"s"}`} (${be(e.expires)}).`)):null,h=xe(e.devices).sort((D,B)=>+(B.id===t.here)-+(D.id===t.here)).map(D=>Tt(D,t));Math.max(0,e.device_limit-e.devices.length)&&h.push(n("button",{type:"button",class:"slot add",onclick:Ht},n("span",{class:"slot-ic"},O("plus")),n("span",{class:"strong"},"Add device")));let $=n("section",{class:"devices","aria-label":"Your devices"},n("div",{class:"card-head"},n("div",{class:"row-baseline"},n("h2",{},"Your devices"))),n("div",{class:"dgrid"},h),t.can_add?null:n("span",{class:"faint s"},`You have reached your limit of ${e.device_limit} devices. Remove one or ask the admin for more.`),n("span",{class:"faint s"},"New device? Install ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"AmneziaVPN")," on it first."));Te(n("div",{class:"hello"},n("span",{class:`avatar${e.online?" online":""}`},Ne(e.name)),n("div",{class:"stack"},n("div",{class:"row"},n("h1",{},`Hi, ${e.name}`),e.state==="active"?null:n("span",{class:`pill ${kt(e)}`},Re[e.state])))),i,n("div",{class:"layout"},_t(t),$))}async function Ee(t){try{return await ne(`devices/${t.id}/config`)}catch(e){return te(e.message,!0),null}}async function Et(t){let e=await Ee(t);e&&le(await Me(e,`${e.server} · ${e.name}`),"Key copied")}async function Dt(t){let e=await Ee(t);e&&ze(e.filename,e.conf)}function Ye(t,e){if(/^\s*\[.+\]\s*$/.test(t))return n("span",{class:"conf-sec"},t);let a=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(t);if(!a)return document.createTextNode(t);let i=/^(\s*)(PrivateKey|PresharedKey)\b/.test(t);return n("span",{},n("span",{class:"conf-k"},a[1])," ",i&&!e?n("span",{class:"conf-mask"},"••••••••••••••••"):a[2])}function Bt(t){let e=!1,a=n("pre",{class:"conf"}),i=()=>a.replaceChildren(...t.conf.split(` -`).flatMap((h,A)=>A?[` -`,Ye(h,e)]:[Ye(h,e)])),v=n("button",{class:"btn small",onclick:h=>{h.preventDefault(),e=!e,v.replaceChildren(O(e?"x":"key"),n("span",{},e?"Hide key":"Show key")),i()}},O("key"),n("span",{},"Show key"));return i(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},t.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>ze(t.filename,t.conf)},O("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},O("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),v,n("button",{class:"btn small",onclick:h=>{h.preventDefault(),le(t.conf,"Configuration copied")}},O("copy"),n("span",{},"Copy"))),a))}async function ue(t,e,a){let i=a!=null?a:await Ee(t);if(!i)return;let v=await Me(i,`${i.server} · ${i.name}`),h=Ae(),A={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:v},O("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let I=n("div",{class:"qr"});return I.innerHTML=Fe(i.conf),n("div",{class:"pane center"},I,n("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},v),n("button",{class:"btn small",onclick:()=>le(v,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Bt(i)},$=h?["app","qr","key","file"]:["qr","key","file"],D={app:"Open in app",qr:"QR code",key:"Key",file:"File"},B=n("div",{class:"tab-body"}),F=n("div",{class:"tabs",role:"tablist"}),J=I=>{F.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===I)),B.replaceChildren(A[I]())};for(let I of $)F.appendChild(n("button",{role:"tab","data-id":I,onclick:()=>J(I)},D[I]));J(e&&$.includes(e)?e:$[0]);let U=n("div",{class:"waiting"}),N=I=>{I!=null&&I.online?U.replaceChildren(n("span",{class:"ok"},`${t.name} is connected`)):I!=null&&I.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${ye(I.handshake)}`)):U.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};N(t);let G=window.setInterval(async()=>{try{let I=await ne("state");S=I,N(I.person.devices.find(re=>re.id===t.id))}catch{}},5e3);fe(t.handshake?`Connect ${t.name}`:`${t.name} is ready`,h?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",F,B,U),ce=()=>{clearInterval(G),S&&de(S)}}function $t(t){let e=n("input",{type:"text",value:t.name,maxlength:48,"aria-label":"Device name"});fe(`Rename ${t.name}`,null,n("form",{class:"stack gap",onsubmit:async a=>{a.preventDefault();try{S=(await ne(`devices/${t.id}`,{action:"rename",name:e.value})).state,ee(),de(S),te("Renamed")}catch(i){te(i.message,!0)}}},e,n("button",{class:"btn primary block",type:"submit"},"Save"))),setTimeout(()=>e.select(),50)}function Pt(t,e){let a=e.here===t.id;fe(`New keys for ${t.name}?`,null,n("p",{class:"muted"},a?"This device is connected through the configuration it has now: it disconnects a few seconds after you confirm. Import the new configuration that opens next.":"Its current configuration stops working. Set the device up again with the new one that opens next."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn primary block",onclick:async()=>{try{let i=await ne(`devices/${t.id}`,{action:"rotate"});S=i.state,de(S),ue(t,void 0,i.config)}catch(i){te(i.message,!0)}}},"New keys")))}function St(t){fe(`Remove ${t.name}?`,null,n("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn danger-solid block",onclick:async()=>{try{S=(await ne(`devices/${t.id}`,{action:"delete"})).state,ee(),de(S),te("Device removed")}catch(e){te(e.message,!0)}}},"Remove")))}var V=navigator.userAgent,Ze=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function ke(){return Ze||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var Rt=[[/^SM-S93/,"Galaxy S25"],[/^SM-S92/,"Galaxy S24"],[/^SM-S91/,"Galaxy S23"],[/^SM-S90/,"Galaxy S22"],[/^SM-G99/,"Galaxy S21"],[/^SM-F9/,"Galaxy Z Fold"],[/^SM-F7/,"Galaxy Z Flip"],[/^SM-A5/,"Galaxy A5x"],[/^SM-A3/,"Galaxy A3x"],[/^SM-X/,"Galaxy Tab"]],Ce="",Nt=(async()=>{var e;let t=navigator.userAgentData;if(!t||!/Android/.test(V))return"";try{let a=((e=(await t.getHighEntropyValues(["model"])).model)!=null?e:"").trim();if(!a||a==="K")return"";let i=Rt.find(([v])=>v.test(a));Ce=i?`${i[1]} (${a})`:/^SM-/.test(a)?`Galaxy ${a}`:a}catch{}return Ce})();function It(t){return/iPhone/.test(V)?"iPhone":Ze?"iPad":/Android/.test(V)?Ce||(t==="tablet"?"Android tablet":"Android phone"):/CrOS/.test(V)?"Chromebook":/Mac OS X/.test(V)?"Mac":/Windows/.test(V)?"Windows PC":/Linux/.test(V)?"Linux PC":ve[t]}function Ht(){if(!S)return;let t=ke(),e=new Set(S.person.devices.map(D=>D.name.toLowerCase())),a=D=>{let B=D===ke()?It(D):ve[D];if(!e.has(B.toLowerCase()))return B;for(let F=2;F<20;F++)if(!e.has(`${B} ${F}`.toLowerCase()))return`${B} ${F}`;return B},i=n("input",{type:"text",value:a(t),maxlength:48,"aria-label":"Device name",required:!0}),v=!1;i.addEventListener("input",()=>v=!0),Nt.then(()=>{!v&&t===ke()&&(i.value=a(t))});let h=n("div",{class:"kinds"},S.kinds.map(D=>n("button",{type:"button",class:`kind${D===t?" on":""}`,"data-k":D,onclick:()=>{t=D,h.querySelectorAll(".kind").forEach(B=>B.classList.toggle("on",B.dataset.k===D)),v||(i.value=a(D))}},O(D),n("span",{},ve[D])))),A=n("p",{class:"err"}),$=n("button",{class:"btn primary block",type:"submit"},"Create connection");fe("Add a device",`${S.person.device_limit-S.person.devices.length} of ${S.person.device_limit} slots free`,n("form",{class:"add",onsubmit:async D=>{D.preventDefault(),$.disabled=!0,A.textContent="";try{let B=await ne("devices",{name:i.value.trim(),kind:t});S=B.state;let F=B.state.person.devices.find(J=>J.id===B.id);await ue(F,void 0,B.config)}catch(B){A.textContent=B.message,$.disabled=!1}}},n("label",{class:"lbl"},"What is it?"),h,n("label",{class:"lbl"},"Name"),i,A,$))}async function Xe(){try{S=await ne("state"),document.title=`${S.person.name} · ${S.title}`,!oe&&!X&&de(S)}catch(t){let e=t;e.status===404||e.status===401?(S=null,Qe()):S||Te(n("div",{class:"card"},n("p",{},e.message)))}}function Ot(){clearInterval(Ve),Ve=window.setInterval(()=>{S&&document.visibilityState==="visible"&&Xe()},15e3)}!pe||!wt?Qe():(Xe(),Ot());})(); +"use strict";(()=>{var ct=Object.create;var He=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,dt=Object.prototype.hasOwnProperty;var ht=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var pt=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of ut(t))!dt.call(e,u)&&u!==r&&He(e,u,{get:()=>t[u],enumerable:!(s=lt(t,u))||s.enumerable});return e};var vt=(e,t,r)=>(r=e!=null?ct(ft(e)):{},pt(t||!e||!e.__esModule?He(r,"default",{value:e,enumerable:!0}):r,e));var je=ht((Ve,Ye)=>{"use strict";var qe=(function(){var e=function(M,A){var b=236,w=17,c=M,m=r[A],i=null,a=0,y=null,d=[],g={},L=function(l,f){a=c*4+17,i=(function(o){for(var h=new Array(o),v=0;v=7&&z(l),y==null&&(y=st(c,m,d)),W(y,f)},D=function(l,f){for(var o=-1;o<=7;o+=1)if(!(l+o<=-1||a<=l+o))for(var h=-1;h<=7;h+=1)f+h<=-1||a<=f+h||(0<=o&&o<=6&&(h==0||h==6)||0<=h&&h<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=h&&h<=4?i[l+o][f+h]=!0:i[l+o][f+h]=!1)},P=function(){for(var l=0,f=0,o=0;o<8;o+=1){L(!0,o);var h=u.getLostPoint(g);(o==0||l>h)&&(l=h,f=o)}return f},I=function(){for(var l=8;l>o&1)==1;i[Math.floor(o/3)][o%3+a-8-3]=h}for(var o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;i[o%3+a-8-3][Math.floor(o/3)]=h}},Q=function(l,f){for(var o=m<<3|f,h=u.getBCHTypeInfo(o),v=0;v<15;v+=1){var x=!l&&(h>>v&1)==1;v<6?i[v][8]=x:v<8?i[v+1][8]=x:i[a-15+v][8]=x}for(var v=0;v<15;v+=1){var x=!l&&(h>>v&1)==1;v<8?i[8][a-v-1]=x:v<9?i[8][15-v-1+1]=x:i[8][15-v-1]=x}i[a-8][8]=!l},W=function(l,f){for(var o=-1,h=a-1,v=7,x=0,C=u.getMaskFunction(f),_=a-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var N=0;N<2;N+=1)if(i[h][_-N]==null){var K=!1;x>>v&1)==1);var T=C(h,_-N);T&&(K=!K),i[h][_-N]=K,v-=1,v==-1&&(x+=1,v=7)}if(h+=o,h<0||a<=h){h-=o,o=-o;break}}},ae=function(l,f){for(var o=0,h=0,v=0,x=new Array(f.length),C=new Array(f.length),_=0;_=0?Pe.getAt(Ne):0}}for(var Re=0,T=0;T_*8)throw"code length overflow. ("+v.getLengthInBits()+">"+_*8+")";for(v.getLengthInBits()+4<=_*8&&v.put(0,4);v.getLengthInBits()%8!=0;)v.putBit(!1);for(;!(v.getLengthInBits()>=_*8||(v.put(b,8),v.getLengthInBits()>=_*8));)v.put(w,8);return ae(v,h)};g.addData=function(l,f){f=f||"Byte";var o=null;switch(f){case"Numeric":o=B(l);break;case"Alphanumeric":o=q(l);break;case"Byte":o=J(l);break;case"Kanji":o=U(l);break;default:throw"mode:"+f}d.push(o),y=null},g.isDark=function(l,f){if(l<0||a<=l||f<0||a<=f)throw l+","+f;return i[l][f]},g.getModuleCount=function(){return a},g.make=function(){if(c<1){for(var l=1;l<40;l++){for(var f=$.getRSBlocks(l,m),o=E(),h=0;h";for(var v=0;v';o+=""}return o+="",o+="",o},g.createSvgTag=function(l,f,o,h){var v={};typeof arguments[0]=="object"&&(v=arguments[0],l=v.cellSize,f=v.margin,o=v.alt,h=v.title),l=l||2,f=typeof f=="undefined"?l*4:f,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||null,o.id=o.text?o.id||"qrcode-description":null,h=typeof h=="string"?{text:h}:h||{},h.text=h.text||null,h.id=h.text?h.id||"qrcode-title":null;var x=g.getModuleCount()*l+f*2,C,_,N,K,T="",Y;for(Y="l"+l+",0 0,"+l+" -"+l+",0 0,-"+l+"z ",T+=''+ie(h.text)+"":"",T+=o.text?''+ie(o.text)+"":"",T+='',T+='":f+=">";break;case"&":f+="&";break;case'"':f+=""";break;default:f+=h;break}}return f},ot=function(l){var f=1;l=typeof l=="undefined"?f*2:l;var o=g.getModuleCount()*f+l*2,h=l,v=o-l,x,C,_,N,K,T={"██":"█","█ ":"▀"," █":"▄"," ":" "},Y={"██":"▀","█ ":"▀"," █":" "," ":" "},j="";for(x=0;x=v?Y[K]:T[K];j+=` +`}return o%2&&l>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(l,f){if(l=l||1,l<2)return ot(f);l-=1,f=typeof f=="undefined"?l*2:f;var o=g.getModuleCount()*l+f*2,h=f,v=o-f,x,C,_,N,K=Array(l+1).join("██"),T=Array(l+1).join(" "),Y="",j="";for(x=0;x>>8),m.push(y&255)):m.push(w)}}return m}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},u=(function(){var M=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],A=1335,b=7973,w=21522,c={},m=function(i){for(var a=0;i!=0;)a+=1,i>>>=1;return a};return c.getBCHTypeInfo=function(i){for(var a=i<<10;m(a)-m(A)>=0;)a^=A<=0;)a^=b<5&&(y+=3+L-5)}for(var d=0;d=256;)c-=255;return M[c]},w})();function k(M,A){if(typeof M.length=="undefined")throw M.length+"/"+A;var b=(function(){for(var c=0;c>>7-w%8&1)==1},b.put=function(w,c){for(var m=0;m>>c-m-1&1)==1)},b.getLengthInBits=function(){return A},b.putBit=function(w){var c=Math.floor(A/8);M.length<=c&&M.push(0),w&&(M[c]|=128>>>A%8),A+=1},b},B=function(M){var A=t.MODE_NUMBER,b=M,w={};w.getMode=function(){return A},w.getLength=function(i){return b.length},w.write=function(i){for(var a=b,y=0;y+2>>8&255)*192+(d&255),i.put(d,13),y+=2}if(y>>8)},A.writeBytes=function(b,w,c){w=w||0,c=c||b.length;for(var m=0;m0&&(b+=","),b+=M[w];return b+="]",b},A},F=function(){var M=0,A=0,b=0,w="",c={},m=function(a){w+=String.fromCharCode(i(a&63))},i=function(a){if(!(a<0)){if(a<26)return 65+a;if(a<52)return 97+(a-26);if(a<62)return 48+(a-52);if(a==62)return 43;if(a==63)return 47}throw"n:"+a};return c.writeByte=function(a){for(M=M<<8|a&255,A+=8,b+=1;A>=6;)m(M>>>A-6),A-=6},c.flush=function(){if(A>0&&(m(M<<6-A),M=0,A=0),b%3!=0)for(var a=3-b%3,y=0;y=A.length){if(c==0)return-1;throw"unexpected end of file./"+c}var a=A.charAt(b);if(b+=1,a=="=")return c=0,-1;if(a.match(/^\s$/))continue;w=w<<6|i(a.charCodeAt(0)),c+=6}var y=w>>>c-8&255;return c-=8,y};var i=function(a){if(65<=a&&a<=90)return a-65;if(97<=a&&a<=122)return a-97+26;if(48<=a&&a<=57)return a-48+52;if(a==43)return 62;if(a==47)return 63;throw"c:"+a};return m},re=function(M,A){var b=M,w=A,c=new Array(M*A),m={};m.setPixel=function(d,g,L){c[g*b+d]=L},m.write=function(d){d.writeString("GIF87a"),d.writeShort(b),d.writeShort(w),d.writeByte(128),d.writeByte(0),d.writeByte(0),d.writeByte(0),d.writeByte(0),d.writeByte(0),d.writeByte(255),d.writeByte(255),d.writeByte(255),d.writeString(","),d.writeShort(0),d.writeShort(0),d.writeShort(b),d.writeShort(w),d.writeByte(0);var g=2,L=a(g);d.writeByte(g);for(var D=0;L.length-D>255;)d.writeByte(255),d.writeBytes(L,D,255),D+=255;d.writeByte(L.length-D),d.writeBytes(L,D,L.length-D),d.writeByte(0),d.writeString(";")};var i=function(d){var g=d,L=0,D=0,P={};return P.write=function(I,G){if(I>>>G)throw"length over";for(;L+G>=8;)g.writeByte(255&(I<>>=8-L,D=0,L=0;D=I<0&&g.writeByte(D)},P},a=function(d){for(var g=1<>6,128|p&63):p<55296||p>=57344?s.push(224|p>>12,128|p>>6&63,128|p&63):(u++,p=65536+((p&1023)<<10|r.charCodeAt(u)&1023),s.push(240|p>>18,128|p>>12&63,128|p>>6&63,128|p&63))}return s}return t(e)}})();(function(e){typeof define=="function"&&define.amd?define([],e):typeof Ve=="object"&&(Ye.exports=e())})(function(){return qe})});function se(e){if(!e||e<0)return"0 B";let t=["B","KB","MB","GB","TB"],r=0,s=e;for(;s>=1024&&r=100||r===0?Math.round(s):s.toFixed(1)} ${t[r]}`}function we(e,t=Date.now()/1e3){if(!e)return"never";let r=Math.max(0,Math.round(t-e));return r<60?"just now":r<3600?`${Math.floor(r/60)} min ago`:r<86400?`${Math.floor(r/3600)} h ago`:r<86400*30?`${Math.floor(r/86400)} d ago`:new Date(e*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function pe(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function ve(e){let[t,r,s]=e.split("-").map(Number);return new Date(t,(r||1)-1,s||1,12)}function gt(e){return(typeof e=="string"?/^\d{4}-\d{2}-\d{2}$/.test(e)?ve(e):new Date(e):e).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function xe(e){return e?gt(e):""}function mt(e,t){let r=s=>{let[u,p,k]=s.split("-").map(Number);return Date.UTC(u,p-1,k)};return Math.round((r(e)-r(t))/864e5)}function Ie(e,t){let r=ve(e);return r.setDate(r.getDate()+t),pe(r)}function Me(e,t=Date.now()){if(!e)return null;let r=typeof t=="number"?pe(new Date(t)):t,s=mt(e,r);return s>=0?s+1:s}var Oe={lan:"Home network",internet:"Internet",both:"Home network + Internet"};var ge={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},Ke={active:"Active",paused:"Paused",paused_all:"Paused (everyone)",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server"};function Ue(e){var u,p,k;let t=e.trim().split(/\s+/).filter(Boolean);if(!t.length)return"?";let r=(u=t[0][0])!=null?u:"",s=t.length>1?(p=t[t.length-1][0])!=null?p:"":(k=t[0][1])!=null?k:"";return(r+s).toUpperCase()}function ke(e){let t=r=>r.disabled?3:r.online?0:r.handshake?1:2;return e.map((r,s)=>[r,s]).sort((r,s)=>t(r[0])-t(s[0])||r[1]-s[1]).map(([r])=>r)}var Fe={phone:'',computer:'',tablet:'',router:'',other:'',ethernet:'',bridge:'',wifi:'',tunnel:'',plus:'',chart:'',reset:'',package:'',code:'',plug:'',sunrise:'',refresh:'',archive:'',qr:'',copy:'',download:'',link:'',trash:'',edit:'',pause:'',play:'',key:'',out:'',admin:'',shield:'',shieldplus:'',lock:'',zap:'',check:'',alert:'',x:'',globe:'',home:'',open:'',file:'',network:'',moon:'',chevron:'',clock:'',calendar:'',minus:'',more:'',pin:'',activity:''};function Ge(e,t="dl-icon"){var s;let r=(s=Fe[e])!=null?s:Fe.phone;return``}var ze=vt(je(),1),yt='';function Je(e,t=3,r=!0){let s=(0,ze.default)(0,e.length>300?"Q":"H");s.addData(e,"Byte"),s.make();let u=s.getModuleCount(),p=u+t*2,k=r?Math.round(u*.22):0;k&&(u-k)%2&&k++;let $=(u-k)/2,E=$+k,B=(U,R)=>k>0&&U>=$&&U=$&&R${yt}`}return`${J}`}var bt={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},wt={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function xt(e){let t={};for(let[r,s]of Object.entries(wt))e[r]!=null&&e[r]!==""&&(t[s]=String(e[r]));return t}function Mt(e,t){var E;let r=e.amnezia,s=(E=r.obfuscation)!=null?E:{},u=B=>s[B]!=null&&s[B]!==""?String(s[B]):bt[B],p=r.host.replace(/^\[(.*)\]$/,"$1"),k={H1:u("h1"),H2:u("h2"),H3:u("h3"),H4:u("h4"),I1:u("i1"),I2:u("i2"),I3:u("i3"),I4:u("i4"),I5:u("i5"),Jc:u("jc"),Jmin:u("jmin"),Jmax:u("jmax"),S1:u("s1"),S2:u("s2"),S3:u("s3"),S4:u("s4"),...xt(s),allowed_ips:r.allowed_ips,client_ip:r.client_ip,client_priv_key:r.client_priv_key,client_pub_key:r.client_pub_key,config:e.conf.replace(/\r?\n/g,`\r +`),hostName:p,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(k),port:String(r.port),protocol_version:s.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:p};return r.dns[0]&&($.dns1=r.dns[0]),r.dns[1]&&($.dns2=r.dns[1]),$}function kt(e){let t="";for(let r=0;r{var e;return(e=S==null?void 0:S.today)!=null?e:pe(new Date)};function n(e,t={},...r){let s=document.createElement(e);for(let[p,k]of Object.entries(t))k==null||k===!1||(p.startsWith("on")&&typeof k=="function"?s.addEventListener(p.slice(2),k):p==="class"?s.className=String(k):k===!0?s.setAttribute(p,""):s.setAttribute(p,String(k)));let u=p=>{p==null||p===!1||(Array.isArray(p)?p.forEach(u):s.appendChild(typeof p=="string"?document.createTextNode(p):p))};return r.forEach(u),s}function O(e){let t=n("span",{class:"ic"});return t.innerHTML=Ge(e,"ic-svg"),t}var _t='',Ee=document.getElementById("app"),Ze,me=(Ze=Ee.dataset.base)!=null?Ze:"",Ct=Ee.dataset.title||"Dawnline",Ce=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,Qe=0,Tt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(me)?me.slice(1):"",Te=class extends Error{constructor(r,s){super(s);this.status=r}};async function ne(e,t){var u;let r=await fetch(`${me}/api/${e}`,{method:t===void 0?"GET":"POST",credentials:"omit",headers:t===void 0?{}:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t),cache:"no-store"}),s=null;try{s=await r.json()}catch{}if(!r.ok)throw new Te(r.status,(u=s==null?void 0:s.error)!=null?u:`Request failed (${r.status})`);return s}function te(e,t=!1){let r=n("div",{class:`toast${t?" bad":""}`,role:"status"},e);document.body.appendChild(r),requestAnimationFrame(()=>r.classList.add("show")),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>r.remove(),300)},2600)}async function ce(e,t="Copied"){try{await navigator.clipboard.writeText(e)}catch{let r=n("textarea",{class:"offscreen"},e);document.body.appendChild(r),r.select();let s=document.execCommand("copy");if(r.remove(),!s)return te("Copying is blocked here. Select the text and copy it by hand.",!0)}te(t)}function Xe(e,t){let r=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),s=n("a",{href:r,download:e,class:"offscreen"});document.body.appendChild(s),s.click(),setTimeout(()=>{URL.revokeObjectURL(r),s.remove()},1e3)}var Z=null;function et(e,t){let r=s=>{Z!=null||(Z=document.body.appendChild(n("div",{class:"tip"}))),Z.replaceChildren(...t().map((u,p)=>n("div",{class:p?"muted":"tip-title"},u))),Z.style.display="",Z.style.left=`${s.clientX}px`,Z.style.top=`${s.clientY-10}px`};e.addEventListener("mouseenter",r),e.addEventListener("mousemove",r),e.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function Lt(e){let t=Math.max(1,...e),r=n("div",{class:"spark"});return e.forEach((s,u)=>{let p=n("i",{class:s?"":"zero"});p.style.height=`${Math.max(8,s/t*100)}%`;let k=e.length-1-u;et(p,()=>[k===0?"Today":k===1?"Yesterday":ve(Ie(De(),-k)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),se(s)]),r.appendChild(p)}),r}async function Be(e,t){if(!e.disabled){e.disabled=!0;try{await t()}finally{e.disabled=!1}}}var oe=null,le=null;function ee(e=!1){if(!oe)return;let t=oe;if(oe=null,document.body.classList.remove("locked"),le==null||le(),le=null,e){t.remove();return}t.classList.remove("open"),setTimeout(()=>t.remove(),250)}function fe(e,t,...r){let s=!!oe;ee(!0);let u=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":e},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},e),t?n("span",{class:"muted s"},t):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},O("x"))),n("div",{class:"sheet-body"},...r)),p=n("div",{class:"sheet",onclick:k=>{k.target===p&&ee()}},u);return document.body.appendChild(p),document.body.classList.add("locked"),s?p.classList.add("open"):requestAnimationFrame(()=>p.classList.add("open")),oe=p,u}document.addEventListener("keydown",e=>{e.key==="Escape"&&(ye(),ee())});var X=null;function ye(){X==null||X.remove(),X=null}document.addEventListener("click",e=>{X&&!X.contains(e.target)&&ye()});function Dt(e,t){ye();let r=t.filter((k,$)=>k||$>0&&t[$-1]&&t.slice($+1).some(Boolean)),s=n("div",{class:"menu",role:"menu"},r.map(k=>k?n("button",{type:"button",role:"menuitem",class:`menu-item${k.danger?" danger":""}`,onclick:()=>{ye(),k.run()}},O(k.icon),n("span",{},k.label)):n("div",{class:"menu-sep"})));document.body.appendChild(s);let u=e.getBoundingClientRect(),p=230;s.style.left=`${Math.max(8,Math.min(window.innerWidth-p-8,u.right-p))}px`,s.style.top=`${u.bottom+6+window.scrollY}px`,X=s}function $e(...e){Ee.replaceChildren(n("header",{class:"top"},n("div",{class:"brand"},(()=>{let t=n("span",{class:"logo"});return t.innerHTML=_t,t})(),n("span",{},(S==null?void 0:S.server.name)||Ct),n("span",{class:"faint"},"· Dawnline"))),n("main",{class:"wrap"},...e))}function tt(){$e(n("div",{class:"card signin"},n("div",{class:"hero-ic"},O("key")),n("h1",{},"This link no longer works"),n("p",{class:"muted"},"Ask for a new personal link.")))}function Et(e){return e.state==="active"?"ok":e.state==="quota"||e.state==="expired"?"bad":"warn"}var Bt={internet:"The internet, through the router",lan:"Devices at home",both:"Devices at home and the internet, through the router"};function $t(e){let t=e.person,r=t.quota_limit?Math.min(100,t.quota_used/t.quota_limit*100):0,s=n("div",{class:`meter${r>=100?" bad":r>=90?" warn":""}`},n("i"));s.firstChild.style.width=`${r}%`,t.quota_limit&&et(s,()=>[`${r.toFixed(1)}% used`,`${se(Math.max(0,t.quota_limit-t.quota_used))} left`]);let u=Me(t.expires,De()),p=n("div",{class:"slots"});for(let E=0;E=t.device_limit?"over":E=0?`${u} day${u===1?"":"s"} left`:"ended"):null)),n("span",{class:"faint s"},t.hours?`Available ${t.hours.replace("-","–")} (router time). Need a change? Ask the admin.`:"Need a change? Ask the admin.")))}function St(e){return e.disabled?n("span",{class:"dstat"},"Disabled by the admin"):e.online?n("span",{class:"dstat ok"},"Connected"):e.handshake?n("span",{class:"dstat"},`Last connected ${we(e.handshake)}`):n("span",{class:"dstat warn"},"Not set up yet")}function nt(e,t){return e.access!=="internet"&&e.state==="active"&&!t.disabled}function Pt(e,t){let r=ke(e.devices).filter(p=>p.hostname&&nt(e,p));if(!r.length)return null;let s=r[0].hostname,u=s.slice(s.indexOf("."));return n("div",{class:"names"},n("div",{class:"names-head"},n("span",{class:"names-ic"},O("home")),n("div",{class:"stack"},n("span",{class:"strong s"},"Names at home"),n("span",{class:"faint s"},t?"Devices at home and on this VPN reach yours as ":"Other devices at home reach yours as ",n("span",{class:"mono"},`name${u}`)))),n("div",{class:"names-list"},r.map(p=>{let k=p.hostname.indexOf(".");return n("button",{type:"button",class:"name-chip",title:p.name,"aria-label":`Copy ${p.hostname}`,onclick:()=>ce(p.hostname,"Address copied")},n("span",{class:"mono"},k>0?[p.hostname.slice(0,k),n("span",{class:"faint"},p.hostname.slice(k))]:p.hostname),O("copy"))})))}function Nt(e,t){let r=n("button",{type:"button",class:"icon-btn soft","aria-label":`${e.name} options`},O("more"));r.addEventListener("click",k=>{k.stopPropagation(),Dt(r,[{label:"Show QR code",icon:"qr",run:()=>ue(e,"qr")},{label:"Copy AmneziaVPN key",icon:"key",run:()=>Rt(e)},{label:"Download .conf",icon:"download",run:()=>Ht(e)},null,...nt(t.person,e)?[{label:"Copy IP address",icon:"copy",run:()=>ce(e.address,"IP address copied")},...e.hostname?[{label:"Copy local address",icon:"home",run:()=>ce(e.hostname,"Address copied")}]:[],null]:[],...e.disabled?[]:[{label:"Rename",icon:"edit",run:()=>Ot(e)},{label:"New keys",icon:"reset",run:()=>Kt(e,t)},{label:"Remove",icon:"trash",danger:!0,run:()=>Ut(e)}]])});let s=e.spark.reduce((k,$)=>k+$,0),u=!e.handshake&&!e.disabled,p=t.here===e.id;return n("article",{class:`dcard${e.online?" online":""}${e.disabled?" off":""}${p?" here":""}`},n("div",{class:"dhead"},n("span",{class:"dic"},O(e.kind)),n("div",{class:"stack grow"},n("span",{class:"dname"},e.name),p?n("span",{class:"dstat here"},"This device"):St(e)),r),u?[n("button",{type:"button",class:"btn primary block",onclick:()=>ue(e)},O(Ce()?"open":"qr"),n("span",{},Ce()?"Open in AmneziaVPN":"Connect this device"))]:n("div",{class:"duse"},n("div",{class:"stack"},n("span",{class:"faint s"},"Last 7 days"),n("span",{class:"mono"},se(s))),Lt(e.spark)),e.config_stale&&!u?n("div",{class:"notice"},O("alert"),n("span",{class:"grow"},"Connection settings changed. Update this device to keep everything working."),n("button",{type:"button",class:"btn small",onclick:()=>ue(e)},"Update")):null)}function de(e){let t=e.person,r=Me(t.expires,De()),s=t.state!=="active"?n("div",{class:"notice bad"},O("alert"),n("span",{},t.state==="quota"?"You have used all your data for this period. Your devices are paused until it resets.":t.state==="expired"?"Your access has ended. Ask the admin to extend it.":t.state==="hours"?`Access is available ${t.hours.replace("-","–")} (router time).`:"Your access is paused by the admin.")):r!=null&&r>=0&&r<=Math.max(t.expire_warn,1)?n("div",{class:"notice"},O("alert"),n("span",{},`Your access ends ${r===0?"today":`in ${r} day${r===1?"":"s"}`} (${xe(t.expires)}).`)):null,p=ke(t.devices).sort((E,B)=>+(B.id===e.here)-+(E.id===e.here)).map(E=>Nt(E,e));Math.max(0,t.device_limit-t.devices.length)&&p.push(n("button",{type:"button",class:"slot add",onclick:Vt},n("span",{class:"slot-ic"},O("plus")),n("span",{class:"strong"},"Add device")));let $=n("section",{class:"devices","aria-label":"Your devices"},n("div",{class:"card-head"},n("div",{class:"row-baseline"},n("h2",{},"Your devices"))),n("div",{class:"dgrid"},p),e.can_add?null:n("span",{class:"faint s"},`You have reached your limit of ${t.device_limit} devices. Remove one or ask the admin for more.`),n("span",{class:"faint s"},"New device? Install ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"AmneziaVPN")," on it first."));$e(n("div",{class:"hello"},n("span",{class:`avatar${t.online?" online":""}`},Ue(t.name)),n("div",{class:"stack"},n("div",{class:"row"},n("h1",{},`Hi, ${t.name}`),t.state==="active"?null:n("span",{class:`pill ${Et(t)}`},Ke[t.state])))),s,n("div",{class:"layout"},$t(e),$))}async function Se(e){try{return await ne(`devices/${e.id}/config`)}catch(t){return te(t.message,!0),null}}async function Rt(e){let t=await Se(e);t&&ce(await Ae(t,`${t.server} · ${t.name}`),"Key copied")}async function Ht(e){let t=await Se(e);t&&Xe(t.filename,t.conf)}function We(e,t){if(/^\s*\[.+\]\s*$/.test(e))return n("span",{class:"conf-sec"},e);let r=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(e);if(!r)return document.createTextNode(e);let s=/^(\s*)(PrivateKey|PresharedKey)\b/.test(e);return n("span",{},n("span",{class:"conf-k"},r[1])," ",s&&!t?n("span",{class:"conf-mask"},"••••••••••••••••"):r[2])}function It(e){let t=!1,r=n("pre",{class:"conf"}),s=()=>r.replaceChildren(...e.conf.split(` +`).flatMap((p,k)=>k?[` +`,We(p,t)]:[We(p,t)])),u=n("button",{class:"btn small",onclick:p=>{p.preventDefault(),t=!t,u.replaceChildren(O(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),s()}},O("key"),n("span",{},"Show key"));return s(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},e.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>Xe(e.filename,e.conf)},O("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},O("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),u,n("button",{class:"btn small",onclick:p=>{p.preventDefault(),ce(e.conf,"Configuration copied")}},O("copy"),n("span",{},"Copy"))),r))}async function ue(e,t,r){let s=r!=null?r:await Se(e);if(!s)return;let u=await Ae(s,`${s.server} · ${s.name}`),p=Ce(),k={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:u},O("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let H=n("div",{class:"qr"});return H.innerHTML=Je(s.conf),n("div",{class:"pane center"},H,n("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},u),n("button",{class:"btn small",onclick:()=>ce(u,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>It(s)},$=p?["app","qr","key","file"]:["qr","key","file"],E={app:"Open in app",qr:"QR code",key:"Key",file:"File"},B=n("div",{class:"tab-body"}),q=n("div",{class:"tabs",role:"tablist"}),J=H=>{q.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===H)),B.replaceChildren(k[H]())};for(let H of $)q.appendChild(n("button",{role:"tab","data-id":H,onclick:()=>J(H)},E[H]));J(t&&$.includes(t)?t:$[0]);let U=n("div",{class:"waiting"}),R=H=>{H!=null&&H.online?U.replaceChildren(n("span",{class:"ok"},`${e.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${we(H.handshake)}`)):U.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};R(e);let F=window.setInterval(async()=>{try{let H=await ne("state");S=H,R(H.person.devices.find(re=>re.id===e.id))}catch{}},5e3);fe(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,p?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",q,B,U),le=()=>{clearInterval(F),S&&de(S)}}function Ot(e){let t=n("input",{type:"text",value:e.name,maxlength:48,"aria-label":"Device name"}),r=n("button",{class:"btn primary block",type:"submit"},"Save");fe(`Rename ${e.name}`,null,n("form",{class:"stack gap",onsubmit:s=>{s.preventDefault(),Be(r,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"rename",name:t.value})).state,ee(),de(S),te("Renamed")}catch(u){te(u.message,!0)}})}},t,r)),setTimeout(()=>t.select(),50)}function Kt(e,t){let r=t.here===e.id;fe(`New keys for ${e.name}?`,null,n("p",{class:"muted"},r?"This device is connected through the configuration it has now: it disconnects a few seconds after you confirm. Import the new configuration that opens next.":"Its current configuration stops working. Set the device up again with the new one that opens next."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn primary block",onclick:s=>Be(s.currentTarget,async()=>{try{let u=await ne(`devices/${e.id}`,{action:"rotate"});S=u.state,de(S),await ue(e,void 0,u.config)}catch(u){te(u.message,!0)}})},"New keys")))}function Ut(e){fe(`Remove ${e.name}?`,null,n("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn danger-solid block",onclick:t=>Be(t.currentTarget,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"delete"})).state,ee(),de(S),te("Device removed")}catch(r){te(r.message,!0)}})},"Remove")))}var V=navigator.userAgent,rt=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function _e(){return rt||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var Ft=[[/^SM-S93/,"Galaxy S25"],[/^SM-S92/,"Galaxy S24"],[/^SM-S91/,"Galaxy S23"],[/^SM-S90/,"Galaxy S22"],[/^SM-G99/,"Galaxy S21"],[/^SM-F9/,"Galaxy Z Fold"],[/^SM-F7/,"Galaxy Z Flip"],[/^SM-A5/,"Galaxy A5x"],[/^SM-A3/,"Galaxy A3x"],[/^SM-X/,"Galaxy Tab"]],Le="",Gt=(async()=>{var t;let e=navigator.userAgentData;if(!e||!/Android/.test(V))return"";try{let r=((t=(await e.getHighEntropyValues(["model"])).model)!=null?t:"").trim();if(!r||r==="K")return"";let s=Ft.find(([u])=>u.test(r));Le=s?`${s[1]} (${r})`:/^SM-/.test(r)?`Galaxy ${r}`:r}catch{}return Le})();function qt(e){return/iPhone/.test(V)?"iPhone":rt?"iPad":/Android/.test(V)?Le||(e==="tablet"?"Android tablet":"Android phone"):/CrOS/.test(V)?"Chromebook":/Mac OS X/.test(V)?"Mac":/Windows/.test(V)?"Windows PC":/Linux/.test(V)?"Linux PC":ge[e]}function Vt(){if(!S)return;let e=_e(),t=new Set(S.person.devices.map(E=>E.name.toLowerCase())),r=E=>{let B=E===_e()?qt(E):ge[E];if(!t.has(B.toLowerCase()))return B;for(let q=2;q<20;q++)if(!t.has(`${B} ${q}`.toLowerCase()))return`${B} ${q}`;return B},s=n("input",{type:"text",value:r(e),maxlength:48,"aria-label":"Device name",required:!0}),u=!1;s.addEventListener("input",()=>u=!0),Gt.then(()=>{!u&&e===_e()&&(s.value=r(e))});let p=n("div",{class:"kinds"},S.kinds.map(E=>n("button",{type:"button",class:`kind${E===e?" on":""}`,"data-k":E,onclick:()=>{e=E,p.querySelectorAll(".kind").forEach(B=>B.classList.toggle("on",B.dataset.k===E)),u||(s.value=r(E))}},O(E),n("span",{},ge[E])))),k=n("p",{class:"err"}),$=n("button",{class:"btn primary block",type:"submit"},"Create connection");fe("Add a device",`${S.person.device_limit-S.person.devices.length} of ${S.person.device_limit} slots free`,n("form",{class:"add",onsubmit:async E=>{E.preventDefault(),$.disabled=!0,k.textContent="";try{let B=await ne("devices",{name:s.value.trim(),kind:e});S=B.state;let q=B.state.person.devices.find(J=>J.id===B.id);await ue(q,void 0,B.config)}catch(B){k.textContent=B.message,$.disabled=!1}}},n("label",{class:"lbl"},"What is it?"),p,n("label",{class:"lbl"},"Name"),s,k,$))}async function at(){try{S=await ne("state"),document.title=`${S.person.name} · ${S.title}`,!oe&&!X&&de(S)}catch(e){let t=e;t.status===404||t.status===401?(S=null,tt()):S||$e(n("div",{class:"card"},n("p",{},t.message)))}}function Yt(){clearInterval(Qe),Qe=window.setInterval(()=>{S&&document.visibilityState==="visible"&&at()},15e3)}!me||!Tt?tt():(at(),Yt());})(); diff --git a/package/luci-app-dawnline/root/usr/share/dawnline/portal/www/cgi-bin/portal b/package/luci-app-dawnline/root/usr/share/dawnline/portal/www/cgi-bin/portal index 5b163bb..2a43f36 100755 --- a/package/luci-app-dawnline/root/usr/share/dawnline/portal/www/cgi-bin/portal +++ b/package/luci-app-dawnline/root/usr/share/dawnline/portal/www/cgi-bin/portal @@ -1,368 +1,21 @@ #!/usr/bin/ucode -// Dawnline personal portal (CGI behind a dedicated uhttpd instance). -// -// GET / the app shell ( = three words, the personal link) -// GET //assets/ its script, styles, fonts -// GET //api/state -// POST //api/devices { name, kind, public_key? } -// GET //api/devices//config -// POST //api/devices/ { action: rename|delete, name? } -// -// The personal link is the key: every request carries its code, there are -// no sessions. Without a valid code every path answers the same bare 404 — -// the root, a person's link, the API and the assets alike — so nothing tells -// a scanner there is a portal here. Wrong codes are rate-limited per IP -// (blocked addresses get the same 404 even with the right code). -// Regenerating the code in LuCI locks the old link out at once. POST bodies -// must be JSON from the same origin; Referrer-Policy keeps the code out of -// other sites' logs. -// -// The portal can only manage the person's own devices within their limit. +// Dawnline personal portal as a CGI script: the request handling itself is +// dawnline.portal. 'use strict'; -import { stdin, stat, unlink, readfile } from 'fs'; -import { - read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, sh_bg, VERSION, RUN_DIR, DATA_DIR -} from 'dawnline.util'; -import * as core from 'dawnline.core'; -import * as live from 'dawnline.live'; -import * as apply from 'dawnline.apply'; -import * as view from 'dawnline.view'; +import { stdin } from 'fs'; +import { serve } from 'dawnline.portal'; -const RATE = `${RUN_DIR}/portal-rate.json`; -const ASSETS = '/usr/share/dawnline/portal/assets'; -const TYPES = { js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml', woff2: 'font/woff2' }; -const FAIL_LIMIT = 8; -const FAIL_WINDOW = 900; +let env = {}; +for (let k in [ 'REQUEST_METHOD', 'REQUEST_URI', 'REMOTE_ADDR', 'HTTPS', 'CONTENT_LENGTH', 'CONTENT_TYPE', + 'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT', + // The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's). + 'HTTP_CF_CONNECTING_IP' ]) + env[k] = getenv(k); -const SECURITY_HEADERS = { - 'X-Content-Type-Options': 'nosniff', - 'Referrer-Policy': 'no-referrer', - 'X-Frame-Options': 'DENY', - 'Cache-Control': 'no-store', - 'Strict-Transport-Security': 'max-age=31536000', -}; - -function headers(status, extra) { - let h = `Status: ${status}\r\n`; - for (let k, v in { ...SECURITY_HEADERS, ...(extra ?? {}) }) - h += `${k}: ${v}\r\n`; - print(h + '\r\n'); -} - -function send_json(status, obj, extra) { - headers(status, { 'Content-Type': 'application/json', ...(extra ?? {}) }); - print(sprintf('%J', obj)); - exit(0); -} - -function fail(status, msg) { - send_json(status, { error: msg }); -} - -function html_escape(s) { - return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); -} - -function page(status, base, title, code) { - // The build's time joins the version so every update busts the hour-long asset cache. - let q = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`; - headers(status, { - 'Content-Type': 'text/html; charset=utf-8', - 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " + - "connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'", - }); - print(` - - - - - - -${html_escape(title)} - - - - -
- - - -`); - exit(0); -} - -/* ---------- request ---------- */ - -const method = getenv('REQUEST_METHOD') ?? 'GET'; -const uri = getenv('REQUEST_URI') ?? '/'; -// Behind a Cloudflare-proxied hostname every request comes from Cloudflare, -// and uhttpd does not hand CF-Connecting-IP to CGI: all those visitors share -// one bucket with a higher limit (three-word codes can't be guessed anyway). -const peer = getenv('REMOTE_ADDR') ?? ''; -const via_cf = cloudflare_ip(peer); -const ip = via_cf ? 'cloudflare' : peer; -const fail_limit = via_cf ? FAIL_LIMIT * 25 : FAIL_LIMIT; -const qpos = index(uri, '?'); -const path = qpos >= 0 ? substr(uri, 0, qpos) : uri; -const query = qpos >= 0 ? substr(uri, qpos + 1) : ''; -const segs = filter(split(path, '/'), (s) => s != ''); - -function query_param(name) { - for (let kv in split(query, '&')) { - let eq = index(kv, '='); - if (eq > 0 && substr(kv, 0, eq) == name) - return substr(kv, eq + 1); - } - return null; -} - -function body() { - let len = +(getenv('CONTENT_LENGTH') ?? 0); - if (len <= 0) - return {}; - if (len > 8192) - fail('413 Payload Too Large', 'Request too large.'); - let raw = stdin.read(len); - try { - let j = json(raw); - return type(j) == 'object' ? j : {}; - } - catch (e) { - fail('400 Bad Request', 'Invalid JSON.'); - } -} - -/* ---------- rate limiting ---------- */ - -function rate_state() { - let st = read_json(RATE, {}); - let now = time(); - for (let k, v in st) - if (now - v.first > FAIL_WINDOW) - delete st[k]; - return st; -} - -function rate_blocked() { - let v = rate_state()[ip]; - return v != null && v.count >= fail_limit; -} - -function rate_fail() { - let l = lock('portal-rate'); - let st = rate_state(); - let v = st[ip] ?? { first: time(), count: 0 }; - v.count++; - st[ip] = v; - ensure_dir(RUN_DIR); - write_json(RATE, st, 0o600); - unlock(l); - if (v.count == fail_limit) - live.add_event({ type: 'portal_blocked', detail: ip }); -} - -// Older versions kept sign-in sessions on flash; they mean nothing now. -if (stat(`${DATA_DIR}/sessions.json`)) - unlink(`${DATA_DIR}/sessions.json`); - -/* ---------- routing ---------- */ - -let m = core.load(); -const redirect = m.settings.portal_redirect; - -/** - * The one answer for anything without a valid code: a bare 404, or the redirect from Settings. - * Files and LuCI's own paths always get the 404: at home this script is LuCI's error page, and a - * missing script must not turn into someone's website. - */ -function not_found() { - let parts = split(split(uri, '?')[0], '/'); - let file = match(uri, /^\/(luci-static|cgi-bin|ubus)(\/|$)/) || match(parts[length(parts) - 1], /\./); - if (redirect && !file) { - headers('302 Found', { 'Location': redirect, 'Cache-Control': 'no-store', 'Content-Type': 'text/plain' }); - print('Moved\n'); - } - else { - headers('404 Not Found', { 'Content-Type': 'text/plain' }); - print('Not found\n'); - } - exit(0); -} - -const title = m.settings.portal_title || 'Dawnline'; - -// Plain HTTP only for an IP address chosen in Settings (no certificate exists -// for it); names, and LuCI's web server at home, stay HTTPS-only. -if (getenv('HTTPS') != 'on') { - let h = getenv('HTTP_HOST') ?? ''; - h = match(h, /^\[/) ? h : split(h, ':')[0]; - if (ip2int(h) == null || index(core.portal_hosts(m), h) < 0) - not_found(); -} -// The link is /[/assets/…|/api/…]: the code is the address. -if (length(segs) < 1 || !match(segs[0], core.WORD_CODE)) - not_found(); -const code = segs[0]; -const base = `/${code}`; -const rest = slice(segs, 1); -let person = null; -for (let id, p in m.people) - if (p.code == code) - person = p; - -// A wrong code or a blocked address: indistinguishable from a path that does -// not exist. Only well-formed guesses count towards the limit. -if (rate_blocked()) - not_found(); -if (person == null) { - rate_fail(); - not_found(); -} - -const person_id = person.id; - -// The app shell; it reads the code from its own URL and sends it along. -if (length(rest) == 0 && method == 'GET') - page('200 OK', base, title, code); - -// Script, styles, icon and fonts (kept outside the web root). -if (rest[0] == 'assets' && length(rest) == 2 && method == 'GET') { - let name = rest[1]; - let ext = match(name, /^[a-z0-9-]+\.(js|css|svg|woff2)$/)?.[1]; - let data = ext ? readfile(`${ASSETS}/${name}`) : null; - if (data == null) - not_found(); - headers('200 OK', { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=3600' }); - print(data); - exit(0); -} - -if (rest[0] != 'api') - not_found(); - -// CSRF: only same-origin JSON requests (uhttpd passes no custom headers to -// CGI; a cross-site page cannot send application/json without CORS, and it -// would need the code anyway). -if (method == 'POST') { - let origin = getenv('HTTP_ORIGIN'); - if (!match(getenv('CONTENT_TYPE') ?? '', /^application\/json/) || - (origin != null && origin != `${getenv('HTTPS') == 'on' ? 'https' : 'http'}://${getenv('HTTP_HOST')}`)) - fail('403 Forbidden', 'Cross-site request refused.'); -} -else if (method != 'GET') - fail('405 Method Not Allowed', 'Method not allowed.'); - -const api = slice(rest, 1); - -function state() { - let usage = core.load_usage(); - let dmp = live.dump(); - let v = view.person_view(m, person, usage, dmp, view.states(m, usage)); - let srv = m.servers[person.server]; - // The device this page was opened from, when it came through the tunnel. - let here = null; - for (let id, d in m.devices) - if (d.person == person.id && d.address == peer) - here = id; - return { - title, - person: v, - here, - server: { name: srv?.name, endpoint: core.endpoint_host(m, srv), device_mesh: !!srv?.device_mesh }, - can_add: length(person.devices) < person.device_limit, - kinds: core.KINDS, - version: VERSION, - }; -} - -function own_device(id) { - let d = m.devices[id]; - if (!d || d.person != person.id) - fail('404 Not Found', 'Device not found.'); - return d; -} - -if (api[0] == 'state' && method == 'GET') - send_json('200 OK', state()); - -if (api[0] == 'devices' && length(api) == 1 && method == 'POST') { - let b = body(); - let l = lock('config'); - let id; - try { - let c = core.open_cursor(); - m = core.load(c); - person = m.people[person_id]; - id = core.create_device(c, m, person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key || null }); - c.commit('dawnline'); - system('chmod 600 /etc/config/dawnline'); - } - catch (e) { - unlock(l); - fail('400 Bad Request', e.message); - } - unlock(l); - apply.sync(); - m = core.load(); - person = m.people[person_id]; - live.add_event({ type: 'device_added', person: person.id, device: id, detail: m.devices[id].name, by: 'portal' }); - core.mark_issued(m, id); - send_json('200 OK', { id, config: core.client_config(m, m.devices[id]), state: state() }); -} - -if (api[0] == 'devices' && length(api) == 3 && api[2] == 'config' && method == 'GET') { - let d = own_device(api[1]); - core.mark_issued(m, d.id); - send_json('200 OK', core.client_config(m, d)); -} - -if (api[0] == 'devices' && length(api) == 2 && method == 'POST') { - own_device(api[1]); - let b = body(); - let l = lock('config'); - try { - let c = core.open_cursor(); - m = core.load(c); - if (b.action == 'rename') - core.rename_device(c, m, api[1], b.name); - else if (b.action == 'rotate') { - if (m.devices[api[1]].disabled) - die('The admin has turned this device off.'); - core.rotate_device(c, m, api[1]); - } - else if (b.action == 'delete') { - let d = m.devices[api[1]]; - core.delete_device(c, m, api[1]); - live.add_event({ type: 'device_removed', person: person.id, device: api[1], detail: d.name, dname: d.name, dkind: d.kind, by: 'portal' }); - } - else - die('Unknown action.'); - c.commit('dawnline'); - system('chmod 600 /etc/config/dawnline'); - } - catch (e) { - unlock(l); - fail('400 Bad Request', e.message); - } - unlock(l); - if (b.action == 'delete') - apply.sync(); - m = core.load(); - person = m.people[person_id]; - if (b.action == 'rotate') { - let d = m.devices[api[1]]; - live.add_event({ type: 'device_keys', person: person.id, device: d.id, detail: d.name, by: 'portal' }); - // The device this page came through would lose its tunnel before the - // answer gets out: load the new key a moment after answering. - if (d.address == peer) - sh_bg('sleep 3; /usr/bin/dawnline sync'); - else - apply.sync(); - core.mark_issued(m, d.id); - send_json('200 OK', { ok: true, config: core.client_config(m, d), state: state() }); - } - send_json('200 OK', { ok: true, state: state() }); -} - -fail('404 Not Found', 'Not found.'); +serve({ + env, + headers: {}, + read: (n) => stdin.read(n), + write: (s) => print(s), +}); diff --git a/package/luci-app-dawnline/root/usr/share/luci/menu.d/luci-app-dawnline.json b/package/luci-app-dawnline/root/usr/share/luci/menu.d/luci-app-dawnline.json index ff6d080..d7f428c 100644 --- a/package/luci-app-dawnline/root/usr/share/luci/menu.d/luci-app-dawnline.json +++ b/package/luci-app-dawnline/root/usr/share/luci/menu.d/luci-app-dawnline.json @@ -70,7 +70,7 @@ } }, "admin/network/dawnline/updates": { - "title": "Updates", + "title": "Components", "order": 70, "action": { "type": "view", diff --git a/package/luci-app-dawnline/root/usr/share/rpcd/acl.d/luci-app-dawnline.json b/package/luci-app-dawnline/root/usr/share/rpcd/acl.d/luci-app-dawnline.json index bfef708..84d45e0 100644 --- a/package/luci-app-dawnline/root/usr/share/rpcd/acl.d/luci-app-dawnline.json +++ b/package/luci-app-dawnline/root/usr/share/rpcd/acl.d/luci-app-dawnline.json @@ -10,27 +10,23 @@ "service_log", "backup_list", "updates_status", + "updates_releases", + "updates_notes", + "updates_changes", "person_usage", "settings_get", + "portal_info", "interfaces", "events" ] - }, - "uci": [ - "dawnline", - "network", - "firewall" - ] + } }, "write": { "ubus": { "luci.dawnline": [ "*" ] - }, - "uci": [ - "dawnline" - ] + } } } } diff --git a/package/luci-app-dawnline/root/usr/share/rpcd/ucode/luci.dawnline b/package/luci-app-dawnline/root/usr/share/rpcd/ucode/luci.dawnline index 83ffc76..8407989 100644 --- a/package/luci-app-dawnline/root/usr/share/rpcd/ucode/luci.dawnline +++ b/package/luci-app-dawnline/root/usr/share/rpcd/ucode/luci.dawnline @@ -1,1348 +1,28 @@ // Dawnline — rpcd backend for the LuCI admin UI (ubus object luci.dawnline). +// +// The methods live in dawnline.rpc.* by page: status (Overview, activity), +// servers, people (and their devices), settings, home (services, circles), +// maint (Diagnostics, backups, removal) and updates (Components). Each module +// exports `methods` as { name: { args, call } }; read-only users get the +// methods listed under "read" in acl.d/luci-app-dawnline.json. 'use strict'; -import { cursor } from 'uci'; -import { readfile, stat } from 'fs'; -import { - q, sh, sh_out, sh_bg, ensure_dir, read_json, write_json, parse_cidr, cidr_str, cidr_overlaps, int2ip, - ip2int, valid_host, rand_int, rand_hex, lock, unlock, uniq, slog_clear, admin_log, VERSION, RUN_DIR, DATA_DIR -} from 'dawnline.util'; -import * as core from 'dawnline.core'; -import * as live from 'dawnline.live'; -import * as apply from 'dawnline.apply'; -import * as view from 'dawnline.view'; -import * as ops from 'dawnline.ops'; -import * as geo from 'dawnline.geo'; -import * as net from 'dawnline.net'; -import * as loop from 'dawnline.loop'; -import * as watchdog from 'dawnline.watchdog'; -import * as access from 'dawnline.access'; - -function wrap(fn) { - return function(req) { - try { - let r = fn(req.args ?? {}); - return type(r) == 'object' ? r : { result: r }; - } - catch (e) { - return { error: e.message ?? `${e}` }; - } - }; -} - -/** Commit the dawnline config and push runtime state. */ -function commit(c, full) { - c.commit('dawnline'); - system('chmod 600 /etc/config/dawnline'); - return full ? apply.apply() : apply.sync(); -} - -const METHODS = [ 'off', 'standard', 'strong', 'max' ]; - -/** A disguise method the installed AmneziaWG can run. */ -function check_method(name) { - if (index(METHODS, name) < 0) - die('Unknown disguise method.'); - if (name == 'max' && !core.awg_caps().v3) - die('Maximum needs AmneziaWG 3.1 on the router (kmod-amneziawg, amneziawg-tools 3.1).'); - return name; -} - -/** Days of history a caller may ask for: 1–400, default 30. */ -function clamp_days(v) { - let n = +(v ?? 30); - return n >= 1 ? (n > 400 ? 400 : n) : 30; -} - -function str(v) { - return v == null ? '' : trim(`${v}`); -} - -/* ---------- map ---------- */ - -/** Router location plus one point per (device, recent client address). */ -function geo_view(m, usage, dmp) { - if (!m.settings.geo_enabled) - return { enabled: false, home: null, points: [] }; - let cache = geo.load(); - let points = []; - let now = time(); - for (let id, d in m.devices) { - let rec = usage.devices?.[id]; - let peer = dmp.peers[d.public_key]; - let cur = live.endpoint_ip(peer?.endpoint); - let online = !!(peer && peer.handshake > 0 && now - peer.handshake < live.ONLINE_WINDOW); - for (let ip, ts in rec?.ips ?? {}) { - // Local (LAN / CGNAT) client addresses are not shown on the map. - let pl = geo.is_public(ip) ? geo.place(cache, ip) : null; - if (!pl) - continue; - push(points, { - person: d.person, device: id, ip, ts, - online: online && ip == cur, - lat: pl.lat, lon: pl.lon, city: pl.city, country: pl.country, cc: pl.cc, - asn: pl.asn ?? 0, org: pl.org ?? '', - }); - } - } - let h = cache.home; - return { - enabled: true, - provider: m.settings.geo_provider, - cached: length(keys(cache.ips)), - home: (h && h.lat != null) ? { lat: h.lat, lon: h.lon, city: h.city, country: h.country, cc: h.cc, asn: h.asn ?? 0, org: h.org ?? '' } : null, - points, - }; -} - -/* ---------- status ---------- */ - -/** Older connections from home get the DHCP name their address has now. */ -function with_hosts(ev) { - let names = null; - for (let e in ev) - if ((e.type == 'connect' || e.type == 'roam') && !e.hosts) { - let h = net.event_hosts(e, names ??= net.lan_names()); - if (h) - e.hosts = h; - } - return ev; -} - -function status(a) { - let m = core.load(); - let usage = core.load_usage(); - let dmp = live.dump(); - let states = view.states(m, usage); - - let servers = []; - let rates = read_json(`${RUN_DIR}/rate.json`, {}); - let prates = read_json(`${RUN_DIR}/rate_people.json`, {}); - for (let id, srv in m.servers) { - let st = live.iface_status(srv.ifname); - let online = 0, peers = 0; - for (let k, p in dmp.peers) - if (p.ifname == srv.ifname) { - peers++; - if (p.handshake > 0 && time() - p.handshake < live.ONLINE_WINDOW) - online++; - } - push(servers, { - id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet, - endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled, - lan_like: srv.lan_like, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns, - address: core.server_address(srv), up: !!st?.up, uptime: st?.uptime ?? 0, - // Home networks (interfaces) for the per-person picker. - home: map(net.server_net(srv).home, (h) => ({ dev: h.dev, nets: h.nets })), - peers, online, obf: srv.obf, - // Bytes per second, one point a minute: [ts, rx, tx] (rx = from devices). - rate: rates[id] ?? [], - // Daily traffic of the people on this server (its Overview chart). - series: live.series(map(filter(keys(m.people), (pid) => m.people[pid].server == id), (pid) => usage.people?.[pid]), clamp_days(a.days)), - }); - } - - let people = []; - for (let id, p in m.people) { - let pv = view.person_view(m, p, usage, dmp, states, { admin: true }); - pv.rate = type(prates[p.id]?.[0]) == 'array' ? prates[p.id] : []; - push(people, pv); - } - people = sort(people, (a, b) => (b.online - a.online) || (b.last_seen - a.last_seen) || (a.name < b.name ? -1 : 1)); - - let totals = { people: length(people), devices: 0, online: 0, active: 0 }; - for (let p in people) { - totals.devices += length(p.devices); - totals.online += p.online; - if (p.state == 'active') - totals.active++; - } - let recs = values(usage.people ?? {}); - let day = live.series(recs, 1)[0]; - totals.today = [ day.rx, day.tx ]; - let mon = [ 0, 0 ]; - for (let r in recs) { - let v = live.month(r); - mon[0] += v[0]; - mon[1] += v[1]; - } - totals.month = mon; - - let events = live.load_events(); - let s = m.settings; - return { - geo: geo_view(m, usage, dmp), - version: VERSION, - now: time(), - hostname: trim(readfile('/proc/sys/kernel/hostname') ?? ''), - settings: { - portal_enabled: s.portal_enabled, portal_port: s.portal_port, portal_host: s.portal_host, - portal_443: s.portal_443, portal_public_port: core.portal_public_port(m), - paused_all: s.paused_all, default_device_limit: s.default_device_limit, domain: s.domain, - hostnames: s.hostnames, geo_enabled: s.geo_enabled, home_dns_fallback: s.home_dns_fallback, - }, - servers, - people, - services: values(m.services), - circles: values(m.circles), - totals, - series: live.series(recs, clamp_days(a.days)), - events: with_hosts(slice(events, length(events) > 60 ? length(events) - 60 : 0)), - like_home: loop.status(), - awg: core.awg_caps(), - }; -} - -/* ---------- setup ---------- */ - -function free_port(m) { - let used = {}; - let nc = cursor(); - nc.load('network'); - nc.foreach('network', 'interface', (s) => { - if (s.listen_port) - used[+s.listen_port] = true; - }); - for (let id, srv in m.servers) - used[srv.port] = true; - for (let i = 0; i < 50; i++) { - let p = rand_int(40000, 60000); - if (!used[p]) - return p; - } - return 51830; -} - -function free_subnet(taken) { - for (let i = 0; i < 200; i++) { - let cand = parse_cidr(sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250))); - let bad = false; - for (let t in taken) { - let tc = parse_cidr(t); - if (tc && cidr_overlaps(cand, tc)) { - bad = true; - break; - } - } - if (!bad) - return cidr_str(cand); - } - return '10.77.0.0/24'; -} - -function free_portal_port(cur) { - for (let p in uniq([ cur || 8443, 8443, 9443, 10443, 7443, 4443 ])) - if (!length(ops.tcp_port_owners(p))) - return p; - return 9443; -} - -function free_ifname(m) { - let nc = cursor(); - nc.load('network'); - for (let i = 0; i < 10; i++) { - let n = `dawn${i}`; - if (nc.get('network', n) == null && !m.servers[n]) - return n; - } - return 'dawnx'; -} - -/** A free server id: home, then server2, server3, … (never a person, device or service id). */ -function free_server_id(m) { - let taken = (id) => m.servers[id] || m.people[id] || m.devices[id] || m.services[id] || index([ 'settings', 'api', 'assets', 'cgi-bin' ], id) >= 0; - if (!taken('home')) - return 'home'; - for (let n = 2; ; n++) - if (!taken(`server${n}`)) - return `server${n}`; -} - -function setup_defaults(a) { - let m = core.load(); - let taken = ops.used_subnets(null); - for (let id, s in m.servers) - push(taken, s.subnet); - let zones = []; - let fc = cursor(); - fc.load('firewall'); - fc.foreach('firewall', 'zone', (z) => push(zones, z.name)); - let host = m.settings.portal_host; - if (!host) { - // Prefer a DDNS name, then the WAN address. - let dc = cursor(); - dc.load('ddns'); - dc.foreach('ddns', 'service', (s) => { - if (!host && s.lookup_host && s.enabled == '1') - host = s.lookup_host; - }); - if (!host) { - let acme = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1"); - if (acme) - host = acme; - } - if (!host) - host = live.iface_status('wan')?.['ipv4-address']?.[0]?.address ?? ''; - } - return { - id: free_server_id(m), - name: length(m.servers) ? `Server ${length(m.servers) + 1}` : 'Home', - ifname: free_ifname(m), - port: free_port(m), - subnet: free_subnet(taken), - endpoint: host, - mtu: 1380, - zones, - lan_zone: index(zones, 'lan') >= 0 ? 'lan' : zones[0], - wan_zone: index(zones, 'wan') >= 0 ? 'wan' : zones[1], - portal_port: free_portal_port(m.settings.portal_port), - awg: core.awg_caps(), - taken, - }; -} - -function server_create(a) { - let l = lock('config'); - try { - let c = core.open_cursor(); - let m = core.load(c); - let id = str(a.id) || 'home'; - // A UCI section name: a dash would make uci drop it silently. - if (!match(id, /^[a-z][a-z0-9_]{0,23}$/)) - die('Server ID may use lowercase letters, digits and underscores.'); - if (m.servers[id] || m.people[id] || id == 'settings' || id == 'api' || id == 'assets' || id == 'cgi-bin') - die(`"${id}" is already taken.`); - let nc = cursor(); - nc.load('network'); - let ifname = str(a.ifname) || free_ifname(m); - if (nc.get('network', ifname) != null) - die(`Network interface ${ifname} already exists.`); - - let srv = { - id, ifname, port: +a.port || free_port(m), subnet: str(a.subnet), endpoint: str(a.endpoint), - obf: core.obf_preset(check_method(a.preset || 'standard')), - }; - let pc = parse_cidr(srv.subnet); - if (pc) - srv.subnet = cidr_str(pc); - let taken = ops.used_subnets(null); - for (let k, s in m.servers) - push(taken, s.subnet); - let errs = core.server_errors(m, srv, taken); - if (length(errs)) - die(join(' ', errs)); - - let priv = core.genkey(), pub = core.pubkey(priv); - if (!pub) - die('Key generation failed (is amneziawg-tools installed?).'); - - c.set('dawnline', 'settings', 'settings'); - c.set('dawnline', id, 'server'); - c.set('dawnline', id, 'name', str(a.name) || 'Home'); - c.set('dawnline', id, 'ifname', ifname); - c.set('dawnline', id, 'port', `${srv.port}`); - c.set('dawnline', id, 'subnet', srv.subnet); - if (srv.endpoint) - c.set('dawnline', id, 'endpoint', srv.endpoint); - c.set('dawnline', id, 'mtu', `${+a.mtu || 1380}`); - c.set('dawnline', id, 'keepalive', '25'); - c.set('dawnline', id, 'private_key', priv); - c.set('dawnline', id, 'public_key', pub); - c.set('dawnline', id, 'preset', a.preset ?? 'standard'); - for (let k, v in srv.obf) - c.set('dawnline', id, k, v); - c.set('dawnline', id, 'lan_zone', str(a.lan_zone) || 'lan'); - c.set('dawnline', id, 'wan_zone', str(a.wan_zone) || 'wan'); - let snap = net.snapshot(true); - c.set('dawnline', id, 'auto_wan', '1'); - c.set('dawnline', id, 'auto_lan', '1'); - if (snap.wan) - c.set('dawnline', id, 'detected_wan', snap.wan); - if (snap.lan) - c.set('dawnline', id, 'detected_lan', snap.lan); - c.set('dawnline', id, 'lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1'); - c.set('dawnline', id, 'enabled', '1'); - - if (a.portal_enabled != null) { - c.set('dawnline', 'settings', 'portal_enabled', a.portal_enabled ? '1' : '0'); - let pp = +a.portal_port; - if (a.portal_enabled && (pp < 1 || pp > 65535)) - die('Portal port must be 1-65535.'); - if (a.portal_enabled && length(ops.tcp_port_owners(pp))) - die(`TCP ${pp} is already used by ${join(', ', ops.tcp_port_owners(pp))}. Choose another portal port.`); - if (pp) - c.set('dawnline', 'settings', 'portal_port', `${pp}`); - } - if (srv.endpoint && !c.get('dawnline', 'settings', 'portal_host') && valid_host(srv.endpoint)) - c.set('dawnline', 'settings', 'portal_host', srv.endpoint); - - c.commit('dawnline'); - system('chmod 600 /etc/config/dawnline'); - unlock(l); - l = null; - let r = apply.apply(); - system('/etc/init.d/dawnline enabled || /etc/init.d/dawnline enable'); - let made = core.load().servers[id]; - admin_log('awg', 'created', 'server', made?.name ?? id, made ? `port ${made.port}` : null); - sh_bg('/etc/init.d/dawnline restart'); - return { id, applied: r }; - } - catch (e) { - if (l) - unlock(l); - die(e.message); - } -} - -/** Interfaces card on the Server page: what exists, what is detected, what the server uses. */ -function interfaces_view(srv, snap) { - let sn = net.server_net(srv, snap); - let home = {}; - for (let h in sn.home) - home[h.dev] = h; - let devices = []; - for (let dev, d in snap.devices) - push(devices, { - ...d, - own: dev == srv.ifname, - home: !!home[dev], - auto: !!home[dev]?.auto, - }); - // Saved names that no longer exist still show, so they can be removed. - for (let h in sn.home) - if (h.missing) - push(devices, { name: h.dev, category: 'other', kind: 'other', missing: true, nets: [], addrs: [], members: [], home: true, auto: h.auto }); - let lan_only = 0; - for (let id, p in core.load().people) - if (p.server == srv.id && p.access == 'lan') - lan_only++; - return { - server: srv.id, - ifname: srv.ifname, - detected: { wan: snap.wan, lan: snap.lan }, - saved: { wan: srv.detected_wan, lan: srv.detected_lan }, - config: { auto_wan: srv.auto_wan, wan_device: srv.wan_device, auto_lan: srv.auto_lan, lan_devices: srv.lan_devices, lan_like: srv.lan_like, - device_mesh: srv.device_mesh, mesh: srv.mesh }, - like_home: loop.status(), - needs: ops.needs().home, - effective: sn, - zones: snap.zones, - devices, - lan_only, - }; -} - -function interfaces_get(a) { - let m = core.load(); - let srv = m.servers[a.id] ?? values(m.servers)[0]; - if (!srv) - die('No server yet.'); - return interfaces_view(srv, net.snapshot(true)); -} - -function server_interfaces(a) { - let c = core.open_cursor(); - let m = core.load(c); - let srv = m.servers[a.id]; - if (!srv) - die('Unknown server.'); - let snap = net.snapshot(true); - let auto_wan = a.auto_wan != false && a.auto_wan != '0'; - let auto_lan = a.auto_lan != false && a.auto_lan != '0'; - let wan_dev = trim(`${a.wan_device ?? ''}`); - if (!auto_wan) { - if (!snap.devices[wan_dev]) - die('Choose the interface that leads to the internet.'); - if (!snap.devices[wan_dev].zone) - die(`${wan_dev} is not in a firewall zone, so the server port cannot be opened on it.`); - } - let lans = []; - for (let d in (type(a.lan_devices) == 'array' ? a.lan_devices : [])) { - d = trim(`${d}`); - // Unknown names are kept only if they were saved before (interface down right now). - if (d == '' || d == srv.ifname || (!snap.devices[d] && index(srv.lan_devices, d) < 0)) - continue; - if (snap.devices[d]?.master) - die(`${d} is part of ${snap.devices[d].master}; choose ${snap.devices[d].master} instead.`); - if (d == (auto_wan ? snap.wan : wan_dev)) - die(`${d} is the WAN.`); - push(lans, d); - } - lans = uniq(lans); - if (a.lan_like != null) - c.set('dawnline', srv.id, 'lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1'); - let mesh = index(core.MESH, a.mesh) >= 0 ? a.mesh - : a.device_mesh == null ? srv.mesh : (a.device_mesh === false || a.device_mesh === '0' ? 'off' : 'all'); - c.set('dawnline', srv.id, 'mesh', mesh); - c.delete('dawnline', srv.id, 'device_mesh'); - c.set('dawnline', srv.id, 'auto_wan', auto_wan ? '1' : '0'); - c.set('dawnline', srv.id, 'auto_lan', auto_lan ? '1' : '0'); - if (auto_wan || wan_dev == '') - c.delete('dawnline', srv.id, 'wan_device'); - else - c.set('dawnline', srv.id, 'wan_device', wan_dev); - if (length(lans)) - c.set('dawnline', srv.id, 'lan_device', lans); - else - c.delete('dawnline', srv.id, 'lan_device'); - // Remember what was detected, as the fallback while an interface is down. - if (snap.wan) - c.set('dawnline', srv.id, 'detected_wan', snap.wan); - if (snap.lan) - c.set('dawnline', srv.id, 'detected_lan', snap.lan); - // Keep the legacy zone options in step (older code paths, health checks). - let m2 = core.load(c); - let sn = net.server_net(m2.servers[srv.id], snap); - if (sn.wan.zone) - c.set('dawnline', srv.id, 'wan_zone', sn.wan.zone); - if (length(sn.zones)) - c.set('dawnline', srv.id, 'lan_zone', sn.zones[0]); - c.commit('dawnline'); - system('chmod 600 /etc/config/dawnline'); - let before = join(',', net.server_net(srv, snap).nets); - // What the admin changed here: the networks, and/or whether devices reach each other. - let sig = (x) => { - let sn = net.server_net(x, snap); - return `${join(',', sn.nets)}|${sn.wan.dev}|${x.lan_like}`; - }; - let what = []; - if (sig(core.load(c).servers[srv.id]) != sig(srv)) - push(what, 'home network and internet path'); - if (mesh != srv.mesh) - push(what, { off: 'devices kept apart', all: 'devices reach each other', circles: 'devices reach each other in circles' }[mesh]); - if (length(what)) - admin_log('awg', 'changed', 'server', srv.name, join(', ', what)); - apply.apply(); - let m3 = core.load(); - let view = interfaces_view(m3.servers[srv.id], net.snapshot(true)); - view.nets_changed = before != join(',', view.effective.nets); - return view; -} - -/** Server settings from the General and Network tabs; applied at once. */ -function server_update(a) { - let c = core.open_cursor(); - let m = core.load(c); - let srv = m.servers[a.id]; - if (!srv) - die('Unknown server.'); - let v = a.values ?? {}; - let set = (k, val) => (val == null || val == '') ? c.delete('dawnline', srv.id, k) : c.set('dawnline', srv.id, k, val); - if (v.name != null) { - if (str(v.name) == '') - die('Name cannot be empty.'); - set('name', str(v.name)); - } - if (v.endpoint != null) { - if (str(v.endpoint) == '' || !valid_host(str(v.endpoint))) - die('Public address must be a hostname or IP address.'); - set('endpoint', str(v.endpoint)); - } - if (v.port != null) { - let n = +v.port; - if (!match(str(v.port), /^[0-9]+$/) || n < 1 || n > 65535) - die('UDP port must be 1-65535.'); - for (let id, o in m.servers) - if (id != srv.id && o.port == n) - die(`UDP ${n} is used by ${o.name}.`); - set('port', `${n}`); - } - if (v.enabled != null) - set('enabled', v.enabled === true || v.enabled == '1' ? '1' : '0'); - if (v.device_mesh != null && v.mesh == null) - v.mesh = v.device_mesh === true || v.device_mesh == '1' ? 'all' : 'off'; - if (v.mesh != null) { - if (index(core.MESH, v.mesh) < 0) - die('Unknown choice for devices reaching each other.'); - set('mesh', v.mesh); - set('device_mesh', null); - } - if (v.mtu != null) { - if (str(v.mtu) != '' && (!match(str(v.mtu), /^[0-9]+$/) || +v.mtu < 1280 || +v.mtu > 1500)) - die('MTU must be 1280-1500.'); - set('mtu', str(v.mtu)); - } - if (v.keepalive != null) { - if (str(v.keepalive) != '' && (!match(str(v.keepalive), /^[0-9]+$/) || +v.keepalive > 600)) - die('Keep-alive must be 0-600 seconds.'); - set('keepalive', str(v.keepalive)); - } - if (v.dns != null) { - let list = filter(map(type(v.dns) == 'array' ? v.dns : split(str(v.dns), /[ ,]+/), str), (x) => x != ''); - for (let d in list) - if (!match(d, /^[0-9]{1,3}(\.[0-9]{1,3}){3}$/) && !match(d, /^[0-9a-fA-F:]+$/)) - die(`${d} is not an IP address.`); - if (length(list)) - c.set('dawnline', srv.id, 'dns', list); - else - c.delete('dawnline', srv.id, 'dns'); - } - // For the log: what changed, in words. Turning on or off is its own line. - let labels = { name: 'name', endpoint: 'public address', port: 'port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS' }; - let what = []; - for (let k, label in labels) { - if (v[k] == null) - continue; - let was = k == 'dns' ? join(' ', srv.dns ?? []) : `${srv[k] ?? ''}`; - let now = k == 'dns' ? join(' ', type(v.dns) == 'array' ? v.dns : split(str(v.dns), /[ ,]+/)) : str(v[k]); - if (trim(was) != trim(now)) - push(what, label); - } - let on = v.enabled == null ? null : (v.enabled === true || v.enabled == '1'); - let mesh = v.mesh; - let name = v.name != null ? str(v.name) : srv.name; - let r = commit(c, true); - if (on != null && on != srv.enabled) - admin_log('awg', on ? 'turned on' : 'turned off', 'server', name); - if (length(what)) - admin_log('awg', 'changed', 'server', name, join(', ', what)); - if (mesh != null && mesh != srv.mesh) - admin_log('awg', 'changed', 'server', name, - { off: 'devices kept apart', all: 'devices reach each other', circles: 'devices reach each other in circles' }[mesh]); - return r; -} - -function server_obfuscation(a) { - let c = core.open_cursor(); - let m = core.load(c); - let srv = m.servers[a.id]; - if (!srv) - die('Unknown server.'); - let o = core.obf_preset(check_method(a.preset || 'standard')); - for (let k in core.OBF_KEYS) - c.delete('dawnline', a.id, k); - for (let k, v in o) - c.set('dawnline', a.id, k, v); - c.set('dawnline', a.id, 'preset', a.preset ?? 'standard'); - let r = commit(c, true); - admin_log('awg', 'changed', 'server', srv.name, `disguise: ${a.preset || 'standard'}`); - return r; -} - -function server_delete(a) { - let c = core.open_cursor(); - let m = core.load(c); - if (!m.servers[a.id]) - die('Unknown server.'); - ops.backup_create('pre-delete'); - let gone = 0; - for (let pid, p in m.people) - if (p.server == a.id) { - core.delete_person(c, m, pid); - gone++; - } - c.delete('dawnline', a.id); - let r = commit(c, true); - admin_log('awg', 'removed', 'server', m.servers[a.id].name, gone ? `with ${gone} ${gone == 1 ? 'person' : 'people'}` : null); - return r; -} - -/* ---------- people ---------- */ - -function person_create(a) { - let l = lock('config'); - try { - let c = core.open_cursor(); - let m = core.load(c); - let slug = core.create_person(c, m, { - name: str(a.name), slug: str(a.slug) || null, server: str(a.server) || null, access: a.access, - device_limit: a.device_limit, expires: str(a.expires), quota_gb: a.quota_gb, quota_period: a.quota_period, - }); - c.commit('dawnline'); - system('chmod 600 /etc/config/dawnline'); - unlock(l); - l = null; - let m2 = core.load(); - live.add_event({ type: 'person_added', person: slug, detail: m2.people[slug].name, by: 'admin' }); - return { id: slug, link: core.portal_url(m2, m2.people[slug]) }; - } - catch (e) { - if (l) - unlock(l); - die(e.message); - } -} - -function person_pause(a) { - let c = core.open_cursor(); - let m = core.load(c); - let p = m.people[a.id]; - if (!p) - die('Unknown person.'); - if (a.paused) - c.set('dawnline', a.id, 'paused', '1'); - else - c.delete('dawnline', a.id, 'paused'); - live.add_event({ type: a.paused ? 'paused' : 'resumed', person: a.id, by: 'admin' }); - return commit(c); -} - -function person_regen(a) { - let c = core.open_cursor(); - let m = core.load(c); - let p = m.people[a.id]; - if (!p) - die('Unknown person.'); - c.set('dawnline', a.id, 'code', core.new_code()); - c.commit('dawnline'); - live.add_event({ type: 'link_changed', person: a.id, by: 'admin' }); - // The old link stops working at once: every portal request carries the code. - let m2 = core.load(); - return { link: core.portal_url(m2, m2.people[a.id]) }; -} - -function person_delete(a) { - let c = core.open_cursor(); - let m = core.load(c); - let name = m.people[a.id]?.name; - core.delete_person(c, m, a.id); - live.add_event({ type: 'person_removed', person: a.id, detail: name, pname: name, by: 'admin' }); - return commit(c); -} - -function pause_all(a) { - let c = core.open_cursor(); - c.set('dawnline', 'settings', 'settings'); - c.set('dawnline', 'settings', 'paused_all', a.paused ? '1' : '0'); - live.add_event({ type: a.paused ? 'paused_all' : 'resumed_all', by: 'admin' }); - return commit(c); -} - -/* ---------- devices ---------- */ - -function device_create(a) { - let l = lock('config'); - try { - let c = core.open_cursor(); - let m = core.load(c); - let id = core.create_device(c, m, a.person, a.name, a.kind, { by: 'admin', force: true }); - c.commit('dawnline'); - system('chmod 600 /etc/config/dawnline'); - unlock(l); - l = null; - apply.sync(); - live.add_event({ type: 'device_added', person: a.person, device: id, detail: a.name, by: 'admin' }); - let m2 = core.load(); - core.mark_issued(m2, id); - return { id, config: core.client_config(m2, m2.devices[id]) }; - } - catch (e) { - if (l) - unlock(l); - die(e.message); - } -} - -function device_config(a) { - let m = core.load(); - let d = m.devices[a.id]; - if (!d) - die('Unknown device.'); - core.mark_issued(m, d.id); - return core.client_config(m, d); -} - -function device_update(a) { - let c = core.open_cursor(); - let m = core.load(c); - let d = m.devices[a.id]; - if (!d) - die('Unknown device.'); - if (a.name != null && a.name != d.name) - core.rename_device(c, m, a.id, a.name); - if (a.disabled != null) { - if (a.disabled) - c.set('dawnline', a.id, 'disabled', '1'); - else - c.delete('dawnline', a.id, 'disabled'); - } - let r = commit(c); - if (a.disabled != null && !!a.disabled != !!d.disabled) - live.add_event({ type: 'device_changed', person: d.person, device: a.id, detail: a.disabled ? 'turned off' : 'turned on', by: 'admin' }); - else if (a.name != null && a.name != d.name) - live.add_event({ type: 'device_changed', person: d.person, device: a.id, detail: `renamed from ${d.name}`, by: 'admin' }); - return r; -} - -function device_delete(a) { - let c = core.open_cursor(); - let m = core.load(c); - let d = m.devices[a.id]; - core.delete_device(c, m, a.id); - live.add_event({ type: 'device_removed', person: d?.person, device: a.id, detail: d?.name, dname: d?.name, dkind: d?.kind, by: 'admin' }); - return commit(c); -} - -function device_rotate(a) { - let c = core.open_cursor(); - let m = core.load(c); - core.rotate_device(c, m, a.id); - commit(c); - live.add_event({ type: 'device_keys', person: m.devices[a.id]?.person, device: a.id, detail: m.devices[a.id]?.name, by: 'admin' }); - let m2 = core.load(); - core.mark_issued(m2, a.id); - return core.client_config(m2, m2.devices[a.id]); -} - -/* ---------- misc ---------- */ - -function person_usage(a) { - let usage = core.load_usage(); - let m = core.load(); - let p = m.people[a.id]; - if (!p) - die('Unknown person.'); - let devs = {}; - for (let d in p.devices) - devs[d] = live.series([ usage.devices?.[d] ], clamp_days(a.days)); - return { person: live.series([ usage.people?.[a.id] ], clamp_days(a.days)), devices: devs }; -} - -function updates_status(a) { - let m = core.load(); - let rel = {}; - for (let line in split(readfile('/etc/openwrt_release') ?? '', '\n')) { - let m = match(line, /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/); - if (m) - rel[lc(m[1])] = m[2]; - } - return { - version: VERSION, - firmware: { version: rel.release ?? '', target: rel.target ?? '', arch: rel.arch ?? '' }, - portal: m.settings.portal_enabled, - home: length(filter(values(m.servers), (x) => x.lan_like)) > 0, - needs: ops.needs(), - check: read_json(`${RUN_DIR}/update-check.json`, null), - job: read_json(`${RUN_DIR}/update-job.json`, null), - }; -} - -function updates_run(a) { - let what = a.what ?? 'check'; - // check | app | all | amneziawg[:slava|grey[:ru]] | pkgs: (the updater checks names against its list) - if (length(what) > 400 || !match(what, /^(check|app|all|amneziawg(:(slava|grey)(:ru)?)?|pkgs:[a-z0-9][a-z0-9.+,-]*)$/)) - die('Unknown update target.'); - let job = read_json(`${RUN_DIR}/update-job.json`, null); - if (job?.state == 'running' && time() - (job.started ?? 0) < 600) - die('An update is already running.'); - ensure_dir(RUN_DIR); - system(`start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- ${what == 'check' ? 'check' : 'install ' + what}`); - return { started: true }; -} - - -/* ---------- immediate edits ---------- */ - -function person_update(a) { - let l = lock('config'); - try { - let c = core.open_cursor(); - let m = core.load(c); - let fields = {}; - for (let k in [ 'name', 'access', 'device_limit', 'expires', 'expire_action', 'expire_warn', 'quota_gb', 'quota_period', - 'bonus_gb', 'hours', 'note', 'dns_mode' ]) - if (a[k] != null) - fields[k] = a[k]; - if (a.paused != null) - fields.paused = a.paused; - if (type(a.services) == 'array') - fields.services = a.services; - if (a.circle != null) - fields.circle = a.circle; - if (type(a.home_nets) == 'array') - fields.home_nets = a.home_nets; - let before = m.people[a.id]; - core.update_person(c, m, a.id, fields); - c.commit('dawnline'); - system('chmod 600 /etc/config/dawnline'); - unlock(l); - l = null; - let changes = join(', ', filter(keys(fields), (k) => k != 'note')); - if (changes) - live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120); - // Access changes affect the nft sets and client AllowedIPs. - apply.sync(); - let m2 = core.load(); - let u = core.load_usage(); - return { person: view.person_view(m2, m2.people[a.id], u, live.dump(), view.states(m2, u), { admin: true }), was: before?.access }; - } - catch (e) { - if (l) - unlock(l); - die(e.message); - } -} - -const SETTING_KEYS = [ 'portal_enabled', 'portal_host', 'portal_alt', 'portal_port', 'portal_443', 'portal_title', 'portal_redirect', 'portal_cert', 'portal_key', - 'default_device_limit', 'hostnames', 'domain', 'geo_enabled', 'geo_provider', 'log_connections', 'watchdog', - 'log_keep_days', 'log_max', 'log_persist', 'usage_keep_days', 'usage_keep_months', 'home_dns_fallback' ]; - -function file_size(path) { - return stat(path)?.size ?? 0; -} - -/** What the log and traffic history hold right now (Settings → Logs & history). */ -function logs_info(m) { - let ev = live.load_events(); - let pol = live.policy(m.settings.retention); - let by = {}; - for (let cat in live.CATEGORIES) - by[cat] = 0; - for (let e in ev) - by[live.category_of(e.type)]++; - let usage = core.load_usage(); - let days = {}; - for (let grp in [ usage?.devices ?? {}, usage?.people ?? {} ]) - for (let id, rec in grp) - for (let k in keys(rec.days ?? {})) - days[k] = true; - let dk = sort(keys(days)); - return { - policy: pol, - events: length(ev), - oldest: length(ev) ? ev[0].ts : 0, - by_category: by, - log_ram: file_size(`${RUN_DIR}/events.json`), - log_flash: file_size(`${DATA_DIR}/events.json`), - usage_flash: file_size(`${DATA_DIR}/usage.json`), - usage_since: length(dk) ? dk[0] : '', - usage_days: length(dk), - geo_flash: file_size(`${DATA_DIR}/geo.json`), - }; -} - -function settings_get(a) { - let c = core.open_cursor(); - let raw = c.get_all('dawnline', 'settings') ?? {}; - let m = core.load(c); - let out = {}; - for (let k in SETTING_KEYS) - out[k] = raw[k] ?? ''; - out.log_category = live.policy(m.settings.retention).categories; - let cert = m.settings.portal_enabled ? ops.portal_cert(m.settings) : null; - return { - settings: out, - needs: ops.needs(), - effective: m.settings, - services: values(m.services), - cert: cert ? { path: cert.cert, self_signed: cert.self_signed, - expires: sh_out(`openssl x509 -enddate -noout -in ${q(cert.cert)} 2>/dev/null | cut -d= -f2`) } : null, - port_owners: m.settings.portal_enabled ? [] : ops.tcp_port_owners(m.settings.portal_port), - wan443_taken: core.wan443_taken(), - portal_public_port: core.portal_public_port(m), - portal_candidates: ops.portal_candidates(m), - // The portal's own checks from Health, shown next to its settings. - portal_checks: filter(ops.health(m), (x) => index([ 'portal', 'portal_dns', 'portal_reply', 'portal_443', 'portal_lan', 'portal_http', 'cert' ], x.id) >= 0), - geo_cached: length(keys(geo.load().ips)), - logs: logs_info(m), - }; -} - -function settings_update(a) { - let c = core.open_cursor(); - let m = core.load(c); - let v = a.values ?? {}; - let restart = false; - c.set('dawnline', 'settings', 'settings'); - for (let k, val in v) { - if (index(SETTING_KEYS, k) < 0 && k != 'log_category') - die(`Unknown setting ${k}.`); - if (k == 'log_category') { - let lst = filter(type(val) == 'array' ? val : [], (x) => index(live.CATEGORIES, x) >= 0); - c.set('dawnline', 'settings', 'log_category', length(lst) ? lst : [ '' ]); - // Superseded by the category list. - c.delete('dawnline', 'settings', 'log_connections'); - continue; - } - if (k == 'portal_alt') { - let lst = uniq(filter(type(val) == 'array' ? val : [], (x) => type(x) == 'string' && valid_host(x))); - if (join(' ', lst) != join(' ', m.settings.portal_alt)) - restart = true; - if (length(lst)) - c.set('dawnline', 'settings', 'portal_alt', lst); - else - c.delete('dawnline', 'settings', 'portal_alt'); - continue; - } - val = trim(`${val ?? ''}`); - if (k == 'portal_port' && val != '') { - let n = +val; - if (n < 1 || n > 65535 || index([ 22, 53, 80, 443 ], n) >= 0) - die('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).'); - if (n != m.settings.portal_port && length(ops.tcp_port_owners(n))) - die(`TCP ${n} is already used by ${join(', ', ops.tcp_port_owners(n))}.`); - } - if (k == 'portal_redirect' && val != '' && (length(val) > 300 || !match(val, /^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^[:space:]"'<>]*)?$/))) - die('Redirect must be a full http:// or https:// address.'); - if (k == 'portal_host' && val != '' && !valid_host(val)) - die('Public address must be a hostname or IP address.'); - if (k == 'default_device_limit' && val != '' && (+val < 1 || +val > 32)) - die('Default device limit must be 1-32.'); - if (k == 'domain' && val != '' && !match(val, /^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/)) - die('Domain may use lowercase letters, digits, dashes and dots.'); - if ((k == 'portal_cert' || k == 'portal_key') && val != '' && !stat(val)) - die(`${val} does not exist.`); - if (k == 'home_dns_fallback') { - if (val != '' && !match(val, /^[0-9]{1,3}(\.[0-9]{1,3}){3}$/)) - die('Fallback DNS must be an IPv4 address (or empty for none).'); - // Empty means "no fallback"; an unset option means the default. - if (val == '') - val = 'none'; - } - if (k == 'log_keep_days' && val != '' && !match(val, /^(0|[1-9][0-9]{0,3})$/)) - die('Keep activity for 0 (no age limit) to 9999 days.'); - if (k == 'log_max' && val != '' && (!match(val, /^[0-9]+$/) || +val < 100 || +val > 20000)) - die('Log size must be 100-20000 events.'); - if (k == 'log_persist' && val != '' && index([ '10min', 'hourly', 'off' ], val) < 0) - die('Save the log every 10min, hourly or off.'); - if (k == 'usage_keep_days' && val != '' && (!match(val, /^[0-9]+$/) || +val < 7 || +val > 1830)) - die('Daily traffic history must be 7-1830 days.'); - if (k == 'usage_keep_months' && val != '' && (!match(val, /^[0-9]+$/) || +val < 1 || +val > 120)) - die('Monthly traffic history must be 1-120 months.'); - if (index([ 'portal_enabled', 'portal_port', 'portal_443', 'portal_cert', 'portal_key', 'portal_host' ], k) >= 0 && val != (c.get('dawnline', 'settings', k) ?? '')) - restart = true; - if (val == '') - c.delete('dawnline', 'settings', k); - else - c.set('dawnline', 'settings', k, val); - } - c.commit('dawnline'); - system('chmod 600 /etc/config/dawnline'); - if (restart) - system('/etc/init.d/dawnline reload >/dev/null 2>&1'); - else - apply.sync(); - // The changes worth a line: the portal and the watchdog (other settings are housekeeping). - let now = core.load().settings, was = m.settings; - if (now.portal_enabled != was.portal_enabled) - admin_log('portal', now.portal_enabled ? 'turned on' : 'turned off', null, 'the personal portal', now.portal_enabled ? `port ${now.portal_port}` : null); - else if (now.portal_enabled) { - let what = []; - if (now.portal_port != was.portal_port) - push(what, `port ${now.portal_port}`); - if (now.portal_host != was.portal_host) - push(what, `address ${now.portal_host}`); - if (join(' ', now.portal_alt) != join(' ', was.portal_alt)) - push(what, 'other addresses'); - if (now.portal_cert != was.portal_cert || now.portal_key != was.portal_key) - push(what, 'certificate'); - if (now.portal_443 != was.portal_443) - push(what, now.portal_443 ? 'links without a port' : 'links with the port'); - if (now.portal_redirect != was.portal_redirect) - push(what, 'redirect'); - if (length(what)) - admin_log('portal', 'changed', null, 'the personal portal', join(', ', what)); - } - if (now.watchdog != was.watchdog) - admin_log('dawnline', now.watchdog ? 'turned on' : 'turned off', null, 'the watchdog', now.watchdog ? null : 'problems are only logged, nothing is repaired'); - return settings_get({}); -} - -function service_set(a) { - let c = core.open_cursor(); - let id = a.id || `svc_${rand_int(100000, 999999)}`; - if (!match(id, /^[A-Za-z0-9_]{1,32}$/)) - die('Invalid service id.'); - // Never turn a person, server or the settings into a service. - let existing = c.get('dawnline', id); - if (existing != null && existing != 'service') - die('That id is taken.'); - if (!a.name || length(a.name) > 48) - die('Enter a service name.'); - if (ip2int(a.address ?? '') == null) - die('Address must be an IPv4 address.'); - let ports = filter(map(type(a.ports) == 'array' ? a.ports : split(`${a.ports ?? ''}`, /[ ,]+/), (x) => trim(`${x}`)), (x) => x != ''); - for (let pt in ports) - if (!match(pt, /^[0-9]+$/) || +pt < 1 || +pt > 65535) - die(`Invalid port ${pt}.`); - c.set('dawnline', id, 'service'); - c.set('dawnline', id, 'name', trim(a.name)); - c.set('dawnline', id, 'address', a.address); - if (length(ports)) - c.set('dawnline', id, 'port', ports); - else - c.delete('dawnline', id, 'port'); - commit(c); - return { id }; -} - -/** Create or edit a circle; `members` (person ids) replaces who is in it. */ -function circle_set(a) { - let c = core.open_cursor(); - let m = core.load(c); - let ci = a.id ? m.circles[a.id] : null; - if (a.id && !ci) - die('Unknown circle.'); - let server = ci?.server ?? a.server; - if (!m.servers[server]) - die('Unknown server.'); - let name = trim(`${a.name ?? ''}`); - if (name == '' || length(name) > 32) - die('Enter a circle name (up to 32 characters).'); - for (let id, o in m.circles) - if (id != a.id && o.server == server && lc(o.name) == lc(name)) - die(`${name} already exists.`); - let id = ci?.id ?? `c_${rand_hex(4)}`; - c.set('dawnline', id, 'circle'); - c.set('dawnline', id, 'server', server); - c.set('dawnline', id, 'name', name); - c.set('dawnline', id, 'color', `${(int(a.color) || 0) % core.CIRCLE_COLORS}`); - if (type(a.members) == 'array') { - let want = {}; - for (let pid in a.members) - if (m.people[pid]?.server == server) - want[pid] = true; - for (let pid, p in m.people) - if (want[pid]) - c.set('dawnline', pid, 'circle', id); - else if (p.circle == id) - c.delete('dawnline', pid, 'circle'); - } - commit(c); - admin_log('awg', ci ? 'changed' : 'added', 'circle', name, m.servers[server].name); - return { id, circles: values(core.load().circles) }; -} - -function circle_delete(a) { - let c = core.open_cursor(); - let m = core.load(c); - let ci = m.circles[a.id]; - if (!ci) - die('Unknown circle.'); - c.delete('dawnline', a.id); - for (let pid, p in m.people) - if (p.circle == a.id) - c.delete('dawnline', pid, 'circle'); - commit(c); - admin_log('awg', 'removed', 'circle', ci.name, m.servers[ci.server]?.name); - return { circles: values(core.load().circles) }; -} - -/** - * Devices at home for the Home services picker: DHCP leases and static hosts - * in the server's home networks, with the services they announce (Bonjour, - * when umdns runs). - */ -function home_hosts(a) { - let m = core.load(); - let srv = m.servers[a.id] ?? values(m.servers)[0]; - if (!srv) - die('No server yet.'); - let nets = net.server_net(srv).nets; - let inside = (ip) => { - let n = ip2int(ip); - for (let cidr in nets) { - let x = match(cidr, /^([0-9.]+)\/([0-9]+)$/); - let size = 1 << (32 - +x[2]), base = ip2int(x[1]); - if (n != null && n >= base && n < base + size) - return true; - } - return false; - }; - let hosts = {}; - for (let line in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) { - let f = split(line, ' '); - if (length(f) >= 4 && inside(f[2])) - hosts[f[2]] = { address: f[2], name: f[3] == '*' ? '' : f[3], mac: f[1], services: [] }; - } - let c = cursor(); - c.foreach('dhcp', 'host', (h) => { - if (h.ip && inside(h.ip)) - hosts[h.ip] ??= { address: h.ip, name: h.name ?? '', mac: type(h.mac) == 'array' ? h.mac[0] : h.mac ?? '', services: [] }; - }); - for (let s in ops.mdns_services()) - if (hosts[s.address]) - push(hosts[s.address].services, { type: s.type, name: s.name, port: s.port }); - else if (inside(s.address)) - hosts[s.address] = { address: s.address, name: s.host ?? '', mac: '', services: [ { type: s.type, name: s.name, port: s.port } ] }; - let out = values(hosts); - return { hosts: sort(out, (x, y) => ip2int(x.address) - ip2int(y.address)), mdns: ops.mdns_running() }; -} - -function service_delete(a) { - let c = core.open_cursor(); - if (c.get('dawnline', a.id) != 'service') - die('Unknown service.'); - c.delete('dawnline', a.id); - c.foreach('dawnline', 'person', (p) => { - if (type(p.service) == 'array' && index(p.service, a.id) >= 0) { - let rest = filter(p.service, (x) => x != a.id); - if (length(rest)) - c.set('dawnline', p['.name'], 'service', rest); - else - c.delete('dawnline', p['.name'], 'service'); - } - }); - commit(c); - return { ok: true }; -} - -function events_list(a) { - // Tunnel down/up events of older versions: the service log tells it better (names, reasons). - let ev = filter(live.load_events(), (e) => e.type != 'server_down' && e.type != 'server_up'); - let n = +a.limit || 300; - return { events: with_hosts(slice(ev, length(ev) > n ? length(ev) - n : 0)), total: length(ev), policy: live.policy() }; -} - -/** Remove activity by person, device, category and/or age; nothing given clears it all. */ -function logs_clear(a) { - let m = core.load(); - let f = {}; - if (a.person) { - if (!m.people[a.person]) - die('Unknown person.'); - f.person = a.person; - } - if (a.device) - f.device = a.device; - if (a.category) { - if (index(live.CATEGORIES, a.category) < 0) - die('Unknown category.'); - f.category = a.category; - } - if (a.older_days) { - if (!match(a.older_days, /^[1-9][0-9]{0,3}$/)) - die('Older than must be a number of days.'); - f.before = time() - +a.older_days * 86400; - } - let removed = live.clear_events(f); - if (removed) - admin_log('dawnline', 'cleared', null, 'the activity log', - join(' · ', filter([ `${removed} event${removed == 1 ? '' : 's'}`, f.category, f.person ? m.people[f.person].name : null, - a.older_days ? `older than ${a.older_days} days` : null ], (x) => x))); - return { ok: true, removed }; -} - -/** - * Reset traffic history (all | person | device). The agent owns the live - * counters, so it gets a marker; the tmpfs copy is edited too so the UI - * shows the result straight away. - */ -function usage_clear(a) { - let m = core.load(); - if (index([ 'all', 'person', 'device' ], a.scope) < 0) - die('Unknown scope.'); - if (a.scope == 'person' && !m.people[a.id]) - die('Unknown person.'); - if (a.scope == 'device' && !m.devices[a.id]) - die('Unknown device.'); - let req = { scope: a.scope, id: a.id, ts: time() }; - ensure_dir(RUN_DIR); - let l = lock('usage-reset'); - let pending = read_json(`${RUN_DIR}/usage.reset`, []); - push(pending, req); - write_json(`${RUN_DIR}/usage.reset`, pending, 0o600); - unlock(l); - let usage = core.load_usage(); - if (usage) { - live.reset_usage(usage, m, a.scope, a.id); - write_json(`${RUN_DIR}/usage.json`, usage, 0o600); - } - admin_log('dawnline', 'reset traffic history', null, - a.scope == 'all' ? 'for everyone' : a.scope == 'person' ? `for ${m.people[a.id].name}` : `for ${m.devices[a.id].name} (${m.people[m.devices[a.id].person]?.name})`); - return { ok: true }; -} - -function uninstall(a) { - if (a.confirm != 'remove') - die('Type "remove" to confirm.'); - ops.backup_create('pre-remove'); - apply.teardown(); - system('/etc/init.d/dawnline stop >/dev/null 2>&1; /etc/init.d/dawnline disable >/dev/null 2>&1'); - let c = core.open_cursor(); - let rm = []; - c.foreach('dawnline', null, (s) => { - if (s['.type'] != 'settings') - push(rm, s['.name']); - }); - for (let n in rm) - c.delete('dawnline', n); - c.set('dawnline', 'settings', 'portal_enabled', '0'); - c.commit('dawnline'); - return { ok: true }; -} - -const methods = { - status: { args: { days: 30 }, call: wrap(status) }, - setup_defaults: { call: wrap(setup_defaults) }, - server_create: { - args: { id: '', name: '', ifname: '', port: 0, subnet: '', endpoint: '', mtu: 0, preset: '', lan_zone: '', wan_zone: '', - lan_like: true, portal_enabled: false, portal_port: 0 }, - call: wrap(server_create), +import * as status from 'dawnline.rpc.status'; +import * as servers from 'dawnline.rpc.servers'; +import * as people from 'dawnline.rpc.people'; +import * as settings from 'dawnline.rpc.settings'; +import * as home from 'dawnline.rpc.home'; +import * as maint from 'dawnline.rpc.maint'; +import * as updates from 'dawnline.rpc.updates'; + +return { + 'luci.dawnline': { + ...status.methods, + ...servers.methods, + ...people.methods, + ...settings.methods, + ...home.methods, + ...maint.methods, + ...updates.methods, }, - server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) }, - server_update: { args: { id: '', values: {} }, call: wrap(server_update) }, - interfaces: { args: { id: '' }, call: wrap(interfaces_get) }, - server_interfaces: { args: { id: '', auto_wan: false, wan_device: '', auto_lan: false, lan_devices: [], lan_like: false, device_mesh: true }, call: wrap(server_interfaces) }, - server_delete: { args: { id: '' }, call: wrap(server_delete) }, - person_create: { - args: { name: '', slug: '', server: '', access: '', device_limit: 0, expires: '', quota_gb: 0, quota_period: '' }, - call: wrap(person_create), - }, - person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) }, - person_regen: { args: { id: '' }, call: wrap(person_regen) }, - person_delete: { args: { id: '' }, call: wrap(person_delete) }, - person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) }, - pause_all: { args: { paused: false }, call: wrap(pause_all) }, - device_create: { args: { person: '', name: '', kind: '' }, call: wrap(device_create) }, - device_config: { args: { id: '' }, call: wrap(device_config) }, - device_update: { args: { id: '', name: '', disabled: false }, call: wrap(device_update) }, - device_delete: { args: { id: '' }, call: wrap(device_delete) }, - device_rotate: { args: { id: '' }, call: wrap(device_rotate) }, - apply: { call: wrap((a) => apply.apply()) }, - health: { call: wrap((a) => ({ checks: ops.health(), ...watchdog.view(core.load()) })) }, - health_fix: { args: { id: '' }, call: wrap((a) => ({ result: ops.fix(a.id), checks: ops.health(), ...watchdog.view(core.load()) })) }, - service_log: { call: wrap((a) => watchdog.view(core.load())) }, - service_log_clear: { args: { older_days: '' }, call: wrap((a) => { - let removed = slog_clear(+a.older_days || 0); - if (removed) - admin_log('dawnline', 'cleared', null, 'the service log', `${removed} entr${removed == 1 ? 'y' : 'ies'}${+a.older_days ? ` older than ${a.older_days} days` : ''}`); - return { removed }; - }) }, - backup_list: { call: wrap((a) => ({ backups: ops.backup_list() })) }, - backup_create: { call: wrap((a) => ({ name: ops.backup_create(null) })) }, - backup_restore: { args: { name: '' }, call: wrap((a) => { - let r = ops.backup_restore(a.name); - admin_log('dawnline', 'restored', 'backup', a.name); - return r; - }) }, - backup_delete: { args: { name: '' }, call: wrap((a) => ({ ok: ops.backup_delete(a.name) })) }, - backup_read: { args: { name: '' }, call: wrap((a) => ({ data: ops.backup_read(a.name) })) }, - backup_upload: { args: { data: '' }, call: wrap((a) => { - let r = ops.backup_upload(a.data); - admin_log('dawnline', 'restored', 'backup', 'from a file'); - return r; - }) }, - export: { call: wrap((a) => { - let r = ops.export_json(); - admin_log('dawnline', 'exported', null, 'all settings', 'the file holds private keys'); - return r; - }) }, - import: { args: { data: {} }, call: wrap((a) => { - let r = ops.import_json(a.data); - admin_log('dawnline', 'imported', null, 'settings from a file'); - return r; - }) }, - updates_status: { call: wrap(updates_status) }, - updates_run: { args: { what: '' }, call: wrap(updates_run) }, - person_update: { - args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '', - quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [] }, - call: wrap(person_update), - }, - settings_get: { call: wrap(settings_get) }, - settings_update: { args: { values: {} }, call: wrap(settings_update) }, - service_set: { args: { id: '', name: '', address: '', ports: [] }, call: wrap(service_set) }, - service_delete: { args: { id: '' }, call: wrap(service_delete) }, - circle_set: { args: { id: '', server: '', name: '', color: 0, members: [] }, call: wrap(circle_set) }, - circle_delete: { args: { id: '' }, call: wrap(circle_delete) }, - access_check: { args: { from: '', to: '' }, call: wrap((a) => access.check(core.load(), a.from, a.to)) }, - home_hosts: { args: { id: '' }, call: wrap(home_hosts) }, - geo_clear: { call: wrap((a) => { geo.clear(); return { ok: true }; }) }, - events: { args: { limit: 300 }, call: wrap(events_list) }, - logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) }, - usage_clear: { args: { scope: '', id: '' }, call: wrap(usage_clear) }, - uninstall: { args: { confirm: '' }, call: wrap(uninstall) }, }; - -return { 'luci.dawnline': methods }; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc index e1c2ff1..21dedd3 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc @@ -3,11 +3,12 @@ 'use strict'; -import { ip2int } from 'dawnline.util'; +import { ip2int, in_nets } from 'dawnline.util'; import * as core from 'dawnline.core'; import * as net from 'dawnline.net'; import * as live from 'dawnline.live'; import * as view from 'dawnline.view'; +import * as awg from 'dawnline.awg'; const STATE_TEXT = { no_server: 'their server is turned off', @@ -30,21 +31,13 @@ function stop(steps, s) { return steps; } -/** The first of `nets` (IPv4 CIDRs, any prefix) that holds `ip`. */ -function in_any(ip, nets) { - let n = ip2int(ip); - if (n == null) - return null; - for (let c in nets) { - let mm = match(c, /^([0-9.]+)\/([0-9]+)$/); - let base = mm ? ip2int(mm[1]) : null; - if (base == null) - continue; - let size = 1 << (32 - +mm[2]); - if (+mm[2] == 0 || (n >= base - base % size && n < base - base % size + size)) - return c; - } - return null; +/** The tunnel subnet (of any server) that holds `ip`: never home, whatever routes cover it. */ +function in_tunnels(m, ip) { + let nets = []; + for (let id, s in m.servers) + for (let t in core.tunnels(s)) + push(nets, t.subnet); + return in_nets(ip, nets); } /** "10.0.1.20:445" → [ip, port]; a device id → its address. */ @@ -70,10 +63,15 @@ function peer_of(dmp, d) { return dmp.peers[d.public_key]; } +/** What the device sends to the router: its configuration's AllowedIPs. */ +function routed(m, srv, p, d) { + return { nets: awg.allowed_ips(m, srv, p), what: 'Its configuration', list: null }; +} + /** The home network (interface) of a server that holds an address. */ function home_dev_of(srv, ip, snap) { for (let h in net.server_net(srv, snap).home) - if (in_any(ip, h.nets)) + if (in_nets(ip, h.nets)) return h.dev; return null; } @@ -113,12 +111,14 @@ function from_device(m, d, t, states, dmp, snap) { let steps = [ person_ok(m, p, d, states) ]; if (!steps[0].ok) return steps; - let allowed = core.allowed_ips(m, srv, p); + let r = routed(m, srv, p, d); + let allowed = r.nets; let via = (ip) => { - let hit = in_any(ip, allowed); + let hit = in_nets(ip, allowed); + let what = r.list ? `${r.what}: ${r.list}` : `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`; return hit - ? step(true, 'Its configuration sends it through the tunnel', `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`) - : step(false, "Its configuration doesn't send it through the tunnel", `AllowedIPs ${join(', ', allowed)}: the device's own network handles it.`); + ? step(true, `${r.what} sends it to the router`, what) + : step(false, `${r.what} doesn't send it to the router`, `${what}: the device's own network handles it.`); }; // Another device. @@ -164,6 +164,11 @@ function from_device(m, d, t, states, dmp, snap) { return steps; } + // A tunnel address no device has. + let tn = in_tunnels(m, t.ip); + if (tn) + return stop(steps, step(false, `No device uses ${t.ip}`, `It is in the tunnel network ${tn}.`)); + // Home. let sn = net.server_net(srv, snap); let hdev = home_dev_of(srv, t.ip, snap); @@ -185,7 +190,7 @@ function from_device(m, d, t, states, dmp, snap) { } else { let h = core.person_home(srv, p, snap); - if (!in_any(t.ip, h.nets)) + if (!in_nets(t.ip, h.nets)) return stop(steps, step(false, `${t.ip} is in ${hdev}, which ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`)); push(steps, step(true, `${t.ip} is in ${hdev}`, h.all ? 'Home access reaches every home network.' : `One of the networks ${p.name} reaches.`)); } @@ -195,7 +200,7 @@ function from_device(m, d, t, states, dmp, snap) { } // Another private address, or the internet. - if (in_any(t.ip, [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16' ])) + if (in_nets(t.ip, [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16' ])) return stop(steps, step(false, `${t.ip} isn't in ${srv.name}'s home network`, 'Private addresses outside the home network are blocked.')); if (p.access == 'lan') return stop(steps, step(true, `${t.ip} is on the internet`, `${p.name} has Home only: their device's own internet reaches it, not the tunnel.`)); @@ -211,7 +216,7 @@ function to_device(m, ip, d, states, dmp, snap) { if (!p || !srv) return [ step(false, `${d.name} has no server`, '') ]; let who = `${p.name} · ${d.name}`; - let hdev = home_dev_of(srv, ip, snap); + let hdev = in_tunnels(m, ip) ? null : home_dev_of(srv, ip, snap); if (!hdev) return [ step(false, `${ip} isn't in ${srv.name}'s home network`, 'Only home devices reach people\'s devices.') ]; let steps = [ step(true, `${ip} is at home (${hdev})`, '') ]; @@ -219,7 +224,7 @@ function to_device(m, ip, d, states, dmp, snap) { return stop(steps, step(false, `${p.name} has ${p.access == 'lan' ? 'only some home services' : ACCESS_TEXT[p.access]}`, 'Home devices reach only people with home access.')); let h = core.person_home(srv, p, snap); - if (!in_any(ip, h.nets)) + if (!in_nets(ip, h.nets)) return stop(steps, step(false, `${p.name} doesn't reach ${hdev}`, 'Networks a person does not reach cannot reach them either.')); push(steps, person_ok(m, p, d, states)); if (!steps[length(steps) - 1].ok) @@ -238,7 +243,7 @@ export function check(m, from, to) { die(`"${to}" is not a device or an IPv4 address.`); let usage = core.load_usage(); let states = view.states(m, usage); - let dmp = live.dump(); + let dmp = live.dump(m); let snap = net.snapshot(true); let steps; if (a.dev) diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/apply.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/apply.uc index 74aa8c9..c4f7db4 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/apply.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/apply.uc @@ -1,481 +1,38 @@ // Dawnline — reconciliation. Turns /etc/config/dawnline into router state: -// * network interfaces (proto amneziawg), peers applied live with `awg syncconf` -// * firewall zones, forwardings and WAN rules (named sections dawnline_*) -// * nft table `inet dawnline` enforcing each person's access +// * network interfaces (dawnline.netifd) and the devices loaded live into +// them (dawnline.awg) +// * firewall zones, forwardings, WAN rules and reply routes (dawnline.fw) +// * the nft table `inet dawnline` enforcing each person's access (dawnline.nft) // * hostnames in /tmp/hosts/dawnline // * the "like a home device" path and the Home-only resolver (dawnline.loop) // Only objects created by Dawnline are ever modified. +// +// apply(), sync() and sync_loop() run under one lock ('apply') and read the +// model inside it, so a rebuild and a runtime update never interleave and the +// last one to run always works from the newest configuration. The config lock +// (dawnline.store) is never taken while 'apply' is held. -import { cursor } from 'uci'; import { readfile, writefile, stat, unlink } from 'fs'; -import { - q, sh, sh_out, sh_bg, ensure_dir, write_file, write_json, read_json, parse_cidr, int2ip, uniq, - lock, unlock, slog, iface_intent, RUN_DIR -} from 'dawnline.util'; +import { ensure_dir, write_file, write_json, with_lock, ip2int, slog, RUN_DIR } from 'dawnline.util'; import * as core from 'dawnline.core'; import * as net from 'dawnline.net'; import * as loop from 'dawnline.loop'; +import * as awg from 'dawnline.awg'; +import * as nft from 'dawnline.nft'; +import * as fw from 'dawnline.fw'; +import * as netifd from 'dawnline.netifd'; +import * as migrate from 'dawnline.migrate'; const HOSTS_FILE = '/tmp/hosts/dawnline'; -/* - * Our own answers leave by the main table: the portal's (TCP) and each - * tunnel's (UDP). Proxies on the router (tproxy with an fwmark rule) may mark - * the router's own traffic to internet addresses and divert it locally, which - * swallows replies to outside clients. These rules sit before such fwmark - * rules and only match our listening ports. - */ -const PREF_REPLY = 90; +/** The network signature the last apply() worked from (the agent compares against it). */ +export const NET_SIG = `${RUN_DIR}/net.sig`; +// The last access-table error that was logged (each distinct failure once). +const NFT_ERR = `${RUN_DIR}/nft.err`; function log(who, msg, level, detail) { slog('dawnline', level ?? 'info', msg, detail, who); } -/* ---------- helpers ---------- */ - -/** Set an option only when it differs; returns true if something changed. */ -function put(c, conf, sec, opt, val) { - let cur = c.get(conf, sec, opt); - if (val == null || val == '' || (type(val) == 'array' && !length(val))) { - if (cur != null) { - c.delete(conf, sec, opt); - return true; - } - return false; - } - if (type(val) == 'array') { - if (type(cur) == 'array' && join('\n', cur) == join('\n', val)) - return false; - } - else if (cur == `${val}`) - return false; - c.set(conf, sec, opt, type(val) == 'array' ? val : `${val}`); - return true; -} - -function ensure_section(c, conf, sec, stype) { - if (c.get(conf, sec) == stype) - return false; - if (c.get(conf, sec) != null) - c.delete(conf, sec); - c.set(conf, sec, stype); - return true; -} - -/** - * After committing a config ourselves (and applying it), record its new - * checksum so a later `reload_config` does not treat it as changed and - * restart unrelated services that reload on any network change. - */ -function ack_config(confs) { - let md5f = '/var/run/config.md5'; - if (!stat(md5f)) - return; - let lines = split(trim(readfile(md5f) ?? ''), '\n'); - for (let conf in confs) { - let path = `/var/run/config.check/${conf}`; - let sum = sh_out(`uci show ${q(conf)} | md5sum | cut -d' ' -f1`); - if (!sum) - continue; - let found = false; - for (let i = 0; i < length(lines); i++) - if (substr(lines[i], -length(path) - 2) == ` ${path}`) { - lines[i] = `${sum} ${path}`; - found = true; - } - if (!found) - push(lines, `${sum} ${path}`); - } - writefile(md5f, join('\n', lines) + '\n'); -} - -/* ---------- network ---------- */ - -function sync_network(m) { - let c = cursor(); - c.load('network'); - let changed = false, touched = []; - let want = {}; - - for (let id, srv in m.servers) { - if (!srv.private_key) - continue; - let ifn = srv.ifname; - want[ifn] = true; - let addr = core.server_address(srv); - let pc = parse_cidr(srv.subnet); - // Per server: with several, each changed one has to be brought up again. - let mine = ensure_section(c, 'network', ifn, 'interface'); - let set = (opt, val) => { - if (put(c, 'network', ifn, opt, val)) - mine = true; - }; - set('proto', 'amneziawg'); - set('private_key', srv.private_key); - set('listen_port', srv.port); - set('addresses', [ `${addr}/${pc.prefix}` ]); - set('mtu', srv.mtu); - set('disabled', srv.enabled ? null : '1'); - set('auto', srv.enabled ? null : '0'); - set('_dawnline', id); - // For the log once the server is gone. - set('_dawnline_name', srv.name); - for (let k in core.OBF_KEYS) - set(`awg_${k}`, srv.obf[k]); - if (mine) { - changed = true; - push(touched, ifn); - // The hotplug log says why the tunnel goes down (not a failure). - iface_intent(ifn, srv.enabled ? 'settings' : 'off', srv.name); - } - } - - // Remove interfaces Dawnline created for servers that no longer exist. - let stale = []; - c.foreach('network', 'interface', (s) => { - if (s._dawnline && !want[s['.name']]) - push(stale, s['.name']); - }); - for (let ifn in stale) { - iface_intent(ifn, 'removed', c.get('network', ifn, '_dawnline_name') ?? ifn); - system(`ifdown ${q(ifn)} 2>/dev/null`); - c.delete('network', ifn); - changed = true; - } - - if (changed) { - c.commit('network'); - ack_config([ 'network' ]); - system('ubus call network reload'); - for (let ifn in touched) - if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled) - system(`ifup ${q(ifn)}`); - // Each tunnel's own line (restarting, turned off, removed) comes from hotplug. - system(`logger -t dawnline ${q('network updated: ' + join(', ', [ ...touched, ...stale ]))}`); - } - return changed; -} - -/* ---------- firewall ---------- */ - -const LOOP_ZONE = 'dl_loop'; - -/** With `dry`, only says whether the firewall config differs from what Dawnline wants. */ -function sync_firewall(m, dry) { - let c = cursor(); - c.load('firewall'); - let changed = false, want = {}; - - let sec = (name, stype, opts) => { - want[name] = true; - changed = ensure_section(c, 'firewall', name, stype) || changed; - for (let k, v in opts) - changed = put(c, 'firewall', name, k, v) || changed; - }; - - let snap = net.snapshot(true); - let portal_zone = null, want_loop = false; - for (let id, srv in m.servers) { - if (!srv.private_key) - continue; - let z = `dawnline_${id}`; - let sn = net.server_net(srv, snap); - portal_zone ??= sn.wan.zone; - sec(`${z}_zone`, 'zone', { - // Forward within the zone (device to device) is decided by the inet dawnline table. - name: srv.ifname, network: [ srv.ifname ], - input: 'ACCEPT', output: 'ACCEPT', forward: 'ACCEPT', - }); - // Access per person is enforced by the inet dawnline table; the zone - // only needs to be allowed to reach each home-network zone and WAN. - // The home network may open connections to the devices too (a router - // or a NAS on the tunnel); their answers pass the table as established. - for (let i, zone in sn.zones) - if (zone != sn.wan.zone && zone != srv.ifname) { - let sfx = i == 0 ? '' : `_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`; - sec(`${z}_lan${sfx}`, 'forwarding', { src: srv.ifname, dest: zone }); - sec(`${z}_from_lan${sfx}`, 'forwarding', { src: zone, dest: srv.ifname }); - } - sec(`${z}_wan`, 'forwarding', { src: srv.ifname, dest: sn.wan.zone }); - if (srv.lan_like) { - sec(`${z}_loop`, 'forwarding', { src: srv.ifname, dest: LOOP_ZONE }); - want_loop = true; - } - sec(`${z}_port`, 'rule', { - name: `Dawnline-${srv.ifname}`, src: sn.wan.zone, proto: 'udp', - dest_port: srv.port, target: 'ACCEPT', enabled: srv.enabled ? null : '0', - }); - } - - // The link into the netns that re-enters the router from the LAN. - if (want_loop) { - sec('dawnline_loop', 'zone', { - name: LOOP_ZONE, device: [ net.INTERNAL.transit ], - input: 'REJECT', output: 'ACCEPT', forward: 'REJECT', - }); - // The Home-only resolver in the netns reaches its upstream DNS this way. - sec('dawnline_loop_wan', 'forwarding', { src: LOOP_ZONE, dest: portal_zone ?? 'wan' }); - } - - if (m.settings.portal_enabled) { - let wan = portal_zone ?? 'wan'; - sec('dawnline_portal', 'rule', { - name: 'Dawnline-Portal', src: wan, proto: 'tcp', - dest_port: m.settings.portal_port, target: 'ACCEPT', - }); - // IP addresses in links: plain HTTP next to the HTTPS port, and 80 forwarded to it. - if (core.portal_http(m)) { - sec('dawnline_portal_http', 'rule', { - name: 'Dawnline-Portal-HTTP', src: wan, proto: 'tcp', - dest_port: core.portal_http_port(m), target: 'ACCEPT', - }); - if (core.portal_http_public(m) == 80) - sec('dawnline_portal_80', 'redirect', { - name: 'Dawnline-Portal-80', src: wan, proto: 'tcp', - src_dport: 80, dest_port: core.portal_http_port(m), target: 'DNAT', - }); - } - // Links use 443: from outside it lands on the portal (LuCI stays closed there). - if (core.portal_public_port(m) == 443 && m.settings.portal_port != 443) - sec('dawnline_portal_443', 'redirect', { - name: 'Dawnline-Portal-443', src: wan, proto: 'tcp', - src_dport: 443, dest_port: m.settings.portal_port, target: 'DNAT', - }); - } - - let stale = []; - c.foreach('firewall', null, (s) => { - if (match(s['.name'], /^dawnline_/) && !want[s['.name']]) - push(stale, s['.name']); - }); - for (let s in stale) { - c.delete('firewall', s); - changed = true; - } - if (dry) - return changed; - - if (changed) { - c.commit('firewall'); - ack_config([ 'firewall' ]); - system('fw4 -q reload'); - system("logger -t dawnline 'firewall updated'"); - } - return changed; -} - -/* ---------- nft access table ---------- */ - -const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ]; - -/** Per-person runtime membership: which tunnel addresses may reach what. */ -export function access_sets(m, usage, states) { - // lan_ok: home access (the router itself, the mesh); lan_all: every home - // network; lan_part: device . network for people limited to some networks; - // mesh_pairs: device . device within a circle (or one person's own devices). - let sets = { lan_ok: [], lan_all: [], lan_part: [], mesh_pairs: [], inet_ok: [], svc_ok: [], dns_real: [] }; - let snap = net.snapshot(); - let homes = {}, groups = {}; - for (let id, d in m.devices) { - let p = m.people[d.person]; - if (!p || d.disabled || !d.address || states[p.id] != 'active') - continue; - // Plain DNS for whoever's internet does not go through the router. - // Home names: the plain resolver (their internet does not use the tunnel). - if (p.access == 'lan' && p.dns_mode == 'home') - push(sets.dns_real, d.address); - if (p.access == 'internet' || p.access == 'both') - push(sets.inet_ok, d.address); - if (p.access == 'both' || (p.access == 'lan' && !length(p.services))) { - push(sets.lan_ok, d.address); - let srv = m.servers[p.server]; - let h = homes[p.id] ??= srv ? core.person_home(srv, p, snap) : { all: true, nets: [] }; - if (h.all) - push(sets.lan_all, d.address); - else - for (let n in h.nets) - push(sets.lan_part, `${d.address} . ${n}`); - // Who this device may reach directly: its circle, or at least its owner's devices. - if (srv?.mesh == 'circles') { - let ci = core.person_circle(m, p); - push(groups[ci ? `c:${ci.id}` : `p:${p.id}`] ??= [], d.address); - } - } - else if (p.access == 'lan') - for (let sid in p.services) { - let s = m.services[sid]; - if (!s || !s.address) - continue; - for (let port in s.ports) - if (match(port, /^[0-9]+$/)) - push(sets.svc_ok, `${d.address} . ${s.address} . ${port}`); - } - } - for (let g, addrs in groups) - for (let a in addrs) - for (let b in addrs) - if (a != b) - push(sets.mesh_pairs, `${a} . ${b}`); - return sets; -}; - -function set_elems(arr) { - return length(arr) ? `elements = { ${join(', ', arr)} }` : ''; -} - -function nft_table(m, sets) { - let ifs = [], lan = []; - let dns_addr = loop.client_dns(); - let rt = loop.resolver_target(); - let snap = net.snapshot(); - for (let id, srv in m.servers) - if (srv.private_key) { - push(ifs, `"${srv.ifname}"`); - push(lan, ...net.server_net(srv, snap).nets); - } - lan = net.collapse(lan); - let t = []; - push(t, 'table inet dawnline {'); - push(t, ` set lan_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(lan)} }`); - push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`); - push(t, ` set lan_all { type ipv4_addr; ${set_elems(sets.lan_all)} }`); - push(t, ` set lan_part { type ipv4_addr . ipv4_addr; flags interval; ${set_elems(sets.lan_part)} }`); - push(t, ` set mesh_pairs { type ipv4_addr . ipv4_addr; ${set_elems(sets.mesh_pairs)} }`); - push(t, ` set inet_ok { type ipv4_addr; ${set_elems(sets.inet_ok)} }`); - push(t, ` set svc_ok { type ipv4_addr . ipv4_addr . inet_service; ${set_elems(sets.svc_ok)} }`); - push(t, ` set dns_real { type ipv4_addr; ${set_elems(sets.dns_real)} }`); - push(t, ' chain pre {'); - // Ahead of mangle-priority hooks (transparent proxies mark at -150). - push(t, ' type filter hook prerouting priority -160; policy accept;'); - if (length(ifs)) - push(t, ` iifname { ${join(', ', ifs)} } jump guard`); - push(t, ' }'); - push(t, ' chain guard {'); - push(t, ' meta nfproto ipv6 drop'); - push(t, ' ct state established,related accept'); - push(t, ' icmp type echo-request fib daddr type local accept'); - push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept'); - push(t, ' fib daddr type local ip saddr @lan_ok accept'); - push(t, ' fib daddr type local counter drop'); - if (dns_addr) - // DNS through the netns (it forwards to the LAN's DNS), for everyone. - push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`); - push(t, ' ip daddr @lan_nets ip saddr @lan_all accept'); - push(t, ' ip saddr . ip daddr @lan_part accept'); - // Devices with home access are part of home: they reach each other, where the - // server allows it (everyone, or within circles). Within one server: the - // firewall has no forwarding between different servers' zones. - for (let id, srv in m.servers) - if (srv.private_key && srv.mesh == 'all') - push(t, ` iifname "${srv.ifname}" ip saddr @lan_ok ip daddr @lan_ok accept`); - else if (srv.private_key && srv.mesh == 'circles') - push(t, ` iifname "${srv.ifname}" ip saddr . ip daddr @mesh_pairs accept`); - push(t, ' meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept'); - push(t, ` ip daddr { ${join(', ', PRIVATE4)} } counter drop`); - push(t, ' ip saddr @inet_ok accept'); - push(t, ' counter drop'); - push(t, ' }'); - // The other way: fw4 lets the server's home zones reach the tunnel; here - // only connections from its home networks to people with home access pass - // (paused, ended and internet-only people are not reachable). The admin's - // own port forwards (DNAT) stay with fw4. - push(t, ' chain inbound {'); - push(t, ' type filter hook forward priority filter - 5; policy accept;'); - if (length(ifs)) - push(t, ` oifname { ${join(', ', ifs)} } iifname != { ${join(', ', ifs)} } ct state new jump to_device`); - push(t, ' }'); - push(t, ' chain to_device {'); - push(t, ' meta nfproto ipv6 drop'); - push(t, ' ct status dnat accept'); - push(t, ' ip saddr @lan_nets ip daddr @lan_all accept'); - push(t, ' ip daddr . ip saddr @lan_part accept'); - push(t, ' counter reject with icmpx admin-prohibited'); - push(t, ' }'); - // Devices ask the tunnel address; send each query where it belongs. - let to_resolver = rt.mode == 'ns' ? `dnat ip to ${rt.address}:53` : `redirect to :${rt.port}`; - let lan_dns = loop.lan_dns(); - push(t, ' chain dns {'); - push(t, ' type nat hook prerouting priority dstnat - 5; policy accept;'); - if (length(ifs)) - // Home names (and no LAN DNS at all): the plain resolver, whatever address was asked. - push(t, ` iifname { ${join(', ', ifs)} } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 ${to_resolver}`); - for (let id, srv in m.servers) { - let a = srv.private_key ? core.server_address(srv) : null; - if (!a) - continue; - // Everyone else: the LAN's DNS, through the netns (from the LAN side) when internet goes that way. - let target = srv.lan_like && dns_addr ? `dnat ip to ${dns_addr}:53` : lan_dns ? `dnat ip to ${lan_dns}:53` : to_resolver; - push(t, ` iifname "${srv.ifname}" ip daddr ${a} meta l4proto { tcp, udp } th dport 53 ${target}`); - } - push(t, ' }'); - push(t, '}'); - return join('\n', t) + '\n'; -} - -function nft_load(script) { - ensure_dir(RUN_DIR); - let f = `${RUN_DIR}/nft.rules`; - writefile(f, script); - let r = sh(`nft -f ${f}`); - if (r.code != 0) - log('Access rules', "couldn't load", 'error', trim(r.out)); - return r.code == 0; -} - -/** Full table rebuild (structure changes: servers, LAN subnets). */ -export function rebuild_nft(m, sets) { - let s = 'table inet dawnline\ndelete table inet dawnline\n' + nft_table(m, sets); - return nft_load(s); -}; - -/** Atomically replace set contents only. */ -export function update_sets(sets) { - let s = ''; - for (let name in [ 'lan_ok', 'lan_all', 'lan_part', 'mesh_pairs', 'inet_ok', 'svc_ok', 'dns_real' ]) { - s += `flush set inet dawnline ${name}\n`; - if (length(sets[name])) - s += `add element inet dawnline ${name} { ${join(', ', sets[name])} }\n`; - } - return nft_load(s); -}; - -export function remove_nft() { - system('nft delete table inet dawnline 2>/dev/null'); -}; - -/* ---------- AmneziaWG peers ---------- */ - -/** Push the peer list of every server to the kernel without restarting it. */ -export function sync_peers(m, states) { - ensure_dir(RUN_DIR); - let res = {}; - for (let id, srv in m.servers) { - if (!srv.private_key || !srv.enabled) - continue; - if (system(`awg show ${q(srv.ifname)} public-key >/dev/null 2>&1`) != 0) { - res[id] = 'down'; - continue; - } - let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ]; - for (let did, d in m.devices) { - let p = m.people[d.person]; - if (!p || p.server != id || d.disabled || states[p.id] != 'active' || !d.public_key || !d.address) - continue; - push(lines, '[Peer]', `PublicKey = ${d.public_key}`); - if (d.preshared_key) - push(lines, `PresharedKey = ${d.preshared_key}`); - push(lines, `AllowedIPs = ${d.address}/32`, ''); - } - let f = `${RUN_DIR}/${srv.ifname}.conf`; - write_file(f, join('\n', lines)); - let r = sh(`awg syncconf ${q(srv.ifname)} ${f}`); - unlink(f); - res[id] = r.code == 0 ? 'ok' : trim(r.out); - if (r.code != 0) - slog('awg', 'error', "couldn't load devices into the tunnel", trim(r.out), srv.name); - } - return res; -}; - /* ---------- hostnames ---------- */ function host_label(s) { @@ -489,7 +46,7 @@ export function sync_hosts(m) { if (m.settings.hostnames) for (let id, d in m.devices) { let p = m.people[d.person]; - if (p && d.address) + if (p && ip2int(d.address) != null) push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`); } let ls = loop.status(); @@ -511,7 +68,7 @@ export function sync_hosts(m) { return true; }; -/* ---------- entry points ---------- */ +/* ---------- access table ---------- */ export function states_for(m, usage) { let st = {}; @@ -520,21 +77,84 @@ export function states_for(m, usage) { return st; }; -/** Runtime sync: peers + access sets + hostnames. Cheap; safe to call often. */ -export function sync(m, usage) { - m ??= core.load(); - usage ??= core.load_usage(); +/** Per-person runtime membership (dawnline.nft). */ +export function access_sets(m, usage, states) { + return nft.access_sets(m, usage, states); +}; + +/** Log an access-table failure once per distinct error; true when the table is in place. */ +function nft_result(err) { + let was = readfile(NFT_ERR); + if (err == null) { + if (was != null) + unlink(NFT_ERR); + return true; + } + if (was != err) { + log('Access rules', "couldn't load — devices aren't loaded into the tunnels until they do", 'error', err); + ensure_dir(RUN_DIR); + writefile(NFT_ERR, err); + } + return false; +} + +/** + * The table in place: rebuilt with `full`, otherwise members only, rebuilt + * when that fails (no table yet at boot, or an older shape) — an error only + * when the rebuild fails too. + */ +function load_table(m, sets, full) { + let err = full ? nft.rebuild(m, sets) : nft.update(sets); + if (err != null && !full) + err = nft.rebuild(m, sets); + return nft_result(err); +} + +/** Full table rebuild (structure changes: servers, LAN subnets). */ +export function rebuild_nft(m, sets) { + return nft_result(nft.rebuild(m, sets)); +}; + +/** Atomically replace set contents only. */ +export function update_sets(sets) { + return nft.update(sets) == null; +}; + +export function remove_nft() { + nft.remove(); +}; + +/** For the watchdog (dawnline.fw). */ +export function firewall_drift(m) { + return fw.drift(m); +}; + +/* ---------- runtime sync ---------- */ + +/* + * With the lock held: access sets first, and devices into the tunnels only + * once the table that limits them is in place. + */ +function locked_sync(m, usage, full) { let states = states_for(m, usage); - let l = lock('apply'); - let peers = sync_peers(m, states); - let sets = access_sets(m, usage, states); - if (!update_sets(sets)) - rebuild_nft(m, sets); + let sets = nft.access_sets(m, usage, states); + let peers = {}; + if (load_table(m, sets, full)) + peers = awg.sync_peers(m, states); sync_hosts(m); - unlock(l); ensure_dir(RUN_DIR); write_json(`${RUN_DIR}/states.json`, states, 0o644); return { peers, states }; +} + +/** + * Runtime sync: devices into the tunnels (AmneziaWG peers), access sets, + * hostnames. Cheap; safe to call often. The model is always read again under + * the lock (`m` is accepted for older callers and not used); `usage` is the + * caller's (the agent holds the live counters). + */ +export function sync(m, usage) { + return with_lock('apply', () => locked_sync(core.load(), usage ?? core.load_usage())); }; /** @@ -552,179 +172,66 @@ export function net_signature(m) { return sprintf('%J', { wan: snap.wan, lan: snap.lan, addrs: lan?.addrs, servers: srvs, dns: loop.lan_dns(), loop: loop.client_dns() }); }; -const PORTAL_CGI = '/usr/share/dawnline/portal/www/cgi-bin/portal'; -const LAN_CGI = '/www/cgi-bin/dawnline-portal'; -const LAN_CGI_URL = '/cgi-bin/dawnline-portal'; - -/* - * At home the portal's hostname usually points at the router itself, where - * LuCI's web server owns 443. Paths it does not know (the portal's) go to the - * portal CGI through its error page, so the same link works inside and out. - */ -function sync_uhttpd(m) { - let want = m.settings.portal_enabled && core.portal_public_port(m) == 443 && m.settings.portal_port != 443; - let c = cursor(); - c.load('uhttpd'); - let cur = c.get('uhttpd', 'main', 'error_page'); - let changed = false; - if (want) { - if (!stat(LAN_CGI)) - system(`ln -sf ${PORTAL_CGI} ${LAN_CGI}`); - if (cur == null && c.get('uhttpd', 'main')) { - c.set('uhttpd', 'main', 'error_page', LAN_CGI_URL); - changed = true; - } - } - else { - if (cur == LAN_CGI_URL) { - c.delete('uhttpd', 'main', 'error_page'); - changed = true; - } - if (stat(LAN_CGI)) - unlink(LAN_CGI); - } - if (changed) { - c.commit('uhttpd'); - system('/etc/init.d/uhttpd reload >/dev/null 2>&1'); - system(`logger -t dawnline ${q(want ? 'portal answers through the LuCI web server' : 'portal removed from the LuCI web server')}`); - } -} - -/** - * For the watchdog: what is wrong with Dawnline's firewall, or null. - * 'off': fw4 is not running at all (not ours to start); 'changed': the config - * lost or changed Dawnline's sections; 'not loaded': fw4 runs without them. - */ -export function firewall_drift(m) { - let t = sh_out('nft -t list table inet fw4 2>/dev/null') ?? ''; - if (t == '') - return 'off'; - if (sync_firewall(m, true)) - return 'changed'; - // Named rules show up in fw4's ruleset as comments. - let names = []; - for (let id, srv in m.servers) - if (srv.private_key && srv.enabled) - push(names, `Dawnline-${srv.ifname}`); - if (m.settings.portal_enabled) - push(names, 'Dawnline-Portal'); - for (let n in names) - if (index(t, `${n}"`) < 0) - return 'not loaded'; - return null; -}; - -/** For the watchdog: LuCI's web server should hand portal links to the portal, but does not. */ -export function uhttpd_drift(m) { - if (!(m.settings.portal_enabled && core.portal_public_port(m) == 443 && m.settings.portal_port != 443)) - return false; - let c = cursor(); - c.load('uhttpd'); - let cur = c.get('uhttpd', 'main', 'error_page'); - // Someone else's error page is theirs: Health explains, nothing to repair. - return cur == null || (cur == LAN_CGI_URL && !stat(LAN_CGI)); -}; - -/** One `ipproto

sport lookup main` rule per listening port and family. */ -function sync_reply_routes(m) { - let want = []; - if (m.settings.portal_enabled) { - push(want, `tcp ${+m.settings.portal_port}`); - if (core.portal_http(m)) - push(want, `tcp ${core.portal_http_port(m)}`); - } - for (let id, srv in m.servers) - if (srv.private_key && srv.enabled && +srv.port) - push(want, `udp ${+srv.port}`); - want = uniq(want); - for (let fam in [ '-4', '-6' ]) { - let have = []; - for (let line in split(sh_out(`ip ${fam} rule show priority ${PREF_REPLY} 2>/dev/null`) ?? '', '\n')) { - let mm = match(line, /ipproto (tcp|udp) sport (\d+) lookup main/); - if (mm) - push(have, `${mm[1]} ${mm[2]}`); - } - for (let h in have) - if (index(want, h) < 0) - sh(`ip ${fam} rule del priority ${PREF_REPLY} ipproto ${split(h, ' ')[0]} sport ${split(h, ' ')[1]} lookup main 2>/dev/null`); - for (let w in want) - if (index(have, w) < 0) - sh(`ip ${fam} rule add priority ${PREF_REPLY} ipproto ${split(w, ' ')[0]} sport ${split(w, ' ')[1]} lookup main`); - } -} - /** * Keep the "like a home device" path and the resolver in step (agent tick). * Cheap when nothing changed; rebuilds the access table when the netns * address appears, moves or goes away (the guard allows DNS to it). */ export function sync_loop(m, usage, force) { - m ??= core.load(); - let before = `${loop.client_dns()} ${loop.resolver_target().mode}`; - let p = loop.ensure(m, force); - loop.sync_resolver(m); - sync_reply_routes(m); - if (`${loop.client_dns()} ${loop.resolver_target().mode}` != before) { - usage ??= core.load_usage(); - rebuild_nft(m, access_sets(m, usage, states_for(m, usage))); - sync_hosts(m); - } + let p = with_lock('apply', () => { + let mm = core.load(); + let before = `${loop.client_dns()} ${loop.resolver_target().mode}`; + let lp = loop.ensure(mm, force); + loop.sync_resolver(mm); + fw.sync_reply_routes(mm); + if (`${loop.client_dns()} ${loop.resolver_target().mode}` != before) + locked_sync(mm, usage ?? core.load_usage(), true); + return lp; + }); + loop.remember(p); return p; }; -/** Every personal code is a word code; older random ones are replaced (their links stop working). */ -function ensure_word_codes() { - let c = cursor(); - c.load('dawnline'); - let changed = false; - c.foreach('dawnline', 'person', (s) => { - if (s.code != null && !match(s.code, core.WORD_CODE)) { - c.set('dawnline', s['.name'], 'code', core.new_code()); - c.delete('dawnline', s['.name'], 'words'); - changed = true; - } - }); - if (changed) { - c.commit('dawnline'); - system('chmod 600 /etc/config/dawnline'); - log('Personal links', 'moved to word codes'); - } -} +/* ---------- entry points ---------- */ /** Full reconcile: router configuration + runtime state. */ export function apply(opts) { opts ??= {}; - ensure_word_codes(); - let m = core.load(); - let usage = core.load_usage(); - let l = lock('reconcile'); - let net = sync_network(m); - let fw = sync_firewall(m); - sync_uhttpd(m); - let lp = loop.ensure(m, true); - loop.sync_resolver(m); - sync_reply_routes(m); - let states = states_for(m, usage); - rebuild_nft(m, access_sets(m, usage, states)); - unlock(l); - let r = sync(m, usage); - return { network: net, firewall: fw, like_home: lp.error ? { error: lp.error } : !lp.off, peers: r.peers }; + migrate.run(); + let r = with_lock('apply', () => { + let m = core.load(); + let usage = core.load_usage(); + let network = netifd.sync(m); + let firewall = fw.sync(m); + let lp = loop.ensure(m, true); + loop.sync_resolver(m); + fw.sync_reply_routes(m); + let s = locked_sync(m, usage, true); + ensure_dir(RUN_DIR); + write_file(NET_SIG, net_signature(m), 0o644); + return { network, firewall, lp, peers: s.peers }; + }); + loop.remember(r.lp); + return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: r.lp.error } : !r.lp.off, peers: r.peers }; }; /** Remove everything Dawnline created (used by the uninstaller). */ export function teardown() { - let m = core.load(); - loop.remove(); - unlink(loop.RESOLVER.conf); - m.servers = {}; - m.settings.portal_enabled = false; - sync_network(m); - sync_firewall(m); - sync_uhttpd(m); - sync_reply_routes(m); - remove_nft(); - unlink(HOSTS_FILE); - system('killall -HUP dnsmasq 2>/dev/null'); + with_lock('apply', () => { + let m = core.load(); + loop.remove(); + unlink(loop.RESOLVER.conf); + m.servers = {}; + m.settings.portal_enabled = false; + netifd.sync(m); + fw.sync(m); + fw.sync_reply_routes(m); + nft.remove(); + unlink(HOSTS_FILE); + unlink(NET_SIG); + system('killall -HUP dnsmasq 2>/dev/null'); + }); + migrate.uhttpd(); // The agent's heartbeat check. if (system('grep -qs /usr/libexec/dawnline/heartbeat /etc/crontabs/root') == 0) system("sed -i '\\#/usr/libexec/dawnline/heartbeat#d' /etc/crontabs/root; /etc/init.d/cron restart >/dev/null 2>&1"); diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc new file mode 100644 index 0000000..c4e365b --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc @@ -0,0 +1,493 @@ +// Dawnline — the AmneziaWG core: keys, disguise (obfuscation), client +// configurations (.conf, AmneziaVPN key), the netifd options of a server's +// tunnel, its peers (`awg syncconf`, no restart), live counters and what the +// watchdog and Health check about it. Plain WireGuard is AmneziaWG with the +// disguise off. + +import { readfile, stat, unlink } from 'fs'; +import { + q, sh, sh_out, rand_int, rand_bytes, valid_key, ensure_dir, write_file, read_json, write_json, lock, unlock, + slog, iface_status, DATA_DIR, RUN_DIR +} from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as net from 'dawnline.net'; + +/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_`. */ +export const OBF_CONF = { + jc: 'Jc', jmin: 'Jmin', jmax: 'Jmax', s1: 'S1', s2: 'S2', s3: 'S3', s4: 'S4', + h1: 'H1', h2: 'H2', h3: 'H3', h4: 'H4', i1: 'I1', i2: 'I2', i3: 'I3', i4: 'I4', i5: 'I5', + header_protection_key: 'HeaderProtectionKey', content_padding_addition: 'ContentPaddingAddition', + rekey_after_time: 'RekeyAfterTime', rekey_timeout: 'RekeyTimeout', reject_after_time: 'RejectAfterTime', + keepalive_timeout: 'KeepaliveTimeout', max_handshake_attempts: 'MaxHandshakeAttempts', + random_trailers: 'RandomTrailers', disable_cookies: 'DisableCookies', +}; + +const TOOL = '/usr/bin/awg', PROTO = '/lib/netifd/proto/amneziawg.sh'; +/** The packages AmneziaWG comes in (the Components tab installs them). */ +const PACKAGES = [ 'kmod-amneziawg', 'amneziawg-tools' ]; + +/** netifd knows the amneziawg protocol (it reads the proto scripts when it starts). */ +function proto_handler() { + try { + return 'amneziawg' in (json(sh_out('ubus call network get_proto_handlers 2>/dev/null') || '{}') ?? {}); + } + catch (e) { + return false; + } +} + +/** + * What of AmneziaWG is on the router: + * tools the awg tool and the netifd protocol script (amneziawg-tools) + * kmod the kernel module, loaded or on disk for the running kernel + * loaded the module is loaded + * handler netifd lists the amneziawg protocol + * missing packages that are not installed; ok: everything is in place + */ +export function state() { + let tools = stat(TOOL) != null && stat(PROTO) != null; + let loaded = stat('/sys/module/amneziawg') != null; + let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? ''); + let kmod = loaded || (rel != '' && stat(`/lib/modules/${rel}/amneziawg.ko`) != null); + let handler = tools && proto_handler(); + let missing = filter(PACKAGES, (p) => p == 'kmod-amneziawg' ? !kmod : !tools); + return { tools, kmod, loaded, handler, missing, ok: !length(missing) && loaded && handler }; +}; + +/** The kernel module and the awg tool are on the router. */ +export function installed() { + let s = state(); + return s.tools && s.kmod; +}; + +/* ---------- keys ---------- */ + +export function genkey() { + return sh_out('awg genkey'); +}; + +export function pubkey(priv) { + if (!valid_key(priv)) + return null; + return sh_out(`printf %s ${q(priv)} | awg pubkey`); +}; + +/** A preshared key is 32 random bytes: no tool needed (`awg genpsk` does the same). */ +export function genpsk() { + return b64enc(rand_bytes(32)); +}; + +/** + * Keys for a new device. With `public_key` (made in the browser) the private + * key never reaches the router. Never without a preshared key. + */ +export function new_keys(public_key) { + let psk = genpsk(); + if (!valid_key(psk)) + die('Key generation failed (no random data).'); + if (public_key) { + if (!valid_key(public_key)) + die('Invalid public key.'); + return { public_key, preshared_key: psk }; + } + let priv = genkey(), pub = pubkey(priv); + if (!pub) + die('Key generation failed (is amneziawg-tools installed?).'); + return { private_key: priv, public_key: pub, preshared_key: psk }; +}; + +/** A server's own key pair (set up once, on the server). */ +export function server_keys() { + let priv = genkey(), pub = pubkey(priv); + if (!pub) + die('Key generation failed (is amneziawg-tools installed?).'); + return { private_key: priv, public_key: pub }; +}; + +/* ---------- obfuscation ---------- */ + +const OBF_SPEC = { jc: [ 0, 10 ], jmin: [ 64, 1024 ], jmax: [ 64, 1024 ], s1: [ 0, 64 ], s2: [ 0, 64 ], s3: [ 0, 64 ], s4: [ 0, 32 ] }; + +function rand_h(used) { + for (let i = 0; i < 50; i++) { + let v = rand_int(5, 2147483647); + if (!used[v]) { + used[v] = true; + return `${v}`; + } + } +} + +/** + * What the installed AmneziaWG can do, from the netifd protocol script (the + * options it passes on) and the `awg` tool (the keys it accepts): + * v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0) + * v3 — header protection, trailers, padding, timing (AWG 3.1) + */ +export function caps() { + let script = readfile('/lib/netifd/proto/amneziawg.sh') ?? ''; + let tool = sh_out("grep -a -o -m1 'HeaderProtectionKey' /usr/bin/awg 2>/dev/null") ?? ''; + let v2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0; + let v3 = v2 && index(script, 'awg_header_protection_key') >= 0 && tool != ''; + return { v2, v3 }; +}; + +/** First junk packet shaped like a DNS answer (AmneziaVPN's own default for 3.1). */ +const DNS_MIMIC = ''; + +/** + * Generate obfuscation parameters for a method: + * off plain WireGuard-compatible packets + * standard junk packets and random headers (any AmneziaWG client) + * strong more and larger junk (any AmneziaWG client) + * max AmneziaWG 3.1: protected headers, random trailers, padding, + * jittered timers and a DNS-like first packet — the values + * AmneziaVPN itself uses for 3.1 servers + */ +export function obf_preset(name) { + if (name == 'max') + return { + jc: `${rand_int(4, 6)}`, jmin: '10', jmax: '50', + s1: '12', s2: '12', s3: '12', s4: '12', + h1: '1', h2: '2', h3: '3', h4: '4', + i1: DNS_MIMIC, + header_protection_key: sh_out('awg genkey'), + content_padding_addition: '10-100', + rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180', + keepalive_timeout: '5-15', max_handshake_attempts: '15-20', + random_trailers: 'on', disable_cookies: 'on', + }; + if (name == 'off') + return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }; + let strong = name == 'strong'; + let o = {}; + o.jc = `${strong ? rand_int(6, 10) : rand_int(3, 6)}`; + let jmin = rand_int(64, strong ? 128 : 96); + o.jmin = `${jmin}`; + o.jmax = `${jmin + rand_int(strong ? 200 : 32, strong ? 600 : 160)}`; + let s1 = rand_int(15, 64), s2 = rand_int(15, 64); + while (s1 + 56 == s2) + s2 = rand_int(15, 64); + o.s1 = `${s1}`; + o.s2 = `${s2}`; + let used = {}; + for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) + o[k] = rand_h(used); + return o; +}; + +export function obf_errors(o) { + let errs = []; + for (let k, r in OBF_SPEC) { + let v = o[k]; + if (v == null || v == '') + continue; + if (!match(v, /^[0-9]+$/) || +v < r[0] || +v > r[1]) { + if (!(v == '0' && (k == 'jmin' || k == 'jmax'))) + push(errs, `${k}=${v} (${r[0]}-${r[1]})`); + } + } + if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax) + push(errs, 'jmin > jmax'); + if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2) + push(errs, 's1 + 56 = s2'); + let hs = {}; + for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) { + let v = o[k]; + if (v == null || v == '') + continue; + if (!match(v, /^[0-9]+(-[0-9]+)?$/)) + push(errs, `${k} must be a number or range`); + else if (hs[v]) + push(errs, 'h1-h4 must be distinct'); + hs[v] = true; + } + return errs; +}; + + + +export function allowed_ips(m, srv, p) { + if (p.access == 'lan') { + let nets = core.person_home(srv, p).nets; + // With devices reaching each other, the whole tunnel network (the router's + // address is in it); otherwise only the router's own address. + let a = core.server_address(srv); + if (srv.device_mesh && srv.subnet) + push(nets, srv.subnet); + else if (a) + push(nets, `${a}/32`); + // The resolver address must be reachable through the tunnel too (not the fallback). + let dns = core.client_dns(m, srv, p)[0]; + if (dns) + push(nets, `${dns}/32`); + return net.collapse(nets); + } + return [ '0.0.0.0/0', '::/0' ]; +}; + + +/** True when the obfuscation settings change nothing on the wire (plain WireGuard). */ +export function obf_neutral(o) { + for (let k in core.OBF_KEYS) { + let v = o?.[k]; + if (v == null || v == '') + continue; + let want = { h1: '1', h2: '2', h3: '3', h4: '4' }[k] ?? '0'; + if (`${v}` != want) + return false; + } + return true; +}; + +export function client_config(m, dev) { + let p = m.people[dev.person]; + let srv = p ? m.servers[p.server] : null; + if (!srv) + return null; + let host = core.endpoint_host(m, srv); + let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host; + let allowed = allowed_ips(m, srv, p); + let dns = core.client_dns(m, srv, p); + let lines = [ '[Interface]' ]; + push(lines, `PrivateKey = ${dev.private_key || ''}`); + push(lines, `Address = ${dev.address}/32`); + if (length(dns)) + push(lines, `DNS = ${join(', ', dns)}`); + push(lines, `MTU = ${srv.mtu}`); + // "Off" is plain WireGuard: neutral values (no junk, H1-H4 = 1-4) are left + // out, so any WireGuard app accepts the file. + if (!obf_neutral(srv.obf)) + for (let k in core.OBF_KEYS) + if (srv.obf[k] != null && srv.obf[k] != '') + push(lines, `${OBF_CONF[k]} = ${srv.obf[k]}`); + push(lines, '', '[Peer]'); + push(lines, `PublicKey = ${srv.public_key}`); + if (dev.preshared_key) + push(lines, `PresharedKey = ${dev.preshared_key}`); + push(lines, `AllowedIPs = ${join(', ', allowed)}`); + push(lines, `Endpoint = ${ep}:${srv.port}`); + if (srv.keepalive > 0) + push(lines, `PersistentKeepalive = ${srv.keepalive}`); + return { + name: dev.name, + person: p.name, + server: srv.name, + filename: `${substr(replace(lc(p.id + '-' + dev.name), /[^a-z0-9]+/g, '-'), 0, 15)}.conf`, + conf: join('\n', lines) + '\n', + has_private_key: dev.private_key != '', + amnezia: { + host, + port: srv.port, + mtu: `${srv.mtu}`, + dns, + allowed_ips: allowed, + client_ip: dev.address, + client_priv_key: dev.private_key, + client_pub_key: dev.public_key, + psk_key: dev.preshared_key, + server_pub_key: srv.public_key, + persistent_keep_alive: `${srv.keepalive}`, + obfuscation: srv.obf, + }, + }; +}; + + + + +/* ---------- the server's tunnel ---------- */ + +/** netifd options of the server's interface (proto amneziawg). */ +export function netifd_options(srv) { + let addr = core.server_address(srv); + let prefix = split(srv.subnet, '/')[1]; + let o = { + proto: 'amneziawg', + private_key: srv.private_key, + listen_port: srv.port, + addresses: [ `${addr}/${prefix}` ], + mtu: srv.mtu, + }; + for (let k in core.OBF_KEYS) + o[`awg_${k}`] = srv.obf[k]; + return o; +}; + +/** Push the peer list of every server to the kernel without restarting it. */ +export function sync_peers(m, states) { + ensure_dir(RUN_DIR); + let res = {}; + for (let id, srv in m.servers) { + // Only Dawnline's own interfaces: never another tunnel of the same name (core.tunnels). + if (!srv.enabled || !length(core.tunnels(srv))) + continue; + if (system(`awg show ${q(srv.ifname)} public-key >/dev/null 2>&1`) != 0) { + res[id] = 'down'; + continue; + } + let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ]; + for (let did, d in m.devices) { + let p = m.people[d.person]; + if (!p || p.server != id || d.disabled || states[p.id] != 'active' || !d.public_key || !d.address) + continue; + push(lines, '[Peer]', `PublicKey = ${d.public_key}`); + if (d.preshared_key) + push(lines, `PresharedKey = ${d.preshared_key}`); + push(lines, `AllowedIPs = ${d.address}/32`, ''); + } + let f = `${RUN_DIR}/${srv.ifname}.conf`; + write_file(f, join('\n', lines)); + let r = sh(`awg syncconf ${q(srv.ifname)} ${f}`); + unlink(f); + res[id] = r.code == 0 ? 'ok' : trim(r.out); + if (r.code != 0) + slog('awg', 'error', "couldn't load devices into the tunnel", trim(r.out), srv.name); + } + return res; +}; + +/** + * Parse `awg show all dump`. Returns { ok, ifaces: { ifname: {...} }, peers: { pubkey: {...} } }. + * Interface lines have many fields (AmneziaWG adds obfuscation values); peer + * lines always have 9. The tool fails when any one interface can't be read, + * but still prints the others: those are kept and `ok` is false, so only the + * interfaces listed in `ifaces` are known. + */ +export function dump() { + let r = sh('awg show all dump'); + let out = { ok: r.code == 0, ifaces: {}, peers: {} }; + for (let line in split(r.out, '\n')) { + let f = split(line, '\t'); + if (length(f) == 9) { + let ep = f[3] == '(none)' ? '' : f[3]; + out.peers[f[1]] = { + ifname: f[0], + endpoint: ep, + handshake: +f[5], + rx: +f[6], + tx: +f[7], + }; + } + else if (length(f) >= 5) { + out.ifaces[f[0]] = { public_key: f[2], port: +f[3] }; + } + } + return out; +}; + +/** Is the server's tunnel up and listening (for status and Overview). */ +export function server_state(srv) { + let st = iface_status(srv.ifname); + return { up: !!st?.up, uptime: st?.uptime ?? 0 }; +}; + +/* ---------- watchdog ---------- */ + +/** Why a tunnel is down, from netifd and the last related syslog lines. */ +export function iface_errors(ifname) { + let s = iface_status(ifname); + let errs = map(s?.errors ?? [], (e) => e.code + (length(e.data ?? []) ? ` (${join(' ', e.data)})` : '')); + // Only what explains a failure, not the ordinary "is now up/down" lines. + let lines = sh_out(`logread -l 400 2>/dev/null | grep -E ${q(`${ifname}|amneziawg`)} | grep -iE 'error|fail|invalid|unrecogni|cannot|unable|not found|refused|denied' | tail -n 6`); + return join('\n', filter([ length(errs) ? `netifd: ${join(', ', errs)}` : null, lines ], (x) => x)); +}; + +/** + * What the watchdog looks at for AmneziaWG (see dawnline.watchdog): + * AmneziaWG itself, then every running server's tunnel. `ctx.udp_listening`, + * `ctx.reapply` and `ctx.owner` (dawnline.netifd) come from the watchdog + * (ops, apply and netifd import this module). + */ +export function probes(m, ctx) { + let out = []; + let srvs = filter(values(m.servers), (x) => x.enabled && x.private_key); + if (!length(srvs)) + return out; + // AmneziaWG itself first: without it no tunnel can run (they come back on the next pass). + // Missing packages and an unknown protocol are reported once; only the module can be loaded here. + let st = state(); + let base = { id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', back: 'is ready again' }; + if (!st.tools || !st.kmod) { + push(out, { ...base, ok: false, repair: null, + problem: `${st.tools ? "kernel module isn't" : "isn't"} installed: no tunnel can run — install it in Dawnline → Components`, + detail: () => `Missing: ${join(', ', st.missing)}.` }); + return out; + } + push(out, { ...base, ok: st.loaded && st.handler, + problem: !st.loaded ? "kernel module isn't loaded" : "isn't known to the network service — restart the network or reboot", + detail: !st.loaded + ? () => sh_out("modprobe amneziawg 2>&1; dmesg 2>/dev/null | grep -i amneziawg | grep -iE 'error|fail|invalid|unknown|disagrees|taint' | tail -n 4") + : () => 'netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.', + repair: !st.loaded ? { what: 'loading it', run: () => system('modprobe amneziawg >/dev/null 2>&1') } : null, + }); + // Without the protocol handler ifup cannot work: the tunnels are not probed (or restarted) one by one. + if (st.loaded && !st.handler) + return out; + for (let srv in srvs) { + // A tunnel Dawnline may not set up (dawnline.netifd) is reported, never restarted: + // an interface of the same name that isn't Dawnline's may be your LAN. + let own = core.valid_ifname(srv.ifname) ? ctx.owner?.(srv.ifname) : null; + let why = srv.blocked ?? (!core.valid_ifname(srv.ifname) ? `has an invalid interface name "${srv.ifname}"` + : own != null && own != srv.id ? `can't use the network interface ${srv.ifname}: it exists and isn't Dawnline's` : null); + if (why) { + push(out, { + id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: false, repair: null, + problem: why, back: 'AmneziaWG is running again', + detail: () => 'Choose another interface name in the server settings.', + }); + continue; + } + let s = iface_status(srv.ifname); + let up = !!s?.up; + push(out, { + id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: up && ctx.udp_listening(srv.port), + problem: !s ? 'AmneziaWG is missing from the router' : !up ? "AmneziaWG isn't running" : `AmneziaWG isn't accepting connections on port ${srv.port}`, + back: `AmneziaWG is running again · accepting connections on port ${srv.port}`, + detail: () => iface_errors(srv.ifname), + repair: s ? { what: 'restarting it', run: () => system(`ifup ${q(srv.ifname)}`) } : { what: 'setting it up again', run: ctx.reapply }, + }); + } + return out; +}; + +/* ---------- issued configurations ---------- */ + +const ISSUED = `${DATA_DIR}/issued.json`; + +function fnv32(str) { + let h = 2166136261; + for (let i = 0; i < length(str); i++) + h = ((h ^ ord(str, i)) * 16777619) & 0xffffffff; + return sprintf('%08x', h); +} + +/** What a device holds, minus its private key: changes when it must import again. */ +export function config_fingerprint(m, dev) { + let c = dev ? client_config(m, dev) : null; + return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, /^PrivateKey/)))) : null; +}; + +/** Device id → fingerprint of the configuration last shown or downloaded. */ +export function issued() { + return read_json(ISSUED, {}); +}; + +/** Remember that a device was just given its current configuration. */ +export function mark_issued(m, id) { + let fp = config_fingerprint(m, m.devices[id]); + if (!fp) + return; + let l = lock('issued'); + let all = issued(); + if (all[id] != fp) { + all[id] = fp; + for (let k in keys(all)) + if (!m.devices[k]) + delete all[k]; + ensure_dir(DATA_DIR, 0o700); + write_json(ISSUED, all, 0o600); + } + unlock(l); +}; + diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg_builds.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg_builds.uc new file mode 100644 index 0000000..5e556cc --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg_builds.uc @@ -0,0 +1,55 @@ +// Dawnline — where AmneziaWG comes from: the awg-openwrt projects publish +// builds per OpenWrt release and target (the kernel module must match the +// firmware). Used by the updater and the Components RPCs. + +import { readfile } from 'fs'; +import { connect } from 'ubus'; +import * as pkg from 'dawnline.pkg'; + +export const SOURCES = { + slava: { repo: 'Slava-Shchipunov/awg-openwrt', label: 'Slava-Shchipunov' }, + grey: { repo: '2Grey/awg-openwrt', label: '2Grey' }, +}; +/** Tried in this order when no build is chosen. */ +export const ORDER = [ 'slava', 'grey' ]; +export const PKGS = [ 'kmod-amneziawg', 'amneziawg-tools', 'luci-proto-amneziawg' ]; +export const RU = 'luci-i18n-amneziawg-ru'; + +/** + * This firmware as the builds name it: { tag: 'v24.10.6', postfix: + * '_v24.10.6_aarch64_cortex-a53_mediatek_filogic', ext }, or null. + */ +export function firmware() { + let u = connect(); + let b = u?.call('system', 'board') ?? {}; + u?.disconnect(); + let rel = b.release ?? {}; + let target = split(rel.target ?? '', '/'); + let arch = rel.arch ?? match(readfile('/etc/openwrt_release') ?? '', /DISTRIB_ARCH='([^']*)'/)?.[1]; + if (!rel.version || length(target) != 2 || !arch) + return null; + return { tag: `v${rel.version}`, postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`, ext: pkg.ext() }; +}; + +/** The file name of a package in a build. */ +export function asset(fw, name) { + return `${name}${fw.postfix}.${fw.ext}`; +}; + +/** The same firmware, another release of its series (v24.10.6 → v24.10.8). */ +export function for_tag(fw, tag) { + return { ...fw, tag, postfix: replace(fw.postfix, fw.tag, tag) }; +}; + +/** AmneziaWG generation of a tools version: 3.x packages carry 3.1, older ones (1.0.x) 2.0. */ +export function gen(version) { + return version == null ? null : match(version, /^3\./) ? '3.1' : '2.0'; +}; + +/** The installed AmneziaWG packages: { name: version | null }. */ +export function installed() { + let r = {}; + for (let p in PKGS) + r[p] = pkg.version(p); + return r; +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc new file mode 100644 index 0000000..21fe38e --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc @@ -0,0 +1,285 @@ +// Dawnline — backups (tar.gz of the config and its data files), restoring +// them, and the JSON export / import. Whatever comes back in is checked first: +// only Dawnline's own regular files, and servers that cannot take over one of +// the router's own interfaces or networks. + +import { readfile, stat, unlink, lsdir } from 'fs'; +import { cursor } from 'uci'; +import { + q, sh, ensure_dir, read_json, write_json, write_file, file_exists, rand_hex, lock, unlock, DATA_DIR, RUN_DIR, VERSION +} from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as live from 'dawnline.live'; +import * as apply from 'dawnline.apply'; +import * as net from 'dawnline.net'; +import * as health from 'dawnline.health'; + +const BACKUP_DIR = `${DATA_DIR}/backups`; +const KEEP_BACKUPS = 10; +const NAME = /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/; +/** What a backup holds (paths inside the archive, relative to /). */ +const FILES = [ 'etc/config/dawnline', 'etc/dawnline/usage.json', 'etc/dawnline/events.json' ]; +/** The unpacked size a backup may have (the upload itself is limited to 4 MB). */ +const MAX_UNPACKED = 16 * 1024 * 1024; + +/* ---------- checking a configuration before it is used ---------- */ + +/** + * What is wrong with the servers of a configuration about to replace the + * current one (cursor `c` holds it): each must have a valid, unique interface + * name that is not one of the router's own interfaces, a free subnet and a + * unique port. [] when it can be used. + */ +export function config_errors(c) { + let m = core.load(c); + let errs = []; + let nc = cursor(); + nc.load('network'); + let foreign = health.foreign_subnets(); + let internal = values(net.INTERNAL); + let ifnames = {}, ports = {}, subnets = []; + for (let id, srv in m.servers) { + let who = `Server ${srv.name}`; + for (let e in core.server_errors(m, srv, [ ...foreign, ...subnets ])) + push(errs, `${who}: ${e}`); + if (ifnames[srv.ifname]) + push(errs, `${who}: interface ${srv.ifname} is also used by ${ifnames[srv.ifname]}.`); + ifnames[srv.ifname] = srv.name; + let t = nc.get('network', srv.ifname); + if (index(internal, srv.ifname) >= 0 || (t != null && (t != 'interface' || nc.get('network', srv.ifname, '_dawnline') == null))) + push(errs, `${who}: ${srv.ifname} is one of the router's own network interfaces.`); + if (ports[srv.port]) + push(errs, `${who}: UDP ${srv.port} is also used by ${ports[srv.port]}.`); + ports[srv.port] = srv.name; + if (srv.subnet) + push(subnets, srv.subnet); + } + return errs; +}; + +/** Check the config file in `dir` (as /etc/config/dawnline would be); dies listing the problems. */ +function check_config_dir(dir) { + ensure_dir(`${dir}/.delta`, 0o700); + // Its own delta directory: changes staged in LuCI must not leak into the check. + let c = cursor(dir, `${dir}/.delta`); + if (!c.load('dawnline')) + die('The configuration in this file cannot be read.'); + let errs = config_errors(c); + if (length(errs)) + die(`This configuration can't be used: ${join(' ', errs)}`); +} + +/** A private scratch directory under RUN_DIR (the caller removes it). */ +function scratch(kind) { + ensure_dir(RUN_DIR); + let dir = `${RUN_DIR}/${kind}.${rand_hex(4)}`; + system(`rm -rf ${q(dir)}; mkdir -m 700 -p ${q(dir)}`); + return dir; +} + +/* ---------- backups ---------- */ + +export function backup_list() { + let out = []; + for (let f in lsdir(BACKUP_DIR) ?? []) { + let mm = match(f, NAME); + if (!mm) + continue; + let st = stat(`${BACKUP_DIR}/${f}`); + push(out, { name: f, created: st?.mtime ?? 0, size: st?.size ?? 0, reason: mm[3] ?? 'manual' }); + } + return sort(out, (a, b) => b.created - a.created); +}; + +/** + * Make a backup now; returns its name. The oldest beyond KEEP_BACKUPS are + * removed, except `keep` (the backup being restored, which must survive the + * backup made just before restoring it). + */ +export function backup_create(reason, keep) { + // Flush live counters first so the backup has current usage. + let u = read_json(`${RUN_DIR}/usage.json`, null); + if (u) + write_json(`${DATA_DIR}/usage.json`, u, 0o600); + live.persist_events(); + ensure_dir(BACKUP_DIR, 0o700); + let t = localtime(); + let tag = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? `-${reason}` : ''; + let name = sprintf('dawnline-%04d%02d%02d-%02d%02d%02d%s.tar.gz', t.year, t.mon, t.mday, t.hour, t.min, t.sec, tag); + let files = join(' ', map(filter(FILES, (f) => file_exists(`/${f}`)), q)); + let r = sh(`tar -czf ${q(BACKUP_DIR + '/' + name)} -C / ${files}`); + if (r.code != 0) + die(`Backup failed: ${trim(r.out)}`); + system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`); + let all = backup_list(); + let old = filter(all, (b) => b.name != keep && b.name != name); + let room = KEEP_BACKUPS - 1 - (length(old) < length(all) - 1 ? 1 : 0); + for (let i = room; i < length(old); i++) + unlink(`${BACKUP_DIR}/${old[i].name}`); + return name; +}; + +function backup_path(name) { + if (!match(name ?? '', NAME)) + die('Invalid backup name.'); + let p = `${BACKUP_DIR}/${name}`; + if (!file_exists(p)) + die('Backup not found.'); + return p; +} + +/** + * Validate an archive: only Dawnline's own files, all of them regular files + * (no links, devices or directories), within a sane unpacked size. + */ +function check_archive(path) { + let r = sh(`tar -tvzf ${q(path)}`); + if (r.code != 0) + die('Not a valid backup archive.'); + let has_config = false, total = 0; + for (let line in split(trim(r.out), '\n')) { + let f = split(trim(line), /[ \t]+/); + let name = replace(f[length(f) >= 6 ? 5 : length(f) - 1] ?? '', /^\.?\//, ''); + // "-rw------- root/root 1234 2026-01-01 12:00:00 etc/config/dawnline"; links show "a -> b". + if (substr(line, 0, 1) != '-' || index(line, ' -> ') >= 0 || index(line, ' link to ') >= 0) + die(`Unexpected entry in backup: ${name}`); + if (index(FILES, name) < 0) + die(`Unexpected file in backup: ${name}`); + total += +(f[2] ?? 0) || 0; + if (name == 'etc/config/dawnline') + has_config = true; + } + if (!has_config) + die('Backup does not contain /etc/config/dawnline.'); + if (total > MAX_UNPACKED) + die('Backup is too large.'); +} + +/** Put the files unpacked in `dir` in place, under the config lock. */ +function install_files(dir) { + ensure_dir(DATA_DIR, 0o700); + let l = lock('config'); + for (let f in FILES) { + let data = readfile(`${dir}/${f}`); + if (data != null) + write_file(`/${f}`, data, 0o600); + } + unlock(l); + system('chmod 600 /etc/config/dawnline'); +} + +export function backup_restore(name, path) { + path ??= backup_path(name); + check_archive(path); + let dir = scratch('restore'); + try { + let r = sh(`tar -xzf ${q(path)} -C ${q(dir)} ${join(' ', map(FILES, q))} 2>/dev/null; test -f ${q(dir + '/etc/config/dawnline')}`); + if (r.code != 0) + die('Not a valid backup archive.'); + check_config_dir(`${dir}/etc/config`); + backup_create('pre-restore', name); + install_files(dir); + } + catch (e) { + system(`rm -rf ${q(dir)}`); + die(e.message); + } + system(`rm -rf ${q(dir)}`); + // Live counters must follow the restored file. + unlink(`${RUN_DIR}/usage.json`); + unlink(`${RUN_DIR}/events.json`); + return apply.apply(); +}; + +export function backup_delete(name) { + unlink(backup_path(name)); + return true; +}; + +export function backup_read(name) { + return b64enc(readfile(backup_path(name))); +}; + +export function backup_upload(data_b64) { + let data = b64dec(data_b64 ?? ''); + if (!data || length(data) > 4 * 1024 * 1024) + die('Upload is empty or too large.'); + ensure_dir(RUN_DIR); + let tmp = `${RUN_DIR}/upload.tar.gz`; + write_file(tmp, data); + let res; + try { + res = backup_restore(null, tmp); + } + catch (e) { + unlink(tmp); + die(e.message); + } + unlink(tmp); + return res; +}; + +/* ---------- export / import (JSON) ---------- */ + +export function export_json() { + let c = cursor(); + c.load('dawnline'); + let sections = []; + c.foreach('dawnline', null, (s) => { + let o = { '.type': s['.type'], '.name': s['.name'] }; + for (let k, v in s) + if (substr(k, 0, 1) != '.') + o[k] = v; + push(sections, o); + }); + return { format: 'dawnline', version: VERSION, exported: time(), sections }; +}; + +/** An export as /etc/config/dawnline text; dies on anything that is not one. */ +function export_to_uci(data) { + if (type(data) != 'object' || data.format != 'dawnline' || type(data.sections) != 'array') + die('Not a Dawnline export.'); + let types = { settings: true, server: true, person: true, device: true, service: true, circle: true }; + let esc = (x) => replace(`${x}`, "'", "'\\''"); + let lines = []; + for (let s in data.sections) { + if (type(s) != 'object' || !types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/)) + die(`Invalid section ${s?.['.name']}.`); + push(lines, `config ${s['.type']} '${s['.name']}'`); + for (let k, v in s) { + if (substr(k, 0, 1) == '.') + continue; + if (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array')) + die(`Invalid option ${k}.`); + if (type(v) == 'array') + for (let x in v) { + if (type(x) != 'string') + die(`Invalid option ${k}.`); + push(lines, `\tlist ${k} '${esc(x)}'`); + } + else + push(lines, `\toption ${k} '${esc(v)}'`); + } + push(lines, ''); + } + return join('\n', lines); +} + +export function import_json(data) { + let text = export_to_uci(data); + let dir = scratch('import'); + try { + write_file(`${dir}/dawnline`, text, 0o600); + check_config_dir(dir); + } + catch (e) { + system(`rm -rf ${q(dir)}`); + die(e.message); + } + system(`rm -rf ${q(dir)}`); + backup_create('pre-import'); + let l = lock('config'); + write_file('/etc/config/dawnline', text, 0o600); + unlock(l); + return apply.apply(); +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc index 44e1786..9f48802 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc @@ -1,38 +1,34 @@ -// Dawnline — data model: reads /etc/config/dawnline, validates and mutates it, -// allocates addresses, generates keys and renders client configurations. +// Dawnline — data model: reads /etc/config/dawnline, validates and mutates it +// and allocates addresses. Nothing here knows how the tunnel works: dawnline.awg +// renders AmneziaWG configurations and runs the tunnels. import { cursor } from 'uci'; -import { readfile } from 'fs'; import { - q, sh, sh_out, valid_name, valid_key, valid_host, valid_date, slugify, - parse_cidr, cidr_str, cidr_overlaps, int2ip, ip2int, in_cidr, rand_token, rand_hex, rand_int, rand_bytes, - date_end, month_key, read_json, write_json, ensure_dir, lock, unlock, DATA_DIR, RUN_DIR, uniq + valid_name, valid_key, valid_host, valid_date, slugify, parse_cidr, cidr_overlaps, int2ip, ip2int, + rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq } from 'dawnline.util'; import * as net from 'dawnline.net'; -import * as loop from 'dawnline.loop'; +import { policy as updates_policy } from 'dawnline.updates'; export const CONFIG = 'dawnline'; +/** + * Servers whose network interface Dawnline may not set up (the name belongs + * to an interface it did not create, or is invalid): { id: why }. Written by + * dawnline.netifd; such a server has no tunnel anywhere (firewall, access + * table, "like a home device"), so nothing of Dawnline lands on that interface. + */ +export const BLOCKED = `${RUN_DIR}/netifd-blocked.json`; export const ACCESS = [ 'lan', 'internet', 'both' ]; export const KINDS = [ 'computer', 'phone', 'tablet', 'router', 'other' ]; /** Devices of different people reaching each other: never, everyone with home access, or within a circle. */ export const MESH = [ 'off', 'all', 'circles' ]; /** Circle colours (index into the admin palette). */ export const CIRCLE_COLORS = 8; +/** AmneziaWG obfuscation options stored on a server (netifd uses `awg_`; dawnline.awg renders them). */ export const OBF_KEYS = [ 'jc', 'jmin', 'jmax', 's1', 's2', 's3', 's4', 'h1', 'h2', 'h3', 'h4', 'i1', 'i2', 'i3', 'i4', 'i5', // AmneziaWG 3.x 'header_protection_key', 'content_padding_addition', 'rekey_after_time', 'rekey_timeout', 'reject_after_time', 'keepalive_timeout', 'max_handshake_attempts', 'random_trailers', 'disable_cookies' ]; - -/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_`. */ -export const OBF_CONF = { - jc: 'Jc', jmin: 'Jmin', jmax: 'Jmax', s1: 'S1', s2: 'S2', s3: 'S3', s4: 'S4', - h1: 'H1', h2: 'H2', h3: 'H3', h4: 'H4', i1: 'I1', i2: 'I2', i3: 'I3', i4: 'I4', i5: 'I5', - header_protection_key: 'HeaderProtectionKey', content_padding_addition: 'ContentPaddingAddition', - rekey_after_time: 'RekeyAfterTime', rekey_timeout: 'RekeyTimeout', reject_after_time: 'RejectAfterTime', - keepalive_timeout: 'KeepaliveTimeout', max_handshake_attempts: 'MaxHandshakeAttempts', - random_trailers: 'RandomTrailers', disable_cookies: 'DisableCookies', -}; - function toint(v, dflt) { if (v == null || v == '') return dflt; @@ -74,8 +70,6 @@ export function load(c) { settings: { portal_enabled: bool(s.portal_enabled, false), portal_port: toint(s.portal_port, 8443), - // Also answer on 443 from the internet (mobile networks often drop TLS on other ports). - portal_443: bool(s.portal_443, true), portal_host: s.portal_host ?? '', // More addresses for the same links (the main one is portal_host). portal_alt: filter(type(s.portal_alt) == 'array' ? s.portal_alt : s.portal_alt ? [ s.portal_alt ] : [], (x) => x != ''), @@ -95,6 +89,8 @@ export function load(c) { watchdog: bool(s.watchdog, true), // Second DNS for "home names" devices, used by the device when the tunnel is down. home_dns_fallback: s.home_dns_fallback == 'none' ? '' : (s.home_dns_fallback ?? '1.1.1.1'), + // Settings → Updates (automatic checks and updates of the components). + updates: updates_policy(s), // Raw retention values; dawnline.live policy() interprets them. retention: { log_keep_days: s.log_keep_days, log_max: s.log_max, log_category: s.log_category, @@ -109,6 +105,7 @@ export function load(c) { circles: {}, }; + let blocked = read_json(BLOCKED, {}); c.foreach(CONFIG, 'server', (r) => { let id = r['.name']; let srv = { @@ -137,13 +134,16 @@ export function load(c) { // (Older configs: device_mesh 0/1.) mesh: index(MESH, r.mesh) >= 0 ? r.mesh : (bool(r.device_mesh, true) ? 'all' : 'off'), enabled: bool(r.enabled, true), + // AmneziaWG disguise values, read by dawnline.awg. obf: {}, }; - // A person's own devices reach each other whenever the mesh is not off. - srv.device_mesh = srv.mesh != 'off'; for (let k in OBF_KEYS) if (r[k] != null && r[k] != '') srv.obf[k] = `${r[k]}`; + // A person's own devices reach each other whenever the mesh is not off. + srv.device_mesh = srv.mesh != 'off'; + if (blocked[id]) + srv.blocked = blocked[id]; m.servers[id] = srv; }); @@ -291,37 +291,43 @@ export function load_usage() { return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, { devices: {}, people: {} }); }; -/* ---------- keys ---------- */ +/* ---------- tunnels and addresses ---------- */ -export function genkey() { - return sh_out('awg genkey'); +/** A server's interface name: also a netifd section and an nft string, so nothing else. */ +export function valid_ifname(s) { + return type(s) == 'string' && match(s, /^[a-z][a-z0-9_]{0,11}$/) != null; }; -export function pubkey(priv) { - if (!valid_key(priv)) - return null; - return sh_out(`printf %s ${q(priv)} | awg pubkey`); -}; - -export function genpsk() { - return sh_out('awg genpsk'); -}; - -/* ---------- networks ---------- */ - -/** IPv4 subnets of the router's LAN zone (from netifd), as CIDR strings. */ -/** Router address inside the server subnet (first host). */ +/** Router address inside the AmneziaWG subnet (first host). */ export function server_address(srv) { let c = parse_cidr(srv.subnet); return c ? int2ip(c.first) : null; }; +/** + * The link a server's devices come in on: { ifname, subnet, address (the + * router's) }, as a list so the access table, firewall zone, "like a home + * device" and DNS treat every tunnel interface alike. None for a server + * without keys, subnet or a valid interface name (an imported config), or + * whose interface name is taken (BLOCKED). + */ +export function tunnels(srv) { + let c = srv?.private_key && !srv.blocked && valid_ifname(srv.ifname) ? parse_cidr(srv.subnet) : null; + return c ? [ { ifname: srv.ifname, subnet: srv.subnet, address: int2ip(c.first) } ] : []; +}; + +/** The server's tunnel link, or null. */ +export function tunnel(srv) { + return tunnels(srv)[0]; +}; + +/** The first free address in the server's subnet (the router has the first). */ export function alloc_address(m, srv) { - let c = parse_cidr(srv.subnet); - if (!c) + let t = parse_cidr(srv.subnet); + if (!t) return null; let used = {}; - used[c.first] = true; + used[t.first] = true; for (let id, d in m.devices) { let p = m.people[d.person]; if (p && p.server == srv.id) { @@ -330,124 +336,24 @@ export function alloc_address(m, srv) { used[n] = true; } } - for (let n = c.first + 1; n <= c.last; n++) + for (let n = t.first + 1; n <= t.last; n++) if (!used[n]) return int2ip(n); return null; }; -/* ---------- obfuscation ---------- */ - -const OBF_SPEC = { jc: [ 0, 10 ], jmin: [ 64, 1024 ], jmax: [ 64, 1024 ], s1: [ 0, 64 ], s2: [ 0, 64 ], s3: [ 0, 64 ], s4: [ 0, 32 ] }; - -function rand_h(used) { - for (let i = 0; i < 50; i++) { - let v = rand_int(5, 2147483647); - if (!used[v]) { - used[v] = true; - return `${v}`; - } - } -} - -/** - * What the installed AmneziaWG can do, from the netifd protocol script (the - * options it passes on) and the `awg` tool (the keys it accepts): - * v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0) - * v3 — header protection, trailers, padding, timing (AWG 3.1) - */ -export function awg_caps() { - let script = readfile('/lib/netifd/proto/amneziawg.sh') ?? ''; - let tool = sh_out("grep -a -o -m1 'HeaderProtectionKey' /usr/bin/awg 2>/dev/null") ?? ''; - let v2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0; - let v3 = v2 && index(script, 'awg_header_protection_key') >= 0 && tool != ''; - return { v2, v3 }; -}; - -/** First junk packet shaped like a DNS answer (AmneziaVPN's own default for 3.1). */ -const DNS_MIMIC = ''; - -/** - * Generate obfuscation parameters for a method: - * off plain WireGuard-compatible packets - * standard junk packets and random headers (any AmneziaWG client) - * strong more and larger junk (any AmneziaWG client) - * max AmneziaWG 3.1: protected headers, random trailers, padding, - * jittered timers and a DNS-like first packet — the values - * AmneziaVPN itself uses for 3.1 servers - */ -export function obf_preset(name) { - if (name == 'max') - return { - jc: `${rand_int(4, 6)}`, jmin: '10', jmax: '50', - s1: '12', s2: '12', s3: '12', s4: '12', - h1: '1', h2: '2', h3: '3', h4: '4', - i1: DNS_MIMIC, - header_protection_key: genkey(), - content_padding_addition: '10-100', - rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180', - keepalive_timeout: '5-15', max_handshake_attempts: '15-20', - random_trailers: 'on', disable_cookies: 'on', - }; - if (name == 'off') - return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }; - let strong = name == 'strong'; - let o = {}; - o.jc = `${strong ? rand_int(6, 10) : rand_int(3, 6)}`; - let jmin = rand_int(64, strong ? 128 : 96); - o.jmin = `${jmin}`; - o.jmax = `${jmin + rand_int(strong ? 200 : 32, strong ? 600 : 160)}`; - let s1 = rand_int(15, 64), s2 = rand_int(15, 64); - while (s1 + 56 == s2) - s2 = rand_int(15, 64); - o.s1 = `${s1}`; - o.s2 = `${s2}`; - let used = {}; - for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) - o[k] = rand_h(used); - return o; -}; - -export function obf_errors(o) { - let errs = []; - for (let k, r in OBF_SPEC) { - let v = o[k]; - if (v == null || v == '') - continue; - if (!match(v, /^[0-9]+$/) || +v < r[0] || +v > r[1]) { - if (!(v == '0' && (k == 'jmin' || k == 'jmax'))) - push(errs, `${k}=${v} (${r[0]}-${r[1]})`); - } - } - if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax) - push(errs, 'jmin > jmax'); - if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2) - push(errs, 's1 + 56 = s2'); - let hs = {}; - for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) { - let v = o[k]; - if (v == null || v == '') - continue; - if (!match(v, /^[0-9]+(-[0-9]+)?$/)) - push(errs, `${k} must be a number or range`); - else if (hs[v]) - push(errs, 'h1-h4 must be distinct'); - hs[v] = true; - } - return errs; -}; - -/* ---------- client configuration ---------- */ +/* ---------- what clients get ---------- */ export function endpoint_host(m, srv) { return srv.endpoint || m.settings.portal_host || ''; }; /** - * DNS for a server's clients: the router's tunnel address, which never - * changes after setup. The router forwards each query where it belongs (the - * LAN's DNS, from the LAN side; or the plain resolver), so configurations on - * devices keep working when the LAN, its DNS or the netns address change. + * DNS for a server's clients: the router's address in the tunnel subnet, + * which never changes after setup. The router forwards each query where it + * belongs (the LAN's DNS, from the LAN side; or the plain resolver), so + * configurations on devices keep working when the LAN, its DNS or the netns + * address change. */ export function dns_list(m, srv) { if (!srv) @@ -459,10 +365,10 @@ export function dns_list(m, srv) { }; /** - * DNS written into a device's configuration. Home-only people keep their - * device's DNS unless they chose home names; then the first server is - * Dawnline's plain resolver (reached through the tunnel) and the second the - * fallback the device uses when the tunnel is down. + * DNS a device uses. Home-only people keep their device's DNS unless they + * chose home names; then the first server is Dawnline's plain resolver + * (reached through the tunnel) and the second the fallback the device uses + * when the tunnel is down. */ export function client_dns(m, srv, p) { if (p?.access != 'lan') @@ -500,132 +406,6 @@ export function person_circle(m, p) { return c && c.server == p.server ? c : null; }; -export function allowed_ips(m, srv, p) { - if (p.access == 'lan') { - let nets = person_home(srv, p).nets; - // With devices reaching each other, the whole tunnel network (the router's - // address is in it); otherwise only the router's own address. - let a = server_address(srv); - if (srv.device_mesh && srv.subnet) - push(nets, srv.subnet); - else if (a) - push(nets, `${a}/32`); - // The resolver address must be reachable through the tunnel too (not the fallback). - let dns = client_dns(m, srv, p)[0]; - if (dns) - push(nets, `${dns}/32`); - return net.collapse(nets); - } - return [ '0.0.0.0/0', '::/0' ]; -}; - -/** Everything a client needs; `conf` is the .conf text. */ -/** True when the obfuscation settings change nothing on the wire (plain WireGuard). */ -export function obf_neutral(o) { - for (let k in OBF_KEYS) { - let v = o?.[k]; - if (v == null || v == '') - continue; - let want = { h1: '1', h2: '2', h3: '3', h4: '4' }[k] ?? '0'; - if (`${v}` != want) - return false; - } - return true; -}; - -export function client_config(m, dev) { - let p = m.people[dev.person]; - let srv = p ? m.servers[p.server] : null; - if (!srv) - return null; - let host = endpoint_host(m, srv); - let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host; - let allowed = allowed_ips(m, srv, p); - let dns = client_dns(m, srv, p); - let lines = [ '[Interface]' ]; - push(lines, `PrivateKey = ${dev.private_key || ''}`); - push(lines, `Address = ${dev.address}/32`); - if (length(dns)) - push(lines, `DNS = ${join(', ', dns)}`); - push(lines, `MTU = ${srv.mtu}`); - // "Off" is plain WireGuard: neutral values (no junk, H1-H4 = 1-4) are left - // out, so any WireGuard app accepts the file. - if (!obf_neutral(srv.obf)) - for (let k in OBF_KEYS) - if (srv.obf[k] != null && srv.obf[k] != '') - push(lines, `${OBF_CONF[k]} = ${srv.obf[k]}`); - push(lines, '', '[Peer]'); - push(lines, `PublicKey = ${srv.public_key}`); - if (dev.preshared_key) - push(lines, `PresharedKey = ${dev.preshared_key}`); - push(lines, `AllowedIPs = ${join(', ', allowed)}`); - push(lines, `Endpoint = ${ep}:${srv.port}`); - if (srv.keepalive > 0) - push(lines, `PersistentKeepalive = ${srv.keepalive}`); - return { - name: dev.name, - person: p.name, - server: srv.name, - filename: `${substr(replace(lc(p.id + '-' + dev.name), /[^a-z0-9]+/g, '-'), 0, 15)}.conf`, - conf: join('\n', lines) + '\n', - has_private_key: dev.private_key != '', - amnezia: { - host, - port: srv.port, - mtu: `${srv.mtu}`, - dns, - allowed_ips: allowed, - client_ip: dev.address, - client_priv_key: dev.private_key, - client_pub_key: dev.public_key, - psk_key: dev.preshared_key, - server_pub_key: srv.public_key, - persistent_keep_alive: `${srv.keepalive}`, - obfuscation: srv.obf, - }, - }; -}; - -/* ---------- issued configurations ---------- */ - -const ISSUED = `${DATA_DIR}/issued.json`; - -function fnv32(str) { - let h = 2166136261; - for (let i = 0; i < length(str); i++) - h = ((h ^ ord(str, i)) * 16777619) & 0xffffffff; - return sprintf('%08x', h); -} - -/** What a device holds, minus its private key: changes when it must import again. */ -export function config_fingerprint(m, dev) { - let c = dev ? client_config(m, dev) : null; - return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, /^PrivateKey/)))) : null; -}; - -/** Device id → fingerprint of the configuration last shown or downloaded. */ -export function issued() { - return read_json(ISSUED, {}); -}; - -/** Remember that a device was just given its current configuration. */ -export function mark_issued(m, id) { - let fp = config_fingerprint(m, m.devices[id]); - if (!fp) - return; - let l = lock('issued'); - let all = issued(); - if (all[id] != fp) { - all[id] = fp; - for (let k in keys(all)) - if (!m.devices[k]) - delete all[k]; - ensure_dir(DATA_DIR, 0o700); - write_json(ISSUED, all, 0o600); - } - unlock(l); -}; - /* ---------- mutations (caller commits) ---------- */ function fail(msg) { @@ -673,7 +453,9 @@ export function create_person(c, m, a) { let base = replace(a.slug ?? slugify(a.name), /-/g, '_'); if (!match(base, /^[a-z0-9_]{1,32}$/)) fail('The id may use lowercase letters, digits and underscores.'); - let taken = (id) => m.people[id] || m.servers[id] || m.devices[id] || m.services[id] || id == 'settings'; + // Any kind of section (store.id_taken, which imports this module). + let taken = (id) => m.people[id] || m.servers[id] || m.devices[id] || m.services[id] || m.circles[id] || + index([ 'settings', 'main', 'global', 'defaults' ], id) >= 0; let slug = base; for (let n = 2; taken(slug); n++) { if (n > 99) @@ -734,8 +516,9 @@ export function update_person(c, m, id, a) { let n = toint(a.device_limit, 0); if (n < 1 || n > 32) fail('Device limit must be between 1 and 32.'); - if (n < length(p.devices)) - fail(`${p.name} already has ${length(p.devices)} devices. Remove one first to lower the limit to ${n}.`); + let have = length(p.devices); + if (n < have) + fail(`${p.name} already has ${have} devices. Remove one first to lower the limit to ${n}.`); set('device_limit', n); } if (a.expires != null) { @@ -808,9 +591,9 @@ export function update_person(c, m, id, a) { }; /** - * Add a device for a person. `opts.by` is 'admin' or 'portal'; the portal - * enforces the device limit. `opts.public_key` keeps the private key on the - * client (browser-generated keys). + * Add a device for a person. `opts.keys` = { private_key?, public_key, + * preshared_key } from dawnline.awg (or a public key the browser generated). + * `opts.by` is 'admin' or 'portal'; the portal is held to the device limit. */ export function create_device(c, m, person_id, name, kind, opts) { opts ??= {}; @@ -833,39 +616,29 @@ export function create_device(c, m, person_id, name, kind, opts) { let addr = alloc_address(m, srv); if (!addr) fail('No free addresses left in the server subnet.'); - - let priv = '', pub; - if (opts.public_key) { - if (!valid_key(opts.public_key)) - fail('Invalid public key.'); - pub = opts.public_key; - } - else { - priv = genkey(); - pub = pubkey(priv); - } - if (!pub) + let k = opts.keys ?? {}; + if (!valid_key(k.public_key)) fail('Key generation failed (is amneziawg-tools installed?).'); - for (let id, d in m.devices) - if (d.public_key == pub) + for (let o, d in m.devices) + if (d.public_key == k.public_key) fail('This key is already in use.'); let id = `d_${rand_hex(4)}`; + let dev = { id, person: person_id, name, kind, address: addr, public_key: k.public_key, private_key: k.private_key ?? '', + preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false }; c.set(CONFIG, id, 'device'); c.set(CONFIG, id, 'person', person_id); c.set(CONFIG, id, 'name', name); c.set(CONFIG, id, 'kind', kind); c.set(CONFIG, id, 'address', addr); - c.set(CONFIG, id, 'public_key', pub); - if (priv) - c.set(CONFIG, id, 'private_key', priv); - c.set(CONFIG, id, 'preshared_key', genpsk()); - c.set(CONFIG, id, 'created', `${time()}`); - c.set(CONFIG, id, 'created_by', opts.by ?? 'admin'); + for (let f in [ 'public_key', 'private_key', 'preshared_key' ]) + if (dev[f]) + c.set(CONFIG, id, f, dev[f]); + c.set(CONFIG, id, 'created', `${dev.created}`); + c.set(CONFIG, id, 'created_by', dev.created_by); // Keep the in-memory model consistent for callers that continue. - m.devices[id] = { id, person: person_id, name, kind, address: addr, public_key: pub, private_key: priv, - preshared_key: c.get(CONFIG, id, 'preshared_key'), created: time(), created_by: opts.by ?? 'admin', disabled: false }; + m.devices[id] = dev; push(p.devices, id); return id; }; @@ -895,16 +668,17 @@ export function delete_device(c, m, id) { delete m.devices[id]; }; -export function rotate_device(c, m, id) { +/** New keys from dawnline.awg (the caller makes them: the model does not run tools). */ +export function rotate_device(c, m, id, keys) { let d = m.devices[id]; if (!d) fail('Unknown device.'); - let priv = genkey(), pub = pubkey(priv); - if (!pub) + if (!valid_key(keys?.public_key) || !keys?.private_key) fail('Key generation failed.'); - c.set(CONFIG, id, 'private_key', priv); - c.set(CONFIG, id, 'public_key', pub); - c.set(CONFIG, id, 'preshared_key', genpsk()); + c.set(CONFIG, id, 'private_key', keys.private_key); + c.set(CONFIG, id, 'public_key', keys.public_key); + if (keys.preshared_key) + c.set(CONFIG, id, 'preshared_key', keys.preshared_key); }; export function delete_person(c, m, id) { @@ -919,7 +693,7 @@ export function delete_person(c, m, id) { /** Validate a server definition (as loaded) against the rest of the router. */ export function server_errors(m, srv, others_subnets) { let errs = []; - if (!match(srv.ifname, /^[a-z][a-z0-9_]{0,11}$/)) + if (!valid_ifname(srv.ifname)) push(errs, 'Interface name: 1-12 lowercase letters, digits or _.'); if (srv.port < 1 || srv.port > 65535) push(errs, 'Port must be 1-65535.'); @@ -934,7 +708,6 @@ export function server_errors(m, srv, others_subnets) { } if (srv.endpoint != '' && !valid_host(srv.endpoint)) push(errs, 'Endpoint must be a hostname or IP address.'); - push(errs, ...obf_errors(srv.obf)); return errs; }; @@ -947,18 +720,14 @@ export function wan_port_taken(port) { if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT') return; for (let p in split(`${r.src_dport ?? ''}`, /[ ,]+/)) { - let m = match(p, /^(\d+)(?:[-:](\d+))?$/); - if (m && +m[1] <= port && port <= +(m[2] ?? m[1])) + let m = match(p, /^(\d+)([-:](\d+))?$/); + if (m && +m[1] <= port && port <= +(m[3] || m[1])) taken = true; } }); return taken; }; -export function wan443_taken() { - return wan_port_taken(443); -}; - /** Every address the links use, the main one first. */ export function portal_hosts(m) { let out = []; @@ -978,17 +747,14 @@ export function portal_http_port(m) { return m.settings.portal_port + 1; }; -/** The port in plain-HTTP links: 80 when standard ports are on and free. */ +/** The port in plain-HTTP links (the portal never takes 80 or 443 for itself). */ export function portal_http_public(m) { - return m.settings.portal_443 && !wan_port_taken(80) ? 80 : portal_http_port(m); + return portal_http_port(m); }; -/** The port in personal links: 443 when the portal also answers there. */ +/** The port in personal links: the portal's own. */ export function portal_public_port(m) { - let s = m.settings; - if (s.portal_port == 443 || !s.portal_443 || wan443_taken()) - return s.portal_port; - return 443; + return m.settings.portal_port; }; /** The link on one address: https for names, plain http for IP addresses. */ diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc new file mode 100644 index 0000000..50e5ba3 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc @@ -0,0 +1,115 @@ +// Dawnline — adding, changing, rotating and removing a person's devices: one +// code path for the admin UI (rpcd) and the portal, with the config lock, +// the runtime sync, the activity log and the "configuration issued" mark. +// +// opts = { by: 'admin' | 'portal', person?: the only person whose devices may +// be touched (the portal), defer?: load new keys a moment later (the portal +// page came through the device being rotated) }. The portal is held to the +// device limit (dawnline.core) and cannot touch a device the admin turned off. + +import { sh_bg } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as awg from 'dawnline.awg'; +import * as apply from 'dawnline.apply'; +import * as live from 'dawnline.live'; +import * as store from 'dawnline.store'; + +/** AmneziaWG is on the router, so device keys can be made and loaded. */ +export function ready() { + return awg.installed(); +}; + +/** Dies with the admin's wording when AmneziaWG is missing. */ +export function need_awg() { + if (!awg.installed()) { + let miss = awg.state().missing ?? []; + die(`AmneziaWG is not installed${length(miss) ? ` (${join(', ', miss)})` : ''}: install it in Dawnline → Components.`); + } +}; + +/** The device `id` as `opts` may touch it (inside a transaction's model). */ +function own(m, id, opts) { + let d = m.devices[id]; + if (!d || (opts.person != null && d.person != opts.person)) + die(opts.person != null ? 'Device not found.' : 'Unknown device.'); + if (opts.by == 'portal' && d.disabled) + die('The admin has turned this device off.'); + return d; +} + +/** New device with fresh keys (or the browser's public key): { id, config }. */ +export function add(person, name, kind, opts) { + opts ??= {}; + let by = opts.by ?? 'admin'; + let id = store.transact((c, m) => core.create_device(c, m, person, name, kind, { by, keys: awg.new_keys(opts.public_key || null) })); + apply.sync(); + let m = core.load(); + live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by }); + awg.mark_issued(m, id); + return { id, config: awg.client_config(m, m.devices[id]) }; +}; + +/** + * Rename and/or turn a device off or on (`ch` = { name?, disabled? }); only + * the admin turns devices off. Returns the runtime sync. + */ +export function update(id, ch, opts) { + opts ??= {}; + let by = opts.by ?? 'admin'; + if (ch.disabled != null && by != 'admin') + die('Only the admin can turn devices off.'); + let d0 = store.transact((c, m) => { + let d = own(m, id, opts); + let was = { ...d }; + if (ch.name != null && ch.name != d.name) + core.rename_device(c, m, id, ch.name); + if (ch.disabled != null) { + if (ch.disabled) + c.set(core.CONFIG, id, 'disabled', '1'); + else + c.delete(core.CONFIG, id, 'disabled'); + } + return was; + }); + let r = apply.sync(); + if (ch.disabled != null && !!ch.disabled != !!d0.disabled) + live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: ch.disabled ? 'turned off' : 'turned on', by }); + else if (ch.name != null && ch.name != d0.name) + live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: `renamed from ${d0.name}`, by }); + return r; +}; + +/** New keys for a device: returns its new configuration. */ +export function rotate(id, opts) { + opts ??= {}; + let by = opts.by ?? 'admin'; + store.transact((c, m) => { + own(m, id, opts); + core.rotate_device(c, m, id, awg.new_keys()); + }); + // The device a portal page came through would lose its tunnel before the + // answer gets out: load the new key a moment after answering. + if (opts.defer) + sh_bg('sleep 3; /usr/bin/dawnline sync'); + else + apply.sync(); + let m = core.load(); + let d = m.devices[id]; + live.add_event({ type: 'device_keys', person: d.person, device: id, detail: d.name, by }); + awg.mark_issued(m, id); + return awg.client_config(m, d); +}; + +/** Remove a device. Returns the runtime sync. */ +export function remove(id, opts) { + opts ??= {}; + let by = opts.by ?? 'admin'; + let d = store.transact((c, m) => { + let d = own(m, id, opts); + core.delete_device(c, m, id); + return d; + }); + let r = apply.sync(); + live.add_event({ type: 'device_removed', person: d.person, device: id, detail: d.name, dname: d.name, dkind: d.kind, by }); + return r; +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/fw.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/fw.uc new file mode 100644 index 0000000..809bc7f --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/fw.uc @@ -0,0 +1,177 @@ +// Dawnline — fw4 and routing around it: each tunnel's zone, its forwardings +// to home and WAN, the WAN rules for the tunnels and the portal (named +// sections dawnline_*), what the watchdog checks about them, and the reply +// routes that keep Dawnline's own answers on the main table. Only sections +// named dawnline_* are ever changed. + +import { cursor } from 'uci'; +import { sh, sh_out, uniq, uci_put, uci_section, ack_config } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as net from 'dawnline.net'; + +const LOOP_ZONE = 'dl_loop'; +/* + * Our own answers leave by the main table: the portal's (TCP) and each + * tunnel's (UDP). Proxies on the router (tproxy with an fwmark rule) may mark + * the router's own traffic to internet addresses and divert it locally, which + * swallows replies to outside clients. These rules sit before such fwmark + * rules and only match the router's own traffic (iif lo) from our listening + * ports: forwarded traffic keeps whatever routing the router has for it. + */ +const PREF_REPLY = 90; + +/** With `dry`, only says whether the firewall config differs from what Dawnline wants. */ +export function sync(m, dry) { + let c = cursor(); + c.load('firewall'); + let changed = false, want = {}; + + let sec = (name, stype, opts) => { + want[name] = true; + changed = uci_section(c, 'firewall', name, stype) || changed; + for (let k, v in opts) + changed = uci_put(c, 'firewall', name, k, v) || changed; + }; + + let snap = net.snapshot(true); + let portal_zone = null, want_loop = false; + for (let id, srv in m.servers) { + if (!length(core.tunnels(srv))) + continue; + let z = `dawnline_${id}`; + let sn = net.server_net(srv, snap); + portal_zone ??= sn.wan.zone; + sec(`${z}_zone`, 'zone', { + // Forward within the zone (device to device) is decided by the inet dawnline table. + name: srv.ifname, network: [ srv.ifname ], + input: 'ACCEPT', output: 'ACCEPT', forward: 'ACCEPT', + }); + // Access per person is enforced by the inet dawnline table; the zone + // only needs to be allowed to reach each home-network zone and WAN. + // The home network may open connections to the devices too (a router + // or a NAS on the tunnel); their answers pass the table as established. + for (let i, zone in sn.zones) + if (zone != sn.wan.zone && zone != srv.ifname) { + let sfx = i == 0 ? '' : `_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`; + sec(`${z}_lan${sfx}`, 'forwarding', { src: srv.ifname, dest: zone }); + sec(`${z}_from_lan${sfx}`, 'forwarding', { src: zone, dest: srv.ifname }); + } + sec(`${z}_wan`, 'forwarding', { src: srv.ifname, dest: sn.wan.zone }); + if (srv.lan_like) { + sec(`${z}_loop`, 'forwarding', { src: srv.ifname, dest: LOOP_ZONE }); + want_loop = true; + } + sec(`${z}_port`, 'rule', { + name: `Dawnline-${srv.ifname}`, src: sn.wan.zone, proto: 'udp', + dest_port: srv.port, target: 'ACCEPT', enabled: srv.enabled ? null : '0', + }); + } + + // The link into the netns that re-enters the router from the LAN. + if (want_loop) { + sec('dawnline_loop', 'zone', { + name: LOOP_ZONE, device: [ net.INTERNAL.transit ], + input: 'REJECT', output: 'ACCEPT', forward: 'REJECT', + }); + // The Home-only resolver in the netns reaches its upstream DNS this way. + sec('dawnline_loop_wan', 'forwarding', { src: LOOP_ZONE, dest: portal_zone ?? 'wan' }); + } + + // Never open SSH, DNS or the LuCI web server for the portal, whatever the settings say. + let portal_port_ok = (p) => p >= 1 && p <= 65535 && index([ 22, 53, 80, 443 ], p) < 0; + if (m.settings.portal_enabled && portal_port_ok(m.settings.portal_port)) { + let wan = portal_zone ?? 'wan'; + sec('dawnline_portal', 'rule', { + name: 'Dawnline-Portal', src: wan, proto: 'tcp', + dest_port: m.settings.portal_port, target: 'ACCEPT', + }); + // IP addresses in links: plain HTTP next to the HTTPS port, and 80 forwarded to it. + if (core.portal_http(m) && portal_port_ok(core.portal_http_port(m))) { + sec('dawnline_portal_http', 'rule', { + name: 'Dawnline-Portal-HTTP', src: wan, proto: 'tcp', + dest_port: core.portal_http_port(m), target: 'ACCEPT', + }); + } + // The portal keeps its own port: 80 and 443 stay with the LuCI web server. + } + + let stale = []; + c.foreach('firewall', null, (s) => { + if (match(s['.name'], /^dawnline_/) && !want[s['.name']]) + push(stale, s['.name']); + }); + for (let s in stale) { + c.delete('firewall', s); + changed = true; + } + if (dry) + return changed; + + if (changed) { + c.commit('firewall'); + ack_config([ 'firewall' ]); + system('fw4 -q reload'); + system("logger -t dawnline 'firewall updated'"); + } + return changed; +}; + +/** + * For the watchdog: what is wrong with Dawnline's firewall, or null. + * 'off': fw4 is not running at all (not ours to start); 'changed': the config + * lost or changed Dawnline's sections; 'not loaded': fw4 runs without them. + */ +export function drift(m) { + let t = sh_out('nft -t list table inet fw4 2>/dev/null') ?? ''; + if (t == '') + return 'off'; + if (sync(m, true)) + return 'changed'; + // Named rules show up in fw4's ruleset as comments. + let names = []; + for (let id, srv in m.servers) + if (srv.enabled && length(core.tunnels(srv))) + push(names, `Dawnline-${srv.ifname}`); + if (m.settings.portal_enabled) + push(names, 'Dawnline-Portal'); + for (let n in names) + if (index(t, `${n}"`) < 0) + return 'not loaded'; + return null; +}; + +/** Our reply rules of one family as `ip rule show` prints them: [{ proto, port, lo }]. */ +function reply_rules(fam) { + let out = []; + // "90: from all iif lo ipproto udp sport 51820 lookup main" (older versions: without "iif lo"). + for (let line in split(sh_out(`ip ${fam} rule show priority ${PREF_REPLY} 2>/dev/null`) ?? '', '\n')) { + let mm = match(line, /ipproto (tcp|udp) sport ([0-9]+) lookup main/); + if (mm) + push(out, { proto: mm[1], port: mm[2], lo: index(line, ' iif lo ') >= 0 }); + } + return out; +} + +/** One `iif lo ipproto

sport lookup main` rule per listening port and family. */ +export function sync_reply_routes(m) { + let want = []; + if (m.settings.portal_enabled) { + push(want, `tcp ${+m.settings.portal_port}`); + if (core.portal_http(m)) + push(want, `tcp ${core.portal_http_port(m)}`); + } + for (let id, srv in m.servers) + if (srv.private_key && srv.enabled && +srv.port) + push(want, `udp ${+srv.port}`); + want = uniq(want); + for (let fam in [ '-4', '-6' ]) { + // Ours that are no longer wanted, and the older ones that also caught forwarded traffic. + for (let r in reply_rules(fam)) + if (!r.lo || index(want, `${r.proto} ${r.port}`) < 0) + sh(`ip ${fam} rule del priority ${PREF_REPLY}${r.lo ? ' iif lo' : ''} ipproto ${r.proto} sport ${r.port} lookup main 2>/dev/null`); + let have = map(filter(reply_rules(fam), (r) => r.lo), (r) => `${r.proto} ${r.port}`); + for (let w in want) + if (index(have, w) < 0) + sh(`ip ${fam} rule add priority ${PREF_REPLY} iif lo ipproto ${split(w, ' ')[0]} sport ${split(w, ' ')[1]} lookup main`); + } +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/github.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/github.uc new file mode 100644 index 0000000..33575d4 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/github.uc @@ -0,0 +1,226 @@ +// Dawnline — GitHub for the updater and the Components tab: API calls with a +// short cache, releases (with each asset's sha256), the changes between two +// tags, and verified downloads. +// +// Trust: the API is only ever asked directly (TLS to api.github.com). Files +// may come through a mirror when GitHub is unreachable, but only when their +// sha256 is known from the API, and a file is kept only if it matches. + +import { stat, popen, access } from 'fs'; +import { q, read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util'; + +/** Prefixes that fetch github.com files when GitHub itself is unreachable. */ +export const MIRRORS = [ 'https://ghfast.top/', 'https://gh-proxy.com/', 'https://ghproxy.net/' ]; + +function run(cmd) { + let p = popen(cmd + ' 2>&1', 'r'); + if (!p) + return { code: 127, out: '' }; + let out = p.read('all') ?? ''; + return { code: p.close(), out }; +} + +function have_curl() { + return access('/usr/bin/curl', 'x'); +} + +/** + * GET a URL: { status, body } (status 0 when there was no answer). curl gives + * the HTTP status, so a 403 rate limit is told apart from a dead network. + */ +function get(url, timeout) { + timeout ??= 12; + if (have_curl()) { + let r = run(`curl -sSL --connect-timeout 6 --max-time ${+timeout} -H 'Accept: application/vnd.github+json' -A Dawnline -w '\\n%{http_code}' ${q(url)}`); + // The body, then the status on the last line (-w). + let i = rindex(r.out, '\n'); + let code = i < 0 ? '' : substr(r.out, i + 1); + return match(code, /^[0-9][0-9][0-9]$/) ? { status: +code, body: substr(r.out, 0, i) } : { status: 0, body: '' }; + } + let r = run(`uclient-fetch -q -T ${+timeout} -O - ${q(url)}`); + return { status: r.code == 0 ? 200 : 0, body: r.code == 0 ? r.out : '' }; +} + +/** JSON from the GitHub API, or null when GitHub did not answer; dies on a rate limit or another API error. */ +function api_json(url) { + let r = get(url); + if (r.status == 0) + return null; + let j = null; + try { + j = json(r.body); + } + catch (e) { + return null; + } + if (r.status == 403 || r.status == 429 || (type(j) == 'object' && match(j.message ?? '', /rate limit/i))) + die('GitHub API rate limit reached: try again in an hour.'); + if (r.status == 404) + return null; + if (r.status >= 400) + die(`GitHub: ${j?.message ?? `HTTP ${r.status}`}`); + return j; +} + +function cached(key, ttl, fn) { + let path = `${RUN_DIR}/gh-${replace(key, /[^A-Za-z0-9_.-]/g, '_')}.json`; + let c = read_json(path, null); + if (c && time() - (c.at ?? 0) < ttl) + return c.data; + let data = fn(); + if (data != null) { + ensure_dir(RUN_DIR); + write_json(path, { at: time(), data }); + } + return data ?? c?.data; +} + +/* ---------- releases ---------- */ + +function slim(x) { + let digests = {}; + for (let a in x.assets ?? []) + if (match(a.digest ?? '', /^sha256:[0-9a-f]{64}$/)) + digests[a.name] = substr(a.digest, 7); + return { + tag: x.tag_name, name: x.name ?? x.tag_name, published: x.published_at ?? null, + prerelease: !!x.prerelease, url: x.html_url ?? null, body: substr(x.body ?? '', 0, 12000), + assets: map(x.assets ?? [], (a) => a.name), digests, + }; +} + +/** Releases of a repository, newest first, five per page (drafts skipped). */ +export function releases(rp, page) { + page = page ?? 1; + return cached(`rel-${rp}-${page}`, 600, () => { + let j = api_json(`https://api.github.com/repos/${rp}/releases?per_page=5&page=${+page}`); + return type(j) == 'array' ? map(filter(j, (x) => !x.draft), slim) : null; + }) ?? []; +}; + +/** One release by tag (notes, assets and their sha256), or null. */ +export function release(rp, tag) { + return cached(`tag-${rp}-${tag}`, 600, () => { + let j = api_json(`https://api.github.com/repos/${rp}/releases/tags/${tag}`); + return type(j) == 'object' && j.tag_name ? slim(j) : null; + }); +}; + +/** The sha256 GitHub publishes for a release file, or null (unknown: no mirrors for it). */ +export function asset_sha256(rp, tag, name) { + try { + return release(rp, tag)?.digests?.[name] ?? null; + } + catch (e) { + return null; + } +}; + +/** The latest stable release; the /releases/latest redirect when the API is out of reach. */ +export function latest(rp) { + let r = null; + try { + r = cached(`latest-${rp}`, 300, () => { + let j = api_json(`https://api.github.com/repos/${rp}/releases/latest`); + return type(j) == 'object' && j.tag_name ? slim(j) : null; + }); + } + catch (e) {} + if (r) + return r; + if (have_curl()) { + let o = run(`curl -sI --connect-timeout 15 --max-time 30 -o /dev/null -w '%{redirect_url}' ${q('https://github.com/' + rp + '/releases/latest')}`); + let m = match(trim(o.out), /\/releases\/tag\/([^\/?#]+)$/); + if (m) + return { tag: m[1], name: m[1], published: null, prerelease: false, url: `https://github.com/${rp}/releases/tag/${m[1]}`, body: '', assets: [], digests: {} }; + } + return null; +}; + +/* ---------- what changed ---------- */ + +/** + * What changed in a commit message, as points: release commits ("Dawnline + * 0.3.1") list their changes as "- " lines in the body; other commits are + * their title. Wrapped points are joined back into one line. + */ +export function points(msg) { + let lines = split(msg ?? '', '\n'); + let title = trim(lines[0] ?? ''); + if (match(title, /^Merge /)) + return []; + let out = [], cur = null; + for (let i = 1; i < length(lines); i++) { + let m = match(lines[i], /^\s*[-*]\s+(.*)$/); + if (m) { + if (cur != null) + push(out, cur); + cur = trim(m[1]); + } + else if (cur != null && match(lines[i], /^\s+\S/)) + cur += ' ' + trim(lines[i]); + else if (cur != null) { + push(out, cur); + cur = null; + } + } + if (cur != null) + push(out, cur); + if (!length(out) && !match(title, /^(Dawnline )?v?[0-9]+\.[0-9]+(\.[0-9]+)?$/) && title != '') + push(out, title); + return out; +}; + +/** The changes from one tag to another, newest first: commit by commit, or the release's own commit. */ +export function changes(rp, base, head) { + return cached(`changes-${rp}-${base}-${head}`, 600, () => { + let out = []; + let j = base ? api_json(`https://api.github.com/repos/${rp}/compare/${base}...${head}`) : null; + if (type(j?.commits) == 'array') { + for (let i = length(j.commits) - 1; i >= 0; i--) + for (let p in points(j.commits[i]?.commit?.message)) + push(out, p); + return slice(out, 0, 20); + } + let c = api_json(`https://api.github.com/repos/${rp}/commits/${head}`); + return c?.commit ? slice(points(c.commit.message), 0, 20) : null; + }) ?? []; +}; + +/* ---------- downloads ---------- */ + +export function sha256(path) { + return match(run(`sha256sum ${q(path)}`).out, /^([0-9a-f]{64})/)?.[1]; +}; + +/** + * Download to a file. o: { sha256, mirrors, log }. Direct first; mirrors + * only when the sha256 is known (from the API) and mirrors are allowed. A + * file that does not match the sha256 is thrown away and the next source is + * tried. Returns the URL that worked, or null. + */ +export function download(url, dest, o) { + o ??= {}; + let want = o.sha256 ? lc(o.sha256) : null; + let tries = [ url ]; + if (want && o.mirrors && match(url, /^https:\/\/(github\.com|raw\.githubusercontent\.com)\//)) + for (let m in MIRRORS) + push(tries, m + url); + for (let i, u in tries) { + let host = replace(u, /^https:\/\/([^\/]+)\/.*$/, '$1'); + if (i > 0) + o.log?.(`Trying mirror ${host}`); + let r = have_curl() + ? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 1 -o ${q(dest)} ${q(u)}`) + : run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(u)}`); + if (r.code == 0 && (stat(dest)?.size ?? 0) > 0) { + if (!want || sha256(dest) == want) + return u; + o.log?.(`Warning: ${host} sent a file that does not match GitHub's sha256, discarded`); + } + system(`rm -f ${q(dest)}`); + if (i == 0 && length(tries) > 1) + o.log?.('GitHub did not answer, trying mirrors'); + } + return null; +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc new file mode 100644 index 0000000..f982a1e --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc @@ -0,0 +1,433 @@ +// Dawnline — Health: what the router has and lacks (packages, listeners, +// networks), the checks shown on Diagnostics → Health, and their fixes. + +import { readfile, stat, lsdir } from 'fs'; +import { cursor } from 'uci'; +import { q, sh, sh_out, parse_cidr, cidr_overlaps, ip2int, in_cidr, file_exists, cloudflare_ip } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as live from 'dawnline.live'; +import * as apply from 'dawnline.apply'; +import * as loop from 'dawnline.loop'; +import * as net from 'dawnline.net'; +import * as awg from 'dawnline.awg'; +import * as lookup from 'dawnline.lookup'; +import * as pc from 'dawnline.portalcert'; + +/* ---------- what the router has ---------- */ + +/** + * Packages a feature needs that are missing, by feature: https (the portal: openssl-util and any + * TLS module for uhttpd), acme (Let's Encrypt certificates), home (the home-like link), awg + * (AmneziaWG: the tools with netifd's protocol script, and the kernel module). Checked by + * files, so it is cheap enough for every page load. + */ +export function needs() { + let tls = false; + for (let d in [ '/lib', '/usr/lib' ]) + for (let f in lsdir(d) ?? []) + if (substr(f, 0, 16) == 'libustream-ssl.s') + tls = true; + let kver = trim(readfile('/proc/sys/kernel/osrelease') ?? ''); + let kmod = (name) => stat(`/sys/module/${name}`) != null || file_exists(`/lib/modules/${kver}/${name}.ko`); + let miss = (list) => map(filter(list, (x) => !x[0]), (x) => x[1]); + return { + https: miss([ [ file_exists('/usr/bin/openssl'), 'openssl-util' ], [ tls, 'libustream-openssl' ] ]), + acme: miss([ [ file_exists('/usr/lib/acme/client/acme.sh'), 'acme' ], [ file_exists('/usr/lib/acme/client/dnsapi/dns_cf.sh'), 'acme-acmesh-dnsapi' ], + [ file_exists('/www/luci-static/resources/view/acme.js'), 'luci-app-acme' ] ]), + home: miss([ [ file_exists('/usr/libexec/ip-full'), 'ip-full' ], [ kmod('veth'), 'kmod-veth' ] ]), + // amneziawg-tools ships both the awg tool and netifd's protocol script. + awg: miss([ [ file_exists('/usr/bin/awg') && file_exists('/lib/netifd/proto/amneziawg.sh'), 'amneziawg-tools' ], + [ kmod('amneziawg'), 'kmod-amneziawg' ] ]), + }; +}; + +export function udp_listening(port) { + let hex = sprintf(':%04X ', port); + for (let f in [ '/proc/net/udp', '/proc/net/udp6' ]) + if (index(readfile(f) ?? '', hex) >= 0) + return true; + return false; +}; + +export function tcp_listening(port) { + let hex = sprintf(':%04X ', port); + for (let f in [ '/proc/net/tcp', '/proc/net/tcp6' ]) + for (let line in split(readfile(f) ?? '', '\n')) + // state 0A = LISTEN + if (index(line, hex) > 0 && match(line, / 0A /)) + return true; + return false; +}; + +/** Processes other than our portal listening on a TCP port: [ "name" ]. */ +export function tcp_port_owners(port) { + let out = sh_out(`netstat -lntp 2>/dev/null | awk '$4 ~ /:${+port}$/ {print $7}'`) ?? ''; + let owners = []; + for (let o in split(out, '\n')) { + let name = split(o, '/')[1]; + if (!name || index(owners, name) >= 0) + continue; + // Our own portal runs as a dedicated uhttpd instance. + let pid = +split(o, '/')[0]; + let cmd = readfile(`/proc/${pid}/cmdline`) ?? ''; + if (index(cmd, '/usr/share/dawnline/portal') >= 0) + continue; + push(owners, name); + } + return owners; +}; + +export function service_running(name, instance) { + let s = sh_out(`ubus call service list '{"name":"${name}"}' 2>/dev/null`); + if (!s) + return false; + try { + return !!json(s)?.[name]?.instances?.[instance]?.running; + } + catch (e) { + return false; + } +}; + +/** IPv4 networks of netifd interfaces: [{ iface, cidr }], without the given server's tunnel. */ +function other_subnets(srv_id) { + let out = []; + let st = sh_out('ubus call network.interface dump 2>/dev/null'); + let d = null; + try { + d = st ? json(st) : null; + } + catch (e) { + d = null; + } + let ours = {}; + for (let id, s in core.load().servers) + ours[s.ifname] = id; + for (let i in d?.interface ?? []) { + if (srv_id != null && ours[i.interface] == srv_id) + continue; + if (srv_id === false && ours[i.interface] != null) + continue; + for (let a in i['ipv4-address'] ?? []) + push(out, { iface: i.interface, cidr: `${a.address}/${a.mask}` }); + } + return out; +}; + +/** Subnets in use on the router except the given server's (null: all of them). */ +export function used_subnets(except_srv) { + return map(other_subnets(except_srv), (x) => x.cidr); +}; + +/** Subnets of interfaces that are not Dawnline tunnels (an imported config is checked against these). */ +export function foreign_subnets() { + return used_subnets(false); +}; + +/* ---------- checks ---------- */ + +/* + * Checks are named for the healthy state ("Clock is set"); a failed one also + * gets the problem in words for notices ("Clock isn't set"). Longest names + * first; a server's name after the check name is kept. + */ +const PROBLEM = [ + [ 'AmneziaWG answers reach devices', 'AmneziaWG answers may not reach devices' ], + [ 'AmneziaWG devices loaded', 'Not every device is loaded into AmneziaWG' ], + [ 'AmneziaWG subnet is unique', 'AmneziaWG subnet overlaps another network' ], + [ 'AmneziaWG port is free', 'AmneziaWG port is taken' ], + [ 'AmneziaWG installed', 'AmneziaWG isn’t ready' ], + [ 'AmneziaWG firewall', 'AmneziaWG firewall rules are missing' ], + [ 'AmneziaWG running', 'AmneziaWG is down' ], + [ 'Portal answers reach visitors', 'Portal answers may not reach visitors' ], + [ 'Portal address points here', 'Portal address doesn’t point here' ], + [ 'Portal address', 'Portal address isn’t set' ], + [ 'Portal certificate', 'Portal certificate needs attention' ], + [ 'Personal portal', 'Personal portal isn’t working' ], + [ 'Plain HTTP links', 'Portal links use plain HTTP' ], + [ 'Internet like a home device', 'Internet like a home device isn’t working' ], + [ 'DNS for Home-only devices', 'DNS for Home-only devices isn’t working' ], + [ 'Background agent running', 'Background agent isn’t running' ], + [ 'Access rules loaded', 'Access rules aren’t loaded' ], + [ 'Server configured', 'No server yet' ], + [ 'Public address', 'Public address needs attention' ], + [ 'Clock is set', 'Clock isn’t set' ], +]; + +function problem_of(title) { + for (let p in PROBLEM) + if (substr(title, 0, length(p[0])) == p[0]) + return p[1] + substr(title, length(p[0])); + return title; +} + +/** problem: the failed check in words, when the table's wording does not fit the case. */ +function check(id, title, status, detail, fix, problem) { + let bad = status == 'warn' || status == 'error'; + return { id, title, status, detail: detail ?? '', fix: fix ?? null, problem: bad ? (problem ?? problem_of(title)) : null }; +} + +/* + * Policy rules that send the router's own (marked) traffic into a local table, + * the way transparent proxies capture it: "pref 1000 fwmark 0x1 → table 100". + */ +function proxy_diverts() { + let out = []; + for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) { + let mm = match(line, /^(\d+):.*fwmark (\S+).* lookup (\S+)/); + if (!mm || +mm[1] >= 32766) + continue; + if (match(sh_out(`ip -4 route show table ${mm[3]} 2>/dev/null`) ?? '', /(^|\n)local default/)) + push(out, `pref ${mm[1]} fwmark ${mm[2]} → table ${mm[3]}`); + } + return out; +} + +/** Our "answers leave by main" rule for this port (see apply.sync_reply_routes). */ +function reply_rule(proto, port) { + return index(sh_out('ip -4 rule show priority 90 2>/dev/null') ?? '', `ipproto ${proto} sport ${+port} lookup main`) >= 0; +} + +function reply_check(id, title, proto, port, diverts) { + let ok = reply_rule(proto, port); + let via = length(diverts) ? ` A proxy on the router diverts its own traffic (${join(', ', diverts)}); these answers skip it.` : ''; + return check(id, title, ok ? 'ok' : (length(diverts) ? 'error' : 'warn'), + ok ? `Answers from ${uc(proto)} ${port} go straight out.${via}` + : length(diverts) ? `Answers from ${uc(proto)} ${port} can be swallowed by a proxy on the router (${join(', ', diverts)}): clients get no reply.` + : `The rule that keeps answers from ${uc(proto)} ${port} out of proxies is missing.`, + ok ? null : 'apply'); +} + +const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr); + +/** What a public address resolves to and whether that reaches this router (for a core's protocol). */ +function endpoint_check(id, title, srv, host, proto_note) { + if (!host) + return check(id, title, 'error', 'No public address: devices will not know where to connect.'); + let ips = lookup.resolve(host); + let wan = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone); + let wc = wan ? ip2int(wan) : null; + let cgnat = wc != null && length(filter(PRIVATE, (c) => in_cidr(wc, c))) > 0; + if (!length(ips)) + return check(id, title, 'error', `${host} does not resolve.`); + if (cgnat) + return check(id, title, 'warn', `WAN address ${wan} is private: forward ${proto_note} on the upstream router, or devices cannot connect.`); + if (length(filter(ips, (a) => cloudflare_ip(a)))) + return check(id, title, 'error', `${host} → ${join(', ', ips)} (Cloudflare). ${proto_note} reaches the router only if this name is DNS-only there, or use the router's IP.`); + if (wan && index(ips, wan) < 0) + return check(id, title, 'warn', `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`); + return check(id, title, 'ok', `${host} → ${join(', ', ips)}`); +} + +const NO_PROTO = "netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it)."; + +/** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */ +function awg_check() { + let st = awg.state(); + let title = 'AmneziaWG installed'; + if (length(st.missing ?? [])) + return check('awg', title, 'error', `${join(' and ', st.missing)} ${length(st.missing) == 1 ? 'is' : 'are'} missing.`, 'install:awg', + 'AmneziaWG isn’t installed'); + if (!st.loaded) { + let why = trim(sh('modprobe amneziawg 2>&1; dmesg | grep -i amneziawg | tail -n 3').out); + return check('awg', title, 'error', + `The kernel module doesn't load${why ? `: ${why}` : '.'} Reinstall a build for this kernel in Components.`, 'updates', + 'AmneziaWG’s kernel module doesn’t load'); + } + if (!st.handler) + return check('awg', title, 'error', NO_PROTO, 'netrestart', 'The network doesn’t know AmneziaWG yet'); + return check('awg', title, 'ok', 'Kernel module, awg tool and the netifd protocol are present.'); +} + +/** Checks of a server's AmneziaWG tunnel. */ +function awg_checks(m, id, srv, label, fwc, dmp, diverts) { + let out = []; + let st = live.iface_status(srv.ifname); + let up = !!st?.up; + let codes = map(st?.errors ?? [], (e) => e.code); + if (!up && index(codes, 'INVALID_PROTO') >= 0) + push(out, check(`up_${id}`, `AmneziaWG running${label}`, 'error', NO_PROTO, 'netrestart')); + else + push(out, check(`up_${id}`, `AmneziaWG running${label}`, up ? 'ok' : 'error', + up ? `${srv.ifname} is up, listening on UDP ${srv.port}.` : + (st ? `${srv.ifname} is down${length(codes) ? ': ' + join(', ', codes) : ''}.` : `${srv.ifname} does not exist.`), + up ? null : (st ? 'ifup:' + srv.ifname : 'apply'))); + if (up) { + let expected = 0; + let states = apply.states_for(m, core.load_usage()); + for (let did, d in m.devices) { + let p = m.people[d.person]; + if (p?.server == id && !d.disabled && states[d.person] == 'active') + expected++; + } + let actual = 0; + for (let k, p in dmp.peers) + if (p.ifname == srv.ifname) + actual++; + push(out, check(`peers_${id}`, `AmneziaWG devices loaded${label}`, expected == actual ? 'ok' : 'warn', + `${actual} of ${expected} active devices are loaded in the tunnel.`, expected == actual ? null : 'sync')); + } + let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule'; + let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone'; + push(out, check(`fw_${id}`, `AmneziaWG firewall${label}`, rule && zone ? 'ok' : 'error', + rule && zone ? `Zone ${srv.ifname} and the WAN rule for UDP ${srv.port} exist.` : 'Firewall zone or WAN rule is missing.', + rule && zone ? null : 'apply')); + push(out, reply_check(`reply_${id}`, `AmneziaWG answers reach devices${label}`, 'udp', srv.port, diverts)); + // Port collisions with other tunnels. + let clash = []; + let nc = cursor(); + nc.load('network'); + nc.foreach('network', 'interface', (s) => { + if (s['.name'] != srv.ifname && (s.proto == 'amneziawg' || s.proto == 'wireguard') && +s.listen_port == srv.port) + push(clash, s['.name']); + }); + if (length(clash)) + push(out, check(`port_${id}`, `AmneziaWG port is free${label}`, 'error', `UDP ${srv.port} is also used by ${join(', ', clash)}.`)); + let overlaps = []; + let sc = parse_cidr(srv.subnet); + for (let o in other_subnets(id)) { + let oc = parse_cidr(o.cidr); + if (sc && oc && cidr_overlaps(sc, oc)) + push(overlaps, `${o.iface} (${o.cidr})`); + } + push(out, check(`subnet_${id}`, `AmneziaWG subnet is unique${label}`, length(overlaps) ? 'error' : 'ok', + length(overlaps) ? `${srv.subnet} overlaps ${join(', ', overlaps)}.` : `${srv.subnet} does not overlap other networks.`)); + return out; +} + +/** The portal's checks: listening, its address, answers, plain HTTP and the certificate. */ +function portal_checks(m, need, diverts) { + let out = []; + let s = m.settings; + if (length(need.https)) + return [ check('portal', 'Personal portal', 'error', `HTTPS isn't available on this router: install ${join(' and ', need.https)}.`, 'install:https') ]; + let owners = tcp_port_owners(s.portal_port); + let listening = tcp_listening(s.portal_port); + if (length(owners)) + push(out, check('portal', 'Personal portal', 'error', + `TCP ${s.portal_port} is already used by ${join(', ', owners)}. Choose another port in Settings.`)); + else + push(out, check('portal', 'Personal portal', listening ? 'ok' : 'error', + listening ? `Listening on TCP ${s.portal_port}.` : `Nothing listens on TCP ${s.portal_port}.`, listening ? null : 'restart')); + if (!s.portal_host) + push(out, check('portal_host', 'Portal address', 'error', 'Set the public hostname in Settings so links can be generated.')); + else { + let ips = lookup.resolve(s.portal_host), wan = lookup.router_wan(m); + let cf = filter(ips, (x) => cloudflare_ip(x)); + push(out, check('portal_dns', 'Portal address points here', !length(ips) ? 'error' : length(cf) ? 'ok' : wan && index(ips, wan) < 0 ? 'warn' : 'ok', + !length(ips) ? `${s.portal_host} does not resolve.` : + length(cf) ? `${s.portal_host} goes through Cloudflare; in Russia such connections often stall after ~16 KB.` : + wan && index(ips, wan) < 0 ? `${s.portal_host} points at ${join(', ', ips)}, not this router (${wan}).` : + `${s.portal_host} → ${join(', ', ips)}${wan ? ' (this router)' : ''}.`)); + } + push(out, reply_check('portal_reply', 'Portal answers reach visitors', 'tcp', s.portal_port, diverts)); + if (core.portal_http(m)) { + let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null); + push(out, check('portal_http', 'Plain HTTP links', 'warn', + `Links on ${join(', ', ipl)} use plain HTTP: the link and the VPN keys in configurations travel unencrypted.`)); + } + if (ip2int(s.portal_host) != null) { + push(out, check('cert', 'Portal certificate', 'skip', 'The main address is an IP: its links use plain HTTP.')); + return out; + } + let cert = pc.portal_cert(s); + let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0; + let sans = cert.self_signed ? [] : pc.cert_names(cert.cert); + let covers = !s.portal_host || cert.self_signed || length(filter(sans, (n) => pc.name_covers(n, s.portal_host))) > 0; + push(out, check('cert', 'Portal certificate', cert.self_signed || !ok || !covers ? 'warn' : 'ok', + cert.self_signed ? `Using a self-signed certificate: browsers will show a warning.${length(need.acme) ? ' ACME can get a free Let’s Encrypt one.' : ''}` : + !covers ? `${cert.cert} does not cover ${s.portal_host} (it has ${join(', ', sans)}): browsers will warn.` : + ok ? `${cert.cert} covers ${s.portal_host} and is valid for more than 14 days.` : `${cert.cert} expires within 14 days.`)); + return out; +} + +/** + * Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix }. + * `fix` names an action accepted by fix(), or one the UI handles itself + * (install:, updates). + */ +export function health(m) { + let diverts = proxy_diverts(); + m ??= core.load(); + let out = []; + let dmp = live.dump(m); + let need = needs(); + + if (length(m.servers)) + push(out, awg_check()); + let y = localtime().year; + push(out, check('clock', 'Clock is set', y >= 2025 ? 'ok' : 'error', + y >= 2025 ? 'End dates and quotas use the router clock.' : 'The router clock looks wrong; end dates will misbehave. Check NTP.')); + + let agent = service_running('dawnline', 'agent'); + push(out, check('agent', 'Background agent running', agent ? 'ok' : 'error', + 'Counts traffic and enforces end dates and quotas.', agent ? null : 'restart')); + + if (!length(m.servers)) { + push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.')); + return out; + } + + let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0; + push(out, check('nft', 'Access rules loaded', nft_ok ? 'ok' : 'error', + nft_ok ? 'Table inet dawnline enforces who may reach LAN and the internet.' : 'Table inet dawnline is missing: access is not enforced.', + nft_ok ? null : 'apply')); + + let fwc = cursor(); + fwc.load('firewall'); + + for (let id, srv in m.servers) { + let label = length(m.servers) > 1 ? ` (${srv.name})` : ''; + if (!srv.enabled) { + push(out, check(`srv_${id}`, `Server${label}`, 'skip', 'Server is disabled.')); + continue; + } + push(out, ...awg_checks(m, id, srv, label, fwc, dmp, diverts)); + push(out, endpoint_check(`ep_${id}`, `Public address${label}`, srv, core.endpoint_host(m, srv), `UDP ${srv.port}`)); + + if (srv.lan_like) { + let ls = loop.status(); + let nh = need.home; + push(out, check(`home_${id}`, `Internet like a home device${label}`, ls.active && ls.bridged ? 'ok' : 'warn', + ls.active && ls.bridged ? `Traffic enters ${ls.dev} as ${ls.address}, so it is handled like any device on your LAN.` : + length(nh) ? `Needs ${join(' and ', nh)}. Internet traffic leaves through WAN directly until then.` : + ls.active ? `The link is up but not attached to ${ls.dev}.` : + `${ls.error ?? 'Not set up.'} Internet traffic leaves through WAN directly.`, + ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply')); + } + } + + if (length(filter(values(m.servers), (x) => x.private_key))) { + let rt = loop.resolver_target(); + let ok = stat(loop.RESOLVER.conf) != null && loop.resolver_running(); + push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn', + ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`) + : 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply')); + } + + if (m.settings.portal_enabled) + push(out, ...portal_checks(m, need, diverts)); + return out; +}; + +/** Run a fix named by a check. */ +export function fix(id) { + if (id == 'apply') + return apply.apply(); + if (id == 'sync') + return apply.sync(); + if (id == 'restart') + return { code: system('/etc/init.d/dawnline restart >/dev/null 2>&1') }; + // netifd learns protocol handlers (amneziawg) only when it starts. In the + // background: the answer goes out before the network blinks. + if (id == 'netrestart') { + system('( sleep 1; /etc/init.d/network restart ) >/dev/null 2>&1 = 5) { - out.ifaces[f[0]] = { public_key: f[2], port: +f[3] }; - } - } - return out; +export function dump(m) { + return awg.dump(); }; export function endpoint_ip(ep) { - let m = match(ep ?? '', /^\[?([^\]]+?)\]?:[0-9]+$/); + let m = match(ep ?? '', /^\[?([^\]]+)\]?:[0-9]+$/); return m ? m[1] : ep; }; @@ -122,7 +102,10 @@ function empty_usage() { } export function load_usage() { - return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage(); + let u = read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage(); + // Per-app counters of earlier test builds are not kept. + delete u.clients; + return u; }; function add(bucket, key, rx, tx) { @@ -182,30 +165,41 @@ export function reset_usage(usage, m, scope, id) { for (let did in m.people[id]?.devices ?? []) wipe(usage.devices[did]); } - else if (scope == 'device') { + else if (scope == 'device') wipe(usage.devices[id]); - } }; +function offline(rec) { + return { online: false, handshake: rec?.handshake ?? 0, endpoint: rec?.endpoint ?? '', present: false }; +} + /** * Fold the current kernel counters into `usage`. Counters restart from zero * when a peer is re-added or the interface restarts; a drop is treated as a * reset. Returns the per-device live view keyed by device id. + * + * A device missing from the dump had its counters reset only when its tunnel + * was actually read: an interface the tool couldn't read says nothing, and + * forgetting the last counters there would count them again on the next good + * read. A failed read with nothing in it changes nothing at all. */ export function collect(m, usage, d) { - d ??= dump(); + d ??= dump(m); let ts = time(); let live = {}; - let by_key = {}; - for (let id, dev in m.devices) - by_key[dev.public_key] = id; - + if (d.ok === false && !length(d.peers)) { + for (let id in keys(m.devices)) + live[id] = offline(usage.devices[id]); + return live; + } for (let id, dev in m.devices) { let rec = usage.devices[id] ??= { raw: [ 0, 0 ] }; let peer = d.peers[dev.public_key]; if (!peer) { - rec.raw = [ 0, 0 ]; - live[id] = { online: false, handshake: rec.handshake ?? 0, endpoint: rec.endpoint ?? '', present: false }; + let ifname = m.servers[m.people[dev.person]?.server]?.ifname; + if (d.ok !== false || d.ifaces[ifname] != null) + rec.raw = [ 0, 0 ]; + live[id] = offline(rec); continue; } let raw = rec.raw ?? [ 0, 0 ]; @@ -260,9 +254,8 @@ export function save_usage(usage, persist) { /** Sum of [rx, tx] over the last `days` days for a usage record. */ export function recent(rec, days) { let out = [ 0, 0 ]; - let ts = time(); for (let i = 0; i < days; i++) { - let v = rec?.days?.[day_key(ts - i * 86400)]; + let v = rec?.days?.[day_key_ago(i)]; if (v) { out[0] += v[0]; out[1] += v[1]; @@ -278,9 +271,8 @@ export function month(rec) { /** Daily series for the last `days` days: [{ day, rx, tx }]. */ export function series(recs, days) { let out = []; - let ts = time(); for (let i = days - 1; i >= 0; i--) { - let k = day_key(ts - i * 86400); + let k = day_key_ago(i); let rx = 0, tx = 0; for (let r in recs) { let v = r?.days?.[k]; @@ -409,17 +401,7 @@ export function clear_events(f) { /* ---------- health ---------- */ export function iface_status(ifname) { - if (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/)) - return null; - let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`); - if (!s) - return null; - try { - return json(s); - } - catch (e) { - return null; - } + return util_iface_status(ifname); }; export function uptime() { diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/lookup.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/lookup.uc new file mode 100644 index 0000000..0182eec --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/lookup.uc @@ -0,0 +1,98 @@ +// Dawnline — where names point and the router's public address, for Health +// and the portal settings. Lookups are cached in RUN_DIR for a few minutes +// and made in parallel with a short timeout: rpcd answers one call at a +// time, so a slow DNS server must not hold up the whole admin UI. + +import { readfile } from 'fs'; +import { q, sh, ensure_dir, read_json, write_json, ip2int, rand_hex, RUN_DIR } from 'dawnline.util'; +import * as live from 'dawnline.live'; +import * as net from 'dawnline.net'; + +const CACHE = `${RUN_DIR}/resolve.json`; +// Answers are kept 5 minutes, failures 1 minute. +const TTL = 300; +const TTL_FAIL = 60; +const TIMEOUT = 2; +const MAX_NAMES = 16; +// Public resolvers first: local DNS often rewrites the router's own name to +// its LAN address (split horizon). +const SERVERS = [ '1.1.1.1', '8.8.8.8', '127.0.0.1' ]; + +function valid_name(h) { + return type(h) == 'string' && length(h) <= 253 && match(h, /^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$/) != null; +} + +/** + * IPv4 addresses of each name: { host: [ ip, … ] } (empty when it does not + * resolve). IP addresses map to themselves. Every uncached name is asked of + * every server at once; the first server (in SERVERS order) that answers wins. + */ +export function resolve_all(hosts) { + let out = {}, now = time(), todo = []; + let cache = read_json(CACHE, {}); + for (let h in hosts) { + if (h == null || out[h] != null) + continue; + if (ip2int(h) != null) { + out[h] = [ h ]; + continue; + } + let c = cache[h]; + if (c && now - c.ts < (length(c.ips) ? TTL : TTL_FAIL)) + out[h] = c.ips; + else if (valid_name(h) && length(todo) < MAX_NAMES) { + out[h] = []; + push(todo, h); + } + else + out[h] = []; + } + if (!length(todo)) + return out; + + ensure_dir(RUN_DIR); + let dir = `${RUN_DIR}/resolve.${rand_hex(4)}`; + let cmds = []; + for (let i = 0; i < length(todo); i++) + for (let j = 0; j < length(SERVERS); j++) + push(cmds, `( timeout ${TIMEOUT} nslookup ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j} ) &`); + sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`); + for (let i = 0; i < length(todo); i++) { + let ips = []; + for (let j = 0; j < length(SERVERS) && !length(ips); j++) { + let r = readfile(`${dir}/${i}.${j}`) ?? ''; + ips = filter(split(trim(r), '\n'), (x) => ip2int(x) != null); + } + out[todo[i]] = ips; + cache[todo[i]] = { ts: now, ips }; + } + system(`rm -rf ${dir}`); + // Only what is still fresh is kept. + for (let h, c in cache) + if (now - c.ts >= TTL) + delete cache[h]; + write_json(CACHE, cache, 0o644); + return out; +}; + +/** IPv4 addresses of one name (see resolve_all). */ +export function resolve(host) { + return resolve_all([ host ])[host] ?? []; +}; + +/** The IPv4 address of a netifd interface (a zone name for older configs). */ +export function wan_ipv4(zone) { + let st = live.iface_status(zone == 'wan' ? 'wan' : zone); + return st?.['ipv4-address']?.[0]?.address; +}; + +/** The router's public IPv4 (the first server's WAN, else the wan interface). */ +export function router_wan(m) { + for (let id, srv in m.servers) + if (srv.private_key) { + let a = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone); + if (a) + return a; + } + return wan_ipv4('wan'); +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc index fc941c8..8dcc6dd 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc @@ -14,12 +14,11 @@ // Clients also use the netns address as DNS: it forwards to the DNS the LAN // gets from DHCP, from the LAN side, so DNS interception applies as well. // -// Separately, people with Home-only access get a plain resolver (real -// addresses from the WAN's DNS, home names from the LAN DNS): their internet -// does not use the tunnel, so fake-IP answers would break it. While the netns -// exists the resolver runs inside it and sends its upstream queries back out -// through the transit link as forwarded traffic — not as the router's own -// traffic and not from the LAN — so tools that capture either leave it alone. +// Separately, people with Home-only access get a plain resolver +// (dawnline.resolver). While the netns exists it runs inside it and sends its +// upstream queries back out through the transit link as forwarded traffic — +// not as the router's own traffic and not from the LAN — so tools that +// capture either leave it alone. This module says where it runs. // // Everything is derived from the router at run time; nothing assumes a // particular subnet or tool. If the LAN is not a bridge or setup fails, the @@ -27,18 +26,19 @@ import { readfile, writefile, readlink, stat, unlink } from 'fs'; import { cursor } from 'uci'; -import { sh, sh_out, q, ip2int, int2ip, ensure_dir, read_json, write_json, uniq, slog, RUN_DIR } from 'dawnline.util'; +import { + sh, sh_out, q, ip2int, int2ip, parse_cidr, cidr_any, ensure_dir, read_json, write_json, slog, RUN_DIR +} from 'dawnline.util'; import * as net from 'dawnline.net'; +import * as core from 'dawnline.core'; +import * as store from 'dawnline.store'; +import * as resolver from 'dawnline.resolver'; export const NS = 'dawnline'; const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.lan, LAN_NS = 'dll1'; const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290; -const RESOLVER_PORT = 5354; -export const RESOLVER_CONF = '/var/etc/dawnline-dns.conf'; -const RESOLVER_RESOLV = '/var/etc/dawnline-dns.resolv'; -const RESOLVER_PID = '/var/run/dawnline-dns.pid'; +export const RESOLVER_CONF = resolver.CONF; const STATE = `${RUN_DIR}/loop.json`; -const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ]; const WHO = 'Internet like a home device'; @@ -60,17 +60,6 @@ function exists(dev) { return stat(`/sys/class/net/${dev}`) != null; } -function cidr_of(a) { - let m = match(a ?? '', /^([0-9.]+)\/([0-9]+)$/); - if (!m) - return null; - let ip = ip2int(m[1]), prefix = +m[2]; - if (ip == null || prefix < 8 || prefix > 30) - return null; - let size = 1 << (32 - prefix); - return { ip, prefix, size, net: ip - ip % size }; -} - /* ---------- facts about the LAN ---------- */ /** DHCP pool, static leases and the DNS handed to LAN clients, for one netifd interface. */ @@ -160,12 +149,8 @@ function pick_transit(saved) { push(busy, n); let free = (base) => { for (let b in busy) { - let c = match(b, /^([0-9.]+)(\/([0-9]+))?$/); - if (!c) - continue; - let ip = ip2int(c[1]), size = 1 << (32 - (c[3] != null ? +c[3] : 32)); - let bn = ip - ip % size; - if (base < bn + size && bn < base + 4) + let c = cidr_any(b); + if (c && base < c.net + c.size && c.net < base + 4) return false; } return true; @@ -203,9 +188,14 @@ function settings() { return c.get_all('dawnline', 'settings') ?? {}; } -/** Servers that want "like a home device" (default on). */ +/** Servers that want "like a home device" (default on) and run a core. */ function wanted(m) { - return filter(values(m.servers), (s) => s.private_key && s.enabled && s.lan_like); + return filter(values(m.servers), (s) => length(core.tunnels(s)) && s.enabled && s.lan_like); +} + +/** Every server's interface, for rules. */ +function all_ifnames(m) { + return map(values(m.servers), (s) => s.ifname); } /** @@ -223,7 +213,7 @@ export function plan(m) { return { error: 'No LAN detected.' }; if (d.kind != 'bridge') return { error: `${dev} is not a bridge, so Dawnline cannot join the LAN as a device.` }; - let lan = cidr_of(d.addrs[0]); + let lan = parse_cidr(d.addrs[0]); if (!lan) return { error: `${dev} has no IPv4 address.` }; let facts = dhcp_facts(d.logical, lan); @@ -241,7 +231,8 @@ export function plan(m) { let servers = []; for (let srv in srvs) { let sn = net.server_net(srv, snap); - push(servers, { ifname: srv.ifname, subnet: srv.subnet, direct: net.collapse([ srv.subnet, ...sn.nets ]) }); + for (let t in core.tunnels(srv)) + push(servers, { ifname: t.ifname, subnet: t.subnet, direct: net.collapse([ t.subnet, ...sn.nets ]) }); } return { dev, @@ -332,7 +323,9 @@ function tunnel_ifnames() { let c = cursor(); c.load('dawnline'); let out = []; - c.foreach('dawnline', 'server', (s) => push(out, s.ifname ?? s['.name'])); + c.foreach('dawnline', 'server', (s) => { + push(out, s.ifname ?? s['.name']); + }); return out; } @@ -360,13 +353,14 @@ export function remove(ifnames) { * last applied plan and only checks that links, bridge port and rules exist. */ export function ensure(m, force) { - let ifnames = map(values(m.servers), (s) => s.ifname); + let ifnames = all_ifnames(m); let p = plan(m); if (p.off || p.error) { - if (stat(STATE) || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames))) + // Read before remove(), which deletes it: the error is logged once, not every tick. + let was = read_json(STATE, {}); + if (was.plan || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames))) remove(ifnames); ensure_dir(RUN_DIR); - let was = read_json(STATE, {}); write_json(STATE, { error: p.error, off: !!p.off }, 0o644); if (p.error && p.error != was.error) log('is off', 'error', p.error); @@ -423,15 +417,6 @@ export function ensure(m, force) { write_json(STATE, { error: `Setup failed: ${errs[0]}` }, 0o644); return { error: errs[0] }; } - // Keep the chosen LAN address stable across restarts. - let c = cursor(); - c.load('dawnline'); - if (c.get('dawnline', 'settings', 'lan_address') != p.address) { - c.set('dawnline', 'settings', 'settings'); - c.set('dawnline', 'settings', 'lan_address', p.address); - c.commit('dawnline'); - system('chmod 600 /etc/config/dawnline'); - } ensure_dir(RUN_DIR); write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644); if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address) @@ -441,6 +426,20 @@ export function ensure(m, force) { return p; }; +/** + * Keep the chosen LAN address stable across restarts (settings.lan_address). + * Called by dawnline.apply once its own lock is released: the config lock is + * never taken inside it. + */ +export function remember(p) { + if (!p?.address || settings().lan_address == p.address) + return; + store.transact((c, m) => { + c.set('dawnline', 'settings', 'settings'); + c.set('dawnline', 'settings', 'lan_address', p.address); + }); +}; + /** Last applied state for views and health checks. */ export function status() { let s = read_json(STATE, {}); @@ -461,33 +460,6 @@ export function client_dns() { /* ---------- plain resolver for Home-only clients ---------- */ -function wan_dns() { - let out = []; - let snap = net.snapshot(); - let wan = snap.devices[snap.wan]?.logical; - for (let name in uniq([ wan, 'wan', 'wan6' ])) { - if (!name) - continue; - try { - let st = json(sh_out(`ubus call network.interface.${name} status 2>/dev/null`) || 'null'); - for (let a in st?.['dns-server'] ?? []) - if (match(a, /^[0-9.]+$/)) - push(out, a); - } - catch (e) {} - } - return length(out) ? uniq(out) : FALLBACK_DNS; -} - -/** Local domain of the LAN DNS (dnsmasq `domain`, else the Dawnline hostname domain). */ -function lan_domain(m) { - let c = cursor(); - c.load('dhcp'); - let d = null; - c.foreach('dhcp', 'dnsmasq', (s) => { d ??= s.domain; }); - return uniq(filter([ d, m.settings.domain ], (x) => x)); -} - /** The DNS your LAN gets from DHCP (option 6), else the router on the LAN. */ export function lan_dns() { let st = status(); @@ -496,7 +468,10 @@ export function lan_dns() { let snap = net.snapshot(); let d = snap.devices[snap.lan]; let a = d?.addrs?.[0]; - return a ? (dhcp_facts(d.logical, cidr_of(a))?.dns ?? split(a, '/')[0]) : null; + if (!a) + return null; + let lan = parse_cidr(a); + return (lan ? dhcp_facts(d.logical, lan).dns : null) ?? split(a, '/')[0]; }; /** @@ -505,62 +480,17 @@ export function lan_dns() { */ export function resolver_target() { let st = status(); - return st.active && st.transit ? { mode: 'ns', address: st.transit, port: 53 } : { mode: 'root', port: RESOLVER_PORT }; + return st.active && st.transit ? { mode: 'ns', address: st.transit, port: 53 } : { mode: 'root', port: resolver.PORT }; }; -/** - * Write the resolver config; returns true when it changed (the running - * instance is then restarted by procd's respawn after a kill). The first line - * tells /usr/libexec/dawnline/resolver where to run it. - */ +/** Write the resolver config where it should run now; true when it changed (see dawnline.resolver). */ export function sync_resolver(m) { - ensure_dir('/var/etc'); - let ifs = map(filter(values(m.servers), (s) => s.private_key), (s) => s.ifname); - let target = resolver_target(); - let lan = lan_dns(); - let lines = [ - `# mode=${target.mode}`, - '# Generated by Dawnline: plain DNS for Home-only tunnel clients.', - `port=${target.port}`, - 'no-hosts', - 'bogus-priv', - 'cache-size=1000', - `pid-file=${RESOLVER_PID}`, - 'user=dnsmasq', - 'group=dnsmasq', - ]; - if (target.mode == 'ns') { - push(lines, `listen-address=${target.address}`, 'bind-interfaces', 'no-resolv'); - // Upstream from the transit address: forwarded through the router to the WAN. - for (let a in wan_dns()) - push(lines, `server=${a}@${target.address}`); - } - else { - push(lines, 'bind-dynamic', ...map(ifs, (i) => `interface=${i}`), `resolv-file=${RESOLVER_RESOLV}`); - let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`)); - if ((readfile(RESOLVER_RESOLV) ?? '') != resolv) { - writefile(RESOLVER_RESOLV, resolv); - system(`chmod 644 ${RESOLVER_RESOLV}`); - } - } - if (lan) - for (let d in lan_domain(m)) - push(lines, `server=/${d}/${lan}`); - let conf = join('\n', lines) + '\n'; - if ((readfile(RESOLVER_CONF) ?? '') == conf) - return false; - writefile(RESOLVER_CONF, conf); - system(`chmod 644 ${RESOLVER_CONF}`); - let pid = trim(readfile(RESOLVER_PID) ?? ''); - if (match(pid, /^[0-9]+$/)) - system(`kill ${pid} 2>/dev/null`); - return true; + return resolver.sync(m, resolver_target(), lan_dns()); }; /** True when the resolver process is alive. */ export function resolver_running() { - let pid = trim(readfile(RESOLVER_PID) ?? ''); - return match(pid, /^[0-9]+$/) != null && stat(`/proc/${pid}`) != null; + return resolver.running(); }; -export const RESOLVER = { port: RESOLVER_PORT, conf: RESOLVER_CONF }; +export const RESOLVER = { port: resolver.PORT, conf: resolver.CONF }; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/migrate.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/migrate.uc new file mode 100644 index 0000000..d4424f8 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/migrate.uc @@ -0,0 +1,64 @@ +// Dawnline — one-time steps for routers set up by older versions. Each one +// checks first and writes nothing when there is nothing to do; dawnline.apply +// runs them before it takes its own lock (changes to /etc/config/dawnline go +// through dawnline.store and its config lock). + +import { cursor } from 'uci'; +import { stat, unlink } from 'fs'; +import { q, slog } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as store from 'dawnline.store'; + +const LAN_CGI = '/www/cgi-bin/dawnline-portal'; +const LAN_CGI_URL = '/cgi-bin/dawnline-portal'; + +/** Every personal code is a word code; older random ones are replaced (their links stop working). */ +function word_codes() { + let old = (s) => s.code != null && !match(s.code, core.WORD_CODE); + let c = cursor(); + c.load('dawnline'); + let any = false; + c.foreach('dawnline', 'person', (s) => { + if (old(s)) + any = true; + }); + if (!any) + return; + store.transact((w, m) => { + w.foreach('dawnline', 'person', (s) => { + if (old(s)) { + w.set('dawnline', s['.name'], 'code', core.new_code()); + w.delete('dawnline', s['.name'], 'words'); + } + }); + }); + slog('dawnline', 'info', 'moved to word codes', null, 'Personal links'); +} + +/* + * Older versions answered on 443 at home through LuCI's web server (its error + * page ran the portal CGI). The portal now keeps its own port: remove that. + */ +export function uhttpd() { + let c = cursor(); + c.load('uhttpd'); + if (c.get('uhttpd', 'main', 'error_page') == LAN_CGI_URL) { + c.delete('uhttpd', 'main', 'error_page'); + c.commit('uhttpd'); + system('/etc/init.d/uhttpd reload >/dev/null 2>&1'); + system(`logger -t dawnline ${q('portal removed from the LuCI web server')}`); + } + if (stat(LAN_CGI)) + unlink(LAN_CGI); + // The old setting itself. + let d = cursor(); + d.load('dawnline'); + if (d.get('dawnline', 'settings', 'portal_443') != null) + store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443')); +}; + +/** All of them, in order. */ +export function run() { + word_codes(); + uhttpd(); +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/net.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/net.uc index 509504d..6c98871 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/net.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/net.uc @@ -14,12 +14,17 @@ import { readfile, readlink, lsdir, stat } from 'fs'; import { cursor } from 'uci'; -import { sh_out, ip2int, int2ip, uniq } from 'dawnline.util'; +import { sh_out, ip2int, int2ip, cidr_any, uniq } from 'dawnline.util'; const SYS = '/sys/class/net'; /** Links Dawnline creates itself (dawnline.loop); never offered as interfaces. */ export const INTERNAL = { transit: 'dlx0', lan: 'dll0' }; const VPN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc', 'pptp', 'l2tp', 'gre', 'gretap', 'vti', 'xfrm' ]; +const VPN_NAMES = /^(wg|awg|tun|tap|ovpn|ipsec|vti|xfrm)/; +// Never the WAN while another default route exists: VPN clients. (PPTP and +// L2TP stay eligible: some ISPs connect the WAN with them.) +const NOT_WAN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc' ]; +const NOT_WAN_NAMES = /^(wg|awg|tun|tap|ovpn)/; // Kernel placeholder devices that never carry a network on their own. const NOISE = /^(ifb|teql|sit|ip6tnl|gre|gretap|erspan|ip6gre|ip6gretap|ip_vti|ip6_vti|tunl|bond)[0-9]*$/; const PRIVATE = [ [ '10.0.0.0', 8 ], [ '172.16.0.0', 12 ], [ '192.168.0.0', 16 ], [ '100.64.0.0', 10 ] ]; @@ -48,16 +53,8 @@ function ubus_json(path, method) { /** "a.b.c.d[/len]" → { net, prefix, size } for any prefix 1-32; null for default or junk. */ function net_of(s) { - let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/); - if (!m) - return null; - let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32; - if (ip == null || prefix < 1 || prefix > 32) - return null; - let size = 1 << (32 - prefix); - if (prefix == 1) - size = 2147483648; - return { net: ip - ip % size, prefix, size }; + let c = cidr_any(s); + return c && c.prefix >= 1 ? c : null; } function net_str(n) { @@ -107,12 +104,12 @@ export function snapshot(fresh) { return cache; // Networks reachable through each device (main table, IPv4). - let routes = {}, wan_dev = null; + let routes = {}, defaults = []; for (let r in ip_json('-4 route show table main')) { if (!r.dev) continue; if (r.dst == 'default') { - wan_dev ??= r.dev; + push(defaults, r); continue; } push(routes[r.dev] ??= [], r.dst); @@ -130,6 +127,19 @@ export function snapshot(fresh) { if (dev && !logical[dev]) logical[dev] = { name: i.interface, proto: i.proto, up: i.up }; } + // The WAN: the default route with the lowest metric that does not go into + // a VPN client (its default route is not where the tunnels listen); only + // VPN routes: the lowest of them. + let vpn = (dev) => index(NOT_WAN_PROTOS, logical[dev]?.proto) >= 0 || match(dev, NOT_WAN_NAMES) != null; + let wan_dev = null, wan_metric = null, wan_vpn = true; + for (let r in defaults) { + let v = vpn(r.dev), metric = r.metric ?? 0; + if (wan_dev == null || (wan_vpn && !v) || (wan_vpn == v && metric < wan_metric)) { + wan_dev = r.dev; + wan_metric = metric; + wan_vpn = v; + } + } let zone_by_net = {}, zone_by_dev = {}, zones = []; let fc = cursor(); fc.load('firewall'); @@ -163,7 +173,7 @@ export function snapshot(fresh) { let cat; if (wifi) cat = 'wifi'; - else if ((lg && index(VPN_PROTOS, lg.proto) >= 0) || kind == 65534 || ((flags & 0x10) && kind != 1) || match(dev, /^(wg|awg|tun|tap|ovpn|ipsec|vti|xfrm)/)) + else if ((lg && index(VPN_PROTOS, lg.proto) >= 0) || kind == 65534 || ((flags & 0x10) && kind != 1) || match(dev, VPN_NAMES)) cat = 'vpn'; else if (kind == 1 || bridge) cat = 'ethernet'; @@ -238,7 +248,9 @@ export function server_net(srv, snap) { if (dev == wan.dev || dev == srv.ifname || devs[dev]?.master) continue; let d = devs[dev]; - let h = { dev, auto: p[1], nets: d?.nets ?? [], zone: d?.zone ?? null, missing: !d }; + // The detected LAN missing for a moment (bridge recreated) keeps its zone, + // so its forwardings are not removed meanwhile. + let h = { dev, auto: p[1], nets: d?.nets ?? [], zone: d?.zone ?? (p[1] ? srv.lan_zone : null), missing: !d }; push(home, h); push(nets, ...h.nets); if (h.zone) diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/netifd.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/netifd.uc new file mode 100644 index 0000000..cc32ba6 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/netifd.uc @@ -0,0 +1,125 @@ +// Dawnline — netifd: one AmneziaWG interface per server, named after its +// ifname and marked `_dawnline` = server id. Only interfaces Dawnline created +// are changed or removed: a name already used by another interface (`lan`, a +// tunnel of your own, one from an imported config) is left alone and the +// server is reported instead. + +import { cursor } from 'uci'; +import { stat, unlink, writefile } from 'fs'; +import { q, uci_put, uci_section, ack_config, iface_intent, ensure_dir, read_json, write_json, slog, RUN_DIR } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as awg from 'dawnline.awg'; + +// Set while AmneziaWG is missing and that was logged (once until it is back). +const NO_AWG = `${RUN_DIR}/netifd-no-awg`; + +function log(who, msg, level, detail) { + slog('dawnline', level ?? 'info', msg, detail, who); +} + +/** The server id that owns network.: null when the section is free, '' when someone else's. */ +export function owner(ifname, c) { + if (!c) { + c = cursor(); + c.load('network'); + } + if (c.get('network', ifname) == null) + return null; + return c.get('network', ifname, '_dawnline') ?? ''; +}; + +/** Bring network config in line with the servers; true when it changed. */ +export function sync(m) { + let c = cursor(); + c.load('network'); + let changed = false, touched = [], want = {}; + // Servers whose interface can't be set up (core.BLOCKED), each logged once while it lasts. + let was = read_json(core.BLOCKED, {}), blocked = {}; + let block = (srv, msg, detail) => { + blocked[srv.id] = msg; + // The rest of this apply works from the same model: no tunnel for it there either. + srv.blocked = msg; + if (was[srv.id] != msg) + log(srv.name, msg, 'error', detail); + }; + + // Without amneziawg-tools there is no protocol script: changing or bringing + // up an interface would only stop a tunnel that is still running. + let tools = awg.state().tools; + if (tools && stat(NO_AWG)) + unlink(NO_AWG); + else if (!tools && length(filter(values(m.servers), (s) => s.private_key)) && !stat(NO_AWG)) { + log('AmneziaWG', "isn't installed: tunnels were left as they are", 'error', 'Install it in Dawnline → Components.'); + ensure_dir(RUN_DIR); + writefile(NO_AWG, `${time()}`); + } + + for (let id, srv in m.servers) { + if (!srv.private_key) + continue; + let ifn = srv.ifname; + if (!core.valid_ifname(ifn)) { + block(srv, `has an invalid interface name "${ifn}"`, 'Interface name: 1-12 lowercase letters, digits or _.'); + continue; + } + let own = owner(ifn, c); + if (own != null && own != id) { + block(srv, `can't use the network interface ${ifn}: it exists and isn't Dawnline's`, + 'Dawnline never changes interfaces it did not create. Choose another interface name for this server.'); + continue; + } + delete srv.blocked; + want[ifn] = true; + if (!tools) + continue; + // Per server: with several, each changed one has to be brought up again. + let mine = uci_section(c, 'network', ifn, 'interface'); + let set = (opt, val) => { + if (uci_put(c, 'network', ifn, opt, val)) + mine = true; + }; + for (let k, v in awg.netifd_options(srv)) + set(k, v); + set('disabled', srv.enabled ? null : '1'); + set('auto', srv.enabled ? null : '0'); + set('_dawnline', id); + // For the log once the server is gone. + set('_dawnline_name', srv.name); + if (mine) { + changed = true; + push(touched, ifn); + // The hotplug log says why the tunnel goes down (not a failure). + iface_intent(ifn, srv.enabled ? 'settings' : 'off', srv.name); + } + } + + if (sprintf('%J', blocked) != sprintf('%J', was)) { + ensure_dir(RUN_DIR); + write_json(core.BLOCKED, blocked, 0o644); + } + + // Remove interfaces Dawnline created for servers that no longer exist. + let stale = []; + c.foreach('network', 'interface', (s) => { + if (s._dawnline && !want[s['.name']]) + push(stale, s['.name']); + }); + for (let ifn in stale) { + iface_intent(ifn, 'removed', c.get('network', ifn, '_dawnline_name') ?? ifn); + system(`ifdown ${q(ifn)} 2>/dev/null`); + c.delete('network', ifn); + changed = true; + } + + if (changed) { + c.commit('network'); + ack_config([ 'network' ]); + system('ubus call network reload'); + for (let ifn in touched) + if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled) + system(`ifup ${q(ifn)}`); + // Each tunnel's own line (restarting, turned off, removed) comes from hotplug. + system(`logger -t dawnline ${q('network updated: ' + join(', ', [ ...touched, ...stale ]))}`); + } + return changed; +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/nft.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/nft.uc new file mode 100644 index 0000000..525b7ae --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/nft.uc @@ -0,0 +1,225 @@ +// Dawnline — the nft table `inet dawnline`: each person's access, enforced +// on the tunnel interfaces before anything else on the router sees the +// traffic, and where tunnel DNS goes. Its shape follows the servers and their +// home networks (rebuild); who is in which set follows people's state and +// changes often (update, one atomic transaction). + +import { unlink } from 'fs'; +import { sh, ensure_dir, write_file, rand_hex, ip2int, RUN_DIR } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as net from 'dawnline.net'; +import * as loop from 'dawnline.loop'; + +const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ]; +/** The sets whose members change at run time (update replaces them together). */ +const SETS = [ 'lan_ok', 'lan_all', 'lan_part', 'mesh_pairs', 'inet_ok', 'svc_ok', 'svc_host', 'dns_real' ]; + +function ip4(a) { + return ip2int(a ?? '') != null; +} + +/** Per-person runtime membership: which tunnel addresses may reach what. */ +export function access_sets(m, usage, states) { + // lan_ok: home access (the router itself, the mesh); lan_all: every home + // network; lan_part: device . network for people limited to some networks; + // mesh_pairs: device . device within a circle (or one person's own devices); + // svc_ok: device . service . port; svc_host: device . service with no ports (all of them). + let sets = {}; + for (let k in SETS) + sets[k] = []; + let snap = net.snapshot(); + let homes = {}, groups = {}; + for (let id, d in m.devices) { + let p = m.people[d.person]; + // Off: paused, ended, over quota or out of hours. Addresses go into nft as they are: IPv4 only. + if (!p || d.disabled || !ip4(d.address) || states[p.id] != 'active') + continue; + // Home names: the plain resolver (their internet does not use the tunnel). + if (p.access == 'lan' && p.dns_mode == 'home') + push(sets.dns_real, d.address); + if (p.access == 'internet' || p.access == 'both') + push(sets.inet_ok, d.address); + if (p.access == 'both' || (p.access == 'lan' && !length(p.services))) { + push(sets.lan_ok, d.address); + let srv = m.servers[p.server]; + let h = homes[p.id] ??= srv ? core.person_home(srv, p, snap) : { all: true, nets: [] }; + if (h.all) + push(sets.lan_all, d.address); + else + for (let n in h.nets) + push(sets.lan_part, `${d.address} . ${n}`); + // Who this device may reach directly: its circle, or at least its owner's devices. + if (srv?.mesh == 'circles') { + let ci = core.person_circle(m, p); + push(groups[ci ? `c:${ci.id}` : `p:${p.id}`] ??= [], d.address); + } + } + else if (p.access == 'lan') + for (let sid in p.services) { + let s = m.services[sid]; + if (!s || !ip4(s.address)) + continue; + if (!length(s.ports)) + push(sets.svc_host, `${d.address} . ${s.address}`); + for (let port in s.ports) + if (match(port, /^[0-9]+$/)) + push(sets.svc_ok, `${d.address} . ${s.address} . ${port}`); + } + } + for (let g, addrs in groups) + for (let a in addrs) + for (let b in addrs) + if (a != b) + push(sets.mesh_pairs, `${a} . ${b}`); + return sets; +}; + +function set_elems(arr) { + return length(arr) ? `elements = { ${join(', ', arr)} }` : ''; +} + +function table(m, sets) { + let ifs = [], lan = [], tun = []; + let dns_addr = loop.client_dns(); + if (!ip4(dns_addr)) + dns_addr = null; + let rt = loop.resolver_target(); + let snap = net.snapshot(); + for (let id, srv in m.servers) { + // Only valid interface names reach here (core.tunnels): they are written into the rules as strings. + let tns = core.tunnels(srv); + for (let t in tns) { + push(ifs, `"${t.ifname}"`); + push(tun, t.subnet); + } + if (length(tns)) + push(lan, ...net.server_net(srv, snap).nets); + } + lan = net.collapse(lan); + tun = net.collapse(tun); + let t = []; + push(t, 'table inet dawnline {'); + push(t, ` set lan_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(lan)} }`); + // Tunnel subnets are never "home", even inside a wider route to the LAN. + push(t, ` set tun_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(tun)} }`); + push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`); + push(t, ` set lan_all { type ipv4_addr; ${set_elems(sets.lan_all)} }`); + push(t, ` set lan_part { type ipv4_addr . ipv4_addr; flags interval; ${set_elems(sets.lan_part)} }`); + push(t, ` set mesh_pairs { type ipv4_addr . ipv4_addr; ${set_elems(sets.mesh_pairs)} }`); + push(t, ` set inet_ok { type ipv4_addr; ${set_elems(sets.inet_ok)} }`); + push(t, ` set svc_ok { type ipv4_addr . ipv4_addr . inet_service; ${set_elems(sets.svc_ok)} }`); + push(t, ` set svc_host { type ipv4_addr . ipv4_addr; ${set_elems(sets.svc_host)} }`); + push(t, ` set dns_real { type ipv4_addr; ${set_elems(sets.dns_real)} }`); + push(t, ' chain pre {'); + // Ahead of mangle-priority hooks (transparent proxies mark at -150). + push(t, ' type filter hook prerouting priority -160; policy accept;'); + if (length(ifs)) + push(t, ` iifname { ${join(', ', ifs)} } jump guard`); + push(t, ' }'); + push(t, ' chain guard {'); + push(t, ' meta nfproto ipv6 drop'); + push(t, ' ct state established,related accept'); + push(t, ' icmp type echo-request fib daddr type local accept'); + push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept'); + push(t, ' fib daddr type local ip saddr @lan_ok accept'); + push(t, ' fib daddr type local counter drop'); + if (dns_addr) + // DNS through the netns (it forwards to the LAN's DNS), for everyone. + push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`); + push(t, ' ip daddr @lan_nets ip daddr != @tun_nets ip saddr @lan_all accept'); + push(t, ' ip saddr . ip daddr @lan_part ip daddr != @tun_nets accept'); + // Devices with home access are part of home: they reach each other, where the + // server allows it (everyone, or within circles). Within one server: the + // firewall has no forwarding between different servers' zones. + for (let id, srv in m.servers) + for (let tn in core.tunnels(srv)) + if (srv.mesh == 'all') + push(t, ` iifname "${tn.ifname}" ip saddr @lan_ok ip daddr @lan_ok accept`); + else if (srv.mesh == 'circles') + push(t, ` iifname "${tn.ifname}" ip saddr . ip daddr @mesh_pairs accept`); + push(t, ' meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept'); + push(t, ' ip saddr . ip daddr @svc_host accept'); + push(t, ` ip daddr { ${join(', ', PRIVATE4)} } counter drop`); + push(t, ' ip saddr @inet_ok accept'); + push(t, ' counter drop'); + push(t, ' }'); + // The other way: fw4 lets the server's home zones reach the tunnel; here + // only connections from its home networks to people with home access pass + // (paused, ended and internet-only people are not reachable). The admin's + // own port forwards (DNAT) stay with fw4. + push(t, ' chain inbound {'); + push(t, ' type filter hook forward priority filter - 5; policy accept;'); + if (length(ifs)) + push(t, ` oifname { ${join(', ', ifs)} } iifname != { ${join(', ', ifs)} } ct state new jump to_device`); + push(t, ' }'); + push(t, ' chain to_device {'); + push(t, ' meta nfproto ipv6 drop'); + push(t, ' ct status dnat accept'); + push(t, ' ip saddr @lan_nets ip saddr != @tun_nets ip daddr @lan_all accept'); + push(t, ' ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept'); + push(t, ' counter reject with icmpx admin-prohibited'); + push(t, ' }'); + // Devices ask the tunnel address; send each query where it belongs. + let to_resolver = rt.mode == 'ns' && ip4(rt.address) ? `dnat ip to ${rt.address}:53` : `redirect to :${+rt.port}`; + let lan_dns = loop.lan_dns(); + if (!ip4(lan_dns)) + lan_dns = null; + push(t, ' chain dns {'); + push(t, ' type nat hook prerouting priority dstnat - 5; policy accept;'); + if (length(ifs)) + // Home names (and no LAN DNS at all): the plain resolver, whatever address was asked. + push(t, ` iifname { ${join(', ', ifs)} } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 ${to_resolver}`); + for (let id, srv in m.servers) + for (let tn in core.tunnels(srv)) { + // Everyone else: the LAN's DNS, through the netns (from the LAN side) when internet goes that way. + let target = srv.lan_like && dns_addr ? `dnat ip to ${dns_addr}:53` : lan_dns ? `dnat ip to ${lan_dns}:53` : to_resolver; + push(t, ` iifname "${tn.ifname}" ip daddr ${tn.address} meta l4proto { tcp, udp } th dport 53 ${target}`); + } + push(t, ' }'); + push(t, '}'); + return join('\n', t) + '\n'; +} + +/** Run an nft script (one transaction); null when it loaded, else what nft said. */ +function load(script) { + ensure_dir(RUN_DIR); + // A file of its own: two writers must never load each other's script. + let f = `${RUN_DIR}/nft.${rand_hex(4)}.rules`; + if (!write_file(f, script)) + return `couldn't write ${f}`; + let r = sh(`nft -f ${f}`); + unlink(f); + if (r.code == 0) + return null; + // Without the random file name, so the same failure reads the same every time. + return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`; +} + +/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */ +export function rebuild(m, sets) { + return load('table inet dawnline\ndelete table inet dawnline\n' + table(m, sets)); +}; + +/** + * Replace the members of every runtime set at once; null or the error. Fails + * as a whole when the table or one of its sets is missing (not loaded yet, + * or an older shape): the caller then rebuilds. + */ +export function update(sets) { + let s = ''; + for (let name in SETS) { + s += `flush set inet dawnline ${name}\n`; + if (length(sets[name])) + s += `add element inet dawnline ${name} { ${join(', ', sets[name])} }\n`; + } + return load(s); +}; + +/** Is the table loaded (watchdog). */ +export function present() { + return system('nft list table inet dawnline >/dev/null 2>&1') == 0; +}; + +export function remove() { + system('nft delete table inet dawnline 2>/dev/null'); +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/ops.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/ops.uc deleted file mode 100644 index 669478a..0000000 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/ops.uc +++ /dev/null @@ -1,689 +0,0 @@ -// Dawnline — operations: health checks (with fixes), backups, export/import. - -import { readfile, writefile, stat, unlink, lsdir } from 'fs'; -import { cursor } from 'uci'; -import { - q, sh, sh_out, ensure_dir, read_json, write_json, write_file, parse_cidr, cidr_overlaps, cidr_str, - ip2int, in_cidr, file_exists, valid_host, cloudflare_ip, DATA_DIR, RUN_DIR, VERSION -} from 'dawnline.util'; -import * as core from 'dawnline.core'; -import * as live from 'dawnline.live'; -import * as apply from 'dawnline.apply'; -import * as loop from 'dawnline.loop'; -import * as net from 'dawnline.net'; - -const BACKUP_DIR = `${DATA_DIR}/backups`; -const KEEP_BACKUPS = 10; - -/** - * Packages a feature needs that are missing, by feature: https (the portal: openssl-util and any - * TLS module for uhttpd), acme (Let's Encrypt certificates), home (the home-like link). Checked by - * files, so it is cheap enough for every page load. - */ -export function needs() { - let tls = false; - for (let d in [ '/lib', '/usr/lib' ]) - for (let f in lsdir(d) ?? []) - if (substr(f, 0, 16) == 'libustream-ssl.s') - tls = true; - let kver = trim(readfile('/proc/sys/kernel/osrelease') ?? ''); - let veth = stat('/sys/module/veth') != null || file_exists(`/lib/modules/${kver}/veth.ko`); - let miss = (list) => map(filter(list, (x) => !x[0]), (x) => x[1]); - return { - https: miss([ [ file_exists('/usr/bin/openssl'), 'openssl-util' ], [ tls, 'libustream-openssl' ] ]), - acme: miss([ [ file_exists('/usr/lib/acme/client/acme.sh'), 'acme' ], [ file_exists('/usr/lib/acme/client/dnsapi/dns_cf.sh'), 'acme-acmesh-dnsapi' ], - [ file_exists('/www/luci-static/resources/view/acme.js'), 'luci-app-acme' ] ]), - home: miss([ [ file_exists('/usr/libexec/ip-full'), 'ip-full' ], [ veth, 'kmod-veth' ] ]), - }; -}; - -/** True while OpenWrt's mDNS daemon answers on ubus. */ -export function mdns_running() { - return index(split(sh_out('ubus list umdns 2>/dev/null') ?? '', '\n'), 'umdns') >= 0; -}; - -/** - * Services announced on the home networks (Bonjour), from umdns: - * [{ type: '_airplay._tcp', name, host, address, port, txt }]. - */ -export function mdns_services() { - if (!mdns_running()) - return []; - let r = {}; - try { - r = json(sh_out(`ubus call umdns browse '{"address":true,"array":true}' 2>/dev/null`) || '{}') ?? {}; - } - catch (e) { - r = {}; - } - let out = []; - for (let t, insts in r) - for (let name, i in insts) { - let addr = type(i.ipv4) == 'array' ? i.ipv4[0] : i.ipv4; - if (addr) - push(out, { type: t, name, host: replace(i.host ?? '', /\.local\.?$/, ''), address: addr, port: i.port ?? 0, txt: i.txt ?? [] }); - } - return out; -}; - -/** ACME certificates on the router and the names each covers. */ -function acme_certs() { - let out = []; - for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) { - let m = match(f, /^(.+)\.fullchain\.crt$/); - if (!m) - continue; - let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`; - if (!file_exists(k)) - continue; - let sans = sh_out(`openssl x509 -in ${q(c)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? ''; - push(out, { cert: c, key: k, names: filter(split(replace(sans, /DNS:/g, ''), /[ \t\r\n]+/), (x) => x != '') }); - } - return out; -} - -/** The ACME certificate that covers host (exact name or a wildcard), if any. */ -function acme_cert_for(host) { - for (let a in acme_certs()) - for (let n in a.names) - if (n == host || (substr(n, 0, 2) == '*.' && index(host, '.') > 0 && substr(host, index(host, '.')) == substr(n, 1))) - return a; - return null; -} - -/** Certificate the portal should use: configured, ACME for the host, or self-signed. */ -export function portal_cert(s) { - if (s.portal_cert && s.portal_key && file_exists(s.portal_cert) && file_exists(s.portal_key)) - return { cert: s.portal_cert, key: s.portal_key, self_signed: false }; - if (s.portal_host) { - for (let base in [ `/etc/ssl/acme/${s.portal_host}`, `/etc/acme/${s.portal_host}_ecc/${s.portal_host}` ]) { - let c = `${base}.fullchain.crt`, k = `${base}.key`; - if (file_exists(c) && file_exists(k)) - return { cert: c, key: k, self_signed: false }; - } - // An ACME certificate issued for several names, the portal's among them. - let a = acme_cert_for(s.portal_host); - if (a) - return { cert: a.cert, key: a.key, self_signed: false }; - } - let c = `${DATA_DIR}/portal.crt`, k = `${DATA_DIR}/portal.key`; - if (!file_exists(c) || !file_exists(k)) { - ensure_dir(DATA_DIR, 0o700); - let cn = s.portal_host || 'dawnline'; - sh(`openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 -subj ${q('/CN=' + cn)} -keyout ${k} -out ${c}`); - system(`chmod 600 ${k}`); - } - return { cert: c, key: k, self_signed: true }; -}; - -/* ---------- health ---------- */ - -function check(id, title, status, detail, fix) { - return { id, title, status, detail: detail ?? '', fix: fix ?? null }; -} - -export function udp_listening(port) { - let hex = sprintf(':%04X ', port); - for (let f in [ '/proc/net/udp', '/proc/net/udp6' ]) - if (index(readfile(f) ?? '', hex) >= 0) - return true; - return false; -}; - -export function tcp_listening(port) { - let hex = sprintf(':%04X ', port); - for (let f in [ '/proc/net/tcp', '/proc/net/tcp6' ]) - for (let line in split(readfile(f) ?? '', '\n')) - // state 0A = LISTEN - if (index(line, hex) > 0 && match(line, / 0A /)) - return true; - return false; -}; - -/** Processes other than our portal listening on a TCP port: [ "name" ]. */ -export function tcp_port_owners(port) { - let out = sh_out(`netstat -lntp 2>/dev/null | awk '$4 ~ /:${+port}$/ {print $7}'`) ?? ''; - let owners = []; - for (let o in split(out, '\n')) { - let name = split(o, '/')[1]; - if (!name || index(owners, name) >= 0) - continue; - // Our own portal runs as a dedicated uhttpd instance. - let pid = +split(o, '/')[0]; - let cmd = readfile(`/proc/${pid}/cmdline`) ?? ''; - if (index(cmd, '/usr/share/dawnline/portal') >= 0) - continue; - push(owners, name); - } - return owners; -}; - -function resolve(host) { - if (ip2int(host) != null) - return [ host ]; - // Public resolvers first: local DNS often rewrites the router's own name - // to its LAN address (split horizon). - for (let srv in [ '1.1.1.1', '8.8.8.8', '127.0.0.1' ]) { - let out = sh_out(`timeout 5 nslookup ${q(host)} ${srv} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}'`); - let ips = out ? filter(split(out, '\n'), (x) => ip2int(x) != null) : []; - if (length(ips)) - return ips; - } - return []; -} - -function wan_ipv4(zone) { - let st = live.iface_status(zone == 'wan' ? 'wan' : zone); - return st?.['ipv4-address']?.[0]?.address; -} - -/** The router's public IPv4 (the first server's WAN, else the wan interface). */ -function router_wan(m) { - for (let id, srv in m.servers) - if (srv.private_key) { - let a = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone); - if (a) - return a; - } - return wan_ipv4('wan'); -} - -/* - * Addresses the portal could use in links, found on the router: names in ACME - * certificates, server endpoints, DDNS names, the current one, and the WAN IP. - * Each says where it points and whether a certificate covers it. - */ -export function portal_candidates(m) { - let wan = router_wan(m); - let names = []; - let add = (h) => { - if (h && valid_host(h) && ip2int(h) == null && substr(h, 0, 2) != '*.' && index(names, h) < 0) - push(names, h); - }; - for (let a in acme_certs()) - for (let n in a.names) - add(n); - for (let id, srv in m.servers) - add(srv.endpoint); - let dc = cursor(); - if (dc.load('ddns')) - dc.foreach('ddns', 'service', (sv) => { - if (sv.enabled != '0') { - add(sv.lookup_host); - add(sv.domain); - } - }); - for (let h in core.portal_hosts(m)) - add(h); - let out = []; - for (let h in names) { - let ips = resolve(h); - push(out, { host: h, kind: 'name', ips, here: wan != null && index(ips, wan) >= 0, - cloudflare: length(filter(ips, (x) => cloudflare_ip(x))) > 0, cert: acme_cert_for(h) != null }); - } - if (wan) - push(out, { host: wan, kind: 'ip', ips: [ wan ], here: true, cloudflare: false, cert: false }); - for (let ph in core.portal_hosts(m)) - if (ip2int(ph) != null && ph != wan) - push(out, { host: ph, kind: 'ip', ips: [ ph ], here: false, cloudflare: false, cert: false }); - // Best first: here with a certificate, then here, then the rest. - let score = (c) => (c.here ? 4 : 0) + (c.cert ? 2 : 0) + (c.kind == 'name' ? 1 : 0) - (c.cloudflare ? 8 : 0); - return sort(out, (a, b) => score(b) - score(a)); -}; - -export function service_running(name, instance) { - let s = sh_out(`ubus call service list '{"name":"${name}"}' 2>/dev/null`); - if (!s) - return false; - try { - let j = json(s); - let inst = j?.[name]?.instances?.[instance]; - return !!inst?.running; - } - catch (e) { - return false; - } -}; - -function other_subnets(srv_id) { - let out = []; - let st = sh_out('ubus call network.interface dump 2>/dev/null'); - let d = st ? json(st) : null; - let ours = {}; - let m = core.load(); - for (let id, s in m.servers) - ours[s.ifname] = id; - for (let i in d?.interface ?? []) { - if (srv_id != null && ours[i.interface] == srv_id) - continue; - for (let a in i['ipv4-address'] ?? []) - push(out, { iface: i.interface, cidr: `${a.address}/${a.mask}` }); - } - return out; -} - -export function used_subnets(except_srv) { - return map(other_subnets(except_srv), (x) => x.cidr); -}; - -/** - * Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix }. - * `fix` names an action accepted by fix(). - */ -/* - * Policy rules that send the router's own (marked) traffic into a local table, - * the way transparent proxies capture it: "pref 1000 fwmark 0x1 → table 100". - */ -function proxy_diverts() { - let out = []; - for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) { - let mm = match(line, /^(\d+):.*fwmark (\S+).* lookup (\S+)/); - if (!mm || +mm[1] >= 32766) - continue; - if (match(sh_out(`ip -4 route show table ${mm[3]} 2>/dev/null`) ?? '', /(^|\n)local default/)) - push(out, `pref ${mm[1]} fwmark ${mm[2]} → table ${mm[3]}`); - } - return out; -} - -/** Our "answers leave by main" rule for this port (see apply.sync_reply_routes). */ -function reply_rule(proto, port) { - return index(sh_out('ip -4 rule show priority 90 2>/dev/null') ?? '', `ipproto ${proto} sport ${+port} lookup main`) >= 0; -} - -function reply_check(id, title, proto, port, diverts) { - let ok = reply_rule(proto, port); - let via = length(diverts) ? ` A proxy on the router diverts its own traffic (${join(', ', diverts)}); these answers skip it.` : ''; - return check(id, title, ok ? 'ok' : (length(diverts) ? 'error' : 'warn'), - ok ? `Answers from ${uc(proto)} ${port} go straight out.${via}` - : length(diverts) ? `Answers from ${uc(proto)} ${port} can be swallowed by a proxy on the router (${join(', ', diverts)}): clients get no reply.` - : `The rule that keeps answers from ${uc(proto)} ${port} out of proxies is missing.`, - ok ? null : 'apply'); -} - -export function health(m) { - let diverts = proxy_diverts(); - m ??= core.load(); - let out = []; - let dmp = live.dump(); - - let kmod = file_exists('/sys/module/amneziawg'); - let tools = file_exists('/usr/bin/awg'); - push(out, check('awg', 'AmneziaWG installed', kmod && tools ? 'ok' : 'error', - kmod && tools ? 'Kernel module and awg tool present.' : - (!tools ? 'amneziawg-tools is missing.' : 'The kmod-amneziawg module is not loaded.'), kmod && tools ? null : 'updates')); - - let y = localtime().year; - push(out, check('clock', 'Clock is set', y >= 2025 ? 'ok' : 'error', - y >= 2025 ? 'End dates and quotas use the router clock.' : 'The router clock looks wrong; end dates will misbehave. Check NTP.')); - - push(out, check('agent', 'Background agent running', service_running('dawnline', 'agent') ? 'ok' : 'error', - 'Counts traffic and enforces end dates and quotas.', service_running('dawnline', 'agent') ? null : 'restart')); - - if (!length(m.servers)) { - push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.')); - return out; - } - - let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0; - push(out, check('nft', 'Access rules loaded', nft_ok ? 'ok' : 'error', - nft_ok ? 'Table inet dawnline enforces who may reach LAN and the internet.' : 'Table inet dawnline is missing: access is not enforced.', - nft_ok ? null : 'apply')); - - let fwc = cursor(); - fwc.load('firewall'); - - for (let id, srv in m.servers) { - let label = length(m.servers) > 1 ? ` (${srv.name})` : ''; - if (!srv.enabled) { - push(out, check(`srv_${id}`, `Server${label}`, 'skip', 'Server is disabled.')); - continue; - } - let st = live.iface_status(srv.ifname); - let up = !!st?.up; - push(out, check(`up_${id}`, `Tunnel interface up${label}`, up ? 'ok' : 'error', - up ? `${srv.ifname} is up, listening on UDP ${srv.port}.` : - (st ? `${srv.ifname} is down${st.errors ? ': ' + join(', ', map(st.errors, (e) => e.code)) : ''}.` : `${srv.ifname} does not exist.`), - up ? null : (st ? 'ifup:' + srv.ifname : 'apply'))); - - if (up) { - let expected = 0; - let states = apply.states_for(m, core.load_usage()); - for (let did, d in m.devices) - if (m.people[d.person]?.server == id && !d.disabled && states[d.person] == 'active') - expected++; - let actual = 0; - for (let k, p in dmp.peers) - if (p.ifname == srv.ifname) - actual++; - push(out, check(`peers_${id}`, `Devices loaded${label}`, expected == actual ? 'ok' : 'warn', - `${actual} of ${expected} active devices are loaded in the tunnel.`, expected == actual ? null : 'sync')); - } - - let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule'; - let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone'; - push(out, check(`fw_${id}`, `Firewall${label}`, rule && zone ? 'ok' : 'error', - rule && zone ? `Zone ${srv.ifname} and the WAN rule for UDP ${srv.port} exist.` : 'Firewall zone or WAN rule is missing.', - rule && zone ? null : 'apply')); - push(out, reply_check(`reply_${id}`, `Answers reach clients${label}`, 'udp', srv.port, diverts)); - - // Port collisions with other tunnels. - let clash = []; - let nc = cursor(); - nc.load('network'); - nc.foreach('network', 'interface', (s) => { - if (s['.name'] != srv.ifname && (s.proto == 'amneziawg' || s.proto == 'wireguard') && +s.listen_port == srv.port) - push(clash, s['.name']); - }); - if (length(clash)) - push(out, check(`port_${id}`, `Port is free${label}`, 'error', `UDP ${srv.port} is also used by ${join(', ', clash)}.`)); - - let overlaps = []; - let sc = parse_cidr(srv.subnet); - for (let o in other_subnets(id)) { - let oc = parse_cidr(o.cidr); - if (sc && oc && cidr_overlaps(sc, oc)) - push(overlaps, `${o.iface} (${o.cidr})`); - } - push(out, check(`subnet_${id}`, `Subnet is unique${label}`, length(overlaps) ? 'error' : 'ok', - length(overlaps) ? `${srv.subnet} overlaps ${join(', ', overlaps)}.` : `${srv.subnet} does not overlap other networks.`)); - - let host = core.endpoint_host(m, srv); - if (!host) - push(out, check(`ep_${id}`, `Public address${label}`, 'error', 'No endpoint hostname: clients will not know where to connect.')); - else { - let ips = resolve(host); - let wan = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone); - let wc = wan ? ip2int(wan) : null; - let cgnat = wc != null && (in_cidr(wc, parse_cidr('100.64.0.0/10')) || in_cidr(wc, parse_cidr('10.0.0.0/8')) || - in_cidr(wc, parse_cidr('172.16.0.0/12')) || in_cidr(wc, parse_cidr('192.168.0.0/16'))); - let stv = 'ok', det; - if (!length(ips)) { - stv = 'error'; - det = `${host} does not resolve.`; - } - else if (cgnat) { - stv = 'warn'; - det = `WAN address ${wan} is private: forward UDP ${srv.port} on the upstream router, or clients cannot connect.`; - } - else if (length(filter(ips, (a) => cloudflare_ip(a)))) - det = `${host} → ${join(', ', ips)} (Cloudflare). The tunnel is UDP: it reaches the router only if this name is DNS-only there.`; - else if (wan && index(ips, wan) < 0) { - stv = 'warn'; - det = `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`; - } - else - det = `${host} → ${join(', ', ips)}`; - push(out, check(`ep_${id}`, `Public address${label}`, stv, det)); - } - - if (srv.lan_like) { - let ls = loop.status(); - let nh = needs().home; - push(out, check(`home_${id}`, `Internet like a home device${label}`, ls.active && ls.bridged ? 'ok' : 'warn', - ls.active && ls.bridged ? `Traffic enters ${ls.dev} as ${ls.address}, so it is handled like any device on your LAN.` : - length(nh) ? `Needs ${join(' and ', nh)}. Internet traffic leaves through WAN directly until then.` : - ls.active ? `The link is up but not attached to ${ls.dev}.` : - `${ls.error ?? 'Not set up.'} Internet traffic leaves through WAN directly.`, - ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply')); - } - } - - if (length(filter(values(m.servers), (x) => x.private_key))) { - let rt = loop.resolver_target(); - let ok = stat(loop.RESOLVER.conf) != null && loop.resolver_running(); - push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn', - ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`) - : 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply')); - } - - let s = m.settings; - let need = needs(); - if (s.portal_enabled && length(need.https)) - push(out, check('portal', 'Personal portal', 'error', - `HTTPS isn't available on this router: install ${join(' and ', need.https)}.`, 'install:https')); - else if (s.portal_enabled) { - let owners = tcp_port_owners(s.portal_port); - let listening = tcp_listening(s.portal_port); - if (length(owners)) - push(out, check('portal', 'Personal portal', 'error', - `TCP ${s.portal_port} is already used by ${join(', ', owners)}. Choose another port in Settings.`)); - else - push(out, check('portal', 'Personal portal', listening ? 'ok' : 'error', - listening ? `Listening on TCP ${s.portal_port}.` : `Nothing listens on TCP ${s.portal_port}.`, listening ? null : 'restart')); - if (!s.portal_host) - push(out, check('portal_host', 'Portal address', 'error', 'Set the public hostname in Settings so links can be generated.')); - else { - let ips = resolve(s.portal_host), wan = router_wan(m); - let cf = filter(ips, (x) => cloudflare_ip(x)); - push(out, check('portal_dns', 'Portal address points here', !length(ips) ? 'error' : length(cf) ? 'ok' : wan && index(ips, wan) < 0 ? 'warn' : 'ok', - !length(ips) ? `${s.portal_host} does not resolve.` : - length(cf) ? `${s.portal_host} goes through Cloudflare; in Russia such connections often stall after ~16 KB.` : - wan && index(ips, wan) < 0 ? `${s.portal_host} points at ${join(', ', ips)}, not this router (${wan}).` : - `${s.portal_host} → ${join(', ', ips)}${wan ? ' (this router)' : ''}.`)); - } - push(out, reply_check('portal_reply', 'Portal answers reach visitors', 'tcp', s.portal_port, diverts)); - if (core.portal_http(m)) { - let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null); - push(out, check('portal_http', 'Plain HTTP links', 'warn', - `Links on ${join(', ', ipl)} use plain HTTP: the link and the VPN keys in configurations travel unencrypted.`)); - } - - // Links on 443: forwarded from outside, and the same link at home through LuCI's web server. - let pub = core.portal_public_port(m); - if (s.portal_port != 443) { - if (!s.portal_443) - push(out, check('portal_443', 'Links without a port', 'skip', - `Off: links use port ${s.portal_port}. Mobile networks often drop HTTPS on ports other than 443.`)); - else if (pub != 443) - push(out, check('portal_443', 'Links without a port', 'warn', - `TCP 443 is already forwarded to another device, so links use port ${s.portal_port}.`)); - else { - let fw = system(`nft list ruleset 2>/dev/null | grep -q 'Dawnline-Portal-443'`) == 0; - push(out, check('portal_443', 'Links without a port', fw ? 'ok' : 'error', - fw ? `From the internet TCP 443 reaches the portal only (LuCI stays closed there).` : 'The 443 forward to the portal is missing.', - fw ? null : 'apply')); - let uc_ = cursor(); - uc_.load('uhttpd'); - let ep = uc_.get('uhttpd', 'main', 'error_page'); - let mine = ep == '/cgi-bin/dawnline-portal' && stat('/www/cgi-bin/dawnline-portal') != null; - push(out, check('portal_lan', 'Same link at home', mine ? 'ok' : ep ? 'warn' : 'error', - mine ? 'At home the link opens through LuCI\'s web server, which hands unknown paths to the portal.' - : ep ? `LuCI's web server already uses ${ep} for unknown paths, so at home links need :${s.portal_port}.` - : 'LuCI\'s web server does not hand portal links to the portal: at home they show Not found.', - mine || ep ? null : 'apply')); - } - } - - let cert = portal_cert(s); - if (ip2int(s.portal_host) != null) - push(out, check('cert', 'Portal certificate', 'skip', 'The main address is an IP: its links use plain HTTP.')); - else { - let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0; - let sans = cert.self_signed ? [] : split(replace(sh_out(`openssl x509 -in ${q(cert.cert)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '', /DNS:/g, ''), /[ \t\r\n]+/); - let covers = !s.portal_host || cert.self_signed || index(sans, s.portal_host) >= 0 || - length(filter(sans, (n) => substr(n, 0, 2) == '*.' && substr(s.portal_host, index(s.portal_host, '.')) == substr(n, 1))); - push(out, check('cert', 'Portal certificate', cert.self_signed || !ok || !covers ? 'warn' : 'ok', - cert.self_signed ? `Using a self-signed certificate: browsers will show a warning.${length(need.acme) ? ' ACME can get a free Let’s Encrypt one.' : ''}` : - !covers ? `${cert.cert} does not cover ${s.portal_host} (it has ${join(', ', sans)}): browsers will warn.` : - ok ? `${cert.cert} covers ${s.portal_host} and is valid for more than 14 days.` : `${cert.cert} expires within 14 days.`)); - } - } - - return out; -}; - -export function fix(id) { - if (id == 'apply') - return apply.apply(); - if (id == 'sync') - return apply.sync(); - if (id == 'restart') - return { code: system('/etc/init.d/dawnline restart >/dev/null 2>&1') }; - let m = match(id ?? '', /^ifup:([a-z][a-z0-9_]{0,11})$/); - if (m) { - system(`ifup ${q(m[1])}`); - return { ok: true }; - } - die('Unknown fix.'); -}; - -/* ---------- backups ---------- */ - -function backup_files() { - let out = [ '/etc/config/dawnline' ]; - for (let f in [ 'usage.json', 'events.json' ]) - if (file_exists(`${DATA_DIR}/${f}`)) - push(out, `${DATA_DIR}/${f}`); - return out; -} - -export function backup_list() { - let out = []; - for (let f in lsdir(BACKUP_DIR) ?? []) { - let mm = match(f, /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/); - if (!mm) - continue; - let st = stat(`${BACKUP_DIR}/${f}`); - push(out, { name: f, created: st?.mtime ?? 0, size: st?.size ?? 0, reason: mm[3] ?? 'manual' }); - } - return sort(out, (a, b) => b.created - a.created); -}; - -export function backup_create(reason) { - // Flush live counters first so the backup has current usage. - let u = read_json(`${RUN_DIR}/usage.json`, null); - if (u) - write_json(`${DATA_DIR}/usage.json`, u, 0o600); - live.persist_events(); - ensure_dir(BACKUP_DIR, 0o700); - let t = localtime(); - let tag = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? `-${reason}` : ''; - let name = sprintf('dawnline-%04d%02d%02d-%02d%02d%02d%s.tar.gz', t.year, t.mon, t.mday, t.hour, t.min, t.sec, tag); - let files = join(' ', map(backup_files(), (f) => q(substr(f, 1)))); - let r = sh(`tar -czf ${q(BACKUP_DIR + '/' + name)} -C / ${files}`); - if (r.code != 0) - die(`Backup failed: ${trim(r.out)}`); - system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`); - let all = backup_list(); - for (let i = KEEP_BACKUPS; i < length(all); i++) - unlink(`${BACKUP_DIR}/${all[i].name}`); - return name; -}; - -function backup_path(name) { - if (!match(name ?? '', /^dawnline-[0-9]{8}-[0-9]{6}(-[a-z0-9-]+)?\.tar\.gz$/)) - die('Invalid backup name.'); - let p = `${BACKUP_DIR}/${name}`; - if (!file_exists(p)) - die('Backup not found.'); - return p; -} - -/** Validate an archive: only Dawnline's own files may be inside. */ -function check_archive(path) { - let r = sh(`tar -tzf ${q(path)}`); - if (r.code != 0) - die('Not a valid backup archive.'); - let allowed = { 'etc/config/dawnline': true }; - let has_config = false; - for (let f in split(trim(r.out), '\n')) { - f = replace(f, /^\.?\//, ''); - // The config plus Dawnline's own data files (older versions had more of them). - if (!allowed[f] && !match(f, /^etc\/dawnline\/[a-z0-9_-]+\.json$/)) - die(`Unexpected file in backup: ${f}`); - if (f == 'etc/config/dawnline') - has_config = true; - } - if (!has_config) - die('Backup does not contain /etc/config/dawnline.'); -} - -export function backup_restore(name, path) { - path ??= backup_path(name); - check_archive(path); - backup_create('pre-restore'); - let r = sh(`tar -xzf ${q(path)} -C /`); - if (r.code != 0) - die(`Restore failed: ${trim(r.out)}`); - system('chmod 600 /etc/config/dawnline'); - // Live counters must follow the restored file. - unlink(`${RUN_DIR}/usage.json`); - unlink(`${RUN_DIR}/events.json`); - return apply.apply(); -}; - -export function backup_delete(name) { - unlink(backup_path(name)); - return true; -}; - -export function backup_read(name) { - return b64enc(readfile(backup_path(name))); -}; - -export function backup_upload(data_b64) { - let data = b64dec(data_b64 ?? ''); - if (!data || length(data) > 4 * 1024 * 1024) - die('Upload is empty or too large.'); - ensure_dir(RUN_DIR); - let tmp = `${RUN_DIR}/upload.tar.gz`; - write_file(tmp, data); - let res; - try { - res = backup_restore(null, tmp); - } - catch (e) { - unlink(tmp); - die(e.message); - } - unlink(tmp); - return res; -}; - -/* ---------- export / import (JSON) ---------- */ - -export function export_json() { - let c = cursor(); - c.load('dawnline'); - let sections = []; - c.foreach('dawnline', null, (s) => { - let o = { '.type': s['.type'], '.name': s['.name'] }; - for (let k, v in s) - if (substr(k, 0, 1) != '.') - o[k] = v; - push(sections, o); - }); - return { format: 'dawnline', version: VERSION, exported: time(), sections }; -}; - -export function import_json(data) { - if (type(data) != 'object' || data.format != 'dawnline' || type(data.sections) != 'array') - die('Not a Dawnline export.'); - let types = { settings: true, server: true, person: true, device: true, service: true }; - for (let s in data.sections) { - if (!types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/)) - die(`Invalid section ${s['.name']}.`); - for (let k, v in s) - if (substr(k, 0, 1) != '.' && (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array'))) - die(`Invalid option ${k}.`); - } - backup_create('pre-import'); - let lines = []; - for (let s in data.sections) { - push(lines, `config ${s['.type']} '${s['.name']}'`); - for (let k, v in s) { - if (substr(k, 0, 1) == '.') - continue; - let esc = (x) => replace(`${x}`, "'", "'\\''"); - if (type(v) == 'array') - for (let x in v) - push(lines, `\tlist ${k} '${esc(x)}'`); - else - push(lines, `\toption ${k} '${esc(v)}'`); - } - push(lines, ''); - } - write_file('/etc/config/dawnline', join('\n', lines), 0o600); - return apply.apply(); -}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc new file mode 100644 index 0000000..41c8eac --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc @@ -0,0 +1,120 @@ +// Dawnline — one interface over the router's package manager: opkg on +// OpenWrt 24.10, apk on 25.12. Commands that change packages take a log(line) +// callback, which gets their output line by line. + +import { access, popen } from 'fs'; +import { q } from 'dawnline.util'; + +function run(cmd) { + let p = popen(cmd + ' 2>&1', 'r'); + if (!p) + return { code: 127, out: '' }; + let out = p.read('all') ?? ''; + return { code: p.close(), out }; +} + +function logged(cmd, log) { + let r = run(cmd); + for (let line in split(trim(r.out), '\n')) + if (length(trim(line))) + log?.(` ${line}`); + return r; +} + +export function is_apk() { + return access('/usr/bin/apk', 'x'); +}; + +export function ext() { + return is_apk() ? 'apk' : 'ipk'; +}; + +/** The installed version of a package, or null. */ +export function version(name) { + let esc = replace(name, /[.+]/g, '\\$&'); + if (is_apk()) { + let m = match(run(`apk list --installed ${q(name)}`).out, regexp(`^${esc}-([^ ]+) `)); + return m ? m[1] : null; + } + // Libraries carry their ABI in the name (libustream-openssl20201210). + let re = regexp(`^${esc}([0-9]+)? - (.+)$`), found = null; + for (let line in split(run('opkg list-installed').out, '\n')) { + let m = match(trim(line), re); + if (m && (found == null || m[1] == null)) + found = m; + } + return found ? trim(found[2]) : null; +}; + +/** The version inside a package file, or null. */ +export function file_version(path) { + if (match(path, /\.ipk$/)) { + let o = run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out; + return match(o, /(^|\n)Version: *([^\n]+)/)?.[2]; + } + return match(run(`apk adbdump ${q(path)}`).out, /\n *version: *([^\n]+)/)?.[1]; +}; + +/** + * Compare two package versions the way the package manager does (so -r10 is + * newer than -r9 and ~rc before the release): -1, 0 or 1; null when unknown. + */ +export function cmp(a, b) { + if (a == null || b == null) + return null; + if (a == b) + return 0; + if (is_apk()) { + let r = trim(run(`apk version -t ${q(a)} ${q(b)}`).out); + return r == '<' ? -1 : r == '>' ? 1 : r == '=' ? 0 : null; + } + if (run(`opkg compare-versions ${q(a)} '<<' ${q(b)}`).code == 0) + return -1; + if (run(`opkg compare-versions ${q(a)} '>>' ${q(b)}`).code == 0) + return 1; + return 0; +}; + +export function refresh(log) { + return logged(is_apk() ? 'apk update' : 'opkg update', log).code == 0; +}; + +/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */ +export function install_files(files, force, log) { + let args = join(' ', map(files, q)); + return logged(is_apk() + ? `apk add --allow-untrusted ${args}` + : `opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0; +}; + +/** Packages by name from the feeds. */ +export function add(names, log) { + return logged(is_apk() ? `apk add ${join(' ', map(names, q))}` : `opkg install ${join(' ', map(names, q))}`, log).code == 0; +}; + +export function upgrade(names, log) { + return logged(is_apk() ? `apk upgrade ${join(' ', map(names, q))}` : `opkg upgrade ${join(' ', map(names, q))}`, log).code == 0; +}; + +export function remove(names, log) { + return logged(is_apk() ? `apk del ${join(' ', map(names, q))}` : `opkg remove ${join(' ', map(names, q))}`, log).code == 0; +}; + +/** Installed packages with a newer version in the feeds: { name: latest }. */ +export function upgradable() { + let up = {}; + if (is_apk()) { + for (let line in split(run('apk version -l "<"').out, '\n')) { + let m = match(line, /^(\S+?)-([0-9][^ ]*)\s+<\s+(\S+)/); + if (m) + up[m[1]] = m[3]; + } + } + else + for (let line in split(run('opkg list-upgradable').out, '\n')) { + let m = match(line, /^(\S+) - (\S+) - (\S+)/); + if (m) + up[m[1]] = m[3]; + } + return up; +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc new file mode 100644 index 0000000..13fafd4 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc @@ -0,0 +1,463 @@ +// Dawnline — the personal portal. +// +// GET / the app shell +// GET //assets/ its script, styles and fonts +// GET //api/state +// POST //api/devices { name, kind, public_key? } +// GET //api/devices//config +// POST //api/devices/ { action: rename|rotate|delete, name? } +// +// The personal link is the key: every request carries its code, there are +// no sessions. Without a valid code every path answers the same bare 404 — +// the root, a person's link, the API and the assets alike — so nothing tells +// a scanner there is a portal here. Wrong codes are rate-limited per client +// (blocked clients get the same 404 even with the right code): per IPv4 +// address or IPv6 /64; behind Cloudflare per visitor (CF-Connecting-IP), with +// a higher ceiling for all Cloudflare visitors together. +// Regenerating the code in LuCI locks the old link out at once. POST bodies +// must be JSON from the same origin; Referrer-Policy keeps the code out of +// other sites' logs. The portal can only manage the person's own devices +// within their limits, and not those the admin turned off (dawnline.devices). +// +// handle() serves one request: `io` = { env, headers, read(n), write(s) }; the +// CGI script (www/cgi-bin/portal) is its wrapper. + +import { stat, readfile } from 'fs'; +import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, VERSION, RUN_DIR } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as awg from 'dawnline.awg'; +import * as live from 'dawnline.live'; +import * as view from 'dawnline.view'; +import * as schema from 'dawnline.schema'; +import * as devices from 'dawnline.devices'; + +const RATE = `${RUN_DIR}/portal-rate.json`; +const ASSETS = '/usr/share/dawnline/portal/assets'; +const TYPES = { js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml', woff2: 'font/woff2', png: 'image/png' }; +const FAIL_LIMIT = 8; +const FAIL_WINDOW = 900; +// All Cloudflare visitors together (three-word codes can't be guessed anyway). +const SHARED_LIMIT = FAIL_LIMIT * 25; +const SHARED_KEY = 'cloudflare'; +// Clients remembered at most (the oldest go first). +const RATE_MAX = 2000; +const BODY_MAX = 8192; +// The early end of a request (a response was written). +const DONE = '__dawnline_done__'; + +const SECURITY_HEADERS = { + 'X-Content-Type-Options': 'nosniff', + 'Referrer-Policy': 'no-referrer', + 'X-Frame-Options': 'DENY', + 'Cache-Control': 'no-store', +}; + +const NOT_READY = "Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link."; + +function html_escape(s) { + return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); +} + +/* ---------- answering ---------- */ + +function headers(r, status, extra) { + let h = `Status: ${status}\r\n`; + let all = { ...SECURITY_HEADERS, ...(extra ?? {}) }; + // HSTS pins the whole name: only when the visitor is on the standard port. + if (r.hsts) + all['Strict-Transport-Security'] = 'max-age=31536000'; + for (let k, v in all) + h += `${k}: ${v}\r\n`; + r.io.write(h + '\r\n'); +} + +function finish() { + die(DONE); +} + +function send_json(r, status, obj) { + headers(r, status, { 'Content-Type': 'application/json' }); + r.io.write(sprintf('%J', obj)); + finish(); +} + +function fail(r, status, msg) { + send_json(r, status, { error: msg }); +} + +/** + * The one answer for anything without a valid code: a bare 404, or the redirect from Settings. + * Files always get the 404: a missing asset must not turn into someone's website. + */ +function not_found(r) { + let redirect = r.m.settings.portal_redirect; + let parts = split(r.path, '/'); + let file = match(r.path, /^\/(luci-static|cgi-bin|ubus)(\/|$)/) || match(parts[length(parts) - 1], /\./); + if (redirect && !file) { + headers(r, '302 Found', { 'Location': redirect, 'Cache-Control': 'no-store', 'Content-Type': 'text/plain' }); + r.io.write('Moved\n'); + } + else { + headers(r, '404 Not Found', { 'Content-Type': 'text/plain' }); + r.io.write('Not found\n'); + } + finish(); +} + +/** The JSON object a POST carries ({} without a body). */ +function body(r) { + let len = +(r.env.CONTENT_LENGTH ?? 0); + if (len <= 0) + return {}; + if (len > BODY_MAX) + fail(r, '413 Payload Too Large', 'Request too large.'); + let raw = ''; + while (length(raw) < len) { + let chunk = r.io.read(len - length(raw)); + if (chunk == null || chunk == '') + break; + raw += chunk; + } + try { + let j = json(raw); + return type(j) == 'object' ? j : {}; + } + catch (e) { + fail(r, '400 Bad Request', 'Invalid JSON.'); + } +} + +/** Run a change; what it refuses becomes a 400 with its message. */ +function guard(r, fn) { + try { + return fn(); + } + catch (e) { + if (e.message == DONE) + die(DONE); + fail(r, '400 Bad Request', e.message); + } +} + +/* ---------- rate limiting ---------- */ + +/** The rate-limit key of an address: an IPv4 address, or the /64 of an IPv6 one. */ +function addr_key(a) { + if (schema.ipv4(a)) + return a; + let g = schema.ipv6_groups(a); + if (!g) + return null; + // An IPv4 address seen through an IPv6 socket. + if (g[0] == 0 && g[1] == 0 && g[2] == 0 && g[3] == 0 && g[4] == 0 && g[5] == 0xffff) + return sprintf('%d.%d.%d.%d', g[6] >> 8, g[6] & 255, g[7] >> 8, g[7] & 255); + return sprintf('%x:%x:%x:%x::/64', g[0], g[1], g[2], g[3]); +} + +/** + * The buckets a request counts against, [{ key, limit }]: its client, and + * behind Cloudflare (the only proxy whose CF-Connecting-IP is believed) also + * the bucket all Cloudflare visitors share. + */ +function buckets(env) { + let peer = env.REMOTE_ADDR ?? ''; + if (!cloudflare_ip(peer)) + return [ { key: addr_key(peer) ?? peer, limit: FAIL_LIMIT } ]; + let out = [ { key: SHARED_KEY, limit: SHARED_LIMIT } ]; + let visitor = addr_key(trim(env.HTTP_CF_CONNECTING_IP ?? '')); + if (visitor && !cloudflare_ip(visitor)) + unshift(out, { key: visitor, limit: FAIL_LIMIT }); + return out; +} + +function rate_state() { + let st = read_json(RATE, {}); + let now = time(); + for (let k, v in st) + if (type(v) != 'object' || now - v.first > FAIL_WINDOW) + delete st[k]; + return st; +} + +function rate_blocked(r) { + let st = rate_state(); + return length(filter(r.buckets, (b) => (st[b.key]?.count ?? 0) >= b.limit)) > 0; +} + +function rate_fail(r) { + let l = lock('portal-rate'); + let st = rate_state(); + let now = time(); + let hit = []; + for (let b in r.buckets) { + let v = st[b.key] ?? { first: now, count: 0 }; + v.count++; + st[b.key] = v; + if (v.count == b.limit) + push(hit, b.key); + } + // Bounded: an attacker with many addresses cannot grow the file without end. + let all = keys(st); + if (length(all) > RATE_MAX) { + all = sort(all, (a, b) => st[a].first - st[b].first); + for (let i = 0; i < length(all) - RATE_MAX; i++) + delete st[all[i]]; + } + ensure_dir(RUN_DIR); + write_json(RATE, st, 0o600); + unlock(l); + for (let k in hit) + live.add_event({ type: 'portal_blocked', detail: k == SHARED_KEY ? 'all Cloudflare visitors' : k }); +} + +/* ---------- pages ---------- */ + +/** The app shell; it reads the code from its own URL and sends it along. */ +function shell(r) { + // The build's time joins the version so every update busts the hour-long asset cache. + let v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`; + let base = r.base, title = r.title; + headers(r, '200 OK', { + 'Content-Type': 'text/html; charset=utf-8', + 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " + + "connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'", + }); + r.io.write(` + + + + + + +${html_escape(title)} + + + + +

+ + + +`); + finish(); +} + +/** Script, styles, icon and fonts (kept outside the web root). */ +function asset(r, name) { + let ext = match(name, /^[a-z0-9-]+\.(js|css|svg|woff2|png)$/)?.[1]; + let data = ext ? readfile(`${ASSETS}/${name}`) : null; + if (data == null) + not_found(r); + headers(r, '200 OK', { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=3600' }); + r.io.write(data); + finish(); +} + +/* ---------- the API ---------- */ + +/** The model again after a change. */ +function reload(r) { + r.m = core.load(); + r.person = r.m.people[r.person.id]; + if (!r.person) + not_found(r); +} + +/** Everything the page shows. */ +function state(r) { + let m = r.m, person = r.person; + let usage = core.load_usage(); + let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage)); + let srv = m.servers[person.server]; + // The device this page was opened from, when it came through the tunnel. + let here = null; + for (let id, d in m.devices) + if (d.person == person.id && d.address == r.peer) + here = id; + return { + title: r.title, + person: v, + here, + server: { + name: srv?.name, endpoint: srv ? core.endpoint_host(m, srv) : '', device_mesh: !!srv?.device_mesh, + // AmneziaWG with the disguise off is plain WireGuard (any WireGuard app). + awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false, + }, + can_add: length(person.devices) < person.device_limit, + kinds: core.KINDS, + // The router's day: access ends and usage days follow its clock, not the browser's. + today: today(), + version: VERSION, + }; +} + +/** One of the person's own devices, or a 404. */ +function own_device(r, id) { + let d = r.m.devices[id]; + if (!d || d.person != r.person.id) + fail(r, '404 Not Found', 'Device not found.'); + return d; +} + +function api_state(r) { + send_json(r, '200 OK', state(r)); +} + +function api_add(r) { + let b = body(r); + if (!devices.ready()) + fail(r, '503 Service Unavailable', NOT_READY); + let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key })); + reload(r); + send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) }); +} + +function api_config(r, id) { + let d = own_device(r, id); + awg.mark_issued(r.m, d.id); + send_json(r, '200 OK', awg.client_config(r.m, d)); +} + +/** POST /devices/ { action }: what each action does; the answer carries the new state. */ +const ACTIONS = { + rename: (r, d, b) => { + guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id })); + return {}; + }, + rotate: (r, d, b) => { + if (!devices.ready()) + fail(r, '503 Service Unavailable', NOT_READY); + let config = guard(r, () => devices.rotate(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer })); + return { config }; + }, + 'delete': (r, d, b) => { + guard(r, () => devices.remove(d.id, { by: 'portal', person: r.person.id })); + return {}; + }, +}; + +function api_device(r, id) { + let d = own_device(r, id); + let b = body(r); + let act = ACTIONS[b.action]; + if (!act) + fail(r, '400 Bad Request', 'Unknown action.'); + let res = act(r, d, b); + reload(r); + send_json(r, '200 OK', { ok: true, ...res, state: state(r) }); +} + +/** API routes: method, path under //api ('*' matches one segment, passed to run). */ +const API = [ + { method: 'GET', path: [ 'state' ], run: api_state }, + { method: 'POST', path: [ 'devices' ], run: api_add }, + { method: 'GET', path: [ 'devices', '*', 'config' ], run: api_config }, + { method: 'POST', path: [ 'devices', '*' ], run: api_device }, +]; + +/** The route for a request: { run, args } or null (routes take at most one '*'). */ +function route(table, method, segs) { + for (let rt in table) { + if (rt.method != method || length(rt.path) != length(segs)) + continue; + let args = [], ok = true; + for (let i = 0; i < length(segs) && ok; i++) + if (rt.path[i] == '*') + push(args, segs[i]); + else if (rt.path[i] != segs[i]) + ok = false; + if (ok) + return { run: rt.run, args }; + } + return null; +} + +/* ---------- one request ---------- */ + +export function handle(io) { + let env = io.env ?? {}; + // Header names arrive lower-case from uhttpd; CGI has only HTTP_* variables. + let hdr = {}; + for (let k, v in io.headers ?? {}) + hdr[lc(k)] = v; + let header = (name) => hdr[name] ?? env[`HTTP_${uc(replace(name, /-/g, '_'))}`]; + let uri = env.REQUEST_URI ?? '/'; + let qpos = index(uri, '?'); + let path = qpos >= 0 ? substr(uri, 0, qpos) : uri; + let https = env.HTTPS == 'on'; + let host = header('host') ?? ''; + let m = core.load(); + let r = { + io, env, m, path, https, + method: env.REQUEST_METHOD ?? 'GET', + peer: env.REMOTE_ADDR ?? '', + buckets: buckets(env), + title: m.settings.portal_title || 'Dawnline', + // The port in the visitor's address bar ([v6]:port, name:port, or the default). + hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443', + person: null, + base: '', + }; + let segs = filter(split(path, '/'), (s) => s != ''); + + // Plain HTTP only for an IP address chosen in Settings (no certificate exists + // for it); names stay HTTPS-only. + if (!https) { + let h = match(host, /^\[/) ? host : split(host, ':')[0]; + if (ip2int(h) == null || index(core.portal_hosts(m), h) < 0) + not_found(r); + } + // The link is /[/assets/…|/api/…]: the code is the address. + if (length(segs) < 1 || !match(segs[0], core.WORD_CODE)) + not_found(r); + let code = segs[0]; + for (let id, p in m.people) + if (p.code == code) + r.person = p; + + // A wrong code or a blocked client: indistinguishable from a path that does + // not exist. Only well-formed guesses count towards the limit. + if (rate_blocked(r)) + not_found(r); + if (r.person == null) { + rate_fail(r); + not_found(r); + } + r.base = `/${code}`; + let rest = slice(segs, 1); + + if (length(rest) == 0 && r.method == 'GET') + shell(r); + if (rest[0] == 'assets' && length(rest) == 2 && r.method == 'GET') + asset(r, rest[1]); + if (rest[0] != 'api') + not_found(r); + + // CSRF: only same-origin JSON requests (a cross-site page cannot send + // application/json without CORS, and it would need the code anyway). + if (r.method == 'POST') { + let origin = header('origin'); + if (!match(env.CONTENT_TYPE ?? '', /^application\/json/) || + (origin != null && origin != `${https ? 'https' : 'http'}://${host}`)) + fail(r, '403 Forbidden', 'Cross-site request refused.'); + } + else if (r.method != 'GET') + fail(r, '405 Method Not Allowed', 'Method not allowed.'); + + let rt = route(API, r.method, slice(rest, 1)); + if (!rt) + fail(r, '404 Not Found', 'Not found.'); + rt.run(r, rt.args[0]); + fail(r, '404 Not Found', 'Not found.'); +}; + +/** Run handle() and swallow its early end. */ +export function serve(io) { + try { + handle(io); + } + catch (e) { + if (e.message != DONE) + io.write(`Status: 500 Internal Server Error\r\nContent-Type: text/plain\r\n\r\nError\n`); + } +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portalcert.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portalcert.uc new file mode 100644 index 0000000..54fd317 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portalcert.uc @@ -0,0 +1,116 @@ +// Dawnline — the portal's certificate (configured, ACME or self-signed) and +// the addresses its links could use. + +import { lsdir } from 'fs'; +import { cursor } from 'uci'; +import { q, sh, sh_out, ensure_dir, file_exists, valid_host, ip2int, cloudflare_ip, DATA_DIR } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as lookup from 'dawnline.lookup'; + +/** The DNS names a certificate file covers. */ +export function cert_names(path) { + let sans = sh_out(`openssl x509 -in ${q(path)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? ''; + return filter(split(replace(sans, /DNS:/g, ''), /[ \t\r\n]+/), (x) => x != ''); +}; + +/** A certificate name covers host: the same name, or a wildcard one level up. */ +export function name_covers(name, host) { + if (name == host) + return true; + let dot = index(host ?? '', '.'); + return substr(name, 0, 2) == '*.' && dot > 0 && substr(host, dot) == substr(name, 1); +}; + +/** ACME certificates on the router and the names each covers. */ +export function acme_certs() { + let out = []; + for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) { + let m = match(f, /^(.+)\.fullchain\.crt$/); + if (!m) + continue; + let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`; + if (file_exists(k)) + push(out, { cert: c, key: k, names: cert_names(c) }); + } + return out; +}; + +/** The ACME certificate that covers host (exact name or a wildcard), if any. */ +export function acme_cert_for(host) { + for (let a in acme_certs()) + for (let n in a.names) + if (name_covers(n, host)) + return a; + return null; +}; + +/** Certificate the portal should use: configured, ACME for the host, or self-signed. */ +export function portal_cert(s) { + if (s.portal_cert && s.portal_key && file_exists(s.portal_cert) && file_exists(s.portal_key)) + return { cert: s.portal_cert, key: s.portal_key, self_signed: false }; + if (s.portal_host) { + for (let base in [ `/etc/ssl/acme/${s.portal_host}`, `/etc/acme/${s.portal_host}_ecc/${s.portal_host}` ]) { + let c = `${base}.fullchain.crt`, k = `${base}.key`; + if (file_exists(c) && file_exists(k)) + return { cert: c, key: k, self_signed: false }; + } + // An ACME certificate issued for several names, the portal's among them. + let a = acme_cert_for(s.portal_host); + if (a) + return { cert: a.cert, key: a.key, self_signed: false }; + } + let c = `${DATA_DIR}/portal.crt`, k = `${DATA_DIR}/portal.key`; + if (!file_exists(c) || !file_exists(k)) { + ensure_dir(DATA_DIR, 0o700); + let cn = s.portal_host || 'dawnline'; + sh(`openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 -subj ${q('/CN=' + cn)} -keyout ${k} -out ${c}`); + system(`chmod 600 ${k}`); + } + return { cert: c, key: k, self_signed: true }; +}; + +/* + * Addresses the portal could use in links, found on the router: names in ACME + * certificates, server endpoints, DDNS names, the current one, and the WAN IP. + * Each says where it points and whether a certificate covers it. + */ +export function portal_candidates(m) { + let wan = lookup.router_wan(m); + let names = []; + let add = (h) => { + if (h && valid_host(h) && ip2int(h) == null && substr(h, 0, 2) != '*.' && index(names, h) < 0) + push(names, h); + }; + let certs = acme_certs(); + for (let a in certs) + for (let n in a.names) + add(n); + for (let id, srv in m.servers) + add(srv.endpoint); + let dc = cursor(); + if (dc.load('ddns')) + dc.foreach('ddns', 'service', (sv) => { + if (sv.enabled != '0') { + add(sv.lookup_host); + add(sv.domain); + } + }); + for (let h in core.portal_hosts(m)) + add(h); + let found = lookup.resolve_all(names); + let covered = (h) => length(filter(certs, (a) => length(filter(a.names, (n) => name_covers(n, h))) > 0)) > 0; + let out = []; + for (let h in names) { + let ips = found[h] ?? []; + push(out, { host: h, kind: 'name', ips, here: wan != null && index(ips, wan) >= 0, + cloudflare: length(filter(ips, (x) => cloudflare_ip(x))) > 0, cert: covered(h) }); + } + if (wan) + push(out, { host: wan, kind: 'ip', ips: [ wan ], here: true, cloudflare: false, cert: false }); + for (let ph in core.portal_hosts(m)) + if (ip2int(ph) != null && ph != wan) + push(out, { host: ph, kind: 'ip', ips: [ ph ], here: false, cloudflare: false, cert: false }); + // Best first: here with a certificate, then here, then the rest. + let score = (c) => (c.here ? 4 : 0) + (c.cert ? 2 : 0) + (c.kind == 'name' ? 1 : 0) - (c.cloudflare ? 8 : 0); + return sort(out, (a, b) => score(b) - score(a)); +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/resolver.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/resolver.uc new file mode 100644 index 0000000..efa416c --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/resolver.uc @@ -0,0 +1,99 @@ +// Dawnline — the plain resolver for people with Home-only access: real +// addresses from the WAN's DNS, home names from the LAN DNS. Their internet +// does not use the tunnel, so fake-IP answers would break it. dawnline.loop +// says where it runs (inside the netns while it exists, otherwise on the +// tunnel interfaces); procd runs dnsmasq through /usr/libexec/dawnline/resolver. + +import { readfile, writefile, stat } from 'fs'; +import { cursor } from 'uci'; +import { ensure_dir, iface_status, uniq } from 'dawnline.util'; +import * as net from 'dawnline.net'; +import * as core from 'dawnline.core'; + +/** Port on the tunnel addresses while it runs on the router itself. */ +export const PORT = 5354; +export const CONF = '/var/etc/dawnline-dns.conf'; +const RESOLV = '/var/etc/dawnline-dns.resolv'; +const PID = '/var/run/dawnline-dns.pid'; +const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ]; + +function wan_dns() { + let out = []; + let snap = net.snapshot(); + let wan = snap.devices[snap.wan]?.logical; + for (let name in uniq([ wan, 'wan', 'wan6' ])) { + if (!name) + continue; + for (let a in iface_status(name)?.['dns-server'] ?? []) + if (match(a, /^[0-9.]+$/)) + push(out, a); + } + return length(out) ? uniq(out) : FALLBACK_DNS; +} + +/** Local domain of the LAN DNS (dnsmasq `domain`, else the Dawnline hostname domain). */ +function lan_domain(m) { + let c = cursor(); + c.load('dhcp'); + let d = null; + c.foreach('dhcp', 'dnsmasq', (s) => { d ??= s.domain; }); + return uniq(filter([ d, m.settings.domain ], (x) => x)); +} + +/** True when the resolver process is alive. */ +export function running() { + let pid = trim(readfile(PID) ?? ''); + return match(pid, /^[0-9]+$/) != null && stat(`/proc/${pid}`) != null; +}; + +/** + * Write the config for `target` (dawnline.loop resolver_target) with home + * names from `lan` (the LAN's DNS); returns true when it changed (the running + * instance is then restarted by procd's respawn after a kill). The first line + * tells /usr/libexec/dawnline/resolver where to run it. + */ +export function sync(m, target, lan) { + ensure_dir('/var/etc'); + let ifs = []; + for (let id, s in m.servers) + for (let t in core.tunnels(s)) + push(ifs, t.ifname); + let lines = [ + `# mode=${target.mode}`, + '# Generated by Dawnline: plain DNS for Home-only tunnel clients.', + `port=${target.port}`, + 'no-hosts', + 'bogus-priv', + 'cache-size=1000', + `pid-file=${PID}`, + 'user=dnsmasq', + 'group=dnsmasq', + ]; + if (target.mode == 'ns') { + push(lines, `listen-address=${target.address}`, 'bind-interfaces', 'no-resolv'); + // Upstream from the transit address: forwarded through the router to the WAN. + for (let a in wan_dns()) + push(lines, `server=${a}@${target.address}`); + } + else { + // No tunnel yet: loopback only (without any interface= line dnsmasq would answer everywhere). + push(lines, 'bind-dynamic', ...(length(ifs) ? map(ifs, (i) => `interface=${i}`) : [ 'listen-address=127.0.0.1' ]), `resolv-file=${RESOLV}`); + let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`)); + if ((readfile(RESOLV) ?? '') != resolv) { + writefile(RESOLV, resolv); + system(`chmod 644 ${RESOLV}`); + } + } + if (lan) + for (let d in lan_domain(m)) + push(lines, `server=/${d}/${lan}`); + let conf = join('\n', lines) + '\n'; + if ((readfile(CONF) ?? '') == conf) + return false; + writefile(CONF, conf); + system(`chmod 644 ${CONF}`); + let pid = trim(readfile(PID) ?? ''); + if (match(pid, /^[0-9]+$/)) + system(`kill ${pid} 2>/dev/null`); + return true; +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/common.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/common.uc new file mode 100644 index 0000000..453fda9 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/common.uc @@ -0,0 +1,83 @@ +// Dawnline — what the rpcd method modules (dawnline.rpc.*) share: the call +// wrapper, argument helpers, the disguise check and the portal port check. + +import * as core from 'dawnline.core'; +import * as awg from 'dawnline.awg'; +import * as health from 'dawnline.health'; +import * as schema from 'dawnline.schema'; + +/** + * An rpcd handler from fn(args): an object result is passed on, anything else + * is wrapped as { result }, and a failure becomes { error } (the UI shows it). + */ +export function wrap(fn) { + return function(req) { + try { + let r = fn(req.args ?? {}); + return type(r) == 'object' ? r : { result: r }; + } + catch (e) { + return { error: e.message ?? `${e}` }; + } + }; +}; + +/** An argument as a trimmed string ('' for null). */ +export function str(v) { + return v == null ? '' : trim(`${v}`); +}; + +/** Days of history a caller may ask for: 1–400, default 30. */ +export function clamp_days(v) { + let n = +(v ?? 30); + return n >= 1 ? (n > 400 ? 400 : int(n)) : 30; +}; + +export const METHODS = [ 'off', 'standard', 'strong', 'max' ]; + +/** A disguise method the installed AmneziaWG can run. */ +export function check_method(name) { + if (index(METHODS, name) < 0) + die('Unknown disguise method.'); + if (name == 'max' && !awg.caps().v3) + die(awg.installed() + ? 'Maximum needs AmneziaWG 3.1 on the router (kmod-amneziawg, amneziawg-tools 3.1): install a 3.1 build in Dawnline → Components.' + : 'AmneziaWG is not installed: install it in Dawnline → Components, then choose Maximum.'); + return name; +}; + +/** + * The portal's ports in the final configuration `m` (compared with `was`, + * before the change) are acceptable: its HTTPS port and, when links on IP + * addresses use plain HTTP, the next port too — both get a WAN ACCEPT rule. + * Neither may be 22, 53, 80 or 443, beyond 65535, or taken by another program. + */ +export function check_portal(m, was) { + let s = m.settings; + if (!s.portal_enabled) + return; + let port = s.portal_port; + if (!schema.valid_port(port) || index(schema.RESERVED_PORTS, port) >= 0) + die('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).'); + let ports = [ port ]; + if (core.portal_http(m)) { + let hp = core.portal_http_port(m); + if (!schema.valid_port(hp) || index(schema.RESERVED_PORTS, hp) >= 0) + die(`Links on IP addresses use plain HTTP on the next port (${hp}), which the portal cannot take. Choose another portal port.`); + push(ports, hp); + } + // Only ports the portal does not hold already: our own uhttpd is not an owner anyway. + let held = []; + if (was?.settings?.portal_enabled) { + push(held, was.settings.portal_port); + if (core.portal_http(was)) + push(held, core.portal_http_port(was)); + } + for (let p in ports) { + if (index(held, p) >= 0) + continue; + let owners = health.tcp_port_owners(p); + if (length(owners)) + die(`TCP ${p} is already used by ${join(', ', owners)}.${p != port ? ' Links on IP addresses use plain HTTP on the port after the portal\'s.' : ''} Choose another portal port.`); + } +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/home.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/home.uc new file mode 100644 index 0000000..87c2f93 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/home.uc @@ -0,0 +1,214 @@ +// Dawnline rpcd methods: what people reach at home — services (home +// devices and ports), circles (who reaches whom), the devices found at home, +// and "Check access". + +import { readfile } from 'fs'; +import { cursor } from 'uci'; +import { sh_out, ip2int, rand_int, rand_hex, admin_log } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as apply from 'dawnline.apply'; +import * as net from 'dawnline.net'; +import * as access from 'dawnline.access'; +import * as store from 'dawnline.store'; +import * as schema from 'dawnline.schema'; +import { wrap, str } from 'dawnline.rpc.common'; + +/* ---------- services ---------- */ + +/** A new id from make() that no section has yet. */ +function new_id(m, make) { + for (let i = 0; i < 20; i++) { + let id = make(); + if (!store.id_taken(m, id)) + return id; + } + die('Could not find a free id, try again.'); +} + +function service_set(a) { + let name = str(a.name); + if (name == '' || length(name) > 48) + die('Enter a service name.'); + let address = str(a.address); + if (!schema.ipv4(address)) + die('Address must be an IPv4 address.'); + let ports = filter(map(type(a.ports) == 'array' ? a.ports : split(str(a.ports), /[ ,]+/), str), (x) => x != ''); + for (let pt in ports) + if (!schema.valid_port(pt)) + die(`Invalid port ${pt}.`); + let id = store.transact((c, m) => { + let id = str(a.id); + if (id == '') + id = new_id(m, () => `svc_${rand_int(100000, 999999)}`); + else if (!match(id, /^[A-Za-z0-9_]{1,32}$/)) + die('Invalid service id.'); + // Never turn a person, device, server, circle or the settings into a service. + else if (!m.services[id] && store.id_taken(m, id)) + die('That id is taken.'); + c.set(core.CONFIG, id, 'service'); + c.set(core.CONFIG, id, 'name', name); + c.set(core.CONFIG, id, 'address', address); + if (length(ports)) + c.set(core.CONFIG, id, 'port', ports); + else + c.delete(core.CONFIG, id, 'port'); + return id; + }); + apply.sync(); + return { id }; +} + +function service_delete(a) { + store.transact((c, m) => { + if (!m.services[a.id]) + die('Unknown service.'); + c.delete(core.CONFIG, a.id); + for (let pid, p in m.people) + if (index(p.services, a.id) >= 0) { + let rest = filter(p.services, (x) => x != a.id); + if (length(rest)) + c.set(core.CONFIG, pid, 'service', rest); + else + c.delete(core.CONFIG, pid, 'service'); + } + }); + apply.sync(); + return { ok: true }; +} + +/* ---------- circles ---------- */ + +/** Create or edit a circle; `members` (person ids) replaces who is in it. */ +function circle_set(a) { + let name = str(a.name); + if (name == '' || length(name) > 32) + die('Enter a circle name (up to 32 characters).'); + let res = store.transact((c, m) => { + let ci = a.id ? m.circles[a.id] : null; + if (a.id && !ci) + die('Unknown circle.'); + let server = ci?.server ?? a.server; + if (!m.servers[server]) + die('Unknown server.'); + for (let id, o in m.circles) + if (id != a.id && o.server == server && lc(o.name) == lc(name)) + die(`${name} already exists.`); + let id = ci?.id ?? new_id(m, () => `c_${rand_hex(4)}`); + let n = core.CIRCLE_COLORS; + c.set(core.CONFIG, id, 'circle'); + c.set(core.CONFIG, id, 'server', server); + c.set(core.CONFIG, id, 'name', name); + c.set(core.CONFIG, id, 'color', `${((int(a.color) || 0) % n + n) % n}`); + if (type(a.members) == 'array') { + let want = {}; + for (let pid in a.members) + if (m.people[pid]?.server == server) + want[pid] = true; + for (let pid, p in m.people) + if (want[pid]) + c.set(core.CONFIG, pid, 'circle', id); + else if (p.circle == id) + c.delete(core.CONFIG, pid, 'circle'); + } + return { id, edit: !!ci, server: m.servers[server].name }; + }); + apply.sync(); + admin_log('awg', res.edit ? 'changed' : 'added', 'circle', name, res.server); + return { id: res.id, circles: values(core.load().circles) }; +} + +function circle_delete(a) { + let res = store.transact((c, m) => { + let ci = m.circles[a.id]; + if (!ci) + die('Unknown circle.'); + c.delete(core.CONFIG, a.id); + for (let pid, p in m.people) + if (p.circle == a.id) + c.delete(core.CONFIG, pid, 'circle'); + return { name: ci.name, server: m.servers[ci.server]?.name }; + }); + apply.sync(); + admin_log('awg', 'removed', 'circle', res.name, res.server); + return { circles: values(core.load().circles) }; +} + +/* ---------- devices at home ---------- */ + +/** True while OpenWrt's mDNS daemon answers on ubus. */ +function mdns_running() { + return index(split(sh_out('ubus list umdns 2>/dev/null') ?? '', '\n'), 'umdns') >= 0; +} + +/** + * Services announced on the home networks (Bonjour), from umdns: + * [{ type: '_airplay._tcp', name, host, address, port, txt }]. + */ +function mdns_services() { + if (!mdns_running()) + return []; + let r = {}; + try { + r = json(sh_out(`ubus call umdns browse '{"address":true,"array":true}' 2>/dev/null`) || '{}') ?? {}; + } + catch (e) { + r = {}; + } + let out = []; + for (let t, insts in r) + for (let name, i in insts) { + let addr = type(i.ipv4) == 'array' ? i.ipv4[0] : i.ipv4; + if (addr) + push(out, { type: t, name, host: replace(i.host ?? '', /\.local\.?$/, ''), address: addr, port: i.port ?? 0, txt: i.txt ?? [] }); + } + return out; +} + +/** + * Devices at home for the Home services picker: DHCP leases and static hosts + * in the server's home networks, with the services they announce (Bonjour, + * when umdns runs). + */ +function home_hosts(a) { + let m = core.load(); + let srv = m.servers[a.id] ?? values(m.servers)[0]; + if (!srv) + die('No server yet.'); + let nets = []; + for (let cidr in net.server_net(srv).nets) { + let x = match(cidr, /^([0-9.]+)\/([0-9]+)$/); + if (x && ip2int(x[1]) != null) + push(nets, [ ip2int(x[1]), 1 << (32 - +x[2]) ]); + } + let inside = (ip) => { + let n = ip2int(ip); + return n != null && length(filter(nets, (r) => n >= r[0] && n < r[0] + r[1])) > 0; + }; + let hosts = {}; + for (let line in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) { + let f = split(line, ' '); + if (length(f) >= 4 && inside(f[2])) + hosts[f[2]] = { address: f[2], name: f[3] == '*' ? '' : f[3], mac: f[1], services: [] }; + } + let c = cursor(); + if (c.load('dhcp')) + c.foreach('dhcp', 'host', (h) => { + if (h.ip && inside(h.ip)) + hosts[h.ip] ??= { address: h.ip, name: h.name ?? '', mac: type(h.mac) == 'array' ? h.mac[0] : h.mac ?? '', services: [] }; + }); + for (let s in mdns_services()) + if (hosts[s.address]) + push(hosts[s.address].services, { type: s.type, name: s.name, port: s.port }); + else if (inside(s.address)) + hosts[s.address] = { address: s.address, name: s.host ?? '', mac: '', services: [ { type: s.type, name: s.name, port: s.port } ] }; + return { hosts: sort(values(hosts), (x, y) => ip2int(x.address) - ip2int(y.address)), mdns: mdns_running() }; +} + +export const methods = { + service_set: { args: { id: '', name: '', address: '', ports: [] }, call: wrap(service_set) }, + service_delete: { args: { id: '' }, call: wrap(service_delete) }, + circle_set: { args: { id: '', server: '', name: '', color: 0, members: [] }, call: wrap(circle_set) }, + circle_delete: { args: { id: '' }, call: wrap(circle_delete) }, + home_hosts: { args: { id: '' }, call: wrap(home_hosts) }, + access_check: { args: { from: '', to: '' }, call: wrap((a) => access.check(core.load(), a.from, a.to)) }, +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/maint.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/maint.uc new file mode 100644 index 0000000..e340821 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/maint.uc @@ -0,0 +1,89 @@ +// Dawnline rpcd methods: Diagnostics (Health, the service log), backups, +// export / import, and removing Dawnline. + +import { slog_clear, admin_log } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as apply from 'dawnline.apply'; +import * as watchdog from 'dawnline.watchdog'; +import * as upd from 'dawnline.updates'; +import * as store from 'dawnline.store'; +import * as health from 'dawnline.health'; +import * as backup from 'dawnline.backup'; +import { wrap } from 'dawnline.rpc.common'; + +function health_view(extra) { + return { ...(extra ?? {}), checks: health.health(), ...watchdog.view(core.load()) }; +} + +function service_log_clear(a) { + let removed = slog_clear(+a.older_days || 0); + if (removed) + admin_log('dawnline', 'cleared', null, 'the service log', `${removed} entr${removed == 1 ? 'y' : 'ies'}${+a.older_days ? ` older than ${a.older_days} days` : ''}`); + return { removed }; +} + +function backup_restore(a) { + let r = backup.backup_restore(a.name); + admin_log('dawnline', 'restored', 'backup', a.name); + return r; +} + +function backup_upload(a) { + let r = backup.backup_upload(a.data); + admin_log('dawnline', 'restored', 'backup', 'from a file'); + return r; +} + +function export_all(a) { + let r = backup.export_json(); + admin_log('dawnline', 'exported', null, 'all settings', 'the file holds private keys'); + return r; +} + +function import_all(a) { + let r = backup.import_json(a.data); + admin_log('dawnline', 'imported', null, 'settings from a file'); + return r; +} + +/** Remove Dawnline's state from the router (the package is removed by the UI afterwards). */ +function uninstall(a) { + if (a.confirm != 'remove') + die('Type "remove" to confirm.'); + // Not in the middle of an update (opkg/apk may be installing Dawnline itself). + if (upd.busy()) + die('An update is running: wait for it to finish, then remove Dawnline.'); + backup.backup_create('pre-remove'); + // Stop first: the agent would put back what teardown removes, and could start an automatic update. + system('/etc/init.d/dawnline stop >/dev/null 2>&1; /etc/init.d/dawnline disable >/dev/null 2>&1'); + apply.teardown(); + store.transact((c, m) => { + let rm = []; + c.foreach(core.CONFIG, null, (s) => { + if (s['.type'] != 'settings') + push(rm, s['.name']); + }); + for (let n in rm) + c.delete(core.CONFIG, n); + c.set(core.CONFIG, 'settings', 'settings'); + c.set(core.CONFIG, 'settings', 'portal_enabled', '0'); + }); + return { ok: true }; +} + +export const methods = { + apply: { call: wrap((a) => apply.apply()) }, + health: { call: wrap((a) => health_view()) }, + health_fix: { args: { id: '' }, call: wrap((a) => health_view({ result: health.fix(a.id) })) }, + service_log: { call: wrap((a) => watchdog.view(core.load())) }, + service_log_clear: { args: { older_days: '' }, call: wrap(service_log_clear) }, + backup_list: { call: wrap((a) => ({ backups: backup.backup_list() })) }, + backup_create: { call: wrap((a) => ({ name: backup.backup_create(null) })) }, + backup_restore: { args: { name: '' }, call: wrap(backup_restore) }, + backup_delete: { args: { name: '' }, call: wrap((a) => ({ ok: backup.backup_delete(a.name) })) }, + backup_read: { args: { name: '' }, call: wrap((a) => ({ data: backup.backup_read(a.name) })) }, + backup_upload: { args: { data: '' }, call: wrap(backup_upload) }, + 'export': { call: wrap(export_all) }, + 'import': { args: { data: {} }, call: wrap(import_all) }, + uninstall: { args: { confirm: '' }, call: wrap(uninstall) }, +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc new file mode 100644 index 0000000..450b39e --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc @@ -0,0 +1,164 @@ +// Dawnline rpcd methods: people (adding, editing, pausing, their personal +// links and traffic) and their devices. + +import * as core from 'dawnline.core'; +import * as live from 'dawnline.live'; +import * as apply from 'dawnline.apply'; +import * as view from 'dawnline.view'; +import * as awg from 'dawnline.awg'; +import * as store from 'dawnline.store'; +import * as devices from 'dawnline.devices'; +import { wrap, str, clamp_days } from 'dawnline.rpc.common'; + +const PERSON_FIELDS = [ 'name', 'access', 'device_limit', 'expires', 'expire_action', 'expire_warn', 'quota_gb', 'quota_period', + 'bonus_gb', 'hours', 'note', 'dns_mode' ]; + +/* ---------- people ---------- */ + +function person_create(a) { + let id = store.transact((c, m) => core.create_person(c, m, { + name: str(a.name), slug: str(a.slug) || null, server: str(a.server) || null, access: a.access, + device_limit: str(a.device_limit), expires: str(a.expires), quota_gb: str(a.quota_gb), quota_period: a.quota_period, + })); + let m = core.load(); + live.add_event({ type: 'person_added', person: id, detail: m.people[id].name, by: 'admin' }); + return { id, link: core.portal_url(m, m.people[id]) }; +} + +/** Immediate edits from the person's page; returns the person as the page shows them. */ +function person_update(a) { + let fields = {}; + for (let k in PERSON_FIELDS) + if (a[k] != null) + fields[k] = a[k]; + if (a.paused != null) + fields.paused = a.paused; + if (type(a.services) == 'array') + fields.services = a.services; + if (a.circle != null) + fields.circle = a.circle; + if (type(a.home_nets) == 'array') + fields.home_nets = a.home_nets; + let before = store.transact((c, m) => { + let p = m.people[a.id]; + core.update_person(c, m, a.id, fields); + return p; + }); + let changes = join(', ', filter(keys(fields), (k) => k != 'note')); + if (changes) + live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120); + // Access changes affect the nft sets and client AllowedIPs. + apply.sync(); + let m = core.load(); + let u = core.load_usage(); + return { person: view.person_view(m, m.people[a.id], u, live.dump(m), view.states(m, u), { admin: true }), was: before?.access }; +} + +function person_pause(a) { + store.transact((c, m) => { + if (!m.people[a.id]) + die('Unknown person.'); + if (a.paused) + c.set(core.CONFIG, a.id, 'paused', '1'); + else + c.delete(core.CONFIG, a.id, 'paused'); + }); + live.add_event({ type: a.paused ? 'paused' : 'resumed', person: a.id, by: 'admin' }); + return apply.sync(); +} + +/** A new personal link: the old one stops working at once (every portal request carries the code). */ +function person_regen(a) { + store.transact((c, m) => { + if (!m.people[a.id]) + die('Unknown person.'); + c.set(core.CONFIG, a.id, 'code', core.new_code()); + }); + live.add_event({ type: 'link_changed', person: a.id, by: 'admin' }); + let m = core.load(); + return { link: core.portal_url(m, m.people[a.id]) }; +} + +/** The personal code and links (Copy link, QR, invite): admins only, unlike status. */ +function person_links(a) { + let m = core.load(); + let p = m.people[a.id]; + if (!p) + die('Unknown person.'); + return { code: p.code, link: core.portal_url(m, p), links: core.portal_urls(m, p) }; +} + +function person_delete(a) { + let name = store.transact((c, m) => { + let name = m.people[a.id]?.name; + core.delete_person(c, m, a.id); + return name; + }); + live.add_event({ type: 'person_removed', person: a.id, detail: name, pname: name, by: 'admin' }); + return apply.sync(); +} + +function person_usage(a) { + let usage = core.load_usage(); + let m = core.load(); + let p = m.people[a.id]; + if (!p) + die('Unknown person.'); + let days = clamp_days(a.days); + let devs = {}; + for (let d in p.devices) + devs[d] = live.series([ usage.devices?.[d] ], days); + return { person: live.series([ usage.people?.[a.id] ], days), devices: devs }; +} + +function pause_all(a) { + store.transact((c, m) => { + c.set(core.CONFIG, 'settings', 'settings'); + c.set(core.CONFIG, 'settings', 'paused_all', a.paused ? '1' : '0'); + }); + live.add_event({ type: a.paused ? 'paused_all' : 'resumed_all', by: 'admin' }); + return apply.sync(); +} + +/* ---------- devices ---------- */ + +function device_create(a) { + devices.need_awg(); + return devices.add(a.person, a.name, a.kind, { by: 'admin' }); +} + +function device_config(a) { + let m = core.load(); + let d = m.devices[a.id]; + if (!d) + die('Unknown device.'); + awg.mark_issued(m, d.id); + return awg.client_config(m, d); +} + +function device_update(a) { + return devices.update(a.id, { name: a.name, disabled: a.disabled }, { by: 'admin' }); +} + +export const methods = { + person_create: { + args: { name: '', slug: '', server: '', access: '', device_limit: '', expires: '', quota_gb: '', quota_period: '' }, + call: wrap(person_create), + }, + person_update: { + args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '', + quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [] }, + call: wrap(person_update), + }, + person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) }, + person_regen: { args: { id: '' }, call: wrap(person_regen) }, + person_links: { args: { id: '' }, call: wrap(person_links) }, + person_delete: { args: { id: '' }, call: wrap(person_delete) }, + person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) }, + pause_all: { args: { paused: false }, call: wrap(pause_all) }, + device_create: { args: { person: '', name: '', kind: '' }, call: wrap(device_create) }, + device_config: { args: { id: '' }, call: wrap(device_config) }, + device_update: { args: { id: '', name: '', disabled: false }, call: wrap(device_update) }, + device_delete: { args: { id: '' }, call: wrap((a) => devices.remove(a.id, { by: 'admin' })) }, + device_rotate: { args: { id: '' }, call: wrap((a) => devices.rotate(a.id, { by: 'admin' })) }, +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc new file mode 100644 index 0000000..e4c46d6 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc @@ -0,0 +1,531 @@ +// Dawnline rpcd methods: setting up a server, its General / Network / +// Interfaces settings, its disguise, and removing it. + +import { cursor } from 'uci'; +import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, rand_int, uniq, admin_log } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as live from 'dawnline.live'; +import * as apply from 'dawnline.apply'; +import * as net from 'dawnline.net'; +import * as loop from 'dawnline.loop'; +import * as awg from 'dawnline.awg'; +import * as store from 'dawnline.store'; +import * as schema from 'dawnline.schema'; +import * as health from 'dawnline.health'; +import * as backup from 'dawnline.backup'; +import * as devices from 'dawnline.devices'; +import { wrap, str, check_method, check_portal } from 'dawnline.rpc.common'; + +/** Server ids that would shadow a portal path. */ +const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ]; + +const MESH_WORDS = { off: 'devices kept apart', all: 'devices reach each other', circles: 'devices reach each other in circles' }; + +/* ---------- free names, ports and subnets ---------- */ + +function free_port(m) { + let used = {}; + let nc = cursor(); + nc.load('network'); + nc.foreach('network', 'interface', (s) => { + if (s.listen_port) + used[+s.listen_port] = true; + }); + for (let id, srv in m.servers) + used[srv.port] = true; + for (let i = 0; i < 50; i++) { + let p = rand_int(40000, 60000); + if (!used[p]) + return p; + } + return 51830; +} + +function free_subnet(taken) { + for (let i = 0; i < 200; i++) { + let cand = parse_cidr(sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250))); + let bad = false; + for (let t in taken) { + let tc = parse_cidr(t); + if (tc && cidr_overlaps(cand, tc)) { + bad = true; + break; + } + } + if (!bad) + return cidr_str(cand); + } + return '10.77.0.0/24'; +} + +function free_portal_port(cur) { + for (let p in uniq([ cur || 8443, 8443, 9443, 10443, 7443, 4443 ])) + if (!length(health.tcp_port_owners(p)) && !length(health.tcp_port_owners(p + 1))) + return p; + return 9443; +} + +/** A network section name nothing uses: not the router's, not Dawnline's own links, not another server's. */ +function ifname_free(m, nc, n) { + if (nc.get('network', n) != null || index(values(net.INTERNAL), n) >= 0) + return false; + for (let id, s in m.servers) + if (s.ifname == n) + return false; + return true; +} + +function free_ifname(m) { + let nc = cursor(); + nc.load('network'); + for (let i = 0; i < 10; i++) + if (ifname_free(m, nc, `dawn${i}`)) + return `dawn${i}`; + return 'dawnx'; +} + +function id_free(m, id) { + return !store.id_taken(m, id) && index(PORTAL_PATHS, id) < 0; +} + +/** A free server id: home, then server2, server3, … (never an id anything else has). */ +function free_server_id(m) { + if (id_free(m, 'home')) + return 'home'; + for (let n = 2; ; n++) + if (id_free(m, `server${n}`)) + return `server${n}`; +} + +/** Subnets a new server must not overlap: the router's networks and the other servers. */ +function taken_subnets(m) { + let taken = health.used_subnets(null); + for (let id, s in m.servers) + push(taken, s.subnet); + return taken; +} + +/* ---------- setup ---------- */ + +function setup_defaults(a) { + let m = core.load(); + let taken = taken_subnets(m); + let zones = []; + let fc = cursor(); + fc.load('firewall'); + fc.foreach('firewall', 'zone', (z) => push(zones, z.name)); + let host = m.settings.portal_host; + if (!host) { + // Prefer a DDNS name, then an ACME certificate's, then the WAN address. + let dc = cursor(); + if (dc.load('ddns')) + dc.foreach('ddns', 'service', (s) => { + if (!host && s.lookup_host && s.enabled == '1') + host = s.lookup_host; + }); + if (!host) + host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || ''; + if (!host) + host = live.iface_status('wan')?.['ipv4-address']?.[0]?.address ?? ''; + } + return { + id: free_server_id(m), + name: length(m.servers) ? `Server ${length(m.servers) + 1}` : 'Home', + ifname: free_ifname(m), + port: free_port(m), + subnet: free_subnet(taken), + endpoint: host, + mtu: 1380, + zones, + lan_zone: index(zones, 'lan') >= 0 ? 'lan' : zones[0], + wan_zone: index(zones, 'wan') >= 0 ? 'wan' : zones[1], + portal_port: free_portal_port(m.settings.portal_port), + awg: awg.caps(), + awg_state: awg.state(), + taken, + }; +} + +/** AmneziaWG can run a server: installed, and its kernel module loads. */ +function need_awg_loaded() { + devices.need_awg(); + if (awg.state().loaded) + return; + system('modprobe amneziawg >/dev/null 2>&1'); + if (!awg.state().loaded) + die("AmneziaWG's kernel module doesn't load on this firmware: reinstall a build for this kernel in Components."); +} + +/** An MTU as typed: '' (the default) or 1280-1500. */ +function check_mtu(v) { + let s = str(v); + if (s != '' && (!match(s, /^[0-9]{1,4}$/) || +s < 1280 || +s > 1500)) + die('MTU must be 1280-1500.'); + return s; +} + +function server_create(a) { + need_awg_loaded(); + let snap = net.snapshot(true); + let router_subnets = health.used_subnets(null); + let id = store.transact((c, m) => { + let id = str(a.id) || 'home'; + // A UCI section name: a dash would make uci drop it silently. + if (!match(id, /^[a-z][a-z0-9_]{0,23}$/)) + die('Server ID may use lowercase letters, digits and underscores.'); + if (!id_free(m, id)) + die(`"${id}" is already taken.`); + let nc = cursor(); + nc.load('network'); + let ifname = str(a.ifname) || free_ifname(m); + if (!ifname_free(m, nc, ifname)) + die(`Network interface ${ifname} already exists.`); + let port = free_port(m); + if (a.port != null && str(a.port) != '' && str(a.port) != '0') { + if (!schema.valid_port(a.port)) + die('UDP port must be 1-65535.'); + port = +str(a.port); + } + for (let sid, o in m.servers) + if (o.port == port) + die(`UDP ${port} is used by ${o.name}.`); + let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu) || '1380'; + let preset = str(a.preset) || 'standard'; + let srv = { id, ifname, port, subnet: str(a.subnet), endpoint: str(a.endpoint), obf: awg.obf_preset(check_method(preset)) }; + let pc = parse_cidr(srv.subnet); + if (pc) + srv.subnet = cidr_str(pc); + let taken = [ ...router_subnets ]; + for (let sid, o in m.servers) + push(taken, o.subnet); + let errs = core.server_errors(m, srv, taken); + push(errs, ...awg.obf_errors(srv.obf)); + if (length(errs)) + die(join(' ', errs)); + + let set = (k, v) => c.set(core.CONFIG, id, k, v); + c.set(core.CONFIG, 'settings', 'settings'); + c.set(core.CONFIG, id, 'server'); + set('name', str(a.name) || 'Home'); + set('ifname', ifname); + set('port', `${port}`); + set('subnet', srv.subnet); + if (srv.endpoint) + set('endpoint', srv.endpoint); + set('mtu', mtu); + set('keepalive', '25'); + let kp = awg.server_keys(); + set('private_key', kp.private_key); + set('public_key', kp.public_key); + set('preset', preset); + for (let ok, ov in srv.obf) + set(ok, ov); + set('lan_zone', str(a.lan_zone) || 'lan'); + set('wan_zone', str(a.wan_zone) || 'wan'); + set('auto_wan', '1'); + set('auto_lan', '1'); + if (snap.wan) + set('detected_wan', snap.wan); + if (snap.lan) + set('detected_lan', snap.lan); + set('lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1'); + set('enabled', '1'); + if (a.portal_enabled != null) { + let on = a.portal_enabled === true || a.portal_enabled === 1 || a.portal_enabled === '1'; + c.set(core.CONFIG, 'settings', 'portal_enabled', on ? '1' : '0'); + if (a.portal_port != null && str(a.portal_port) != '' && str(a.portal_port) != '0') { + if (!schema.valid_port(a.portal_port)) + die('Portal port must be 1-65535.'); + c.set(core.CONFIG, 'settings', 'portal_port', `${+str(a.portal_port)}`); + } + } + if (srv.endpoint && !c.get(core.CONFIG, 'settings', 'portal_host') && valid_host(srv.endpoint)) + c.set(core.CONFIG, 'settings', 'portal_host', srv.endpoint); + // The portal as it will be, whatever this call changed. + check_portal(core.load(c), m); + return id; + }); + let r = apply.apply(); + system('/etc/init.d/dawnline enabled || /etc/init.d/dawnline enable'); + let made = core.load().servers[id]; + admin_log('dawnline', 'created', 'server', made?.name ?? id, made ? `UDP ${made.port}` : null); + sh_bg('/etc/init.d/dawnline restart'); + return { id, applied: r }; +} + +/* ---------- interfaces ---------- */ + +/** Interfaces card on the Server page: what exists, what is detected, what the server uses. */ +function interfaces_view(m, srv, snap) { + let sn = net.server_net(srv, snap); + let home = {}; + for (let h in sn.home) + home[h.dev] = h; + let devs = []; + for (let dev, d in snap.devices) + push(devs, { + ...d, + own: dev == srv.ifname, + home: !!home[dev], + auto: !!home[dev]?.auto, + }); + // Saved names that no longer exist still show, so they can be removed. + for (let h in sn.home) + if (h.missing) + push(devs, { name: h.dev, category: 'other', kind: 'other', missing: true, nets: [], addrs: [], members: [], home: true, auto: h.auto }); + let lan_only = 0; + for (let id, p in m.people) + if (p.server == srv.id && p.access == 'lan') + lan_only++; + return { + server: srv.id, + ifname: srv.ifname, + detected: { wan: snap.wan, lan: snap.lan }, + saved: { wan: srv.detected_wan, lan: srv.detected_lan }, + config: { auto_wan: srv.auto_wan, wan_device: srv.wan_device, auto_lan: srv.auto_lan, lan_devices: srv.lan_devices, lan_like: srv.lan_like, + device_mesh: srv.device_mesh, mesh: srv.mesh }, + like_home: loop.status(), + needs: health.needs().home, + effective: sn, + zones: snap.zones, + devices: devs, + lan_only, + }; +} + +function interfaces_get(a) { + let m = core.load(); + let srv = m.servers[a.id] ?? values(m.servers)[0]; + if (!srv) + die('No server yet.'); + return interfaces_view(m, srv, net.snapshot(true)); +} + +function server_interfaces(a) { + let snap = net.snapshot(true); + let auto_wan = a.auto_wan != false && a.auto_wan != '0'; + let auto_lan = a.auto_lan != false && a.auto_lan != '0'; + let wan_dev = str(a.wan_device); + let res = store.transact((c, m) => { + let srv = m.servers[a.id]; + if (!srv) + die('Unknown server.'); + if (!auto_wan) { + if (!snap.devices[wan_dev]) + die('Choose the interface that leads to the internet.'); + if (!snap.devices[wan_dev].zone) + die(`${wan_dev} is not in a firewall zone, so the server port cannot be opened on it.`); + } + let lans = []; + for (let d in (type(a.lan_devices) == 'array' ? a.lan_devices : [])) { + d = str(d); + // Unknown names are kept only if they were saved before (interface down right now). + if (d == '' || d == srv.ifname || (!snap.devices[d] && index(srv.lan_devices, d) < 0)) + continue; + if (snap.devices[d]?.master) + die(`${d} is part of ${snap.devices[d].master}; choose ${snap.devices[d].master} instead.`); + if (d == (auto_wan ? snap.wan : wan_dev)) + die(`${d} is the WAN.`); + push(lans, d); + } + lans = uniq(lans); + let id = srv.id; + if (a.lan_like != null) + c.set(core.CONFIG, id, 'lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1'); + let mesh = index(core.MESH, a.mesh) >= 0 ? a.mesh + : a.device_mesh == null ? srv.mesh : (a.device_mesh === false || a.device_mesh === '0' ? 'off' : 'all'); + c.set(core.CONFIG, id, 'mesh', mesh); + c.delete(core.CONFIG, id, 'device_mesh'); + c.set(core.CONFIG, id, 'auto_wan', auto_wan ? '1' : '0'); + c.set(core.CONFIG, id, 'auto_lan', auto_lan ? '1' : '0'); + if (auto_wan || wan_dev == '') + c.delete(core.CONFIG, id, 'wan_device'); + else + c.set(core.CONFIG, id, 'wan_device', wan_dev); + if (length(lans)) + c.set(core.CONFIG, id, 'lan_device', lans); + else + c.delete(core.CONFIG, id, 'lan_device'); + // Remember what was detected, as the fallback while an interface is down. + if (snap.wan) + c.set(core.CONFIG, id, 'detected_wan', snap.wan); + if (snap.lan) + c.set(core.CONFIG, id, 'detected_lan', snap.lan); + // Keep the legacy zone options in step (older code paths, health checks). + let now = core.load(c).servers[id]; + let sn = net.server_net(now, snap); + if (sn.wan.zone) + c.set(core.CONFIG, id, 'wan_zone', sn.wan.zone); + if (length(sn.zones)) + c.set(core.CONFIG, id, 'lan_zone', sn.zones[0]); + return { was: srv, now: core.load(c).servers[id], mesh }; + }); + let srv = res.was; + // What the admin changed here: the networks, and/or whether devices reach each other. + let sig = (x) => { + let sn = net.server_net(x, snap); + return `${join(',', sn.nets)}|${sn.wan.dev}|${x.lan_like}`; + }; + let what = []; + if (sig(res.now) != sig(srv)) + push(what, 'home network and internet path'); + if (res.mesh != srv.mesh) + push(what, MESH_WORDS[res.mesh]); + if (length(what)) + admin_log('awg', 'changed', 'server', srv.name, join(', ', what)); + let before = join(',', net.server_net(srv, snap).nets); + apply.apply(); + let m = core.load(); + let v = interfaces_view(m, m.servers[srv.id], net.snapshot(true)); + v.nets_changed = before != join(',', v.effective.nets); + return v; +} + +/* ---------- settings ---------- */ + +/** A list of DNS servers as typed (array or "a, b"): each an IPv4 or IPv6 address. */ +function dns_list(v) { + let list = filter(map(type(v) == 'array' ? v : split(str(v), /[ ,]+/), str), (x) => x != ''); + for (let d in list) + if (!schema.ip(d)) + die(`${d} is not an IP address.`); + return list; +} + +/** Server settings from the General and Network tabs; applied at once. */ +function server_update(a) { + let v = a.values ?? {}; + if (v.device_mesh != null && v.mesh == null) + v.mesh = v.device_mesh === true || v.device_mesh == '1' ? 'all' : 'off'; + let srv = store.transact((c, m) => { + let srv = m.servers[a.id]; + if (!srv) + die('Unknown server.'); + let set = (k, val) => (val == null || val == '') ? c.delete(core.CONFIG, srv.id, k) : c.set(core.CONFIG, srv.id, k, val); + if (v.name != null) { + if (str(v.name) == '') + die('Name cannot be empty.'); + set('name', str(v.name)); + } + if (v.endpoint != null) { + if (str(v.endpoint) == '' || !valid_host(str(v.endpoint))) + die('Public address must be a hostname or IP address.'); + set('endpoint', str(v.endpoint)); + } + if (v.port != null) { + if (!schema.valid_port(v.port)) + die('UDP port must be 1-65535.'); + let n = +str(v.port); + for (let id, o in m.servers) + if (id != srv.id && o.port == n) + die(`UDP ${n} is used by ${o.name}.`); + set('port', `${n}`); + } + if (v.enabled != null) + set('enabled', v.enabled === true || v.enabled == '1' ? '1' : '0'); + if (v.mesh != null) { + if (index(core.MESH, v.mesh) < 0) + die('Unknown choice for devices reaching each other.'); + set('mesh', v.mesh); + set('device_mesh', null); + } + if (v.mtu != null) + set('mtu', check_mtu(v.mtu)); + if (v.keepalive != null) { + if (str(v.keepalive) != '' && (!match(str(v.keepalive), /^[0-9]{1,3}$/) || +v.keepalive > 600)) + die('Keep-alive must be 0-600 seconds.'); + set('keepalive', str(v.keepalive)); + } + if (v.dns != null) { + let list = dns_list(v.dns); + if (length(list)) + c.set(core.CONFIG, srv.id, 'dns', list); + else + c.delete(core.CONFIG, srv.id, 'dns'); + } + return srv; + }); + // For the log: what changed, in words. Turning on or off is its own line. + let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS' }; + let what = []; + for (let k, label in labels) { + if (v[k] == null) + continue; + let was = k == 'dns' ? join(' ', srv.dns ?? []) : `${srv[k] ?? ''}`; + let now = k == 'dns' ? join(' ', dns_list(v.dns)) : str(v[k]); + if (trim(was) != trim(now)) + push(what, label); + } + let turned = v.enabled == null ? null : (v.enabled === true || v.enabled == '1'); + let name = v.name != null ? str(v.name) : srv.name; + let r = apply.apply(); + if (turned != null && turned != srv.enabled) + admin_log('dawnline', turned ? 'turned on' : 'turned off', 'server', name); + if (length(what)) + admin_log('dawnline', 'changed', 'server', name, join(', ', what)); + if (v.mesh != null && v.mesh != srv.mesh) + admin_log('dawnline', 'changed', 'server', name, MESH_WORDS[v.mesh]); + return r; +} + +function server_obfuscation(a) { + let preset = str(a.preset) || 'standard'; + let o = awg.obf_preset(check_method(preset)); + let srv = store.transact((c, m) => { + let srv = m.servers[a.id]; + if (!srv) + die('Unknown server.'); + for (let k in core.OBF_KEYS) + c.delete(core.CONFIG, srv.id, k); + for (let k, v in o) + c.set(core.CONFIG, srv.id, k, v); + c.set(core.CONFIG, srv.id, 'preset', preset); + return srv; + }); + let r = apply.apply(); + admin_log('awg', 'changed', 'server', srv.name, `disguise: ${preset}`); + return r; +} + +/** Remove a server with its people, their devices and its circles (a backup is made first). */ +function server_delete(a) { + if (!core.load().servers[a.id]) + die('Unknown server.'); + backup.backup_create('pre-delete'); + let res = store.transact((c, m) => { + let srv = m.servers[a.id]; + if (!srv) + die('Unknown server.'); + let gone = 0; + for (let pid, p in m.people) + if (p.server == srv.id) { + core.delete_person(c, m, pid); + gone++; + } + for (let cid, ci in m.circles) + if (ci.server == srv.id) + c.delete(core.CONFIG, cid); + c.delete(core.CONFIG, srv.id); + return { name: srv.name, gone }; + }); + let r = apply.apply(); + admin_log('awg', 'removed', 'server', res.name, res.gone ? `with ${res.gone} ${res.gone == 1 ? 'person' : 'people'}` : null); + return r; +} + +export const methods = { + setup_defaults: { call: wrap(setup_defaults) }, + server_create: { + args: { id: '', name: '', ifname: '', port: 0, subnet: '', endpoint: '', mtu: 0, preset: '', lan_zone: '', wan_zone: '', + lan_like: true, portal_enabled: false, portal_port: 0 }, + call: wrap(server_create), + }, + server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) }, + server_update: { args: { id: '', values: {} }, call: wrap(server_update) }, + interfaces: { args: { id: '' }, call: wrap(interfaces_get) }, + server_interfaces: { + args: { id: '', auto_wan: false, wan_device: '', auto_lan: false, lan_devices: [], lan_like: false, device_mesh: true, mesh: '' }, + call: wrap(server_interfaces), + }, + server_delete: { args: { id: '' }, call: wrap(server_delete) }, +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/settings.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/settings.uc new file mode 100644 index 0000000..7d01cd4 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/settings.uc @@ -0,0 +1,150 @@ +// Dawnline rpcd methods: the Settings page (the portal, defaults, logs and +// history, updates). What may be saved is dawnline.schema's. + +import { stat } from 'fs'; +import { q, sh_out, admin_log, RUN_DIR, DATA_DIR } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as live from 'dawnline.live'; +import * as apply from 'dawnline.apply'; +import * as geo from 'dawnline.geo'; +import * as store from 'dawnline.store'; +import * as schema from 'dawnline.schema'; +import * as health from 'dawnline.health'; +import * as pc from 'dawnline.portalcert'; +import { wrap, check_portal } from 'dawnline.rpc.common'; + +/** The portal's own checks from Health, shown next to its settings. */ +const PORTAL_CHECKS = [ 'portal', 'portal_dns', 'portal_reply', 'portal_http', 'cert' ]; + +function file_size(path) { + return stat(path)?.size ?? 0; +} + +/** What the log and traffic history hold right now (Settings → Logs & history). */ +function logs_info(m) { + let ev = live.load_events(); + let by = {}; + for (let cat in live.CATEGORIES) + by[cat] = 0; + for (let e in ev) + by[live.category_of(e.type)]++; + let usage = core.load_usage(); + let days = {}; + for (let grp in [ usage?.devices ?? {}, usage?.people ?? {} ]) + for (let id, rec in grp) + for (let k in keys(rec.days ?? {})) + days[k] = true; + let dk = sort(keys(days)); + return { + policy: live.policy(m.settings.retention), + events: length(ev), + oldest: length(ev) ? ev[0].ts : 0, + by_category: by, + log_ram: file_size(`${RUN_DIR}/events.json`), + log_flash: file_size(`${DATA_DIR}/events.json`), + usage_flash: file_size(`${DATA_DIR}/usage.json`), + usage_since: length(dk) ? dk[0] : '', + usage_days: length(dk), + geo_flash: file_size(`${DATA_DIR}/geo.json`), + }; +} + +function settings_get(a) { + let c = core.open_cursor(); + let raw = c.get_all(core.CONFIG, 'settings') ?? {}; + let m = core.load(c); + let out = {}; + for (let k in keys(schema.SETTINGS)) + out[k] = raw[k] ?? ''; + out.log_category = live.policy(m.settings.retention).categories; + let cert = m.settings.portal_enabled ? pc.portal_cert(m.settings) : null; + return { + settings: out, + needs: health.needs(), + effective: m.settings, + services: values(m.services), + cert: cert ? { path: cert.cert, self_signed: cert.self_signed, + expires: sh_out(`openssl x509 -enddate -noout -in ${q(cert.cert)} 2>/dev/null | cut -d= -f2`) } : null, + port_owners: m.settings.portal_enabled ? [] : health.tcp_port_owners(m.settings.portal_port), + portal_public_port: core.portal_public_port(m), + geo_cached: length(keys(geo.load().ips)), + logs: logs_info(m), + }; +} + +/* + * The slow part of the portal settings (DNS lookups and the Health checks), + * fetched after the page shows. + */ +function portal_info(a) { + let m = core.load(); + return { + candidates: pc.portal_candidates(m), + checks: filter(health.health(m), (x) => index(PORTAL_CHECKS, x.id) >= 0), + }; +} + +function same(a, b) { + return (type(a) == 'array' ? join('\n', a) : a ?? '') == (type(b) == 'array' ? join('\n', b) : b ?? ''); +} + +/** Save settings (`values`: key → value, '' back to the default); the portal is checked as it will be. */ +function settings_update(a) { + let v = a.values ?? {}; + if (type(v) != 'object') + die('Nothing to save.'); + let res = store.transact((c, m) => { + let restart = false; + c.set(core.CONFIG, 'settings', 'settings'); + for (let k, val in v) { + if (k == 'log_category') { + let lst = filter(type(val) == 'array' ? val : [], (x) => index(live.CATEGORIES, x) >= 0); + c.set(core.CONFIG, 'settings', 'log_category', length(lst) ? lst : [ '' ]); + // Superseded by the category list. + c.delete(core.CONFIG, 'settings', 'log_connections'); + continue; + } + let nv = schema.validate(k, val); + if (schema.SETTINGS[k].restart && !same(nv, c.get(core.CONFIG, 'settings', k))) + restart = true; + if (nv == null) + c.delete(core.CONFIG, 'settings', k); + else + c.set(core.CONFIG, 'settings', k, nv); + } + check_portal(core.load(c), m); + return { restart, was: m.settings }; + }); + if (res.restart) + system('/etc/init.d/dawnline reload >/dev/null 2>&1'); + else + apply.sync(); + // The changes worth a line: the portal and the watchdog (other settings are housekeeping). + let now = core.load().settings, was = res.was; + if (now.portal_enabled != was.portal_enabled) + admin_log('portal', now.portal_enabled ? 'turned on' : 'turned off', null, 'the personal portal', now.portal_enabled ? `port ${now.portal_port}` : null); + else if (now.portal_enabled) { + let what = []; + if (now.portal_port != was.portal_port) + push(what, `port ${now.portal_port}`); + if (now.portal_host != was.portal_host) + push(what, `address ${now.portal_host}`); + if (join(' ', now.portal_alt) != join(' ', was.portal_alt)) + push(what, 'other addresses'); + if (now.portal_cert != was.portal_cert || now.portal_key != was.portal_key) + push(what, 'certificate'); + if (now.portal_redirect != was.portal_redirect) + push(what, 'redirect'); + if (length(what)) + admin_log('portal', 'changed', null, 'the personal portal', join(', ', what)); + } + if (now.watchdog != was.watchdog) + admin_log('dawnline', now.watchdog ? 'turned on' : 'turned off', null, 'the watchdog', now.watchdog ? null : 'problems are only logged, nothing is repaired'); + return settings_get({}); +} + +export const methods = { + settings_get: { call: wrap(settings_get) }, + portal_info: { call: wrap(portal_info) }, + settings_update: { args: { values: {} }, call: wrap(settings_update) }, +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/status.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/status.uc new file mode 100644 index 0000000..b773292 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/status.uc @@ -0,0 +1,230 @@ +// Dawnline rpcd methods: the Overview status (servers, people, totals, map, +// recent activity), the activity log and traffic history. + +import { readfile } from 'fs'; +import { read_json, write_json, ensure_dir, lock, unlock, admin_log, VERSION, RUN_DIR } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as live from 'dawnline.live'; +import * as view from 'dawnline.view'; +import * as geo from 'dawnline.geo'; +import * as net from 'dawnline.net'; +import * as loop from 'dawnline.loop'; +import * as awg from 'dawnline.awg'; +import { wrap, clamp_days } from 'dawnline.rpc.common'; + +/** Router location plus one point per (device, recent client address). */ +function geo_view(m, usage, dmp) { + if (!m.settings.geo_enabled) + return { enabled: false, home: null, points: [] }; + let cache = geo.load(); + let points = []; + let now = time(); + for (let id, d in m.devices) { + let rec = usage.devices?.[id]; + let peer = dmp.peers[d.public_key]; + let cur = live.endpoint_ip(peer?.endpoint); + let online = !!(peer && peer.handshake > 0 && now - peer.handshake < live.ONLINE_WINDOW); + for (let ip, ts in rec?.ips ?? {}) { + // Local (LAN / CGNAT) client addresses are not shown on the map. + let pl = geo.is_public(ip) ? geo.place(cache, ip) : null; + if (!pl) + continue; + push(points, { + person: d.person, device: id, ip, ts, + online: online && ip == cur, + lat: pl.lat, lon: pl.lon, city: pl.city, country: pl.country, cc: pl.cc, + asn: pl.asn ?? 0, org: pl.org ?? '', + }); + } + } + let h = cache.home; + return { + enabled: true, + provider: m.settings.geo_provider, + cached: length(keys(cache.ips)), + home: (h && h.lat != null) ? { lat: h.lat, lon: h.lon, city: h.city, country: h.country, cc: h.cc, asn: h.asn ?? 0, org: h.org ?? '' } : null, + points, + }; +} + +/** Older connections from home get the DHCP name their address has now. */ +function with_hosts(ev) { + let names = null; + for (let e in ev) + if ((e.type == 'connect' || e.type == 'roam') && !e.hosts) { + let h = net.event_hosts(e, names ??= net.lan_names()); + if (h) + e.hosts = h; + } + return ev; +} + +function server_view(m, srv, usage, dmp, rates, days) { + let online = 0, peers = 0, now = time(); + let links = map(core.tunnels(srv), (t) => t.ifname); + for (let k, p in dmp.peers) + if (index(links, p.ifname) >= 0) { + peers++; + if (p.handshake > 0 && now - p.handshake < live.ONLINE_WINDOW) + online++; + } + let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 }; + return { + id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet, + endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled, + lan_like: srv.lan_like, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns, + address: core.server_address(srv), up: !!st.up, uptime: st.uptime ?? 0, + // Why the tunnel cannot run (its interface name belongs to another network section), or null. + blocked: srv.blocked ?? null, + // Home networks (interfaces) for the per-person picker. + home: map(net.server_net(srv).home, (h) => ({ dev: h.dev, nets: h.nets })), + peers, online, obf: srv.obf, + // Bytes per second, one point a minute: [ts, rx, tx] (rx = from devices). + rate: rates[srv.id] ?? [], + // Daily traffic of the people on this server (its Overview chart). + series: live.series(map(filter(keys(m.people), (pid) => m.people[pid].server == srv.id), (pid) => usage.people?.[pid]), days), + }; +} + +/* + * Everything the pages show at once. Readable by read-only users: no personal + * codes or links here (person_links has them). + */ +function status(a) { + let m = core.load(); + let usage = core.load_usage(); + let dmp = live.dump(m); + let states = view.states(m, usage); + let days = clamp_days(a.days); + + let servers = []; + let rates = read_json(`${RUN_DIR}/rate.json`, {}); + let prates = read_json(`${RUN_DIR}/rate_people.json`, {}); + for (let id, srv in m.servers) + push(servers, server_view(m, srv, usage, dmp, rates, days)); + + let people = []; + for (let id, p in m.people) { + let pv = view.person_view(m, p, usage, dmp, states, { admin: true }); + pv.rate = type(prates[p.id]?.[0]) == 'array' ? prates[p.id] : []; + push(people, pv); + } + people = sort(people, (a, b) => (b.online - a.online) || (b.last_seen - a.last_seen) || (a.name < b.name ? -1 : 1)); + + let totals = { people: length(people), devices: 0, online: 0, active: 0 }; + for (let p in people) { + totals.devices += length(p.devices); + totals.online += p.online; + if (p.state == 'active') + totals.active++; + } + let recs = values(usage.people ?? {}); + let day = live.series(recs, 1)[0]; + totals.today = [ day.rx, day.tx ]; + let mon = [ 0, 0 ]; + for (let r in recs) { + let v = live.month(r); + mon[0] += v[0]; + mon[1] += v[1]; + } + totals.month = mon; + + let events = live.load_events(); + let s = m.settings; + return { + geo: geo_view(m, usage, dmp), + version: VERSION, + now: time(), + hostname: trim(readfile('/proc/sys/kernel/hostname') ?? ''), + settings: { + portal_enabled: s.portal_enabled, portal_port: s.portal_port, portal_host: s.portal_host, + portal_public_port: core.portal_public_port(m), + paused_all: s.paused_all, default_device_limit: s.default_device_limit, domain: s.domain, + hostnames: s.hostnames, geo_enabled: s.geo_enabled, home_dns_fallback: s.home_dns_fallback, + }, + servers, + people, + services: values(m.services), + circles: values(m.circles), + totals, + series: live.series(recs, days), + events: with_hosts(slice(events, length(events) > 60 ? length(events) - 60 : 0)), + like_home: loop.status(), + awg: awg.caps(), + awg_state: awg.state(), + }; +} + +function events_list(a) { + // Tunnel down/up events of older versions: the service log tells it better (names, reasons). + let ev = filter(live.load_events(), (e) => e.type != 'server_down' && e.type != 'server_up'); + let n = +a.limit || 300; + return { events: with_hosts(slice(ev, length(ev) > n ? length(ev) - n : 0)), total: length(ev), policy: live.policy() }; +} + +/** Remove activity by person, device, category and/or age; nothing given clears it all. */ +function logs_clear(a) { + let m = core.load(); + let f = {}; + if (a.person) { + if (!m.people[a.person]) + die('Unknown person.'); + f.person = a.person; + } + if (a.device) + f.device = a.device; + if (a.category) { + if (index(live.CATEGORIES, a.category) < 0) + die('Unknown category.'); + f.category = a.category; + } + if (a.older_days) { + if (!match(a.older_days, /^[1-9][0-9]{0,3}$/)) + die('Older than must be a number of days.'); + f.before = time() - +a.older_days * 86400; + } + let removed = live.clear_events(f); + if (removed) + admin_log('dawnline', 'cleared', null, 'the activity log', + join(' · ', filter([ `${removed} event${removed == 1 ? '' : 's'}`, f.category, f.person ? m.people[f.person].name : null, + a.older_days ? `older than ${a.older_days} days` : null ], (x) => x))); + return { ok: true, removed }; +} + +/** + * Reset traffic history (all | person | device). The agent owns the live + * counters, so it gets a marker; the tmpfs copy is edited too so the UI + * shows the result straight away. + */ +function usage_clear(a) { + let m = core.load(); + if (index([ 'all', 'person', 'device' ], a.scope) < 0) + die('Unknown scope.'); + if (a.scope == 'person' && !m.people[a.id]) + die('Unknown person.'); + if (a.scope == 'device' && !m.devices[a.id]) + die('Unknown device.'); + let req = { scope: a.scope, id: a.id, ts: time() }; + ensure_dir(RUN_DIR); + let l = lock('usage-reset'); + let pending = read_json(`${RUN_DIR}/usage.reset`, []); + push(pending, req); + write_json(`${RUN_DIR}/usage.reset`, pending, 0o600); + unlock(l); + let usage = core.load_usage(); + if (usage) { + live.reset_usage(usage, m, a.scope, a.id); + write_json(`${RUN_DIR}/usage.json`, usage, 0o600); + } + admin_log('dawnline', 'reset traffic history', null, + a.scope == 'all' ? 'for everyone' : a.scope == 'person' ? `for ${m.people[a.id].name}` : `for ${m.devices[a.id].name} (${m.people[m.devices[a.id].person]?.name})`); + return { ok: true }; +} + +export const methods = { + status: { args: { days: 30 }, call: wrap(status) }, + events: { args: { limit: 300 }, call: wrap(events_list) }, + logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) }, + usage_clear: { args: { scope: '', id: '' }, call: wrap(usage_clear) }, + geo_clear: { call: wrap((a) => { geo.clear(); return { ok: true }; }) }, +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/updates.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/updates.uc new file mode 100644 index 0000000..a0969df --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/updates.uc @@ -0,0 +1,139 @@ +// Dawnline rpcd methods for the Components tab: status, starting update jobs +// (the updater does the work in the background), releases, release notes +// and the changes between two releases. luci.dawnline merges `methods`. + +import { readfile } from 'fs'; +import { cursor } from 'uci'; +import { read_json, ensure_dir, VERSION, REPO, RUN_DIR } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as health from 'dawnline.health'; +import * as upd from 'dawnline.updates'; +import * as gh from 'dawnline.github'; +import * as builds from 'dawnline.awg_builds'; +import { NAMES as PKG_NAMES } from 'dawnline.upd_pkgs'; + +const TAG = /^v?[0-9][0-9A-Za-z.+~-]{0,40}$/; +// check[:app|amneziawg|packages] | app[@tag|:reinstall|:rollback] +// | amneziawg[:auto|slava|grey[:ru]|:rollback] | pkgs: (only packages Dawnline manages) +const TARGET = /^(check(:(app|amneziawg|packages))?|app(@v?[0-9][0-9A-Za-z.+~-]{0,40}|:reinstall|:rollback)?|amneziawg(:rollback|:(auto|slava|grey)(:ru)?)?|pkgs:[a-z0-9][a-z0-9.+,-]*)$/; + +function wrap(fn) { + return function(req) { + try { + let r = fn(req.args ?? {}); + return type(r) == 'object' ? r : { result: r }; + } + catch (e) { + return { error: e.message ?? `${e}` }; + } + }; +} + +/** AmneziaWG interfaces by name: switching builds restarts them. */ +function awg_tunnels() { + let out = []; + let c = cursor(); + c.load('network'); + c.foreach('network', 'interface', (s) => { + if (s.proto == 'amneziawg' && s.disabled != '1') + push(out, s._dawnline_name ?? s['.name']); + }); + return out; +} + +function status(a) { + let m = core.load(); + let rel = {}; + for (let line in split(readfile('/etc/openwrt_release') ?? '', '\n')) { + let x = match(line, /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/); + if (x) + rel[lc(x[1])] = x[2]; + } + return { + version: VERSION, + firmware: { version: rel.release ?? '', target: rel.target ?? '', arch: rel.arch ?? '' }, + portal: m.settings.portal_enabled, + home: length(filter(values(m.servers), (x) => x.lan_like)) > 0, + needs: health.needs(), + check: read_json(upd.CHECK_FILE, null), + job: upd.job(), + now: time(), + repo: REPO, + policy: m.settings.updates, + auto: upd.auto_state(), + kept: upd.kept_all(builds.firmware()?.postfix), + history: slice(upd.history(), 0, 12), + tunnels: awg_tunnels(), + }; +} + +/** Releases for the Versions list (Dawnline), five per page. */ +function releases(a) { + let page = +(a.page ?? 1); + if (page != int(page) || page < 1 || page > 50) + die('Unknown page.'); + return { releases: map(gh.releases(REPO, page), (x) => ({ ...x, body: null, digests: null })), page }; +} + +/** Release notes for What's new: Dawnline by tag, or an AmneziaWG build's release. */ +function notes(a) { + let rp = a.component == 'amneziawg' ? builds.SOURCES[a.build || 'slava']?.repo : REPO; + let tag = a.tag ?? ''; + if (!rp || !match(tag, TAG)) + die('Unknown release.'); + let r = gh.release(rp, tag); + if (!r && a.component != 'amneziawg' && substr(tag, 0, 1) != 'v') + r = gh.release(rp, `v${tag}`); + if (!r) + die(`No release ${tag} in ${rp}.`); + return { ...r, digests: null, repo: rp }; +} + +/** What changed between the installed Dawnline and a release (points for the Components tab). */ +function changes(a) { + let to = a.to ?? '', from = a.from ?? ''; + if (!match(to, TAG) || (from != '' && !match(from, TAG))) + die('Unknown release.'); + // The installed version as a tag when it was released (a build ahead of the releases has none). + let base = null; + for (let t in (from != '' ? [ `v${replace(from, /^v/, '')}`, replace(from, /^v/, '') ] : [])) + if (!base && gh.release(REPO, t)) + base = t; + return { items: gh.changes(REPO, base, to) }; +} + +/** + * Start an update job. Returns the new job once its worker has written it, + * else null (the caller follows updates_status); never an older job. + */ +function run(a) { + let what = a.what ?? 'check'; + if (length(what) > 400 || !match(what, TARGET)) + die('Unknown update target.'); + // Checked here too, so a wrong name never becomes a failed job in the history. + if (substr(what, 0, 5) == 'pkgs:') + for (let n in split(substr(what, 5), ',')) + if (index(PKG_NAMES, n) < 0) + die(n == '' ? 'Unknown update target.' : `${n} is not a package Dawnline manages.`); + if (upd.busy()) + die('Another component action is already running.'); + ensure_dir(RUN_DIR); + let t0 = time(); + let args = substr(what, 0, 5) == 'check' ? `check ${substr(what, 6)}` : `install ${what}`; + system(`start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- ${args}`); + for (let i = 0; i < 20; i++) { + let j = read_json(upd.JOB_FILE, null); + if (j?.state == 'running' && j.started >= t0) + return { started: true, job: j }; + system('usleep 100000 2>/dev/null || sleep 1'); + } + return { started: true, job: null }; +} + +export const methods = { + updates_status: { call: wrap(status) }, + updates_run: { args: { what: '' }, call: wrap(run) }, + updates_releases: { args: { page: 1 }, call: wrap(releases) }, + updates_notes: { args: { component: '', tag: '', build: '' }, call: wrap(notes) }, + updates_changes: { args: { from: '', to: '' }, call: wrap(changes) }, +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc new file mode 100644 index 0000000..8dd9068 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc @@ -0,0 +1,254 @@ +// Dawnline — what the settings section may hold: one entry per option with +// its type, default and range, used to validate what the admin saves and to +// parse what is stored. Also the address checks the rest of the code shares. +// +// Booleans are stored as '1' / '0' only, and parsed the way the init script's +// config_get_bool does, so the service and the code never disagree. + +import { stat } from 'fs'; +import { ip2int, valid_host } from 'dawnline.util'; +import { INTERVALS, TARGETS } from 'dawnline.updates'; + +/* ---------- addresses ---------- */ + +/** An IPv4 address in dotted form. */ +export function ipv4(s) { + return type(s) == 'string' && ip2int(s) != null; +}; + +/** + * An IPv6 address → its eight 16-bit groups, or null. Accepts '::' and an + * embedded IPv4 at the end (::ffff:192.0.2.1); no zone ids or prefixes. + */ +export function ipv6_groups(s) { + if (type(s) != 'string' || length(s) < 2 || length(s) > 45 || !match(s, /^[0-9A-Fa-f:.]+$/)) + return null; + let tail = []; + let v4 = match(s, /^(.*:)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/); + if (v4) { + let n = ip2int(v4[2]); + if (n == null) + return null; + tail = [ (n >> 16) & 0xffff, n & 0xffff ]; + s = substr(v4[1], -2) == '::' ? v4[1] : substr(v4[1], 0, length(v4[1]) - 1); + } + else if (index(s, '.') >= 0) + return null; + let halves = split(s, '::'); + if (length(halves) > 2) + return null; + let groups = (part) => { + let out = []; + if (part == '') + return out; + for (let g in split(part, ':')) { + if (!match(g, /^[0-9A-Fa-f]{1,4}$/)) + return null; + push(out, hex(g)); + } + return out; + }; + let head = groups(halves[0]); + let rest = length(halves) == 2 ? groups(halves[1]) : []; + if (head == null || rest == null) + return null; + if (length(halves) == 1) { + push(head, ...tail); + return length(head) == 8 ? head : null; + } + push(rest, ...tail); + let gap = 8 - length(head) - length(rest); + if (gap < 1) + return null; + let out = [ ...head ]; + for (let i = 0; i < gap; i++) + push(out, 0); + push(out, ...rest); + return out; +}; + +/** An IPv6 address (any valid notation). */ +export function ipv6(s) { + return ipv6_groups(s) != null; +}; + +/** An IPv4 or IPv6 address. */ +export function ip(s) { + return ipv4(s) || ipv6(s); +}; + +/** A TCP/UDP port as typed: 1-5 digits, 1-65535. */ +export function valid_port(v) { + let s = trim(`${v ?? ''}`); + return match(s, /^[0-9]{1,5}$/) != null && +s >= 1 && +s <= 65535; +}; + +/* ---------- parsing stored values ---------- */ + +/** A stored boolean, as the init script's config_get_bool reads it. */ +export function bool(v, dflt) { + v = lc(trim(`${v ?? ''}`)); + if (index([ '1', 'on', 'true', 'yes', 'enabled' ], v) >= 0) + return true; + if (index([ '0', 'off', 'false', 'no', 'disabled' ], v) >= 0) + return false; + return dflt; +}; + +/** A stored whole number within [min, max], else the default. */ +export function to_int(v, dflt, lo, hi) { + let s = trim(`${v ?? ''}`); + if (!match(s, /^-?[0-9]{1,9}$/)) + return dflt; + let n = +s; + return (lo != null && n < lo) || (hi != null && n > hi) ? dflt : n; +}; + +/* ---------- the settings section ---------- */ + +/* + * type: bool | int | enum | host | hosts | url | file | domain | ipv4 | time | text | targets + * dflt: the parsed default; restart: the portal (uhttpd) must restart when it changes; + * min/max: ints and text length; values: enums; msg: the error for a bad value. + */ +export const SETTINGS = { + portal_enabled: { type: 'bool', dflt: false, restart: true }, + portal_host: { type: 'host', dflt: '', restart: true, msg: 'Public address must be a hostname or IP address.' }, + portal_alt: { type: 'hosts', dflt: [], restart: true }, + portal_port: { type: 'int', dflt: 8443, min: 1, max: 65535, restart: true, + msg: 'Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).' }, + portal_title: { type: 'text', dflt: 'Dawnline', max: 64, msg: 'Portal title: up to 64 characters on one line.' }, + portal_redirect: { type: 'url', dflt: '', msg: 'Redirect must be a full http:// or https:// address.' }, + portal_cert: { type: 'file', dflt: '', restart: true }, + portal_key: { type: 'file', dflt: '', restart: true }, + default_device_limit: { type: 'int', dflt: 3, min: 1, max: 32, msg: 'Default device limit must be 1-32.' }, + hostnames: { type: 'bool', dflt: true }, + domain: { type: 'domain', dflt: 'lan', msg: 'Domain may use lowercase letters, digits, dashes and dots.' }, + geo_enabled: { type: 'bool', dflt: true }, + geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ], msg: 'Unknown location service.' }, + log_connections: { type: 'bool', dflt: true }, + watchdog: { type: 'bool', dflt: true }, + log_keep_days: { type: 'int', dflt: 30, min: 0, max: 9999, msg: 'Keep activity for 0 (no age limit) to 9999 days.' }, + log_max: { type: 'int', dflt: 2000, min: 100, max: 20000, msg: 'Log size must be 100-20000 events.' }, + log_persist: { type: 'enum', dflt: 'hourly', values: [ '10min', 'hourly', 'off' ], msg: 'Save the log every 10min, hourly or off.' }, + usage_keep_days: { type: 'int', dflt: 62, min: 7, max: 1830, msg: 'Daily traffic history must be 7-1830 days.' }, + usage_keep_months: { type: 'int', dflt: 24, min: 1, max: 120, msg: 'Monthly traffic history must be 1-120 months.' }, + // Empty means "no fallback" (stored as 'none'); unset means the default. + home_dns_fallback: { type: 'ipv4', dflt: '1.1.1.1', msg: 'Fallback DNS must be an IPv4 address (or empty for none).' }, + update_check: { type: 'bool', dflt: true }, + update_interval: { type: 'enum', dflt: '1d', values: keys(INTERVALS), msg: 'Check every 6h, 12h, 1d or 7d.' }, + update_auto: { type: 'bool', dflt: true }, + update_mode: { type: 'enum', dflt: 'scheduled', values: [ 'immediate', 'scheduled' ], msg: 'Install updates immediately or scheduled.' }, + update_time: { type: 'time', dflt: '04:00', msg: 'Enter a time as HH:MM, 00:00 to 23:59.' }, + update_targets: { type: 'targets', dflt: [ 'app', 'packages' ] }, + update_keep: { type: 'bool', dflt: false }, + update_mirrors: { type: 'bool', dflt: true }, +}; + +/** Ports the portal never takes: SSH, DNS and the LuCI web server. */ +export const RESERVED_PORTS = [ 22, 53, 80, 443 ]; + +function bad(spec, key) { + die(spec.msg ?? `Invalid value for ${key}.`); +} + +/** + * Check a value the admin saves for setting `key`. Returns what to store: a + * string, a list, or null to remove the option (back to the default). Dies + * with a message for the admin when the value is not acceptable. + */ +export function validate(key, val) { + let spec = SETTINGS[key]; + if (!spec) + die(`Unknown setting ${key}.`); + let t = spec.type; + if (t == 'hosts') { + let lst = []; + for (let x in (type(val) == 'array' ? val : [])) + if (type(x) == 'string' && valid_host(trim(x)) && index(lst, trim(x)) < 0) + push(lst, trim(x)); + return length(lst) ? lst : null; + } + if (t == 'targets') { + let lst = []; + for (let x in (type(val) == 'array' ? val : [])) + if (index(TARGETS, x) >= 0 && index(lst, x) < 0) + push(lst, x); + // An empty list is a choice too ("none"), unlike a missing option (the default). + return length(lst) ? lst : [ 'none' ]; + } + if (type(val) == 'bool') + val = val ? '1' : '0'; + val = trim(`${val ?? ''}`); + if (t == 'ipv4' && val == '') + return 'none'; + if (val == '') + return null; + if (t == 'bool') { + if (val != '0' && val != '1') + die(`${key} is 0 or 1.`); + } + else if (t == 'int') { + if (!match(val, /^[0-9]{1,9}$/) || +val < spec.min || +val > spec.max) + bad(spec, key); + val = `${+val}`; + } + else if (t == 'enum') { + if (index(spec.values, val) < 0) + bad(spec, key); + } + else if (t == 'host') { + if (!valid_host(val)) + bad(spec, key); + } + else if (t == 'url') { + if (length(val) > 300 || !match(val, /^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^[:space:]"'<>]*)?$/)) + bad(spec, key); + } + else if (t == 'file') { + if (substr(val, 0, 1) != '/' || !stat(val)) + die(`${val} does not exist.`); + } + else if (t == 'domain') { + if (!match(val, /^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/)) + bad(spec, key); + } + else if (t == 'ipv4') { + if (!ipv4(val)) + bad(spec, key); + } + else if (t == 'time') { + if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/)) + bad(spec, key); + } + else if (t == 'text') { + if (length(val) > spec.max || match(val, /[[:cntrl:]]/)) + bad(spec, key); + } + return val; +}; + +/** + * A stored setting parsed by its schema entry: the typed value, or the default + * when it is missing or invalid. For dawnline.core's load(). + */ +export function get(raw, key) { + let spec = SETTINGS[key]; + let v = raw?.[key]; + if (!spec) + return v; + let t = spec.type; + if (t == 'bool') + return bool(v, spec.dflt); + if (t == 'int') + return to_int(v, spec.dflt, spec.min, spec.max); + if (t == 'hosts' || t == 'targets') + return v == null ? spec.dflt : filter(type(v) == 'array' ? v : [ v ], (x) => x != ''); + if (v == null || v == '') + return spec.dflt; + if (t == 'enum') + return index(spec.values, v) >= 0 ? v : spec.dflt; + if (t == 'ipv4') + return v == 'none' ? '' : (ipv4(v) ? v : spec.dflt); + return v; +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/store.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/store.uc new file mode 100644 index 0000000..cd2906d --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/store.uc @@ -0,0 +1,43 @@ +// Dawnline — changes to /etc/config/dawnline, the one way: under the config +// lock, against a model loaded inside that lock, committed with the file kept +// private. rpcd, the portal, the CLI and the agent all go through here, so +// no change is made on a stale model and none is lost to another writer. + +import { lock, unlock } from 'dawnline.util'; +import * as core from 'dawnline.core'; + +/** Section names that are never ids of people, devices, servers, services or circles. */ +export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ]; + +/** Commit the dawnline config and keep it readable by root only. */ +export function commit(c) { + c.commit(core.CONFIG); + system('chmod 600 /etc/config/dawnline'); +}; + +/** + * Run fn(c, m) with the config lock held, on a fresh cursor and model; commit + * when fn returns (the return value is passed on). Anything fn throws aborts + * without committing and is rethrown with the same message. + */ +export function transact(fn) { + let l = lock('config'); + try { + let c = core.open_cursor(); + let m = core.load(c); + let r = fn(c, m); + commit(c); + unlock(l); + return r; + } + catch (e) { + unlock(l); + die(e.message ?? `${e}`); + } +}; + +/** Is `id` used by anything in the model (any kind of section), or reserved? */ +export function id_taken(m, id) { + return index(RESERVED_IDS, id) >= 0 || m.servers?.[id] != null || m.people?.[id] != null || m.devices?.[id] != null || + m.services?.[id] != null || m.circles?.[id] != null; +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_app.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_app.uc new file mode 100644 index 0000000..552cdbc --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_app.uc @@ -0,0 +1,135 @@ +// Dawnline updater: Dawnline itself — check the latest release, install a +// release (latest, a tag, the same one again) or the kept previous version. +// ctx is the updater's job context (see usr/libexec/dawnline/updater). + +import { readfile } from 'fs'; +import { VERSION, REPO } from 'dawnline.util'; +import * as upd from 'dawnline.updates'; +import * as gh from 'dawnline.github'; +import * as pkg from 'dawnline.pkg'; + +function status(installed, latest) { + let c = upd.version_cmp(installed, latest); + return c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest'; +} + +export function check(ctx) { + let r = gh.latest(REPO); + if (!r) + return { installed: VERSION, latest: null, update: false, repo: REPO, status: '', note: `Cannot reach github.com/${REPO}` }; + let latest = replace(r.tag, /^v/, ''); + let st = status(VERSION, latest); + ctx.log(st == 'outdated' ? `Dawnline update is available: ${VERSION} → ${latest}` + : st == 'dev' ? `Installed Dawnline ${VERSION} is newer than the release ${latest}` + : `Dawnline is up to date (${VERSION})`); + return { installed: VERSION, latest, tag: r.tag, repo: REPO, url: r.url, published: r.published, update: st == 'outdated', status: st }; +}; + +/** + * The sha256 a release publishes for a file: GitHub's own (API), else the + * release's sha256sums.txt fetched straight from github.com (never a mirror). + */ +function want_sha(ctx, tag, asset, dir) { + let want = gh.asset_sha256(REPO, tag, asset); + if (want) + return want; + let sums = `${dir}/sha256sums-${replace(tag, /[^A-Za-z0-9.-]/g, '_')}.txt`; + if (!gh.download(`https://github.com/${REPO}/releases/download/${tag}/sha256sums.txt`, sums, { mirrors: false, log: ctx.log })) + return null; + for (let line in split(readfile(sums) ?? '', '\n')) { + let m = match(trim(line), /^([0-9a-f]{64})[ \t]+\*?(\S+)$/); + if (m && m[2] == asset) + return m[1]; + } + return null; +} + +/** Download a release's package, verified against its sha256. */ +function fetch(ctx, tag, dir) { + let ver = replace(tag, /^v/, ''); + let asset = `luci-app-dawnline-${ver}.${pkg.ext()}`; + ctx.phase(`Downloading ${asset}`); + let want = want_sha(ctx, tag, asset, dir); + if (!want) + die(`Release ${tag} publishes no checksum for ${asset}: not installing an unverified package`); + let f = `${dir}/${asset}`; + if (!gh.download(`https://github.com/${REPO}/releases/download/${tag}/${asset}`, f, { sha256: want, mirrors: ctx.pol.mirrors, log: ctx.log })) + die(`Download failed: ${asset}`); + ctx.log(`sha256 matches the release (${substr(want, 0, 12)}…)`); + return f; +} + +/** The release tag of a version: tags may or may not carry the v. */ +function tag_of(ver) { + for (let t in [ `v${ver}`, ver ]) { + try { + if (gh.release(REPO, t)) + return t; + } + catch (e) {} + } + return `v${ver}`; +} + +function backup(ctx) { + ctx.phase('Backing up configuration'); + system('/usr/bin/dawnline backup --reason pre-update >/dev/null 2>&1'); +} + +/** arg: null (latest) | @ | reinstall | rollback */ +export function install(ctx, arg) { + let out = { from: VERSION, to: null }; + if (arg == 'rollback') { + let k = upd.kept('app'); + if (!k) + die('No previous Dawnline version is kept on the router'); + out.to = k.version; + ctx.versions(VERSION, k.version); + backup(ctx); + ctx.phase(`Rolling back to ${k.version}`); + if (!pkg.install_files(k.files, true, ctx.log)) + die('Installation failed'); + upd.forget('app'); + ctx.after('app'); + return out; + } + let tag, force = false; + if (arg == 'reinstall') { + tag = tag_of(VERSION); + force = true; + } + else if (arg && substr(arg, 0, 1) == '@') { + tag = substr(arg, 1); + force = upd.version_cmp(replace(tag, /^v/, ''), VERSION) <= 0; + } + else { + let c = check(ctx); + if (!c.latest) + die(c.note); + if (!c.update) { + out.to = VERSION; + return out; + } + tag = c.tag; + } + out.to = replace(tag, /^v/, ''); + ctx.versions(VERSION, out.to); + let f = fetch(ctx, tag, ctx.work); + // The version being replaced, for Roll back (downloaded again: opkg keeps no package files). + if (ctx.pol.keep && out.to != VERSION && upd.kept('app')?.version != VERSION) { + ctx.phase(`Keeping Dawnline ${VERSION} for rollback`); + try { + system(`mkdir -p '${ctx.work}/keep'`); + upd.keep('app', VERSION, [ fetch(ctx, tag_of(VERSION), `${ctx.work}/keep`) ]); + } + catch (e) { + ctx.log(`Warning: could not keep ${VERSION}: ${e.message}`); + } + } + backup(ctx); + ctx.phase('Installing package'); + if (!pkg.install_files([ f ], force, ctx.log)) + die('Installation failed'); + ctx.after('app'); + return out; +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc new file mode 100644 index 0000000..01c7d86 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc @@ -0,0 +1,231 @@ +// Dawnline updater: AmneziaWG — the builds published for this firmware by +// each source, installing or switching a build (verified against GitHub's +// sha256), the Russian LuCI translation, and rolling back to a kept build. +// ctx is the updater's job context (see usr/libexec/dawnline/updater). + +import { stat } from 'fs'; +import { cursor } from 'uci'; +import { iface_intent } from 'dawnline.util'; +import * as upd from 'dawnline.updates'; +import * as gh from 'dawnline.github'; +import * as pkg from 'dawnline.pkg'; +import * as builds from 'dawnline.awg_builds'; + +function sh(cmd) { + return system(`${cmd} >/dev/null 2>&1`); +} + +/** + * Download one package of a build to dir, verified when GitHub publishes its + * sha256 (then mirrors may serve it); without a sha256 only github.com itself. + * Returns the path or null. + */ +function fetch(ctx, fw, name, src, dir) { + let file = builds.asset(fw, name); + let dest = `${dir}/${src}_${file}`; + let want = gh.asset_sha256(builds.SOURCES[src].repo, fw.tag, file); + let url = `https://github.com/${builds.SOURCES[src].repo}/releases/download/${fw.tag}/${file}`; + return gh.download(url, dest, { sha256: want, mirrors: ctx.pol.mirrors, log: ctx.log }) ? dest : null; +} + +/** The newest tag of the same OpenWrt series (24.10.x) in a repository, if newer than ours. */ +function newer_series_tag(rp, tag) { + let series = match(tag, /^v([0-9]+\.[0-9]+)\./)?.[1]; + let best = null; + try { + for (let x in gh.releases(rp, 1)) { + let t = x.tag; + if (series && match(t, regexp(`^v${replace(series, '.', '\\.')}\\.`)) && pkg.cmp(substr(t, 1), substr(tag, 1)) > 0 && + (!best || pkg.cmp(substr(t, 1), substr(best, 1)) > 0)) + best = t; + } + } + catch (e) {} + return best; +} + +export function check(ctx) { + let installed = builds.installed(); + let ru = pkg.version(builds.RU) != null; + let cur = installed['amneziawg-tools']; + let fw = builds.firmware(); + if (!fw) + return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '', + note: 'Cannot detect the firmware target' }; + let dir = `${ctx.work}/check`; + system(`mkdir -p '${dir}'`); + let sources = {}; + for (let id in builds.ORDER) { + let src = builds.SOURCES[id]; + ctx.log(`Looking for the ${src.label} build for OpenWrt ${substr(fw.tag, 1)}`); + let f = fetch(ctx, fw, 'amneziawg-tools', id, dir); + let v = f ? pkg.file_version(f) : null; + let date = null; + try { + date = f ? gh.release(src.repo, fw.tag)?.published : null; + } + catch (e) {} + let s = { label: src.label, repo: src.repo, tag: fw.tag, version: v, gen: builds.gen(v), date }; + // A newer firmware may already get 3.1 from this source. + if (s.gen != '3.1') { + let nt = newer_series_tag(src.repo, fw.tag); + if (nt) { + let nf = fetch(ctx, builds.for_tag(fw, nt), 'amneziawg-tools', id, dir); + if (builds.gen(nf ? pkg.file_version(nf) : null) == '3.1') + s.newer = { tag: nt, gen: '3.1' }; + } + } + sources[id] = s; + } + // The installed build: the source whose package matches. Unknown stays unknown + // (an automatic update never switches a build it could not identify). + let current = null; + for (let id, x in sources) + if (!current && cur && x.version == cur) + current = id; + let mine = current ? sources[current] : null; + let c = cur && mine?.version ? pkg.cmp(cur, mine.version) : null; + let st = c == null ? '' : c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest'; + ctx.log(cur == null ? 'AmneziaWG is not installed' + : !current ? `AmneziaWG ${cur}: no source publishes this build for this firmware any more` + : st == 'outdated' ? `AmneziaWG update is available: ${cur} → ${mine.version}` + : `AmneziaWG is up to date (${cur})`); + return { installed: cur, gen: builds.gen(cur), packages: installed, current, ru, release: fw.tag, sources, + latest: mine?.version ?? null, status: st, + update: cur == null || st == 'outdated', + // An update that changes the generation (2.0 → 3.1) breaks older apps: never automatic. + gen_change: cur != null && mine?.version != null && builds.gen(cur) != builds.gen(mine.version), + note: !length(filter(values(sources), (x) => x.version)) ? `No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} yet` : null }; +}; + +/** Tunnels on a new kernel module: every AmneziaWG interface is brought down and up again. */ +function reload_module(ctx, before, after) { + if (!before['kmod-amneziawg'] || before['kmod-amneziawg'] == after['kmod-amneziawg']) + return; + let ifaces = []; + let c = cursor(); + c.load('network'); + c.foreach('network', 'interface', (s) => { + if (s.proto == 'amneziawg' && s.disabled != '1') + push(ifaces, s['.name']); + }); + ctx.phase(`Reloading the kernel module (${length(ifaces)} tunnel(s) restart)`); + for (let i in ifaces) { + iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i); + sh(`ifdown '${i}'`); + } + sh('rmmod amneziawg'); + ctx.run('modprobe amneziawg'); + for (let i in ifaces) + sh(`ifup '${i}'`); +} + +/** After packages changed: the module loaded, netifd knowing the protocol, Dawnline set up again. */ +function settle(ctx, before, after) { + if (!before['kmod-amneziawg'] && after['kmod-amneziawg']) { + ctx.phase('Loading the kernel module'); + if (ctx.run('modprobe amneziawg').code != 0 && !stat('/sys/module/amneziawg')) + die("AmneziaWG is installed, but its kernel module doesn't load on this firmware"); + } + else + reload_module(ctx, before, after); + // netifd reads its protocol handlers when it starts. + if (index(ctx.run('ubus call network get_proto_handlers').out, '"amneziawg"') < 0) { + ctx.phase('Restarting the network so it knows AmneziaWG (connections drop for a few seconds)'); + ctx.run('/etc/init.d/network restart'); + } + ctx.after('apply'); +} + +/** The first source that publishes every package for this firmware. */ +function pick(fw) { + for (let id in builds.ORDER) { + let r = null; + try { + r = gh.release(builds.SOURCES[id].repo, fw.tag); + } + catch (e) {} + if (r && length(filter(builds.PKGS, (p) => index(r.assets, builds.asset(fw, p)) >= 0)) == length(builds.PKGS)) + return id; + } + return null; +} + +/** arg: [auto|slava|grey][:ru] | rollback */ +export function install(ctx, arg) { + let before = builds.installed(); + let out = { from: before['amneziawg-tools'], to: null, before }; + let fw = builds.firmware(); + if (!fw) + die('Cannot detect the firmware target'); + if (arg == 'rollback') { + let k = upd.kept('amneziawg'); + if (!k) + die('No previous AmneziaWG build is kept on the router'); + if (k.firmware && k.firmware != fw.postfix) + die('The kept AmneziaWG build was made for another firmware: it would not load on this one'); + out.to = k.version; + out.build = k.build; + ctx.versions(out.from, out.to); + ctx.phase(`Rolling back to ${k.version}`); + if (!pkg.install_files(k.files, true, ctx.log)) + die('Package installation failed'); + upd.forget('amneziawg'); + out.after = builds.installed(); + settle(ctx, before, out.after); + return out; + } + let parts = split(arg ?? '', ':'); + let id = parts[0] || 'auto'; + let want_ru = parts[1] == 'ru'; + if (id == 'auto') { + id = pick(fw); + if (!id) + die(`No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} (${fw.postfix}) yet`); + } + let src = builds.SOURCES[id]; + if (!src) + die(`Unknown AmneziaWG build ${id}`); + out.build = id; + let files = []; + for (let p in [ ...builds.PKGS, ...(want_ru ? [ builds.RU ] : []) ]) { + ctx.phase(`Downloading ${p} from ${src.repo}`); + let f = fetch(ctx, fw, p, id, ctx.work); + if (!f) + die(`No ${p} build for OpenWrt ${substr(fw.tag, 1)} in ${src.repo}, or it could not be verified`); + push(files, f); + } + out.to = pkg.file_version(files[1]); + ctx.versions(out.from, out.to); + // The build being replaced, for Roll back: from another source that still publishes it. + if (ctx.pol.keep && out.from && out.to != out.from) { + let dir = `${ctx.work}/keep`; + system(`mkdir -p '${dir}'`); + let kept = null; + for (let sid in builds.ORDER) { + if (sid == id || kept) + continue; + let f = fetch(ctx, fw, 'amneziawg-tools', sid, dir); + if (f && pkg.file_version(f) == out.from) + kept = sid; + } + if (kept) { + ctx.phase(`Keeping AmneziaWG ${out.from} for rollback`); + let keepf = filter(map(builds.PKGS, (p) => fetch(ctx, fw, p, kept, dir)), (x) => x); + if (length(keepf) == length(builds.PKGS)) + upd.keep('amneziawg', out.from, keepf, kept, fw.postfix); + } + else + ctx.log('Warning: the installed build is no longer published, nothing to keep for rollback'); + } + ctx.phase('Refreshing package lists'); + pkg.refresh(ctx.log); + ctx.phase(`Installing the ${src.label} build`); + if (!pkg.install_files(files, true, ctx.log)) + die('Package installation failed'); + if (!want_ru && pkg.version(builds.RU)) + pkg.remove([ builds.RU ], ctx.log); + out.after = builds.installed(); + settle(ctx, before, out.after); + return out; +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_pkgs.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_pkgs.uc new file mode 100644 index 0000000..dc4253d --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_pkgs.uc @@ -0,0 +1,92 @@ +// Dawnline updater: the OpenWrt packages Dawnline adds — the home-like link +// (ip-full, kmod-veth) and HTTPS plus certificates for the personal portal — +// checked against and updated from the OpenWrt feeds. +// ctx is the updater's job context (see usr/libexec/dawnline/updater). + +import * as pkg from 'dawnline.pkg'; + +/** What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the stock system). */ +export const NAMES = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme' ]; + +// Packages released together with each of the above, updated as a set so OpenSSL never ends up +// half old and half new. +const FAMILY = [ + [ /^ip-full$/, /^ip-/ ], + [ /^(libustream-openssl|openssl-util)$/, /^(libustream-openssl|libopenssl|openssl-util$)/ ], + [ /^(acme|luci-app-acme$)/, /^acme/ ], +]; + +function family(p) { + for (let f in FAMILY) + if (match(p, f[0])) + return f[1]; + return null; +} + +/** The packages to update for these names: each one plus its upgradable family. */ +function with_family(names, up) { + let set = {}; + for (let n in names) { + if (up[n]) + set[n] = true; + let f = family(n); + if (f) + for (let u in keys(up)) + if (match(u, f)) + set[u] = true; + } + return sort(keys(set)); +} + +/** refresh: update the package lists first (a check by hand or on schedule). */ +export function check(ctx, refresh) { + if (refresh ?? true) { + ctx.phase('Refreshing package lists'); + pkg.refresh(); + } + let up = pkg.upgradable(); + let res = {}, all = {}; + for (let p in NAMES) { + let v = pkg.version(p); + let set = v ? with_family([ p ], up) : []; + res[p] = { installed: v, latest: v && up[p] ? up[p] : null, with: filter(set, (x) => x != p) }; + for (let x in set) + all[x] = true; + } + let n = length(keys(all)); + ctx.log(n ? `${n} package update${n == 1 ? '' : 's'} in the feeds: ${join(', ', sort(keys(all)))}` : 'System packages are up to date'); + return { pkgs: res, updates: n, status: n ? 'outdated' : 'latest' }; +}; + +/** arg: name,name,… (only names Dawnline manages): missing ones are installed, present ones updated with their family. */ +export function install(ctx, arg) { + let names = filter(split(arg ?? '', ','), (x) => x != ''); + for (let n in names) + if (index(NAMES, n) < 0) + die(`${n} is not a package Dawnline manages`); + if (!length(names)) + die('Nothing to install'); + ctx.phase('Refreshing package lists'); + pkg.refresh(ctx.log); + let missing = filter(names, (n) => pkg.version(n) == null); + let have = with_family(filter(names, (n) => pkg.version(n) != null), pkg.upgradable()); + if (length(have)) { + ctx.phase(`Updating ${join(', ', have)}`); + if (!pkg.upgrade(have, ctx.log)) + die('Update failed'); + } + if (length(missing)) { + ctx.phase(`Installing ${join(', ', missing)}`); + if (!pkg.add(missing, ctx.log)) + die('Installation failed'); + } + // The portal's HTTPS runs in uhttpd; a piece that just arrived lets the portal or the home-like link start. + let touched = [ ...missing, ...have ]; + if (length(filter(missing, (n) => match(n, /^(openssl-util|libustream|ip-full|kmod-veth)/)))) { + ctx.after('apply'); + ctx.after('uhttpd'); + } + else if (length(filter(touched, (n) => match(n, /^(libustream|libopenssl)/)))) + ctx.after('uhttpd'); + return { updated: have, installed: missing, check: check(ctx, false) }; +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/updates.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/updates.uc new file mode 100644 index 0000000..36a62ad --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/updates.uc @@ -0,0 +1,228 @@ +// Dawnline — what the Components tab, the updater and the agent share: the +// update policy (Settings → Updates), when an automatic run is due, the one +// update job at a time (a kernel lock), the history for Activity, and the +// versions kept for rollback. GitHub and the package manager live in +// dawnline.github and dawnline.pkg. + +import { open, stat } from 'fs'; +import { q, read_json, write_json, ensure_dir, RUN_DIR, DATA_DIR } from 'dawnline.util'; + +export const JOB_FILE = `${RUN_DIR}/update-job.json`; +export const CHECK_FILE = `${RUN_DIR}/update-check.json`; +/** Held (flock) by the updater for the whole job: busy() and stale jobs come from it, not from pids. */ +export const LOCK_FILE = `${RUN_DIR}/update.lock`; +/** Automatic runs: when the last check and the last scheduled install happened. */ +export const AUTO_FILE = `${DATA_DIR}/update-auto.json`; +/** What happened: updates (by hand or automatic), failures, checks that found something. */ +export const HISTORY_FILE = `${DATA_DIR}/update-history.json`; +/** The version each component had before its last update (Keep the previous version). */ +export const KEEP_DIR = `${DATA_DIR}/keep`; + +export const INTERVALS = { '6h': 6 * 3600, '12h': 12 * 3600, '1d': 86400, '7d': 7 * 86400 }; +export const TARGETS = [ 'app', 'amneziawg', 'packages' ]; + +function on(v, dflt) { + if (v == null || v == '') + return dflt; + return v == '1' || v == 'true' || v == 'on' || v == 'yes'; +} + +/** The update policy from raw UCI settings (core.load puts it in m.settings.updates). */ +export function policy(s) { + s ??= {}; + let t = type(s.update_targets) == 'array' ? s.update_targets : s.update_targets ? [ s.update_targets ] : null; + let time_ok = match(s.update_time ?? '', /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/); + return { + check: on(s.update_check, true), + interval: INTERVALS[s.update_interval] ? s.update_interval : '1d', + auto: on(s.update_auto, true), + mode: s.update_mode == 'immediate' ? 'immediate' : 'scheduled', + time: time_ok ? s.update_time : '04:00', + // AmneziaWG is left out by default: a new kernel module restarts every tunnel. + targets: t ? filter(t, (x) => index(TARGETS, x) >= 0) : [ 'app', 'packages' ], + keep: on(s.update_keep, false), + mirrors: on(s.update_mirrors, true), + }; +}; + +/* ---------- schedule ---------- */ + +/** The scheduled time on the day of `ts` (router local time), in seconds since the epoch. */ +function scheduled_on(pol, ts) { + let t = localtime(ts); + let hm = split(pol.time, ':'); + return ts - (t.hour * 3600 + t.min * 60 + t.sec) + int(hm[0]) * 3600 + int(hm[1]) * 60; +} + +function day_of(ts) { + let t = localtime(ts); + return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday); +} + +/** The scheduled slot `now` is in (up to an hour after the set time, also across midnight), or null. */ +function slot(pol, now) { + for (let at in [ scheduled_on(pol, now), scheduled_on(pol, now - 86400) ]) + if (now >= at && now - at < 3600) + return at; + return null; +} + +/** + * What an automatic run should do now: 'install' (the scheduled window, at + * most an hour after the set time, once per slot), 'check' (the interval has + * passed), or null. + */ +export function due(pol, st, now) { + now ??= time(); + st ??= {}; + if (pol.auto && pol.mode == 'scheduled' && length(pol.targets)) { + let at = slot(pol, now); + if (at != null && st.install_day != day_of(at)) + return 'install'; + } + if (pol.check && now - (st.check ?? 0) >= INTERVALS[pol.interval]) + return 'check'; + return null; +}; + +export function auto_state() { + return read_json(AUTO_FILE, {}); +}; + +export function auto_save(st) { + ensure_dir(DATA_DIR); + write_json(AUTO_FILE, st, 0o600); +}; + +/** Record that the scheduled slot `now` is in has run (the slot's own day, not today's after midnight). */ +export function mark_day(pol, st, now) { + now ??= time(); + st.install_day = day_of(slot(pol, now) ?? now); + return st; +}; + +/* ---------- one job at a time ---------- */ + +/** + * Take the update lock without waiting: the open file (keep it for the whole + * job; the kernel releases it when the process ends), or null when another + * job holds it. + */ +export function try_lock() { + ensure_dir(RUN_DIR); + let f = open(LOCK_FILE, 'a'); + if (f && f.lock('xn')) + return f; + f?.close(); + return null; +}; + +/** A job is running: someone holds the update lock. */ +export function busy() { + let f = try_lock(); + if (!f) + return true; + f.close(); + return false; +}; + +/** The last job; a "running" one whose worker is gone (the lock is free) reads as failed. */ +export function job() { + let j = read_json(JOB_FILE, null); + if (j?.state == 'running' && !busy()) { + j.state = 'failed'; + j.error = 'The update stopped unexpectedly.'; + j.finished = j.finished ?? time(); + } + return j; +}; + +/* ---------- history (Components → Activity) ---------- */ + +export function history() { + let h = read_json(HISTORY_FILE, []); + return type(h) == 'array' ? h : []; +}; + +/** Newest first, the last 30 kept on flash. */ +export function history_add(e) { + let h = history(); + unshift(h, { ts: time(), ...e }); + ensure_dir(DATA_DIR); + write_json(HISTORY_FILE, slice(h, 0, 30), 0o600); +}; + +/* ---------- Dawnline versions ---------- */ + +/** + * Compare Dawnline release versions (0.3.2, v0.4.0-rc1): -1, 0 or 1. Numbers + * compare as numbers; a pre-release (-rc1, -beta) comes before its release. + */ +export function version_cmp(a, b) { + let parse = (v) => { + let m = match(replace(`${v}`, /^v/, ''), /^([0-9.]+)([-~]([0-9A-Za-z.]+))?/); + return m ? { nums: map(split(m[1], '.'), (x) => int(x)), pre: m[3] } : { nums: [ 0 ], pre: `${v}` }; + }; + let x = parse(a), y = parse(b); + for (let i = 0; i < length(x.nums) || i < length(y.nums); i++) { + let p = x.nums[i] ?? 0, r = y.nums[i] ?? 0; + if (p != r) + return p < r ? -1 : 1; + } + if (x.pre == y.pre) + return 0; + if (x.pre == null) + return 1; + if (y.pre == null) + return -1; + // rc1 < rc2 < rc10: compare the number runs as numbers. + let px = match(x.pre, /^([^0-9]*)([0-9]*)/), py = match(y.pre, /^([^0-9]*)([0-9]*)/); + if (px[1] != py[1]) + return px[1] < py[1] ? -1 : 1; + return int(px[2] || 0) < int(py[2] || 0) ? -1 : int(px[2] || 0) > int(py[2] || 0) ? 1 : 0; +}; + +/* ---------- kept previous versions ---------- */ + +/** { version, build?, firmware?, files: [paths], saved } of the kept version, or null. */ +export function kept(component) { + let k = read_json(`${KEEP_DIR}/${component}/meta.json`, null); + if (!k?.version || !length(k.files ?? [])) + return null; + for (let f in k.files) + if (!stat(f)) + return null; + return k; +}; + +/** What the Components tab shows; firmware: the current one (a kept AmneziaWG build is for one firmware only). */ +export function kept_all(firmware) { + let out = {}; + for (let c in [ 'app', 'amneziawg' ]) { + let k = kept(c); + if (k && c == 'amneziawg' && k.firmware && firmware && k.firmware != firmware) + k = null; + out[c] = k ? { version: k.version, build: k.build ?? null, saved: k.saved ?? null } : null; + } + return out; +}; + +/** Replace the kept version of a component with these files (copied in). */ +export function keep(component, version, files, build, firmware) { + let dir = `${KEEP_DIR}/${component}`; + system(`rm -rf ${q(dir)}; mkdir -p ${q(dir)}; chmod 700 ${q(KEEP_DIR)} ${q(dir)}`); + let saved = []; + for (let f in files) { + let to = `${dir}/${replace(f, /^.*\//, '')}`; + if (system(`cp ${q(f)} ${q(to)}`) == 0) + push(saved, to); + } + if (length(saved) == length(files)) + write_json(`${dir}/meta.json`, { version, build, firmware, files: saved, saved: time() }, 0o600); + else + system(`rm -rf ${q(dir)}`); +}; + +export function forget(component) { + system(`rm -rf ${q(KEEP_DIR + '/' + component)}`); +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc index dc331af..4aab999 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc @@ -1,9 +1,10 @@ // Dawnline — small helpers shared by the rpcd plugin, the CLI, the agent and -// the portal CGI. Nothing in here touches configuration. +// the portal CGI. Nothing in here loads or commits configuration (the uci +// helpers work on a cursor the caller owns). import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs'; -export const VERSION = '0.3.1'; +export const VERSION = '0.4.0'; /** GitHub repository with Dawnline releases (updates and the installer). */ export const REPO = 'tickcount/luci-app-dawnline'; export const RUN_DIR = '/var/run/dawnline'; @@ -91,15 +92,27 @@ export function read_json(path, fallback) { } }; -/** Atomic write (temp file + rename). `mode` defaults to 0600. */ +/** + * Atomic write (temp file + rename). `mode` defaults to 0600. A short write + * (flash full) leaves the old file in place and returns false. + */ export function write_file(path, data, mode) { let tmp = `${path}.tmp${rand_hex(3)}`; let f = open(tmp, 'w', mode ?? 0o600); if (!f) return false; - f.write(data); - f.close(); - return rename(tmp, path); + data = `${data ?? ''}`; + let n = length(data) ? f.write(data) : 0; + let closed = f.close(); + if (n != length(data) || !closed) { + unlink(tmp); + return false; + } + if (!rename(tmp, path)) { + unlink(tmp); + return false; + } + return true; }; export function write_json(path, data, mode) { @@ -126,6 +139,92 @@ export function unlock(f) { } }; +// Locks this process holds through with_lock (flock does not nest: a second +// open of the same lock file in one process would wait for itself). +let held = {}; + +/** + * Run fn() holding the named lock and return what it returns. Nested calls + * for the same name in one process run fn() directly. Anything fn throws + * releases the lock and is rethrown with the same message. + */ +export function with_lock(name, fn) { + if (held[name]) + return fn(); + let l = lock(name); + held[name] = true; + try { + let r = fn(); + delete held[name]; + unlock(l); + return r; + } + catch (e) { + delete held[name]; + unlock(l); + die(e.message ?? `${e}`); + } +}; + +/* ---------- uci (on the caller's cursor) ---------- */ + +/** Set an option only when it differs (null, '' or [] delete it); true if something changed. */ +export function uci_put(c, conf, sec, opt, val) { + let cur = c.get(conf, sec, opt); + if (val == null || val == '' || (type(val) == 'array' && !length(val))) { + if (cur != null) { + c.delete(conf, sec, opt); + return true; + } + return false; + } + if (type(val) == 'array') { + if (type(cur) == 'array' && join('\n', cur) == join('\n', val)) + return false; + } + else if (cur == `${val}`) + return false; + c.set(conf, sec, opt, type(val) == 'array' ? val : `${val}`); + return true; +}; + +/** Make `sec` a section of type `stype` (recreated when its type differs); true if it changed. */ +export function uci_section(c, conf, sec, stype) { + if (c.get(conf, sec) == stype) + return false; + if (c.get(conf, sec) != null) + c.delete(conf, sec); + c.set(conf, sec, stype); + return true; +}; + +/** + * After committing a config ourselves (and applying it), record its new + * checksum so a later `reload_config` does not treat it as changed and + * restart unrelated services that reload on any network change. + */ +export function ack_config(confs) { + let md5f = '/var/run/config.md5'; + if (!stat(md5f)) + return; + let lines = split(trim(readfile(md5f) ?? ''), '\n'); + for (let conf in confs) { + let path = `/var/run/config.check/${conf}`; + let sum = sh_out(`uci show ${q(conf)} | md5sum | cut -d' ' -f1`); + if (!sum) + continue; + let found = false; + for (let i = 0; i < length(lines); i++) + if (substr(lines[i], -length(path) - 2) == ` ${path}`) { + lines[i] = `${sum} ${path}`; + found = true; + } + if (!found) + push(lines, `${sum} ${path}`); + } + writefile(md5f, join('\n', lines) + '\n'); +}; + /* ---------- service log ---------- */ /* @@ -271,6 +370,35 @@ export function int2ip(n) { return sprintf('%d.%d.%d.%d', (n >> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255); }; +/** + * "a.b.c.d[/len]" with any prefix 0-32 (a bare address is a /32) → + * { net, prefix, size, ip }; null for anything else. Routes, rules and + * allowed networks use this; parse_cidr is the stricter one for subnets. + */ +export function cidr_any(s) { + let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/); + if (!m) + return null; + let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32; + if (ip == null || prefix > 32) + return null; + let size = 1 << (32 - prefix); + return { net: ip - ip % size, prefix, size, ip }; +}; + +/** The first of `nets` (CIDR strings, any prefix) that holds `ip` (a string or an int), or null. */ +export function in_nets(ip, nets) { + let n = type(ip) == 'int' ? ip : ip2int(ip); + if (n == null) + return null; + for (let s in nets) { + let c = cidr_any(s); + if (c && n >= c.net && n < c.net + c.size) + return s; + } + return null; +}; + // Cloudflare's published ranges (https://www.cloudflare.com/ips/). const CF_V4 = [ '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', @@ -286,13 +414,7 @@ export function cloudflare_ip(a) { return true; return false; } - for (let c in CF_V4) { - let m = match(c, /^([0-9.]+)\/([0-9]+)$/); - let size = 1 << (32 - +m[2]), net = ip2int(m[1]); - if (n >= net && n < net + size) - return true; - } - return false; + return in_nets(n, CF_V4) != null; }; /** Parse "a.b.c.d/len" → { net, prefix, first, last, size } (net is the masked base). */ @@ -378,6 +500,16 @@ export function day_key(ts) { return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday); }; +/** + * The day key `days` days before `ts` (default now). Counted from local noon, + * so a 23- or 25-hour day around a DST change neither skips nor repeats a day. + */ +export function day_key_ago(days, ts) { + let t = localtime(ts ?? time()); + let noon = timelocal({ year: t.year, mon: t.mon, mday: t.mday, hour: 12, min: 0, sec: 0 }); + return day_key(noon - (days ?? 0) * 86400); +}; + export function uniq(arr) { let seen = {}, out = []; for (let v in arr) @@ -399,3 +531,18 @@ export function remove(path) { export function now() { return time(); }; + +/** netifd's view of an interface (ubus network.interface. status), or null. */ +export function iface_status(ifname) { + if (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/)) + return null; + let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`); + if (!s) + return null; + try { + return json(s); + } + catch (e) { + return null; + } +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/view.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/view.uc index 756c705..d95cc6d 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/view.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/view.uc @@ -3,22 +3,24 @@ import * as core from 'dawnline.core'; import * as live from 'dawnline.live'; -import { day_key, month_key } from 'dawnline.util'; +import * as awg from 'dawnline.awg'; +import { day_key_ago, month_key } from 'dawnline.util'; /** Daily totals (rx+tx) for the last `n` days, oldest first. */ export function spark(rec, n) { - let out = [], ts = time(); + let out = []; for (let i = n - 1; i >= 0; i--) { - let v = rec?.days?.[day_key(ts - i * 86400)]; + let v = rec?.days?.[day_key_ago(i)]; push(out, v ? v[0] + v[1] : 0); } return out; }; +/** The device holds an older configuration than the one it would get now. */ function config_stale(m, d) { - m._issued ??= core.issued(); + m._issued ??= awg.issued(); let was = m._issued[d.id]; - return was != null && was != core.config_fingerprint(m, d); + return was != null && was != awg.config_fingerprint(m, d); } export function device_view(m, d, usage, dmp) { @@ -27,7 +29,7 @@ export function device_view(m, d, usage, dmp) { let ts = time(); let hs = peer?.handshake || u?.handshake || 0; let p = m.people[d.person]; - return { + let v = { id: d.id, name: d.name, kind: d.kind, @@ -47,6 +49,7 @@ export function device_view(m, d, usage, dmp) { // Its configuration changed since it was last shown or downloaded. config_stale: config_stale(m, d), }; + return v; }; export function person_view(m, p, usage, dmp, states, opts) { @@ -85,9 +88,9 @@ export function person_view(m, p, usage, dmp, states, opts) { if (d.handshake > v.last_seen) v.last_seen = d.handshake; if (opts.admin) { - v.code = p.code; - v.link = core.portal_url(m, p); - v.links = core.portal_urls(m, p); + // The code and links themselves are person_links' (admins only): the + // code opens the person's portal and their devices' configurations. + v.has_link = core.portal_url(m, p) != null; v.note = p.note; v.services = p.services; v.home_nets = p.home_nets; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc index 17b5f87..ed69f80 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc @@ -6,11 +6,12 @@ import { stat } from 'fs'; import { sh_out, q, read_json, write_json, slog, slog_read, RUN_DIR } from 'dawnline.util'; -import * as core from 'dawnline.core'; -import * as live from 'dawnline.live'; import * as apply from 'dawnline.apply'; import * as loop from 'dawnline.loop'; -import * as ops from 'dawnline.ops'; +import * as health from 'dawnline.health'; +import * as awg from 'dawnline.awg'; +import * as nft from 'dawnline.nft'; +import * as netifd from 'dawnline.netifd'; export const STATE = `${RUN_DIR}/watchdog.json`; /** The agent writes the time here on every tick. */ @@ -18,13 +19,9 @@ export const BEAT = `${RUN_DIR}/agent.beat`; // Seconds before the next repair, by the number of repairs so far. const WAIT = [ 0, 120, 600, 1800, 3600 ]; -/** Why a tunnel is down, from netifd and the last related syslog lines. */ +/** Why a tunnel is down (AmneziaWG; kept here for older callers). */ export function iface_errors(ifname) { - let s = live.iface_status(ifname); - let errs = map(s?.errors ?? [], (e) => e.code + (length(e.data ?? []) ? ` (${join(' ', e.data)})` : '')); - // Only what explains a failure, not the ordinary "is now up/down" lines. - let lines = sh_out(`logread -l 400 2>/dev/null | grep -E ${q(`${ifname}|amneziawg`)} | grep -iE 'error|fail|invalid|unrecogni|cannot|unable|not found|refused|denied' | tail -n 6`); - return join('\n', filter([ length(errs) ? `netifd: ${join(', ', errs)}` : null, lines ], (x) => x)); + return awg.iface_errors(ifname); }; function restart_services() { @@ -38,30 +35,11 @@ function restart_services() { */ function probes(m) { let out = []; - // The kernel module first: without it no tunnel can run (they come back on the next pass). - if (length(filter(values(m.servers), (x) => x.enabled && x.private_key)) && stat('/usr/bin/awg')) - push(out, { - id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', ok: stat('/sys/module/amneziawg') != null, - problem: "kernel module isn't loaded", back: 'kernel module is loaded again', - detail: () => sh_out("modprobe amneziawg 2>&1; dmesg 2>/dev/null | grep -i amneziawg | grep -iE 'error|fail|invalid|unknown|disagrees|taint' | tail -n 4"), - repair: { what: 'loading it', run: () => system('modprobe amneziawg >/dev/null 2>&1') }, - }); - for (let id, srv in m.servers) { - if (!srv.enabled || !srv.private_key) - continue; - let s = live.iface_status(srv.ifname); - let up = !!s?.up; - push(out, { - id: `up_${id}`, src: 'awg', name: srv.name, who: srv.name, ok: up && ops.udp_listening(srv.port), - problem: !s ? 'is missing from the router' : !up ? "isn't running" : `isn't accepting connections on port ${srv.port}`, - back: `is running again · accepting connections on port ${srv.port}`, - detail: () => iface_errors(srv.ifname), - repair: s ? { what: 'restarting it', run: () => system(`ifup ${q(srv.ifname)}`) } : { what: 'setting it up again', run: () => apply.apply() }, - }); - } + // The tunnels check themselves: AmneziaWG (packages, kernel module, netifd) and each server's interface. + push(out, ...awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) })); if (length(m.servers)) push(out, { - id: 'nft', src: 'dawnline', name: 'Access rules', who: 'Access rules', ok: system('nft list table inet dawnline >/dev/null 2>&1') == 0, + id: 'nft', src: 'dawnline', name: 'Access rules', who: 'Access rules', ok: nft.present(), problem: 'are missing', back: 'are loaded again', repair: { what: 'loading them again', run: () => apply.apply() }, }); @@ -79,15 +57,9 @@ function probes(m) { } let s = m.settings; - if (s.portal_enabled && core.portal_public_port(m) == 443 && s.portal_port != 443) + if (s.portal_enabled && !length(health.needs().https) && !length(health.tcp_port_owners(s.portal_port))) push(out, { - id: 'portal_lan', src: 'portal', name: 'Portal at home', who: 'Personal portal', ok: !apply.uhttpd_drift(m), - problem: "links don't open at home (LuCI's web server lost the setting)", back: 'links open at home again', - repair: { what: 'restoring it', run: () => apply.apply() }, - }); - if (s.portal_enabled && !length(ops.needs().https) && !length(ops.tcp_port_owners(s.portal_port))) - push(out, { - id: 'portal', src: 'portal', name: 'Portal', who: 'Personal portal', ok: ops.tcp_listening(s.portal_port), + id: 'portal', src: 'portal', name: 'Portal', who: 'Personal portal', ok: health.tcp_listening(s.portal_port), problem: `isn't answering on port ${s.portal_port}`, back: 'answers again', detail: () => sh_out("logread -l 400 2>/dev/null | grep 'uhttpd' | grep -iE 'error|fail|cert|key|bind|address' | tail -n 4"), repair: { what: 'restarting it', run: restart_services }, diff --git a/scripts/check-ucode.sh b/scripts/check-ucode.sh index 132838f..9fc3a24 100755 --- a/scripts/check-ucode.sh +++ b/scripts/check-ucode.sh @@ -16,9 +16,11 @@ ssh "$HOST" sh <<'REMOTE' rm -rf /tmp/dlc && mkdir -p /tmp/dlc && tar -xzf /tmp/dl-check.tgz -C /tmp/dlc && rm /tmp/dl-check.tgz cd /tmp/dlc rc=0 -for f in usr/share/ucode/dawnline/*.uc; do - n=$(basename "$f" .uc) - out=$(ucode -L '/tmp/dlc/usr/share/ucode/*.uc' -e "import * as x from 'dawnline.$n';" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; } +# Modules by their import name: dawnline/x.uc is dawnline.x, dawnline/rpc/x.uc dawnline.rpc.x. +for f in usr/share/ucode/dawnline/*.uc usr/share/ucode/dawnline/rpc/*.uc; do + [ -f "$f" ] || continue + n=$(echo "${f#usr/share/ucode/}" | sed 's/\.uc$//; s#/#.#g') + out=$(ucode -L '/tmp/dlc/usr/share/ucode/*.uc' -e "import * as x from '$n';" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; } done for f in usr/share/rpcd/ucode/luci.dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/bin/dawnline usr/share/dawnline/portal/www/cgi-bin/portal; do [ -f "$f" ] || continue diff --git a/scripts/lint-ucode.py b/scripts/lint-ucode.py index dfbc103..a9e61db 100755 --- a/scripts/lint-ucode.py +++ b/scripts/lint-ucode.py @@ -3,35 +3,56 @@ ucode resolves names where they are used: calling a function that is declared further down the same file fails at runtime ("access to undeclared variable"). +Also: calls and named imports must match what a Dawnline module exports, and +the rpcd methods (dawnline.rpc.*) must match the plugin and its ACL. Run: scripts/lint-ucode.py [package root] """ import glob +import json import os import re import sys root = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), '..', 'package', 'luci-app-dawnline', 'root') -files = glob.glob(f"{root}/usr/share/ucode/dawnline/*.uc") + [ - f"{root}/usr/share/rpcd/ucode/luci.dawnline", +MODDIR = f"{root}/usr/share/ucode/dawnline" +PLUGIN = f"{root}/usr/share/rpcd/ucode/luci.dawnline" +ACL = f"{root}/usr/share/rpcd/acl.d/luci-app-dawnline.json" +modules = sorted(glob.glob(f"{MODDIR}/*.uc") + glob.glob(f"{MODDIR}/rpc/*.uc")) +files = modules + [ + PLUGIN, f"{root}/usr/libexec/dawnline/agent", f"{root}/usr/libexec/dawnline/updater", f"{root}/usr/libexec/dawnline/resolver", f"{root}/usr/bin/dawnline", f"{root}/usr/share/dawnline/portal/www/cgi-bin/portal", ] +files = [f for f in files if os.path.exists(f)] bad = 0 -checked = 0 + + +def problem(msg): + global bad + print(msg) + bad = 1 + + +def strip_comments(text): + return re.sub(r'//[^\n]*|/\*.*?\*/', '', text, flags=re.S) + + +def modname(path): + """dawnline/rpc/people.uc → 'rpc.people' (as in import … from 'dawnline.rpc.people').""" + rel = os.path.relpath(path, MODDIR)[:-3] + return rel.replace(os.sep, '.') + + for f in files: - if not os.path.exists(f): - continue - checked += 1 - code = re.sub(r'//[^\n]*|/\*.*?\*/', '', open(f, encoding='utf-8').read(), flags=re.S) + code = strip_comments(open(f, encoding='utf-8').read()) defs = {m.group(1): m.start() for m in re.finditer(r'^(?:export )?function (\w+)\(', code, re.M)} for name, pos in defs.items(): for m in re.finditer(r'(? [owner/repo]}" +REPO="${2:-tickcount/luci-app-dawnline}" + +git rev-parse -q --verify "$TAG^{commit}" >/dev/null || { + echo "release-notes: no tag $TAG" >&2 + exit 1 +} +# The previous release: the nearest older tag, or PREV_TAG when a tag was never published. +PREV="${PREV_TAG:-$(git describe --tags --abbrev=0 --match 'v[0-9]*' "$TAG^" 2>/dev/null || true)}" +if [ -n "$PREV" ] && ! git rev-parse -q --verify "$PREV^{commit}" >/dev/null; then + echo "release-notes: no tag $PREV" >&2 + exit 1 +fi +RANGE="$TAG" +[ -n "$PREV" ] && RANGE="$PREV..$TAG" +# git log runs alone first: a failure must stop the script, not vanish into the pipe. +git log --no-merges --format='%s' "$RANGE" >/dev/null + +# One record per commit, newest first: the subject, then the body; records end with RS (\036). +points="$(git log --no-merges --format='%s%n%b%x1e' "$RANGE" | awk ' + BEGIN { RS = "\036" } + { + n = split($0, line, "\n") + title = "" + for (i = 1; i <= n; i++) if (line[i] != "") { title = line[i]; start = i + 1; break } + if (title == "") next + got = 0; cur = "" + for (i = start; i <= n; i++) { + if (line[i] ~ /^[ \t]*[-*][ \t]+/) { + if (cur != "") { print "- " cur; got = 1 } + cur = line[i]; sub(/^[ \t]*[-*][ \t]+/, "", cur) + } else if (cur != "" && line[i] ~ /^[ \t]+[^ \t]/) { + l = line[i]; sub(/^[ \t]+/, "", l); cur = cur " " l + } else if (cur != "") { print "- " cur; got = 1; cur = "" } + } + if (cur != "") { print "- " cur; got = 1 } + # A release commit without a list says nothing new; any other commit is its title. + if (!got && title !~ /^(Dawnline )?v?[0-9]+\.[0-9]+(\.[0-9]+)?$/) print "- " title + }')" + +if [ -n "$points" ]; then + printf "## What’s new\n\n%s\n\n" "$points" +fi +cat </dev/null && [ "${TERM:-dumb}" != "dumb" ]; then + C_RESET="${ESC}[0m" + C_BOLD="${ESC}[1m" + C_RED="${ESC}[31;1m" + C_GREEN="${ESC}[32;1m" + C_YELLOW="${ESC}[33;1m" + C_CYAN="${ESC}[36;1m" +else + C_RESET="" + C_BOLD="" + C_RED="" + C_GREEN="" + C_YELLOW="" + C_CYAN="" +fi + +START_TS="$(date +%s 2>/dev/null || echo 0)" + +# ---------- output ---------- + +ts_elapsed() { + _now="$(date +%s 2>/dev/null || echo "$START_TS")" + _el=$((_now - START_TS)) + [ "$_el" -ge 0 ] 2>/dev/null || _el=0 + printf '+%02d:%02d' $((_el / 60)) $((_el % 60)) +} + +log_line() { + [ "$LOG_READY" -eq 1 ] || return 0 + printf '[%s %s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S' 2>/dev/null)" "$(ts_elapsed)" "$1" >>"$LOG_FILE" 2>/dev/null || true +} + +msg() { + log_line "INFO $1" + printf ' [%s] %s%s%s\n' "$(ts_elapsed)" "$C_CYAN" "$1" "$C_RESET" +} + +ok() { + log_line "OK $1" + printf ' [%s] %s%s✓%s %s\n' "$(ts_elapsed)" "$C_GREEN" "$C_BOLD" "$C_RESET" "$1" +} + +warn() { + log_line "WARN $1" + printf ' [%s] %s%s⚠%s %s\n' "$(ts_elapsed)" "$C_YELLOW" "$C_BOLD" "$C_RESET" "$1" >&2 +} + +err() { + log_line "ERROR $1" + printf ' [%s] %s%s✗%s %s\n' "$(ts_elapsed)" "$C_RED" "$C_BOLD" "$C_RESET" "$1" >&2 +} + +debug() { + log_line "DEBUG $1" + [ "$VERBOSE" -eq 1 ] || return 0 + printf ' [%s] [debug] %s\n' "$(ts_elapsed)" "$1" >&2 +} + +dry() { + msg "[dry-run] would $1" +} + +step() { + STEP=$((STEP + 1)) + log_line "STEP [$STEP/$STEPS] $1" + printf ' [%s] %s[%s/%s] %s%s\n' "$(ts_elapsed)" "$C_BOLD" "$STEP" "$STEPS" "$1" "$C_RESET" +} + +fail() { + err "$1" + [ "$LOG_READY" -eq 1 ] && err "Uninstaller log: $LOG_FILE" + exit 1 +} + +usage() { + cat </dev/null 2>&1; } + +acquire_lock() { + if mkdir "$LOCK_DIR" 2>/dev/null; then + echo "$$" >"$LOCK_DIR/pid" + LOCK_HELD=1 + return 0 + fi + _old="$(cat "$LOCK_DIR/pid" 2>/dev/null)" + if [ -n "$_old" ] && kill -0 "$_old" 2>/dev/null; then + err "Another Dawnline installer or uninstaller is running (pid $_old)" + return 1 + fi + warn "Removing a stale installer lock${_old:+ (pid $_old)}" + rm -rf "$LOCK_DIR" 2>/dev/null + mkdir "$LOCK_DIR" 2>/dev/null || { + err "Cannot create the lock $LOCK_DIR" + return 1 + } + echo "$$" >"$LOCK_DIR/pid" + LOCK_HELD=1 +} + +release_lock() { + [ "$LOCK_HELD" -eq 1 ] || return 0 + [ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$$" ] && rm -rf "$LOCK_DIR" 2>/dev/null + LOCK_HELD=0 +} + +_NL=' +' + +_stream_poll() { + _ssize="$(wc -c <"$_sf" 2>/dev/null | tr -d " ")" + case "$_ssize" in '' | *[!0-9]*) _ssize=0 ;; esac + [ "$_ssize" -gt "$_spos" ] || return 0 + _sbuf="$_sbuf$(tail -c +$((_spos + 1)) "$_sf" 2>/dev/null)$_NL" + _spos="$_ssize" + case "$(tail -c 1 "$_sf" 2>/dev/null)" in + '') ;; + *) _sbuf="${_sbuf%"$_NL"}" ;; + esac + while :; do + case "$_sbuf" in + *"$_NL"*) ;; + *) break ;; + esac + _sline="${_sbuf%%"$_NL"*}" + _sbuf="${_sbuf#*"$_NL"}" + [ -n "$_sline" ] && printf ' [%s] [%s] %s\n' "$(ts_elapsed)" "$_stag" "$_sline" + done + return 0 +} + +_stream_loop() { + _sf="$1" + _stag="$2" + _sstop="$3" + _sparent="$4" + _spos=0 + _sbuf="" + _sidle=0 + while :; do + [ -e "$_sstop" ] && break + kill -0 "$_sparent" 2>/dev/null || break + _spre="$_spos" + _stream_poll + if [ "$_spos" -eq "$_spre" ]; then + _sidle=$((_sidle + 1)) + [ $((_sidle % 10)) -eq 0 ] && printf ' [%s] [%s] … still running (%ss)\n' "$(ts_elapsed)" "$_stag" "$_sidle" + else + _sidle=0 + fi + sleep 1 + done + _stream_poll + [ -n "$_sbuf" ] && printf ' [%s] [%s] %s\n' "$(ts_elapsed)" "$_stag" "$_sbuf" + return 0 +} + +stream_stop() { + [ -n "$_STREAM_PID" ] || return 0 + : >"$_STREAM_STOP" 2>/dev/null + wait "$_STREAM_PID" 2>/dev/null + _STREAM_PID="" + rm -f "$_STREAM_STOP" 2>/dev/null + return 0 +} + +# run_logged TAG COMMAND...: foreground, output streamed and kept in the log. +run_logged() { + _tag="$1" + shift + _out="$TMP_DIR/cmd.$$.out" + log_line "EXEC [$_tag] $*" + : >"$_out" + _STREAM_STOP="$_out.stop" + rm -f "$_STREAM_STOP" + _stream_loop "$_out" "$_tag" "$_STREAM_STOP" "$$" & + _STREAM_PID=$! + "$@" >"$_out" 2>&1 /dev/null + rm -f "$_out" + return "$_rc" +} + +# act DESCRIPTION TAG COMMAND...: run, or only say it in a dry run. +act() { + _desc="$1" + shift + if [ "$DRY_RUN" -eq 1 ]; then + dry "$_desc" + return 0 + fi + debug "$_desc" + run_logged "$@" +} + +# ---------- packages ---------- + +detect_package_manager() { + if command_exists apk; then + PKG_MANAGER="apk" + PKG_IS_APK=1 + elif command_exists opkg; then + PKG_MANAGER="opkg" + PKG_IS_APK=0 + else + err "Neither apk nor opkg is available" + return 1 + fi +} + +pkg_is_installed() { + if [ "$PKG_IS_APK" -eq 1 ]; then + apk info -e "$1" >/dev/null 2>&1 + else + opkg status "$1" 2>/dev/null | grep -q '^Status: .* installed' + fi +} + +installed_dawnline_pkgs() { + _l="" + pkg_is_installed "$PKG_NAME" && _l="$PKG_NAME" + if [ "$PKG_IS_APK" -eq 1 ]; then + _i18n="$(apk info 2>/dev/null | grep '^luci-i18n-dawnline-')" + else + _i18n="$(opkg list-installed 'luci-i18n-dawnline-*' 2>/dev/null | awk '{ print $1 }')" + fi + # Translations first: they depend on the app. + for _p in $_i18n; do _l="$_p $_l"; done + printf '%s' "$_l" +} + +pkg_remove() { + _tag="$1" + shift + if [ "$PKG_IS_APK" -eq 1 ]; then + act "apk del $*" "$_tag" apk del "$@" + else + _w=0 + while pidof opkg >/dev/null 2>&1 && [ "$_w" -lt 30 ]; do + _w=$((_w + 1)) + sleep 1 + done + act "opkg remove $*" "$_tag" opkg remove "$@" + fi +} + +# ---------- steps ---------- + +dawnline_present() { + pkg_is_installed "$PKG_NAME" || [ -e /usr/bin/dawnline ] || [ -e /etc/init.d/dawnline ] || + [ -e /etc/config/dawnline ] || [ -d "$DATA_DIR" ] +} + +confirm() { + [ "$ASSUME_YES" -eq 0 ] && [ "$DRY_RUN" -eq 0 ] && [ -t 0 ] || return 0 + printf ' This removes %sDawnline%s from the router: everyone is disconnected, and its\n' "$C_BOLD" "$C_RESET" + printf ' tunnels, firewall rules, portal and the %s package are removed.\n' "$PKG_NAME" + if [ "$PURGE" -eq 1 ]; then + printf ' %s--purge: the configuration, keys, history and every backup are deleted too.%s\n' "$C_RED" "$C_RESET" + printf ' %sThis cannot be undone.%s\n' "$C_RED" "$C_RESET" + else + printf ' A backup of the configuration is kept in %s.\n' "$BACKUP_DIR" + fi + if [ "$REMOVE_AWG" -eq 1 ]; then + printf ' AmneziaWG is removed too, unless another interface still uses it.\n' + else + printf ' AmneziaWG stays installed (other tunnels may use it; --remove-awg removes it).\n' + fi + printf '\n Remove Dawnline? [y/N] ' + read -r _answer || _answer="" + case "$_answer" in + y | Y | yes | Yes | YES) ;; + *) + msg "Cancelled: nothing was changed" + exit 0 + ;; + esac +} + +# An update (by hand or automatic) may be in the middle of opkg/apk: let it +# finish rather than tear the package out from under it. The updater holds +# UPDATE_LOCK for a whole job; once this script has it, no automatic update +# can start until the removal is over. +UPDATE_JOB=/var/run/dawnline/update-job.json +UPDATE_LOCK=/var/run/dawnline/update.lock +update_running() { + if command_exists flock && [ -e "$UPDATE_LOCK" ]; then + exec 8>>"$UPDATE_LOCK" + flock -n 8 && return 1 + return 0 + fi + [ -f "$UPDATE_JOB" ] || return 1 + grep -q '"state": *"running"' "$UPDATE_JOB" 2>/dev/null || return 1 + _pid="$(sed -n 's/.*"pid": *\([0-9][0-9]*\).*/\1/p' "$UPDATE_JOB" | head -n 1)" + [ -n "$_pid" ] && [ -d "/proc/$_pid" ] +} + +wait_for_update() { + update_running || return 0 + if [ "$DRY_RUN" -eq 1 ]; then + warn "An update is running: the removal would wait for it to finish" + return 0 + fi + msg "An update is running: waiting for it to finish (up to 5 min)" + _w=0 + while update_running; do + [ "$_w" -ge 300 ] && fail "The update is still running after 5 min. Nothing was removed; try again when it finishes" + sleep 5 + _w=$((_w + 5)) + [ $((_w % 30)) -eq 0 ] && msg "… still updating (${_w}s)" + done + ok "The update finished" +} + +do_backup() { + step "Backing up the configuration" + if [ "$PURGE" -eq 1 ]; then + warn "--purge: no backup is made" + return 0 + fi + if [ ! -f /etc/config/dawnline ]; then + ok "No /etc/config/dawnline: nothing to back up" + return 0 + fi + if [ "$DRY_RUN" -eq 1 ]; then + dry "save /etc/config/dawnline and Dawnline's data to $BACKUP_DIR" + return 0 + fi + _bn="" + if [ -x /usr/bin/dawnline ]; then + _bn="$(/usr/bin/dawnline backup --reason pre-remove 2>>"$LOG_FILE")" + [ -n "$_bn" ] && [ -f "$BACKUP_DIR/$_bn" ] || _bn="" + [ -n "$_bn" ] || warn "dawnline backup failed; saving the files directly" + fi + if [ -z "$_bn" ]; then + # The same archive format Dawnline makes, so Settings → Backups can restore it. + _bn="dawnline-$(date +%Y%m%d-%H%M%S)-pre-remove.tar.gz" + set -- etc/config/dawnline + for _f in usage.json events.json; do + [ -f "$DATA_DIR/$_f" ] && set -- "$@" "${DATA_DIR#/}/$_f" + done + mkdir -p "$BACKUP_DIR" && chmod 700 "$DATA_DIR" "$BACKUP_DIR" 2>/dev/null + tar -czf "$BACKUP_DIR/$_bn" -C / "$@" 2>>"$LOG_FILE" || { + rm -f "$BACKUP_DIR/$_bn" + fail "The backup failed and nothing was removed (--purge removes without a backup)" + } + fi + chmod 600 "$BACKUP_DIR/$_bn" 2>/dev/null + BACKUP_PATH="$BACKUP_DIR/$_bn" + ok "Backup: $BACKUP_PATH" +} + +do_teardown() { + step "Running Dawnline's own removal" + if ubus list luci.dawnline >/dev/null 2>&1; then + # The same call as Settings → Remove Dawnline from this router. + if act "call luci.dawnline uninstall (Settings → Remove Dawnline)" rpc \ + ubus -t 120 call luci.dawnline uninstall '{"confirm":"remove"}'; then + [ "$DRY_RUN" -eq 1 ] && return 0 + if grep -q '"ok": *true' "$TMP_DIR/last.out" 2>/dev/null; then + ok "Tunnels, firewall rules, portal and routing removed; service stopped" + return 0 + fi + fi + warn "luci.dawnline uninstall failed: $(sed -n 's/.*"error": *"\(.*\)".*/\1/p' "$TMP_DIR/last.out" 2>/dev/null | head -n 1)" + fi + if [ -x /usr/bin/dawnline ]; then + act "stop the Dawnline service" stop /etc/init.d/dawnline stop + if act "run 'dawnline teardown'" teardown /usr/bin/dawnline teardown; then + ok "dawnline teardown removed what Dawnline created" + else + warn "dawnline teardown failed: leftovers are cleaned in step 5" + fi + act "disable the Dawnline service" disable /etc/init.d/dawnline disable + return 0 + fi + if [ -x /etc/init.d/dawnline ]; then + act "stop and disable the Dawnline service" stop sh -c '/etc/init.d/dawnline stop; /etc/init.d/dawnline disable' + fi + warn "/usr/bin/dawnline is missing: leftovers are cleaned in step 5" +} + +do_remove_package() { + step "Removing the package" + _pkgs="$(installed_dawnline_pkgs)" + if [ -z "$_pkgs" ]; then + ok "$PKG_NAME is not installed" + return 0 + fi + # shellcheck disable=SC2086 + pkg_remove pkg $_pkgs + if [ "$DRY_RUN" -eq 0 ] && pkg_is_installed "$PKG_NAME"; then + err "$PKG_MANAGER could not remove $PKG_NAME (see $LOG_FILE)" + FAILED=1 + return 0 + fi + [ "$DRY_RUN" -eq 1 ] || ok "Removed: $_pkgs" +} + +do_awg() { + step "AmneziaWG" + _have="" + for _p in $AWG_PKGS; do + pkg_is_installed "$_p" && _have="$_have $_p" + done + _have="${_have# }" + if [ -z "$_have" ]; then + ok "AmneziaWG is not installed" + return 0 + fi + if [ "$REMOVE_AWG" -eq 0 ]; then + ok "AmneziaWG kept (other tunnels may use it; --remove-awg removes it)" + return 0 + fi + # AmneziaWG interfaces that are not Dawnline's (tagged _dawnline). + _users="" + for _i in $(uci -q show network 2>/dev/null | sed -n "s/^network\.\([^.]*\)\.proto='amneziawg'$/\1/p"); do + [ -n "$(uci -q get "network.$_i._dawnline")" ] || _users="$_users $_i" + done + if [ -n "$_users" ]; then + warn "AmneziaWG kept: still used by interface(s)$_users" + return 0 + fi + # shellcheck disable=SC2086 + pkg_remove awg $_have + if [ "$DRY_RUN" -eq 0 ]; then + if pkg_is_installed kmod-amneziawg || pkg_is_installed amneziawg-tools; then + warn "AmneziaWG could not be removed completely (see $LOG_FILE)" + else + ok "AmneziaWG removed" + fi + fi +} + +# Only objects Dawnline names as its own (see "What Dawnline changes" in the +# README); normally `dawnline teardown` has removed all of them already. +clean_network_leftovers() { + _ifs="$(uci -q show network 2>/dev/null | sed -n "s/^network\.\([^.]*\)\._dawnline=.*/\1/p")" + _fw="$(uci -q show firewall 2>/dev/null | sed -n 's/^firewall\.\(dawnline[A-Za-z0-9_]*\)=.*/\1/p')" + _found=0 + if [ -n "$_ifs" ]; then + _found=1 + for _i in $_ifs; do + if [ "$DRY_RUN" -eq 1 ]; then + dry "delete network interface $_i" + else + ifdown "$_i" >/dev/null 2>&1 + uci -q delete "network.$_i" + fi + done + [ "$DRY_RUN" -eq 1 ] || { + uci -q commit network + ubus call network reload >/dev/null 2>&1 + } + [ "$DRY_RUN" -eq 1 ] || ok "Removed leftover tunnel interfaces: $(echo "$_ifs" | tr '\n' ' ')" + fi + if [ -n "$_fw" ]; then + _found=1 + if [ "$DRY_RUN" -eq 1 ]; then + dry "delete firewall sections: $(echo "$_fw" | tr '\n' ' ')" + else + for _s in $_fw; do uci -q delete "firewall.$_s"; done + uci -q commit firewall + /etc/init.d/firewall reload >/dev/null 2>&1 + ok "Removed leftover firewall sections: $(echo "$_fw" | tr '\n' ' ')" + fi + fi + if command_exists nft && nft list table inet dawnline >/dev/null 2>&1; then + _found=1 + if [ "$DRY_RUN" -eq 1 ]; then + dry "delete the nft table inet dawnline" + else + nft delete table inet dawnline 2>/dev/null + ok "Removed the nft table inet dawnline" + fi + fi + if [ -e /var/run/netns/dawnline ] || ip link show dlx0 >/dev/null 2>&1 || ip link show dll0 >/dev/null 2>&1; then + _found=1 + if [ "$DRY_RUN" -eq 1 ]; then + dry "delete the dawnline network namespace and its veth links" + else + ip link del dlx0 >/dev/null 2>&1 + ip link del dll0 >/dev/null 2>&1 + ip netns del dawnline >/dev/null 2>&1 || rm -f /var/run/netns/dawnline + ok "Removed the dawnline network namespace (policy rules left behind go away on reboot)" + fi + fi + clean_routing_leftovers "$_ifs" && _found=1 + [ "$_found" -eq 1 ] || ok "No tunnel, firewall, nft or routing leftovers" +} + +# Dawnline's policy rules: priority 90 sends the portal's and the tunnels' +# answers by the main table; 5200-5299 are the "like a home device" loop for a +# tunnel interface (Dawnline's, or one already gone), with tables 2077-2176. +clean_routing_leftovers() { + _ours=" $(echo "$1" | tr '\n' ' ') " + _rules="" + for _fam in -4 -6; do + _r="$(ip "$_fam" rule show 2>/dev/null | awk -v fam="$_fam" -v ours="$_ours" ' + { pr = $1; sub(/:$/, "", pr); pr += 0; line = $0; sub(/^[0-9]+:[ \t]*/, "", line) } + pr == 90 && line ~ /ipproto (tcp|udp) sport [0-9]+ lookup main/ { print fam "|" pr "|" line; next } + pr >= 5200 && pr < 5300 && fam == "-4" && match(line, /iif [^ ]+/) { + dev = substr(line, RSTART + 4, RLENGTH - 4) + if (line ~ /\[detached\]/ || index(ours, " " dev " ")) print fam "|" pr "|" line + }')" + [ -n "$_r" ] && _rules="$_rules$_r +" + done + _rules="$(printf '%s' "$_rules" | sed '/^$/d')" + [ -n "$_rules" ] || return 1 + _tables="$(printf '%s\n' "$_rules" | awk '{ t = $NF + 0; if ($(NF - 1) == "lookup" && t >= 2077 && t < 2177) print t }' | sort -u)" + if [ "$DRY_RUN" -eq 1 ]; then + printf '%s\n' "$_rules" | while IFS='|' read -r _f _p _l; do dry "delete ip $_f rule $_p: $_l"; done + for _t in $_tables; do dry "flush route table $_t"; done + return 0 + fi + printf '%s\n' "$_rules" | while IFS='|' read -r _f _p _l; do + # "from all" and "[detached]" are how ip prints a rule, not how it takes one. + _spec="$(echo "$_l" | sed -e 's/^from all //' -e 's/ \[detached\]//')" + # shellcheck disable=SC2086 # the rule spec is words for ip + ip "$_f" rule del priority "$_p" $_spec 2>/dev/null + done + for _t in $_tables; do ip -4 route flush table "$_t" 2>/dev/null; done + ok "Removed $(printf '%s\n' "$_rules" | wc -l | tr -d ' ') leftover routing rule(s)" + return 0 +} + +do_leftovers() { + step "Cleaning up leftovers" + clean_network_leftovers + + if grep -qs '/usr/libexec/dawnline/' /etc/crontabs/root; then + if [ "$DRY_RUN" -eq 1 ]; then + dry "remove Dawnline lines from /etc/crontabs/root" + else + sed -i '\#/usr/libexec/dawnline/#d' /etc/crontabs/root + /etc/init.d/cron restart >/dev/null 2>&1 + ok "Removed the heartbeat cron job" + fi + fi + + set -- /var/run/dawnline /var/run/dawnline-dns.pid /var/etc/dawnline-dns.conf \ + /var/etc/dawnline-dns.resolv /var/etc/dawnline-ns.nft /tmp/hosts/dawnline /tmp/dawnline-update \ + /www/cgi-bin/dawnline-portal + # The package's own files, only once the package manager has let go of them. + if ! pkg_is_installed "$PKG_NAME"; then + set -- "$@" /usr/bin/dawnline /usr/libexec/dawnline /usr/share/dawnline /usr/share/ucode/dawnline \ + /etc/init.d/dawnline /etc/hotplug.d/iface/95-dawnline /etc/uci-defaults/90_dawnline \ + /usr/share/rpcd/ucode/luci.dawnline /usr/share/rpcd/acl.d/luci-app-dawnline.json \ + /usr/share/luci/menu.d/luci-app-dawnline.json /www/luci-static/resources/dawnline \ + /www/luci-static/resources/view/dawnline + for _r in /etc/rc.d/*dawnline; do [ -e "$_r" ] && set -- "$@" "$_r"; done + fi + if [ "$PURGE" -eq 1 ]; then + set -- "$@" "$DATA_DIR" /etc/config/dawnline /etc/config/dawnline-opkg /etc/config/dawnline.apk-new + fi + _gone="" + for _p in "$@"; do + [ -e "$_p" ] || [ -L "$_p" ] || continue + _gone="$_gone $_p" + if [ "$DRY_RUN" -eq 1 ]; then + dry "delete $_p" + else + rm -rf "$_p" + fi + done + if [ -n "$_gone" ] && [ "$DRY_RUN" -eq 0 ]; then + log_line "INFO deleted:$_gone" + case "$_gone" in *"/tmp/hosts/dawnline"*) killall -HUP dnsmasq 2>/dev/null ;; esac + ok "Removed leftover files ($(echo "$_gone" | wc -w | tr -d ' '))" + elif [ -z "$_gone" ]; then + ok "No leftover files" + fi + if [ "$PURGE" -eq 1 ] && [ "$DRY_RUN" -eq 0 ]; then + ok "Configuration, keys, history and backups deleted (--purge)" + elif [ "$PURGE" -eq 0 ]; then + _kept="" + [ -f /etc/config/dawnline ] && _kept="/etc/config/dawnline" + [ -d "$DATA_DIR" ] && _kept="${_kept:+$_kept and }$DATA_DIR (backups, history)" + [ -z "$_kept" ] || ok "Kept: $_kept" + fi + + if [ "$DRY_RUN" -eq 1 ]; then + dry "clear the LuCI caches" + else + rm -f /tmp/luci-indexcache* /var/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null + ok "LuCI caches cleared" + fi +} + +do_reload_luci() { + step "Reloading LuCI" + _done="" + for _svc in rpcd uhttpd; do + [ -x "/etc/init.d/$_svc" ] || continue + act "restart $_svc" "$_svc" "/etc/init.d/$_svc" restart && _done="${_done:+$_done and }$_svc" + done + [ "$DRY_RUN" -eq 1 ] || [ -z "$_done" ] || ok "Restarted $_done (log in to LuCI again if asked)" + return 0 +} + +cleanup() { + trap '' HUP INT TERM + stream_stop + [ -n "$TMP_DIR" ] && rm -rf "$TMP_DIR" 2>/dev/null + release_lock +} + +on_hup() { exit 129; } +on_int() { exit 130; } +on_term() { exit 143; } +on_pipe() { + trap '' PIPE + exit 141 +} + +main() { + trap cleanup EXIT + trap on_hup HUP + trap on_int INT + trap on_term TERM + trap on_pipe PIPE + + parse_args "$@" || exit 2 + [ "$(id -u 2>/dev/null || echo 1)" = 0 ] || fail "Run the uninstaller as root" + acquire_lock || exit 1 + : >"$LOG_FILE" 2>/dev/null && chmod 600 "$LOG_FILE" 2>/dev/null && LOG_READY=1 + log_line "INFO Dawnline Uninstaller $UNINSTALLER_VERSION: $0 $*" + TMP_DIR="$(mktemp -d /tmp/dawnline-uninstaller.XXXXXX 2>/dev/null)" || TMP_DIR="" + [ -n "$TMP_DIR" ] || { + TMP_DIR="/tmp/dawnline-uninstaller.$$" + mkdir -p "$TMP_DIR" || fail "Cannot create a temporary directory in /tmp" + } + detect_package_manager || fail "No supported package manager" + + printf '\n %s%sDawnline Uninstaller%s v%s\n' "$C_CYAN" "$C_BOLD" "$C_RESET" "$UNINSTALLER_VERSION" + printf ' Removes Dawnline and everything it set up; AmneziaWG stays unless asked\n\n' + [ "$DRY_RUN" -eq 1 ] && msg "Dry run: nothing on the router is changed" + + if ! dawnline_present; then + ok "Dawnline is not installed: nothing to do" + return 0 + fi + confirm + wait_for_update + # Once started, an SSH drop must not leave the removal half done. + trap '' HUP + + do_backup + do_teardown + do_remove_package + do_awg + do_leftovers + do_reload_luci + + _took=$(($(date +%s 2>/dev/null || echo "$START_TS") - START_TS)) + if [ "$DRY_RUN" -eq 1 ]; then + ok "Dry run finished in ${_took}s: nothing was changed" + msg "Log: $LOG_FILE" + return 0 + fi + if [ "$FAILED" -eq 1 ]; then + err "Dawnline was not removed completely in ${_took}s" + else + ok "Dawnline removed in ${_took}s" + fi + [ -n "$BACKUP_PATH" ] && msg "Backup: $BACKUP_PATH (restore it in Dawnline → Settings → Backups after reinstalling)" + msg "Log: $LOG_FILE" + [ "$FAILED" -eq 0 ] || exit 1 +} + +main "$@" diff --git a/web/.prettierignore b/web/.prettierignore index 3dd0449..1de8c4e 100644 --- a/web/.prettierignore +++ b/web/.prettierignore @@ -2,3 +2,4 @@ node_modules/ coverage/ package-lock.json src/portal/fonts/ +src/admin/styles/*.css diff --git a/web/package-lock.json b/web/package-lock.json index 4e8459a..0f2353c 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "dawnline-web", - "version": "0.3.1", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "dawnline-web", - "version": "0.3.1", + "version": "0.4.0", "license": "MIT", "dependencies": { "qrcode-generator": "1.4.4" diff --git a/web/package.json b/web/package.json index a5b7e77..eed802d 100644 --- a/web/package.json +++ b/web/package.json @@ -1,6 +1,6 @@ { "name": "dawnline-web", - "version": "0.3.1", + "version": "0.4.0", "private": true, "license": "MIT", "type": "module", diff --git a/web/src/admin/access.ts b/web/src/admin/access.ts index cfd048a..995aad5 100644 --- a/web/src/admin/access.ts +++ b/web/src/admin/access.ts @@ -4,8 +4,10 @@ import type { Circle, Person, Server, Status } from '../shared/types'; import { E } from './e'; import { api, type HomeHost } from './api'; -import { attempt, button, closeModal, confirmDialog, modal } from './ui'; -import { input } from './kit'; +import { button } from './ui/button'; +import { cancelButton, closeModal, confirmDialog, modal } from './ui/modal'; +import { attempt } from './ui/toast'; +import { chipToggle, input } from './ui/controls'; import { icon } from '../shared/icons'; type Service = Status['services'][number]; @@ -21,7 +23,7 @@ export const homeAccess = (p: Person) => p.access === 'both' || (p.access === 'l /* ---------- Home services ---------- */ -export function serviceDialog(sv: Service | null, prefill: Partial, onSaved: () => void) { +export function serviceDialog(sv: Service | null, prefill: Partial, onSaved: () => unknown) { const name = input(sv?.name ?? prefill.name ?? '', { placeholder: 'NAS' }); const addr = input(sv?.address ?? prefill.address ?? '', { placeholder: '192.168.1.10', class: 'cbi-input-text dl-mono' }); const ports = input((sv?.ports ?? prefill.ports ?? []).join(', '), { @@ -34,7 +36,7 @@ export function serviceDialog(sv: Service | null, prefill: Partial, onS sv ? `Edit ${sv.name}` : 'Add service', [field('Name', name), field('Address', addr), field('Ports', ports)], [ - E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + cancelButton(), ' ', button( 'Save', @@ -88,59 +90,91 @@ function portGroups(h: HomeHost): [string, string[]][] { return by.size ? [...by].map(([l, p]) => [l, [...p].sort((a, b) => +a - +b)]) : DEFAULT_PORTS; } -/** Services shared by all servers, and the devices at home to add them from. */ -export function homeServices(st: Status, serverId: string, reload: () => void): HTMLElement { - const services = st.services; +/** Home services as a live part of Server → Access: `update` repaints it from a new status. */ +export interface HomeServices { + el: HTMLElement; + update(st: Status): void; +} + +/** + * Services shared by all servers, and the devices at home to add them from. + * The devices are read once; `reload` refreshes the status after a change + * (the rest of the Access section, and what is typed there, stays). + */ +export function homeServices(initial: Status, serverId: string, reload: () => Promise): HomeServices { + let st = initial; + let hosts: { hosts: HomeHost[]; mdns: boolean } | null = null; + let failed = false; + /** The "Add from devices at home" fold, once opened or closed by hand. */ + let open: boolean | null = null; + /** Devices with a change on its way: a second click would add the service twice. */ + const busy = new Set(); + const list = E('div', { class: 'dl-list' }); const picker = E('div', { class: 'dl-stack gap8' }, E('span', { class: 'dl-sub' }, 'Looking for devices at home…')); - const rows = services.length - ? services.map((sv) => - E('div', { class: 'dl-row' }, [ - icon('home'), - E('span', { class: 'dl-row-main dl-stack' }, [ - E('b', {}, sv.name), - E( - 'span', - { class: 'dl-mono dl-faint' }, - `${sv.address}${sv.ports.length ? ` · ports ${sv.ports.join(', ')}` : ' · all ports'}`, - ), - ]), - button('Edit', () => serviceDialog(sv, {}, reload)), - button( - [icon('trash')], - async () => { - if ( - (await confirmDialog(`Remove ${sv.name}?`, 'People limited to this service lose access to it.', 'Remove', true)) && - (await attempt(() => api.serviceDelete(sv.id), 'Removed')) - ) - reload(); - }, - 'neutral', - { title: 'Remove', 'aria-label': `Remove ${sv.name}` }, - ), - ]), - ) - : [E('div', { class: 'dl-row dl-muted' }, 'No services yet: pick ports of a device below.')]; + const paintRows = () => { + const services = st.services; + dom.content( + list, + services.length + ? services.map((sv) => + E('div', { class: 'dl-row' }, [ + icon('home'), + E('span', { class: 'dl-row-main dl-stack' }, [ + E('b', {}, sv.name), + E( + 'span', + { class: 'dl-mono dl-faint' }, + `${sv.address}${sv.ports.length ? ` · ports ${sv.ports.join(', ')}` : ' · all ports'}`, + ), + ]), + button('Edit', () => serviceDialog(sv, {}, reload)), + button( + [icon('trash')], + async () => { + if ( + (await confirmDialog(`Remove ${sv.name}?`, 'People limited to this service lose access to it.', 'Remove', true)) && + (await attempt(() => api.serviceDelete(sv.id), 'Removed')) + ) + await reload(); + }, + 'neutral', + { title: 'Remove', 'aria-label': `Remove ${sv.name}` }, + ), + ]), + ) + : [E('div', { class: 'dl-row dl-muted' }, 'No services yet: pick ports of a device below.')], + ); + }; /** Ports chosen for a device: add, change or remove its service at once. */ async function choose(h: HomeHost, ports: string[] | null) { - const sv = services.find((s) => s.address === h.address); - const ok = - ports === null - ? sv && (await attempt(() => api.serviceDelete(sv.id), `${sv.name} removed`)) - : await attempt( - () => api.serviceSet(sv?.id ?? '', sv?.name ?? (h.name || h.address), h.address, ports), - sv ? `${sv.name} updated` : `${h.name || h.address} added`, - ); - if (ok) reload(); + if (busy.has(h.address)) return; + busy.add(h.address); + paintPicker(); + try { + const sv = st.services.find((s) => s.address === h.address); + const ok = + ports === null + ? sv && (await attempt(() => api.serviceDelete(sv.id), `${sv.name} removed`)) + : await attempt( + () => api.serviceSet(sv?.id ?? '', sv?.name ?? (h.name || h.address), h.address, ports), + sv ? `${sv.name} updated` : `${h.name || h.address} added`, + ); + if (ok) await reload(); + } finally { + busy.delete(h.address); + paintPicker(); + } } function hostRow(h: HomeHost): HTMLElement { - const sv = services.find((s) => s.address === h.address); + const sv = st.services.find((s) => s.address === h.address); const all = !!sv && !sv.ports.length; const chosen = new Set(sv?.ports ?? []); + const wait = busy.has(h.address); const chip = (label: string, on: boolean, click: () => void) => - E('button', { type: 'button', class: `dl-chipbtn${on ? ' on' : ''}`, 'aria-pressed': on ? 'true' : 'false', click }, label); + chipToggle(label, on, click, { disabled: wait ? 'disabled' : null, 'aria-busy': wait ? 'true' : null }); return E('div', { class: 'dl-row' }, [ icon(h.services.some((s) => s.type.startsWith('_ipp') || s.type.startsWith('_printer')) ? 'file' : 'computer'), E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, h.name || h.address), E('span', { class: 'dl-mono dl-faint' }, h.address)]), @@ -161,36 +195,46 @@ export function homeServices(st: Status, serverId: string, reload: () => void): ]); } + function paintPicker() { + if (failed) return dom.content(picker, E('span', { class: 'dl-sub' }, "Couldn't read the devices at home.")); + if (!hosts) return; + const r = hosts; + if (!r.hosts.length) return dom.content(picker, E('span', { class: 'dl-sub' }, 'No devices found in the home network right now.')); + // Open while there are no services yet (that is where they come from), then as left. + const fold = E('details', { class: 'dl-params', open: (open ?? !st.services.length) ? '' : null }, [ + E('summary', {}, [ + icon('chevron'), + E('span', {}, 'Add from devices at home'), + E('span', { class: 'dl-pcount' }, String(r.hosts.length)), + ]), + E('div', { class: 'dl-params-body' }, [ + E( + 'span', + { class: 'dl-sub' }, + r.mdns + ? 'Ports they announce over Bonjour. Pick what to open, or all ports.' + : 'Devices that got an address from this router. Pick the ports to open, or all ports.', + ), + E('div', { class: 'dl-list' }, r.hosts.map(hostRow)), + ]), + ]); + fold.addEventListener('toggle', () => (open = (fold as HTMLDetailsElement).open)); + dom.content(picker, fold); + } + api .homeHosts(serverId) .then((r) => { - const open = r.hosts.some((h) => services.some((s) => s.address === h.address)) && !services.length; - dom.content( - picker, - r.hosts.length - ? E('details', { class: 'dl-params', open: open ? '' : null }, [ - E('summary', {}, [ - icon('chevron'), - E('span', {}, 'Add from devices at home'), - E('span', { class: 'dl-pcount' }, String(r.hosts.length)), - ]), - E('div', { class: 'dl-params-body' }, [ - E( - 'span', - { class: 'dl-sub' }, - r.mdns - ? 'Ports they announce over Bonjour. Pick what to open, or all ports.' - : 'Devices that got an address from this router. Pick the ports to open, or all ports.', - ), - E('div', { class: 'dl-list' }, r.hosts.map(hostRow)), - ]), - ]) - : E('span', { class: 'dl-sub' }, 'No devices found in the home network right now.'), - ); + hosts = r; + paintPicker(); }) - .catch(() => dom.content(picker, E('span', { class: 'dl-sub' }, "Couldn't read the devices at home."))); + .catch(() => { + failed = true; + paintPicker(); + }); + paintRows(); - return E('div', { class: 'dl-stack gap8' }, [ + const el = E('div', { class: 'dl-stack gap8' }, [ E('div', { class: 'dl-iflead' }, [ E('div', { class: 'dl-iflead-row' }, [ E('b', {}, 'Home services'), @@ -202,14 +246,22 @@ export function homeServices(st: Status, serverId: string, reload: () => void): 'Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers.', ), ]), - E('div', { class: 'dl-list' }, rows), + list, picker, ]); + return { + el, + update(n: Status) { + st = n; + paintRows(); + paintPicker(); + }, + }; } /* ---------- Circles ---------- */ -export function circleDialog(st: Status, serverId: string, ci: Circle | null, onDone: () => void) { +export function circleDialog(st: Status, serverId: string, ci: Circle | null, onDone: () => unknown) { const used = new Set(st.circles.filter((c) => c.server === serverId).map((c) => c.color)); let color = ci?.color ?? CIRCLE_COLORS.findIndex((_, i) => !used.has(i)); if (color < 0) color = 0; @@ -287,7 +339,7 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on ) : '', E('span', { class: 'dl-spacer' }), - E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + cancelButton(), ' ', button( 'Save', @@ -305,7 +357,7 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on } /** The server's circles as chips (click to edit) and a round "+" to add one. */ -export function circleChips(st: Status, serverId: string, onDone: () => void): HTMLElement { +export function circleChips(st: Status, serverId: string, onDone: () => unknown): HTMLElement { const list = st.circles.filter((c) => c.server === serverId); return E('div', { class: 'dl-chips-row dl-circles' }, [ ...list.map((c) => { diff --git a/web/src/admin/api.ts b/web/src/admin/api.ts index 97cf47e..b3c47ba 100644 --- a/web/src/admin/api.ts +++ b/web/src/admin/api.ts @@ -1,6 +1,6 @@ // luci.dawnline RPC bindings. The backend reports failures as { error }. -import type { AwgCaps, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types'; +import type { AwgCaps, AwgState, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types'; function call(method: string, params: string[] = []) { const fn = rpc.declare({ object: 'luci.dawnline', method, params }); @@ -25,6 +25,7 @@ export interface SetupDefaults { portal_port: number; taken: string[]; awg: AwgCaps; + awg_state?: AwgState; } export interface Backup { @@ -40,6 +41,12 @@ export interface UpdateComponent { installed?: string | null; latest?: string | null; update?: boolean; + /** latest | outdated | dev (installed is newer than the release) | '' (unknown). */ + status?: 'latest' | 'outdated' | 'dev' | ''; + /** When this component was last checked. */ + time?: number; + url?: string | null; + published?: string | null; note?: string; error?: string; repo?: string; @@ -78,23 +85,89 @@ export interface UpdatesStatus { home?: boolean; needs?: Needs; check: { time: number; components: Record } | null; - job: { - action: string; - component: string | null; - state: 'running' | 'done' | 'failed'; - started: number; - finished: number | null; - phase: string; - log: string[]; - error: string | null; - } | null; + job: UpdateJob | null; + /** Router time, for the job timer. */ + now: number; + repo: string; + policy: UpdatePolicy; + /** Automatic runs: the last check and the last scheduled install day. */ + auto: { check?: number; install_day?: string }; + /** The version kept for Roll back, per component. */ + kept: Record<'app' | 'amneziawg', { version: string; build: AwgSource | null; saved: number | null } | null>; + /** Components → Activity, newest first. */ + history: UpdateEvent[]; + /** AmneziaWG interfaces (their Dawnline names): switching builds restarts them. */ + tunnels: string[]; } -/** Missing packages by feature: the portal's HTTPS, ACME certificates, the home-like link. */ +export interface UpdateEvent { + ts: number; + /** found: a check found updates; install: an update ran; error: a check or an update failed. */ + kind: 'found' | 'install' | 'error'; + auto?: boolean; + items?: string[]; + component?: string | null; + from?: string | null; + to?: string | null; + state?: 'done' | 'failed'; + error?: string | null; + took?: number; +} + +export interface UpdateJob { + id: string; + action: string; + component: string | null; + state: 'running' | 'done' | 'failed'; + started: number; + finished: number | null; + /** Started by Settings → Updates, not by a click. */ + auto?: boolean; + phase: string; + from: string | null; + to: string | null; + log: string[]; + error: string | null; + result: Record | null; +} + +/** Settings → Updates. */ +export interface UpdatePolicy { + check: boolean; + interval: '6h' | '12h' | '1d' | '7d'; + auto: boolean; + mode: 'immediate' | 'scheduled'; + time: string; + targets: ('app' | 'amneziawg' | 'packages')[]; + keep: boolean; + mirrors: boolean; +} + +export interface Release { + tag: string; + name: string; + published: string | null; + prerelease: boolean; + url: string | null; + body: string | null; + assets: string[]; +} + +/** Missing packages by feature: the portal's HTTPS, ACME certificates, the home-like link, AmneziaWG itself. */ export interface Needs { https: string[]; acme: string[]; home: string[]; + /** amneziawg-tools and/or kmod-amneziawg (older backends leave it out). */ + awg?: string[]; +} + +/** The slow part of the portal settings, loaded after the page shows. */ +export interface PortalInfo { + /** Addresses the portal could use, found on the router. */ + candidates: { host: string; kind: 'name' | 'ip'; ips: string[]; here: boolean; cloudflare: boolean; cert: boolean }[]; + /** The portal's checks from Health. */ + checks: HealthCheck[]; } export interface SettingsData { @@ -106,10 +179,6 @@ export interface SettingsData { port_owners: string[]; wan443_taken?: boolean; portal_public_port?: number; - /** Addresses the portal could use, found on the router. */ - portal_candidates?: { host: string; kind: 'name' | 'ip'; ips: string[]; here: boolean; cloudflare: boolean; cert: boolean }[]; - /** The portal's checks from Health. */ - portal_checks?: HealthCheck[]; geo_cached: number; logs: LogsInfo; } @@ -290,14 +359,7 @@ async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: P return r; } -const statusRaw = call('status', ['days']); -export let lastStatusAt = 0; - -async function status(days?: number): Promise { - const st = await statusRaw(days); - lastStatusAt = Date.now(); - return st; -} +const status = call('status', ['days']); /** One line of the service log: tunnel and service starts, stops, watchdog repairs, errors. */ export interface ServiceLogEntry { @@ -333,6 +395,7 @@ export type Health = { checks: HealthCheck[] } & ServiceLog; export const api = { personUpdate, settingsGet: call('settings_get'), + portalInfo: call('portal_info'), settingsUpdate: call('settings_update', ['values']), serviceSet: call<{ id: string }>('service_set', ['id', 'name', 'address', 'ports']), serviceDelete: call('service_delete', ['id']), @@ -376,6 +439,8 @@ export const api = { serverObfuscation: call('server_obfuscation', ['id', 'preset']), serverUpdate: call('server_update', ['id', 'values']), serverDelete: call('server_delete', ['id']), + /** The personal link, its code and every address it works on (main first); not part of the status. */ + personLinks: call<{ code: string; link: string | null; links: string[] }>('person_links', ['id']), personCreate: call<{ id: string; link: string | null }>('person_create', [ 'name', 'slug', @@ -410,5 +475,8 @@ export const api = { exportJson: call>('export'), importJson: call('import', ['data']), updatesStatus: call('updates_status'), - updatesRun: call<{ started: boolean }>('updates_run', ['what']), + updatesRun: call<{ started: boolean; job: UpdateJob | null }>('updates_run', ['what']), + updatesReleases: call<{ releases: Release[]; page: number }>('updates_releases', ['page']), + updatesNotes: call('updates_notes', ['component', 'tag', 'build']), + updatesChanges: call<{ items: string[] }>('updates_changes', ['from', 'to']), }; diff --git a/web/src/admin/charts.ts b/web/src/admin/charts.ts deleted file mode 100644 index 7166000..0000000 --- a/web/src/admin/charts.ts +++ /dev/null @@ -1,96 +0,0 @@ -// DOM bar charts with a hover tooltip (traffic per day, sparklines). - -import type { DayUsage } from '../shared/types'; -import { E } from './e'; -import { bytes } from '../shared/format'; - -function dayLabel(day: string): string { - const [y, m, d] = day.split('-').map(Number); - return new Date(y, m - 1, d).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' }); -} - -/** - * Daily traffic bars (download stacked over upload, from the person's point - * of view: router tx = download). `top(day)` may name the busiest device. - */ -export function trafficBars(series: DayUsage[], height = 180, top?: (day: string) => string | null): HTMLElement { - const max = Math.max(1, ...series.map((d) => d.rx + d.tx)); - const tip = E('div', { class: 'dl-tip' }); - tip.style.display = 'none'; - const bars = E('div', { class: 'dl-bars' }); - bars.style.height = `${height}px`; - series.forEach((d) => { - const total = d.rx + d.tx; - const col = E('div', { class: 'dl-bar' }, [E('i', { class: 'down' }), E('i', { class: 'up' })]); - (col.children[0] as HTMLElement).style.height = `${(d.tx / max) * 100}%`; - (col.children[1] as HTMLElement).style.height = `${(d.rx / max) * 100}%`; - if (!total) col.classList.add('empty'); - col.addEventListener('mouseenter', () => { - const t = top?.(d.day); - tip.replaceChildren( - E('div', { class: 'dl-tip-title' }, dayLabel(d.day)), - E('div', { class: 'dl-muted' }, `↓ ${bytes(d.tx)} · ↑ ${bytes(d.rx)}`), - t ? E('div', { class: 'dl-faint' }, `Top: ${t}`) : '', - ); - tip.style.display = ''; - const r = col.getBoundingClientRect(); - const host = bars.getBoundingClientRect(); - const x = r.left - host.left + r.width / 2; - tip.style.left = `${Math.min(Math.max(x, 70), host.width - 70)}px`; - }); - bars.appendChild(col); - }); - bars.addEventListener('mouseleave', () => (tip.style.display = 'none')); - const first = series[0]?.day; - return E('div', { class: 'dl-chartbox' }, [ - bars, - tip, - E('div', { class: 'dl-axis' }, [E('span', {}, first ? dayLabel(first) : ''), E('span', {}, 'Today')]), - ]); -} - -let floating: HTMLElement | null = null; - -/** Floating tooltip that follows the pointer (for small charts and meters). */ -export function attachTip(el: HTMLElement, content: () => (Node | string)[]) { - const show = (ev: MouseEvent) => { - floating ??= document.body.appendChild(E('div', { class: 'dl-tip dl-tip-float dl-root' })); - floating.replaceChildren(...content().map((c) => (typeof c === 'string' ? document.createTextNode(c) : c))); - floating.style.display = ''; - floating.style.left = `${ev.clientX}px`; - floating.style.top = `${ev.clientY - 10}px`; - }; - el.addEventListener('mouseenter', show); - el.addEventListener('mousemove', show); - el.addEventListener('mouseleave', () => floating && (floating.style.display = 'none')); -} - -/** Tiny daily sparkline (oldest first, the last bar is today) with per-day tooltips. */ -export function spark(values: number[], width = 120, height = 26): HTMLElement { - const max = Math.max(1, ...values); - const el = E('div', { class: 'dl-spark' }); - el.style.width = `${width}px`; - el.style.height = `${height}px`; - const now = Date.now(); - values.forEach((v, i) => { - const b = E('i'); - b.style.height = `${Math.max(6, (v / max) * 100)}%`; - if (!v) b.classList.add('zero'); - const back = values.length - 1 - i; - const d = new Date(now - back * 86400000); - attachTip(b, () => [ - E( - 'div', - { class: 'dl-tip-title' }, - back === 0 - ? 'Today' - : back === 1 - ? 'Yesterday' - : d.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' }), - ), - E('div', { class: 'dl-muted' }, bytes(v)), - ]); - el.appendChild(b); - }); - return el; -} diff --git a/web/src/admin/cores/awg.ts b/web/src/admin/cores/awg.ts new file mode 100644 index 0000000..2773299 --- /dev/null +++ b/web/src/admin/cores/awg.ts @@ -0,0 +1,389 @@ +// The AmneziaWG core in the admin: how a device connects (.conf, AmneziaVPN +// key, QR), the disguise and its parameters, and the core's own settings on +// Server → AmneziaWG. Plain WireGuard is AmneziaWG with the disguise off. + +import type { AwgConfig, Server, Status } from '../../shared/types'; +import { E } from '../e'; +import { api } from '../api'; +import { button } from '../ui/button'; +import { confirmDialog } from '../ui/modal'; +import { copyText, downloadFile } from '../ui/files'; +import { attempt, notify } from '../ui/toast'; +import { input } from '../ui/controls'; +import { callout, card, group, row, svg } from '../ui/layout'; +import { qrSvg } from '../../shared/qr'; +import { vpnKey } from '../../shared/vpnkey'; +import { icon } from '../../shared/icons'; +import { methodInfo, methodPicker, type Method } from '../disguise'; +import { coreHead, type Core, type CoreCtx } from './common'; + +/** `.conf` names of the disguise parameters, in file order. */ +const CONF: [string, string][] = [ + ['jc', 'Jc'], + ['jmin', 'Jmin'], + ['jmax', 'Jmax'], + ['s1', 'S1'], + ['s2', 'S2'], + ['s3', 'S3'], + ['s4', 'S4'], + ['h1', 'H1'], + ['h2', 'H2'], + ['h3', 'H3'], + ['h4', 'H4'], + ['i1', 'I1'], + ['i2', 'I2'], + ['i3', 'I3'], + ['i4', 'I4'], + ['i5', 'I5'], + ['header_protection_key', 'HeaderProtectionKey'], + ['content_padding_addition', 'ContentPaddingAddition'], + ['rekey_after_time', 'RekeyAfterTime'], + ['rekey_timeout', 'RekeyTimeout'], + ['reject_after_time', 'RejectAfterTime'], + ['keepalive_timeout', 'KeepaliveTimeout'], + ['max_handshake_attempts', 'MaxHandshakeAttempts'], + ['random_trailers', 'RandomTrailers'], + ['disable_cookies', 'DisableCookies'], +]; + +/** + * The applied parameters, grouped by what they do, with a plain-language + * line per group. Collapsed by default; copyable as config lines. + */ +function paramsView(o: Record): HTMLElement | null { + const has = (k: string) => o[k] != null && o[k] !== ''; + const keys = CONF.filter(([k]) => has(k)); + if (!keys.length) return null; + const val = (k: string, name: string) => + E('span', { class: 'dl-pv' }, [E('i', {}, name), E('b', {}, k === 'header_protection_key' ? `${o[k].slice(0, 6)}••••` : o[k])]); + const group = (title: string, ic: string, text: string, ks: string[]) => { + const present = CONF.filter(([k]) => ks.includes(k) && has(k)); + return present.length + ? E('div', { class: 'dl-pgroup' }, [ + E('div', { class: 'dl-pgroup-head' }, [icon(ic), E('b', {}, title)]), + E('p', {}, text), + E( + 'div', + { class: 'dl-pvals' }, + present.map(([k, n]) => val(k, n)), + ), + ]) + : ''; + }; + const jc = Number(o.jc || 0); + const signature = (o.i1 ?? '').includes('0x8580') + ? 'A first packet shaped like a DNS answer.' + : 'Extra packets sent before the handshake.'; + const conf = keys.map(([k, n]) => `${n} = ${o[k]}`).join('\n'); + const body = E('div', { class: 'dl-pgrid' }, [ + group( + 'Junk packets', + 'zap', + jc ? `${jc} random packet${jc === 1 ? '' : 's'} of ${o.jmin}–${o.jmax} bytes before each handshake.` : 'No junk packets.', + ['jc', 'jmin', 'jmax'], + ), + group('Padding', 'archive', 'Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.', [ + 's1', + 's2', + 's3', + 's4', + ]), + group('Packet types', 'key', 'The values that replace WireGuard’s recognisable message types.', ['h1', 'h2', 'h3', 'h4']), + group('Signatures', 'globe', signature, ['i1', 'i2', 'i3', 'i4', 'i5']), + group('Protection', 'lock', 'AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.', [ + 'header_protection_key', + 'content_padding_addition', + 'random_trailers', + 'disable_cookies', + ]), + group('Timing', 'clock', 'Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.', [ + 'rekey_after_time', + 'rekey_timeout', + 'reject_after_time', + 'keepalive_timeout', + 'max_handshake_attempts', + ]), + ]); + return E('details', { class: 'dl-params' }, [ + E('summary', {}, [ + icon('chevron'), + E('span', {}, 'Current parameters'), + E('span', { class: 'dl-pcount' }, String(keys.length)), + E('span', { class: 'dl-spacer' }), + E( + 'button', + { + type: 'button', + class: 'dl-linkbtn', + click: (ev: Event) => { + ev.preventDefault(); + copyText(conf, 'Parameters copied'); + }, + }, + 'Copy as config', + ), + ]), + body, + ]); +} + +/** One configuration line, highlighted; private and preshared keys masked unless shown. */ +function confLine(line: string, reveal: boolean): Node { + if (/^\s*\[.+\]\s*$/.test(line)) return E('span', { class: 'dl-conf-sec' }, line); + const m = /^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(line); + if (!m) return document.createTextNode(line); + const secret = /^(\s*)(PrivateKey|PresharedKey)\b/.test(line); + return E('span', {}, [ + E('span', { class: 'dl-conf-k' }, m[1]), + ' ', + secret && !reveal ? E('span', { class: 'dl-conf-mask' }, '••••••••••••••••') : m[2], + ]); +} + +/** The .conf as a file card (download) and a folded, highlighted view with copy and a hidden key. */ +function fileCard(cfg: AwgConfig): HTMLElement { + let reveal = false; + const pre = E('pre', { class: 'dl-conf' }); + const paint = () => + dom.content( + pre, + cfg.conf.split('\n').flatMap((l, i) => (i ? ['\n', confLine(l, reveal)] : [confLine(l, reveal)])), + ); + const eye = E( + 'button', + { + type: 'button', + class: 'dl-chipbtn', + click: (ev: Event) => { + ev.preventDefault(); + reveal = !reveal; + dom.content(eye, [icon(reveal ? 'x' : 'key'), reveal ? 'Hide key' : 'Show key']); + paint(); + }, + }, + [icon('key'), 'Show key'], + ); + paint(); + const size = new Blob([cfg.conf]).size; + return E('div', { class: 'dl-stack gap8' }, [ + E('div', { class: 'dl-filecard' }, [ + E('span', { class: 'dl-filecard-ic' }, '.conf'), + E('span', { class: 'dl-stack' }, [ + E('span', { class: 'dl-mono dl-ellipsis' }, cfg.filename), + E('span', { class: 'dl-sub' }, `AmneziaWG · ${size} bytes · import it in the app`), + ]), + button([icon('download'), ' Download'], () => downloadFile(cfg.filename, cfg.conf, 'application/octet-stream'), 'positive'), + ]), + E('details', { class: 'dl-params' }, [ + E('summary', {}, [ + icon('chevron'), + E('span', {}, 'Configuration'), + E('span', { class: 'dl-spacer' }), + eye, + E( + 'button', + { + type: 'button', + class: 'dl-chipbtn', + click: (ev: Event) => { + ev.preventDefault(); + copyText(cfg.conf, 'Configuration copied'); + }, + }, + [icon('copy'), 'Copy'], + ), + ]), + pre, + ]), + ]); +} + +/** File / key / QR switcher for a client configuration; opens on the file unless asked otherwise. */ +export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr' = 'file'): Promise { + if (!cfg.has_private_key) + return E( + 'div', + { class: 'dl-hint' }, + 'This device generated its own keys in the browser, so its full configuration only exists on that device.', + ); + const key = await vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`); + const panes: Record Node> = { + qr: () => + E('div', { class: 'dl-qr-pane' }, [ + svg(qrSvg(cfg.conf), 'dl-qr'), + E('span', { class: 'dl-sub' }, 'Scan with AmneziaVPN or AmneziaWG on the device.'), + ]), + key: () => + E('div', { class: 'dl-stack gap8' }, [ + E('div', { class: 'dl-linkbox' }, [E('span', { class: 'dl-mono' }, key), button('Copy', () => copyText(key, 'Key copied'))]), + E('span', { class: 'dl-sub' }, 'AmneziaVPN → Add server → Insert key. Keep it private.'), + ]), + file: () => fileCard(cfg), + }; + const body = E('div', { class: 'dl-connect-body' }); + const seg = E('div', { class: 'dl-seg' }); + const show = (id: string) => { + seg.querySelectorAll('button').forEach((b) => b.classList.toggle('on', b.dataset.id === id)); + dom.content(body, panes[id]()); + }; + for (const [id, label] of [ + ['file', 'File'], + ['key', 'Key'], + ['qr', 'QR code'], + ]) + seg.appendChild(E('button', { type: 'button', 'data-id': id, click: () => show(id) }, label)); + show(initial); + return E('div', { class: 'dl-stack gap12' }, [seg, body]); +} + +/** Switch the disguise (every device imports its configuration again). */ +async function applyDisguise(ctx: CoreCtx, srv: Server, m: Method, same: boolean) { + const info = methodInfo(m)!; + const people = ctx.st.people.filter((p) => p.server === srv.id); + const devices = people.reduce((n, p) => n + p.devices.length, 0); + const ok = await confirmDialog( + same ? 'Generate new disguise values?' : `Switch to ${info.title}?`, + `${devices} AmneziaWG device${devices === 1 ? '' : 's'} stop connecting until they import their configuration again (from their personal link or from you).${m === 'max' ? ' They need an app with AmneziaWG 3.1.' : ''}`, + same ? 'Generate and apply' : 'Switch and apply', + true, + ); + if (!ok) return; + if (await attempt(() => api.serverObfuscation(srv.id, m), same ? 'New values applied' : `${info.title} applied`)) { + notify('Devices are marked “Update config” until they import again.', 'info', 6000); + await ctx.refresh(); + } +} + +/** Server → AmneziaWG: listening port, what goes into every configuration, disguise, tunnel. */ +export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement { + const st: Status = ctx.st; + const port = input(String(srv.port), { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }); + const mtu = input(String(srv.mtu ?? ''), { placeholder: '1380', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }); + const ka = input(String(srv.keepalive ?? ''), { placeholder: '25', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }); + const current = methodInfo(srv.preset) ? (srv.preset as Method) : undefined; + let selected: Method = current ?? 'standard'; + const apply = button('', () => applyDisguise(ctx, srv, selected, selected === current), 'neutral'); + const label = () => + dom.content(apply, selected === current ? [icon('reset'), ' Generate new values'] : [`Switch to ${methodInfo(selected)!.title}`]); + label(); + const devs = st.people.filter((p) => p.server === srv.id).reduce((n, p) => n + p.devices.length, 0); + const tools = st.awg_state?.tools !== false; + return card( + '', + [ + coreHead( + 'AmneziaWG', + srv.up ? 'ok' : 'bad', + srv.up ? 'Running' : 'Not running', + `${srv.ifname} · ${devs} device${devs === 1 ? '' : 's'}`, + ), + group('globe', 'Listening', 'Where devices reach this core from the internet', [ + row('UDP port', port, 'Opened on the WAN firewall automatically.'), + ]), + group('file', 'In every device configuration', 'Changing these marks devices “Update config” until they import again', [ + row('MTU', mtu, 'Lower it if some sites hang on mobile networks.'), + row('Keep-alive', ka, 'Seconds between packets devices send to keep NAT open. 0 = off.'), + ]), + group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [ + methodPicker( + st.awg, + selected, + (m) => { + selected = m; + label(); + }, + current, + tools, + ), + // Only about an installed AmneziaWG: without one the server page says what to install. + tools && !st.awg.v3 + ? callout('info', [ + 'This router runs an older AmneziaWG. ', + E('b', {}, 'Maximum'), + ' becomes available with kmod-amneziawg and amneziawg-tools 3.1.', + ]) + : '', + paramsView(srv.obf ?? {}) ?? '', + E('div', { class: 'dl-row-end' }, [ + E('span', { class: 'dl-sub' }, 'Applies at once: every AmneziaWG device imports its configuration again.'), + apply, + ]), + ]), + E('details', { class: 'dl-params' }, [ + E('summary', {}, [icon('chevron'), E('span', {}, 'Tunnel'), E('span', { class: 'dl-pcount' }, '3')]), + E('div', { class: 'dl-params-body' }, [ + row('Interface', E('span', { class: 'dl-mono' }, `${srv.ifname} · router ${srv.address}`)), + row('Tunnel subnet', E('span', { class: 'dl-mono' }, srv.subnet), 'Device addresses come from it.'), + row( + 'Server public key', + E('span', { class: 'dl-keyrow' }, [ + E('code', { class: 'dl-mono' }, srv.public_key), + button([icon('copy')], () => copyText(srv.public_key, 'Public key copied'), 'neutral', { + title: 'Copy', + class: 'cbi-button cbi-button-neutral dl-icon-only sm', + }), + ]), + ), + ]), + ]), + ], + [ + E('span', { class: 'dl-sub' }, 'Port, MTU and keep-alive apply at once.'), + button('Save', () => ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, 'AmneziaWG saved'), 'positive'), + ], + ); +} + +/** Overview: the disguise in use, its stealth and speed, and the values devices carry in words. */ +function overviewTile(srv: Server): HTMLElement { + const m = methodInfo(srv.preset); + const o = srv.obf ?? {}; + const segs = (n: number, cls: string) => + E( + 'span', + { class: `dl-segs ${cls}` }, + [0, 1, 2, 3].map((i) => E('i', { class: i < n ? 'on' : '' })), + ); + const chips: string[] = []; + if (+o.jc) chips.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`); + const pad = ['s1', 's2', 's3', 's4'].filter((k) => +o[k]).map((k) => `${k.toUpperCase()} ${o[k]}`); + if (pad.length) chips.push(pad.slice(0, 2).join(' · ') + (pad.length > 2 ? ` +${pad.length - 2}` : '')); + if (['h1', 'h2', 'h3', 'h4'].some((k) => o[k] && o[k] !== String(['h1', 'h2', 'h3', 'h4'].indexOf(k) + 1))) chips.push('H1–H4 random'); + if (o.i1) chips.push(o.i1.includes('0x8580') ? 'DNS-like first packet' : 'Signature packets'); + if (o.header_protection_key) chips.push('Encrypted headers'); + if (!chips.length) chips.push(m?.id === 'off' ? 'Plain WireGuard' : 'No values yet'); + return E('div', { class: 'dl-bento-tile dl-disg' }, [ + E('div', { class: 'dl-bento-head' }, [ + E('span', { class: 'dl-metric-label' }, 'Disguise'), + E('a', { href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(srv.id)}§ion=awg` }, 'Change'), + ]), + E('div', { class: 'dl-disg-id' }, [ + E('span', { class: 'dl-disg-ic' }, icon(m?.ic ?? 'shield')), + E('span', { class: 'dl-stack' }, [E('b', {}, m ? m.title : 'Custom'), E('span', { class: 'dl-sub' }, m ? m.short : 'Set by hand')]), + ]), + m + ? E('div', { class: 'dl-disg-meters' }, [ + E('span', {}, 'Stealth'), + segs(m.stealth, 'acc'), + E('span', {}, 'Speed'), + segs(m.speed, 'ok'), + ]) + : '', + E( + 'div', + { class: 'dl-disg-chips' }, + chips.map((c) => E('span', {}, c)), + ), + ]); +} + +export const awg: Core = { + id: 'awg', + label: 'AmneziaWG', + settingsCard, + overviewTile, + connectBlock, + qrText: (cfg) => cfg.conf, + appKey: { label: 'Copy AmneziaVPN key', make: (cfg) => vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`) }, + file: { label: 'Download .conf', make: (cfg) => ({ name: cfg.filename, text: cfg.conf }) }, +}; diff --git a/web/src/admin/cores/common.ts b/web/src/admin/cores/common.ts new file mode 100644 index 0000000..10ac6e7 --- /dev/null +++ b/web/src/admin/cores/common.ts @@ -0,0 +1,41 @@ +// What every tunnel core gives the admin (cores/index.ts holds the registry), +// what a core's settings card gets from the Server page, and that card's head. + +import type { ClientConfig, Server, Status } from '../../shared/types'; +import { E } from '../e'; + +/** What the Server page hands a core's settings card. */ +export interface CoreCtx { + st: Status; + /** server_update with these values, then refresh. */ + save: (values: Record, ok?: string) => Promise; + refresh: () => Promise; +} + +/** A tunnel core (AmneziaWG today): its name and the pieces of the admin that differ per core. */ +export interface Core { + id: string; + /** "AmneziaWG": the server section, the address bar, the settings card. */ + label: string; + /** Server →