commit a3910f8b979e9f92188a5681e9aae46baa3f8301 Author: Aemeath <35622087+tickcount@users.noreply.github.com> Date: Thu Oct 15 03:28:57 2026 +0300 Dawnline 0.1.0: AmneziaWG access server for OpenWrt LuCI admin (people, devices, limits, disguise, health, updates, backups) and a personal self-service portal, built as ipk (OpenWrt 24.10) and apk (OpenWrt 25.12) with the OpenWrt SDK. Successor of openwrt-liminal. - install.sh: checks the router, installs AmneziaWG for its firmware, then the release package verified against sha256sums.txt - CI: Prettier, types, tests, committed bundles, ShellCheck, ucode checks; tagged releases build both packages and publish them - Web bundles minified with esbuild (JS and CSS) - README with framed screenshots diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..834f725 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,113 @@ +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. +on: + push: + tags: ['v*'] + workflow_dispatch: + +permissions: + contents: write + +jobs: + version: + name: Version + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - name: Checkout + uses: actions/checkout@v5 + + - name: Read and check the version + id: version + run: | + v="$(sed -n 's/^PKG_VERSION:=//p' package/luci-app-dawnline/Makefile)" + grep -q "^export const VERSION = '$v';" package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc || + { echo "::error::util.uc VERSION differs from the Makefile ($v)"; exit 1; } + grep -q "\"version\": \"$v\"" web/package.json || + { echo "::error::web/package.json version differs from the Makefile ($v)"; exit 1; } + if [ "${GITHUB_REF_TYPE}" = tag ] && [ "${GITHUB_REF_NAME}" != "v$v" ]; then + echo "::error::Tag ${GITHUB_REF_NAME} does not match the package version v$v" + exit 1 + fi + echo "version=$v" >> "$GITHUB_OUTPUT" + + build: + name: Build ${{ matrix.type }} + runs-on: ubuntu-24.04 + needs: version + strategy: + fail-fast: true + matrix: + include: + - { type: ipk, sdk: 'itdoginfo/openwrt-sdk-ipk:24.10.6' } + - { type: apk, sdk: 'itdoginfo/openwrt-sdk-apk:25.12.3' } + steps: + - name: Checkout + uses: actions/checkout@v5 + + - name: Setup Node.js + uses: actions/setup-node@v5 + with: + node-version: '22' + cache: npm + cache-dependency-path: web/package-lock.json + + - name: Build the web bundles + working-directory: web + run: | + npm ci + npm run --silent build + + - name: Build the ${{ matrix.type }} with the OpenWrt SDK + env: + IPK_SDK: ${{ matrix.sdk }} + APK_SDK: ${{ matrix.sdk }} + run: scripts/build-packages.sh ${{ matrix.type }} + + - name: Upload + uses: actions/upload-artifact@v4 + with: + name: package-${{ matrix.type }} + path: dist/luci-app-dawnline-${{ needs.version.outputs.version }}.${{ matrix.type }} + if-no-files-found: error + retention-days: 7 + + release: + name: Release + runs-on: ubuntu-24.04 + needs: [version, build] + if: github.ref_type == 'tag' + steps: + - name: Download packages + uses: actions/download-artifact@v4 + with: + pattern: package-* + path: release + merge-multiple: true + + - name: Checksums + working-directory: release + run: | + sha256sum luci-app-dawnline-* > sha256sums.txt + cat sha256sums.txt + + - name: Publish the release + uses: softprops/action-gh-release@v2 + with: + 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. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e54e375 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,115 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + web: + name: Web (format, types, tests, bundles) + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: web + steps: + - name: Checkout + uses: actions/checkout@v5 + + - name: Setup Node.js + uses: actions/setup-node@v5 + with: + node-version: '22' + cache: npm + cache-dependency-path: web/package-lock.json + + - name: Install dependencies + run: npm ci + + - name: Check formatting + id: format + run: | + if ! npm run --silent format:check; then + echo "::error::Code is not formatted. Run 'npm run format' in web/." + exit 1 + fi + + - name: Type check + id: types + run: npm run --silent typecheck + + - name: Tests + id: tests + run: npm test + + - name: Build bundles and check they are committed + id: build + run: | + npm run --silent build + if ! git diff --exit-code -- ../package; then + echo "::error::The committed bundles are out of date. Run 'npm run build' in web/ and commit the result." + exit 1 + fi + + - name: Summary + if: always() + run: | + { + echo "## Web" + echo "" + echo "| Check | Result |" + echo "|---|---|" + echo "| Formatting | ${{ steps.format.outcome }} |" + echo "| Types | ${{ steps.types.outcome }} |" + echo "| Tests | ${{ steps.tests.outcome }} |" + echo "| Bundles | ${{ steps.build.outcome }} |" + } >> "$GITHUB_STEP_SUMMARY" + + shell: + name: ShellCheck + runs-on: ubuntu-24.04 + steps: + - name: Checkout + uses: actions/checkout@v5 + + - name: ShellCheck + run: | + shellcheck --version + shellcheck -S warning \ + install.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 \ + scripts/*.sh + + ucode: + name: ucode static checks + runs-on: ubuntu-24.04 + steps: + - name: Checkout + uses: actions/checkout@v5 + + - name: Use before definition + run: python3 scripts/lint-ucode.py + + - name: Executables keep their mode + run: | + cd package/luci-app-dawnline/root + for f in usr/bin/dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/libexec/dawnline/resolver \ + etc/init.d/dawnline etc/uci-defaults/90_dawnline usr/share/dawnline/portal/www/cgi-bin/portal; do + [ -x "$f" ] || { echo "::error file=$f::not executable (git update-index --chmod=+x $f)"; exit 1; } + done + + - name: Versions agree + run: | + v="$(sed -n 's/^PKG_VERSION:=//p' package/luci-app-dawnline/Makefile)" + grep -q "^export const VERSION = '$v';" package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc + grep -q "\"version\": \"$v\"" web/package.json + echo "Version $v" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..176e429 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +dist/ +.DS_Store +web/coverage/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9c27bca --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 tickcount + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..9dbc131 --- /dev/null +++ b/README.md @@ -0,0 +1,154 @@ +# Dawnline + +[![CI](https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml/badge.svg)](https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml) +[![Build packages](https://github.com/tickcount/luci-app-dawnline/actions/workflows/build.yml/badge.svg)](https://github.com/tickcount/luci-app-dawnline/actions/workflows/build.yml) + +Your OpenWrt router as a private VPN for the people you choose. + +Dawnline runs an [AmneziaWG](https://docs.amnezia.org/) server on the router +and gives every person a personal link. They open it, add their own devices +(up to the limit you set) and connect with AmneziaVPN or AmneziaWG. You decide +what each person may reach: the home network, the internet, or both. + +Dawnline is the successor of [Liminal](https://github.com/tickcount/openwrt-liminal): +the same idea rebuilt around people instead of peers, with a personal portal, +limits, live traffic and a LuCI admin that follows a modern design. + +![Overview](docs/screenshots/overview.png) + +| People | A person | +|---|---| +| ![People](docs/screenshots/people.png) | ![Person](docs/screenshots/person.png) | + +| Personal portal | Where people connect from | +|---|---| +| ![Personal portal](docs/screenshots/portal.png) | ![Map](docs/screenshots/map.png) | + +## Features + +- **People, not peers.** One card per person with device chips, live status, + traffic, end date and data limit. Add a person, send them the link or the + invite card (QR code), and they do the rest. +- **Personal portal.** Every person gets a link made of three words + (`https://vpn.example.com/kamiro-telosu-bavine`). The link is the key: no + 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 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 services. +- **Limits.** End dates (pause, keep, or remove devices when they pass), monthly + or total data limits, allowed hours, pause one person or everyone. Devices + drop off the tunnel at once (`awg syncconf`, no interface restart). +- **Disguise presets** for AmneziaWG obfuscation (junk packets, + header and padding parameters), with what each preset needs from the apps. +- **Internet like a home device.** Tunnel clients' internet traffic enters the + router from the LAN, through a small network namespace on the LAN bridge + (needs `kmod-veth`). Whatever handles LAN traffic on the router (proxies, DPI + bypass, DNS filters, the `lan` zone) handles VPN clients too, with no + per-tool integration. +- **Overview.** Who is online with what, speed now, today and the last 30 days, + and a map of where people connect from (city level). +- **Health** checks with one-click fixes, including the ones that matter for + reaching the portal from outside (DNS, port forwards, reply routing behind + proxies such as SSClash/Mihomo, certificate coverage). +- **Updates.** Dawnline itself, AmneziaWG builds for your firmware (choose + between [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt) + and [2Grey](https://github.com/2Grey/awg-openwrt), AmneziaWG 2.0 or 3.1), and + the few OpenWrt packages Dawnline adds. +- **Backups** nightly and before risky operations, JSON export/import to move + to another router. + +## Requirements + +- OpenWrt **24.10** (opkg, `.ipk`) or **25.12** (apk, `.apk`) +- AmneziaWG (`kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`): + the installer adds a build made for your firmware when it is missing +- About 2 MB of free flash + +## Install + +On the router: + +```sh +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. + +Options: + +```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 +``` + +By hand, from a [release](https://github.com/tickcount/luci-app-dawnline/releases): + +```sh +opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # OpenWrt 24.10 +apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12 +``` + +**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`. + +## What Dawnline changes on the router + +Only objects it created: network interfaces tagged `_dawnline`, firewall +sections named `dawnline_*`, the `inet dawnline` nft table, `/tmp/hosts/dawnline`, +the `dawnline` network namespace with its two veth links (`dlx0`, `dll0`, the +latter a port of the LAN bridge), policy rules for the tunnel interfaces with +one routing table, a second dnsmasq instance on port 5354 +(`/var/etc/dawnline-dns.conf`) and, while the portal is on, a uhttpd instance +for it. `dawnline teardown` removes all of them. + +Data lives in `/etc/config/dawnline` (mode 0600, contains private keys) and +`/etc/dawnline/` (usage, events, issued configurations, backups). Live counters +are kept in `/var/run/dawnline` and flushed to flash at most hourly. + +## Development + +``` +package/luci-app-dawnline/ + root/usr/share/ucode/dawnline/ ucode library (model, apply, live, ops, view, loop) + 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/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 +build/Dockerfile package build with the OpenWrt SDK +scripts/ build, deploy and check scripts +``` + +```sh +cd web +npm ci +npm run format # Prettier +npm run ci # format check, types, tests, minified bundles + +scripts/lint-ucode.py # static ucode checks +scripts/check-ucode.sh root@router # compile every ucode file on a router +scripts/deploy.sh root@router # install the working tree (backs up configs first) +scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker +scripts/frame-screenshots.py # frame docs/screenshots/raw/*.png for this README +``` + +The web bundles are committed: CI fails when they are out of date. Pushing a +tag `vX.Y.Z` (matching `PKG_VERSION`) builds both packages with the OpenWrt SDK +and publishes a release with `sha256sums.txt`. + +## License + +[MIT](LICENSE) diff --git a/build/Dockerfile b/build/Dockerfile new file mode 100644 index 0000000..9e09bef --- /dev/null +++ b/build/Dockerfile @@ -0,0 +1,21 @@ +# Builds luci-app-dawnline with the OpenWrt SDK. +# docker build -f build/Dockerfile --build-arg SDK_IMAGE=itdoginfo/openwrt-sdk-ipk:24.10.6 . +# The web bundles (htdocs/.../app.js, portal assets) are built by npm first and +# committed; the SDK only packs files, so the package is the same on every arch. +ARG SDK_IMAGE=itdoginfo/openwrt-sdk-ipk:24.10.6 +FROM ${SDK_IMAGE} + +COPY package/luci-app-dawnline /builder/package/feeds/luci/luci-app-dawnline + +# The SDK's default config builds every kernel module and every package in the +# feeds; turn that off and select only this package (it ships scripts and web +# files, so nothing else needs building). +RUN make defconfig && \ + sed -i -e 's/^CONFIG_ALL_KMODS=y/# CONFIG_ALL_KMODS is not set/' \ + -e 's/^CONFIG_ALL_NONSHARED=y/# CONFIG_ALL_NONSHARED is not set/' \ + -e 's/^CONFIG_ALL=y/# CONFIG_ALL is not set/' .config && \ + echo 'CONFIG_PACKAGE_luci-app-dawnline=m' >> .config && \ + make defconfig && \ + make package/luci-app-dawnline/compile V=s -j4 && \ + mkdir -p /builder/out && \ + find /builder/bin/packages -name 'luci-app-dawnline*' \( -name '*.ipk' -o -name '*.apk' \) -exec cp {} /builder/out/ \; diff --git a/docs/screenshots/map.png b/docs/screenshots/map.png new file mode 100644 index 0000000..a39c52f Binary files /dev/null and b/docs/screenshots/map.png differ diff --git a/docs/screenshots/overview.png b/docs/screenshots/overview.png new file mode 100644 index 0000000..4140350 Binary files /dev/null and b/docs/screenshots/overview.png differ diff --git a/docs/screenshots/people.png b/docs/screenshots/people.png new file mode 100644 index 0000000..1b5fd84 Binary files /dev/null and b/docs/screenshots/people.png differ diff --git a/docs/screenshots/person.png b/docs/screenshots/person.png new file mode 100644 index 0000000..b03fd71 Binary files /dev/null and b/docs/screenshots/person.png differ diff --git a/docs/screenshots/portal.png b/docs/screenshots/portal.png new file mode 100644 index 0000000..943d650 Binary files /dev/null and b/docs/screenshots/portal.png differ diff --git a/docs/screenshots/raw/map.png b/docs/screenshots/raw/map.png new file mode 100644 index 0000000..001ce8c Binary files /dev/null and b/docs/screenshots/raw/map.png differ diff --git a/docs/screenshots/raw/overview.png b/docs/screenshots/raw/overview.png new file mode 100644 index 0000000..197d065 Binary files /dev/null and b/docs/screenshots/raw/overview.png differ diff --git a/docs/screenshots/raw/people.png b/docs/screenshots/raw/people.png new file mode 100644 index 0000000..a3e91ef Binary files /dev/null and b/docs/screenshots/raw/people.png differ diff --git a/docs/screenshots/raw/person.png b/docs/screenshots/raw/person.png new file mode 100644 index 0000000..d60744c Binary files /dev/null and b/docs/screenshots/raw/person.png differ diff --git a/docs/screenshots/raw/portal.png b/docs/screenshots/raw/portal.png new file mode 100644 index 0000000..5a78a58 Binary files /dev/null and b/docs/screenshots/raw/portal.png differ diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..46ffa38 --- /dev/null +++ b/install.sh @@ -0,0 +1,181 @@ +#!/bin/sh +# shellcheck shell=dash +# +# 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) +# +# 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 + +REPO="${DAWNLINE_REPO:-tickcount/luci-app-dawnline}" +AWG_SOURCE="${DAWNLINE_AWG:-auto}" +VERSION="${1:-}" +TMP="/tmp/dawnline-install" +REQUIRED_KB=2048 + +PKG_IS_APK=0 +command -v apk >/dev/null 2>&1 && PKG_IS_APK=1 +EXT=ipk +[ "$PKG_IS_APK" -eq 1 ] && EXT=apk + +msg() { printf '\033[32;1m%s\033[0m\n' "$*"; } +note() { printf '%s\n' "$*"; } +die() { + printf '\033[31;1m%s\033[0m\n' "$*" >&2 + exit 1 +} + +cleanup() { rm -rf "$TMP"; } +trap cleanup EXIT INT TERM + +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 + return 0 + fi + rm -f "$2" + attempt=$((attempt + 1)) + sleep 2 + done + return 1 +} + +pkg_update() { + if [ "$PKG_IS_APK" -eq 1 ]; then apk update >/dev/null; else opkg update >/dev/null; fi +} + +pkg_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 " + fi +} + +pkg_install_files() { + if [ "$PKG_IS_APK" -eq 1 ]; then + # Packages from GitHub releases are not signed with the feed key. + apk add --allow-untrusted "$@" + else + opkg install "$@" + fi +} + +check_system() { + [ "$(id -u)" = 0 ] || die "Run this as root." + [ -f /etc/openwrt_release ] || die "This is not OpenWrt." + # 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." ;; + esac + + 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." + fi + + nslookup github.com >/dev/null 2>&1 || die "DNS does not work: github.com does not resolve." +} + +# 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." + return 0 + fi + [ "$AWG_SOURCE" = skip ] && die "AmneziaWG is missing and DAWNLINE_AWG=skip." + + case "$AWG_SOURCE" in + slava) sources="Slava-Shchipunov/awg-openwrt" ;; + grey) sources="2Grey/awg-openwrt" ;; + *) sources="Slava-Shchipunov/awg-openwrt 2Grey/awg-openwrt" ;; + esac + + 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" + else + ok=0 + break + fi + done + if [ "$ok" -eq 1 ]; then + msg "Installing AmneziaWG" + # shellcheck disable=SC2086 + pkg_install_files $files || die "AmneziaWG installation failed." + return 0 + fi + note "No build for OpenWrt $RELEASE ($TARGET) in $src." + done + die "No AmneziaWG build for OpenWrt $RELEASE ($TARGET). Install kmod-amneziawg, amneziawg-tools and luci-proto-amneziawg by hand, then run this again." +} + +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 + fi + msg "Installing Dawnline $VERSION" + pkg_install_files "$TMP/$asset" || die "Dawnline installation failed." +} + +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 + + 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." +} + +main "$@" diff --git a/package/luci-app-dawnline/Makefile b/package/luci-app-dawnline/Makefile new file mode 100644 index 0000000..141828a --- /dev/null +++ b/package/luci-app-dawnline/Makefile @@ -0,0 +1,49 @@ +# SPDX-License-Identifier: MIT +# +# Dawnline — AmneziaWG access server for OpenWrt with a LuCI admin UI and a +# personal self-service portal. + +include $(TOPDIR)/rules.mk + +PKG_NAME:=luci-app-dawnline +PKG_VERSION:=0.1.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 +# 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 +# and web files, so the SDK has nothing to build for them, and as build +# dependencies ip-full (iproute2) and kmod-veth would pull in the whole kernel. +# OpenWrt 25.12's luci.mk wants a version on each; (>=0) means any. +LUCI_EXTRA_DEPENDS:=luci-base (>=0), rpcd-mod-ucode (>=0), ucode (>=0), ucode-mod-fs (>=0), ucode-mod-uci (>=0), \ + ucode-mod-ubus (>=0), ucode-mod-uloop (>=0), ip-full (>=0), kmod-veth (>=0), uhttpd (>=0) +LUCI_PKGARCH:=all +# The web bundles are already minified by esbuild (LuCI's jsmin cannot parse modern JS). +LUCI_MINIFY_JS:=0 +LUCI_MINIFY_CSS:=0 + +PKG_MAINTAINER:=tickcount +LUCI_MAINTAINER:=tickcount +LUCI_URL:=https://github.com/tickcount/luci-app-dawnline + +define Package/luci-app-dawnline/conffiles +/etc/config/dawnline +endef + +define Package/luci-app-dawnline/prerm +#!/bin/sh +[ -n "$${IPKG_INSTROOT}" ] && exit 0 +# An upgrade keeps everything running; only a removal tears down. +[ "$$1" = "upgrade" ] && exit 0 +/etc/init.d/dawnline stop 2>/dev/null +/usr/bin/dawnline teardown 2>/dev/null +exit 0 +endef + +include $(TOPDIR)/feeds/luci/luci.mk + +# call BuildPackage - OpenWrt buildroot signature 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 new file mode 100644 index 0000000..e4c7f12 --- /dev/null +++ b/package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/app.js @@ -0,0 +1,19 @@ +// Generated from dawnline/web — do not edit by hand. +'use strict'; +'require baseclass'; +'require dom'; +'require form'; +'require poll'; +'require rpc'; +'require uci'; +'require ui'; +var yn=Object.create;var Ft=Object.defineProperty;var kn=Object.getOwnPropertyDescriptor;var $n=Object.getOwnPropertyNames;var _n=Object.getPrototypeOf,Mn=Object.prototype.hasOwnProperty;var Ln=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports);var Sn=(s,t,a,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $n(t))!Mn.call(s,i)&&i!==a&&Ft(s,i,{get:()=>t[i],enumerable:!(n=kn(t,i))||n.enumerable});return s};var Tn=(s,t,a)=>(a=s!=null?yn(_n(s)):{},Sn(t||!s||!s.__esModule?Ft(a,"default",{value:s,enumerable:!0}):a,s));var Jt=Ln((Vt,Yt)=>{"use strict";var Kt=(function(){var s=function(y,D){var T=236,f=17,g=y,k=a[D],c=null,p=0,C=null,v=[],b={},j=function(M,S){p=g*4+17,c=(function(x){for(var E=new Array(x),A=0;A=7&&ie(M),C==null&&(C=yt(g,k,v)),he(C,S)},q=function(M,S){for(var x=-1;x<=7;x+=1)if(!(M+x<=-1||p<=M+x))for(var E=-1;E<=7;E+=1)S+E<=-1||p<=S+E||(0<=x&&x<=6&&(E==0||E==6)||0<=E&&E<=6&&(x==0||x==6)||2<=x&&x<=4&&2<=E&&E<=4?c[M+x][S+E]=!0:c[M+x][S+E]=!1)},H=function(){for(var M=0,S=0,x=0;x<8;x+=1){j(!0,x);var E=i.getLostPoint(b);(x==0||M>E)&&(M=E,S=x)}return S},Z=function(){for(var M=8;M>x&1)==1;c[Math.floor(x/3)][x%3+p-8-3]=E}for(var x=0;x<18;x+=1){var E=!M&&(S>>x&1)==1;c[x%3+p-8-3][Math.floor(x/3)]=E}},ue=function(M,S){for(var x=k<<3|S,E=i.getBCHTypeInfo(x),A=0;A<15;A+=1){var I=!M&&(E>>A&1)==1;A<6?c[A][8]=I:A<8?c[A+1][8]=I:c[p-15+A][8]=I}for(var A=0;A<15;A+=1){var I=!M&&(E>>A&1)==1;A<8?c[8][p-A-1]=I:A<9?c[8][15-A-1+1]=I:c[8][15-A-1]=I}c[p-8][8]=!M},he=function(M,S){for(var x=-1,E=p-1,A=7,I=0,G=i.getMaskFunction(S),U=p-1;U>0;U-=2)for(U==6&&(U-=1);;){for(var te=0;te<2;te+=1)if(c[E][U-te]==null){var de=!1;I>>A&1)==1);var F=G(E,U-te);F&&(de=!de),c[E][U-te]=de,A-=1,A==-1&&(I+=1,A=7)}if(E+=x,E<0||p<=E){E-=x,x=-x;break}}},Te=function(M,S){for(var x=0,E=0,A=0,I=new Array(S.length),G=new Array(S.length),U=0;U=0?qt.getAt(Ut):0}}for(var Gt=0,F=0;FU*8)throw"code length overflow. ("+A.getLengthInBits()+">"+U*8+")";for(A.getLengthInBits()+4<=U*8&&A.put(0,4);A.getLengthInBits()%8!=0;)A.putBit(!1);for(;!(A.getLengthInBits()>=U*8||(A.put(T,8),A.getLengthInBits()>=U*8));)A.put(f,8);return Te(A,E)};b.addData=function(M,S){S=S||"Byte";var x=null;switch(S){case"Numeric":x=h(M);break;case"Alphanumeric":x=m(M);break;case"Byte":x=u(M);break;case"Kanji":x=$(M);break;default:throw"mode:"+S}v.push(x),C=null},b.isDark=function(M,S){if(M<0||p<=M||S<0||p<=S)throw M+","+S;return c[M][S]},b.getModuleCount=function(){return p},b.make=function(){if(g<1){for(var M=1;M<40;M++){for(var S=l.getRSBlocks(M,k),x=d(),E=0;E"u"?M*4:S;var x="";x+='";for(var A=0;A';x+=""}return x+="",x+="
",x},b.createSvgTag=function(M,S,x,E){var A={};typeof arguments[0]=="object"&&(A=arguments[0],M=A.cellSize,S=A.margin,x=A.alt,E=A.title),M=M||2,S=typeof S>"u"?M*4:S,x=typeof x=="string"?{text:x}:x||{},x.text=x.text||null,x.id=x.text?x.id||"qrcode-description":null,E=typeof E=="string"?{text:E}:E||{},E.text=E.text||null,E.id=E.text?E.id||"qrcode-title":null;var I=b.getModuleCount()*M+S*2,G,U,te,de,F="",fe;for(fe="l"+M+",0 0,"+M+" -"+M+",0 0,-"+M+"z ",F+=''+R(E.text)+"":"",F+=x.text?''+R(x.text)+"":"",F+='',F+='"u"?M*4:S;var x=b.getModuleCount()*M+S*2,E=S,A=x-S;return B(x,x,function(I,G){if(E<=I&&I"u"?M*4:S;var E=b.getModuleCount()*M+S*2,A="";return A+="",A};var R=function(M){for(var S="",x=0;x":S+=">";break;case"&":S+="&";break;case'"':S+=""";break;default:S+=E;break}}return S},oe=function(M){var S=1;M=typeof M>"u"?S*2:M;var x=b.getModuleCount()*S+M*2,E=M,A=x-M,I,G,U,te,de,F={"██":"█","█ ":"▀"," █":"▄"," ":" "},fe={"██":"▀","█ ":"▀"," █":" "," ":" "},me="";for(I=0;I=A?fe[de]:F[de];me+=` +`}return x%2&&M>0?me.substring(0,me.length-x-1)+Array(x+1).join("▀"):me.substring(0,me.length-1)};return b.createASCII=function(M,S){if(M=M||1,M<2)return oe(S);M-=1,S=typeof S>"u"?M*2:S;var x=b.getModuleCount()*M+S*2,E=S,A=x-S,I,G,U,te,de=Array(M+1).join("██"),F=Array(M+1).join(" "),fe="",me="";for(I=0;I>>8),k.push(C&255)):k.push(f)}}return k}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},a={L:1,M:0,Q:3,H:2},n={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},i=(function(){var y=[[],[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]],D=1335,T=7973,f=21522,g={},k=function(c){for(var p=0;c!=0;)p+=1,c>>>=1;return p};return g.getBCHTypeInfo=function(c){for(var p=c<<10;k(p)-k(D)>=0;)p^=D<=0;)p^=T<5&&(C+=3+j-5)}for(var v=0;v=256;)g-=255;return y[g]},f})();function r(y,D){if(typeof y.length>"u")throw y.length+"/"+D;var T=(function(){for(var g=0;g"u")throw"bad rs block @ typeNumber:"+g+"/errorCorrectionLevel:"+k;for(var p=c.length/3,C=[],v=0;v>>7-f%8&1)==1},T.put=function(f,g){for(var k=0;k>>g-k-1&1)==1)},T.getLengthInBits=function(){return D},T.putBit=function(f){var g=Math.floor(D/8);y.length<=g&&y.push(0),f&&(y[g]|=128>>>D%8),D+=1},T},h=function(y){var D=t.MODE_NUMBER,T=y,f={};f.getMode=function(){return D},f.getLength=function(c){return T.length},f.write=function(c){for(var p=T,C=0;C+2>>8&255)*192+(v&255),c.put(v,13),C+=2}if(C>>8)},D.writeBytes=function(T,f,g){f=f||0,g=g||T.length;for(var k=0;k0&&(T+=","),T+=y[f];return T+="]",T},D},N=function(){var y=0,D=0,T=0,f="",g={},k=function(p){f+=String.fromCharCode(c(p&63))},c=function(p){if(!(p<0)){if(p<26)return 65+p;if(p<52)return 97+(p-26);if(p<62)return 48+(p-52);if(p==62)return 43;if(p==63)return 47}throw"n:"+p};return g.writeByte=function(p){for(y=y<<8|p&255,D+=8,T+=1;D>=6;)k(y>>>D-6),D-=6},g.flush=function(){if(D>0&&(k(y<<6-D),y=0,D=0),T%3!=0)for(var p=3-T%3,C=0;C=D.length){if(g==0)return-1;throw"unexpected end of file./"+g}var p=D.charAt(T);if(T+=1,p=="=")return g=0,-1;if(p.match(/^\s$/))continue;f=f<<6|c(p.charCodeAt(0)),g+=6}var C=f>>>g-8&255;return g-=8,C};var c=function(p){if(65<=p&&p<=90)return p-65;if(97<=p&&p<=122)return p-97+26;if(48<=p&&p<=57)return p-48+52;if(p==43)return 62;if(p==47)return 63;throw"c:"+p};return k},V=function(y,D){var T=y,f=D,g=new Array(y*D),k={};k.setPixel=function(v,b,j){g[b*T+v]=j},k.write=function(v){v.writeString("GIF87a"),v.writeShort(T),v.writeShort(f),v.writeByte(128),v.writeByte(0),v.writeByte(0),v.writeByte(0),v.writeByte(0),v.writeByte(0),v.writeByte(255),v.writeByte(255),v.writeByte(255),v.writeString(","),v.writeShort(0),v.writeShort(0),v.writeShort(T),v.writeShort(f),v.writeByte(0);var b=2,j=p(b);v.writeByte(b);for(var q=0;j.length-q>255;)v.writeByte(255),v.writeBytes(j,q,255),q+=255;v.writeByte(j.length-q),v.writeBytes(j,q,j.length-q),v.writeByte(0),v.writeString(";")};var c=function(v){var b=v,j=0,q=0,H={};return H.write=function(Z,ee){if(Z>>>ee)throw"length over";for(;j+ee>=8;)b.writeByte(255&(Z<>>=8-j,q=0,j=0;q=Z<0&&b.writeByte(q)},H},p=function(v){for(var b=1<>6,128|o&63):o<55296||o>=57344?n.push(224|o>>12,128|o>>6&63,128|o&63):(i++,o=65536+((o&1023)<<10|a.charCodeAt(i)&1023),n.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63))}return n}return t(s)}})();(function(s){typeof define=="function"&&define.amd?define([],s):typeof Vt=="object"&&(Yt.exports=s())})(function(){return Kt})});function $t(s,t){return s==null||s===!1||s===""||(Array.isArray(s)?s.forEach(a=>$t(a,t)):t.push(s instanceof Node?s:String(s))),t}function e(s,t,a){let n=window.E,i=t!=null&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Node);return!i&&a===void 0?n(s,{},$t(t,[])):n(s,i?t:{},$t(a,[]))}function W(s,t=[]){let a=rpc.declare({object:"luci.dawnline",method:s,params:t});return async(...n)=>{let i=await a(...n);if(i&&typeof i=="object"&&typeof i.error=="string")throw new Error(i.error);return i}}var En=W("logs_clear",["person","device","category","older_days"]),Cn=(s={})=>En(s.person??"",s.device??"",s.category??"",s.older_days??""),Dn=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"]});async function An(s,t){let n=[s,...["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],i=await Dn(...n);if(i&&typeof i.error=="string")throw new Error(i.error);return i}var Pn=W("status",["days"]),zn=0;async function Nn(s){let t=await Pn(s);return zn=Date.now(),t}var P={personUpdate:An,settingsGet:W("settings_get"),settingsUpdate:W("settings_update",["values"]),serviceSet:W("service_set",["id","name","address","ports"]),serviceDelete:W("service_delete",["id"]),geoClear:W("geo_clear"),events:W("events",["limit"]),logsClear:Cn,interfaces:W("interfaces",["id"]),serverInterfaces:W("server_interfaces",["id","auto_wan","wan_device","auto_lan","lan_devices","lan_like"]),usageClear:W("usage_clear",["scope","id"]),uninstall:W("uninstall",["confirm"]),status:Nn,setupDefaults:W("setup_defaults"),serverCreate:W("server_create",["id","name","ifname","port","subnet","endpoint","mtu","preset","lan_zone","wan_zone","lan_like","portal_enabled","portal_port"]),serverObfuscation:W("server_obfuscation",["id","preset"]),serverUpdate:W("server_update",["id","values"]),serverDelete:W("server_delete",["id"]),personCreate:W("person_create",["name","slug","server","access","device_limit","expires","quota_gb","quota_period"]),personPause:W("person_pause",["id","paused"]),personRegen:W("person_regen",["id"]),personDelete:W("person_delete",["id"]),personUsage:W("person_usage",["id","days"]),pauseAll:W("pause_all",["paused"]),deviceCreate:W("device_create",["person","name","kind"]),deviceConfig:W("device_config",["id"]),deviceUpdate:W("device_update",["id","name","disabled"]),deviceDelete:W("device_delete",["id"]),deviceRotate:W("device_rotate",["id"]),apply:W("apply"),health:W("health"),healthFix:W("health_fix",["id"]),backupList:W("backup_list"),backupCreate:W("backup_create"),backupRestore:W("backup_restore",["name"]),backupDelete:W("backup_delete",["name"]),backupRead:W("backup_read",["name"]),backupUpload:W("backup_upload",["data"]),exportJson:W("export"),importJson:W("import",["data"]),updatesStatus:W("updates_status"),updatesRun:W("updates_run",["what"])};var Wt={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:'',shield:'',shieldplus:'',lock:'',zap:'',check:'',alert:'',x:'',globe:'',home:'',open:'',file:'',search:'',network:'',moon:'',chevron:'',clock:'',calendar:'',minus:'',more:'',pin:'',activity:''};function _t(s,t="dl-icon"){let a=Wt[s]??Wt.phone;return``}function w(s,t="dl-icon"){let a=document.createElement("span");return a.className="dl-icon-wrap",a.innerHTML=_t(s,t),a}function z(s,t,a="neutral",n={}){let{disabled:i,...o}=n,r=e("button",{class:`cbi-button cbi-button-${a}`,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){X(Mt(d),"error")}finally{r.disabled=!1,r.classList.remove("spinning")}}}},s);return r.disabled=!!i,r}function ye(s,t,a,n="neutral",i=""){return z([w(s),e("span",{class:"dl-btn-label"},t)],a,n,{title:t,class:`cbi-button cbi-button-${n} dl-icon-btn ${i}`.trim()})}function X(s,t="info",a=0){let n=document.querySelector(".dl-toasts");n||(n=e("div",{class:"dl-toasts dl-root",role:"status","aria-live":"polite"}),document.body.appendChild(n));let i=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}`},[i?w(i):"",e("span",{},s),t==="error"?e("button",{type:"button","aria-label":"Close",click:o},w("x")):""]);n.appendChild(r),requestAnimationFrame(()=>r.classList.add("show")),setTimeout(o,a||(t==="error"?8e3:t==="warning"?5e3:2600))}function Mt(s){return s instanceof Error?s.message:String(s)}async function O(s,t){try{let a=await s();return t&&X(t,"success",3500),a}catch(a){X(Mt(a),"error",1e4);return}}function ne(s,t,a,n=""){ui.showModal(s,[e("div",{class:`dl-modal ${n}`},t),e("div",{class:"button-row"},a)])}function Y(){ui.hideModal()}function ae(s,t,a="Confirm",n=!1){return new Promise(i=>{ne(s,t,[e("button",{class:"cbi-button cbi-button-neutral",type:"button",click:()=>{Y(),i(!1)}},"Cancel")," ",e("button",{class:`cbi-button ${n?"cbi-button-negative":"cbi-button-positive"}`,type:"button",click:()=>{Y(),i(!0)}},a)])})}async function re(s,t="Copied to clipboard"){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(s);else{let a=e("textarea",{style:"position:fixed;opacity:0"},s);document.body.appendChild(a),a.select(),document.execCommand("copy"),a.remove()}X(t,"success",2500)}catch(a){X(Mt(a),"error")}}function ge(s,t,a="text/plain"){let n=globalThis,i=typeof t=="string"?new n.Blob([t],{type:a}):t,o=URL.createObjectURL(i),r=e("a",{href:o,download:s,style:"display:none"});document.body.appendChild(r),r.click(),setTimeout(()=>{URL.revokeObjectURL(o),r.remove()},1e3)}function Ee(s,t){let a={ok:"success",warn:"warning",error:"error",info:"notice"}[s];return e("div",{class:`alert-message ${a}`},t)}function Pe(s,t=""){let a=e("div",{class:t});return a.innerHTML=s,a}function Lt(s,t){return new Promise(a=>{let n=e("input",{type:"file",accept:s,style:"display:none"});n.addEventListener("cancel",()=>{n.remove(),a(null)}),n.addEventListener("change",()=>{let i=n.files?.[0];if(n.remove(),!i)return a(null);let o=new FileReader;o.onload=()=>{let r=String(o.result??"");a({name:i.name,data:t==="base64"?r.replace(/^data:[^,]*,/,""):r})},o.onerror=()=>a(null),t==="base64"?o.readAsDataURL(i):o.readAsText(i)}),document.body.appendChild(n),n.click()})}function ke(s,t){let a=document.querySelector(".dl-dd");if(a&&(a.dlClose?a.dlClose():a.remove(),a.dlAnchor===s))return;let n=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:()=>{h(),m.run()}},[m.icon??"",e("span",{},m.label)]):e("hr")));document.body.appendChild(n);let i=s.getBoundingClientRect(),o=n.offsetWidth,r=n.offsetHeight;n.style.top=`${i.bottom+6+r>window.innerHeight-8&&i.top-6-r>8?i.top-6-r:i.bottom+6}px`,n.style.left=`${Math.max(8,Math.min(i.right-o,window.innerWidth-o-8))}px`;let l=m=>{!n.contains(m.target)&&!s.contains(m.target)&&h()},d=m=>{m.key==="Escape"&&h()};n.dlAnchor=s,n.dlClose=h;function h(){n.remove(),document.removeEventListener("mousedown",l,!0),document.removeEventListener("keydown",d,!0),window.removeEventListener("scroll",h,!0)}setTimeout(()=>{document.addEventListener("mousedown",l,!0),document.addEventListener("keydown",d,!0),window.addEventListener("scroll",h,!0)}),n.querySelector("button")?.focus({preventScroll:!0})}var Qt=Tn(Jt(),1),Rn='';function Ie(s,t=3,a=!0){let n=(0,Qt.default)(0,s.length>300?"Q":"H");n.addData(s,"Byte"),n.make();let i=n.getModuleCount(),o=i+t*2,r=a?Math.round(i*.22):0;r&&(i-r)%2&&r++;let l=(i-r)/2,d=l+r,h=($,_)=>r>0&&$>=l&&$=l&&_${Rn}`}return`${u}`}var Hn={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:""},In={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 Bn(s){let t={};for(let[a,n]of Object.entries(In))s[a]!=null&&s[a]!==""&&(t[n]=String(s[a]));return t}function jn(s,t){let a=s.amnezia,n=a.obfuscation??{},i=d=>n[d]!=null&&n[d]!==""?String(n[d]):Hn[d],o=a.host.replace(/^\[(.*)\]$/,"$1"),r={H1:i("h1"),H2:i("h2"),H3:i("h3"),H4:i("h4"),I1:i("i1"),I2:i("i2"),I3:i("i3"),I4:i("i4"),I5:i("i5"),Jc:i("jc"),Jmin:i("jmin"),Jmax:i("jmax"),S1:i("s1"),S2:i("s2"),S3:i("s3"),S4:i("s4"),...Bn(n),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:s.conf.replace(/\r?\n/g,`\r +`),hostName:o,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},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(r),port:String(a.port),protocol_version:n.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:o};return a.dns[0]&&(l.dns1=a.dns[0]),a.dns[1]&&(l.dns2=a.dns[1]),l}function On(s){let t="";for(let a=0;a"u")return null;try{let a=new t.Blob([s]).stream().pipeThrough(new t.CompressionStream("deflate")),n=new Uint8Array(await new t.Response(a).arrayBuffer()),i=new Uint8Array(4+n.length);return new DataView(i.buffer).setUint32(0,s.length,!1),i.set(n,4),i}catch{return null}}async function Zt(s,t,a=!0){let n=new TextEncoder().encode(JSON.stringify(jn(s,t))),i=a?await qn(n):null;return`vpn://${On(i??n)}`}function K(s){if(!s||s<0)return"0 B";let t=["B","KB","MB","GB","TB"],a=0,n=s;for(;n>=1024&&a=100||a===0?Math.round(n):n.toFixed(1)} ${t[a]}`}function $e(s){let t=s*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 ce(s,t=Date.now()/1e3){if(!s)return"never";let a=Math.max(0,Math.round(t-s));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(s*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function Xt(s){if(!s||s<0)return"—";let t=Math.floor(s/86400),a=Math.floor(s%86400/3600),n=Math.floor(s%3600/60);return t?`${t}d ${a}h`:a?`${a}h ${n}m`:`${n}m`}function St(s){let t=new Date(s*1e3),a=new Date,n=t.toDateString()===a.toDateString(),i=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});return n?i:`${t.toLocaleDateString("en-GB",{day:"numeric",month:"short"})} ${i}`}function _e(s){if(!s)return"";let[t,a,n]=s.split("-").map(Number);return new Date(t,a-1,n).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function ze(s,t=Date.now()){if(!s)return null;let[a,n,i]=s.split("-").map(Number),o=new Date(a,n-1,i,23,59,59).getTime();return Math.ceil((o-t)/864e5)}var Be={lan:"Home network",internet:"Internet",both:"Home network + Internet"},en={lan:"LAN",internet:"Internet",both:"LAN + Internet"},tn=["computer","phone","tablet","router","other"],Me={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},Tt={active:"Active",paused:"Paused",paused_all:"Paused (everyone)",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server"};function Le(s){let t=s.trim().split(/\s+/).filter(Boolean);if(!t.length)return"?";let a=t[0][0]??"",n=t.length>1?t[t.length-1][0]??"":t[0][1]??"";return(a+n).toUpperCase()}var Ne=null;function le(s,t){let a=n=>{Ne??(Ne=document.body.appendChild(e("div",{class:"dl-tip dl-tip-float dl-root"}))),Ne.replaceChildren(...t().map(i=>typeof i=="string"?document.createTextNode(i):i)),Ne.style.display="",Ne.style.left=`${n.clientX}px`,Ne.style.top=`${n.clientY-10}px`};s.addEventListener("mouseenter",a),s.addEventListener("mousemove",a),s.addEventListener("mouseleave",()=>Ne&&(Ne.style.display="none"))}function nn(s,t=120,a=26){let n=Math.max(1,...s),i=e("div",{class:"dl-spark"});i.style.width=`${t}px`,i.style.height=`${a}px`;let o=Date.now();return s.forEach((r,l)=>{let d=e("i");d.style.height=`${Math.max(6,r/n*100)}%`,r||d.classList.add("zero");let h=s.length-1-l,m=new Date(o-h*864e5);le(d,()=>[e("div",{class:"dl-tip-title"},h===0?"Today":h===1?"Yesterday":m.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})),e("div",{class:"dl-muted"},K(r))]),i.appendChild(d)}),i}var Un={connect:"connections",disconnect:"connections",roam:"connections",device_added:"devices",device_removed:"devices",devices_removed:"devices",person_added:"people",person_removed:"people",person_changed:"people",paused:"people",resumed:"people",paused_all:"people",resumed_all:"people",server_down:"problems",server_up:"problems",portal_blocked:"problems"},je=["connections","devices","people","problems"],Oe={connections:"Connections",devices:"Devices",people:"People",problems:"Problems"},an={connections:"Connects, disconnects and IP changes",devices:"Devices added and removed",people:"People added, changed, paused",problems:"Tunnel down, blocked portal sign-ins"},rt=s=>Un[s]??"problems";function Gn(s){let t=new Map(s.people.map(n=>[n.id,n.name])),a=new Map(s.people.flatMap(n=>n.devices.map(i=>[i.id,i.name])));return{people:t,devices:a}}function Fn(s){let t=s==null?"":String(s);return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function ve(s,t,a,n=""){let i=Gn(s),o=t.map(m=>({time:new Date(m.ts*1e3).toISOString(),category:rt(m.type),type:m.type,person:m.person?i.people.get(m.person)??m.person:"",device:m.device?i.devices.get(m.device)??m.device:"",detail:m.detail??"",where:m.where??""})),r=new Date().toISOString().slice(0,10),l=`dawnline-activity${n?`-${n}`:""}-${r}.${a}`;if(a==="json"){ge(l,JSON.stringify(o,null,2),"application/json");return}let d=["time","category","type","person","device","detail","where"],h=[d.join(","),...o.map(m=>d.map(u=>Fn(m[u])).join(","))].join(` +`);ge(l,h,"text/csv")}var Wn=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]];function Ce(s,t,a,n,i){let o=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...je.map(l=>e("option",{value:l,selected:l===i?"selected":null},Oe[l]))]),r=e("select",{class:"cbi-input-select"},Wn.map(([l,d])=>e("option",{value:l},d)));ne(s,[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"),o]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Which events"),r])],[e("button",{class:"cbi-button cbi-button-neutral",click:Y},"Cancel")," ",z("Clear",async()=>{let l=await O(()=>P.logsClear({...a,category:o.value,older_days:r.value}));l&&(Y(),X(l.removed?`${l.removed} event${l.removed===1?"":"s"} removed`:"Nothing matched","success",3e3),n())},"negative")])}function qe(s,t,a,n){let i=s==="device"?`Clears ${a}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:s==="person"?`Clears ${a}'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(s==="all"?"Reset all traffic history?":`Reset traffic history for ${a}?`,[e("p",{class:"dl-muted"},i)],[e("button",{class:"cbi-button cbi-button-neutral",click:Y},"Cancel")," ",z("Reset",async()=>{await O(()=>P.usageClear(s,t),"Traffic history reset")&&(Y(),n())},"negative")])}var lt=null;function Kn(s){return s?new Date(s*1e3).toLocaleString("en-GB",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function sn(s,t,a=!0){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},s),e("button",{type:"button",class:`dl-kvrow-v copy${a?" dl-mono":""}`,title:"Copy",click:()=>re(t,`${s} copied`)},[e("span",{},t),w("copy")])])}function dt(s,t){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},s),e("span",{class:"dl-kvrow-v"},t)])}function on(s,t){if(/^\s*\[.+\]\s*$/.test(s))return e("span",{class:"dl-conf-sec"},s);let a=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(s);if(!a)return document.createTextNode(s);let n=/^(\s*)(PrivateKey|PresharedKey)\b/.test(s);return e("span",{},[e("span",{class:"dl-conf-k"},a[1])," ",n&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):a[2]])}function Vn(s){let t=!1,a=e("pre",{class:"dl-conf"}),n=()=>dom.content(a,s.conf.split(` +`).flatMap((r,l)=>l?[` +`,on(r,t)]:[on(r,t)])),i=e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),t=!t,dom.content(i,[w(t?"x":"key"),t?"Hide key":"Show key"]),n()}},[w("key"),"Show key"]);n();let o=new Blob([s.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"},s.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${o} bytes · import it in the app`)]),z([w("download")," Download"],()=>ge(s.filename,s.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[w("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),i,e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),re(s.conf,"Configuration copied")}},[w("copy"),"Copy"])]),a])])}async function Et(s){if(!s.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 t=await Zt(s,`${s.server} · ${s.person} · ${s.name}`),a={qr:()=>e("div",{class:"dl-qr-pane"},[Pe(Ie(s.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"},t),z("Copy",()=>re(t,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>Vn(s)},n=e("div",{class:"dl-connect-body"}),i=e("div",{class:"dl-seg"}),o=r=>{i.querySelectorAll("button").forEach(l=>l.classList.toggle("on",l.dataset.id===r)),dom.content(n,a[r]())};for(let[r,l]of[["qr","QR code"],["key","Key"],["file","File"]])i.appendChild(e("button",{type:"button","data-id":r,click:()=>o(r)},l));return o("qr"),e("div",{class:"dl-stack gap12"},[i,n])}function Yn(s,t,a,n){lt?.close();let i=e("aside",{class:"dl-drawer",role:"dialog","aria-modal":"true"},[e("div",{class:"dl-drawer-head"},[s,e("button",{type:"button",class:"dl-drawer-x","aria-label":"Close",click:()=>l()},w("x"))]),e("div",{class:"dl-drawer-body"},t),a?e("div",{class:"dl-drawer-foot"},a):""]),o=e("div",{class:"dl-drawer-overlay dl-root",click:h=>{h.target===o&&l()}},i),r=h=>{h.key==="Escape"&&!document.body.classList.contains("modal-overlay-active")&&l()};function l(){document.removeEventListener("keydown",r),o.classList.remove("open"),setTimeout(()=>o.remove(),220),lt===d&&(lt=null),n()}let d={close:l,panel:i};return document.addEventListener("keydown",r),document.body.appendChild(o),requestAnimationFrame(()=>o.classList.add("open")),lt=d,d}var rn={connect:["ok","Connected"],disconnect:["","Went offline"],roam:["","Changed network"],device_added:["accent","Added"],device_removed:["","Removed"]};function Jn(s,t){let a=s.filter(n=>n.device===t&&rn[n.type]).reverse().slice(0,12);return a.length?e("div",{class:"dl-dev-log"},a.map(n=>{let[i,o]=rn[n.type],r=n.type==="connect"?[n.detail?e("span",{class:"dl-mono"},` ${n.detail}`):"",n.where?e("span",{class:"dl-faint"},` · ${n.where}`):""]:n.type==="roam"?[e("span",{class:"dl-mono dl-faint"},` ${n.detail??""}`)]:n.type==="device_added"?[e("span",{class:"dl-faint"},(n.detail??"").includes("(portal)")?" from the portal":" by you")]:[],l=new Date(n.ts*1e3);return e("div",{class:"dl-dev-log-row"},[e("span",{class:`dl-ev-dot ${i}`}),e("span",{class:"dl-row-main"},[e("span",{},o),...r]),e("span",{class:"dl-faint dl-nowrap",title:l.toLocaleString()},ce(n.ts))])})):e("div",{class:"dl-sub"},"No activity yet.")}function Qn(s){return s.disabled?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),"Disabled"]):s.online?e("span",{class:"dl-dstat ok"},[e("i",{class:"dot ok"}),`Online from ${s.endpoint}`]):s.handshake?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),`Last seen ${ce(s.handshake)}`]):e("span",{class:"dl-dstat warn"},[e("i",{class:"dot warn"}),"Waiting for the first connection"])}async function De(s,t,a,n){let i=await O(()=>P.deviceConfig(t.id));if(!i)return;let o=t,r=s,l=await Et(i),d=e("div",{class:"dl-drawer-title"}),h=e("div",{}),m=e("div",{}),u=e("div",{class:"dl-live"}),$=e("div",{},e("div",{class:"dl-sub"},"Loading…")),_=[],N=async()=>{let g=await P.events(5e3).catch(()=>null);g&&(_=g.events.filter(k=>k.device===o.id),dom.content($,Jn(g.events,o.id)))},J=()=>{let g=n?.points.find(c=>c.device===o.id&&c.ip===o.endpoint);dom.content(d,[e("span",{class:`dl-dcard-ic${o.online?" on":""}`},w(o.kind)),e("div",{class:"dl-stack"},[e("div",{class:"dl-title-row"},[e("h3",{},o.name),z([w("edit")],()=>B(),"neutral",{title:"Rename",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),e("span",{class:"dl-sub"},[`${r.name} · ${Me[o.kind]}`])])]);let k=o.spark.reduce((c,p)=>c+p,0);dom.content(h,e("div",{class:"dl-dstats"},[e("div",{class:"dl-dstats-cell wide"},[e("span",{class:"dl-metric-label"},"Status"),Qn(o)]),e("div",{class:"dl-dstats-cell"},[e("span",{class:"dl-metric-label"},"This month"),e("b",{},K(o.month[0]+o.month[1])),e("span",{class:"dl-sub dl-mono"},`↓ ${K(o.month[1])} ↑ ${K(o.month[0])}`)]),e("div",{class:"dl-dstats-cell"},[e("span",{class:"dl-metric-label"},"Last 7 days"),e("b",{},K(k)),nn(o.spark,120,22)])])),dom.content(m,e("div",{class:"dl-kv2"},[sn("Tunnel address",o.address),o.hostname&&r.access!=="internet"?sn("Local address",o.hostname):"",o.endpoint?dt("Client IP",e("span",{},[e("span",{class:"dl-mono"},o.endpoint),g?e("span",{class:"dl-faint"},` · ${[g.city,g.org].filter(Boolean).join(" · ")}`):""])):"",dt("Total",e("span",{class:"dl-kv-act"},[`↓ ${K(o.total[1])} · ↑ ${K(o.total[0])}`,e("button",{type:"button",class:"dl-linkbtn danger",click:()=>qe("device",o.id,o.name,()=>setTimeout(V,300))},"Reset")])),dt("Added",`${Kn(o.created)} · ${o.created_by==="portal"?"from the portal":"by you"}`),dt("Public key",e("span",{class:"dl-mono dl-faint"},i.amnezia.client_pub_key?`${i.amnezia.client_pub_key.slice(0,16)}…`:"—"))])),dom.content(u,o.online?[e("i",{class:"dot ok"}),e("span",{class:"dl-ok"},"Connected")]:o.handshake?[e("i",{class:"dot"}),e("span",{class:"dl-muted"},`Last connected ${ce(o.handshake)}`)]:[e("i",{class:"dot warn pulse"}),e("span",{class:"dl-muted"},"Waiting for the first connection…")]),dom.content(y,[z([w(o.disabled?"play":"pause"),o.disabled?" Enable":" Disable"],async()=>{await O(()=>P.deviceUpdate(o.id,void 0,!o.disabled),o.disabled?"Device enabled":"Device disabled")&&await V()},"neutral",o.disabled?{}:{class:"cbi-button cbi-button-neutral dl-btn-warn"}),z([w("key")," New keys"],async()=>{if(!await ae("Generate new keys?","The current configuration on this device stops working until it is imported again.","Generate",!0))return;if(await O(()=>P.deviceRotate(o.id),"New keys generated")){a(),f.close();let p=await P.status(1),C=p.people.find(b=>b.id===r.id),v=C?.devices.find(b=>b.id===o.id);C&&v&&De(C,v,a,p.geo)}}),e("span",{class:"dl-spacer"}),z([w("trash")," Remove"],async()=>{await ae(`Remove ${o.name}?`,"The device is disconnected immediately and its configuration stops working.","Remove",!0)&&await O(()=>P.deviceDelete(o.id),"Device removed")&&(f.close(),a())},"negative")])},V=async()=>{let g=await P.status(1).catch(()=>null),k=g?.people.find(p=>p.id===r.id),c=k?.devices.find(p=>p.id===o.id);!g||!k||!c||(r=k,o=c,n=g.geo,J(),a())},B=()=>{let g=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"},g)])],[e("button",{class:"cbi-button cbi-button-neutral",click:Y},"Cancel")," ",z("Save",async()=>{await O(()=>P.deviceUpdate(o.id,g.value,void 0),"Renamed")&&(Y(),await V())},"positive")]),setTimeout(()=>g.select(),50)},y=e("div",{class:"dl-drawer-actions"}),D=e("div",{class:"dl-stack gap16"},[h,e("section",{class:"dl-dsec"},[e("div",{class:"dl-dsec-head"},[e("h4",{},"Connect"),u]),o.config_stale?e("div",{class:"dl-note warn"},[w("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]),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:()=>ve({people:[r]},_,"csv",o.id)},"Export"),e("button",{type:"button",class:"dl-linkbtn danger",click:()=>Ce(`Clear ${o.name}'s activity`,`Removes events about ${o.name}.`,{device:o.id},N)},"Clear"),e("a",{href:L.url("admin/network/dawnline/activity")},"All activity")])]),$]),e("section",{class:"dl-dsec"},[e("div",{class:"dl-dsec-head"},e("h4",{},"Details")),m])]);N();let T=window.setInterval(()=>{V(),N()},8e3),f=Yn(d,D,y,()=>clearInterval(T));J()}function Re(s,t){let a=e("input",{type:"text",class:"cbi-input-text",placeholder:Me.phone,maxlength:48}),n="phone",i=e("div",{class:"dl-kinds",role:"radiogroup","aria-label":"Type"},tn.map(r=>e("button",{type:"button",role:"radio",class:r===n?"on":"","aria-checked":r===n?"true":"false","data-kind":r,click:()=>{n=r,i.querySelectorAll("button").forEach(l=>{let d=l.dataset.kind===r;l.classList.toggle("on",d),l.setAttribute("aria-checked",d?"true":"false")}),a.placeholder=Me[r]}},[w(r),e("span",{},Me[r])]))),o=s.devices.length>=s.device_limit;ne(`Add a device for ${s.name}`,[o?e("p",{class:"dl-hint"},`${s.name} already has ${s.devices.length} of ${s.device_limit} devices. As admin you can still add one.`):"",e("div",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Type"),i]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Name"),a])],[e("button",{class:"cbi-button cbi-button-neutral",click:Y},"Cancel")," ",z("Add device",async()=>{let r=a.value.trim()||a.placeholder.replace(/^e\.g\. /,""),l=await O(()=>P.deviceCreate(s.id,r,n));if(!l)return;Y(),X(`${r} added`,"success",3e3),t();let d=await P.status(1),h=d.people.find(u=>u.id===s.id),m=h?.devices.find(u=>u.id===l.id);h&&m&&De(h,m,t,d.geo)},"positive")]),setTimeout(()=>a.focus(),50)}var Se=1080,Ye=1512,be=96,Zn="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",Xn="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",Ve=s=>s.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]);function ea(s,t,a){let n=new URL(a),i=n.pathname.slice(1),o=Math.min(92,Math.floor((Se-2*be)/(.58*(4+s.name.length)))),r=Se-2*be,l=392,d=40,h=Ie(a,2).replace("`${J}`;return``+m(be+82,be+42,36,"#a3a3a3",Ve(t))+m(be,276,o,"#ffffff",`Hi, ${Ve(s.name)}`,'font-weight="600"')+m(be,340,40,"#8a8a8a",`Scan to connect to ${Ve(t)}`)+``+h+`${Ve(i)}`+m(Se/2,l+r+156,34,"#737373",Ve(n.host),'text-anchor="middle"')+""}async function ta(s){let t=new Image;t.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(s)}`,await t.decode();let a=document.createElement("canvas");return a.width=Se,a.height=Ye,a.getContext("2d").drawImage(t,0,0,Se,Ye),new Promise((n,i)=>a.toBlob(o=>o?n(o):i(new Error("Could not draw the card")),"image/png"))}async function Je(s,t,a={}){if(!s.link){X("The personal portal is off. Turn it on in Settings.","warning");return}let n=s.link,i=await O(()=>ta(ea(s,t,n)));if(!i)return;let o=new File([i],`${s.id}-invite.png`,{type:"image/png"}),r=URL.createObjectURL(i),l=navigator,d=!!l.canShare?.({files:[o]}),h=()=>{URL.revokeObjectURL(r),Y()},m=d?z([w("link")," Share card"],async()=>{try{await l.share({files:[o],title:`Invite ${s.name}`})}catch{}},"positive"):z([w("download")," Download card"],()=>ge(o.name,i),"positive");ne(a.title??`Invite ${s.name}`,e("div",{class:"dl-invite"},[e("img",{src:r,alt:`Invite card for ${s.name}`}),e("div",{class:"dl-invite-side"},[e("p",{class:"dl-muted"},a.lead??`Send ${s.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:()=>re(n,"Personal link copied")},[e("span",{},n.replace(/^https:\/\//,"")),w("copy")]),...(s.links??[]).filter(u=>u!==n).map(u=>e("button",{type:"button",class:"dl-invite-link alt",title:"Copy this link",click:()=>re(u,"Link copied")},[e("span",{},u.replace(/^https?:\/\//,"")),e("span",{class:`dl-pill ${u.startsWith("http:")?"warn":""}`},u.startsWith("http:")?"HTTP":"Also"),w("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"},[m,z([w("copy")," Copy link"],()=>re(n,"Personal link copied"))])])]),[e("button",{class:"cbi-button cbi-button-neutral",click:h},"Done")],"wide")}var Ue=null,ct=!1;function Qe(s){return`${L.url("admin/network/dawnline/server")}?${s?`server=${encodeURIComponent(s)}&`:""}section=people`}function pe(s,t){return`${L.url("admin/network/dawnline/person")}?id=${encodeURIComponent(s)}${t?`&device=${encodeURIComponent(t)}`:""}`}function na(s){location.href=L.url(`admin/network/dawnline/${s}`)}function aa(s,t){let a=s?new Date(`${s}T12:00:00`):new Date,n=a.getTime()re(s.link,"Personal link copied")}),n.push({group:a,label:`Add device for ${s.name}`,icon:"plus",run:()=>location.href=`${pe(s.id)}&add=1`}),n.push({group:a,label:s.paused?`Resume ${s.name}`:`Pause ${s.name}`,icon:s.paused?"play":"pause",kbd:"P",run:async()=>{await O(()=>P.personPause(s.id,!s.paused),s.paused?`${s.name} resumed`:`${s.name} paused`),t()}}),n.push({group:a,label:"Extend access by 1 month",icon:"key",run:async()=>{await O(()=>P.personUpdate(s.id,{expires:aa(s.expires,1)}),"Access extended"),t()}}),n}function sa(s,t,a){let n=t.trim().toLowerCase(),i=[],o=s.people.filter(l=>!n||[l.name,l.id].some(d=>d.toLowerCase().includes(n)));for(let l of o.slice(0,6))i.push({group:"People",label:l.name,hint:`${en[l.access]} · ${l.online?`${l.online} online`:`${l.devices.length} devices`}`,avatar:Le(l.name),run:()=>location.href=pe(l.id)});for(let l of s.people)for(let d of l.devices){let h=[d.name,d.address,d.endpoint,d.hostname].join(" ").toLowerCase();n&&!h.includes(n)||!n&&!d.online||i.push({group:"Devices",label:d.name,hint:`${l.name} · ${d.address}${d.online?` · ${d.endpoint}`:""}`,icon:d.kind,run:()=>location.href=pe(l.id,d.id)})}(o.length===1||o.length&&n)&&i.push(...ia(o[0],a));let r=[["overview","Overview","globe"],["people","People","shield"],["activity","Activity","file"],["server","Server","key"],["health","Health","check"],["settings?section=backups","Backups","archive"],["settings","Settings","edit"]];for(let[l,d,h]of r)(!n||d.toLowerCase().includes(n))&&i.push({group:"Go to",label:d,icon:h,run:()=>na(l)});return(!n||"add person".includes(n))&&i.push({group:"Go to",label:"Add person",icon:"plus",run:()=>location.href=`${L.url("admin/network/dawnline/server")}?section=people&add=1`}),i}async function Ct(){if(ct)return;ct=!0;let s=e("input",{type:"text",class:"dl-pal-input",placeholder:"Search people, devices, IPs or actions…","aria-label":"Search"}),t=e("div",{class:"dl-pal-list",role:"listbox"}),a=e("div",{class:"dl-pal",role:"dialog","aria-label":"Command menu"},[e("label",{class:"dl-pal-search"},[w("search"),s,e("kbd",{},"Esc")]),t,e("div",{class:"dl-pal-foot"},[e("span",{},[e("kbd",{},"↑↓")," navigate"]),e("span",{},[e("kbd",{},"↵")," open"]),e("span",{},[e("kbd",{},"⌘K")," toggle"])])]),n=e("div",{class:"dl-pal-overlay dl-root"},a),i=[],o=0,r=()=>{n.remove(),document.removeEventListener("keydown",d,!0),ct=!1},l=()=>{let h=Ue?.st;if(!h){t.replaceChildren(e("div",{class:"dl-pal-empty"},"Loading…"));return}i=sa(h,s.value,()=>{Ue=null,r(),location.reload()}),o=Math.min(o,Math.max(0,i.length-1));let m=[],u="";i.forEach(($,_)=>{$.group!==u&&(u=$.group,m.push(e("div",{class:"dl-pal-group"},u)));let N=e("div",{class:`dl-pal-item${_===o?" sel":""}`,role:"option","aria-selected":_===o?"true":"false",click:()=>{r(),$.run()},mousemove:()=>{o!==_&&(o=_,l())}},[$.avatar?e("span",{class:"dl-avatar sm"},$.avatar):$.icon?w($.icon):e("span",{class:"dl-pal-ic"}),e("span",{class:"dl-pal-label"},[$.label,$.hint?e("span",{class:"dl-faint"},` · ${$.hint}`):""]),$.kbd?e("kbd",{},$.kbd):""]);m.push(N)}),i.length||m.push(e("div",{class:"dl-pal-empty"},"Nothing found.")),t.replaceChildren(...m),t.querySelector(".sel")?.scrollIntoView({block:"nearest"})},d=h=>{if(h.key==="Escape")h.preventDefault(),r();else if(h.key==="ArrowDown")h.preventDefault(),o=Math.min(i.length-1,o+1),l();else if(h.key==="ArrowUp")h.preventDefault(),o=Math.max(0,o-1),l();else if(h.key==="Enter"){h.preventDefault();let m=i[o];m&&(r(),m.run())}};if(s.addEventListener("input",()=>{o=0,l()}),n.addEventListener("click",h=>{h.target===n&&r()}),document.addEventListener("keydown",d,!0),document.body.appendChild(n),s.focus(),l(),!Ue||Date.now()-Ue.at>1e4){let h=await P.status(1).catch(()=>null);h&&(Ue={st:h,at:Date.now()}),ct&&l()}}function xe(s){s&&(Ue={st:s,at:Date.now()});let t=window;t.__dlPalette||(t.__dlPalette=!0,window.addEventListener("keydown",a=>{if(!location.pathname.includes("/admin/network/dawnline"))return;let n=/^(INPUT|TEXTAREA|SELECT)$/.test(a.target?.tagName??"")||a.target?.isContentEditable,i=(a.key==="k"||a.key==="K")&&(a.metaKey||a.ctrlKey),o=a.key==="/"&&!n&&!document.body.classList.contains("modal-overlay-active");!i&&!o||(a.preventDefault(),a.stopImmediatePropagation(),Ct())},!0))}var ln="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl",oa="https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",ra="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",la={online:0,"24h":86400,"7d":7*86400,"30d":30*86400},Ze=null;function da(s){let t=window;return s.appendChild(e("link",{rel:"stylesheet",href:`${ln}.css`})),t.maplibregl?Promise.resolve(t.maplibregl):Ze||(Ze=new Promise((a,n)=>{let i=e("script",{src:`${ln}.js`});i.onload=()=>t.maplibregl?a(t.maplibregl):n(new Error("MapLibre failed to load")),i.onerror=()=>{Ze=null,n(new Error("Could not load the map library (no internet access from this browser?)"))},s.appendChild(i)}),Ze)}function pt(){let s=document.documentElement.getAttribute("data-darkmode");return s!=null?s==="true":window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1}function ca(s,t,a=48){let n=(s[0]+t[0])/2,i=(s[1]+t[1])/2,o=t[0]-s[0],r=t[1]-s[1],l=Math.hypot(o,r)||1,d=Math.min(.25*l,12),h=n-r/l*d,m=i+o/l*d,u=[];for(let $=0;$<=a;$++){let _=$/a,N=1-_;u.push([N*N*s[0]+2*N*_*h+_*_*t[0],N*N*s[1]+2*N*_*m+_*_*t[1]])}return u}function pa(s,t){let a=new Map;for(let n of s.geo.points){if(s.person&&n.person!==s.person||(t==="online"?!n.online:s.now-n.ts>la[t]))continue;let i=a.get(n.device);(!i||n.online&&!i.online||n.online===i.online&&n.ts>i.ts)&&a.set(n.device,n)}return[...a.values()]}var Ge=class{constructor(t,a="online",n=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=a,this.status=e("div",{class:"dl-map-status"}),this.el=e("div",{class:"dl-geomap",style:`height:${n}px`},this.status)}async mount(t){this.data=t;try{this.gl=await da(this.el)}catch(a){this.status.textContent=a.message;return}this.map=new this.gl.Map({container:this.el,style:pt()?oa:ra,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",pt()?"#ededed":"#0d0d0d"],"circle-opacity":["case",["get","online"],.12,.06],"circle-stroke-width":1,"circle-stroke-color":["case",["get","online"],"#40c977",pt()?"#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":pt()?"#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]],a=-1,n=0,i=o=>{this.map&&(o-n>70&&(n=o,a=(a+1)%t.length,this.map.getLayer("dl-arc-flow")&&this.map.setPaintProperty("dl-arc-flow","line-dasharray",t[a])),this.anim=requestAnimationFrame(i))};this.anim=requestAnimationFrame(i)}groups(t){let a=new Map;for(let n of t){let i=`${n.asn||n.org||n.ip}|${n.city}|${n.cc}`,o=a.get(i);o||(o={key:i,lat:n.lat,lon:n.lon,city:n.city,country:n.country,cc:n.cc,asn:n.asn,org:n.org,online:!1,ts:0,points:[]},a.set(i,o)),o.points.push(n),o.online||(o.online=n.online),o.ts=Math.max(o.ts,n.ts)}return[...a.values()]}draw(){if(!this.map||!this.data||!this.map.getSource("dl-arcs"))return;let t=this.data,a=this.groups(pa(t,this.range)),n=t.geo.home;for(let r of this.markers)r.remove();this.markers=[];let i=new Map,o=a.map(r=>{let l=`${r.lat.toFixed(2)},${r.lon.toFixed(2)}`,d=i.get(l)??0;return i.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:n?o.map(({g:r,at:l})=>({type:"Feature",properties:{online:r.online},geometry:{type:"LineString",coordinates:ca([n.lon,n.lat],l)}})):[]}),n){let r=e("div",{class:"dl-mk-home",title:`Home router${n.city?` · ${n.city}`:""}${n.org?` · ${n.org}`:""}`});r.innerHTML=_t("home","dl-mk-home-ic"),this.markers.push(new this.gl.Marker({element:r}).setLngLat([n.lon,n.lat]).addTo(this.map))}for(let{g:r,at:l}of o){let d=r.points.length,h=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"})),u=!!n&&Math.abs(l[0]-n.lon)<.02&&Math.abs(l[1]-n.lat)<.02?[22,-16]:[0,0];h.addEventListener("click",$=>{$.stopPropagation(),this.openPopup(r,l,u)}),this.markers.push(new this.gl.Marker({element:h,offset:u}).setLngLat(l).addTo(this.map))}if(!this.fitted){let r=o.map(l=>l.at);n&&(r.length===0||this.range!=="online"||o.some(l=>l.g.online))&&r.push([n.lon,n.lat]),this.fit(r),this.fitted=!0}this.status.textContent=o.length||n?"":"No locations yet",this.status.style.display=this.status.textContent?"":"none"}fit(t){if(!t.length)return;let a=(d,h)=>{let m=Math.PI/180,u=(h[1]-d[1])*m,$=(h[0]-d[0])*m,_=Math.sin(u/2)**2+Math.cos(d[1]*m)*Math.cos(h[1]*m)*Math.sin($/2)**2;return 12742*Math.asin(Math.sqrt(_))},n=[t.reduce((d,h)=>d+h[0],0)/t.length,t.reduce((d,h)=>d+h[1],0)/t.length],i=t;if(t.length>=5){let d=[...t].sort((h,m)=>a(n,h)-a(n,m));i=d.slice(0,Math.ceil(d.length*.9))}if(Math.max(...i.map(d=>a(n,d)))<25){this.map.jumpTo({center:n,zoom:9.5});return}let r=new this.gl.LngLatBounds(i[0],i[0]);i.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,a,n=[0,0]){let i=this.data;this.popup?.remove();let o=[t.city,t.cc||t.country].filter(Boolean).join(", "),r=[...new Set(t.points.map(m=>m.person))],l=t.points.sort((m,u)=>Number(u.online)-Number(m.online)||u.ts-m.ts).map(m=>{let u=i.people.find(_=>_.id===m.person),$=u?.devices.find(_=>_.id===m.device);return e("button",{type:"button",class:"dl-pop-row",click:()=>this.cb.openDevice(m.person,m.device)},[e("span",{class:`dl-pop-dot${m.online?" on":""}`}),e("span",{class:"dl-pop-name"},[e("b",{},u?.name??m.person),` · ${$?.name??"device"}`]),e("span",{class:"dl-faint dl-nowrap"},m.online?"now":ce(m.ts,i.now))])}),d=e("div",{class:"dl-pop"},[e("div",{class:"dl-pop-head"},[e("span",{class:"dl-pop-net"},w("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 ${i.people.find(m=>m.id===r[0])?.name??"person"}`)]):""]),h=this.el.clientHeight||380;this.map.easeTo({center:a,offset:[0,Math.min(140,h*.32)],duration:300}),this.popup=new this.gl.Popup({offset:[n[0],n[1]-18],anchor:"bottom",closeButton:!1,focusAfterOpen:!1,maxWidth:"300px",className:"dl-popup"}).setLngLat(a).setDOMContent(d).addTo(this.map)}};function ut(s,t,a=!0){let n=[["online","Online now"],["24h","24h"],["7d","7 days"],["30d","30 days"]],i=e("div",{class:"dl-seg",role:"tablist"});for(let[o,r]of n)o==="online"&&!a||i.appendChild(e("button",{type:"button",role:"tab",class:o===s?"on":"","data-v":o,click:()=>{i.querySelectorAll("button").forEach(l=>l.classList.toggle("on",l.dataset.v===o)),t(o)}},r));return i}var cn=[{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"}],Fe=s=>cn.find(t=>t.id===s),ua={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 dn(s,t){return e("span",{class:"dl-dots",title:`${t}: ${s} of 4`},[e("span",{class:"dl-dots-label"},t),e("span",{class:"dl-dots-row"},[0,1,2,3].map(a=>e("i",{class:adom.content(i,cn.map(r=>{let l=!r.needs||s[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(),a(r.id))}},[e("div",{class:"dl-method-head"},[e("span",{class:"dl-method-ic"},w(r.ic)),e("b",{},r.title),r.id===n?e("span",{class:"dl-pill ok"},"Current"):r.id==="standard"&&!n?e("span",{class:"dl-pill"},"Recommended"):""]),e("p",{},r.text),e("div",{class:"dl-method-meters"},[dn(r.stealth,"Stealth"),dn(r.speed,"Speed")]),e("div",{class:"dl-method-foot"},l?[w("phone"),e("span",{},r.apps)]:[w("alert"),e("span",{},ua[r.needs])])])}));return o(),i}var ha={connect:"ok",disconnect:"",roam:"",device_added:"accent",device_removed:"",person_added:"",person_removed:"",paused:"warn",resumed:"ok",paused_all:"warn",resumed_all:"ok",server_down:"bad",server_up:"ok",portal_blocked:"bad",person_changed:"",devices_removed:"warn"};function Xe(s,t){let a=s.people.find(h=>h.id===t.person),n=a?.name??t.person??"",i=a?.devices.find(h=>h.id===t.device)?.name??"",o=h=>e("b",{},h),r=h=>e("span",{class:"dl-muted"},h),l=h=>e("span",{class:"dl-mono"},h),d=i?`${n} · ${i}`:n;switch(t.type){case"connect":return[o(d),r(" connected"),...t.detail?[r(" from "),l(t.detail)]:[],...t.where?[r(` · ${t.where}`)]:[]];case"disconnect":return[o(d),r(" went offline")];case"roam":return[o(d),r(" changed network "),l(t.detail??"")];case"device_added":return[o(n),r(" added "),e("span",{},t.detail??"a device")];case"device_removed":return[o(n),r(" removed "),e("span",{},t.detail??"a device")];case"person_added":return[r("You added "),o(t.detail??n)];case"person_removed":return[r("You removed "),o(t.detail??n)];case"person_changed":return[r("You changed "),o(n),r(` · ${t.detail??""}`)];case"paused":return[o(n),r(` paused — ${t.detail??""}`)];case"resumed":return[o(n),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"server_down":return[r("Tunnel "),l(t.detail??""),r(" went down")];case"server_up":return[r("Tunnel "),l(t.detail??""),r(" is back up")];case"portal_blocked":return[r("Portal blocked "),l(t.detail??""),r(" for 15 min after too many wrong codes")];case"devices_removed":return[o(n),r("’s devices were removed — end date reached")];default:return[r(`${t.type}${t.detail?`: ${t.detail}`:""}`)]}}function et(s,t){return e("div",{class:"dl-row"},[e("span",{class:`dl-ev-dot ${ha[t.type]??""}`}),e("span",{class:"dl-row-main"},Xe(s,t)),e("span",{class:"dl-faint dl-nowrap",title:new Date(t.ts*1e3).toLocaleString()},ce(t.ts,s.now))])}function fa(s){let t=[],a=(i,o)=>e("a",{href:i},o);for(let i of s.servers)i.enabled&&!i.up&&t.push({tone:"bad",text:[`Tunnel ${i.ifname} is down. `,a(L.url("admin/network/dawnline/health"),"Open Health")]});s.settings.paused_all&&t.push({tone:"warn",text:["Everyone is paused."]});for(let i of s.people)if(i.state==="quota")t.push({tone:"warn",text:[a(pe(i.id),i.name)," reached the data limit."]});else if(i.state==="expired")t.push({tone:"warn",text:[a(pe(i.id),i.name),"’s access has ended."]});else{let o=ze(i.expires);o!=null&&o>=0&&o<=Math.max(i.expire_warn,3)&&t.push({tone:"",text:[a(pe(i.id),i.name),`’s access ends in ${o} day${o===1?"":"s"}.`]}),i.quota_limit&&i.quota_used>=i.quota_limit*.9&&t.push({tone:"",text:[a(pe(i.id),i.name)," has used 90% of the data limit."]})}let n=s.people.flatMap(i=>i.devices.filter(o=>o.config_stale).map(o=>[i,o]));return n.length&&t.push({tone:"warn",text:n.length===1?[a(pe(n[0][0].id,n[0][1].id),`${n[0][0].name} · ${n[0][1].name}`)," needs its configuration again."]:[`${n.length} devices need their configuration again (networks or DNS changed).`]}),s.servers.some(i=>i.lan_like)&&s.like_home.error&&t.push({tone:"warn",text:[`Internet through the LAN is off: ${s.like_home.error} `,a(L.url("admin/network/dawnline/health"),"Details")]}),s.settings.portal_enabled||t.push({tone:"",text:["The personal portal is off. ",a(L.url("admin/network/dawnline/settings"),"Turn on")]}),t}function ht(s,t){let a=s.servers.find(d=>d.id===t)??s.servers[0],n=s.people.filter(d=>d.server===a.id),i=new Set(n.map(d=>d.id)),o=n.flatMap(d=>d.devices),r=d=>n.reduce((h,m)=>{let u=d(m);return[h[0]+u[0],h[1]+u[1]]},[0,0]),l=a.series?.[a.series.length-1];return{...s,servers:[a],people:n,series:a.series??s.series,events:s.events.filter(d=>d.person?i.has(d.person):!0),geo:{...s.geo,points:s.geo.points.filter(d=>i.has(d.person))},totals:{people:n.length,devices:o.length,online:o.filter(d=>d.online).length,active:n.filter(d=>d.state==="active").length,today:l?[l.rx,l.tx]:[0,0],month:r(d=>d.month)}}}var ft=class{constructor(t,a){this.srvId=t;this.go=a;this.el=e("div",{class:"dl-srvov"});this.map=null;this.range="online";this.parts={};this.healthAt=0}mount(t){this.st=ht(t,this.srvId);for(let a of["health","bento","side","activity"])this.parts[a]=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=ht(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 P.health().catch(()=>null);if(!t)return;let a=t.checks.filter(o=>o.status==="warn"||o.status==="error");if(!a.length){dom.content(this.parts.health,"");return}let n=a.filter(o=>o.status==="error").length,i=`${a.length} ${n?a.length===1?"problem":"problems":a.length===1?"warning":"warnings"}`;dom.content(this.parts.health,e("div",{class:`dl-healthstrip ${n?"bad":"warn"}`},[e("span",{class:"dl-healthstrip-title"},[w("alert"),i]),...a.slice(0,3).map(o=>{let r=e("span",{class:"dl-healthstrip-item"},o.title);return le(r,()=>[e("div",{class:"dl-tip-title"},o.title),e("div",{class:"dl-muted"},o.detail)]),r}),a.length>3?e("span",{class:"dl-sub"},`+${a.length-3} more`):"",e("a",{href:L.url("admin/network/dawnline/health")},a.some(o=>o.fix)?"Fix in Health →":"Open Health →")]))}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now}}mapCard(){let t=this.st,a=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"}),ut(this.range,o=>{this.range=o,this.map?.setRange(o)})]);if(!t.geo.enabled)return e("div",{class:"dl-panel flush"},[a,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 Ge({openPerson:o=>location.href=pe(o),openDevice:(o,r)=>location.href=pe(o,r)},this.range);let n=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"])]),i=e("div",{class:"dl-map-wrap"},[this.map.el,n]);return requestAnimationFrame(()=>this.map.mount(this.mapData())),e("div",{class:"dl-panel flush"},[a,i])}paint(){let t=this.st,a=t.servers[0],n=t.people.reduce((l,d)=>l+Math.max(0,d.device_limit-d.devices.length),0),i=t.people.flatMap(l=>l.devices.filter(d=>d.online));dom.content(this.parts.bento,e("div",{class:"dl-bento"},[this.onlineTile(i),this.speedTile(),this.disguiseTile(a),this.monthTile(n)]));let o=fa(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/health")},"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"},[w("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/activity")},"View all")]),r.length?r.map(l=>et(t,l)):e("div",{class:"dl-row dl-muted"},"Nothing yet. Connections, new devices and pauses appear here.")]))}onlineTile(t){let a=this.st,n=12,i=B=>B.spark[B.spark.length-1]??0,o=B=>a.geo.points.find(y=>y.device===B.id&&y.city)?.city,r=B=>/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(B.endpoint??""),l=B=>(r(B)?"home":o(B))??"",d=B=>[...a.events].reverse().find(y=>y.type==="connect"&&y.device===B.id)?.ts??0,h=a.people.map(B=>({p:B,devs:B.devices.filter(y=>y.online).sort((y,D)=>i(D)-i(y))})).filter(B=>B.devs.length).sort((B,y)=>y.devs.reduce((D,T)=>D+i(T),0)-B.devs.reduce((D,T)=>D+i(T),0)),m=h.length<=2,u=({p:B,devs:y})=>{let D=y.map(d).filter(Boolean),T=D.length?Math.min(...D):0,f=(B.rate??[]).slice(-15),g=f[f.length-1],k=g&&a.now-g[0]<180?g:null,c=200,p=30,C=Math.max(1,...f.map(H=>Math.max(H[1],H[2]))),v=H=>f.map((Z,ee)=>`${f.length>1?ee/(f.length-1)*c:c},${p-2-Z[H]/C*(p-6)}`),b=f.length>1?Pe(``):"",j=!k||k[1]<64&&k[2]<64,q=B.access==="both"?["home","globe"]:B.access==="lan"?["home"]:["globe"];return[e("div",{class:"dl-hc"},[e("div",{class:"dl-hc-head"},[e("span",{class:"dl-onl-av sm"},Le(B.name)),e("span",{class:"dl-stack"},[e("b",{},B.name),e("span",{class:"dl-hc-since"},T?`online for ${ce(T,a.now).replace(" ago","")}`:"online")]),e("span",{class:"dl-hc-reach"},q.map(H=>e("span",{class:`dl-ibadge ${H==="home"?"lan":"inet"}`},w(H))))]),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(k[2])}`]),e("span",{},[e("span",{class:"dl-up"},"↑"),` ${$e(k[1])}`]),e("span",{class:"dl-spacer"}),e("span",{class:"dl-faint"},"15 min")]),b]),e("div",{class:"dl-hc-devs"},y.map(H=>e("span",{class:"dl-hc-dev"},[w(H.kind),[H.name,l(H)].filter(Boolean).join(" · ")]))),e("div",{class:"dl-hc-foot"},[e("span",{class:"dl-faint"},`${K(y.reduce((H,Z)=>H+i(Z),0))} today · ${K(B.month[0]+B.month[1])} this month`)])])]},$=B=>{let{p:y,devs:D}=B,T=e("span",{class:"dl-onl-dev"},D.length>1?String(D.length):w(D[0].kind)),f=e("a",{class:`dl-onl-p${m?"":" sm"}`,href:pe(y.id),"aria-label":`${y.name}, online`},[e("span",{class:"dl-onl-av"},[Le(y.name),T]),m?e("span",{class:"dl-onl-name"},y.name):"",m?e("span",{class:"dl-onl-meta"},[...D.slice(0,3).map(g=>w(g.kind)),D.length>3?`+${D.length-3}`:"",l(D[0])?e("span",{},` · ${l(D[0])}`):""]):""]);return le(f,()=>u(B)),f},_=e("b",{class:`dl-onl-count${h.length?"":" none"}`},String(h.length)),N=h.reduce((B,y)=>B+y.devs.length,0);h.length&&le(_,()=>[`${h.length} ${h.length===1?"person":"people"} · ${N} device${N===1?"":"s"}`]);let J=h.length>n?h.slice(0,n-1):h,V=a.people.flatMap(B=>B.devices.map(y=>({p:B,d:y}))).filter(B=>B.d.handshake).sort((B,y)=>y.d.handshake-B.d.handshake)[0];return e("div",{class:"dl-bento-tile online"},[e("div",{class:"dl-bento-head"},[e("span",{class:"dl-metric-label"},"Online"),_]),h.length?e("div",{class:`dl-onl-row${m?"":" grid"}`},[...J.map($),h.length>n?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:B=>{this.go&&(B.preventDefault(),this.go("people","online"))}},[e("span",{class:"dl-onl-av"},`+${h.length-J.length}`)]):""]):e("div",{class:"dl-onl-empty"},[e("span",{},"Nobody is connected"),V?e("span",{class:"dl-sub"},`Last: ${V.p.name}, ${ce(V.d.handshake,a.now)}`):e("span",{class:"dl-sub"},"No device has connected yet")])])}speedTile(){return At(this.st.servers[0]?.rate??[],this.st.now,this.st.totals.today)}disguiseTile(t){let a=Fe(t.preset),n=t.obf??{},i=(l,d)=>e("span",{class:`dl-segs ${d}`},[0,1,2,3].map(h=>e("i",{class:h+n[l]).map(l=>`${l.toUpperCase()} ${n[l]}`);return r.length&&o.push(r.slice(0,2).join(" · ")+(r.length>2?` +${r.length-2}`:"")),["h1","h2","h3","h4"].some(l=>n[l]&&n[l]!==String(["h1","h2","h3","h4"].indexOf(l)+1))&&o.push("H1–H4 random"),n.i1&&o.push(n.i1.includes("0x8580")?"DNS-like first packet":"Signature packets"),n.header_protection_key&&o.push("Encrypted headers"),o.length||o.push(a?.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"},w(a?.ic??"shield")),e("span",{class:"dl-stack"},[e("b",{},a?a.title:"Custom"),e("span",{class:"dl-sub"},a?a.short:"Set by hand")])]),a?e("div",{class:"dl-disg-meters"},[e("span",{},"Stealth"),i(a.stealth,"acc"),e("span",{},"Speed"),i(a.speed,"ok")]):"",e("div",{class:"dl-disg-chips"},o.map(l=>e("span",{},l)))])}monthTile(t){let a=this.st.totals,n=this.st.people.filter(i=>i.state!=="active").length;return Pt(this.st.series,`${a.people} ${a.people===1?"person":"people"}${n?` · ${n} paused`:""} · ${t} device slot${t===1?"":"s"} free`)}};function At(s,t,a){let n=s.slice(-15),i=n[n.length-1],o=i&&t-i[0]<180,r=o?i[2]:0,l=o?i[1]:0,[d,h]=a,m=200,u=40,$=Math.max(1,...n.map(y=>Math.max(y[1],y[2]))),_=y=>n.map((D,T)=>`${n.length>1?T/(n.length-1)*m:m},${u-2-D[y]/$*(u-6)}`),N=_(2),J=_(1),V=n.length>1?Pe(``):e("div",{class:"dl-speed-wait"},[e("i"),e("span",{},"Collecting… 1 point a minute")]),B=(y,D,T,f)=>e("div",{class:"dl-speed-col"},[e("span",{class:"dl-sub"},[e("span",{class:T},D),` ${y}`]),e("span",{class:"dl-speed-val"},$e(f))]);return n.length>1&&le(V,()=>{let y=n[n.length-1];return[e("div",{class:"dl-tip-title"},new Date(y[0]*1e3).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})),e("div",{},`↓ ${$e(y[2])} · ↑ ${$e(y[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"},[B("Download","↓","dl-dn",r),B("Upload","↑","dl-up",l)]),V,e("div",{class:"dl-speed-today"},[e("span",{},["Today ",e("b",{},K(d+h))]),e("span",{},[e("span",{class:"dl-dn"},"↓"),` ${K(h)} `,e("span",{class:"dl-up"},"↑"),` ${K(d)}`])])])}function Pt(s,t){let a=s.slice(-30),n=a.map(h=>h.rx+h.tx),i=Math.max(1,...n),o=n.reduce((h,m)=>h+m,0),r=n.reduce((h,m,u)=>m>n[h]?u:h,0),l=h=>new Date(`${h}T12:00:00`).toLocaleDateString("en-GB",{day:"numeric",month:"short"}),d=e("div",{class:"dl-bento-bars"},a.map((h,m)=>{let u=n[m],$=e("i",{class:m===a.length-1?"hi":"",style:`height:${Math.max(4,u/i*100)}%`});return le($,()=>[e("div",{class:"dl-tip-title"},m===a.length-1?`Today · ${l(h.day)}`:l(h.day)),e("div",{},K(u)),e("div",{class:"dl-muted dl-mono"},`↓ ${K(h.tx)} ↑ ${K(h.rx)}`)]),$}));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"},K(o))]),n[r]>0?e("span",{class:"dl-sub"},`peak ${K(n[r])} · ${l(a[r].day)}`):""]),a.length?d:e("p",{class:"dl-muted"},"No traffic yet."),e("div",{class:"dl-bento-head"},[e("span",{class:"dl-sub"},a.length?l(a[0].day):""),e("span",{class:"dl-sub"},t),e("span",{class:"dl-sub"},"today")])])}var ma={active:"",paused:"pause",paused_all:"pause",expired:"calendar",quota:"chart",hours:"clock",no_server:"alert"};function zt(s){if(s.state==="active")return"";let t=e("span",{class:`dl-ibadge ${va(s)}`,"aria-label":Tt[s.state]},w(ma[s.state]||"alert"));return le(t,()=>[e("div",{class:"dl-tip-title"},Tt[s.state])]),t}function ga(s){let t=s.access==="both"?["lan","inet"]:s.access==="lan"?["lan"]:["inet"],a=e("span",{class:"dl-access","aria-label":Be[s.access]},t.map(n=>e("span",{class:`dl-ibadge ${n}`},w(n==="lan"?"home":"globe"))));return le(a,()=>[e("div",{class:"dl-tip-title"},Be[s.access]),s.access==="lan"&&s.services?.length?e("div",{class:"dl-muted"},`${s.services.length} home service${s.services.length===1?"":"s"} only`):""]),a}function va(s){return s.state==="active"?"ok":s.state==="quota"||s.state==="expired"?"bad":"warn"}function ba(s,t){let a=s,i=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===a?" selected":""}`,"data-v":o.v,click:()=>{a=o.v,i.querySelectorAll(".dl-choice").forEach(r=>r.classList.toggle("selected",r.dataset.v===o.v)),t?.(o.v)}},[e("span",{class:"dl-choice-title"},[w(o.ic),Be[o.v]]),e("span",{class:"dl-choice-text"},o.text)])));return{el:i,get:()=>a}}function xa(s){return`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")}`}function pn(s){let t=ze(s.expires);return s.state==="quota"||s.state==="expired"||t!=null&&t<=Math.max(s.expire_warn,3)||!!s.quota_limit&&s.quota_used>=s.quota_limit*.9}function wa(s){let t=s?new Date(`${s}T12:00:00`):new Date,a=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 P.status(30)}scope(t){return this.serverId?ht(t,this.serverId):t}embed(t,a){return this.serverId=a,this.render(t)}person(t){return this.st.people.find(a=>a.id===t)}async latestStatus(){let t=++this.statusSeq,a=await P.status(30).catch(()=>null);return!a||te("em",{},a.servers.length?"No people yet. Add someone and send them their personal link.":"Set up the server first, then add people."),n.serverId&&(r.filter=l=>n.st.people.some(d=>d.id===l)),r.handleAdd=()=>n.openCreate(),r.handleRemove=l=>n.remove(l),r.renderRowActions=()=>e("div",{class:"dl-none"}),i=r.option(form.DummyValue,"_card"),i.modalonly=!1,i.textvalue=l=>n.renderCard(e("div",{class:"dl-card",id:`dl-card-${l}`}),l),o.render().then(l=>{l.classList.add("dl-map","dl-root"),xe(a);let d=e("input",{type:"search",class:"dl-search-input",placeholder:"Search people, devices, IPs",input:u=>{n.query=u.target.value.trim().toLowerCase(),n.decorate()}}),h=e("select",{class:"dl-select","aria-label":"Sort",change:u=>{n.sort=u.target.value,n.decorate()}},[e("option",{value:"seen"},"Last seen"),e("option",{value:"name"},"Name"),e("option",{value:"usage"},"Usage")]),m=e("div",{class:"dl-root"},[n.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())]),a.servers.length?z([w("plus")," Add person"],()=>n.openCreate(),"add"):""]),a.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"},[e("label",{class:"dl-search"},[w("search"),d,e("kbd",{},"/")]),h,n.serverId?z([w("plus")," Add person"],()=>n.openCreate(),"add"):""])]),l]);return this.el=m,requestAnimationFrame(()=>this.decorate()),this.polling||(this.polling=!0,poll.add(()=>n.el?.isConnected?n.poll():Promise.resolve(),10)),!un&&new URLSearchParams(location.search).get("add")&&(un=!0,setTimeout(()=>n.openCreate(),100)),m})}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 a=this.st.people,n={all:a.length,online:a.filter(u=>u.online>0).length,attention:a.filter(pn).length,paused:a.filter(u=>u.state!=="active"&&u.state!=="quota"&&u.state!=="expired").length},i=document.getElementById("dl-people-tabs");if(i){let u={all:"All",online:"Online",attention:"Needs attention",paused:"Paused"};dom.content(i,Object.keys(u).map($=>e("button",{type:"button",role:"tab",class:$===this.filter?"on":"",click:()=>{this.filter=$,this.decorate()}},[u[$],e("b",{class:$==="attention"&&n[$]?"warn":""},String(n[$]))])))}let o=u=>this.filter==="online"&&!u.online||this.filter==="attention"&&!pn(u)||this.filter==="paused"&&!(u.state!=="active"&&u.state!=="quota"&&u.state!=="expired")?!1:this.query?[u.name,u.id,...u.devices.flatMap(_=>[_.name,_.address,_.endpoint,_.hostname])].join(" ").toLowerCase().includes(this.query):!0,r=[...a].sort((u,$)=>this.sort==="name"?u.name.localeCompare($.name):this.sort==="usage"?$.month[0]+$.month[1]-(u.month[0]+u.month[1]):$.online-u.online||$.last_seen-u.last_seen),l=null,d=0;for(let u of r){let _=document.getElementById(`dl-card-${u.id}`)?.closest(".cbi-section-table-row");if(!_)continue;l??(l=_.parentElement),l?.appendChild(_),_.classList.toggle("dl-off",u.state!=="active"),_.classList.toggle("dl-attn-row",u.state==="quota"||u.state==="expired");let N=o(u);_.classList.toggle("dl-filtered",!N),N&&d++}let h=l?.closest(".cbi-section-table")??l,m=document.getElementById("dl-people-none");h&&a.length&&!d?(m??(m=e("div",{id:"dl-people-none",class:"dl-empty"})),dom.content(m,e("p",{},this.query?`No one matches “${this.query}”.`:"No one here right now.")),m.parentElement!==h.parentElement&&h.after(m)):m?.remove()}async poll(){let t=await this.latestStatus();if(!t)return;let a=this.scope(t);this.st=a,this.paintCards(),this.decorate()}async quick(t,a,n){await O(()=>P.personUpdate(t.id,a),n)&&await this.poll()}renderCard(t,a){let n=this.person(a);if(!n)return dom.content(t,e("em",{},"Not saved yet — use “Save & Apply”.")),t;let i=ze(n.expires),o=Math.max(0,n.device_limit-n.devices.length),r=[];if(n.expires){let u=i!=null&&i>=0&&i<=Math.max(n.expire_warn,3),$=i!=null&&i<0;r.push(e("span",{class:`dl-pill-ic${$?" bad":u?" warn":""}`,title:`Access ends ${_e(n.expires)}`},[w("calendar"),$?`ended ${_e(n.expires)}`:u?`ends in ${i} day${i===1?"":"s"}`:`until ${_e(n.expires)}`]))}n.hours&&r.push(e("span",{class:"dl-pill-ic",title:"Allowed hours"},[w("clock"),n.hours.replace("-","–")]));let l=n.devices.map(u=>e("button",{type:"button",class:`dl-chip${u.disabled?" disabled":""}${u.online?" live":""}`,title:`${Me[u.kind]} · ${u.address}${u.online?` · online from ${u.endpoint}`:u.handshake?` · seen ${ce(u.handshake,this.st.now)}`:""}`,click:$=>{$.preventDefault(),De(n,u,()=>this.refresh(),this.st.geo)}},[w(u.kind),e("span",{class:"dl-chip-name"},u.name),!u.handshake&&!u.disabled?e("span",{class:"dl-chip-tag"},"not set up"):""]));o>0&&l.push(e("button",{type:"button",class:"dl-chip add",title:`${n.devices.length} of ${n.device_limit} devices`,click:u=>{u.preventDefault(),Re(n,()=>this.refresh())}},[w("plus"),e("span",{class:"dl-chip-name"},"Add device")]));let d=[];n.state==="quota"&&n.quota_period==="month"&&d.push(e("button",{type:"button",class:"dl-fix",click:()=>this.quick(n,{bonus_gb:String((n.bonus_gb||0)+10)},"+10 GB this month")},"+10 GB this month")),n.expires&&i!=null&&i<=Math.max(n.expire_warn,3)&&d.push(e("button",{type:"button",class:"dl-fix",click:()=>this.quick(n,{expires:wa(n.expires)},"Extended by 1 month")},"Extend 1 month"));let h=ye("more","More",u=>ke(u.currentTarget,[{label:"Open",icon:w("open"),run:()=>{location.href=pe(n.id)}},n.link?{label:"Invite card",icon:w("qr"),run:()=>Je(n,this.st.servers.find($=>$.id===n.server)?.name??"Home")}:null,o>0?{label:"Add device",icon:w("plus"),run:()=>Re(n,()=>this.refresh())}:null,null,{label:n.paused?"Resume":"Pause",icon:w(n.paused?"play":"pause"),warn:!n.paused,run:()=>this.togglePause(n)},{label:"Delete",icon:w("trash"),danger:!0,run:()=>this.remove(n.id)}].filter(($,_,N)=>$||_>0&&N[_-1])),"neutral","dl-icon-only"),m=e("div",{class:"dl-pcard-actions"},[n.link?ye("link","Copy link",()=>re(n.link,"Personal link copied"),"neutral","dl-icon-only"):"",h]);return dom.content(t,e("div",{class:"dl-pcard"},[e("div",{class:"dl-pcard-main"},[e("div",{class:"dl-card-head"},[e("span",{class:`dl-avatar${n.online?" online":""}`},Le(n.name)),e("a",{class:"dl-card-name",href:pe(n.id)},n.name),zt(n),ga(n),...r]),e("div",{class:"dl-meta"},[e("span",{},`${n.devices.length} of ${n.device_limit} devices`),e("span",{class:"dl-sep"},"·"),e("span",{},n.online?"online now":n.last_seen?`seen ${ce(n.last_seen,this.st.now)}`:"never connected")]),e("div",{class:"dl-chips"},l),d.length?e("div",{class:"dl-fixes"},d):""]),this.usageSide(n,m)])),t}usageSide(t,a){let n=t.quota_used||t.month[0]+t.month[1],i=t.quota_limit?Math.min(100,t.quota_used/t.quota_limit*100):0,o=t.devices.reduce((m,u)=>m+(u.spark[u.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${i>=100?" bad":i>=90?" warn":""}`});if(t.quota_limit){let m=e("i",{class:"fill"});m.style.width=`${i}%`,d.appendChild(m),le(d,()=>[e("div",{class:"dl-tip-title"},`${i.toFixed(1)}% used`),e("div",{class:"dl-muted"},`${K(t.quota_used)} of ${K(t.quota_limit)} · ${K(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 m=t.devices.map(u=>({d:u,v:u.month[0]+u.month[1]})).filter(u=>u.v>0).sort((u,$)=>$.v-u.v);m.forEach((u,$)=>{let _=e("i",{class:`c${Math.min($,4)}`});_.style.flexGrow=String(u.v),d.appendChild(_)}),m.length&&le(d,()=>[e("div",{class:"dl-tip-title"},"This month by device"),...m.map((u,$)=>e("div",{class:"dl-tip-row"},[e("span",{class:`dl-swatch c${Math.min($,4)}`}),e("span",{},u.d.name),e("b",{},K(u.v))]))])}let h=t.quota_limit?`${K(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"},[e("i",{class:"dl-dot online"}),"Live"]):e("span",{class:"dl-pside-state"},t.online?"Online":t.last_seen?"Offline":"Not connected"),a]),e("div",{class:"dl-use-num"},[e("b",{class:n?"":"dl-faint"},K(n)),e("span",{class:"dl-faint"},t.quota_limit?`of ${K(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 ${K(o)} · ${h}`:h)])}async togglePause(t){await O(()=>P.personPause(t.id,!t.paused),t.paused?`${t.name} resumed`:`${t.name} paused`)&&await this.refresh()}async remove(t){let a=this.person(t);await ae(`Remove ${a?.name??t}?`,`All ${a?.devices.length??0} devices are disconnected immediately and the personal link stops working. Usage history is kept in backups.`,"Remove",!0)&&await O(()=>P.personDelete(t),"Person removed")&&await this.refresh()}openCreate(){let t=this.st;if(!t.servers.length){X("Set up the server first.","warning");return}let a=e("input",{type:"text",class:"cbi-input-text",placeholder:"e.g. Myata",maxlength:48}),n=ba("internet"),i=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=(u,$)=>e("button",{type:"button",class:"cbi-button cbi-button-neutral",click:()=>{if(!$)o.value="";else{let _=new Date;_.setMonth(_.getMonth()+$),o.value=xa(_)}}},u),d=t.servers[0],h=!this.serverId&&t.servers.length>1?e("select",{class:"cbi-input-select"},t.servers.map(u=>e("option",{value:u.id},u.name))):null,m=(u,$,_)=>e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},u),e("div",{class:"cbi-value-field"},[$,_?e("div",{class:"cbi-value-description"},_):""])]);ne("Add person",[m("Name",a),h?m("Server",h):"",e("div",{class:"cbi-value dl-block"},[e("label",{class:"cbi-value-title"},"Access"),e("div",{class:"cbi-value-field"},n.el)]),m("Devices",i,"How many devices they can add themselves."),m("End date",e("div",{class:"dl-actions"},[o,l("1 month",1),l("3 months",3),l("1 year",12),l("None",0)]),"Optional."),m("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:Y},"Cancel")," ",z("Create and copy link",async()=>{let u=await O(()=>P.personCreate(a.value.trim(),"",h?.value??d.id,n.get(),Number(i.value)||t.settings.default_device_limit,o.value,Number(r.value)||0,"month"));u&&(u.link&&await re(u.link,"Personal link copied"),this.showCreated(u.id,a.value.trim(),u.link,t.servers.find($=>$.id===(h?.value??d.id))?.name??d.name),await this.refresh())},"positive")]),setTimeout(()=>a.focus(),50)}showCreated(t,a,n,i){if(n){Je({id:t,name:a,link:n},i,{title:`${a} is ready`,lead:`Send ${a} the card or the link. They open it, add their devices and connect — no account needed.`});return}ne(`${a} 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:Y},"Done")])}};var ya={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link"},ka=300*1e3;async function tt(s,t,a){if(!t.length)return!0;if(!await ae(`Install ${ya[s]}?`,`${t.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,"Install"))return!1;let i=(await P.updatesStatus().catch(()=>null))?.job?.started??0;if(!await O(()=>P.updatesRun(`pkgs:${t.join(",")}`)))return!1;X(`Installing ${t.join(", ")}…`,"info",4e3);let o=Date.now()+ka;for(;Date.now()setTimeout(d,2e3));let l=(await P.updatesStatus().catch(()=>null))?.job;if(!(!l||l.started===i||l.state==="running"))return l.state==="done"?(X(`${t.join(", ")} installed`,"success"),setTimeout(()=>a?.(),4e3),!0):(X(l.error??"Installation failed","error"),!1)}return X("Still installing: see Updates for the log.","warning"),!1}async function hn(s,t){let a=await O(()=>P.updatesStatus());return a?tt(s,a.needs?.[s]??[],t):!1}var $a=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],_a={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Nt(s,t,a){let n=e("button",{type:"button",role:"switch",class:`dl-switch${s?" on":""}`,"aria-checked":s?"true":"false","aria-label":t,click:()=>{let i=!n.classList.contains("on");n.classList.toggle("on",i),n.setAttribute("aria-checked",i?"true":"false"),a(i)}},e("i"));return n}function fn(s,t="Interfaces"){let a=e("section",{class:"dl-setsec dl-ifcard"},e("div",{class:"dl-setsec-body"},e("p",{class:"dl-muted"},"Loading interfaces…"))),n,i=!0,o="",r=!0,l=!0,d=new Set,h="",m=()=>JSON.stringify([l,i,i?"":o,r,[...d].sort()]),u=()=>n.detected.lan||n.saved.lan||"",$=()=>(i?n.detected.wan||n.saved.wan:o)||"",_=()=>new Map(n.devices.map(f=>[f.name,f])),N=()=>{let f=_();return[...r&&u()?[u()]:[],...[...d].filter(k=>k!==u())].filter(k=>k!==$()).map(k=>f.get(k)??{name:k,nets:[],missing:!0})},J=(f,g)=>{n=f,g&&(i=f.config.auto_wan,o=f.config.wan_device||f.detected.wan||f.saved.wan||"",r=f.config.auto_lan,l=f.config.lan_like,d=new Set(f.config.lan_devices),h=m()),T()},V=async f=>{let g=await P.interfaces(s).catch(k=>(X(k.message,"error"),null));g&&J(g,f)};function B(f){let g=r&&f.name===u(),k=f.name===$(),c=!g&&d.has(f.name),C=!(!!f.own||!!f.master||k||g)&&(f.nets.length>0||c||!!f.missing),v=(c||g)&&!f.zone&&!f.missing,b=f.missing?"Not present right now":f.own?"This server":f.master?`Port of ${f.master}`:k?`Internet${f.zone?` · zone ${f.zone}`:""}`:f.nets.length?f.nets.join(", "):"No IPv4 network",j=e("button",{type:"button",class:`dl-if${c?" sel":""}${g?" auto":""}${!C&&!c&&!g?" off":""}${v?" warn":""}`,"aria-pressed":c||g?"true":"false","aria-disabled":C?null:"true",click:()=>{C&&(d.has(f.name)?d.delete(f.name):d.add(f.name),T())}},[e("span",{class:"dl-if-ic"},w(_a[f.kind]??"link")),e("span",{class:"dl-if-main"},[e("span",{class:"dl-if-name"},f.name),e("span",{class:"dl-if-sub"},b)]),g?e("span",{class:"dl-if-badge ok"},[e("i",{class:"dot ok"}),"Auto"]):c?e("span",{class:"dl-if-check"},w("check")):""]);return le(j,()=>[e("div",{class:"dl-tip-title"},f.name),e("div",{class:"dl-muted"},[f.logical?`Interface ${f.logical}`:"No netifd interface",f.zone?` · zone ${f.zone}`:" · no firewall zone"]),f.members.length?e("div",{class:"dl-muted"},`Ports: ${f.members.join(", ")}`):"",f.nets.length?e("div",{class:"dl-mono"},f.nets.join(", ")):"",v?e("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",f.master?e("div",{class:"dl-muted"},`Choose ${f.master} to include it.`):""]),j}function y(){let f=n.like_home;return!l||!n.config.lan_like?"":!n.needs?.length&&f.active&&f.bridged?"ok":"warn"}function D(){let f=n.like_home;return l?n.needs?.length?[e("span",{class:"dl-warn"},`Needs ${n.needs.join(" and ")}.`)," Until they are installed, internet traffic goes straight to the WAN."]:n.config.lan_like?f.active&&f.bridged?["Internet traffic enters ",e("span",{class:"dl-mono"},f.dev??"")," as ",e("span",{class:"dl-mono"},f.address??""),", so whatever handles home traffic (proxies, filters, DNS) handles it too."]:[e("span",{class:"dl-warn"},`Not working: ${f.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."]}function T(){let f=e("select",{class:"cbi-input-select","aria-label":"Internet interface",change:b=>{o=b.target.value,T()}},n.devices.filter(b=>!b.own&&!b.master&&b.zone&&!b.missing).map(b=>e("option",{value:b.name,selected:b.name===o?"selected":null},`${b.name} · zone ${b.zone}`))),g=(b,j)=>e("span",{},[" Live: ",e("span",{class:"dl-mono"},b||"—")," · Saved: ",e("span",{class:"dl-mono"},j||"—")]),k=$a.map(([b,j])=>{let q=n.devices.filter(H=>H.category===b);return q.length?e("div",{class:"dl-ifgroup"},[e("h4",{},j),e("div",{class:"dl-ifgrid"},q.map(B))]):""}),p=N().flatMap(b=>b.nets.map(j=>[j,b.name])),C=m()!==h,v=z("Save",async()=>{let b=await O(()=>P.serverInterfaces(s,i,i?"":o,r,[...d],l),"Interfaces saved");b&&(J(b,!0),b.nets_changed&&b.lan_only&&X(`${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:!C});dom.content(a,[e("div",{class:"dl-setsec-body"},[e("div",{class:"dl-panel-head"},[e("h3",{},t),e("span",{class:"dl-spacer"}),z([w("reset")," Rescan"],()=>V(!1),"neutral",{title:"Read the interfaces again"})]),e("div",{class:"dl-setrow"},[e("div",{class:"dl-lh-main"},[e("span",{class:`dl-need-ic ${y()}`},w("home")),e("div",{class:"dl-stack"},[e("span",{class:"dl-setrow-label"},"Internet like a home device"),e("span",{class:"dl-sub"},D())])]),e("div",{class:"dl-setrow-ctl dl-if-wanctl"},[l&&n.needs?.length?z("Install",()=>tt("home",n.needs,()=>V(!1)),"positive"):"",Nt(l,"Internet like a home device",b=>{l=b,T()})])]),e("div",{class:"dl-setrow"},[e("div",{class:"dl-lh-main"},[e("span",{class:"dl-need-ic"},w("globe")),e("div",{class:"dl-stack"},[e("span",{class:"dl-setrow-label"},"Auto-detect WAN"),e("span",{class:"dl-sub"},["The interface with the default route: the server port opens there and Internet access leaves through it.",g(n.detected.wan,n.saved.wan)])])]),e("div",{class:"dl-setrow-ctl dl-if-wanctl"},[i?"":f,Nt(i,"Auto-detect WAN",b=>{i=b,T()})])]),e("div",{class:"dl-setrow"},[e("div",{class:"dl-lh-main"},[e("span",{class:"dl-need-ic"},w("network")),e("div",{class:"dl-stack"},[e("span",{class:"dl-setrow-label"},"Auto-detect LAN"),e("span",{class:"dl-sub"},["Adds the detected LAN to the home network.",g(n.detected.lan,n.saved.lan)])])]),e("div",{class:"dl-setrow-ctl"},Nt(r,"Auto-detect LAN",b=>{r=b,T()}))]),e("div",{class:"dl-iflead"},[e("b",{},"Home network"),e("span",{class:"dl-sub"},"What people with Home access can reach. Click to add an interface; bridge ports and Wi-Fi in a bridge come with the bridge.")]),...k]),e("div",{class:"dl-setsec-foot"},[e("span",{class:"dl-sub dl-if-summary"},p.length?["Home access reaches ",...p.flatMap(([b,j],q)=>[q?", ":"",e("span",{class:"dl-mono"},b),` (${j})`]),l?" · Internet like a home device":$()?` · Internet via ${$()}`:""]:["No home network: Home access reaches nothing but this router.",$()?` Internet via ${$()}.`:""]),v])])}return V(!0),a}function nt(s,t,a){let n=e("button",{type:"button",role:"switch",class:`dl-switch${s?" on":""}`,"aria-checked":s?"true":"false","aria-label":t,click:()=>{let i=!n.classList.contains("on");n.classList.toggle("on",i),n.setAttribute("aria-checked",i?"true":"false"),a?.(i)}},e("i"));return n}var We=s=>s.classList.contains("on");function se(s,t={}){return e("input",{type:"text",class:"cbi-input-text",value:s,...t})}function Q(s,t,a){return e("div",{class:"dl-setrow"},[e("div",{class:"dl-stack"},[e("span",{class:"dl-setrow-label"},s),a?e("span",{class:"dl-sub"},a):""]),e("div",{class:"dl-setrow-ctl"},t)])}function Ke(s,t,a,n=""){return e("section",{class:`dl-setsec ${n}`},[e("div",{class:"dl-setsec-body"},[s?e("h3",{},s):"",...t]),a.length?e("div",{class:"dl-setsec-foot"},a):""])}function we(s,t,a,n){return e("div",{class:"dl-group"},[e("div",{class:"dl-group-head"},[e("span",{class:"dl-group-ic"},w(s)),e("span",{class:"dl-stack"},[e("b",{},t),a?e("span",{class:"dl-sub"},a):""])]),e("div",{class:"dl-group-body"},n.filter(i=>i!==""))])}var mn=[["overview","Overview"],["people","People"],["connection","Connection"],["access","Access"],["disguise","Disguise"],["tunnel","Tunnel"]],Ma={general:"connection",network:"connection",interfaces:"access",advanced:"tunnel"};function La(s,t,a){let n=e("div",{class:"dl-choices"},s.map(i=>e("button",{type:"button",class:`dl-choice${i.v===t?" selected":""}`,"data-v":i.v,click:()=>{n.querySelectorAll(".dl-choice").forEach(o=>o.classList.toggle("selected",o.dataset.v===i.v)),a(i.v)}},[e("span",{class:"dl-choice-title"},[i.ic?w(i.ic):"",i.title]),e("span",{class:"dl-choice-text"},i.text)])));return n}var gn=[["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 Sa(s){let t=h=>s[h]!=null&&s[h]!=="",a=gn.filter(([h])=>t(h));if(!a.length)return null;let n=(h,m)=>e("span",{class:"dl-pv"},[e("i",{},m),e("b",{},h==="header_protection_key"?`${s[h].slice(0,6)}••••`:s[h])]),i=(h,m,u,$)=>{let _=gn.filter(([N])=>$.includes(N)&&t(N));return _.length?e("div",{class:"dl-pgroup"},[e("div",{class:"dl-pgroup-head"},[w(m),e("b",{},h)]),e("p",{},u),e("div",{class:"dl-pvals"},_.map(([N,J])=>n(N,J)))]):""},o=Number(s.jc||0),r=(s.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=a.map(([h,m])=>`${m} = ${s[h]}`).join(` +`),d=e("div",{class:"dl-pgrid"},[i("Junk packets","zap",o?`${o} random packet${o===1?"":"s"} of ${s.jmin}–${s.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),i("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),i("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),i("Signatures","globe",r,["i1","i2","i3","i4","i5"]),i("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"]),i("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",{},[w("chevron"),e("span",{},"Current parameters"),e("span",{class:"dl-pcount"},String(a.length)),e("span",{class:"dl-spacer"}),e("button",{type:"button",class:"dl-linkbtn",click:h=>{h.preventDefault(),re(l,"Parameters copied")}},"Copy as config")]),d])}var Rt=(s,t)=>{let a=new URLSearchParams;s&&a.set("server",s),t&&t!=="overview"&&a.set("section",t);let n=a.toString();return`${L.url("admin/network/dawnline/server")}${n?`?${n}`:""}`},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 P.status(31),a=t.servers.length?null:await P.setupDefaults();return[t,a]}render([t,a]){if(this.st=t,!t.servers.length&&a)return this.wizard(a);let n=new URLSearchParams(location.search),i=n.get("section")??"",o=Ma[i]??i;return mn.some(([r])=>r===o)&&(this.section=o),this.srvId=(t.servers.find(r=>r.id===n.get("server"))??t.servers[0]).id,xe(t),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 P.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 P.status(31).catch(()=>null);t&&(this.st=t,t.servers.length?this.paint():location.href=Rt())}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(a=>e("button",{type:"button",role:"tab",class:`dl-srvtab${a.id===t.id?" on":""}`,"aria-selected":a.id===t.id?"true":"false",click:()=>{a.id!==this.srvId&&(this.srvId=a.id,this.paint())}},[e("i",{class:`dot ${a.up?"ok":"bad"}`}),e("b",{},a.name),e("span",{class:"dl-mono dl-faint"},`:${a.port}`)])),e("button",{type:"button",class:"dl-srvtab add",click:()=>this.addServer()},[w("plus"),"Add server"])]))}paintSections(){dom.content(this.secEl,e("div",{class:"dl-seg dl-srvsections",role:"tablist","aria-label":"Server"},mn.map(([t,a])=>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)},a))))}go(t,a){let n=this.pp[this.current().id];if(a&&n)n.filter=a,n.el&&n.decorate();else if(a){let i=this.pp[this.current().id]=new He;i.filter=a}this.showSection(t),window.scrollTo({top:0,behavior:"smooth"})}showSection(t){this.section=t,this.secEl.querySelectorAll("[data-section]").forEach(o=>{let r=o.dataset.section===t;o.classList.toggle("on",r),o.setAttribute("aria-selected",r?"true":"false")});let a=this.st,n=this.current(),i={overview:()=>{let o=this.ov[n.id];return o?(o.update(a),o.el):(this.ov[n.id]=new ft(n.id,(r,l)=>this.go(r,l))).mount(a)},people:()=>{var d,h;let o=this.pp[n.id];if(o?.el)return o.poll(),o.el;let r=e("div",{},e("p",{class:"dl-muted"},"Loading people…"));return((d=this.pp)[h=n.id]??(d[h]=new He)).embed(a,n.id).then(m=>{r.isConnected?dom.content(r,m):r.replaceChildren(m)}),r},connection:()=>this.connection(n),access:()=>this.access(n),disguise:()=>this.disguise(n),tunnel:()=>this.tunnel(n)};dom.content(this.bodyEl,i[t]())}head(t){let a=this.st,n=(l,d)=>e("span",{class:"dl-addrbar-seg"},[w(l),...d]),i=`${t.endpoint||"—"}:${t.port}`,o=!t.enabled||a.settings.paused_all,r=e("div",{class:"dl-actions"},[z([w("search")," Search ",e("kbd",{},"⌘K")],()=>Ct(),"neutral",{class:"cbi-button cbi-button-neutral dl-searchbtn"}),o?z([w("play")," Turn on"],async()=>{a.settings.paused_all&&!await O(()=>P.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"}`},[e("i",{class:"dl-pill-dot"}),t.enabled?t.up?"Ready":"Down":"Disabled"]),a.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:()=>re(i,"Address copied")},[w("globe"),e("span",{class:"dl-mono"},i),w("copy")]),n("tunnel",[e("span",{class:"dl-mono"},t.ifname)]),n("network",[e("span",{class:"dl-mono"},t.subnet)]),t.up?n("clock",[`up ${Xt(t.uptime)}`]):""])])}async save(t,a,n="Saved"){await O(()=>P.serverUpdate(t.id,a),n)&&await this.refresh()}connection(t){let a=se(t.name,{placeholder:"Home"}),n=se(t.endpoint,{placeholder:"vpn.example.com",class:"cbi-input-text dl-mono"}),i=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 Ke("Connection",[e("p",{class:"dl-muted"},"How devices find this server, and what goes into their configuration."),we("router","Server","What people see",[Q("Name",a,"Shown to people in their portal.")]),we("globe","Devices connect to","Where the tunnel answers from the internet",[Q("Public address",n,"Hostname or IP of the router on the internet. A DDNS name keeps links working when your IP changes."),Q("UDP port",i,"Opened on the WAN firewall automatically.")]),we("file","In every device configuration","Changing these marks devices “Update config” until they import again",[Q("DNS for devices",o,"Empty = this router, which sends each query where your home network would."),Q("MTU",r,"Lower it if some sites hang on mobile networks."),Q("Keep-alive",l,"Seconds between packets devices send to keep NAT open. 0 = off.")])],[e("span"),z("Save",()=>this.save(t,{name:a.value,endpoint:n.value,port:i.value,dns:o.value,mtu:r.value,keepalive:l.value}),"positive")])}access(t){let a=this.st.services;return e("div",{class:"dl-stack gap16"},[fn(t.id,"Access"),Ke("Home services",[e("p",{class:"dl-muted"},"People with Home-only access can be limited to these services instead of the whole home network (chosen per person). The list is shared by all servers."),e("div",{class:"dl-list"},a.length?a.map(n=>e("div",{class:"dl-row"},[w("home"),e("span",{class:"dl-row-main dl-stack"},[e("b",{},n.name),e("span",{class:"dl-mono dl-faint"},`${n.address}${n.ports.length?` · ports ${n.ports.join(", ")}`:" · all ports"}`)])])):[e("div",{class:"dl-row dl-muted"},"No services yet.")])],[e("span"),e("a",{class:"cbi-button cbi-button-neutral",href:`${L.url("admin/network/dawnline/settings")}#dl-set-services`},"Edit in Settings")])])}disguise(t){let a=Fe(t.preset)?t.preset:void 0,n=a??"standard",i=z("",()=>this.applyDisguise(t,n,n===a),"positive"),o=()=>{dom.content(i,n===a?[w("reset")," Generate new values"]:`Switch to ${Fe(n).title}`)};o();let r=Sa(t.obf??{});return Ke("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."),Dt(this.st.awg,n,l=>{n=l,o()},a),this.st.awg.v3?"":Ee("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."),i])}async applyDisguise(t,a,n){let i=Fe(a),r=this.st.people.filter(d=>d.server===t.id).reduce((d,h)=>d+h.devices.length,0);await ae(n?"Generate new disguise values?":`Switch to ${i.title}?`,`${r} device${r===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${a==="max"?" They need an app with AmneziaWG 3.1.":""}`,n?"Generate and apply":"Switch and apply",!0)&&await O(()=>P.serverObfuscation(t.id,a),n?"New values applied":`${i.title} applied`)&&(X("Devices are marked “Update config” until they import again.","info",6e3),await this.refresh())}tunnel(t){let a=this.st.people.filter(i=>i.server===t.id).length,n=z(t.enabled?"Turn off":"Turn on",async()=>{t.enabled&&!await ae(`Turn off ${t.name}?`,`The tunnel stops and ${a} ${a===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"},[Ke("Tunnel",[e("p",{class:"dl-muted"},"Technical details. They are set when the server is created and rarely change."),Q("Interface",e("span",{class:"dl-mono"},`${t.ifname} · router ${t.address}`)),Q("Tunnel subnet",e("span",{class:"dl-mono"},t.subnet),"Device addresses come from it."),Q("Server public key",e("span",{class:"dl-keyrow"},[e("code",{class:"dl-mono"},t.public_key),z([w("copy")],()=>re(t.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})])),Q("Link path",e("span",{class:"dl-mono"},`/${t.id}/`),"Changing it would break every personal link already sent.")],[]),Ke("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"},n)]),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 ${a} ${a===1?"person":"people"} with all their devices. A backup is made first.`)]),e("div",{class:"dl-setrow-ctl"},z([w("trash")," Remove"],()=>this.remove(t),"negative"))])],[],"danger")])}async addServer(){let t=await O(()=>P.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 a=this.st.people.filter(n=>n.server===t.id);ne(`Remove ${t.name}?`,[e("p",{},`This removes the tunnel, its firewall rules and ${a.length} ${a.length===1?"person":"people"} with all their devices. A backup is made first.`)],[e("button",{class:"cbi-button cbi-button-neutral",click:Y},"Cancel")," ",z("Remove",async()=>{Y(),await O(()=>P.serverDelete(t.id),"Server removed")&&setTimeout(()=>{location.href=Rt()},800)},"negative")])}wizard(t,a=!1,n){let i={id:t.id,name:t.name,endpoint:t.endpoint,port:t.port,subnet:t.subnet,preset:"standard",portal:!0,portal_port:t.portal_port||8443,lan_zone:t.lan_zone,wan_zone:t.wan_zone},o=0,r=e("div",{class:"dl-wizard"}),l=(u,$={})=>{let _=se(String(i[u]),$);return _.addEventListener("input",()=>{i[u]=u==="port"||u==="portal_port"?Number(_.value):_.value.trim()}),_},d=a?["Connection","Disguise"]:["Connection","Disguise","Portal"],h=[()=>e("div",{},[e("p",{},"Where devices connect to. Use a hostname that always points at your router (DDNS), so links keep working when your IP changes."),Q("Name",l("name"),"Shown to people in their portal."),Q("Link path",l("id",{maxlength:24,class:"cbi-input-text dl-mono"}),"First part of personal links: https://address:port//."),Q("Public address",l("endpoint",{placeholder:"vpn.example.com",class:"cbi-input-text dl-mono"}),"Hostname or IP address of your router on the internet."),Q("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."),Q("Tunnel subnet",l("subnet",{class:"cbi-input-text dl-mono"}),`Addresses for devices. 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."),Dt(t.awg,i.preset,u=>i.preset=u)]),()=>{let u=l("portal_port",{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"});return e("div",{},[Ee("info","Devices reach the internet the way devices on your home network do: whatever handles home traffic on this router handles theirs too. You can change this later under Servers → Access."),e("h4",{},"Personal portal"),e("p",{},"A small page where each person adds their own devices, with their personal link. It gets its own HTTPS port on WAN."),La([{v:"on",title:"On",ic:"link",text:"People manage their devices themselves within the limits you set."},{v:"off",title:"Off",ic:"x",text:"Only you add devices, from LuCI."}],"on",$=>{i.portal=$==="on",u.disabled=!i.portal}),Q("Portal port",u,"TCP port on WAN. The whole port belongs to the portal.")])}],m=()=>{dom.content(r,[e("h2",{},a?"Add a server":"Set up Dawnline"),e("div",{class:"dl-steps"},d.map((u,$)=>e("span",{class:`dl-step${$===o?" current":$0?z("Back",()=>{o--,m()}):n?z("Cancel",n):"",e("span",{class:"dl-spacer"}),o{if(o===0&&(!i.endpoint||!i.port||!i.subnet)){X("Fill in the public address, port and subnet.","warning");return}o++,m()},"positive"):z("Create server",async()=>{let u=await O(()=>P.serverCreate(i.id,i.name,t.ifname,i.port,i.subnet,i.endpoint,t.mtu,i.preset,i.lan_zone,i.wan_zone,!0,a?void 0:i.portal,a?void 0:i.portal_port),"Server created");u&&setTimeout(()=>{location.href=Rt(u.id)},1500)},"positive")])])};return m(),r}};var it=300;function Ta(s){let t=new Date(s*1e3),a=new Date,n=new Date;return n.setDate(a.getDate()-1),t.toDateString()===a.toDateString()?"Today":t.toDateString()===n.toDateString()?"Yesterday":t.toLocaleDateString("en-GB",{weekday:"long",day:"numeric",month:"long"})}function Ht(s){let t=s.keep_days>0?`${s.keep_days} day${s.keep_days===1?"":"s"}`:"no age limit",a=s.persist==="off"?"kept in memory only (lost on reboot)":`saved to flash ${s.persist==="10min"?"every 10 minutes":"hourly"}`;return`Kept for ${t}, up to ${s.max.toLocaleString("en-GB")} events, ${a}.`}var mt=class{constructor(){this.events=[];this.kind="all";this.query="";this.shown=it;this.list=e("div",{});this.sub=e("span",{class:"dl-muted"});this.tabs=e("div",{class:"dl-seg",role:"tablist"})}async load(){return Promise.all([P.status(1),P.events(2e4)])}render([t,a]){this.st=t,this.take(a),xe(t);let n=e("input",{type:"search",class:"dl-search-input",placeholder:"Search people, devices, IPs",input:r=>{this.query=r.target.value.trim().toLowerCase(),this.shown=it,this.paint()}}),i=z([w("download")," Export"],()=>ke(i,[{label:"CSV (spreadsheet)",icon:w("download"),run:()=>ve(this.st,this.filtered().reverse(),"csv",this.kind==="all"?"":this.kind)},{label:"JSON",icon:w("download"),run:()=>ve(this.st,this.filtered().reverse(),"json",this.kind==="all"?"":this.kind)}])),o=z([w("trash")," Clear"],()=>Ce("Clear activity","Removes events from the log on the router.",{},()=>this.reload(),this.kind==="all"?void 0:this.kind));return this.paint(),poll.add(async()=>{let r=await P.events(2e4).catch(()=>null);r&&(this.take(r),this.paint())},15),e("div",{},[e("div",{class:"dl-pagehead"},[e("div",{class:"dl-stack"},[e("h2",{class:"dl-h1"},"Activity"),this.sub]),e("div",{class:"dl-row-actions"},[i,o])]),e("div",{class:"dl-toolbar"},[this.tabs,e("span",{class:"dl-spacer"}),e("label",{class:"dl-search"},[w("search"),n])]),this.list])}take(t){this.events=t.events,this.policy=t.policy;let a=je.filter(n=>!t.policy.categories.includes(n));this.sub.textContent=`${Ht(t.policy)}${a.length?` Not recorded: ${a.map(n=>Oe[n].toLowerCase()).join(", ")}.`:""}`}async reload(){let t=await P.events(2e4).catch(()=>null);t&&(this.take(t),this.paint())}filtered(){return[...this.events].reverse().filter(t=>this.kind!=="all"&&rt(t.type)!==this.kind?!1:this.query?`${Xe(this.st,t).map(n=>n.textContent??"").join(" ")} ${t.detail??""} ${t.where??""}`.toLowerCase().includes(this.query):!0)}paintTabs(){let t=a=>a==="all"?this.events.length:this.events.filter(n=>rt(n.type)===a).length;dom.content(this.tabs,["all",...je].map(a=>e("button",{type:"button",role:"tab",class:a===this.kind?"on":"",click:()=>{this.kind=a,this.shown=it,this.paint()}},[a==="all"?"All":Oe[a],e("b",{},String(t(a)))])))}paint(){this.paintTabs();let t=this.filtered();if(!t.length){dom.content(this.list,e("div",{class:"dl-empty"},[e("p",{},this.events.length?"No events match.":"The log is empty.")]));return}let a=[],n="",i=null;for(let o of t.slice(0,this.shown)){let r=Ta(o.ts);r!==n&&(n=r,i=e("div",{class:"dl-panel flush"},e("div",{class:"dl-panel-head pad"},e("h3",{},r))),a.push(i));let l=et(this.st,o);l.lastElementChild.textContent=new Date(o.ts*1e3).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),i.appendChild(l)}t.length>this.shown&&a.push(e("div",{class:"dl-more-row"},z(`Show ${Math.min(it,t.length-this.shown)} more of ${t.length-this.shown}`,()=>{this.shown+=it,this.paint()}))),dom.content(this.list,a)}};var Ea={manual:"Manual",auto:"Nightly","pre-restore":"Before restore","pre-import":"Before import","pre-delete":"Before removing a server","pre-update":"Before update"},vn=3;function It(s){let t=new Date(s*1e3),a=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),n=Math.round((new Date(new Date().toDateString()).getTime()-new Date(t.toDateString()).getTime())/864e5);return`${n===0?"Today":n===1?"Yesterday":t.toLocaleDateString("en-GB",{day:"numeric",month:"short"})}, ${a}`}async function Ca(s){let t=await O(()=>P.backupRead(s.name));if(!t)return;let a=atob(t.data),n=new Uint8Array(a.length);for(let o=0;oCa(s),"neutral","dl-icon-only"),ye("more","More",a=>ke(a.currentTarget,[{label:"Restore",icon:w("reset"),run:async()=>{await ae("Restore this backup?",`Everything returns to ${It(s.created)}. The current state is backed up first.`,"Restore",!0)&&await O(()=>P.backupRestore(s.name),"Restored")&&t()}},{label:"Delete",icon:w("trash"),danger:!0,run:async()=>{await ae("Delete this backup?",`The backup from ${It(s.created)} is removed from the router.`,"Delete",!0)&&await O(()=>P.backupDelete(s.name),"Backup deleted")&&t()}}]),"neutral","dl-icon-only")])])}function Bt(s,t){let a=s.slice(0,vn).map(d=>bn(d,t)),n=s.slice(vn),i=s.length?e("div",{class:"dl-list"},[...a,n.length?e("details",{class:"dl-bk-older"},[e("summary",{},[w("chevron"),`${n.length} older backup${n.length===1?"":"s"}`]),...n.map(d=>bn(d,t))]):""]):e("div",{class:"dl-list"},[e("div",{class:"dl-row dl-muted"},"No backups yet.")]),o=z("Restore from file",async()=>{let d=await Lt(".tar.gz,.tgz,application/gzip","base64");if(!d)return;await ae("Restore from file?",`Replace the current Dawnline configuration with ${d.name}? The current state is backed up first.`,"Restore",!0)&&await O(()=>P.backupUpload(d.data),"Restored")&&t()}),r=z("Export JSON",async()=>{let d=await O(()=>P.exportJson());d&&ge(`dawnline-export-${new Date().toISOString().slice(0,10)}.json`,JSON.stringify(d,null,2),"application/json")}),l=z("Import JSON",async()=>{let d=await Lt(".json,application/json","text");if(!d)return;let h;try{h=JSON.parse(d.data)}catch{X("Not a JSON file.","error");return}await ae("Import?","This replaces the whole Dawnline configuration on this router. The current state is backed up first.","Import",!0)&&await O(()=>P.importJson(h),"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"}),z([w("plus")," Back up now"],async()=>{await O(()=>P.backupCreate(),"Backup created")&&t()},"positive")]),i]),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 st(s,t,a){s.some(([o])=>o===t)||(s=[...s,[t,t]]);let n=e("div",{class:"dl-seg sm",role:"radiogroup","aria-label":a,"data-value":t}),i=()=>dom.content(n,s.map(([o,r])=>e("button",{type:"button",role:"radio",class:o===n.dataset.value?"on":"","aria-checked":o===n.dataset.value?"true":"false",click:()=>{n.dataset.value=o,i()}},r)));return i(),n}function jt(s,t,a=`${t}s`){return`${s.toLocaleString("en-GB")} ${s===1?t:a}`}function gt(s){return s<1024?`${s} B`:s<1048576?`${(s/1024).toFixed(s<10240?1:0)} KB`:`${(s/1048576).toFixed(1)} MB`}var vt=class{constructor(){this.root=e("div",{class:"dl-settings-main"});this.backups=[]}load(){return P.settingsGet()}render(t){return this.d=t,xe(),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,a="Saved"){let n=await O(()=>P.settingsUpdate(t),a);n&&(this.d=n,this.paint())}section(t,a,n,i,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",{},a),e("span",{class:"dl-spacer"}),...r]):e("h3",{},a),...n]),i.length?e("div",{class:"dl-setsec-foot"},i):""])}portalSection(){let t=this.d.settings,a=this.d.effective,n=this.d.cert,i=this.d.portal_candidates??[],o=this.d.portal_checks??[],r=nt(a.portal_enabled,"Enable portal"),l=se(t.portal_port,{placeholder:"8443",inputmode:"numeric",class:"cbi-input-text dl-w-port"}),d=nt(a.portal_443,"Standard ports",()=>f()),h=se(t.portal_title,{placeholder:"Dawnline"}),m=se(t.portal_redirect,{placeholder:"Show “Not found”",class:"cbi-input-text dl-mono"}),u=se("",{placeholder:"vpn.example.com or an IP","aria-label":"Other address"}),$=R=>/^\d{1,3}(\.\d{1,3}){3}$/.test(R),_=[a.portal_host,...a.portal_alt??[]].filter((R,oe,M)=>R&&M.indexOf(R)===oe);!_.length&&i[0]&&(_=[i[0].host]);let N=[...i],J=R=>{R&&!N.some(oe=>oe.host===R)&&N.push({host:R,kind:$(R)?"ip":"name",ips:[],here:!1,cloudflare:!1,cert:!1})};_.forEach(J);let V=R=>R.kind==="ip"?e("span",{class:"dl-addr-warn"},[w("alert"),"Plain HTTP: the link and VPN keys travel unencrypted"]):e("span",{class:"dl-sub"},R.cloudflare?"Behind Cloudflare · often stalls in Russia":R.ips.length?R.here?`Points at this router${R.cert?" · Let’s Encrypt certificate":" · no certificate yet"}`:`Points at ${R.ips.join(", ")}, not this router`:"Your address"),B=e("div",{class:"dl-addr-opts",role:"group","aria-label":"Portal addresses"}),y=R=>{_.includes(R)?_.length>1&&(_=_.filter(oe=>oe!==R)):_=[..._,R],D(),f()},D=()=>dom.content(B,[...N.map(R=>{let oe=_.includes(R.host),M=_[0]===R.host;return e("div",{class:`dl-addr-opt${oe?" on":""}`,role:"checkbox","aria-checked":oe?"true":"false",tabindex:"0",click:()=>y(R.host),keydown:S=>{(S.key===" "||S.key==="Enter")&&(S.preventDefault(),y(R.host))}},[e("i",{class:"dl-addr-check"},oe?w("check"):""),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono"},R.host),V(R)]),M?e("span",{class:"dl-pill info"},"Main"):oe?e("button",{type:"button",class:"dl-linkbtn",click:S=>{S.stopPropagation(),_=[R.host,..._.filter(x=>x!==R.host)],D(),f()}},"Make main"):R.cloudflare?e("span",{class:"dl-pill warn"},"Cloudflare"):R.kind==="ip"?e("span",{class:"dl-pill"},"IP"):R.here&&R.cert?e("span",{class:"dl-pill ok"},"Recommended"):""])}),e("div",{class:"dl-addr-opt other"},[e("i",{class:"dl-addr-check"},w("plus")),u,z("Add",()=>{let R=u.value.trim().toLowerCase();R&&(J(R),_.includes(R)||(_=[..._,R]),u.value="",D(),f())})])]);u.addEventListener("keydown",R=>{R.key==="Enter"&&(R.preventDefault(),u.nextElementSibling?.click())});let T=e("div",{class:"dl-links"}),f=()=>{let R=We(d),oe=Number(l.value)||a.portal_port;dom.content(T,_.map((M,S)=>{let x=$(M),E=x?R?80:oe+1:R&&!this.d.wan443_taken?443:oe,A=`${x?"http":"https"}://${M}${E===(x?80:443)?"":`:${E}`}/`;return e("div",{class:"dl-link-row"},[e("span",{class:`dl-link-ic ${x?"warn":"ok"}`},w(x?"alert":"lock")),e("span",{class:"dl-mono dl-link-url"},[A,e("b",{},"kamiro-telosu-bavine")]),S===0?e("span",{class:"dl-pill info"},"Main"):x?e("span",{class:"dl-pill warn"},"HTTP"):""])}))};D(),f(),l.addEventListener("input",()=>f());let g={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"},k=o.filter(R=>R.status!=="skip"),c=k.filter(R=>R.status==="error"||R.status==="warn"),p=k.some(R=>R.status==="error")?"error":c.length?"warn":"ok",C=e("div",{class:"dl-ready-details",hidden:!0},k.map(R=>e("div",{class:`dl-ready-item ${R.status}`},[w(R.status==="ok"?"check":"alert"),e("span",{class:"dl-stack"},[e("span",{},R.title),e("span",{class:"dl-sub"},R.detail)])]))),v=e("div",{class:"dl-stack gap8"},[e("div",{class:`dl-ready-sum ${p}`},[w(p==="ok"?"check":"alert"),e("span",{class:"dl-stack"},[e("b",{},p==="ok"?`All ${k.length} checks passed`:`${k.length-c.length} of ${k.length} checks passed`),c.length?e("span",{class:"dl-sub"},c.map(R=>R.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:R=>{C.hidden=!C.hidden,R.currentTarget.textContent=C.hidden?"Details":"Hide"}},"Details")]),e("div",{class:"dl-chips-row"},k.map(R=>e("span",{class:`dl-check-chip ${R.status}`,title:R.detail},[w(R.status==="ok"?"check":"alert"),g[R.id]??R.title]))),C]),b=n&&!n.self_signed&&n.expires?new Date(n.expires).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}):"",j=Q("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."),q=Q("Listening port",l,this.d.port_owners.length?`Port ${a.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 ${a.portal_port+1}.`),H=!!(t.portal_cert&&t.portal_key),Z=n?H?"Your files":n.self_signed?"Self-signed":"Let’s Encrypt":"Portal is off",ee=()=>{let R=se(t.portal_cert,{placeholder:"/etc/ssl/…/fullchain.crt"}),oe=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."),Q("Certificate file",R),Q("Key file",oe)],[e("button",{class:"cbi-button cbi-button-neutral",click:Y},"Cancel")," ",z("Save",()=>{Y(),this.save({portal_cert:R.value.trim(),portal_key:oe.value.trim()},"Certificate saved")},"positive")])},ie=this.d.needs??{https:[],acme:[],home:[]},ue=(R,oe,M,S,x,E)=>e("div",{class:`dl-row dl-need-row ${oe}`},[oe?e("span",{class:"dl-need-ic"},w(R)):w(R),e("span",{class:"dl-row-main dl-stack"},[e("b",{},M),e("span",{class:"dl-sub"},S)]),z(E,()=>tt(x,ie[x],()=>this.reload()),"positive")]),he=ie.https.length?ue("lock","bad","HTTPS isn’t available on this router",`The portal needs ${ie.https.join(" and ")}. It can’t start without them.`,"https","Install"):"",Te=ie.acme.length&&(!n||n.self_signed)?ue("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"):"",yt=[e("div",{class:"dl-row"},[w("lock"),e("span",{class:"dl-row-main dl-stack"},[e("b",{},[Z,b?e("span",{class:"dl-faint"},` · until ${b}`):""]),e("span",{class:"dl-sub dl-ellipsis",title:n?.path??""},n?n.self_signed?"Made by the router: browsers warn until a certificate covers the address.":`${H?"Your files":"Found automatically"} · ${n.path}`:"Turn the portal on to see its certificate.")])]),e("div",{class:"dl-row"},[w("file"),e("span",{class:"dl-row-main dl-stack"},[e("b",{},"Your own files"),e("span",{class:"dl-sub"},H?`${t.portal_cert} · ${t.portal_key}`:"Not set: the certificate is picked automatically.")]),H?z("Reset",()=>this.save({portal_cert:"",portal_key:""},"Automatic certificate"),"negative"):"",z(H?"Change":"Use files",ee)]),Te];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."),he?e("div",{class:"dl-list"},[he]):"",we("network","Ports","How the portal listens",[j,q]),we("edit","Appearance","What people see",[Q("Title",h,"Shown at the top of the portal."),Q("Unknown links",m,"Where a wrong or old link goes, for example your website. Empty shows a plain “Not found”.")]),we("link","Addresses","Pick one or more; the first is the main link",[B,e("div",{class:"dl-stack gap8"},[T,e("span",{class:"dl-sub"},"Example code; each person gets their own three words.")])]),we("lock","Certificate","Used for HTTPS links",yt),a.portal_enabled&&k.length?we("check","Ready to share","The portal’s checks from Health",[v]):""],[e("span"),z("Save",()=>this.save({portal_enabled:We(r)?"1":"0",portal_443:We(d)?"1":"0",portal_host:_[0]??"",portal_alt:_.slice(1),portal_port:l.value,portal_title:h.value,portal_redirect:m.value.trim()}),"positive")],"",[a.portal_enabled?ie.https.length?e("span",{class:"dl-pill bad"},"Can’t start"):e("span",{class:`dl-pill ${p==="ok"?"ok":p==="error"?"bad":"warn"}`},p==="error"?"Needs attention":"Ready"):"",r])}paint(){let t=this.d.settings,a=this.d.effective,n=this.portalSection(),i=se(t.default_device_limit,{placeholder:"3",inputmode:"numeric",class:"cbi-input-text dl-w-port"}),o=nt(a.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||a.home_dns_fallback||"",{placeholder:"None",inputmode:"decimal",class:"cbi-input-text dl-w-ip dl-mono"}),d=this.section("defaults","Defaults",[Q("Devices per person",i,"Pre-filled when you add someone."),Q("Device hostnames",e("div",{class:"dl-hostport"},[o,e("span",{class:"dl-faint dl-mono"},"phone.myata."),r]),"Name devices in your home DNS."),Q("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"),z("Save",()=>this.save({default_device_limit:i.value,hostnames:We(o)?"1":"0",domain:r.value,home_dns_fallback:l.value}),"positive")]),h=nt(a.geo_enabled,"Locations"),m=e("select",{class:"cbi-input-select"},[e("option",{value:"ipwho.is",selected:a.geo_provider!=="ipapi.co"?"selected":null},"ipwho.is (fallback: ipapi.co)"),e("option",{value:"ipapi.co",selected:a.geo_provider==="ipapi.co"?"selected":null},"ipapi.co (fallback: ipwho.is)")]),u=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."),h]),Q("Provider",m)],[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."),z("Save",()=>this.save({geo_enabled:We(h)?"1":"0",geo_provider:m.value}),"positive")]),$=this.logsSection(),_=this.d.services.map(B=>e("div",{class:"dl-row"},[w("home"),e("span",{class:"dl-row-main dl-stack"},[e("b",{},B.name),e("span",{class:"dl-mono dl-faint"},`${B.address}${B.ports.length?` · ports ${B.ports.join(", ")}`:" · all ports"}`)]),z("Edit",()=>this.editService(B)),z([w("trash")],async()=>{await ae(`Remove ${B.name}?`,"People limited to this service lose access to it.","Remove",!0)&&await O(()=>P.serviceDelete(B.id),"Removed")&&this.reload()},"negative",{title:"Remove"})])),N=this.section("services","Home services",[e("p",{class:"dl-muted"},"Give people with home-network access only specific services instead of the whole network (choose them per person)."),e("div",{class:"dl-list"},_.length?_:[e("div",{class:"dl-row dl-muted"},"No services yet.")])],[e("span"),z([w("plus")," Add service"],()=>this.editService(null),"add")]),J=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"),z("Remove",()=>this.uninstall(),"negative")],"danger"),V=Bt(this.backups,()=>{this.reload(),this.loadBackups()});dom.content(this.root,[n,d,u,$,N,V,J])}logsSection(){let t=this.d.logs,a=t.policy,n=st([["7","7 days"],["30","30 days"],["90","90 days"],["365","1 year"],["0","No limit"]],String(a.keep_days),"Keep activity"),i=st([["500","500"],["2000","2,000"],["5000","5,000"],["20000","20,000"]],String(a.max),"Maximum events"),o=st([["10min","Every 10 min"],["hourly","Hourly"],["off","Memory only"]],a.persist,"Save to flash"),r=st([["31","1 month"],["62","2 months"],["180","6 months"],["365","1 year"],["730","2 years"]],String(a.usage_days),"Daily traffic"),l=st([["12","1 year"],["24","2 years"],["60","5 years"],["120","10 years"]],String(a.usage_months),"Monthly traffic"),d=new Set(a.categories),h=e("div",{class:"dl-chips-row"},je.map(N=>{let J=e("button",{type:"button",class:`dl-chipbtn${d.has(N)?" on":""}`,title:an[N],click:()=>{d.has(N)?d.delete(N):d.add(N),J.classList.toggle("on",d.has(N))}},[Oe[N],e("b",{},String(t.by_category[N]??0))]);return J})),m=N=>new Date(N).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}),u=t.oldest?m(new Date(t.oldest*1e3)):"",$=(N,J,V,B)=>e("div",{class:"dl-row"},[w(N),e("span",{class:"dl-row-main dl-stack"},[e("b",{},J),e("span",{class:"dl-sub"},V)]),...B]),_=N=>z(N.toUpperCase(),async()=>{let[J,V]=await Promise.all([P.status(1),P.events(2e4)]);ve(J,V.events,N)},"neutral",{title:`Download the log as ${N.toUpperCase()}`});return this.section("logs","Logs & history",[e("p",{class:"dl-muted"},Ht(a)),Q("Keep activity",n,"Older events are removed automatically."),Q("Maximum size",i,"Newest events are kept when the log is full."),Q("Record",h,"Switched-off categories are not logged from now on."),Q("Save to flash",o,"The log lives in memory and is copied to flash. Memory only saves flash writes but is lost on reboot."),Q("Daily traffic",r,"Per-day history behind the charts."),Q("Monthly traffic",l,"Per-month totals; data limits use the current month."),e("h4",{class:"dl-setsub"},"Stored data"),e("div",{class:"dl-list"},[$("activity","Activity log",t.events?`${jt(t.events,"event")} since ${u} · ${gt(t.log_ram)} in memory${a.persist==="off"?"":`, ${gt(t.log_flash)} on flash`}`:"Empty",[_("csv"),_("json"),z("Clear",()=>Ce("Clear activity","Removes events from the log on the router.",{},()=>this.reload()),"negative")]),$("chart","Traffic history",t.usage_days?`${jt(t.usage_days,"day")} since ${m(t.usage_since)} · ${gt(t.usage_flash)} on flash`:"Empty",[z("Reset",()=>qe("all","","",()=>setTimeout(()=>this.reload(),300)),"negative")]),$("pin","Location cache",`${jt(this.d.geo_cached,"address","addresses")} · ${gt(t.geo_flash)} on flash`,[z("Clear",async()=>{await O(()=>P.geoClear(),"Location cache cleared")&&this.reload()},"negative")])])],[e("span",{class:"dl-sub"},"Clear one person or device from their own page."),z("Save",()=>this.save({log_keep_days:n.dataset.value,log_max:i.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 P.backupList().catch(()=>null);if(t){this.backups=t.backups;let a=document.getElementById("dl-set-backups");a&&a.replaceWith(Bt(this.backups,()=>{this.reload(),this.loadBackups()}))}}async reload(){let t=await P.settingsGet().catch(()=>null);t&&(this.d=t,this.paint())}editService(t){let a=se(t?.name??"",{placeholder:"NAS"}),n=se(t?.address??"",{placeholder:"192.168.1.10"}),i=se(t?.ports.join(", ")??"",{placeholder:"All ports, or e.g. 445, 5000"});ne(t?`Edit ${t.name}`:"Add service",[e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},"Name"),e("div",{class:"cbi-value-field"},a)]),e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},"Address"),e("div",{class:"cbi-value-field"},n)]),e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},"Ports"),e("div",{class:"cbi-value-field"},i)])],[e("button",{class:"cbi-button cbi-button-neutral",click:Y},"Cancel")," ",z("Save",async()=>{let o=i.value.split(/[ ,]+/).filter(Boolean);await O(()=>P.serviceSet(t?.id??"",a.value,n.value,o),"Saved")&&(Y(),this.reload())},"positive")])}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:Y},"Cancel")," ",z("Remove Dawnline",async()=>{await O(()=>P.uninstall(t.value.trim()),"Dawnline removed")&&(Y(),setTimeout(()=>location.reload(),800))},"negative")])}};var Da={ok:"check",warn:"alert",error:"x",skip:"pause"},xn={apply:"Repair",sync:"Reload devices",restart:"Restart service",updates:"Open updates"},bt=class{load(){return P.health()}render(t){return this.root=e("div",{class:"dl-root"}),this.paint(t.checks),e("div",{},[e("h2",{},"Health"),e("div",{class:"cbi-map-descr"},"Everything Dawnline depends on, checked live. Problems come with a fix button where one exists."),this.root])}paint(t){let a=t.filter(i=>i.status==="error").length,n=t.filter(i=>i.status==="warn").length;dom.content(this.root,[a?Ee("error",`${a} problem${a>1?"s":""} need attention.`):n?Ee("warn",`${n} warning${n>1?"s":""}.`):Ee("ok","All checks passed."),e("div",{class:"dl-panel"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Checks"),e("span",{class:"dl-spacer"}),z("Run again",async()=>{let i=await O(()=>P.health());i&&this.paint(i.checks)})]),e("ul",{class:"dl-checks"},t.map(i=>e("li",{},[e("span",{class:`dl-check-icon ${i.status}`},w(Da[i.status])),e("div",{class:"dl-check-body"},[e("div",{class:"dl-check-title"},i.title),e("div",{class:"dl-check-detail"},i.detail)]),i.fix?i.fix.startsWith("install:")?z("Install",()=>hn(i.fix.slice(8),async()=>{let o=await P.health().catch(()=>null);o&&this.paint(o.checks)}),"action"):i.fix==="updates"?e("a",{class:"cbi-button cbi-button-action",href:L.url("admin/network/dawnline/updates")},xn.updates):z(xn[i.fix]??"Fix",async()=>{let o=await O(()=>P.healthFix(i.fix),"Done");o&&this.paint(o.checks)},"action"):""])))])])}},Aa=[{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}],xt=class{constructor(){this.running=!1}load(){return P.updatesStatus()}render(t){return this.root=e("div",{class:"dl-root dl-upd"}),this.paint(t),poll.add(async()=>{let a=await P.updatesStatus().catch(()=>null);a&&a.job?.state==="running"?this.paint(a):a&&this.running&&(this.running=!1,this.paint(a),a.job?.component==="app"&&a.job.state==="done"&&setTimeout(()=>location.reload(),1500))},3),this.root}paint(t){let a=t.job;this.running=a?.state==="running";let n=t.check?.components??{},i=t.firmware,o=n.app,r=n.amneziawg,l=n.packages,d={disabled:this.running},h=(v,b)=>e("span",{class:`dl-pill ${v}`},b),m=(v,b,j)=>e("div",{class:"dl-upd-row"},[e("span",{class:"dl-stack"},[e("span",{class:"dl-upd-name"},v),e("span",{class:"dl-sub"},b)]),j]),u=(v,b,j,q,H=[])=>e("section",{class:"dl-setsec dl-upd-sec"},[e("div",{class:"dl-upd-head"},[e("span",{class:"dl-group-ic"},w(v)),e("span",{class:"dl-stack"},[e("b",{},b),e("span",{class:"dl-sub"},j)]),q]),...H]),$=v=>v?new Date(v).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}):"",_=u("sunrise","Dawnline",o?.repo?`${t.version} · ${o.repo}`:t.version,o?o.update?z(`Update to ${o.latest}`,()=>this.run("app"),"positive",d):o.latest?h("ok","Up to date"):h("","No releases yet"):h("","Not checked")),N=r?.sources??{},V=Object.keys(N).map(v=>{let b=N[v],j=r?.current===v,q=[b.version?`${b.tag} build${b.date?` · ${$(b.date)}`:""} · ${b.gen==="3.1"?"devices need AmneziaVPN with 3.1":"works with every AmneziaWG app"}`:`No build for OpenWrt ${i?.version??""}`],H=b.version?j?r?.update?z("Update",()=>this.runAwg(v,!!r.ru,b.gen),"positive",d):h("ok","Installed"):z("Switch",()=>this.runAwg(v,!!r?.ru,b.gen),"neutral",d):h("","No build");return m([b.gen?`AmneziaWG ${b.gen}`:"AmneziaWG",e("span",{class:"dl-faint"},` · ${b.label}`)],q,H)});r?.current&&N[r.current]?.version&&V.push(m("Russian translation","LuCI pages for AmneziaWG in Russian",z(r.ru?"Remove":"Add",()=>this.runAwg(r.current,!r.ru,r.gen),"neutral",d)));let B=u("shield","AmneziaWG",r?.installed?`${r.gen?`${r.gen} · `:""}${r.installed} · changing it restarts every tunnel`:"Not installed",r?"":h("","Not checked"),V.length?V:[m("Builds for this router","Check for updates to see them.","")]),y=l?.pkgs??{},D=[],T=Aa.filter(v=>v.feature==="home"?t.home:t.portal);for(let v of T){let b=v.pkgs.filter(H=>y[H]?.installed),j=[...new Set(b.flatMap(H=>[...y[H]?.latest?[H]:[],...y[H]?.with??[]]))],q=t.needs?.[v.feature]??v.pkgs.filter(H=>!y[H]?.installed);if(q.length)D.push(m(v.title,v.optional?`Not installed · ${v.sub}`:e("span",{class:"dl-upd-bad"},`Missing ${q.join(", ")} · ${v.sub}`),z("Install",()=>this.runPkgs(q,v.title),"neutral",d)));else if(j.length){let H=b.find(ie=>y[ie]?.latest),Z=H?[e("span",{class:"dl-mono"},[`${y[H].installed} → `,e("b",{},y[H].latest)])]:[],ee=j.filter(ie=>ie!==H);ee.length&&Z.push(`${H?" · ":""}${ee.length<=2?`${H?"with ":""}${ee.join(", ")}`:`${H?"+":""}${ee.length} related packages`}`),D.push(m(v.title,Z,z("Update",()=>this.runPkgs(b.filter(ie=>y[ie]?.latest||y[ie]?.with?.length),v.title,j),"neutral",d)))}else D.push(m(v.title,v.sub,h("ok","Up to date")))}let f=T.flatMap(v=>v.pkgs).filter(v=>y[v]?.installed),g=[...new Set(f.flatMap(v=>[...y[v].latest?[v]:[],...y[v].with??[]]))],k=u("package","System packages",l?g.length?`${g.length} update${g.length===1?"":"s"} from the OpenWrt ${i?.version?.replace(/\.\d+$/,"")??""} feeds`:"What Dawnline adds to OpenWrt is current":"What Dawnline adds to OpenWrt",l?g.length?z("Update all",()=>this.runPkgs(f.filter(v=>y[v].latest||y[v].with?.length),"all packages",g),"positive",d):"":h("","Not checked"),l?D:[]),c=a?e("details",{class:"dl-params dl-upd-job",open:this.running?"open":null},[e("summary",{},[w("chevron"),e("span",{},"Last job"),h(a.state==="done"?"ok":a.state==="failed"?"bad":"warn",a.state==="running"?a.phase||"Running":a.state==="done"?"Finished":"Failed"),e("span",{class:"dl-sub"},`${a.action==="check"?"check":a.component??""} · ${St(a.started)}${a.finished?` · ${a.finished-a.started} s`:""}`)]),a.error?Ee("error",a.error):"",e("pre",{class:"dl-log"},a.log.join(` +`))]):"",p=g.length+(o?.update?1:0)+(r?.update?1:0),C=[i?.version?`OpenWrt ${i.version} · ${i.target}`:"",t.check?p?`${p} update${p===1?"":"s"} ready`:"everything is current":"not checked yet",t.check?`checked ${St(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"},C)]),z([w("refresh")," Check now"],()=>this.run("check"),"neutral",d)]),_,B,k,c])}async runAwg(t,a,n){await ae(n?`Install AmneziaWG ${n}?`:"Install AmneziaWG?","Every AmneziaWG tunnel on the router restarts for a few seconds, HomeTunnel too. Devices stay configured.","Install")&&this.start(`amneziawg:${t}${a?":ru":""}`)}async runPkgs(t,a,n=t){await ae(`Update ${a}?`,`${n.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 ae(`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(()=>P.updatesRun(t))){this.running=!0;let a=await P.updatesStatus().catch(()=>null);a&&this.paint(a)}}};function Ot(s){return`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")}`}function Pa(s,t,a,n=30){let i=s?new Date(`${s}T12:00:00`):new Date;return t==="day"?i.setDate(i.getDate()+a):t==="week"?i.setDate(i.getDate()+7*a):t==="month"?i.setMonth(i.getMonth()+a):t==="year"?i.setFullYear(i.getFullYear()+a):i.setDate(i.getDate()+n*a),Ot(i)}var za={internet:"Browse the internet through your router. No access to devices at home.",lan:"Reach devices at home. Internet stays on their own connection.",both:"Home devices and the internet, all through your router."},wt=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,a,n]=await Promise.all([P.status(30),P.events(5e3).catch(()=>({events:[]})),P.personUsage(this.id,30).catch(()=>null)]);return this.series=n?.person??[],this.devSeries=n?.devices??{},[t,a.events]}render([t,a]){this.st=t,this.events=a,xe(t);let n=t.people.find(l=>l.id===this.id);if(!n)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=n;for(let l of["head","devices","traffic","places","activity","limits"])this.parts[l]=e("div",{});this.parts.devices.className="dl-person-devices";let i=e("div",{},[e("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[e("a",{href:Qe(n.server)},t.servers.find(l=>l.id===n.server)?.name??"Servers"),e("span",{},"/"),e("a",{href:Qe(n.server)},"People"),e("span",{},"/"),e("span",{},n.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")&&n.devices.find(l=>l.id===o.get("device"));return r?setTimeout(()=>De(this.p,r,()=>this.refresh(),this.st.geo),50):o.get("add")&&setTimeout(()=>Re(this.p,()=>this.refresh()),50),poll.add(()=>this.refresh(!0),15),i}async refresh(t=!1){let a=++this.refreshSeq,[n,i,o]=await Promise.all([P.status(30).catch(()=>null),P.events(5e3).catch(()=>null),P.personUsage(this.id,30).catch(()=>null)]);if(!n||al.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,a){var o;let n=await O(()=>P.personUpdate(this.p.id,t),a);if(!n)return;let i=this.st.people.findIndex(r=>r.id===this.p.id);(o=n.person).rate??(o.rate=this.p.rate),i>=0&&(this.st.people[i]=n.person),this.p=n.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?ut("30d",a=>this.map?.setRange(a),!1):"",z("Hide",()=>{this.mapOpen=!1,this.map?.destroy(),this.map=null,this.paintPlaces()},"neutral")]);return this.st.geo.enabled?(this.map=new Ge({openPerson:()=>{},openDevice:(a,n)=>{let i=this.p.devices.find(o=>o.id===n);i&&De(this.p,i,()=>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,a=this.st,n=t.online?"online now":t.last_seen?`last seen ${ce(t.last_seen,a.now)}`:"never connected",i=this.series.find(u=>u.day===Ot(new Date));dom.content(this.parts.traffic,e("div",{class:`dl-person-live${t.online?"":" solo"}`},[t.online?At(t.rate??[],a.now,i?[i.rx,i.tx]:[0,0]):"",Pt(this.series,`${K(t.month[0]+t.month[1])} this month`)]));let o=t.created?`Added ${_e(Ot(new Date(t.created*1e3)))}`:"",r=[{label:"Rename",icon:w("edit"),run:()=>this.rename()},{label:t.note?"Edit note":"Add note",icon:w("file"),run:()=>this.editNote()},...t.link?[null,{label:"Invite card",icon:w("qr"),run:()=>this.invite()},{label:"New link",icon:w("key"),run:()=>this.newLink()}]:[],null,{label:t.paused?"Resume":"Pause",icon:w(t.paused?"play":"pause"),warn:!t.paused,run:()=>this.patch({paused:!t.paused},t.paused?"Resumed":"Paused")},{label:"Delete",icon:w("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":""}`},Le(t.name)),e("div",{class:"dl-stack"},[e("div",{class:"dl-title-row"},[e("h2",{class:"dl-h1"},t.name),zt(t)]),e("span",{class:"dl-faint",title:o},`${t.devices.length} of ${t.device_limit} devices · ${n}`)])]),e("div",{class:"dl-pcard-actions"},[t.link?ye("link","Copy link",()=>re(t.link,"Personal link copied"),"neutral","dl-icon-only"):"",ye("more","More",u=>ke(u.currentTarget,r),"neutral","dl-icon-only")])]),t.note?e("button",{type:"button",class:"dl-pnote",title:"Edit note",click:()=>this.editNote()},[w("file"),e("span",{},t.note)]):""])),this.paintDevices(),this.paintLimits(),this.paintPlaces();let l=this.events.filter(u=>u.person===t.id),d=[],h=[...l].reverse();for(let u=0;u1){let J=N.querySelector(".dl-row-main");dom.content(J,[...Xe(a,$).slice(0,2),e("span",{class:"dl-muted"},`${_} times`)]),J.title=h.slice(u,u+_).map(V=>V.detail??"").join(` +`)}d.push(N),u+=_-1}let m=z([w("more")],()=>ke(m,[{label:"Export CSV",icon:w("download"),run:()=>ve(this.st,l,"csv",t.id)},{label:"Export JSON",icon:w("download"),run:()=>ve(this.st,l,"json",t.id)},null,{label:`Clear ${t.name}'s activity`,icon:w("trash"),danger:!0,run:()=>Ce(`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"}),m]),d.length?d:e("div",{class:"dl-row dl-muted"},"Nothing yet.")]))}deviceStatus(t){return t.disabled?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),"Disabled"]):t.online?e("span",{class:"dl-dstat ok"},[e("i",{class:"dot ok"}),`Online · ${ce(t.handshake,this.st.now).replace(" ago","")}`]):t.handshake?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),`Last seen ${ce(t.handshake,this.st.now)}`]):e("span",{class:"dl-dstat warn",title:"Waiting for the first connection"},[e("i",{class:"dot warn"}),"Not set up yet"])}addrs(t){if(!t.online||!t.endpoint)return"";let a=this.st.geo?.points.find(o=>o.device===t.id&&o.ip===t.endpoint),n=a?.city?`Client IP · ${a.city}${a.org?` · ${a.org}`:""}`:"Client IP",i=e("button",{type:"button",class:"dl-addr wan","aria-label":`Copy ${t.endpoint}`,click:()=>re(t.endpoint,"Client IP copied")},[w("globe"),e("span",{},t.endpoint)]);return le(i,()=>[e("div",{class:"dl-tip-title"},n),e("div",{class:"dl-muted"},"Click to copy")]),e("div",{class:"dl-addrs"},i)}deviceBars(t){let a=(this.devSeries[t]??[]).slice(-30),n=a.map(r=>r.rx+r.tx),i=Math.max(1,...n),o=r=>new Date(`${r}T12:00:00`).toLocaleDateString("en-GB",{day:"numeric",month:"short"});return e("div",{class:"dl-dbars"},a.map((r,l)=>{let d=e("i",{class:`${n[l]?"":"zero"}${l===a.length-1?" hi":""}`});return d.style.height=`${Math.max(8,n[l]/i*100)}%`,le(d,()=>[e("div",{class:"dl-tip-title"},l===a.length-1?`Today · ${o(r.day)}`:o(r.day)),e("div",{},K(n[l]))]),d}))}paintDevices(){let t=this.p,a=()=>this.refresh(),n=t.devices.map(o=>{let r=()=>De(t,o,a,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"},w(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"):""]),z([w("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",{},K(o.month[0]+o.month[1])),e("span",{class:"dl-sub"},"this month")]),this.deviceBars(o.id)]):o.disabled?e("div",{class:"dl-sub"},`${Me[o.kind]} · created ${ce(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)},[w("qr"),"Show QR"]),e("button",{type:"button",class:"dl-chipbtn",click:()=>this.downloadConfig(o)},[w("download"),"Config"])]),this.addrs(o)])}),i=Math.max(0,t.device_limit-t.devices.length);i&&n.push(e("button",{type:"button",class:"dl-dslot add",click:()=>Re(t,a)},[e("span",{class:"dl-dslot-ic"},w("plus")),e("b",{},"Add device")])),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("span",{class:"dl-spacer"}),i?"":z([w("plus")," Add device"],()=>Re(t,a),"neutral",{title:"Over the limit — admins can still add"})]),e("div",{class:"dl-dgrid"},n)]))}paintLimits(){let t=this.p,a=e("div",{class:"dl-seg wide",role:"radiogroup","aria-label":"Access"},["internet","lan","both"].map(c=>e("button",{type:"button",role:"radio",class:t.access===c?"on":"","aria-checked":t.access===c?"true":"false",click:()=>t.access!==c&&this.patch({access:c},`Access: ${Be[c]}`)},[w(c==="internet"?"globe":c==="lan"?"home":"shield"),c==="internet"?"Internet":c==="lan"?"Home":"Both"]))),n=ze(t.expires),i=e("input",{type:"date",class:"dl-date-hidden",value:t.expires,tabindex:"-1","aria-hidden":"true"});i.addEventListener("change",()=>i.value&&this.patch({expires:i.value},`Access until ${_e(i.value)}`));let o=(c,p,C)=>{let v=Pa(t.expires&&(n??-1)>=0?t.expires:"",c,p);return this.patch({expires:v},`Access until ${_e(v)}`),C},r=[["week",1,"+1 week"],["month",1,"+1 month"],["month",3,"+3 months"],["year",1,"+1 year"]].map(([c,p,C])=>e("button",{type:"button",class:"dl-chipbtn",click:()=>o(c,p,C)},C)),l=e("span",{class:"dl-datechip"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>{try{i.showPicker()}catch{i.focus()}}},[w("calendar"),t.expires?_e(t.expires):"Date"]),i]),d={pause:"pause access",notify:"keep access",remove:"remove their devices"}[t.expire_action],h=e("div",{class:"dl-tile2"},[e("div",{class:"dl-tile2-label"},[e("span",{},"Access ends"),t.expires?e("span",{class:n!=null&&n<0?"dl-bad":n!=null&&n<=t.expire_warn?"dl-warn":"dl-ok"},n!=null&&n<0?"ended":`${n} day${n===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:c=>{c.preventDefault(),this.endSettings()}},"Change")])]),m=t.quota_used||t.month[0]+t.month[1],u=t.quota_limit?Math.min(100,t.quota_used/t.quota_limit*100):0,$=e("div",{class:`dl-meter${u>=100?" bad":u>=90?" warn":""}`},[e("i"),t.quota_limit?e("span",{class:"mark",title:"Alert at 90%"}):""]);$.firstChild.style.width=`${u}%`,t.quota_limit&&le($,()=>[e("div",{class:"dl-tip-title"},`${u.toFixed(1)}% used`),e("div",{class:"dl-muted"},`${K(t.quota_used)} of ${K(t.quota_limit)} · ${K(Math.max(0,t.quota_limit-t.quota_used))} left`),e("div",{class:"dl-faint"},"Alert at 90%")]);let _=e("div",{class:"dl-seg sm"},["month","total"].map(c=>e("button",{type:"button",class:t.quota_period===c?"on":"",click:()=>t.quota_period!==c&&this.patch({quota_period:c})},c==="month"?"Monthly":"Total"))),N=[10,50,100].map(c=>e("button",{type:"button",class:`dl-chipbtn${t.quota_gb===c?" on":""}`,click:()=>this.patch({quota_gb:String(c)},`Data limit ${c} GB`)},`${c} GB`));N.push(e("button",{type:"button",class:`dl-chipbtn${t.quota_gb?"":" on"}`,click:()=>this.patch({quota_gb:""},"No data limit")},"Unlimited")),N.push(e("button",{type:"button",class:"dl-chipbtn",click:()=>{let c=prompt("Data limit in GB",t.quota_gb?String(t.quota_gb):"");c!=null&&c.trim()!==""&&Number(c)>0&&this.patch({quota_gb:c.trim()},`Data limit ${c.trim()} GB`)}},"Custom"));let J=e("div",{class:"dl-tile2"},[e("div",{class:"dl-tile2-label"},[e("span",{},"Data"),_]),e("div",{class:"dl-tile2-row"},[e("span",{class:"dl-tile2-value"},[K(m),t.quota_limit?e("span",{class:"dl-faint"},` of ${K(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?$:"",e("div",{class:"dl-chips-row"},N),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:c=>{c.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"},`${K(t.total[0]+t.total[1])} in total`),e("button",{type:"button",class:"dl-linkbtn danger",click:()=>qe("person",t.id,t.name,()=>setTimeout(()=>this.refresh(),300))},"Reset usage")])]),V=!!t.hours,[B,y]=(t.hours||"07:00-23:00").split("-"),D=e("input",{type:"time",class:"cbi-input-text",value:B}),T=e("input",{type:"time",class:"cbi-input-text",value:y}),f=()=>this.patch({hours:`${D.value}-${T.value}`},`Allowed ${D.value}–${T.value}`);D.addEventListener("change",f),T.addEventListener("change",f);let g=e("button",{type:"button",role:"switch","aria-checked":V?"true":"false",class:`dl-switch${V?" on":""}`,"aria-label":"Limit hours",click:()=>this.patch({hours:V?"":"07:00-23:00"},V?"Any time":"Allowed 07:00–23:00")},e("i")),k=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",{},V?`${B} – ${y} (router time)`:"Any time")]),g]),V?e("div",{class:"dl-tile2-row"},[D,e("span",{class:"dl-faint"},"to"),T]):""]);dom.content(this.parts.limits,e("section",{class:"dl-panel","aria-label":"Access and limits"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Access & limits")]),e("div",{class:"dl-stack gap8"},[e("span",{class:"dl-tile2-label"},"Can reach"),a,e("span",{class:"dl-sub"},za[t.access]),t.access==="lan"&&this.st.services.length?this.servicesPicker():"",t.access==="lan"?this.dnsPicker():""]),e("div",{class:"dl-tiles2"},[this.devTile(),h,J,k])]))}dnsPicker(){let t=this.p,a=e("div",{class:"dl-seg sm",role:"radiogroup","aria-label":"DNS"},[["device","Device’s own DNS"],["home","Home names"]].map(([i,o])=>e("button",{type:"button",role:"radio",class:t.dns_mode===i?"on":"","aria-checked":t.dns_mode===i?"true":"false",click:()=>t.dns_mode!==i&&this.patch({dns_mode:i},i==="home"?"Home names on — devices need their configuration again":"Device DNS — devices need their configuration again")},o))),n=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"),a]),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",n?[" (",e("span",{class:"dl-mono"},n)," 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.")])}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(a=>e("button",{type:"button",class:`dl-chipbtn${t.has(a.id)?" on":""}`,title:`${a.address}${a.ports.length?` · ${a.ports.join(", ")}`:""}`,click:()=>{t.has(a.id)?t.delete(a.id):t.add(a.id),this.patch({services:[...t]},t.size?"Home services updated":"Whole home network")}},a.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,a=e("div",{class:"dl-slots"});for(let o=0;o[e("div",{class:"dl-tip-title"},r?r.name:"Free slot"),e("div",{class:"dl-muted"},r?r.online?"Online":r.handshake?`Last seen ${ce(r.handshake,this.st.now)}`:"Not set up yet":"They can add a device here")]),a.appendChild(l)}let n=Math.max(1,t.devices.length),i=e("button",{type:"button","aria-label":"Allow fewer devices",disabled:t.device_limit<=n?"disabled":null,click:()=>this.patch({device_limit:String(t.device_limit-1)})},"−");return t.device_limit<=n&&t.devices.length>1&&le(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:()=>this.patch({device_limit:String(t.device_limit+1)})},"+")])]),a])}paintPlaces(){let t=this.st;if(!t.geo.enabled){dom.content(this.parts.places,e("div",{class:"dl-places"},[w("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 a=t.now-30*86400,n=t.geo.points.filter(r=>r.person===this.p.id&&r.ts>=a).sort((r,l)=>l.ts-r.ts),i=[...new Set(n.map(r=>r.city||r.country).filter(Boolean))],o=n[0];dom.content(this.parts.places,e("div",{class:"dl-places"},[w("pin"),e("div",{class:"dl-stack"},[e("span",{},o?o.city||o.country:"No locations yet"),e("span",{class:"dl-sub"},o?`${i.length} place${i.length===1?"":"s"} in 30 days${o.org?` · ${o.org}`:""}`:"Shown after a device connects")]),e("span",{class:"dl-spacer"}),n.length?z("Show map",()=>{this.mapOpen=!0,this.paintPlaces()},"neutral"):""]))}invite(){let t=this.st.servers.find(a=>a.id===this.p.server)?.name??"Home";Je(this.p,t)}showQr(){let t=this.p;t.link&&ne(`${t.name}’s link`,[e("div",{class:"dl-qr-pane"},[Pe(Ie(t.link),"dl-qr"),e("div",{class:"dl-hint"},"Scan with the phone camera to open the portal.")])],[e("button",{class:"cbi-button",click:Y},"Close")])}async newLink(){let t=this.p;if(!await ae("Create a new link?","The old link stops working right away.","Create new link",!0))return;let a=await O(()=>P.personRegen(t.id),"New link created");a?.link&&(t.link=a.link,re(a.link,"New link copied"),this.paint())}async showDeviceQr(t){let a=await O(()=>P.deviceConfig(t.id));a&&ne(`Set up ${t.name}`,[await Et(a)],[e("button",{class:"cbi-button",click:Y},"Close")])}async downloadConfig(t){let a=await O(()=>P.deviceConfig(t.id));if(a){if(!a.has_private_key){X("This device made its own keys in the browser; its configuration only exists there.","warning");return}ge(a.filename,a.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:Y},"Cancel")," ",z("Save",async()=>{Y(),await this.patch({note:t.value.trim()},t.value.trim()?"Note saved":"Note removed")},"positive")]),setTimeout(()=>t.focus(),50)}endSettings(){let t=this.p,a=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")]),n=e("select",{class:"cbi-input-select"},[0,1,3,7,14].map(i=>e("option",{value:i,selected:t.expire_warn===i?"selected":null},i?`${i} day${i===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"},a)]),e("div",{class:"cbi-value"},[e("label",{class:"cbi-value-title"},"Warn"),e("div",{class:"cbi-value-field"},[n,e("div",{class:"cbi-value-description"},"Shown in their portal and on the Overview.")])])],[e("button",{class:"cbi-button cbi-button-neutral",click:Y},"Cancel")," ",z("Save",async()=>{Y(),await this.patch({expire_action:a.value,expire_warn:n.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:Y},"Cancel")," ",z("Save",async()=>{Y(),await this.patch({name:t.value},"Renamed")},"positive")]),setTimeout(()=>t.select(),50)}async remove(){let t=this.p;await ae(`Delete ${t.name}?`,`All ${t.devices.length} devices are disconnected immediately and the personal link stops working.`,"Delete",!0)&&await O(()=>P.personDelete(t.id),"Deleted")&&(location.href=Qe(t.server))}};var Na=':root{--dl-card: var(--panel-bg, transparent);--dl-line: var(--border, 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, 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-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);justify-content:center}.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-meta{display:flex;flex-wrap:wrap;align-items:baseline;gap:2px 8px;margin:6px 0 0 44px;font-size:13px;line-height:20px;color:var(--dl-fg-muted);font-variant-numeric:tabular-nums}.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)}.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}.dl-search{min-width:240px}@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-meta,.dl-chips,.dl-quota{margin-left:0}.dl-btn-label{display:none}.dl-search{min-width:0;flex:1}}.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(--elevated, var(--dl-card));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)}.dl-srvtab i.dot.bad{background:var(--dl-bad)}.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;align-items:center;gap:10px}.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-searchbtn{display:inline-flex!important;align-items:center;gap:6px}.dl-searchbtn kbd{font-size:11px;padding:1px 5px;border-radius:5px;background:var(--dl-soft);color:var(--dl-fg-muted);font-family:inherit}.dl-toolbar-end{display:flex;align-items:center;gap:8px;margin-left:auto;flex-wrap:nowrap;min-width:0}.dl-toolbar-end .dl-search{flex:0 1 260px;min-width:160px}@media(max-width:640px){.dl-toolbar-end{flex-wrap:wrap;width:100%}.dl-toolbar-end .dl-search{flex:1 1 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-addrs{display:flex;flex-wrap:wrap;gap:6px;padding-top:12px;border-top:1px solid var(--dl-line);min-width:0}.dl-addr{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:6px;height:24px;padding:0 8px 0 6px;max-width:100%;border-radius:7px;background:var(--dl-soft);color:var(--dl-fg-muted);font:500 11.5px/1 var(--dl-mono)}.dl-addr .dl-icon{width:12px;height:12px;flex:0 0 auto;opacity:.8}.dl-addr span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.dl-addr:hover{background:var(--dl-soft-hover);color:var(--dl-fg)}.dl-addr:focus-visible{outline:2px solid var(--dl-ring);outline-offset:1px}.dl-addr.lan .dl-icon{color:var(--dl-accent);opacity:1}.dl-addr.wan .dl-icon{color:var(--dl-ok);opacity:1}.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-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-pill-dot{width:6px;height:6px;border-radius:50%;background:currentColor;display:inline-block}.dl-root kbd,.dl-pal kbd{font-family:var(--dl-mono);font-size:11px;line-height:16px;padding:0 6px;border-radius:4px;background:var(--dl-soft);color:var(--dl-fg-muted)}.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 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(--elevated, #131313);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(--elevated, #131313)!important;border-bottom-color:var(--elevated, #131313)!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(--elevated, #131313);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-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-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}.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:color-mix(in srgb,var(--dl-ok) 6%,var(--dl-soft));border:1px dashed color-mix(in srgb,var(--dl-ok) 55%,transparent)}.dl-chip.live:hover{background:color-mix(in srgb,var(--dl-ok) 11%,var(--dl-soft))}.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-search{display:flex;align-items:center;gap:8px;height:34px;padding:0 10px 0 12px;border:1px solid var(--input, var(--dl-line));border-radius:999px;background:var(--input-bg, transparent);width:280px;max-width:100%;color:var(--dl-fg-faint);box-sizing:border-box;min-width:0}.dl-search-input{border:0!important;background:transparent!important;box-shadow:none!important;outline:none;flex:1;min-width:0;color:var(--dl-fg);font:inherit;font-size:13px;padding:0!important;height:32px!important}.dl-select{height:34px!important;border-radius:999px!important;min-width:0!important;padding:0 30px 0 12px!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(--elevated, #131313);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(--elevated, #111));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-live{display:inline-flex;align-items:center;gap:8px;font-size:12px}.dl-live i.dot,.dl-dstat i.dot{width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);display:inline-block}.dl-live i.dot.ok{background:var(--dl-ok);box-shadow:0 0 0 3px var(--dl-ok-wash)}.dl-live i.dot.warn{background:var(--dl-warn)}.dl-live i.dot.pulse{animation:dl-wait 1.6s ease-in-out infinite}@keyframes dl-wait{0%,to{box-shadow:0 0 0 0 var(--dl-warn-wash)}50%{box-shadow:0 0 0 6px transparent}}.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:baseline;gap:10px;padding:7px 0;border-top:1px solid var(--dl-line);font-size:13px;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-pal-overlay{position:fixed;inset:0;z-index:1000;background:var(--scrim, rgba(0,0,0,.5));display:flex;justify-content:center;align-items:flex-start;padding:12vh 16px 0}.dl-pal{width:min(640px,100%);background:var(--elevated, #131313);color:var(--dl-fg);border-radius:16px;overflow:hidden;box-shadow:var(--shadow-menu, 0 16px 32px -8px rgba(0,0,0,.6));border:1px solid var(--dl-line)}.dl-pal-search{display:flex;align-items:center;gap:12px;height:56px;padding:0 16px;border-bottom:1px solid var(--dl-line);color:var(--dl-fg-faint)}.dl-pal-input{flex:1;border:0!important;background:transparent!important;box-shadow:none!important;outline:none;font:inherit;font-size:16px;color:var(--dl-fg);padding:0!important}.dl-pal-list{max-height:52vh;overflow:auto;padding:8px}.dl-pal-group{padding:8px 12px 4px;font-size:12px;font-weight:500;color:var(--dl-fg-faint)}.dl-pal-item{display:flex;align-items:center;gap:12px;min-height:40px;padding:0 12px;border-radius:8px;cursor:pointer;font-size:14px}.dl-pal-item.sel{background:var(--dl-soft-hover)}.dl-pal-item .dl-icon{color:var(--dl-fg-muted)}.dl-pal-label{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-pal-ic{width:16px}.dl-pal-empty{padding:16px 12px;color:var(--dl-fg-muted);font-size:14px}.dl-pal-foot{display:flex;gap:16px;padding:10px 16px;border-top:1px solid var(--dl-line);font-size:12px;color:var(--dl-fg-faint)}.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}';function wn(){let s=document.createElement("style");return s.dataset.dawnline="1",s.textContent=Na,s}function Ae(s,t){return()=>{let a=new s,n={load:()=>a.load(),render:async i=>{let o=await a.render(i),r=document.createElement("div");return r.className="dl-root",r.append(wn(),o),r},addFooter(){return a.noFooter?document.createElement("div"):this.super("addFooter",[])}};return t||Object.assign(n,{handleSave:null,handleSaveApply:null,handleReset:null}),n}}var ko=Ae(at,!1),$o=Ae(He,!0),_o=Ae(at,!1),Mo=Ae(vt,!1),Lo=Ae(wt,!1),So=Ae(mt,!1),To=Ae(bt,!1),Eo=Ae(xt,!1);return baseclass.extend({ activity: So, health: To, overview: ko, people: $o, person: Lo, server: _o, settings: Mo, updates: Eo }); diff --git a/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/activity.js b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/activity.js new file mode 100644 index 0000000..8692329 --- /dev/null +++ b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/activity.js @@ -0,0 +1,5 @@ +'use strict'; +'require view'; +'require dawnline.app as app'; + +return view.extend(app.activity()); diff --git a/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/health.js b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/health.js new file mode 100644 index 0000000..584a1f3 --- /dev/null +++ b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/health.js @@ -0,0 +1,5 @@ +'use strict'; +'require view'; +'require dawnline.app as app'; + +return view.extend(app.health()); diff --git a/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/overview.js b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/overview.js new file mode 100644 index 0000000..e12aa87 --- /dev/null +++ b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/overview.js @@ -0,0 +1,5 @@ +'use strict'; +'require view'; +'require dawnline.app as app'; + +return view.extend(app.overview()); diff --git a/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/people.js b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/people.js new file mode 100644 index 0000000..daf02ed --- /dev/null +++ b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/people.js @@ -0,0 +1,5 @@ +'use strict'; +'require view'; +'require dawnline.app as app'; + +return view.extend(app.people()); diff --git a/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/person.js b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/person.js new file mode 100644 index 0000000..e6a723f --- /dev/null +++ b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/person.js @@ -0,0 +1,5 @@ +'use strict'; +'require view'; +'require dawnline.app as app'; + +return view.extend(app.person()); diff --git a/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/server.js b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/server.js new file mode 100644 index 0000000..cb67351 --- /dev/null +++ b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/server.js @@ -0,0 +1,5 @@ +'use strict'; +'require view'; +'require dawnline.app as app'; + +return view.extend(app.server()); diff --git a/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/settings.js b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/settings.js new file mode 100644 index 0000000..e80a1f0 --- /dev/null +++ b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/settings.js @@ -0,0 +1,5 @@ +'use strict'; +'require view'; +'require dawnline.app as app'; + +return view.extend(app.settings()); diff --git a/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/updates.js b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/updates.js new file mode 100644 index 0000000..1362d03 --- /dev/null +++ b/package/luci-app-dawnline/htdocs/luci-static/resources/view/dawnline/updates.js @@ -0,0 +1,5 @@ +'use strict'; +'require view'; +'require dawnline.app as app'; + +return view.extend(app.updates()); diff --git a/package/luci-app-dawnline/root/etc/hotplug.d/iface/95-dawnline b/package/luci-app-dawnline/root/etc/hotplug.d/iface/95-dawnline new file mode 100644 index 0000000..00abe6c --- /dev/null +++ b/package/luci-app-dawnline/root/etc/hotplug.d/iface/95-dawnline @@ -0,0 +1,5 @@ +#!/bin/sh +# Load devices into a Dawnline tunnel whenever netifd (re)creates it. +[ "$ACTION" = ifup ] || exit 0 +[ -n "$(uci -q get "network.$INTERFACE._dawnline")" ] || exit 0 +/usr/bin/dawnline sync >/dev/null 2>&1 & diff --git a/package/luci-app-dawnline/root/etc/init.d/dawnline b/package/luci-app-dawnline/root/etc/init.d/dawnline new file mode 100755 index 0000000..d8e0a67 --- /dev/null +++ b/package/luci-app-dawnline/root/etc/init.d/dawnline @@ -0,0 +1,65 @@ +#!/bin/sh /etc/rc.common +# shellcheck shell=dash disable=SC2034 # START/STOP/USE_PROCD are read by /etc/rc.common +# Dawnline: AmneziaWG access server — agent and personal portal. + +START=95 +STOP=10 +USE_PROCD=1 + +PORTAL_ROOT=/usr/share/dawnline/portal/www + +start_portal() { + local enabled port certs cert key hport http + config_get_bool enabled settings portal_enabled 0 + [ "$enabled" = 1 ] || return 0 + config_get port settings portal_port 8443 + certs="$(/usr/bin/dawnline portal-cert 2>/dev/null)" + cert="${certs% *}" + key="${certs#* }" + [ -f "$cert" ] && [ -f "$key" ] || return 0 + # IP addresses in links get plain HTTP on the next port (names stay HTTPS-only). + hport="$(/usr/bin/dawnline portal-http-port 2>/dev/null)" + [ -n "$hport" ] && http="-p 0.0.0.0:$hport -p [::]:$hport" + + procd_open_instance portal + procd_set_param command /usr/sbin/uhttpd -f -h "$PORTAL_ROOT" -x /cgi-bin -E /cgi-bin/portal \ + -D -n 16 -N 64 -t 20 -T 30 -k 10 -A 1 \ + -s "0.0.0.0:$port" -s "[::]:$port" -C "$cert" -K "$key" $http + procd_set_param file "$cert" + procd_set_param respawn 3600 5 0 + procd_close_instance +} + +# Plain DNS for Home-only tunnel devices (config written by `dawnline apply`). +start_resolver() { + [ -f /var/etc/dawnline-dns.conf ] || return 0 + procd_open_instance dns + procd_set_param command /usr/libexec/dawnline/resolver + procd_set_param file /var/etc/dawnline-dns.conf + procd_set_param respawn 3600 5 0 + procd_close_instance +} + +start_service() { + config_load dawnline + mkdir -p /var/run/dawnline + /usr/bin/dawnline apply >/dev/null 2>&1 + + procd_open_instance agent + procd_set_param command /usr/libexec/dawnline/agent + procd_set_param respawn 3600 5 0 + procd_set_param stderr 1 + procd_close_instance + + start_portal + start_resolver +} + +reload_service() { + /usr/bin/dawnline apply >/dev/null 2>&1 + start +} + +service_triggers() { + procd_add_reload_trigger dawnline +} diff --git a/package/luci-app-dawnline/root/etc/uci-defaults/90_dawnline b/package/luci-app-dawnline/root/etc/uci-defaults/90_dawnline new file mode 100755 index 0000000..6b77c98 --- /dev/null +++ b/package/luci-app-dawnline/root/etc/uci-defaults/90_dawnline @@ -0,0 +1,33 @@ +#!/bin/sh +# Dawnline first-run / upgrade housekeeping. + +[ -f /etc/config/dawnline ] || cat > /etc/config/dawnline <<'CFG' +config settings 'settings' + option portal_enabled '0' + option portal_port '8443' + option default_device_limit '3' + option hostnames '1' +CFG +chmod 600 /etc/config/dawnline +mkdir -p /etc/dawnline && chmod 700 /etc/dawnline +# Webhook alerts were removed. +uci -q delete dawnline.settings.webhook_url +uci -q delete dawnline.settings.alert +uci -q commit dawnline +rm -f /etc/dawnline/alerts.json +# Backups moved into Settings. +rm -f /www/luci-static/resources/view/dawnline/backups.js +# Portal assets moved out of the web root (served only with a valid code). +rm -rf /usr/share/dawnline/portal/www/assets + +# LuCI caches: menu index, and module URLs (?v= follows the opkg status time). +rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null +touch /usr/lib/opkg/status 2>/dev/null + +/etc/init.d/rpcd reload +# A reload keeps LuCI logins but sometimes misses the plugin; restart only then. +sleep 2 +ubus list luci.dawnline >/dev/null 2>&1 || { /etc/init.d/rpcd restart; sleep 2; } +/etc/init.d/dawnline enable +/etc/init.d/dawnline restart +exit 0 diff --git a/package/luci-app-dawnline/root/usr/bin/dawnline b/package/luci-app-dawnline/root/usr/bin/dawnline new file mode 100755 index 0000000..743efac --- /dev/null +++ b/package/luci-app-dawnline/root/usr/bin/dawnline @@ -0,0 +1,125 @@ +#!/usr/bin/ucode +// Dawnline command line: `dawnline help`. +'use strict'; + +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 { VERSION } from 'dawnline.util'; + +const args = ARGV; +const cmd = args[0] ?? 'help'; + +function out(v) { + print(type(v) == 'string' ? v + '\n' : sprintf('%.J\n', v)); +} + +function opt(name, dflt) { + for (let i = 1; i < length(args); i++) + if (args[i] == `--${name}`) + return args[i + 1]; + return dflt; +} + +function help() { + out(`Dawnline ${VERSION} + +Usage: dawnline + + apply Reconcile router configuration and runtime state + sync Push devices and access rules to the tunnel + status People and devices with live state (JSON) + health Run health checks (JSON) + person add [--slug s] [--access lan|internet|both] [--devices n] + [--expires YYYY-MM-DD] [--quota GB] + 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 rm Remove a device + backup Create a backup in /etc/dawnline/backups + portal-cert Print the certificate and key the portal uses + portal-http-port Print the plain-HTTP port when an IP is among the portal addresses + teardown Remove everything Dawnline created on the router + version`); +} + +function commit(c) { + c.commit('dawnline'); + system('chmod 600 /etc/config/dawnline'); +} + +try { + if (cmd == 'apply') + out(apply.apply()); + 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); + out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true }))); + } + else if (cmd == 'health') + out(ops.health()); + else if (cmd == 'person' && args[1] == 'add') { + let c = core.open_cursor(), m = core.load(c); + let id = 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); + } + else if (cmd == 'person' && args[1] == 'link') { + let m = core.load(); + let p = m.people[args[2]] ?? die('Unknown person.'); + 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); + 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); + 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); + } + 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); + apply.sync(); + } + else if (cmd == 'backup') + out(ops.backup_create(opt('reason'))); + else if (cmd == 'portal-cert') { + let c = ops.portal_cert(core.load().settings); + out(`${c.cert} ${c.key}`); + } + else if (cmd == 'portal-http-port') { + let m = core.load(); + if (core.portal_http(m)) + out(`${core.portal_http_port(m)}`); + } + else if (cmd == 'teardown') + apply.teardown(); + else if (cmd == 'version') + out(VERSION); + else + help(); +} +catch (e) { + warn(`dawnline: ${e.message}\n`); + exit(1); +} diff --git a/package/luci-app-dawnline/root/usr/libexec/dawnline/agent b/package/luci-app-dawnline/root/usr/libexec/dawnline/agent new file mode 100755 index 0000000..4629db2 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/libexec/dawnline/agent @@ -0,0 +1,334 @@ +#!/usr/bin/ucode +// Dawnline agent (procd instance). Every minute it: +// * folds AmneziaWG 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 +// * enforces end dates, quotas, schedules and pauses (peers + nft sets) +// * watches the tunnel interfaces +'use strict'; + +import * as uloop from 'uloop'; +import { readfile, stat, unlink } from 'fs'; +import { read_json, write_json, ensure_dir, sh_out, q, DATA_DIR, 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 ops from 'dawnline.ops'; +import * as geo from 'dawnline.geo'; + +const TICK = 60 * 1000; +const FLUSH_EVERY = 3600; +const LOG_FLUSH = { '10min': 600, hourly: 3600 }; +const RESYNC_EVERY = 600; + +let usage = live.load_usage(); +let last_states = null; +// Who was online, kept in tmpfs so an agent restart (update, reload) does not +// swallow connects that happened in between. +let presence = read_json(`${RUN_DIR}/presence.json`, {}); +let last_online = presence.online ?? {}; +let last_endpoint = presence.endpoint ?? {}; +let offline_ticks = {}; +let iface_down = {}; +let last_flush = time(); +let last_log_flush = time(); +let last_net = null; +let rate_prev = null; + +/** + * Throughput per server for the Overview's "Speed now": bytes per second + * over the last minute, newest 30 points, kept in tmpfs only. + */ +function record_rate(m) { + let ts = time(); + let now = {}; + for (let pid, p in m.people) { + let t = usage.people?.[pid]?.total; + if (!t) + continue; + now[p.server] ??= [ 0, 0 ]; + now[p.server][0] += t[0]; + now[p.server][1] += t[1]; + } + let hist = read_json(`${RUN_DIR}/rate.json`, {}); + // Per person: the last 15 points (People list, person page). + let people = read_json(`${RUN_DIR}/rate_people.json`, {}); + if (type(people) != 'object') + people = {}; + if (rate_prev) { + let dt = ts - rate_prev.ts; + if (dt > 0 && dt < 600) { + for (let s, v in now) { + let p = rate_prev.v[s] ?? v; + push(hist[s] ??= [], [ ts, int(max(0, v[0] - p[0]) / dt), int(max(0, v[1] - p[1]) / dt) ]); + while (length(hist[s]) > 30) + shift(hist[s]); + } + for (let pid in keys(m.people)) { + let t = usage.people?.[pid]?.total, p = rate_prev.p?.[pid]; + if (!t || !p) + continue; + if (type(people[pid]?.[0]) != 'array') + people[pid] = []; + push(people[pid], [ ts, int(max(0, t[0] - p[0]) / dt), int(max(0, t[1] - p[1]) / dt) ]); + while (length(people[pid]) > 15) + shift(people[pid]); + } + } + } + for (let s in keys(hist)) + if (!m.servers[s]) + delete hist[s]; + for (let pid in keys(people)) + if (!m.people[pid]) + delete people[pid]; + let totals = {}; + for (let pid in keys(m.people)) + if (usage.people?.[pid]?.total) + totals[pid] = [ ...usage.people[pid].total ]; + rate_prev = { ts, v: now, p: totals }; + write_json(`${RUN_DIR}/rate.json`, hist, 0o644); + write_json(`${RUN_DIR}/rate_people.json`, people, 0o644); +} +let last_sync = 0; +let cert_mtime = null; + +const REASON = { + paused: 'paused by admin', paused_all: 'everyone paused', expired: 'end date reached', + quota: 'data limit reached', hours: 'outside allowed hours', no_server: 'no server', active: 'active', +}; + +function check_people(m, states, events) { + let ts = time(); + for (let id, p in m.people) { + let st = states[id], prev = last_states?.[id]; + if (prev != null && prev != st) + 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'); + push(events, { type: 'devices_removed', person: id, detail: 'end date reached' }); + last_sync = 0; + } + } +} + +let last_home = 0; + +/** Locate new client addresses for the admin map (a couple per minute). */ +function check_geo(m) { + if (!m.settings.geo_enabled) + return; + let cache = geo.load(); + let ips = []; + for (let id, rec in usage.devices) + for (let ip in keys(rec.ips ?? {})) + push(ips, ip); + let changed = geo.resolve(m.settings, cache, ips, 2); + if (time() - last_home > 3600) { + last_home = time(); + let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address; + changed = geo.resolve_home(m.settings, cache, wan) || changed; + } + if (changed) + geo.save(cache); +} + +function place_of(ip) { + let pl = geo.place(geo.load(), ip); + return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null; +} + +function check_devices(m, lv, events) { + for (let id, d in lv) { + let dev = m.devices[id]; + let was = last_online[id]; + // A device we have never seen before that is online now counts as a connect. + if (was == null && d.online && d.present) + was = false; + // Debounce: a device has to look offline on two ticks in a row before + // a disconnect is logged (handshakes are renewed only every 2-3 min). + if (was && !d.online) { + offline_ticks[id] = (offline_ticks[id] ?? 0) + 1; + if (offline_ticks[id] < 2) + continue; + } + else + delete offline_ticks[id]; + if (was != null && was != d.online) { + if (d.online) + push(events, { type: 'connect', person: dev.person, device: id, detail: d.endpoint, where: place_of(d.endpoint) }); + else + push(events, { type: 'disconnect', person: dev.person, device: id }); + } + else if (d.online && last_endpoint[id] && d.endpoint && last_endpoint[id] != d.endpoint) + push(events, { type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${d.endpoint}` }); + last_online[id] = d.online; + if (d.endpoint) + last_endpoint[id] = d.endpoint; + } + for (let id in keys(last_online)) + if (!m.devices[id]) { + delete last_online[id]; + delete last_endpoint[id]; + } + ensure_dir(RUN_DIR); + write_json(`${RUN_DIR}/presence.json`, { online: last_online, endpoint: last_endpoint }, 0o600); +} + +function check_servers(m, dmp, events) { + for (let id, srv in m.servers) { + if (!srv.enabled || !srv.private_key) + continue; + let up = dmp.ifaces[srv.ifname] != null; + if (!up) { + iface_down[id] = (iface_down[id] ?? 0) + 1; + if (iface_down[id] == 2) { + push(events, { type: 'server_down', server: id, detail: srv.ifname }); + } + } + else { + if ((iface_down[id] ?? 0) >= 2) { + push(events, { type: 'server_up', server: id, detail: srv.ifname }); + } + iface_down[id] = 0; + } + } +} + +function check_cert(m) { + if (!m.settings.portal_enabled) + return; + let c = ops.portal_cert(m.settings); + let mt = stat(c.cert)?.mtime; + if (cert_mtime != null && mt != null && mt != cert_mtime) + system('/etc/init.d/dawnline reload >/dev/null 2>&1 &'); + cert_mtime = mt; +} + +let last_backup_day = null; + +function nightly_backup() { + let t = localtime(); + if (t.hour != 3 || last_backup_day == t.mday) + return; + last_backup_day = t.mday; + let sum = sh_out('md5sum /etc/config/dawnline | cut -d" " -f1'); + let st = read_json(`${DATA_DIR}/backup-state.json`, {}); + if (sum && sum != st.auto) { + try { + ops.backup_create('auto'); + write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600); + } + catch (e) {} + } +} + +/** + * Traffic history resets requested from LuCI (rpcd cannot touch the + * counters this process holds in memory). Applied, then saved to flash. + */ +function check_usage_reset(m) { + let path = `${RUN_DIR}/usage.reset`; + let req = read_json(path, null); + if (req == null) + return false; + unlink(path); + for (let r in (type(req) == 'array' ? req : [ req ])) { + live.reset_usage(usage, m, r.scope, r.id); + } + return true; +} + +function tick() { + // 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 = []; + + check_devices(m, lv, events); + check_people(m, states, events); + check_servers(m, dmp, events); + + 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); + 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) { + system(`logger -t dawnline-agent 'network changed, re-applying'`); + apply.apply(); + sig = apply.net_signature(core.load()); + } + last_net = sig; + } + catch (e) { + system(`logger -t dawnline-agent ${q('like-home: ' + e.message)}`); + } + check_cert(m); + nightly_backup(); + try { + check_geo(m); + } + catch (e) { + system(`logger -t dawnline-agent ${q('geo: ' + e.message)}`); + } +} + +function shutdown() { + live.save_usage(usage, true); + live.persist_events(); +} + +uloop.init(); + +let timer; +timer = uloop.timer(1000, function() { + try { + tick(); + } + catch (e) { + system(`logger -t dawnline-agent ${q('tick failed: ' + e.message)}`); + } + timer.set(TICK); +}); + +if (type(uloop.signal) == 'function') { + uloop.signal('TERM', () => { shutdown(); uloop.end(); }); + uloop.signal('INT', () => { shutdown(); uloop.end(); }); +} + +uloop.run(); +shutdown(); diff --git a/package/luci-app-dawnline/root/usr/libexec/dawnline/resolver b/package/luci-app-dawnline/root/usr/libexec/dawnline/resolver new file mode 100755 index 0000000..475c93b --- /dev/null +++ b/package/luci-app-dawnline/root/usr/libexec/dawnline/resolver @@ -0,0 +1,9 @@ +#!/bin/sh +# Dawnline: run the Home-only resolver where its config says (inside the +# dawnline netns while it exists, otherwise on the router itself). +CONF=/var/etc/dawnline-dns.conf +[ -f "$CONF" ] || exit 1 +if head -n1 "$CONF" | grep -q '^# mode=ns' && [ -e /var/run/netns/dawnline ]; then + exec ip netns exec dawnline /usr/sbin/dnsmasq -k -C "$CONF" +fi +exec /usr/sbin/dnsmasq -k -C "$CONF" diff --git a/package/luci-app-dawnline/root/usr/libexec/dawnline/updater b/package/luci-app-dawnline/root/usr/libexec/dawnline/updater new file mode 100755 index 0000000..992cf5f --- /dev/null +++ b/package/luci-app-dawnline/root/usr/libexec/dawnline/updater @@ -0,0 +1,521 @@ +#!/usr/bin/ucode +// Dawnline background update worker, started detached by luci.dawnline. +// +// updater check +// updater install app|amneziawg[:slava|grey[:ru]]|pkgs:|all +// +// Progress: /var/run/dawnline/update-job.json; check results: +// /var/run/dawnline/update-check.json. The Updates tab polls both. +'use strict'; + +import * as fs from 'fs'; +import { cursor } from 'uci'; +import { connect } from 'ubus'; +import { VERSION, REPO } from 'dawnline.util'; + +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; +} + +let job = { + action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null, + phase: '', log: [], error: null, result: null, +}; + +function save() { + fs.writefile(`${JOB_FILE}.tmp`, sprintf('%J', job)); + fs.rename(`${JOB_FILE}.tmp`, JOB_FILE); +} + +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); + save(); +} + +function phase(p) { + job.phase = p; + log(p); +} + +function q(s) { + return "'" + replace(`${s ?? ''}`, "'", "'\\''") + "'"; +} + +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')) + if (length(trim(line))) + log(` ${line}`); + return r; +} + +function repo() { + return REPO; +} + +function have_curl() { + return fs.access('/usr/bin/curl', 'x'); +} + +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; +} + +/** 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; + } + 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) {} + return best; +} + +function awg_installed() { + let r = {}; + for (let p in AWG_PKGS) + r[p] = pkg_version(p); + return r; +} + +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' }; + } + } + sources[id] = s2; + } + // 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) + 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]; + } + } + 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; +} + +// 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 }; +} + +/* ---------- main ---------- */ + +const CHECKS = { app: check_app, amneziawg: check_awg, packages: check_pkgs }; +const INSTALLS = { app: install_app, amneziawg: install_awg, pkgs: install_pkgs }; + + +if (!fs.access(STATE_DIR)) + fs.mkdir(STATE_DIR, 0o755); +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); + } + } + else + die('Usage: updater check | install app|amneziawg[:build[:ru]]|pkgs:|all'); + job.state = 'done'; + phase('Finished'); +} +catch (e) { + job.state = 'failed'; + job.error = e.message; + log(`Error: ${e.message}`); +} + +run(`rm -rf ${WORK_DIR}`); +job.finished = time(); +save(); diff --git a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/LICENSE.txt b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/LICENSE.txt new file mode 100644 index 0000000..3e44e16 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/LICENSE.txt @@ -0,0 +1,3 @@ +Geist and Geist Mono are licensed under the SIL Open Font License, Version 1.1. +Copyright (c) 2023 Vercel, in collaboration with basement.studio. +https://github.com/vercel/geist-font/blob/main/OFL.txt diff --git a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/geist-cyrillic-wght-normal.woff2 b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/geist-cyrillic-wght-normal.woff2 new file mode 100644 index 0000000..4b7a2be Binary files /dev/null and b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/geist-cyrillic-wght-normal.woff2 differ diff --git a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/geist-latin-wght-normal.woff2 b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/geist-latin-wght-normal.woff2 new file mode 100644 index 0000000..991445d Binary files /dev/null and b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/geist-latin-wght-normal.woff2 differ diff --git a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/geist-mono-latin-wght-normal.woff2 b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/geist-mono-latin-wght-normal.woff2 new file mode 100644 index 0000000..0750682 Binary files /dev/null and b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/geist-mono-latin-wght-normal.woff2 differ diff --git a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/icon.svg b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/icon.svg new file mode 100644 index 0000000..2bb9132 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/icon.svg @@ -0,0 +1 @@ + diff --git a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.css b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.css new file mode 100644 index 0000000..6ecd9b6 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.css @@ -0,0 +1 @@ +@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{--bg: #fcfcfc;--card: #ffffff;--elevated: #ffffff;--text: #0d0d0d;--muted: #5d5d5d;--faint: #8f8f8f;--line: #0000001a;--input: #00000026;--soft: #0d0d0d0d;--soft-hover: #0d0d0d1a;--primary: #0d0d0d;--primary-fg: #ffffff;--accent: #3a83f7;--info: #2c67c5;--ok: #00a240;--ok-wash: #00a24026;--warn: #e25507;--warn-wash: #e2550726;--bad: #e02e2a;--bad-wash: #e02e2a1f;--chart: #3a83f7;--track: #0d0d0d1a;--scrim: #00000040;--shadow: 0 1px 2px -1px #00000014;--shadow-xl: 0 8px 16px -4px #0000001f;--radius: 16px;--mono: "Geist Mono", ui-monospace, Menlo, monospace;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg: #000000;--card: #0a0a0a;--elevated: #131313;--text: #ededed;--muted: #edededa6;--faint: #ededed78;--line: #ededed13;--input: #ededed24;--soft: #ededed0d;--soft-hover: #ededed1a;--primary: #ededed;--primary-fg: #131313;--accent: #006efe;--info: #5ba2fe;--ok: #40c977;--ok-wash: #40c97726;--warn: #ff8549;--warn-wash: #ff854926;--bad: #ff6764;--bad-wash: #ff676422;--chart: #3a83f7;--track: #ededed1a;--scrim: #00000099;--shadow: none;--shadow-xl: 0 8px 16px -4px #00000080}}*{box-sizing:border-box}html,body{margin:0}body{background:var(--bg);color:var(--text);font:400 15px/22px Geist,-apple-system,system-ui,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}h1,h2{margin:0;font-weight:500;letter-spacing:-.01em}h1{font-size:24px;line-height:32px}h2{font-size:16px;line-height:24px}.muted{color:var(--muted)}.faint{color:var(--faint)}.s{font-size:13px;line-height:18px}.ok{color:var(--ok)}.warn{color:var(--warn)}.strong{font-weight:500}.center{text-align:center}.mono{font-family:var(--mono);font-size:12px}.stack{display:flex;flex-direction:column;gap:2px;min-width:0}.stack.gap{gap:10px}.grow{flex:1}.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.row.gap{gap:8px;flex-wrap:nowrap}.row-baseline{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.offscreen{position:fixed;left:-9999px;opacity:0}.top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:max(12px,env(safe-area-inset-top)) 16px 12px;border-bottom:1px solid var(--line);position:sticky;top:0;background:color-mix(in srgb,var(--bg) 85%,transparent);backdrop-filter:saturate(180%) blur(12px);z-index:5}.brand{display:flex;align-items:center;gap:8px;font-weight:500;min-width:0}.brand .faint{font-weight:400}.logo{display:inline-flex;width:22px;height:22px;color:var(--text)}.logo svg{width:100%;height:100%}.wrap{width:100%;max-width:1048px;margin:0 auto;padding:20px 16px max(32px,env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:20px}.hello{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:50%;background:var(--soft-hover);display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;position:relative;flex:0 0 auto}.avatar.online:after{content:"";position:absolute;right:0;bottom:0;width:10px;height:10px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px var(--bg)}.pill{display:inline-flex;align-items:center;height:22px;padding:0 9px;border-radius:999px;font-size:12px;font-weight:500;background:var(--soft);color:var(--muted)}.pill.ok{background:var(--ok-wash);color:var(--ok)}.pill.warn{background:var(--warn-wash);color:var(--warn)}.pill.bad{background:var(--bad-wash);color:var(--bad)}.notice{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border-radius:12px;background:var(--warn-wash);font-size:14px}.notice.bad{background:var(--bad-wash)}.notice .ic{color:var(--warn)}.notice.bad .ic{color:var(--bad)}.layout{display:grid;grid-template-columns:minmax(0,1fr);gap:20px;grid-template-areas:"access" "devices"}.access{grid-area:access}.devices{grid-area:devices;display:flex;flex-direction:column;gap:12px;min-width:0}.desktop-only{display:none!important}@media(min-width:960px){.top{padding-left:max(16px,calc((100vw - 1048px)/2 + 16px));padding-right:max(16px,calc((100vw - 1048px)/2 + 16px))}.layout{grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);grid-template-areas:"devices access";align-items:start;gap:16px}.desktop-only{display:inline-flex!important}.wrap{padding-top:28px}}.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;box-shadow:var(--shadow);min-width:0}.card-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.access{display:flex;flex-direction:column;gap:12px;min-width:0}.access-card{display:flex;flex-direction:column;gap:12px}.reach{display:flex;align-items:center;gap:12px;padding:12px;border-radius:12px;background:var(--soft)}.reach-ic{width:36px;height:36px;border-radius:10px;display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;background:color-mix(in srgb,var(--info) 14%,transparent);color:var(--info)}.tile{border:1px solid var(--line);border-radius:14px;padding:14px;display:flex;flex-direction:column;gap:8px;min-width:0}.tiles2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.tile-label{display:flex;justify-content:space-between;gap:8px;font-size:12px;font-weight:500;color:var(--faint)}.tile-value{font-size:20px;line-height:28px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums}.tile-value.sm{font-size:16px}.tile-value .faint{font-size:14px;font-weight:400}.meter{position:relative;height:6px;border-radius:999px;background:var(--track);cursor:default}.meter i{display:block;height:100%;border-radius:999px;background:var(--accent)}.meter.warn i{background:var(--warn)}.meter.bad i{background:var(--bad)}.slots{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(0,1fr);gap:3px}.slots i{display:block;height:4px;border-radius:999px;background:var(--track)}.slots i.used{background:var(--text)}.dgrid{display:grid;grid-template-columns:minmax(0,1fr);gap:10px}@media(min-width:640px){.dgrid{grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}}.dgrid>.slot.add:only-child{grid-column:1 / -1}.dcard{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:14px;display:flex;flex-direction:column;gap:12px;min-width:0;box-shadow:var(--shadow)}.dcard.online{border-color:color-mix(in srgb,var(--ok) 35%,transparent)}.dcard.off{opacity:.7}.dhead{display:flex;align-items:center;gap:12px}.dic{width:40px;height:40px;border-radius:12px;background:var(--soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--muted)}.dic .ic-svg{width:20px;height:20px}.dcard.online .dic{background:var(--ok-wash);color:var(--ok)}.dname{font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dstat{display:inline-flex;align-items:center;gap:6px;font-size:13px;color:var(--muted)}.dstat.ok{color:var(--ok)}.dstat.warn{color:var(--warn)}.dot{width:6px;height:6px;border-radius:50%;background:var(--faint);display:inline-block;flex:0 0 auto}.dot.ok{background:var(--ok);box-shadow:0 0 0 3px var(--ok-wash)}.dot.warn{background:var(--warn)}.dot.pulse{animation:pulse 1.6s ease-in-out infinite}@keyframes pulse{0%,to{box-shadow:0 0 0 0 var(--warn-wash)}50%{box-shadow:0 0 0 6px transparent}}.duse{display:flex;align-items:flex-end;justify-content:space-between;gap:12px}.spark{display:flex;align-items:flex-end;gap:3px;height:26px;width:128px}.spark i{flex:1;display:block;border-radius:2px 2px 0 0;background:var(--chart);opacity:.85;cursor:default}.spark i.zero{opacity:.22}.spark i:hover{opacity:1;filter:brightness(1.2)}.dfoot{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:8px;padding-top:12px;border-top:1px solid var(--line)}.dfoot>.faint{white-space:nowrap}.lan-pill{all:unset;cursor:pointer;display:inline-flex;align-items:center;height:26px;padding:0 3px;border-radius:999px;max-width:100%;min-width:0;background:linear-gradient(180deg,color-mix(in srgb,var(--text) 6%,transparent),color-mix(in srgb,var(--text) 2.5%,transparent));box-shadow:inset 0 0 0 1px var(--line),0 1px 2px #0003}.lan-pill:hover{box-shadow:inset 0 0 0 1px var(--input),0 1px 2px #0003}.lan-pill:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.lan-ic{width:20px;height:20px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;background:color-mix(in srgb,var(--info) 14%,transparent);color:var(--info)}.lan-ic .ic-svg{width:11px;height:11px}.lan-pill .mono{padding:0 8px 0 7px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.lan-sep{width:1px;height:14px;background:var(--line);flex:0 0 auto}.lan-pill>.ic:last-child{width:22px;justify-content:center;color:var(--muted)}.lan-pill>.ic:last-child .ic-svg{width:12px;height:12px}.slot.add{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:14px;padding:16px;min-height:72px;border:1px dashed var(--input);border-radius:var(--radius);color:var(--text);text-align:left;transition:background .15s,border-color .15s}.slot.add:hover{background:var(--soft);border-color:color-mix(in srgb,var(--text) 30%,transparent)}.slot-ic{width:40px;height:40px;border-radius:12px;background:var(--soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--muted)}.slot.add:hover .slot-ic{background:var(--primary);color:var(--primary-fg)}.slot.add:focus-visible{outline:2px solid var(--accent);outline-offset:2px}@media(min-width:960px){.slot.add{flex-direction:column;justify-content:center;gap:10px;min-height:140px;text-align:center;color:var(--muted)}.slot.add .stack{align-items:center}.slot.add .strong{color:var(--text)}.slot.add .slot-ic{border-radius:999px;width:36px;height:36px}}.ic{display:inline-flex;line-height:0}.ic-svg{width:16px;height:16px}.btn{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:8px;height:40px;padding:0 16px;border-radius:999px;font-size:14px;font-weight:500;background:var(--soft);color:var(--text);-webkit-tap-highlight-color:transparent;white-space:nowrap}.btn:hover{background:var(--soft-hover)}.btn.primary{background:var(--primary);color:var(--primary-fg)}.btn.primary:hover{opacity:.9}.btn.danger-solid{background:var(--bad);color:#fff}.btn.small{height:32px;padding:0 12px;font-size:13px}.btn.big{height:48px;font-size:15px}.btn.block{display:flex;width:100%}.btn[disabled]{opacity:.45;cursor:not-allowed}.btn:focus-visible,.kind:focus-visible,.icon-btn:focus-visible,.slot:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.icon-btn{all:unset;cursor:pointer;width:36px;height:36px;display:inline-flex;align-items:center;justify-content:center;border-radius:50%;color:var(--muted);flex:0 0 auto}.icon-btn:hover{background:var(--soft);color:var(--text)}.icon-btn.soft{background:var(--soft)}@media(pointer:coarse){.icon-btn{width:40px;height:40px}}input[type=text]{width:100%;font:inherit;color:var(--text);background:var(--card);border:1px solid var(--input);border-radius:10px;padding:0 12px;height:44px}input[type=text]:focus{outline:2px solid color-mix(in srgb,var(--accent) 60%,transparent);outline-offset:0;border-color:transparent}.lbl{display:block;font-size:13px;font-weight:500;color:var(--muted);margin:14px 2px 6px}.err{color:var(--bad);min-height:1.2em;margin:8px 2px;font-size:14px}.kinds{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:6px}.kind{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;height:68px;min-width:0;border-radius:12px;box-shadow:inset 0 0 0 1px var(--line);color:var(--muted);font-size:12.5px;font-weight:500;text-align:center}.kind .ic-svg{width:20px;height:20px}.kind:hover{color:var(--text);background:color-mix(in srgb,var(--text) 4%,transparent)}.kind.on{box-shadow:inset 0 0 0 1.5px var(--accent);color:var(--text);background:color-mix(in srgb,var(--accent) 10%,transparent)}.kind.on .ic{color:var(--accent)}.signin{text-align:center;max-width:420px;margin:8vh auto 0;width:100%;padding:28px 20px;display:flex;flex-direction:column;gap:10px}.hero-ic{width:52px;height:52px;margin:0 auto 6px;border-radius:16px;display:grid;place-items:center;background:var(--primary);color:var(--primary-fg)}.hero-ic .ic-svg{width:24px;height:24px}.signin input{text-align:center;margin-top:8px}.menu{position:absolute;z-index:30;width:230px;padding:4px;border-radius:14px;background:var(--elevated);border:1px solid var(--line);box-shadow:var(--shadow-xl)}.menu-item{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:10px;width:100%;height:40px;padding:0 12px;border-radius:10px;font-size:14px}.menu-item:hover,.menu-item:focus-visible{background:var(--soft-hover)}.menu-item .ic{color:var(--muted)}.menu-item.danger,.menu-item.danger .ic{color:var(--bad)}.menu-sep{height:1px;background:var(--line);margin:4px 8px}@media(pointer:coarse){.menu-item{height:44px}}.sheet{position:fixed;inset:0;z-index:20;display:flex;align-items:flex-end;justify-content:center;background:transparent;transition:background .2s}.sheet.open{background:var(--scrim)}.sheet-panel{width:100%;max-width:520px;max-height:92vh;max-height:92dvh;overflow:auto;background:var(--elevated);border-radius:20px 20px 0 0;border:1px solid var(--line);border-bottom:0;padding:6px 16px max(20px,env(safe-area-inset-bottom));transform:translateY(100%);transition:transform .25s cubic-bezier(.2,.8,.2,1)}.sheet.open .sheet-panel{transform:none}.grab{width:36px;height:4px;border-radius:999px;background:var(--input);margin:4px auto 8px}.sheet-head{display:flex;align-items:flex-start;justify-content:space-between;gap:8px;padding:4px 0 12px}.sheet-head h2{font-size:20px;line-height:28px;font-weight:600}.sheet-body{display:flex;flex-direction:column;gap:14px}@media(min-width:640px){.sheet{align-items:center}.sheet-panel{border-radius:16px;border-bottom:1px solid var(--line);padding:20px;max-width:480px;transform:scale(.97);opacity:0;transition:transform .18s ease,opacity .18s ease}.sheet.open .sheet-panel{transform:none;opacity:1}.grab{display:none}}.tabs{display:flex;gap:4px;padding:4px;background:var(--soft);border-radius:999px}.tabs button{all:unset;cursor:pointer;flex:1 1 auto;white-space:nowrap;text-align:center;padding:7px 10px;border-radius:999px;font-weight:500;font-size:13px;color:var(--muted)}.tabs button.on{background:var(--soft-hover);color:var(--text)}.pane{display:flex;flex-direction:column;gap:10px}.pane.center{align-items:center;text-align:center}.qr{width:min(240px,70vw);aspect-ratio:1;background:#fff;border-radius:12px;padding:10px;box-shadow:inset 0 0 0 1px var(--line)}.qr svg{display:block;width:100%;height:100%}.steps{margin:4px 0 0;padding:14px 16px 14px 34px;border-radius:14px;border:1px solid var(--line);background:var(--card);display:flex;flex-direction:column;gap:8px;font-size:14px}.keybox{display:flex;align-items:center;gap:8px;height:44px;padding:0 6px 0 12px;border:1px solid var(--input);border-radius:10px}.keybox .mono{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--muted)}.filecard{display:flex;align-items:center;gap:12px;padding:12px;border-radius:14px;background:var(--soft);min-width:0}.filecard>.stack{flex:1;min-width:0}.filecard-ic{width:40px;height:46px;border-radius:8px;flex:none;display:inline-flex;align-items:center;justify-content:center;font:10px var(--mono);color:var(--muted);background:var(--card);box-shadow:inset 0 0 0 1px var(--line)}.ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}@media(max-width:480px){.filecard .ellipsis{white-space:normal;overflow-wrap:anywhere}}.confbox{border:1px solid var(--line);border-radius:12px}.confbox>summary{list-style:none;display:flex;align-items:center;gap:8px;padding:8px 10px 8px 12px;color:var(--text)}.confbox>summary::-webkit-details-marker{display:none}.confbox>summary>.ic:first-child{transition:transform .15s;color:var(--muted)}.confbox[open]>summary>.ic:first-child{transform:rotate(90deg)}.confbox .grow{flex:1}.confbox>.conf{margin:0;border-top:1px solid var(--line);border-radius:0 0 12px 12px;background:none}.conf-sec{color:var(--accent, var(--info))}.conf-k{color:var(--faint)}.conf-mask{padding:0 6px;border-radius:4px;background:var(--soft);color:var(--muted)}.conf{white-space:pre-wrap;word-break:break-all;font:12px/18px var(--mono);background:var(--soft);border-radius:10px;padding:12px;max-height:16rem;overflow:auto}details>summary{cursor:pointer;color:var(--muted);font-size:13px;font-weight:500}.waiting{display:flex;align-items:center;gap:10px;padding:12px 14px;border-radius:12px;background:var(--soft);font-size:14px}.tip{position:fixed;z-index:50;transform:translate(-50%,-100%);padding:6px 10px;border-radius:10px;font-size:12px;line-height:17px;white-space:nowrap;background:var(--elevated);border:1px solid var(--line);box-shadow:var(--shadow-xl);pointer-events:none}.tip-title{font-weight:500}.toast{position:fixed;left:50%;bottom:max(20px,env(safe-area-inset-bottom));transform:translate(-50%,20px);opacity:0;z-index:60;background:var(--primary);color:var(--primary-fg);padding:10px 16px;border-radius:999px;font-weight:500;font-size:14px;transition:all .25s;max-width:90vw}.toast.show{opacity:1;transform:translate(-50%)}.toast.bad{background:var(--bad);color:#fff}@media(prefers-reduced-motion:reduce){*{transition:none!important;animation:none!important}} 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 new file mode 100644 index 0000000..0e21338 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.js @@ -0,0 +1,6 @@ +"use strict";(()=>{var tt=Object.create;var $e=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var at=Object.getPrototypeOf,it=Object.prototype.hasOwnProperty;var st=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ot=(n,e,a,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let v of rt(e))!it.call(n,v)&&v!==a&&$e(n,v,{get:()=>e[v],enumerable:!(o=nt(e,v))||o.enumerable});return n};var lt=(n,e,a)=>(a=n!=null?tt(at(n)):{},ot(e||!n||!n.__esModule?$e(a,"default",{value:n,enumerable:!0}):a,n));var Ue=st((Oe,Ke)=>{"use strict";var Ie=(function(){var n=function(M,k){var w=236,b=17,l=M,m=a[k],i=null,r=0,y=null,f=[],g={},T=function(c,u){r=l*4+17,i=(function(s){for(var d=new Array(s),h=0;h=7&&z(c),y==null&&(y=Xe(l,m,f)),W(y,u)},E=function(c,u){for(var s=-1;s<=7;s+=1)if(!(c+s<=-1||r<=c+s))for(var d=-1;d<=7;d+=1)u+d<=-1||r<=u+d||(0<=s&&s<=6&&(d==0||d==6)||0<=d&&d<=6&&(s==0||s==6)||2<=s&&s<=4&&2<=d&&d<=4?i[c+s][u+d]=!0:i[c+s][u+d]=!1)},P=function(){for(var c=0,u=0,s=0;s<8;s+=1){T(!0,s);var d=v.getLostPoint(g);(s==0||c>d)&&(c=d,u=s)}return u},I=function(){for(var c=8;c>s&1)==1;i[Math.floor(s/3)][s%3+r-8-3]=d}for(var s=0;s<18;s+=1){var d=!c&&(u>>s&1)==1;i[s%3+r-8-3][Math.floor(s/3)]=d}},Q=function(c,u){for(var s=m<<3|u,d=v.getBCHTypeInfo(s),h=0;h<15;h+=1){var x=!c&&(d>>h&1)==1;h<6?i[h][8]=x:h<8?i[h+1][8]=x:i[r-15+h][8]=x}for(var h=0;h<15;h+=1){var x=!c&&(d>>h&1)==1;h<8?i[8][r-h-1]=x:h<9?i[8][15-h-1+1]=x:i[8][15-h-1]=x}i[r-8][8]=!c},W=function(c,u){for(var s=-1,d=r-1,h=7,x=0,C=v.getMaskFunction(u),A=r-1;A>0;A-=2)for(A==6&&(A-=1);;){for(var S=0;S<2;S+=1)if(i[d][A-S]==null){var K=!1;x>>h&1)==1);var L=C(d,A-S);L&&(K=!K),i[d][A-S]=K,h-=1,h==-1&&(x+=1,h=7)}if(d+=s,d<0||r<=d){d-=s,s=-s;break}}},re=function(c,u){for(var s=0,d=0,h=0,x=new Array(u.length),C=new Array(u.length),A=0;A=0?Ee.getAt(Be):0}}for(var De=0,L=0;LA*8)throw"code length overflow. ("+h.getLengthInBits()+">"+A*8+")";for(h.getLengthInBits()+4<=A*8&&h.put(0,4);h.getLengthInBits()%8!=0;)h.putBit(!1);for(;!(h.getLengthInBits()>=A*8||(h.put(w,8),h.getLengthInBits()>=A*8));)h.put(b,8);return re(h,d)};g.addData=function(c,u){u=u||"Byte";var s=null;switch(u){case"Numeric":s=D(c);break;case"Alphanumeric":s=F(c);break;case"Byte":s=J(c);break;case"Kanji":s=U(c);break;default:throw"mode:"+u}f.push(s),y=null},g.isDark=function(c,u){if(c<0||r<=c||u<0||r<=u)throw c+","+u;return i[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),s=B(),d=0;d";for(var h=0;h';s+=""}return s+="",s+="",s},g.createSvgTag=function(c,u,s,d){var h={};typeof arguments[0]=="object"&&(h=arguments[0],c=h.cellSize,u=h.margin,s=h.alt,d=h.title),c=c||2,u=typeof u=="undefined"?c*4:u,s=typeof s=="string"?{text:s}:s||{},s.text=s.text||null,s.id=s.text?s.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,A,S,K,L="",Y;for(Y="l"+c+",0 0,"+c+" -"+c+",0 0,-"+c+"z ",L+=''+ae(d.text)+"":"",L+=s.text?''+ae(s.text)+"":"",L+='',L+='":u+=">";break;case"&":u+="&";break;case'"':u+=""";break;default:u+=d;break}}return u},et=function(c){var u=1;c=typeof c=="undefined"?u*2:c;var s=g.getModuleCount()*u+c*2,d=c,h=s-c,x,C,A,S,K,L={"██":"█","█ ":"▀"," █":"▄"," ":" "},Y={"██":"▀","█ ":"▀"," █":" "," ":" "},j="";for(x=0;x=h?Y[K]:L[K];j+=` +`}return s%2&&c>0?j.substring(0,j.length-s-1)+Array(s+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(c,u){if(c=c||1,c<2)return et(u);c-=1,u=typeof u=="undefined"?c*2:u;var s=g.getModuleCount()*c+u*2,d=u,h=s-u,x,C,A,S,K=Array(c+1).join("██"),L=Array(c+1).join(" "),Y="",j="";for(x=0;x>>8),m.push(y&255)):m.push(b)}}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},o={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,w=7973,b=21522,l={},m=function(i){for(var r=0;i!=0;)r+=1,i>>>=1;return r};return l.getBCHTypeInfo=function(i){for(var r=i<<10;m(r)-m(k)>=0;)r^=k<=0;)r^=w<5&&(y+=3+T-5)}for(var f=0;f=256;)l-=255;return M[l]},b})();function _(M,k){if(typeof M.length=="undefined")throw M.length+"/"+k;var w=(function(){for(var l=0;l>>7-b%8&1)==1},w.put=function(b,l){for(var m=0;m>>l-m-1&1)==1)},w.getLengthInBits=function(){return k},w.putBit=function(b){var l=Math.floor(k/8);M.length<=l&&M.push(0),b&&(M[l]|=128>>>k%8),k+=1},w},D=function(M){var k=e.MODE_NUMBER,w=M,b={};b.getMode=function(){return k},b.getLength=function(i){return w.length},b.write=function(i){for(var r=w,y=0;y+2>>8&255)*192+(f&255),i.put(f,13),y+=2}if(y>>8)},k.writeBytes=function(w,b,l){b=b||0,l=l||w.length;for(var m=0;m0&&(w+=","),w+=M[b];return w+="]",w},k},G=function(){var M=0,k=0,w=0,b="",l={},m=function(r){b+=String.fromCharCode(i(r&63))},i=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,w+=1;k>=6;)m(M>>>k-6),k-=6},l.flush=function(){if(k>0&&(m(M<<6-k),M=0,k=0),w%3!=0)for(var r=3-w%3,y=0;y=k.length){if(l==0)return-1;throw"unexpected end of file./"+l}var r=k.charAt(w);if(w+=1,r=="=")return l=0,-1;if(r.match(/^\s$/))continue;b=b<<6|i(r.charCodeAt(0)),l+=6}var y=b>>>l-8&255;return l-=8,y};var i=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},ne=function(M,k){var w=M,b=k,l=new Array(M*k),m={};m.setPixel=function(f,g,T){l[g*w+f]=T},m.write=function(f){f.writeString("GIF87a"),f.writeShort(w),f.writeShort(b),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(w),f.writeShort(b),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 i=function(f){var g=f,T=0,E=0,P={};return P.write=function(I,q){if(I>>>q)throw"length over";for(;T+q>=8;)g.writeByte(255&(I<>>=8-T,E=0,T=0;E=I<0&&g.writeByte(E)},P},r=function(f){for(var g=1<>6,128|p&63):p<55296||p>=57344?o.push(224|p>>12,128|p>>6&63,128|p&63):(v++,p=65536+((p&1023)<<10|a.charCodeAt(v)&1023),o.push(240|p>>18,128|p>>12&63,128|p>>6&63,128|p&63))}return o}return e(n)}})();(function(n){typeof define=="function"&&define.amd?define([],n):typeof Oe=="object"&&(Ke.exports=n())})(function(){return Ie})});function ee(n){if(!n||n<0)return"0 B";let e=["B","KB","MB","GB","TB"],a=0,o=n;for(;o>=1024&&a=100||a===0?Math.round(o):o.toFixed(1)} ${e[a]}`}function ye(n,e=Date.now()/1e3){if(!n)return"never";let a=Math.max(0,Math.round(e-n));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(n*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function we(n){if(!n)return"";let[e,a,o]=n.split("-").map(Number);return new Date(e,a-1,o).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function be(n,e=Date.now()){if(!n)return null;let[a,o,v]=n.split("-").map(Number),p=new Date(a,o-1,v,23,59,59).getTime();return Math.ceil((p-e)/864e5)}var Pe={lan:"Home network",internet:"Internet",both:"Home network + Internet"};var ue={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},Se={active:"Active",paused:"Paused",paused_all:"Paused (everyone)",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server"};function Re(n){var v,p,_;let e=n.trim().split(/\s+/).filter(Boolean);if(!e.length)return"?";let a=(v=e[0][0])!=null?v:"",o=e.length>1?(p=e[e.length-1][0])!=null?p:"":(_=e[0][1])!=null?_:"";return(a+o).toUpperCase()}var Ne={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:'',shield:'',shieldplus:'',lock:'',zap:'',check:'',alert:'',x:'',globe:'',home:'',open:'',file:'',search:'',network:'',moon:'',chevron:'',clock:'',calendar:'',minus:'',more:'',pin:'',activity:''};function He(n,e="dl-icon"){var o;let a=(o=Ne[n])!=null?o:Ne.phone;return``}var Ge=lt(Ue(),1),ct='';function qe(n,e=3,a=!0){let o=(0,Ge.default)(0,n.length>300?"Q":"H");o.addData(n,"Byte"),o.make();let v=o.getModuleCount(),p=v+e*2,_=a?Math.round(v*.22):0;_&&(v-_)%2&&_++;let $=(v-_)/2,B=$+_,D=(U,N)=>_>0&&U>=$&&U=$&&N${ct}`}return`${J}`}var ut={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:""},ft={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 dt(n){let e={};for(let[a,o]of Object.entries(ft))n[a]!=null&&n[a]!==""&&(e[o]=String(n[a]));return e}function ht(n,e){var B;let a=n.amnezia,o=(B=a.obfuscation)!=null?B:{},v=D=>o[D]!=null&&o[D]!==""?String(o[D]):ut[D],p=a.host.replace(/^\[(.*)\]$/,"$1"),_={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"),...dt(o),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:n.conf.replace(/\r?\n/g,`\r +`),hostName:p,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(_),port:String(a.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:p};return a.dns[0]&&($.dns1=a.dns[0]),a.dns[1]&&($.dns2=a.dns[1]),$}function vt(n){let e="";for(let a=0;a{p==null||p===!1||(Array.isArray(p)?p.forEach(v):o.appendChild(typeof p=="string"?document.createTextNode(p):p))};return a.forEach(v),o}function O(n){let e=t("span",{class:"ic"});return e.innerHTML=He(n,"ic-svg"),e}var gt='',Ce=document.getElementById("app"),Ye,de=(Ye=Ce.dataset.base)!=null?Ye:"",mt=Ce.dataset.title||"Dawnline",ke=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),R=null,Fe=0,yt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(de)?de.slice(1):"",Ae=class extends Error{constructor(a,o){super(o);this.status=a}};async function oe(n,e){var v;let a=await fetch(`${de}/api/${n}`,{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"}),o=null;try{o=await a.json()}catch{}if(!a.ok)throw new Ae(a.status,(v=o==null?void 0:o.error)!=null?v:`Request failed (${a.status})`);return o}function se(n,e=!1){let a=t("div",{class:`toast${e?" bad":""}`,role:"status"},n);document.body.appendChild(a),requestAnimationFrame(()=>a.classList.add("show")),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>a.remove(),300)},2600)}async function ve(n,e="Copied"){try{await navigator.clipboard.writeText(n)}catch{let a=t("textarea",{class:"offscreen"},n);document.body.appendChild(a),a.select(),document.execCommand("copy"),a.remove()}se(e)}function je(n,e){let a=URL.createObjectURL(new Blob([e],{type:"application/octet-stream"})),o=t("a",{href:a,download:n,class:"offscreen"});document.body.appendChild(o),o.click(),setTimeout(()=>{URL.revokeObjectURL(a),o.remove()},1e3)}var Z=null;function ze(n,e){let a=o=>{Z!=null||(Z=document.body.appendChild(t("div",{class:"tip"}))),Z.replaceChildren(...e().map((v,p)=>t("div",{class:p?"muted":"tip-title"},v))),Z.style.display="",Z.style.left=`${o.clientX}px`,Z.style.top=`${o.clientY-10}px`};n.addEventListener("mouseenter",a),n.addEventListener("mousemove",a),n.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function wt(n){let e=Math.max(1,...n),a=t("div",{class:"spark"});return n.forEach((o,v)=>{let p=t("i",{class:o?"":"zero"});p.style.height=`${Math.max(8,o/e*100)}%`;let _=n.length-1-v,$=new Date(Date.now()-_*864e5);ze(p,()=>[_===0?"Today":_===1?"Yesterday":$.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ee(o)]),a.appendChild(p)}),a}var ie=null,le=null;function te(n=!1){if(!ie)return;let e=ie;if(ie=null,document.body.classList.remove("locked"),le==null||le(),le=null,n){e.remove();return}e.classList.remove("open"),setTimeout(()=>e.remove(),250)}function pe(n,e,...a){let o=!!ie;te(!0);let v=t("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":n},t("div",{class:"grab"}),t("div",{class:"sheet-head"},t("div",{class:"stack"},t("h2",{},n),e?t("span",{class:"muted s"},e):null),t("button",{class:"icon-btn","aria-label":"Close",onclick:()=>te()},O("x"))),t("div",{class:"sheet-body"},...a)),p=t("div",{class:"sheet",onclick:_=>{_.target===p&&te()}},v);return document.body.appendChild(p),document.body.classList.add("locked"),o?p.classList.add("open"):requestAnimationFrame(()=>p.classList.add("open")),ie=p,v}document.addEventListener("keydown",n=>{n.key==="Escape"&&(he(),te())});var X=null;function he(){X==null||X.remove(),X=null}document.addEventListener("click",n=>{X&&!X.contains(n.target)&&he()});function bt(n,e){he();let a=t("div",{class:"menu",role:"menu"},e.map(p=>p?t("button",{type:"button",role:"menuitem",class:`menu-item${p.danger?" danger":""}`,onclick:()=>{he(),p.run()}},O(p.icon),t("span",{},p.label)):t("div",{class:"menu-sep"})));document.body.appendChild(a);let o=n.getBoundingClientRect(),v=230;a.style.left=`${Math.max(8,Math.min(window.innerWidth-v-8,o.right-v))}px`,a.style.top=`${o.bottom+6+window.scrollY}px`,X=a}function Le(...n){Ce.replaceChildren(t("header",{class:"top"},t("div",{class:"brand"},(()=>{let e=t("span",{class:"logo"});return e.innerHTML=gt,e})(),t("span",{},(R==null?void 0:R.server.name)||mt),t("span",{class:"faint"},"· Dawnline"))),t("main",{class:"wrap"},...n))}function Je(){Le(t("div",{class:"card signin"},t("div",{class:"hero-ic"},O("key")),t("h1",{},"This link no longer works"),t("p",{class:"muted"},"Ask for a new personal link.")))}function xt(n){return n.state==="active"?"ok":n.state==="quota"||n.state==="expired"?"bad":"warn"}var Mt={internet:"The internet, through the router",lan:"Devices at home",both:"Devices at home and the internet, through the router"};function kt(n){let e=n.person,a=e.quota_limit?Math.min(100,e.quota_used/e.quota_limit*100):0,o=t("div",{class:`meter${a>=100?" bad":a>=90?" warn":""}`},t("i"));o.firstChild.style.width=`${a}%`,e.quota_limit&&ze(o,()=>[`${a.toFixed(1)}% used`,`${ee(Math.max(0,e.quota_limit-e.quota_used))} left`]);let v=be(e.expires),p=t("div",{class:"slots"});for(let B=0;B=0?`${v} day${v===1?"":"s"} left`:"ended"):null)),t("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 At(n){return n.disabled?t("span",{class:"dstat"},t("i",{class:"dot"}),"Disabled by the admin"):n.online?t("span",{class:"dstat ok"},t("i",{class:"dot ok"}),"Connected"):n.handshake?t("span",{class:"dstat"},t("i",{class:"dot"}),`Last connected ${ye(n.handshake)}`):t("span",{class:"dstat warn"},t("i",{class:"dot warn"}),"Not set up yet")}function _t(n,e){return!n.hostname||e.access==="internet"?null:t("div",{class:"dfoot"},t("span",{class:"faint s"},"Local address"),t("button",{type:"button",class:"lan-pill","aria-label":`Copy ${n.hostname}`,onclick:()=>ve(n.hostname,"Address copied")},t("span",{class:"lan-ic"},O("home")),t("span",{class:"mono"},n.hostname),t("span",{class:"lan-sep"}),O("copy")))}function Ct(n,e){let a=e.person,o=t("button",{type:"button",class:"icon-btn soft","aria-label":`${n.name} options`},O("more"));o.addEventListener("click",_=>{_.stopPropagation(),bt(o,[{label:"Show QR code",icon:"qr",run:()=>fe(n,"qr")},{label:"Copy AmneziaVPN key",icon:"key",run:()=>Lt(n)},{label:"Download .conf",icon:"download",run:()=>Tt(n)},null,{label:"Rename",icon:"edit",run:()=>Bt(n)},{label:"Remove",icon:"trash",danger:!0,run:()=>Dt(n)}])});let v=n.spark.reduce((_,$)=>_+$,0),p=!n.handshake&&!n.disabled;return t("article",{class:`dcard${n.online?" online":""}${n.disabled?" off":""}`},t("div",{class:"dhead"},t("span",{class:"dic"},O(n.kind)),t("div",{class:"stack grow"},t("span",{class:"dname"},n.name),At(n)),o),p?[t("button",{type:"button",class:"btn primary block",onclick:()=>fe(n)},O(ke()?"open":"qr"),t("span",{},ke()?"Open in AmneziaVPN":"Connect this device")),t("span",{class:"faint s center"},"Setting up another device? QR, key and file are under ⋯")]:t("div",{class:"duse"},t("div",{class:"stack"},t("span",{class:"faint s"},"Last 7 days"),t("span",{class:"mono"},ee(v))),wt(n.spark)),n.config_stale&&!p?t("div",{class:"notice"},O("alert"),t("span",{class:"grow"},"Connection settings changed. Update this device to keep everything working."),t("button",{type:"button",class:"btn small",onclick:()=>fe(n)},"Update")):null,_t(n,a))}function ge(n){let e=n.person,a=be(e.expires),o=e.state!=="active"?t("div",{class:"notice bad"},O("alert"),t("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)?t("div",{class:"notice"},O("alert"),t("span",{},`Your access ends ${a===0?"today":`in ${a} day${a===1?"":"s"}`} (${we(e.expires)}).`)):null,v=e.devices.map($=>Ct($,n)),p=Math.max(0,e.device_limit-e.devices.length);p&&v.push(t("button",{type:"button",class:"slot add",onclick:Rt},t("span",{class:"slot-ic"},O("plus")),t("span",{class:"stack"},t("span",{class:"strong"},"Add device"),t("span",{class:"faint s"},`${p} slot${p===1?"":"s"} free`))));let _=t("section",{class:"devices","aria-label":"Your devices"},t("div",{class:"card-head"},t("div",{class:"row-baseline"},t("h2",{},"Your devices"),t("span",{class:"faint s"},`${e.devices.length} of ${e.device_limit} · ${e.online} online`))),t("div",{class:"dgrid"},v),n.can_add?null:t("span",{class:"faint s"},`You have reached your limit of ${e.device_limit} devices. Remove one or ask the admin for more.`),t("span",{class:"faint s"},"New device? Install ",t("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"AmneziaVPN")," on it first."));Le(t("div",{class:"hello"},t("span",{class:`avatar${e.online?" online":""}`},Re(e.name)),t("div",{class:"stack"},t("div",{class:"row"},t("h1",{},`Hi, ${e.name}`),t("span",{class:`pill ${xt(e)}`},Se[e.state])),t("span",{class:"faint s"},`${e.online?`${e.online} device${e.online===1?"":"s"} online`:"Nothing connected right now"} · ${ee(e.month[0]+e.month[1])} this month`))),o,t("div",{class:"layout"},kt(n),_))}async function Te(n){try{return await oe(`devices/${n.id}/config`)}catch(e){return se(e.message,!0),null}}async function Lt(n){let e=await Te(n);e&&ve(await xe(e,`${e.server} · ${e.name}`),"Key copied")}async function Tt(n){let e=await Te(n);e&&je(e.filename,e.conf)}function Ve(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"conf-sec"},n);let a=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!a)return document.createTextNode(n);let o=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},t("span",{class:"conf-k"},a[1])," ",o&&!e?t("span",{class:"conf-mask"},"••••••••••••••••"):a[2])}function Et(n){let e=!1,a=t("pre",{class:"conf"}),o=()=>a.replaceChildren(...n.conf.split(` +`).flatMap((p,_)=>_?[` +`,Ve(p,e)]:[Ve(p,e)])),v=t("button",{class:"btn small",onclick:p=>{p.preventDefault(),e=!e,v.replaceChildren(O(e?"x":"key"),t("span",{},e?"Hide key":"Show key")),o()}},O("key"),t("span",{},"Show key"));return o(),t("div",{class:"pane"},t("div",{class:"filecard"},t("span",{class:"filecard-ic"},".conf"),t("span",{class:"stack"},t("span",{class:"mono ellipsis"},n.filename),t("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),t("button",{class:"btn primary",onclick:()=>je(n.filename,n.conf)},O("download"),t("span",{},"Download"))),t("details",{class:"confbox"},t("summary",{},O("chevron"),t("span",{},"Configuration"),t("span",{class:"grow"}),v,t("button",{class:"btn small",onclick:p=>{p.preventDefault(),ve(n.conf,"Configuration copied")}},O("copy"),t("span",{},"Copy"))),a))}async function fe(n,e,a){let o=a!=null?a:await Te(n);if(!o)return;let v=await xe(o,`${o.server} · ${o.name}`),p=ke(),_={app:()=>t("div",{class:"pane"},t("a",{class:"btn primary block big",href:v},O("open"),t("span",{},"Open in AmneziaVPN")),t("ol",{class:"steps"},t("li",{},"No AmneziaVPN yet? ",t("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),t("li",{},"Tap ",t("b",{},"Open in AmneziaVPN")," and confirm the import."),t("li",{},"Turn the connection on — this page shows ",t("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let H=t("div",{class:"qr"});return H.innerHTML=qe(o.conf),t("div",{class:"pane center"},H,t("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>t("div",{class:"pane"},t("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),t("div",{class:"keybox"},t("span",{class:"mono"},v),t("button",{class:"btn small",onclick:()=>ve(v,"Key copied")},"Copy")),t("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Et(o)},$=p?["app","qr","key","file"]:["qr","key","file"],B={app:"Open in app",qr:"QR code",key:"Key",file:"File"},D=t("div",{class:"tab-body"}),F=t("div",{class:"tabs",role:"tablist"}),J=H=>{F.querySelectorAll("button").forEach(ne=>ne.classList.toggle("on",ne.dataset.id===H)),D.replaceChildren(_[H]())};for(let H of $)F.appendChild(t("button",{role:"tab","data-id":H,onclick:()=>J(H)},B[H]));J(e&&$.includes(e)?e:$[0]);let U=t("div",{class:"waiting"}),N=H=>{H!=null&&H.online?U.replaceChildren(t("i",{class:"dot ok"}),t("span",{class:"ok"},`${n.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(t("i",{class:"dot"}),t("span",{class:"muted"},`Last connected ${ye(H.handshake)}`)):U.replaceChildren(t("i",{class:"dot warn pulse"}),t("span",{class:"muted"},"Waiting for the first connection…"))};N(n);let G=window.setInterval(async()=>{try{let H=await oe("state");R=H,N(H.person.devices.find(ne=>ne.id===n.id))}catch{}},5e3);pe(n.handshake?`Connect ${n.name}`:`${n.name} is ready`,p?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",F,D,U),le=()=>{clearInterval(G),R&&ge(R)}}function Bt(n){let e=t("input",{type:"text",value:n.name,maxlength:48,"aria-label":"Device name"});pe(`Rename ${n.name}`,null,t("form",{class:"stack gap",onsubmit:async a=>{a.preventDefault();try{R=(await oe(`devices/${n.id}`,{action:"rename",name:e.value})).state,te(),ge(R),se("Renamed")}catch(o){se(o.message,!0)}}},e,t("button",{class:"btn primary block",type:"submit"},"Save"))),setTimeout(()=>e.select(),50)}function Dt(n){pe(`Remove ${n.name}?`,null,t("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),t("div",{class:"row gap"},t("button",{class:"btn block",onclick:()=>te()},"Cancel"),t("button",{class:"btn danger-solid block",onclick:async()=>{try{R=(await oe(`devices/${n.id}`,{action:"delete"})).state,te(),ge(R),se("Device removed")}catch(e){se(e.message,!0)}}},"Remove")))}var V=navigator.userAgent,Qe=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function Me(){return Qe||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var $t=[[/^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"]],_e="",Pt=(async()=>{var e;let n=navigator.userAgentData;if(!n||!/Android/.test(V))return"";try{let a=((e=(await n.getHighEntropyValues(["model"])).model)!=null?e:"").trim();if(!a||a==="K")return"";let o=$t.find(([v])=>v.test(a));_e=o?`${o[1]} (${a})`:/^SM-/.test(a)?`Galaxy ${a}`:a}catch{}return _e})();function St(n){return/iPhone/.test(V)?"iPhone":Qe?"iPad":/Android/.test(V)?_e||(n==="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":ue[n]}function Rt(){if(!R)return;let n=Me(),e=new Set(R.person.devices.map(B=>B.name.toLowerCase())),a=B=>{let D=B===Me()?St(B):ue[B];if(!e.has(D.toLowerCase()))return D;for(let F=2;F<20;F++)if(!e.has(`${D} ${F}`.toLowerCase()))return`${D} ${F}`;return D},o=t("input",{type:"text",value:a(n),maxlength:48,"aria-label":"Device name",required:!0}),v=!1;o.addEventListener("input",()=>v=!0),Pt.then(()=>{!v&&n===Me()&&(o.value=a(n))});let p=t("div",{class:"kinds"},R.kinds.map(B=>t("button",{type:"button",class:`kind${B===n?" on":""}`,"data-k":B,onclick:()=>{n=B,p.querySelectorAll(".kind").forEach(D=>D.classList.toggle("on",D.dataset.k===B)),v||(o.value=a(B))}},O(B),t("span",{},ue[B])))),_=t("p",{class:"err"}),$=t("button",{class:"btn primary block",type:"submit"},"Create connection");pe("Add a device",`${R.person.device_limit-R.person.devices.length} of ${R.person.device_limit} slots free`,t("form",{class:"add",onsubmit:async B=>{B.preventDefault(),$.disabled=!0,_.textContent="";try{let D=await oe("devices",{name:o.value.trim(),kind:n});R=D.state;let F=D.state.person.devices.find(J=>J.id===D.id);await fe(F,void 0,D.config)}catch(D){_.textContent=D.message,$.disabled=!1}}},t("label",{class:"lbl"},"What is it?"),p,t("label",{class:"lbl"},"Name"),o,_,$))}async function We(){try{R=await oe("state"),document.title=`${R.person.name} · ${R.title}`,!ie&&!X&&ge(R)}catch(n){let e=n;e.status===404||e.status===401?(R=null,Je()):R||Le(t("div",{class:"card"},t("p",{},e.message)))}}function Nt(){clearInterval(Fe),Fe=window.setInterval(()=>{R&&document.visibilityState==="visible"&&We()},15e3)}!de||!yt?Je():(We(),Nt());})(); 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 new file mode 100755 index 0000000..935ea37 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/dawnline/portal/www/cgi-bin/portal @@ -0,0 +1,344 @@ +#!/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. +'use strict'; + +import { stdin, stat, unlink, readfile } from 'fs'; +import { + read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, 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'; + +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; + +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]; + return { + title, + person: v, + server: { name: srv?.name, endpoint: core.endpoint_host(m, srv) }, + 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} (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 == '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} (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]; + send_json('200 OK', { ok: true, state: state() }); +} + +fail('404 Not Found', 'Not found.'); 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 new file mode 100644 index 0000000..e147483 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/luci/menu.d/luci-app-dawnline.json @@ -0,0 +1,76 @@ +{ + "admin/network/dawnline": { + "title": "Dawnline", + "order": 65, + "action": { + "type": "alias", + "path": "admin/network/dawnline/server" + }, + "depends": { + "acl": [ + "luci-app-dawnline" + ], + "uci": { + "dawnline": true + } + } + }, + "admin/network/dawnline/overview": { + "action": { + "type": "view", + "path": "dawnline/server" + } + }, + "admin/network/dawnline/people": { + "action": { + "type": "view", + "path": "dawnline/people" + } + }, + "admin/network/dawnline/activity": { + "title": "Activity", + "order": 25, + "action": { + "type": "view", + "path": "dawnline/activity" + } + }, + "admin/network/dawnline/person": { + "action": { + "type": "view", + "path": "dawnline/person" + } + }, + "admin/network/dawnline/server": { + "title": "Servers", + "order": 10, + "action": { + "type": "view", + "path": "dawnline/server" + } + }, + "admin/network/dawnline/health": { + "title": "Health", + "order": 40, + "action": { + "type": "view", + "path": "dawnline/health" + } + }, + "admin/network/dawnline/settings": { + "title": "Settings", + "order": 60, + "action": { + "type": "view", + "path": "dawnline/settings" + } + }, + "admin/network/dawnline/updates": { + "title": "Updates", + "order": 70, + "action": { + "type": "view", + "path": "dawnline/updates" + } + } +} 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 new file mode 100644 index 0000000..96b13d1 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/rpcd/acl.d/luci-app-dawnline.json @@ -0,0 +1,35 @@ +{ + "luci-app-dawnline": { + "description": "Grant access to Dawnline", + "read": { + "ubus": { + "luci.dawnline": [ + "status", + "setup_defaults", + "health", + "backup_list", + "updates_status", + "person_usage", + "settings_get", + "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 new file mode 100644 index 0000000..d1a7938 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/rpcd/ucode/luci.dawnline @@ -0,0 +1,1103 @@ +// Dawnline — rpcd backend for the LuCI admin UI (ubus object luci.dawnline). +'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, lock, unlock, uniq, 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'; + +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 ---------- */ + +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, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns, + address: core.server_address(srv), up: !!st?.up, uptime: st?.uptime ?? 0, + 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), + totals, + series: live.series(recs, clamp_days(a.days)), + events: 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'; +} + +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: length(m.servers) ? `server${length(m.servers) + 1}` : 'home', + 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'); + 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 }, + 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'); + 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); + 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.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'); + } + return commit(c, true); +} + +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'); + return commit(c, true); +} + +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'); + for (let pid, p in m.people) + if (p.server == a.id) + core.delete_person(c, m, pid); + c.delete('dawnline', a.id); + return commit(c, true); +} + +/* ---------- 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 }); + 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, detail: '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'); + // 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 }); + 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' }); + 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} (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'); + } + return commit(c); +} + +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} (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); + 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; + 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 }, 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', + '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(); + 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 }; +} + +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) { + let ev = live.load_events(); + let n = +a.limit || 300; + return { events: 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; + } + return { ok: true, removed: live.clear_events(f) }; +} + +/** + * 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); + } + 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), + }, + 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 }, 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() })) }, + health_fix: { args: { id: '' }, call: wrap((a) => ({ result: ops.fix(a.id), checks: ops.health() })) }, + 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) => ops.backup_restore(a.name)) }, + 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) => ops.backup_upload(a.data)) }, + export: { call: wrap((a) => ops.export_json()) }, + import: { args: { data: {} }, call: wrap((a) => ops.import_json(a.data)) }, + 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: [] }, + 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) }, + 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/apply.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/apply.uc new file mode 100644 index 0000000..aaecb5b --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/apply.uc @@ -0,0 +1,621 @@ +// 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 +// * 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. + +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, RUN_DIR +} from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as net from 'dawnline.net'; +import * as loop from 'dawnline.loop'; + +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; + +function log(msg) { + system(`logger -t dawnline ${q(msg)}`); +} + +/* ---------- 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); + let before = changed; + changed = ensure_section(c, 'network', ifn, 'interface') || changed; + changed = put(c, 'network', ifn, 'proto', 'amneziawg') || changed; + changed = put(c, 'network', ifn, 'private_key', srv.private_key) || changed; + changed = put(c, 'network', ifn, 'listen_port', srv.port) || changed; + changed = put(c, 'network', ifn, 'addresses', [ `${addr}/${pc.prefix}` ]) || changed; + changed = put(c, 'network', ifn, 'mtu', srv.mtu) || changed; + changed = put(c, 'network', ifn, 'disabled', srv.enabled ? null : '1') || changed; + changed = put(c, 'network', ifn, 'auto', srv.enabled ? null : '0') || changed; + changed = put(c, 'network', ifn, '_dawnline', id) || changed; + for (let k in core.OBF_KEYS) + changed = put(c, 'network', ifn, `awg_${k}`, srv.obf[k]) || changed; + if (changed != before) + push(touched, ifn); + } + + // 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) { + 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)}`); + log(`network updated (${join(', ', touched) || 'removed ' + join(', ', stale)})`); + } + return changed; +} + +/* ---------- firewall ---------- */ + +const LOOP_ZONE = 'dl_loop'; + +function sync_firewall(m) { + 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', { + name: srv.ifname, network: [ srv.ifname ], + input: 'ACCEPT', output: 'ACCEPT', forward: 'REJECT', + }); + // 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. + for (let i, zone in sn.zones) + if (zone != sn.wan.zone && zone != srv.ifname) + sec(i == 0 ? `${z}_lan` : `${z}_lan_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`, 'forwarding', { src: srv.ifname, dest: zone }); + 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 (changed) { + c.commit('firewall'); + ack_config([ 'firewall' ]); + system('fw4 -q reload'); + log('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) { + let sets = { lan_ok: [], inet_ok: [], svc_ok: [], dns_real: [] }; + 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); + 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}`); + } + } + 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 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_ok 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, ' }'); + // 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(`nft failed: ${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', '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) + log(`awg syncconf ${srv.ifname}: ${trim(r.out)}`); + } + return res; +}; + +/* ---------- hostnames ---------- */ + +function host_label(s) { + let l = replace(lc(s), /[^a-z0-9]+/g, '-'); + l = replace(l, /^-+|-+$/g, ''); + return substr(l, 0, 40) || 'device'; +} + +export function sync_hosts(m) { + let lines = []; + if (m.settings.hostnames) + for (let id, d in m.devices) { + let p = m.people[d.person]; + if (p && d.address) + push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`); + } + let ls = loop.status(); + if (ls.active) + push(lines, `${ls.address} dawnline.${m.settings.domain}`); + let body = length(lines) ? join('\n', lines) + '\n' : ''; + // dnsmasq runs as its own user; rpcd's umask would leave the file 0600. + let readable = ((stat(HOSTS_FILE)?.perm?.other_read) ?? false); + if ((readfile(HOSTS_FILE) ?? '') == body && (body == '' || readable)) + return false; + ensure_dir('/tmp/hosts'); + if (body == '') + unlink(HOSTS_FILE); + else { + writefile(HOSTS_FILE, body); + system(`chmod 644 ${HOSTS_FILE}`); + } + system('killall -HUP dnsmasq 2>/dev/null'); + return true; +}; + +/* ---------- entry points ---------- */ + +export function states_for(m, usage) { + let st = {}; + for (let id, p in m.people) + st[id] = core.person_state(m, p, 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(); + 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); + sync_hosts(m); + unlock(l); + ensure_dir(RUN_DIR); + write_json(`${RUN_DIR}/states.json`, states, 0o644); + return { peers, states }; +}; + +/** + * Everything on the router that Dawnline's state is derived from: WAN and + * LAN, the home networks and zones of each server, the netns address and the + * LAN's DNS. The agent re-applies when it changes (LAN renumbered, interface + * added, bridge recreated, DHCP DNS changed, ...). + */ +export function net_signature(m) { + let snap = net.snapshot(true); + let srvs = {}; + for (let id, srv in m.servers) + srvs[id] = net.server_net(srv, snap); + let lan = snap.devices[snap.lan]; + 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'); + log(want ? 'portal answers on 443 at home too' : 'portal removed from the LuCI web server'); + } +} + +/** 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); + } + 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'); + } +} + +/** 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 }; +}; + +/** 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'); +}; 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 new file mode 100644 index 0000000..6e54081 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc @@ -0,0 +1,937 @@ +// Dawnline — data model: reads /etc/config/dawnline, validates and mutates it, +// allocates addresses, generates keys and renders client configurations. + +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 +} from 'dawnline.util'; +import * as net from 'dawnline.net'; +import * as loop from 'dawnline.loop'; + +export const CONFIG = 'dawnline'; +export const ACCESS = [ 'lan', 'internet', 'both' ]; +export const KINDS = [ 'computer', 'phone', 'tablet', 'router', 'other' ]; +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; + let n = +v; + return n != n ? dflt : int(n); +} + +function num(v, dflt) { + if (v == null || v == '') + return dflt; + let n = +v; + return n != n ? dflt : n; +} + +function bool(v, dflt) { + if (v == null || v == '') + return dflt; + return v == '1' || v == 'true' || v == 'yes' || v == 'on'; +} + +function list(v) { + if (v == null) + return []; + return type(v) == 'array' ? v : split(trim(v), /[[:space:],]+/); +} + +/* ---------- load ---------- */ + +export function open_cursor() { + let c = cursor(); + c.load(CONFIG); + return c; +}; + +export function load(c) { + c ??= open_cursor(); + let s = c.get_all(CONFIG, 'settings') ?? {}; + let m = { + 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 != ''), + portal_cert: s.portal_cert ?? '', + portal_key: s.portal_key ?? '', + portal_title: s.portal_title ?? 'Dawnline', + // Where unknown portal links go instead of a bare 404 (empty = 404). + portal_redirect: s.portal_redirect ?? '', + paused_all: bool(s.paused_all, false), + default_device_limit: toint(s.default_device_limit, 3), + geo_enabled: bool(s.geo_enabled, true), + geo_provider: s.geo_provider == 'ipapi.co' ? 'ipapi.co' : 'ipwho.is', + hostnames: bool(s.hostnames, true), + domain: s.domain ?? 'lan', + log_connections: bool(s.log_connections, 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'), + // 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, + log_connections: s.log_connections, log_persist: s.log_persist, + usage_keep_days: s.usage_keep_days, usage_keep_months: s.usage_keep_months, + }, + }, + servers: {}, + people: {}, + devices: {}, + services: {}, + }; + + c.foreach(CONFIG, 'server', (r) => { + let id = r['.name']; + let srv = { + id, + name: r.name ?? id, + ifname: r.ifname ?? id, + port: toint(r.port, 51820), + subnet: r.subnet ?? '', + endpoint: r.endpoint ?? '', + mtu: toint(r.mtu, 1380), + dns: list(r.dns), + keepalive: toint(r.keepalive, 25), + private_key: r.private_key ?? '', + public_key: r.public_key ?? '', + preset: r.preset ?? 'standard', + lan_zone: r.lan_zone ?? 'lan', + wan_zone: r.wan_zone ?? 'wan', + auto_wan: bool(r.auto_wan, true), + wan_device: r.wan_device ?? '', + auto_lan: bool(r.auto_lan, true), + lan_devices: list(r.lan_device), + detected_wan: r.detected_wan ?? '', + detected_lan: r.detected_lan ?? '', + lan_like: bool(r.lan_like, true), + enabled: bool(r.enabled, true), + obf: {}, + }; + for (let k in OBF_KEYS) + if (r[k] != null && r[k] != '') + srv.obf[k] = `${r[k]}`; + m.servers[id] = srv; + }); + + c.foreach(CONFIG, 'person', (r) => { + let id = r['.name']; + m.people[id] = { + id, + server: r.server ?? '', + name: r.name ?? id, + access: index(ACCESS, r.access) >= 0 ? r.access : 'internet', + device_limit: toint(r.device_limit, m.settings.default_device_limit), + code: r.code ?? '', + expires: r.expires ?? '', + quota_gb: num(r.quota_gb, 0), + quota_period: r.quota_period == 'total' ? 'total' : 'month', + paused: bool(r.paused, false), + hours: r.hours ?? '', + expire_action: index([ 'pause', 'notify', 'remove' ], r.expire_action) >= 0 ? r.expire_action : 'pause', + // Home-only access: keep the device's own DNS, or use home names (Dawnline's resolver). + dns_mode: r.dns_mode == 'home' ? 'home' : 'device', + expire_warn: toint(r.expire_warn, 3), + bonus_gb: num(r.bonus_gb, 0), + bonus_month: r.bonus_month ?? '', + services: list(r.service), + note: r.note ?? '', + created: toint(r.created, 0), + devices: [], + }; + }); + + c.foreach(CONFIG, 'device', (r) => { + let id = r['.name']; + let d = { + id, + person: r.person ?? '', + name: r.name ?? id, + kind: index(KINDS, r.kind) >= 0 ? r.kind : 'other', + address: r.address ?? '', + public_key: r.public_key ?? '', + private_key: r.private_key ?? '', + preshared_key: r.preshared_key ?? '', + created: toint(r.created, 0), + created_by: r.created_by ?? 'admin', + disabled: bool(r.disabled, false), + }; + m.devices[id] = d; + if (m.people[d.person]) + push(m.people[d.person].devices, id); + }); + + c.foreach(CONFIG, 'service', (r) => { + let id = r['.name']; + m.services[id] = { + id, + name: r.name ?? id, + address: r.address ?? '', + ports: list(r.port), + }; + }); + + return m; +}; + +/* ---------- derived state ---------- */ + +/** Parse "07:00-23:00" → [startMin, endMin] or null. */ +export function parse_hours(s) { + let m = match(s ?? '', /^([0-9]{1,2}):([0-9]{2})-([0-9]{1,2}):([0-9]{2})$/); + if (!m) + return null; + let a = +m[1] * 60 + +m[2], b = +m[3] * 60 + +m[4]; + if (a >= 1440 || b > 1440 || a == b) + return null; + return [ a, b ]; +}; + +function within_hours(h, ts) { + let t = localtime(ts); + let cur = t.hour * 60 + t.min; + return h[0] < h[1] ? (cur >= h[0] && cur < h[1]) : (cur >= h[0] || cur < h[1]); +} + +/** Bytes used in the person's quota period. */ +export function person_usage(p, usage) { + let u = usage?.people?.[p.id]; + if (!u) + return 0; + if (p.quota_period == 'total') + return (u.total?.[0] ?? 0) + (u.total?.[1] ?? 0); + let mm = u.months?.[month_key()]; + return mm ? mm[0] + mm[1] : 0; +}; + +/** Quota in bytes for the current period (base + this month's bonus), 0 = unlimited. */ +export function person_quota(p) { + if (!(p.quota_gb > 0)) + return 0; + let gb = p.quota_gb; + if (p.bonus_gb > 0 && p.bonus_month == month_key()) + gb += p.bonus_gb; + return gb * 1073741824; +}; + +export function person_expired(p, ts) { + if (p.expires == '') + return false; + let end = date_end(p.expires); + return end != null && (ts ?? time()) > end; +}; + +/** + * Effective state of a person: 'active', or why they are off: + * 'paused' (admin), 'paused_all', 'expired', 'quota', 'hours', 'no_server'. + */ +export function person_state(m, p, usage, ts) { + ts ??= time(); + let srv = m.servers[p.server]; + if (!srv || !srv.enabled) + return 'no_server'; + if (p.paused) + return 'paused'; + if (m.settings.paused_all) + return 'paused_all'; + // "notify" keeps access after the end date (shown in Overview and People). + if (person_expired(p, ts) && p.expire_action != 'notify') + return 'expired'; + let quota = person_quota(p); + if (quota > 0 && person_usage(p, usage) >= quota) + return 'quota'; + let h = parse_hours(p.hours); + if (h && !within_hours(h, ts)) + return 'hours'; + return 'active'; +}; + +export function load_usage() { + return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, { devices: {}, people: {} }); +}; + +/* ---------- 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`); +}; + +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). */ +export function server_address(srv) { + let c = parse_cidr(srv.subnet); + return c ? int2ip(c.first) : null; +}; + +export function alloc_address(m, srv) { + let c = parse_cidr(srv.subnet); + if (!c) + return null; + let used = {}; + used[c.first] = true; + for (let id, d in m.devices) { + let p = m.people[d.person]; + if (p && p.server == srv.id) { + let n = ip2int(d.address); + if (n != null) + used[n] = true; + } + } + for (let n = c.first + 1; n <= c.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 ---------- */ + +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. + */ +export function dns_list(m, srv) { + if (!srv) + return []; + if (length(srv.dns)) + return srv.dns; + let a = server_address(srv); + return a ? [ a ] : []; +}; + +/** + * 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. + */ +export function client_dns(m, srv, p) { + if (p?.access != 'lan') + return dns_list(m, srv); + if (p.dns_mode != 'home') + return []; + let a = server_address(srv); + let out = a ? [ a ] : []; + if (m.settings.home_dns_fallback && m.settings.home_dns_fallback != a) + push(out, m.settings.home_dns_fallback); + return out; +}; + +export function allowed_ips(m, srv, p) { + if (p.access == 'lan') { + let nets = net.server_net(srv).nets; + let a = server_address(srv); + 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. */ +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}`); + 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) { + die(msg); +} + +/* + * Personal codes are three pronounceable words of three syllables each + * (kamiro-telosu-bavine): easy to read out or type, ~2^55 combinations, and + * guessing is rate-limited by the portal. The code is the whole link path. + */ +export const WORD_CODE = /^[a-z]{6}-[a-z]{6}-[a-z]{6}$/; +const SYL_C = 'bdfgklmnprstvz', SYL_V = 'aeiou'; +const CODE_AVOID = [ 'suka', 'pido', 'muda', 'zalup', 'dura', 'gavn' ]; + +function pick(alphabet) { + let n = length(alphabet), lim = 256 - 256 % n; + for (;;) { + let b = ord(rand_bytes(1), 0); + if (b < lim) + return substr(alphabet, b % n, 1); + } +} + +export function new_code() { + for (;;) { + let words = []; + for (let w = 0; w < 3; w++) { + let s = ''; + for (let i = 0; i < 3; i++) + s += pick(SYL_C) + pick(SYL_V); + push(words, s); + } + let code = join('-', words); + if (!length(filter(CODE_AVOID, (x) => index(code, x) >= 0))) + return code; + } +}; + +export function create_person(c, m, a) { + if (!valid_name(a.name)) + fail('Enter a name (up to 48 characters).'); + // The id is a UCI section name: letters, digits and underscores only (a dash + // makes uci drop the section). Repeated names get _2, _3, … + 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'; + let slug = base; + for (let n = 2; taken(slug); n++) { + if (n > 99) + fail(`"${base}" is already taken.`); + slug = `${substr(base, 0, 28)}_${n}`; + } + let srv_id = a.server ?? keys(m.servers)[0]; + if (!m.servers[srv_id]) + fail('Set up a server first.'); + let access = a.access ?? 'internet'; + if (index(ACCESS, access) < 0) + fail('Access must be lan, internet or both.'); + let limit = toint(a.device_limit, m.settings.default_device_limit); + if (limit < 1 || limit > 32) + fail('Device limit must be between 1 and 32.'); + if (a.expires && !valid_date(a.expires)) + fail('End date must be YYYY-MM-DD.'); + let quota = num(a.quota_gb, 0); + if (quota < 0 || quota > 100000) + fail('Monthly data must be a positive number of GB.'); + + c.set(CONFIG, slug, 'person'); + c.set(CONFIG, slug, 'server', srv_id); + c.set(CONFIG, slug, 'name', trim(a.name)); + c.set(CONFIG, slug, 'access', access); + c.set(CONFIG, slug, 'device_limit', `${limit}`); + c.set(CONFIG, slug, 'code', new_code()); + c.set(CONFIG, slug, 'created', `${time()}`); + if (a.expires) + c.set(CONFIG, slug, 'expires', a.expires); + if (quota > 0) { + c.set(CONFIG, slug, 'quota_gb', `${quota}`); + c.set(CONFIG, slug, 'quota_period', a.quota_period == 'total' ? 'total' : 'month'); + } + return slug; +}; + +/** + * Immediate edit of a person from the admin page. Only keys present in `a` + * change; '' clears optional values (end date, data limit, hours). + */ +export function update_person(c, m, id, a) { + let p = m.people[id]; + if (!p) + fail('Unknown person.'); + let set = (k, v) => (v == null || v == '') ? c.delete(CONFIG, id, k) : c.set(CONFIG, id, k, `${v}`); + if (a.name != null) { + if (!valid_name(a.name)) + fail('Enter a name (up to 48 characters).'); + set('name', trim(a.name)); + } + if (a.access != null) { + if (index(ACCESS, a.access) < 0) + fail('Access must be lan, internet or both.'); + set('access', a.access); + } + if (a.device_limit != null) { + 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}.`); + set('device_limit', n); + } + if (a.expires != null) { + if (a.expires != '' && !valid_date(a.expires)) + fail('End date must be YYYY-MM-DD.'); + set('expires', a.expires); + } + if (a.expire_action != null) { + if (index([ 'pause', 'notify', 'remove' ], a.expire_action) < 0) + fail('Unknown end action.'); + set('expire_action', a.expire_action == 'pause' ? '' : a.expire_action); + } + if (a.dns_mode != null) { + if (index([ 'device', 'home' ], a.dns_mode) < 0) + fail('Unknown DNS choice.'); + set('dns_mode', a.dns_mode == 'device' ? '' : a.dns_mode); + } + if (a.expire_warn != null) { + let n = toint(a.expire_warn, -1); + if (n < 0 || n > 60) + fail('Warning must be 0-60 days.'); + set('expire_warn', n == 3 ? '' : n); + } + if (a.quota_gb != null) { + let q = num(a.quota_gb, -1); + if (a.quota_gb != '' && (q < 0 || q > 100000)) + fail('Data limit must be a positive number of GB.'); + set('quota_gb', q > 0 ? q : ''); + } + if (a.quota_period != null) + set('quota_period', a.quota_period == 'total' ? 'total' : ''); + if (a.bonus_gb != null) { + let b = num(a.bonus_gb, -1); + if (b < 0 || b > 100000) + fail('Extra data must be a positive number of GB.'); + set('bonus_gb', b > 0 ? b : ''); + set('bonus_month', b > 0 ? month_key() : ''); + } + if (a.hours != null) { + if (a.hours != '' && !parse_hours(a.hours)) + fail('Hours must look like 07:00-23:00.'); + set('hours', a.hours); + } + if (a.note != null) + set('note', substr(trim(a.note), 0, 500)); + if (type(a.services) == 'array') { + for (let sid in a.services) + if (!m.services[sid]) + fail(`Unknown service ${sid}.`); + if (length(a.services)) + c.set(CONFIG, id, 'service', a.services); + else + c.delete(CONFIG, id, 'service'); + } + if (a.paused != null) + set('paused', a.paused ? '1' : ''); +}; + +/** + * 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). + */ +export function create_device(c, m, person_id, name, kind, opts) { + opts ??= {}; + let p = m.people[person_id]; + if (!p) + fail('Unknown person.'); + let srv = m.servers[p.server]; + if (!srv) + fail('The person has no server.'); + name = trim(name ?? ''); + if (!valid_name(name)) + fail('Enter a device name (up to 48 characters).'); + if (index(KINDS, kind) < 0) + kind = 'other'; + if (opts.by == 'portal' && length(p.devices) >= p.device_limit) + fail(`Device limit reached (${p.device_limit}).`); + for (let id in p.devices) + if (lc(m.devices[id].name) == lc(name)) + fail(`"${name}" already exists.`); + 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) + fail('Key generation failed (is amneziawg-tools installed?).'); + for (let id, d in m.devices) + if (d.public_key == pub) + fail('This key is already in use.'); + + let id = `d_${rand_hex(4)}`; + 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'); + + // 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 }; + push(p.devices, id); + return id; +}; + +export function rename_device(c, m, id, name) { + let d = m.devices[id]; + if (!d) + fail('Unknown device.'); + name = trim(name ?? ''); + if (!valid_name(name)) + fail('Enter a device name (up to 48 characters).'); + for (let o in m.people[d.person]?.devices ?? []) + if (o != id && lc(m.devices[o].name) == lc(name)) + fail(`"${name}" already exists.`); + c.set(CONFIG, id, 'name', name); + d.name = name; +}; + +export function delete_device(c, m, id) { + let d = m.devices[id]; + if (!d) + fail('Unknown device.'); + c.delete(CONFIG, id); + let p = m.people[d.person]; + if (p) + p.devices = filter(p.devices, (x) => x != id); + delete m.devices[id]; +}; + +export function rotate_device(c, m, id) { + let d = m.devices[id]; + if (!d) + fail('Unknown device.'); + let priv = genkey(), pub = pubkey(priv); + if (!pub) + 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()); +}; + +export function delete_person(c, m, id) { + let p = m.people[id]; + if (!p) + fail('Unknown person.'); + for (let d in p.devices) + c.delete(CONFIG, d); + c.delete(CONFIG, 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}$/)) + push(errs, 'Interface name: 1-12 lowercase letters, digits or _.'); + if (srv.port < 1 || srv.port > 65535) + push(errs, 'Port must be 1-65535.'); + let c = parse_cidr(srv.subnet); + if (!c) + push(errs, 'Subnet must look like 10.77.0.0/24.'); + else + for (let o in others_subnets ?? []) { + let oc = parse_cidr(o); + if (oc && cidr_overlaps(c, oc)) + push(errs, `Subnet overlaps ${o}.`); + } + 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; +}; + +/** Someone else already forwards this TCP port from outside (a port forward we must not take over). */ +export function wan_port_taken(port) { + let c = cursor(); + c.load('firewall'); + let taken = false; + c.foreach('firewall', 'redirect', (r) => { + 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])) + 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 = []; + for (let h in [ m.settings.portal_host, ...m.settings.portal_alt ]) + if (h && index(out, h) < 0) + push(out, h); + return out; +}; + +/** IP addresses have no certificate: the portal also answers plain HTTP for them. */ +export function portal_http(m) { + return length(filter(portal_hosts(m), (h) => ip2int(h) != null)) > 0; +}; + +/** Where the portal listens for plain HTTP (next to its HTTPS port). */ +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. */ +export function portal_http_public(m) { + return m.settings.portal_443 && !wan_port_taken(80) ? 80 : portal_http_port(m); +}; + +/** The port in personal links: 443 when the portal also answers there. */ +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; +}; + +/** The link on one address: https for names, plain http for IP addresses. */ +export function portal_link(m, p, host) { + if (!host || !m.servers[p.server] || !match(p.code ?? '', WORD_CODE)) + return null; + if (ip2int(host) != null) { + let hp = portal_http_public(m); + return `http://${host}${hp == 80 ? '' : `:${hp}`}/${p.code}`; + } + let pp = portal_public_port(m); + return `https://${host}${pp == 443 ? '' : `:${pp}`}/${p.code}`; +}; + +/** The main link (QR, invite card, Copy link). */ +export function portal_url(m, p) { + return portal_link(m, p, portal_hosts(m)[0]); +}; + +/** Every link to the same portal, the main one first. */ +export function portal_urls(m, p) { + return filter(map(portal_hosts(m), (h) => portal_link(m, p, h)), (x) => x != null); +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/geo.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/geo.uc new file mode 100644 index 0000000..90d0218 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/geo.uc @@ -0,0 +1,135 @@ +// Dawnline — city-level locations for the admin map. +// +// Client addresses are looked up once with a third-party service (ipwho.is, +// ipapi.co as fallback) and cached in DATA_DIR/geo.json. Only the agent +// performs lookups, a few per minute at most; the UI reads the cache. + +import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR } from 'dawnline.util'; + +const CACHE = `${DATA_DIR}/geo.json`; +const TTL = 30 * 86400; +const RETRY = 86400; + +// [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …). +const PRIVATE4 = map([ [ '0.0.0.0', 8 ], [ '10.0.0.0', 8 ], [ '100.64.0.0', 10 ], [ '127.0.0.0', 8 ], [ '169.254.0.0', 16 ], + [ '172.16.0.0', 12 ], [ '192.168.0.0', 16 ], [ '198.18.0.0', 15 ], [ '224.0.0.0', 3 ] ], (r) => [ ip2int(r[0]), 1 << (32 - r[1]) ]); + +/** True for addresses a geolocation service can say something about. */ +export function is_public(ip) { + if (type(ip) != 'string' || ip == '') + return false; + let n = ip2int(ip); + if (n != null) { + for (let r in PRIVATE4) + if (n >= r[0] && n < r[0] + r[1]) + return false; + return true; + } + let l = lc(ip); + return match(l, /^[0-9a-f:]+$/) != null && !match(l, /^(fe[89ab]|f[cd]|::1$|::$)/); +}; + +export function load() { + return read_json(CACHE, null) ?? { ips: {}, home: null }; +}; + +export function save(cache) { + ensure_dir(DATA_DIR, 0o700); + write_json(CACHE, cache, 0o600); +}; + +function fetch_json(url) { + let out = sh_out(`uclient-fetch -q -T 8 -O - ${q(url)}`); + if (!out) + return null; + try { + return json(out); + } + catch (e) { + return null; + } +} + +function lookup_ipwho(ip) { + let j = fetch_json(`https://ipwho.is/${ip}?fields=success,ip,latitude,longitude,city,country,country_code,connection`); + if (!j || j.success !== true || j.latitude == null) + return null; + let cn = j.connection ?? {}; + return { lat: +j.latitude, lon: +j.longitude, city: j.city ?? '', country: j.country ?? '', cc: j.country_code ?? '', ip: j.ip, + asn: cn.asn ? +cn.asn : 0, org: cn.isp || cn.org || '' }; +} + +function lookup_ipapi(ip) { + let j = fetch_json(ip ? `https://ipapi.co/${ip}/json/` : 'https://ipapi.co/json/'); + if (!j || j.error || j.latitude == null) + return null; + return { lat: +j.latitude, lon: +j.longitude, city: j.city ?? '', country: j.country_name ?? '', cc: j.country_code ?? '', ip: j.ip, + asn: +replace(`${j.asn ?? ''}`, /^AS/i, '') || 0, org: j.org ?? '' }; +} + +/** One lookup with the configured provider and the other as fallback. */ +export function lookup(provider, ip) { + let order = provider == 'ipapi.co' ? [ lookup_ipapi, lookup_ipwho ] : [ lookup_ipwho, lookup_ipapi ]; + for (let fn in order) { + let r = fn(ip ?? ''); + if (r) + return r; + } + return null; +}; + +/** + * Resolve up to `max` addresses that are missing or stale. Returns true when + * the cache changed (the caller saves it). + */ +export function resolve(settings, cache, ips, max) { + let now = time(), changed = false, done = 0; + for (let ip in ips) { + if (done >= max) + break; + if (!is_public(ip)) + continue; + let c = cache.ips[ip]; + if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL))) + continue; + let r = lookup(settings.geo_provider, ip); + done++; + changed = true; + if (r) { + delete r.ip; + r.ts = now; + cache.ips[ip] = r; + } + else + cache.ips[ip] = { fail: now }; + } + // Keep the cache bounded: drop the oldest entries beyond 500. + let all = keys(cache.ips); + if (length(all) > 500) { + all = sort(all, (a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0)); + for (let i = 0; i < length(all) - 500; i++) + delete cache.ips[all[i]]; + } + return changed; +}; + +/** Locate the router itself (the arcs' origin), at most every 6 hours. */ +export function resolve_home(settings, cache, wan_ip) { + let h = cache.home; + let now = time(); + if (h && h.asn != null && now - (h.ts ?? 0) < 6 * 3600 && (!wan_ip || !is_public(wan_ip) || h.wan == wan_ip)) + return false; + // Behind NAT, ask the service for our public address instead. + let r = lookup(settings.geo_provider, is_public(wan_ip) ? wan_ip : ''); + cache.home = r ? { ...r, wan: wan_ip, ts: now } : { ...(h ?? {}), ts: now }; + return true; +}; + +export function place(cache, ip) { + let c = cache.ips[ip]; + return (c && !c.fail) ? c : null; +}; + +export function clear() { + save({ ips: {}, home: null }); +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/live.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/live.uc new file mode 100644 index 0000000..5df432c --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/live.uc @@ -0,0 +1,408 @@ +// Dawnline — live data: peer status from `awg show all dump`, traffic +// accounting and the connection/event log. +// +// Counters live in RUN_DIR (tmpfs) and are flushed to DATA_DIR at most once +// an hour, so flash is not worn by the 60-second agent loop. + +import { readfile, stat, unlink } from 'fs'; +import { cursor } from 'uci'; +import { + q, sh, sh_out, sh_bg, ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, uniq, + RUN_DIR, DATA_DIR +} from 'dawnline.util'; + +export const ONLINE_WINDOW = 300; +const KEEP_DAYS = 62; +const KEEP_MONTHS = 24; +const KEEP_EVENTS = 2000; + +/* ---------- retention policy ---------- */ + +/** Event type → log category (what Settings lets you switch off or clear). */ +export const CATEGORY = { + connect: 'connections', disconnect: 'connections', roam: 'connections', + device_added: 'devices', device_removed: 'devices', devices_removed: 'devices', + person_added: 'people', person_removed: 'people', person_changed: 'people', + paused: 'people', resumed: 'people', paused_all: 'people', resumed_all: 'people', + server_down: 'problems', server_up: 'problems', portal_blocked: 'problems', +}; +export const CATEGORIES = [ 'connections', 'devices', 'people', 'problems' ]; + +export function category_of(type) { + return CATEGORY[type] ?? 'problems'; +}; + +function int_or(v, d) { + return (v == null || v == '' || match(`${v}`, /[^0-9]/)) ? d : +v; +} + +/** + * Log and history retention from /etc/config/dawnline (read fresh, the + * portal and rpcd call add_event without a loaded model). + * log_keep_days days of activity to keep, 0 = until log_max + * log_max newest N events kept + * log_category categories that are recorded + * log_persist how often the log is saved to flash: 10min | hourly | off + * usage_keep_days / usage_keep_months daily / monthly traffic buckets + */ +export function policy(s) { + if (s == null) { + let c = cursor(); + s = c.get_all('dawnline', 'settings') ?? {}; + } + let cats = s.log_category; + if (cats == null) + cats = (s.log_connections == '0') ? filter(CATEGORIES, (x) => x != 'connections') : CATEGORIES; + else if (type(cats) != 'array') + cats = split(cats, /[ ,]+/); + cats = filter(cats, (x) => index(CATEGORIES, x) >= 0); + return { + keep_days: int_or(s.log_keep_days, 30), + max: min(max(int_or(s.log_max, KEEP_EVENTS), 100), 20000), + categories: cats, + persist: index([ '10min', 'hourly', 'off' ], s.log_persist) >= 0 ? s.log_persist : 'hourly', + usage_days: min(max(int_or(s.usage_keep_days, KEEP_DAYS), 7), 1830), + usage_months: min(max(int_or(s.usage_keep_months, KEEP_MONTHS), 1), 120), + }; +}; + +/** Drop events older than keep_days and beyond max. */ +function trim_events(ev, pol) { + if (pol.keep_days > 0) { + let cut = time() - pol.keep_days * 86400; + ev = filter(ev, (e) => (e.ts ?? 0) >= cut); + } + if (length(ev) > pol.max) + ev = slice(ev, length(ev) - pol.max); + return ev; +} + +/* ---------- awg dump ---------- */ + +/** + * Parse `awg show all dump`. Returns { ifaces: { ifname: {...} }, peers: { pubkey: {...} } }. + * Interface lines have many fields (AmneziaWG adds obfuscation values); peer + * lines always have 9. + */ +export function dump() { + let r = sh('awg show all dump'); + let out = { ifaces: {}, peers: {} }; + if (r.code != 0) + return out; + 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; +}; + +export function endpoint_ip(ep) { + let m = match(ep ?? '', /^\[?([^\]]+?)\]?:[0-9]+$/); + return m ? m[1] : ep; +}; + +/* ---------- usage ---------- */ + +function empty_usage() { + return { devices: {}, people: {}, updated: 0, flushed: 0 }; +} + +export function load_usage() { + return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage(); +}; + +function add(bucket, key, rx, tx) { + let v = bucket[key] ?? [ 0, 0 ]; + bucket[key] = [ v[0] + rx, v[1] + tx ]; +} + +function prune(obj, keep) { + let ks = sort(keys(obj)); + for (let i = 0; i < length(ks) - keep; i++) + delete obj[ks[i]]; +} + +function account(rec, rx, tx, ts) { + rec.total = [ (rec.total?.[0] ?? 0) + rx, (rec.total?.[1] ?? 0) + tx ]; + rec.months ??= {}; + rec.days ??= {}; + add(rec.months, month_key(ts), rx, tx); + add(rec.days, day_key(ts), rx, tx); +} + +/** Apply the traffic history retention to every record. */ +export function prune_usage(usage, pol) { + pol ??= policy(); + for (let grp in [ usage.devices, usage.people ]) + for (let id, rec in grp) { + if (rec.months) + prune(rec.months, pol.usage_months); + if (rec.days) + prune(rec.days, pol.usage_days); + } +}; + +/** Forget a record's traffic history; kernel counters (raw) and the last handshake stay. */ +function wipe(rec) { + if (!rec) + return; + delete rec.total; + delete rec.months; + delete rec.days; +} + +/** + * Reset traffic history. scope: all | person | device. A person reset also + * clears their devices and restarts their data limit; a device reset leaves + * the person's totals (and so their limit) alone. + */ +export function reset_usage(usage, m, scope, id) { + if (scope == 'all') { + for (let k, rec in usage.devices) + wipe(rec); + for (let k, rec in usage.people) + wipe(rec); + } + else if (scope == 'person') { + wipe(usage.people[id]); + for (let did in m.people[id]?.devices ?? []) + wipe(usage.devices[did]); + } + else if (scope == 'device') { + wipe(usage.devices[id]); + } +}; + +/** + * 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. + */ +export function collect(m, usage, d) { + d ??= dump(); + let ts = time(); + let live = {}; + let by_key = {}; + for (let id, dev in m.devices) + by_key[dev.public_key] = id; + + 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 }; + continue; + } + let raw = rec.raw ?? [ 0, 0 ]; + let drx = peer.rx >= raw[0] ? peer.rx - raw[0] : peer.rx; + let dtx = peer.tx >= raw[1] ? peer.tx - raw[1] : peer.tx; + rec.raw = [ peer.rx, peer.tx ]; + if (drx > 0 || dtx > 0) { + account(rec, drx, dtx, ts); + let p = usage.people[dev.person] ??= {}; + account(p, drx, dtx, ts); + } + if (peer.handshake > 0) { + rec.handshake = peer.handshake; + rec.endpoint = endpoint_ip(peer.endpoint); + // Recent client addresses (for the map): ip → last seen, newest 8. + rec.ips ??= {}; + if (rec.endpoint) + rec.ips[rec.endpoint] = peer.handshake; + let ips = sort(keys(rec.ips), (x, y) => rec.ips[y] - rec.ips[x]); + for (let i = 8; i < length(ips); i++) + delete rec.ips[ips[i]]; + } + live[id] = { + online: peer.handshake > 0 && ts - peer.handshake < ONLINE_WINDOW, + handshake: peer.handshake || rec.handshake || 0, + endpoint: endpoint_ip(peer.endpoint) || rec.endpoint || '', + present: true, + }; + } + + // Forget counters of devices that no longer exist (their bytes stay in + // the person's totals). + for (let id in keys(usage.devices)) + if (!m.devices[id]) + delete usage.devices[id]; + + prune_usage(usage, policy(m.settings.retention)); + usage.updated = ts; + return live; +}; + +export function save_usage(usage, persist) { + ensure_dir(RUN_DIR); + write_json(`${RUN_DIR}/usage.json`, usage, 0o600); + if (persist) { + usage.flushed = time(); + ensure_dir(DATA_DIR, 0o700); + write_json(`${DATA_DIR}/usage.json`, usage, 0o600); + } +}; + +/** 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)]; + if (v) { + out[0] += v[0]; + out[1] += v[1]; + } + } + return out; +}; + +export function month(rec) { + return rec?.months?.[month_key()] ?? [ 0, 0 ]; +}; + +/** 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 rx = 0, tx = 0; + for (let r in recs) { + let v = r?.days?.[k]; + if (v) { + rx += v[0]; + tx += v[1]; + } + } + push(out, { day: k, rx, tx }); + } + return out; +}; + +/* ---------- events ---------- */ + +export function load_events() { + return read_json(`${RUN_DIR}/events.json`, null) ?? read_json(`${DATA_DIR}/events.json`, []); +}; + +export function add_events(list, pol) { + pol ??= policy(); + list = filter(list ?? [], (e) => index(pol.categories, category_of(e.type)) >= 0); + if (!length(list)) + return; + let l = lock('events'); + let ev = load_events(); + let ts = time(); + for (let e in list) { + e.ts ??= ts; + push(ev, e); + } + ev = trim_events(ev, pol); + ensure_dir(RUN_DIR); + write_json(`${RUN_DIR}/events.json`, ev, 0o600); + unlock(l); +}; + +export function add_event(e) { + add_events([ e ]); +}; + +/** Like add_event, but folds into the previous event of the same kind and person within `window` s. */ +export function add_event_merged(e, window) { + let pol = policy(); + if (index(pol.categories, category_of(e.type)) < 0) + return; + let l = lock('events'); + let ev = load_events(); + let last = ev[length(ev) - 1]; + let ts = time(); + if (last && last.type == e.type && last.person == e.person && ts - last.ts < (window ?? 120)) { + let parts = uniq([ ...split(last.detail ?? '', ', '), ...split(e.detail ?? '', ', ') ]); + last.detail = join(', ', filter(parts, (x) => x != '')); + last.ts = ts; + } + else { + e.ts = ts; + push(ev, e); + } + ev = trim_events(ev, pol); + ensure_dir(RUN_DIR); + write_json(`${RUN_DIR}/events.json`, ev, 0o600); + unlock(l); +}; + +/** Save the log to flash, or drop the flash copy when it is kept in RAM only. */ +export function persist_events(pol) { + pol ??= policy(); + if (pol.persist == 'off') { + if (stat(`${DATA_DIR}/events.json`)) + unlink(`${DATA_DIR}/events.json`); + return; + } + let ev = read_json(`${RUN_DIR}/events.json`, null); + if (ev != null) { + ensure_dir(DATA_DIR, 0o700); + write_json(`${DATA_DIR}/events.json`, trim_events(ev, pol), 0o600); + } +}; + +/** + * Remove events matching every given filter (person, device, category, + * older than `before` ts); no filters clears the whole log. Edits both the + * live copy and the one on flash. Returns how many were removed. + */ +export function clear_events(f) { + f ??= {}; + let hit = (e) => + (!f.person || e.person == f.person) && + (!f.device || e.device == f.device) && + (!f.category || category_of(e.type) == f.category) && + (!f.before || (e.ts ?? 0) < f.before); + let l = lock('events'); + let removed = 0; + for (let path in [ `${RUN_DIR}/events.json`, `${DATA_DIR}/events.json` ]) { + let ev = read_json(path, null); + if (ev == null) + continue; + let keep = filter(ev, (e) => !hit(e)); + if (path == `${RUN_DIR}/events.json` || removed == 0) + removed = max(removed, length(ev) - length(keep)); + write_json(path, keep, 0o600); + } + unlock(l); + return removed; +}; + +/* ---------- 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; + } +}; + +export function uptime() { + let s = readfile('/proc/uptime'); + return s ? int(+split(s, ' ')[0]) : 0; +}; 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 new file mode 100644 index 0000000..934d8ee --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc @@ -0,0 +1,555 @@ +// Dawnline — "like a home device": tunnel clients' internet traffic enters +// the router from the LAN, so whatever handles LAN traffic there (proxies, +// DPI bypass, DNS filters, fw4's lan zone, ...) handles it too, without +// Dawnline knowing about any of them. +// +// dawn0 ──policy route──▶ dlx0 ═veth═ dlx1 ┐ netns "dawnline" ┌ dll1 ═veth═ dll0 ── br-lan +// └── NAT to a LAN address ┘ +// +// The netns is one more device on the LAN bridge with its own address (picked +// from the LAN subnet above the DHCP pool). Replies come back the same way. +// Home-network destinations keep their direct route; per-person access is +// still enforced on dawn0 before any of this (table inet dawnline). +// +// 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. +// +// 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 +// direct path stays and status() says why. + +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, RUN_DIR } from 'dawnline.util'; +import * as net from 'dawnline.net'; + +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'; +const STATE = `${RUN_DIR}/loop.json`; +const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ]; + +function log(msg) { + system(`logger -t dawnline ${q(msg)}`); +} + +function run(cmds) { + let errs = []; + for (let c in cmds) { + let r = sh(c); + if (r.code != 0) + push(errs, `${c}: ${trim(r.out)}`); + } + return errs; +} + +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. */ +function dhcp_facts(logical, lan) { + let c = cursor(); + c.load('dhcp'); + let pool = null, dns = null, statics = []; + c.foreach('dhcp', 'dhcp', (s) => { + if (s.interface != logical || s.ignore == '1') + return; + let start = +(s.start ?? 100), limit = +(s.limit ?? 150); + pool = [ lan.net + start, lan.net + start + limit - 1 ]; + let opts = type(s.dhcp_option) == 'array' ? s.dhcp_option : (s.dhcp_option ? [ s.dhcp_option ] : []); + for (let o in opts) { + let m = match(o, /^(option:dns-server|6),([0-9.]+)/); + if (m && !dns) + dns = m[2]; + } + }); + c.foreach('dhcp', 'host', (s) => { + let ip = ip2int(s.ip ?? ''); + if (ip != null) + push(statics, ip); + }); + return { pool, dns, statics }; +} + +/** Addresses other devices are using right now (neighbour table + leases). */ +function used_addresses(dev) { + let used = {}; + try { + for (let n in json(sh_out(`ip -j -4 neigh show dev ${q(dev)}`) || '[]') ?? []) + if (n.dst && !(index(n.state ?? [], 'FAILED') >= 0 || index(n.state ?? [], 'INCOMPLETE') >= 0)) + used[n.dst] = n.lladdr ?? true; + } + catch (e) {} + for (let l in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) { + let f = split(l, ' '); + if (length(f) >= 3) + used[f[2]] = f[1]; + } + return used; +} + +function our_mac() { + return sh_out(`ip -n ${NS} -j link show ${LAN_NS} 2>/dev/null | jsonfilter -e '@[0].address'`); +} + +/** + * A LAN address for the netns: keep the saved one while it is valid and not + * taken by someone else, otherwise the highest free host above the DHCP pool + * (then below it), skipping static leases and anything that answers. + */ +function pick_address(lan, facts, saved, dev) { + let used = used_addresses(dev); + let mine = our_mac(); + let taken = (ip) => { + let s = int2ip(ip); + if (ip == lan.ip || index(facts.statics, ip) >= 0) + return true; + if (facts.pool && ip >= facts.pool[0] && ip <= facts.pool[1]) + return true; + let u = used[s]; + return u != null && !(mine && u == mine); + }; + let sv = ip2int(saved ?? ''); + if (sv != null && sv > lan.net && sv < lan.net + lan.size - 1 && !taken(sv)) + return int2ip(sv); + for (let ip = lan.net + lan.size - 2; ip > lan.net; ip--) { + if (taken(ip)) + continue; + // Last check: nobody answers on it. + sh(`ping -c 1 -W 1 -I ${q(dev)} ${int2ip(ip)}`); + let again = used_addresses(dev)[int2ip(ip)]; + if (again != null && !(mine && again == mine)) + continue; + return int2ip(ip); + } + return null; +} + +/** A /30 in 169.254.0.0/16 that no route or address on the router overlaps. */ +function pick_transit(saved) { + let busy = []; + for (let dev, d in net.snapshot().devices) + for (let n in [ ...d.nets, ...d.addrs ]) + 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) + return false; + } + return true; + }; + let sv = ip2int(saved ?? ''); + if (sv != null && free(sv)) + return sv; + for (let k = 77; k < 77 + 256; k++) { + let base = ip2int(`169.254.${k % 256}.0`); + if (free(base)) + return base; + } + return null; +} + +/** A routing table nobody else uses (ours holds a single route via the transit link). */ +function pick_table(saved) { + let free = (t) => { + let r = sh_out(`ip -4 route show table ${t}`) ?? ''; + return r == '' || (length(split(r, '\n')) == 1 && index(r, ` dev ${TX_ROOT}`) >= 0); + }; + if (saved && free(saved)) + return saved; + for (let t = 2077; t < 2177; t++) + if (free(t)) + return t; + return null; +} + +/* ---------- plan ---------- */ + +function settings() { + let c = cursor(); + c.load('dawnline'); + return c.get_all('dawnline', 'settings') ?? {}; +} + +/** Servers that want "like a home device" (default on). */ +function wanted(m) { + return filter(values(m.servers), (s) => s.private_key && s.enabled && s.lan_like); +} + +/** + * What should exist, or { error } when it cannot. Pure apart from reading + * router state (and one ping per candidate address). + */ +export function plan(m) { + let srvs = wanted(m); + if (!length(srvs)) + return { off: true }; + let snap = net.snapshot(); + let dev = snap.lan; + let d = snap.devices[dev]; + if (!dev || !d) + 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]); + if (!lan) + return { error: `${dev} has no IPv4 address.` }; + let facts = dhcp_facts(d.logical, lan); + let st = settings(); + let addr = pick_address(lan, facts, st.lan_address, dev); + if (!addr) + return { error: `No free address on ${int2ip(lan.net)}/${lan.prefix}.` }; + let last = read_json(STATE, {}); + let tx = pick_transit(last?.transit); + if (tx == null) + return { error: 'No free link-local range for the internal link.' }; + let table = pick_table(last?.plan?.table); + if (table == null) + return { error: 'No free routing table.' }; + 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 ]) }); + } + return { + dev, + gateway: int2ip(lan.ip), + address: addr, + prefix: lan.prefix, + dns: facts.dns ?? int2ip(lan.ip), + transit: tx, + tx_root: int2ip(tx + 1), + tx_ns: int2ip(tx + 2), + table, + servers, + }; +}; + +/* ---------- apply ---------- */ + +function ns_rules(p) { + return `table inet dawnline +delete table inet dawnline +table inet dawnline { + chain nat_pre { + type nat hook prerouting priority dstnat; policy accept; + iifname "${TX_NS}" ip daddr ${p.address} meta l4proto { tcp, udp } th dport 53 dnat ip to ${p.dns}:53 + } + chain nat_post { + type nat hook postrouting priority srcnat; policy accept; + oifname "${LAN_NS}" masquerade + } + chain filter_forward { + type filter hook forward priority filter; policy drop; + ct state established,related accept + iifname "${TX_NS}" oifname "${LAN_NS}" accept + } + chain filter_input { + type filter hook input priority filter; policy drop; + ct state established,related accept + iifname "lo" accept + icmp type echo-request accept + iifname "${TX_NS}" meta l4proto { tcp, udp } th dport 53 accept + } +} +`; +} + +/** Our policy rules: in our priority band and bound to a Dawnline tunnel interface. */ +function current_rules(ifnames) { + let out = []; + try { + for (let r in json(sh_out('ip -j -4 rule show') || '[]') ?? []) + if (r.priority >= 5200 && r.priority < 5300 && r.iif && index(ifnames, r.iif) >= 0) + push(out, r); + } + catch (e) {} + return out; +} + + +function rule_key(pref, iif, to, table) { + return `${pref} ${iif} ${to ?? 'all'} ${table}`; +} + +function sync_rules(p, ifnames) { + let want = []; + for (let s in p?.servers ?? []) { + push(want, [ PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}` ]); + for (let n in s.direct) + push(want, [ PREF_MAIN, s.ifname, n, 'main' ]); + push(want, [ PREF_LOOP, s.ifname, null, `${p.table}` ]); + } + let have = map(current_rules(ifnames), (r) => rule_key(r.priority, r.iif, r.dst ? `${r.dst}${r.dstlen != null ? '/' + r.dstlen : ''}` : null, r.table)); + let wantk = map(want, (w) => rule_key(w[0], w[1], w[2] ?? null, w[3])); + if (join('\n', sort(have)) == join('\n', sort(wantk))) + return []; + let cmds = []; + for (let r in current_rules(ifnames)) + push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`); + for (let w in want) + push(cmds, `ip -4 rule add priority ${w[0]} iif ${q(w[1])}${w[2] ? ' to ' + w[2] : ''} lookup ${w[3]}`); + return cmds; +} + +function tunnel_ifnames() { + let c = cursor(); + c.load('dawnline'); + let out = []; + c.foreach('dawnline', 'server', (s) => push(out, s.ifname ?? s['.name'])); + return out; +} + +/** Remove the netns, links and rules. */ +export function remove(ifnames) { + ifnames ??= tunnel_ifnames(); + let cmds = []; + for (let r in current_rules(ifnames)) + push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`); + let t = read_json(STATE, {})?.plan?.table; + if (t) + push(cmds, `ip -4 route flush table ${t}`); + if (exists(TX_ROOT)) + push(cmds, `ip link del ${TX_ROOT}`); + if (exists(LAN_ROOT)) + push(cmds, `ip link del ${LAN_ROOT}`); + if (stat(`/var/run/netns/${NS}`)) + push(cmds, `ip netns del ${NS}`); + run(cmds); + unlink(STATE); +}; + +/** + * Bring the loop to the plan. Cheap when nothing changed: compares with the + * 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 p = plan(m); + if (p.off || p.error) { + if (stat(STATE) || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames))) + remove(ifnames); + ensure_dir(RUN_DIR); + write_json(STATE, { error: p.error, off: !!p.off }, 0o644); + if (p.error) + log(`like-home routing off: ${p.error}`); + return p; + } + let last = read_json(STATE, {}); + let same = !force && last.applied && sprintf('%J', last.plan) == sprintf('%J', p); + let healthy = exists(TX_ROOT) && exists(LAN_ROOT) && stat(`/var/run/netns/${NS}`) && + replace(readlink(`/sys/class/net/${LAN_ROOT}/master`) ?? '', /^.*\//, '') == p.dev; + let rules = sync_rules(p, ifnames); + if (same && healthy && !length(rules)) + return p; + + let cmds = []; + if (!stat(`/var/run/netns/${NS}`)) + push(cmds, `ip netns add ${NS}`); + if (!exists(TX_ROOT)) + push(cmds, `ip link add ${TX_ROOT} type veth peer name ${TX_NS} netns ${NS}`); + if (!exists(LAN_ROOT)) + push(cmds, `ip link add ${LAN_ROOT} type veth peer name ${LAN_NS} netns ${NS}`); + let errs = run(cmds); + cmds = [ + `ip addr flush dev ${TX_ROOT}`, + `ip addr add ${p.tx_root}/30 dev ${TX_ROOT}`, + `ip link set ${TX_ROOT} up`, + `ip link set ${LAN_ROOT} master ${q(p.dev)}`, + `ip link set ${LAN_ROOT} up`, + `ip -n ${NS} link set lo up`, + `ip -n ${NS} addr flush dev ${TX_NS}`, + `ip -n ${NS} addr add ${p.tx_ns}/30 dev ${TX_NS}`, + `ip -n ${NS} link set ${TX_NS} up`, + `ip -n ${NS} addr flush dev ${LAN_NS}`, + `ip -n ${NS} addr add ${p.address}/${p.prefix} dev ${LAN_NS}`, + `ip -n ${NS} link set ${LAN_NS} up`, + `ip -n ${NS} route replace default via ${p.gateway} dev ${LAN_NS}`, + // The resolver's own queries (from the transit address) go back out the transit link. + `ip -n ${NS} route replace default via ${p.tx_root} dev ${TX_NS} table 100`, + `ip -n ${NS} rule del from ${p.tx_ns} lookup 100 2>/dev/null; ip -n ${NS} rule add from ${p.tx_ns} lookup 100`, + `ip netns exec ${NS} sh -c 'echo 1 > /proc/sys/net/ipv4/ip_forward; echo 0 > /proc/sys/net/ipv4/conf/all/rp_filter; echo 0 > /proc/sys/net/ipv4/conf/default/rp_filter'`, + `ip -4 route replace default via ${p.tx_ns} dev ${TX_ROOT} table ${p.table}`, + ]; + for (let s in p.servers) + push(cmds, `ip -n ${NS} route replace ${q(s.subnet)} via ${q(p.tx_root)} dev ${TX_NS}`); + ensure_dir('/var/etc'); + writefile('/var/etc/dawnline-ns.nft', ns_rules(p)); + push(cmds, `ip netns exec ${NS} nft -f /var/etc/dawnline-ns.nft`); + push(errs, ...run(cmds)); + push(errs, ...run(sync_rules(p, ifnames))); + + if (length(errs)) { + log(`like-home routing failed, using the direct path: ${errs[0]}`); + remove(ifnames); + 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); + log(`like-home routing: ${p.dev} as ${p.address}`); + return p; +}; + +/** Last applied state for views and health checks. */ +export function status() { + let s = read_json(STATE, {}); + if (s.plan) + return { + active: exists(TX_ROOT) && exists(LAN_ROOT), + dev: s.plan.dev, address: s.plan.address, dns: s.plan.dns, gateway: s.plan.gateway, transit: s.plan.tx_ns, + bridged: replace(readlink(`/sys/class/net/${LAN_ROOT}/master`) ?? '', /^.*\//, '') == s.plan.dev, + }; + return { active: false, off: !!s.off, error: s.error }; +}; + +/** The DNS address tunnel clients should use while the loop is up. */ +export function client_dns() { + let s = status(); + return s.active ? s.address : null; +}; + +/* ---------- 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(); + if (st.dns) + return st.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; +}; + +/** + * Where Home-only clients' DNS goes: inside the netns while it is up + * (`ns`: transit address, port 53), otherwise on the tunnel address (`root`). + */ +export function resolver_target() { + let st = status(); + 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. + */ +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; +}; + +/** 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; +}; + +export const RESOLVER = { port: RESOLVER_PORT, conf: RESOLVER_CONF }; 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 new file mode 100644 index 0000000..bcd3e93 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/net.uc @@ -0,0 +1,268 @@ +// Dawnline — the router's network interfaces: what exists, which one is the +// WAN, and which ones make up a server's "home network". +// +// Per server (uci `server` section): +// auto_wan 1 = use the interface of the default route (detected_wan +// is kept as a fallback while the WAN is down) +// wan_device the WAN interface when auto_wan is off +// auto_lan 1 = include the detected LAN (detected_lan as fallback) +// lan_device extra interfaces that count as the home network (list) +// +// Home access is enforced by destination: the networks routed out of the +// chosen interfaces form the nft `lan_nets` set, and the tunnel's firewall +// zone gets a forwarding to each of their zones. + +import { readfile, readlink, lsdir, stat } from 'fs'; +import { cursor } from 'uci'; +import { sh_out, ip2int, int2ip, 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' ]; +// 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 ] ]; + +function sysread(dev, f) { + return trim(readfile(`${SYS}/${dev}/${f}`) ?? ''); +} + +function ip_json(args) { + try { + return json(sh_out(`ip -j ${args} 2>/dev/null`) || '[]') ?? []; + } + catch (e) { + return []; + } +} + +function ubus_json(path, method) { + try { + return json(sh_out(`ubus call ${path} ${method} 2>/dev/null`) || 'null'); + } + catch (e) { + return null; + } +} + +/** "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 }; +} + +function net_str(n) { + return `${int2ip(n.net)}/${n.prefix}`; +} + +/** Drop networks already covered by a wider one. */ +export function collapse(list) { + let nets = filter(map(uniq(list), net_of), (x) => x != null); + nets = sort(nets, (a, b) => a.prefix - b.prefix || a.net - b.net); + let keep = []; + for (let n in nets) { + let inside = false; + for (let k in keep) + if (n.net >= k.net && n.net < k.net + k.size) { + inside = true; + break; + } + if (!inside) + push(keep, n); + } + return map(sort(keep, (a, b) => a.net - b.net), net_str); +}; + +function is_private(cidr) { + let n = net_of(cidr); + if (!n) + return false; + for (let p in PRIVATE) { + let base = ip2int(p[0]), size = 1 << (32 - p[1]); + if (n.net >= base && n.net < base + size) + return true; + } + return false; +} + +/* ---------- snapshot ---------- */ + +let cache = null; + +/** + * One consistent view of the router's interfaces, cached for a few seconds + * (rpcd keeps this module loaded, so the cache must expire). + */ +export function snapshot(fresh) { + if (!fresh && cache && time() - cache.ts < 5) + return cache; + + // Networks reachable through each device (main table, IPv4). + let routes = {}, wan_dev = null; + for (let r in ip_json('-4 route show table main')) { + if (!r.dev) + continue; + if (r.dst == 'default') { + wan_dev ??= r.dev; + continue; + } + push(routes[r.dev] ??= [], r.dst); + } + let addrs = {}; + for (let l in ip_json('-4 addr show')) + for (let a in l.addr_info ?? []) + if (a.family == 'inet') + push(addrs[l.ifname] ??= [], `${a.local}/${a.prefixlen}`); + + // Logical (netifd) interfaces by device, and firewall zones by network. + let logical = {}; + for (let i in ubus_json('network.interface', 'dump')?.interface ?? []) { + let dev = i.l3_device ?? i.device; + if (dev && !logical[dev]) + logical[dev] = { name: i.interface, proto: i.proto, up: i.up }; + } + let zone_by_net = {}, zone_by_dev = {}, zones = []; + let fc = cursor(); + fc.load('firewall'); + fc.foreach('firewall', 'zone', (z) => { + if (!z.name) + return; + push(zones, z.name); + for (let n in (type(z.network) == 'array' ? z.network : split(z.network ?? '', /\s+/))) + if (n != '') + zone_by_net[n] ??= z.name; + for (let d in (type(z.device) == 'array' ? z.device : split(z.device ?? '', /\s+/))) + if (d != '') + zone_by_dev[d] ??= z.name; + }); + + let devices = {}; + for (let dev in sort(lsdir(SYS) ?? [])) { + if (dev == 'lo' || dev == INTERNAL.transit || dev == INTERNAL.lan) + continue; + let lg = logical[dev]; + let flags = hex(sysread(dev, 'flags') || '0'); + let kind = +(sysread(dev, 'type') || '0'); + let master = readlink(`${SYS}/${dev}/master`); + master = master ? replace(master, /^.*\//, '') : null; + let bridge = stat(`${SYS}/${dev}/bridge`) != null; + let wifi = stat(`${SYS}/${dev}/phy80211`) != null || stat(`${SYS}/${dev}/wireless`) != null; + let nets = routes[dev] ? collapse(routes[dev]) : []; + let up = (flags & 1) != 0; + if (match(dev, NOISE) && !length(nets)) + continue; + 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)/)) + cat = 'vpn'; + else if (kind == 1 || bridge) + cat = 'ethernet'; + else + cat = 'other'; + devices[dev] = { + name: dev, + category: dev == wan_dev ? 'wan' : cat, + kind: bridge ? 'bridge' : cat, + up, + master, + members: [], + nets, + addrs: addrs[dev] ?? [], + logical: lg?.name, + proto: lg?.proto, + zone: zone_by_dev[dev] ?? (lg ? zone_by_net[lg.name] : null), + }; + } + for (let dev, d in devices) + if (d.master && devices[d.master]) + push(devices[d.master].members, dev); + + // The LAN: netifd's "lan" if present, otherwise the first bridge (then + // ethernet device) carrying a private network. + let lan_dev = null; + for (let dev, lg in logical) + if (lg.name == 'lan' && devices[dev]) + lan_dev = dev; + if (!lan_dev) + for (let pass in [ 'bridge', 'ethernet' ]) + for (let dev, d in devices) + if (!lan_dev && dev != wan_dev && d.kind == pass && !d.master && length(filter(d.nets, is_private))) + lan_dev = dev; + + cache = { ts: time(), devices, wan: wan_dev, lan: lan_dev, zones }; + return cache; +}; + +/* ---------- per server ---------- */ + +/** + * What a server actually uses right now: + * wan: { dev, zone, auto, missing } + * home: [{ dev, auto, nets, zone, missing }] + * nets: home networks (collapsed), zones: their firewall zones + */ +export function server_net(srv, snap) { + snap ??= snapshot(); + let devs = snap.devices; + + let wan_dev = srv.auto_wan ? (snap.wan ?? srv.detected_wan) : srv.wan_device; + let wan = { + dev: wan_dev || null, + auto: !!srv.auto_wan, + zone: devs[wan_dev]?.zone ?? srv.wan_zone ?? 'wan', + missing: !!wan_dev && !devs[wan_dev], + }; + + let picked = []; + let auto_lan = srv.auto_lan ? (snap.lan ?? srv.detected_lan) : null; + if (auto_lan) + push(picked, [ auto_lan, true ]); + for (let d in srv.lan_devices ?? []) + if (d != auto_lan) + push(picked, [ d, false ]); + + let home = [], nets = [], zones = []; + for (let p in picked) { + let dev = p[0]; + // Never the WAN, the tunnel itself, or a bridge port (routing only sees the bridge). + 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 }; + push(home, h); + push(nets, ...h.nets); + if (h.zone) + push(zones, h.zone); + } + // Older configs and routers where nothing could be resolved: the zone set at setup. + if (!length(home) && srv.auto_lan && srv.lan_zone) + push(zones, srv.lan_zone); + return { wan, home, nets: collapse(nets), zones: uniq(zones) }; +}; + +/** Router address on the home network (DNS for tunnel clients). */ +export function home_address(srv, snap) { + snap ??= snapshot(); + let sn = server_net(srv, snap); + for (let h in sn.home) + for (let a in snap.devices[h.dev]?.addrs ?? []) + return split(a, '/')[0]; + return null; +}; + +/** WAN IPv4 address of a server's WAN interface. */ +export function wan_address(srv, snap) { + snap ??= snapshot(); + let a = snap.devices[server_net(srv, snap).wan.dev]?.addrs?.[0]; + return a ? split(a, '/')[0] : 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 new file mode 100644 index 0000000..7d35bbf --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/ops.uc @@ -0,0 +1,658 @@ +// 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' ] ]), + }; +}; + +/** 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 }; +} + +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; +} + +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)); +}; + +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 (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) ? 'warn' : 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/util.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc new file mode 100644 index 0000000..2d69e55 --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc @@ -0,0 +1,276 @@ +// Dawnline — small helpers shared by the rpcd plugin, the CLI, the agent and +// the portal CGI. Nothing in here touches configuration. + +import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs'; + +export const VERSION = '0.1.0'; +/** GitHub repository with Dawnline releases (updates and the installer). */ +export const REPO = 'tickcount/luci-app-dawnline'; +export const RUN_DIR = '/var/run/dawnline'; +export const DATA_DIR = '/etc/dawnline'; + +/* ---------- shell ---------- */ + +export function q(s) { + return "'" + replace(`${s}`, "'", "'\\''") + "'"; +}; + +/** Run a shell command; returns { code, out }. Stdout and stderr are merged. */ +export function sh(cmd) { + let p = popen(`${cmd} 2>&1`, 'r'); + if (!p) + return { code: -1, out: '' }; + let out = p.read('all') ?? ''; + let code = p.close(); + return { code: code ?? 0, out: out }; +}; + +/** Trimmed stdout of a command, or null when it failed. */ +export function sh_out(cmd) { + let r = sh(cmd); + return r.code == 0 ? trim(r.out) : null; +}; + +/** Fire-and-forget: run a shell snippet detached from the caller. */ +export function sh_bg(cmd) { + system(`( ${cmd} ) >/dev/null 2>&1 255) + return null; + n = n * 256 + o; + } + return n; +}; + +export function int2ip(n) { + return sprintf('%d.%d.%d.%d', (n >> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255); +}; + +// 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', + '162.158.0.0/15', '104.16.0.0/13', '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22' ]; +const CF_V6 = [ /^2400:cb00:/i, /^2606:4700:/i, /^2803:f800:/i, /^2405:b500:/i, /^2405:8100:/i, /^2a06:98c[0-7]:/i, /^2c0f:f248:/i ]; + +/** True for an address in Cloudflare's network (its proxies and edge). */ +export function cloudflare_ip(a) { + let n = ip2int(a); + if (n == null) { + for (let r in CF_V6) + if (match(a ?? '', r)) + 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; +}; + +/** Parse "a.b.c.d/len" → { net, prefix, first, last, size } (net is the masked base). */ +export function parse_cidr(cidr) { + let m = match(cidr ?? '', /^([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); + let net = ip - ip % size; + return { net, prefix, size, first: net + 1, last: net + size - 2, ip }; +}; + +export function cidr_str(c) { + return `${int2ip(c.net)}/${c.prefix}`; +}; + +export function cidr_overlaps(a, b) { + return a.net < b.net + b.size && b.net < a.net + a.size; +}; + +export function in_cidr(ip, c) { + let n = type(ip) == 'int' ? ip : ip2int(ip); + return n != null && n >= c.net && n < c.net + c.size; +}; + +/* ---------- validation ---------- */ + +export function valid_slug(s) { + return type(s) == 'string' && match(s, /^[a-z0-9][a-z0-9-]{0,30}[a-z0-9]$|^[a-z0-9]$/) != null; +}; + +export function valid_name(s) { + return type(s) == 'string' && length(trim(s)) > 0 && length(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null; +}; + +export function valid_key(s) { + return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null; +}; + +export function valid_host(s) { + return type(s) == 'string' && length(s) <= 253 && + (match(s, /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/) != null || + ip2int(s) != null || match(s, /^[0-9a-fA-F:]+$/) != null); +}; + +export function valid_date(s) { + return type(s) == 'string' && match(s, /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/) != null; +}; + +/** Turn a display name into a portal slug candidate. */ +export function slugify(s) { + let out = lc(trim(`${s ?? ''}`)); + out = replace(out, /[^a-z0-9]+/g, '-'); + out = replace(out, /^-+|-+$/g, ''); + return substr(out, 0, 32) || 'user'; +}; + +/* ---------- time ---------- */ + +/** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */ +export function date_end(s) { + let m = match(s ?? '', /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/); + if (!m) + return null; + return timelocal({ sec: 59, min: 59, hour: 23, mday: +m[3], mon: +m[2], year: +m[1] }); +}; + +export function today() { + let t = localtime(); + return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday); +}; + +export function month_key(ts) { + let t = localtime(ts ?? time()); + return sprintf('%04d-%02d', t.year, t.mon); +}; + +export function day_key(ts) { + let t = localtime(ts ?? time()); + return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday); +}; + +export function uniq(arr) { + let seen = {}, out = []; + for (let v in arr) + if (!seen[v]) { + seen[v] = true; + push(out, v); + } + return out; +}; + +export function list_dir(path) { + return lsdir(path) ?? []; +}; + +export function remove(path) { + return unlink(path); +}; + +export function now() { + return time(); +}; 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 new file mode 100644 index 0000000..16bdf5d --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/view.uc @@ -0,0 +1,103 @@ +// Dawnline — read models shared by the admin RPC and the portal: people and +// devices merged with live peer state and usage. + +import * as core from 'dawnline.core'; +import * as live from 'dawnline.live'; +import { day_key, 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(); + for (let i = n - 1; i >= 0; i--) { + let v = rec?.days?.[day_key(ts - i * 86400)]; + push(out, v ? v[0] + v[1] : 0); + } + return out; +}; + +function config_stale(m, d) { + m._issued ??= core.issued(); + let was = m._issued[d.id]; + return was != null && was != core.config_fingerprint(m, d); +} + +export function device_view(m, d, usage, dmp) { + let u = usage.devices?.[d.id]; + let peer = dmp.peers[d.public_key]; + let ts = time(); + let hs = peer?.handshake || u?.handshake || 0; + let p = m.people[d.person]; + return { + id: d.id, + name: d.name, + kind: d.kind, + address: d.address, + disabled: d.disabled, + created: d.created, + created_by: d.created_by, + online: !!(peer && peer.handshake > 0 && ts - peer.handshake < live.ONLINE_WINDOW), + handshake: hs, + endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '', + active: !!peer, + month: live.month(u), + total: u?.total ?? [ 0, 0 ], + spark: spark(u, 7), + hostname: m.settings.hostnames && p ? `${replace(replace(lc(d.name), /[^a-z0-9]+/g, '-'), /^-+|-+$/g, '') || 'device'}.${p.id}.${m.settings.domain}` : '', + browser_key: d.private_key == '', + // Its configuration changed since it was last shown or downloaded. + config_stale: config_stale(m, d), + }; +}; + +export function person_view(m, p, usage, dmp, states, opts) { + opts ??= {}; + let u = usage.people?.[p.id]; + let devs = []; + for (let id in p.devices) + push(devs, device_view(m, m.devices[id], usage, dmp)); + devs = sort(devs, (a, b) => a.created - b.created); + let used = core.person_usage(p, usage); + let v = { + id: p.id, + name: p.name, + server: p.server, + access: p.access, + device_limit: p.device_limit, + expires: p.expires, + quota_gb: p.quota_gb, + quota_period: p.quota_period, + quota_used: used, + quota_limit: core.person_quota(p), + bonus_gb: (p.bonus_gb > 0 && p.bonus_month == month_key()) ? p.bonus_gb : 0, + expire_action: p.expire_action, + dns_mode: p.dns_mode, + expire_warn: p.expire_warn, + paused: p.paused, + hours: p.hours, + state: states[p.id] ?? core.person_state(m, p, usage), + month: live.month(u), + total: u?.total ?? [ 0, 0 ], + online: length(filter(devs, (d) => d.online)), + last_seen: 0, + devices: devs, + }; + for (let d in devs) + 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); + v.note = p.note; + v.services = p.services; + v.created = p.created; + } + return v; +}; + +export function states(m, usage) { + let out = {}; + for (let id, p in m.people) + out[id] = core.person_state(m, p, usage); + return out; +}; diff --git a/scripts/build-packages.sh b/scripts/build-packages.sh new file mode 100755 index 0000000..e757b49 --- /dev/null +++ b/scripts/build-packages.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Build the release packages with the OpenWrt SDK in Docker (as CI does): +# scripts/build-packages.sh [ipk|apk|all] +# Output: dist/luci-app-dawnline-.{ipk,apk} and dist/sha256sums.txt +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +APP="$ROOT/package/luci-app-dawnline" +VERSION="$(sed -n 's/^PKG_VERSION:=//p' "$APP/Makefile")" +OUT="$ROOT/dist" +WHAT="${1:-all}" +IPK_SDK="${IPK_SDK:-itdoginfo/openwrt-sdk-ipk:24.10.6}" +APK_SDK="${APK_SDK:-itdoginfo/openwrt-sdk-apk:25.12.3}" + +# One version everywhere: the Makefile, the ucode library and the web package. +grep -q "^export const VERSION = '$VERSION';" "$APP/root/usr/share/ucode/dawnline/util.uc" || { echo "util.uc VERSION != $VERSION" >&2; exit 1; } +grep -q "\"version\": \"$VERSION\"" "$ROOT/web/package.json" || { echo "web/package.json version != $VERSION" >&2; exit 1; } + +mkdir -p "$OUT" +build() { + local type="$1" sdk="$2" tag="dawnline-build:$1" + docker build --platform linux/amd64 -f "$ROOT/build/Dockerfile" --build-arg "SDK_IMAGE=$sdk" -t "$tag" "$ROOT" + local id + id="$(docker create "$tag")" + rm -rf "$OUT/.$type" && mkdir -p "$OUT/.$type" + docker cp "$id:/builder/out/." "$OUT/.$type/" + docker rm "$id" >/dev/null + local f + f="$(find "$OUT/.$type" -type f -name "*.$type" | head -n1)" + [ -n "$f" ] || { echo "no .$type built" >&2; exit 1; } + # ipk names use underscores (luci-app-dawnline_0.1.0-r1_all.ipk): one stable name for both. + mv "$f" "$OUT/luci-app-dawnline-$VERSION.$type" + rm -rf "$OUT/.$type" + echo "$OUT/luci-app-dawnline-$VERSION.$type" +} + +case "$WHAT" in +ipk) build ipk "$IPK_SDK" ;; +apk) build apk "$APK_SDK" ;; +all) build ipk "$IPK_SDK"; build apk "$APK_SDK" ;; +*) echo "usage: $0 [ipk|apk|all]" >&2; exit 2 ;; +esac + +( + cd "$OUT" + set -- luci-app-dawnline-"$VERSION".ipk luci-app-dawnline-"$VERSION".apk + files="" + for f in "$@"; do [ -f "$f" ] && files="$files $f"; done + # shellcheck disable=SC2086 + if command -v sha256sum >/dev/null; then sha256sum $files; else shasum -a 256 $files; fi > sha256sums.txt +) +cat "$OUT/sha256sums.txt" diff --git a/scripts/build-release.sh b/scripts/build-release.sh new file mode 100755 index 0000000..3d6c49f --- /dev/null +++ b/scripts/build-release.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Build the web bundles and pack luci-app-dawnline as a filesystem overlay +# tarball: dist/luci-app-dawnline-.tar.gz (paths relative to /). +# This is the asset the in-app updater and install.sh install. +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +APP="$ROOT/package/luci-app-dawnline" +VERSION="$(sed -n "s/^export const VERSION = '\(.*\)';/\1/p" "$APP/root/usr/share/ucode/dawnline/util.uc")" +OUT="$ROOT/dist" +STAGE="$(mktemp -d)" +trap 'rm -rf "$STAGE"' EXIT + +grep -q "PKG_VERSION:=$VERSION\$" "$APP/Makefile" || { echo "Makefile PKG_VERSION != $VERSION" >&2; exit 1; } +grep -q "\"version\": \"$VERSION\"" "$ROOT/web/package.json" || { echo "web/package.json version != $VERSION" >&2; exit 1; } + +[ "${SKIP_WEB:-0}" = 1 ] || (cd "$ROOT/web" && npm run --silent ci) + +mkdir -p "$STAGE/www" "$OUT" +cp -R "$APP/root/." "$STAGE/" +cp -R "$APP/htdocs/." "$STAGE/www/" +chmod 755 "$STAGE/usr/bin/dawnline" "$STAGE/usr/libexec/dawnline/agent" "$STAGE/usr/libexec/dawnline/updater" "$STAGE/usr/libexec/dawnline/resolver" \ + "$STAGE/etc/init.d/dawnline" "$STAGE/etc/uci-defaults/90_dawnline" "$STAGE/etc/hotplug.d/iface/95-dawnline" \ + "$STAGE/usr/share/dawnline/portal/www/cgi-bin/portal" +find "$STAGE" -name '.DS_Store' -delete + +TAR="$OUT/luci-app-dawnline-$VERSION.tar.gz" +# Files only (no directory entries) and root ownership: extracting into / +# must never touch the mode or owner of /usr, /www or /etc. +( cd "$STAGE" && find usr www etc -type f | LC_ALL=C sort > "$STAGE/.files" ) +COPYFILE_DISABLE=1 tar --format ustar --uid 0 --gid 0 --uname root --gname root \ + -czf "$TAR" -C "$STAGE" -T "$STAGE/.files" +( cd "$OUT" && shasum -a 256 "$(basename "$TAR")" > "$(basename "$TAR").sha256" ) +echo "$TAR" diff --git a/scripts/check-ucode.sh b/scripts/check-ucode.sh new file mode 100755 index 0000000..132838f --- /dev/null +++ b/scripts/check-ucode.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Compile-check every ucode file on a router without installing anything: +# the tree is unpacked under /tmp/dlc and modules are resolved from there. +# scripts/check-ucode.sh [root@host] +set -euo pipefail +HOST="${1:-root@outline.lan}" +ROOT="$(cd "$(dirname "$0")/.." && pwd)/package/luci-app-dawnline/root" +TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT + +# ucode resolves names at compile time: calling a function declared further +# down a file fails at runtime ("access to undeclared variable"). Catch it here. +python3 "$(dirname "$0")/lint-ucode.py" "$ROOT" +( cd "$ROOT" && COPYFILE_DISABLE=1 tar -czf "$TMP/t.tgz" usr etc ) +scp -q "$TMP/t.tgz" "$HOST:/tmp/dl-check.tgz" +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; } +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 + out=$(ucode -L '/tmp/dlc/usr/share/ucode/*.uc' -c -o /dev/null "$f" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; } +done +rm -rf /tmp/dlc +[ $rc = 0 ] && echo "all ucode files compile" +exit $rc +REMOTE diff --git a/scripts/deploy.sh b/scripts/deploy.sh new file mode 100755 index 0000000..7d2eff3 --- /dev/null +++ b/scripts/deploy.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Dev deploy: build the release tarball and install it on a router over SSH. +# scripts/deploy.sh [root@host] +# Backs up the configs Dawnline touches to /root/dawnline-predeploy-/ first. +set -euo pipefail + +HOST="${1:-root@outline.lan}" +TAR="$("$(dirname "$0")/build-release.sh" | tail -n1)" + +scp -q "$TAR" "$HOST:/tmp/luci-app-dawnline.tar.gz" +ssh "$HOST" sh <<'REMOTE' +set -e +ts="$(date +%Y%m%d-%H%M%S)" +mkdir -p "/root/dawnline-predeploy-$ts" +for c in network firewall dhcp dawnline; do + [ -f "/etc/config/$c" ] && cp "/etc/config/$c" "/root/dawnline-predeploy-$ts/$c" +done +# Keep only the five most recent pre-deploy backups. +ls -d /root/dawnline-predeploy-* 2>/dev/null | sort | head -n -5 | xargs -r rm -rf +tar -xozf /tmp/luci-app-dawnline.tar.gz -C / +rm -f /tmp/luci-app-dawnline.tar.gz +sh /etc/uci-defaults/90_dawnline && rm -f /etc/uci-defaults/90_dawnline +sleep 1 +ubus list luci.dawnline >/dev/null && echo "luci.dawnline registered (backup: /root/dawnline-predeploy-$ts)" +REMOTE diff --git a/scripts/frame-screenshots.py b/scripts/frame-screenshots.py new file mode 100755 index 0000000..9a160e9 --- /dev/null +++ b/scripts/frame-screenshots.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Put the README screenshots into a browser window on a dawn gradient. + +Raw captures live in docs/screenshots/raw/.png; the framed images are +written to docs/screenshots/.png. Needs a Chromium-based browser for the +headless render (BROWSER=/path/to/chrome, default: Brave or Chrome on macOS). +Run: scripts/frame-screenshots.py +""" +import os +import shutil +import struct +import subprocess +import sys +import tempfile + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) +RAW = os.path.join(ROOT, 'docs', 'screenshots', 'raw') +OUT = os.path.join(ROOT, 'docs', 'screenshots') + +# name -> what the address bar shows +SHOTS = { + 'overview': 'router.lan · Dawnline', + 'people': 'router.lan · Dawnline · People', + 'person': 'router.lan · Dawnline · Myata', + 'portal': 'vpn.example.com/kamiro-telosu-bavine', + 'map': 'router.lan · Dawnline · Overview', +} +PAD_X, PAD_Y, BAR = 120, 96, 40 + +CANDIDATES = [ + os.environ.get('BROWSER', ''), + '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser', + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + shutil.which('chromium') or '', + shutil.which('google-chrome') or '', +] + +TEMPLATE = """

+ +{url} +
""" + + +def png_size(path): + with open(path, 'rb') as f: + head = f.read(24) + return struct.unpack('>II', head[16:24]) + + +def main(): + browser = next((b for b in CANDIDATES if b and os.path.exists(b)), None) + if not browser: + sys.exit('No Chromium-based browser found; set BROWSER=/path/to/chrome') + tmp = tempfile.mkdtemp() + for name, url in SHOTS.items(): + src = os.path.join(RAW, f'{name}.png') + if not os.path.exists(src): + print(f'skip {name}: no raw capture') + continue + iw, ih = png_size(src) + w, h = iw + 2 * PAD_X, ih + BAR + 2 * PAD_Y + html = os.path.join(tmp, f'{name}.html') + with open(html, 'w', encoding='utf-8') as f: + f.write(TEMPLATE.format(w=w, h=h, iw=iw, ih=ih, bar=BAR, url=url, src=src, + gw=int(w * .8), gh=int(h * .5), gw2=int(w * .6), gh2=int(h * .45))) + out = os.path.join(OUT, f'{name}.png') + subprocess.run([browser, '--headless=new', '--disable-gpu', '--hide-scrollbars', '--allow-file-access-from-files', + '--force-device-scale-factor=1', f'--window-size={w},{h}', f'--screenshot={out}', f'file://{html}'], + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + print(f'{name}: {w}x{h}') + shutil.rmtree(tmp) + + +if __name__ == '__main__': + main() diff --git a/scripts/lint-ucode.py b/scripts/lint-ucode.py new file mode 100755 index 0000000..a1bbf09 --- /dev/null +++ b/scripts/lint-ucode.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Static checks for the ucode sources that need no router. + +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"). +Run: scripts/lint-ucode.py [package root] +""" +import glob +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", + 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", +] +bad = 0 +checked = 0 +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) + 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'(?=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.6.tgz", + "integrity": "sha512-FkO19Fowv/OQeJZPVfdetJaI3/VpbZmBsnmAlR/rQ+b3QwfiGQiOpVegpSRH331kelvHTVw9hXYG3DwjAaRzyQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.6.tgz", + "integrity": "sha512-si5/Etm6MphPc2xYHnk455Shls/hoMjTy3mhXge4OPmvCw7TwC4KP4fKokAlKLV4XaQvLvgSHfafPcblLMYYdQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.6.tgz", + "integrity": "sha512-PQCl3q7b0BgvVt72i2xrWM6I5KliwwVe4GpWW5QDGyUQawDS9aPZss/aGyFqBmxdRxlE8wDc9CaxiQ5DHRSp/Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.6.tgz", + "integrity": "sha512-l9DFl1Itb1YYdSrP1K3U8ih44AOHa/p+Q4WMMDfGvH5qVWp+ajfgS1DlYo4yCRh8wJ2ZJv0Fqccf+ULAmMFjmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.6.tgz", + "integrity": "sha512-bR4GR3205N9+od0+l5Dd9/iZTDpJkIe6d6Ydp2qbcQZJLmKBdYQQRp8gbWpbMt92twKJY66o1vK4NkoKQODIrA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.6.tgz", + "integrity": "sha512-XTVNaDzcFl2TeBglvxdGgsCv9JGtAGRAoJENmGBR/XvDH2mA2K0IXc2aMfP0dR8mexSXSKifJ85FixoXX1wfTw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.6.tgz", + "integrity": "sha512-qWc6qbc+25ugG9vqPR9P422KJBbVfZ05mjcMggoq8tsfWP+eRfC+/tiDdIlRF5VL2pDVZWN9zAhWsmu7R1+7Dw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.6.tgz", + "integrity": "sha512-V4Nwkp8844X/Xnww3PI1LYS0YPei8XQEVG70R+5MPZGO7AhYoun4hCN7Svs4U3wbQLZbwiz+9xRFhUZZdRl8Ww==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.6.tgz", + "integrity": "sha512-xb72A1aPaaIsp+a88VtRae/ovIEXislbUMyp7b9AQQU7ZkP2m/+ik6DW9TQcJyw5R8/RIailF9zExYwkjR++UA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.6.tgz", + "integrity": "sha512-pbcs1BVBwC43hZkjhjlF8Rx8m5G0KnhLZs9Azy/gqccP6UsNSzJr0hKGIAVPqzAH1O/NdPxxC9GVGb4msQg/aw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.6.tgz", + "integrity": "sha512-EKOC8os6Vsg487ZLKUqzLF99Jsmnq6tu7O7mAELakNpcA+8KadktFf/JYdRuHe/DzCUXmN38pUKu4XBcKlqGbQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.6.tgz", + "integrity": "sha512-v/SQ68GnSlr/HyjB79sNXesGDwkOPu9JjbHfmWaymCiM+nZsQ9TstG1KfA4MuEvTr2d3PoY8PhFxj9bt0e32JA==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.6.tgz", + "integrity": "sha512-G3pmliMQ7r15zFFNwBlaT/xTdSLi4lfgI7CUrQueyKYheNVhrd8JrWCE6Ll8xf4AA1RZFqq+mNJYntiElsVOyA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.6.tgz", + "integrity": "sha512-XQTB/IPoB/wG6x/wu9uomAt8YH61IAr5iZTubMiad/lu88sotq2ocz9hJd556+Jz2kIkF7ZQZIsUuWE3OWqtcA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.6.tgz", + "integrity": "sha512-O5mpokth6+ydMuwiGtY8fIjvOBfH7u6SzmDNmZ3k6GK5C6iEAC2q2ZN/T5L9jYILx0IcCT0KnfMDihQ5yQFSBw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.6.tgz", + "integrity": "sha512-aIFxbAD9v3TvIaEDsKmukjcDg1JS4/tFXw8SHyQQgzOwzWCQ4cyDK7Ju1pQKqUXDFkEu/BZCFDCDATsKhQcB/Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.6.tgz", + "integrity": "sha512-fuNo1UwBc6BxnHDOxxguQL/InhheMN3RJcJMb0b4xP8r5Q3CNCrJbVg0eCIFuJ4e/zAfjR2gYbOfbzO/G7CIyw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.6.tgz", + "integrity": "sha512-05v6wFKDKJPZs9xlytVrrRu6IbRuoSvlH9xNwEOafXsKyjBFZPvAcZz2VIAB/M+lblYeKa9iOYC4RDVdfcAAaw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.6.tgz", + "integrity": "sha512-wJXKcdMjvkc/FaavZXNP1yW4i0pfOmhZAIWRSLG2yJ0PB0TWi7dkLErhX0u0vptDcXKKO/m1Y/YTeuyvb2MXwg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.6.tgz", + "integrity": "sha512-cwg7/h0ThvJwy8CBkmACdiHAxRWpbsCmIsjOt+Zzx0hTnIcSUmKYEV03bGg+hD827OnwUsbKh1ZZDW754xWyBA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.6.tgz", + "integrity": "sha512-T0RkYIJbdYXJEQFw+tMBO09KDFdgmNxkHsof3wWAABrvnx15Yh8RytmrgYy9+q9cBeBNZF66MMQZC+5nzEz6vg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.6.tgz", + "integrity": "sha512-KlfpmF1AAIdAWxt8QQNClbpLFlAUfYOzqIuJ7IXEStMHpFRuH78RG6FjqPb3Rqhh0K89F5npvG+/i3Fjl6IveQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.6.tgz", + "integrity": "sha512-MrTLjd7Jlt9/ZavJZYG61KQv9Iy9bzbY+yXy73Xvwoa2uP66wvDShkyBr5Chz/yrE6lbD/zHMuTmKQVNQqBApg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.6.tgz", + "integrity": "sha512-8fWDH1CkPI8GdBKAxzHDza7UmgficsKo2+MVbvUgOGhB0629w5sHMg3Qu5y7TZsrYKHHWpz8fla4KvoT7WsO3Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.6.tgz", + "integrity": "sha512-9/c9PWdr5GCIHkkxiHM1HjNBQMVdftP4O8QTcoUAaRza2FSqJ4axbf8QAnBuE6BIGQDl71SaRPeDdDYid5ecTw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vitest/expect": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.4.tgz", + "integrity": "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.4.tgz", + "integrity": "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.4", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz", + "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.4.tgz", + "integrity": "sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.4", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.4.tgz", + "integrity": "sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.4", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot/node_modules/@vitest/pretty-format": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.4.tgz", + "integrity": "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.4.tgz", + "integrity": "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.4.tgz", + "integrity": "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.4", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils/node_modules/@vitest/pretty-format": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.4.tgz", + "integrity": "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true, + "license": "MIT" + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/bundle-require": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz", + "integrity": "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "load-tsconfig": "^0.2.3" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "peerDependencies": { + "esbuild": ">=0.18" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/consola": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fix-dts-default-cjs-exports": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz", + "integrity": "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "magic-string": "^0.30.17", + "mlly": "^1.7.4", + "rollup": "^4.34.8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/joycon": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", + "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/load-tsconfig": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/load-tsconfig/-/load-tsconfig-0.2.5.tgz", + "integrity": "sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/lodash.sortby": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz", + "integrity": "sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA==", + "dev": true, + "license": "MIT" + }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/mlly": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz", + "integrity": "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.16.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.3" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pirates": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/postcss": { + "version": "8.5.30", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz", + "integrity": "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-load-config": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz", + "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.1.1" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "jiti": ">=1.21.0", + "postcss": ">=8.0.9", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + }, + "postcss": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/prettier": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", + "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/qrcode-generator": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-1.4.4.tgz", + "integrity": "sha512-HM7yY8O2ilqhmULxGMpcHSF1EhJJ9yBj8gvDEuZ6M+KGJ0YY2hKpnXvRD+hZPLrDVck3ExIGhmPtSdcjC+guuw==", + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/rollup": { + "version": "4.64.6", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.6.tgz", + "integrity": "sha512-fX1Vy+UNKdXn+xKDnu/HBXbHVr1AY8cSdQj9BU4kLv5aFCMqGpvrVbyUMmjN3DdzWhSAuTbcX8PCNEVaumthYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.64.6", + "@rollup/rollup-android-arm64": "4.64.6", + "@rollup/rollup-darwin-arm64": "4.64.6", + "@rollup/rollup-darwin-x64": "4.64.6", + "@rollup/rollup-freebsd-arm64": "4.64.6", + "@rollup/rollup-freebsd-x64": "4.64.6", + "@rollup/rollup-linux-arm-gnueabihf": "4.64.6", + "@rollup/rollup-linux-arm-musleabihf": "4.64.6", + "@rollup/rollup-linux-arm64-gnu": "4.64.6", + "@rollup/rollup-linux-arm64-musl": "4.64.6", + "@rollup/rollup-linux-loong64-gnu": "4.64.6", + "@rollup/rollup-linux-loong64-musl": "4.64.6", + "@rollup/rollup-linux-ppc64-gnu": "4.64.6", + "@rollup/rollup-linux-ppc64-musl": "4.64.6", + "@rollup/rollup-linux-riscv64-gnu": "4.64.6", + "@rollup/rollup-linux-riscv64-musl": "4.64.6", + "@rollup/rollup-linux-s390x-gnu": "4.64.6", + "@rollup/rollup-linux-x64-gnu": "4.64.6", + "@rollup/rollup-linux-x64-musl": "4.64.6", + "@rollup/rollup-openbsd-x64": "4.64.6", + "@rollup/rollup-openharmony-arm64": "4.64.6", + "@rollup/rollup-win32-arm64-msvc": "4.64.6", + "@rollup/rollup-win32-ia32-msvc": "4.64.6", + "@rollup/rollup-win32-x64-gnu": "4.64.6", + "@rollup/rollup-win32-x64-msvc": "4.64.6", + "fsevents": "~2.3.2" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map": { + "version": "0.8.0-beta.0", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.8.0-beta.0.tgz", + "integrity": "sha512-2ymg6oRBpebeZi9UUNsgQ89bhx01TcTkmNTGnNO88imTmbSgy4nfujrgVEFKWpMTEGA11EDkTt7mqObTPdigIA==", + "deprecated": "The work that was done in this beta branch won't be included in future versions", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "whatwg-url": "^7.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/sucrase": { + "version": "3.35.1", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", + "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.6.tgz", + "integrity": "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tr46": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-1.0.1.tgz", + "integrity": "sha512-dTpowEjclQ7Kgx5SdBkqRzVhERQXov8/l9Ft9dVM9fmg0W0KQSVaXX9T4i6twCPNtYiZM53lpSSUAwJbFPOHxA==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "license": "MIT", + "bin": { + "tree-kill": "cli.js" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/tsup": { + "version": "8.5.0", + "resolved": "https://registry.npmjs.org/tsup/-/tsup-8.5.0.tgz", + "integrity": "sha512-VmBp77lWNQq6PfuMqCHD3xWl22vEoWsKajkF8t+yMBawlUS8JzEI+vOVMeuNZIuMML8qXRizFKi9oD5glKQVcQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "bundle-require": "^5.1.0", + "cac": "^6.7.14", + "chokidar": "^4.0.3", + "consola": "^3.4.0", + "debug": "^4.4.0", + "esbuild": "^0.25.0", + "fix-dts-default-cjs-exports": "^1.0.0", + "joycon": "^3.1.1", + "picocolors": "^1.1.1", + "postcss-load-config": "^6.0.1", + "resolve-from": "^5.0.0", + "rollup": "^4.34.8", + "source-map": "0.8.0-beta.0", + "sucrase": "^3.35.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.11", + "tree-kill": "^1.2.2" + }, + "bin": { + "tsup": "dist/cli-default.js", + "tsup-node": "dist/cli-node.js" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@microsoft/api-extractor": "^7.36.0", + "@swc/core": "^1", + "postcss": "^8.4.12", + "typescript": ">=4.5.0" + }, + "peerDependenciesMeta": { + "@microsoft/api-extractor": { + "optional": true + }, + "@swc/core": { + "optional": true + }, + "postcss": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/ufo": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", + "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "7.3.7", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.7.tgz", + "integrity": "sha512-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.27.0 || ^0.28.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vite/node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/vitest": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz", + "integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.4", + "@vitest/mocker": "3.2.4", + "@vitest/pretty-format": "^3.2.4", + "@vitest/runner": "3.2.4", + "@vitest/snapshot": "3.2.4", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.4", + "@vitest/ui": "3.2.4", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/webidl-conversions": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz", + "integrity": "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-7.1.0.tgz", + "integrity": "sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "lodash.sortby": "^4.7.0", + "tr46": "^1.0.1", + "webidl-conversions": "^4.0.2" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + } + } +} diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..0660de2 --- /dev/null +++ b/web/package.json @@ -0,0 +1,25 @@ +{ + "name": "dawnline-web", + "version": "0.1.0", + "private": true, + "license": "MIT", + "type": "module", + "scripts": { + "build": "tsc --noEmit && tsup", + "dev": "tsup --watch", + "typecheck": "tsc --noEmit", + "test": "vitest run", + "format": "prettier --write .", + "format:check": "prettier --check .", + "ci": "npm run format:check && npm run typecheck && npm run test && npm run build" + }, + "dependencies": { + "qrcode-generator": "1.4.4" + }, + "devDependencies": { + "prettier": "3.6.2", + "tsup": "8.5.0", + "typescript": "5.9.3", + "vitest": "3.2.4" + } +} diff --git a/web/src/admin/api.ts b/web/src/admin/api.ts new file mode 100644 index 0000000..5684f3a --- /dev/null +++ b/web/src/admin/api.ts @@ -0,0 +1,344 @@ +// luci.dawnline RPC bindings. The backend reports failures as { error }. + +import type { AwgCaps, ClientConfig, DayUsage, HealthCheck, LogEvent, Person, Status } from '../shared/types'; + +function call(method: string, params: string[] = []) { + const fn = rpc.declare({ object: 'luci.dawnline', method, params }); + return async (...args: unknown[]): Promise => { + const r = await fn(...args); + if (r && typeof r === 'object' && typeof r.error === 'string') throw new Error(r.error); + return r as T; + }; +} + +export interface SetupDefaults { + id: string; + name: string; + ifname: string; + port: number; + subnet: string; + endpoint: string; + mtu: number; + zones: string[]; + lan_zone: string; + wan_zone: string; + portal_port: number; + taken: string[]; + awg: AwgCaps; +} + +export interface Backup { + name: string; + created: number; + size: number; + reason: string; +} + +export type AwgSource = 'slava' | 'grey'; + +export interface UpdateComponent { + installed?: string | null; + latest?: string | null; + update?: boolean; + note?: string; + error?: string; + repo?: string; + tag?: string; + packages?: Record; + // AmneziaWG: the installed build and both builds for this firmware + current?: AwgSource | null; + gen?: '2.0' | '3.1' | null; + ru?: boolean; + release?: string; + sources?: Partial< + Record< + AwgSource, + { + label: string; + repo: string; + tag: string; + version: string | null; + gen: '2.0' | '3.1' | null; + date: string | null; + newer?: { tag: string; gen: '3.1' }; + } + > + >; + // OpenWrt packages Dawnline uses + pkgs?: Record; + updates?: number; +} + +export interface UpdatesStatus { + version: string; + firmware?: { version: string; target: string; arch: string }; + /** The personal portal is on: its HTTPS packages are listed too. */ + portal?: boolean; + /** A server uses the home-like link. */ + 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; +} + +/** Missing packages by feature: the portal's HTTPS, ACME certificates, the home-like link. */ +export interface Needs { + https: string[]; + acme: string[]; + home: string[]; +} + +export interface SettingsData { + settings: Record; + needs?: Needs; + effective: Record; + services: { id: string; name: string; address: string; ports: string[] }[]; + cert: { path: string; self_signed: boolean; expires: string | null } | null; + 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; +} + +export type LogCategory = 'connections' | 'devices' | 'people' | 'problems'; + +export interface LogsInfo { + policy: { + keep_days: number; + max: number; + categories: LogCategory[]; + persist: '10min' | 'hourly' | 'off'; + usage_days: number; + usage_months: number; + }; + events: number; + oldest: number; + by_category: Record; + log_ram: number; + log_flash: number; + usage_flash: number; + usage_since: string; + usage_days: number; + geo_flash: number; +} + +/** The path that makes tunnel clients' internet traffic enter from the LAN. */ +export interface LikeHome { + active: boolean; + dev?: string; + address?: string; + dns?: string; + gateway?: string; + bridged?: boolean; + off?: boolean; + error?: string; +} + +export type IfaceCategory = 'wan' | 'ethernet' | 'wifi' | 'vpn' | 'other'; + +export interface NetDevice { + name: string; + category: IfaceCategory; + kind: 'bridge' | IfaceCategory; + up: boolean; + master: string | null; + members: string[]; + nets: string[]; + addrs: string[]; + logical: string | null; + proto: string | null; + zone: string | null; + /** The server's own tunnel interface. */ + own?: boolean; + /** Part of the server's home network (auto = via Auto-detect LAN). */ + home?: boolean; + auto?: boolean; + /** Saved but not present right now. */ + missing?: boolean; +} + +export interface InterfacesData { + server: string; + /** Packages the home-like link still needs. */ + needs?: string[]; + ifname: string; + detected: { wan: string | null; lan: string | null }; + saved: { wan: string; lan: string }; + config: { auto_wan: boolean; wan_device: string; auto_lan: boolean; lan_devices: string[]; lan_like: boolean }; + like_home: LikeHome; + effective: { + wan: { dev: string | null; zone: string; auto: boolean; missing: boolean }; + home: { dev: string; auto: boolean; nets: string[]; zone: string | null; missing: boolean }[]; + nets: string[]; + zones: string[]; + }; + zones: string[]; + devices: NetDevice[]; + /** People on this server with Home-only access (their AllowedIPs follow the home networks). */ + lan_only: number; + nets_changed?: boolean; +} + +/** Filters for logs_clear; all empty clears the whole log. */ +export interface LogFilter { + person?: string; + device?: string; + category?: string; + older_days?: string; +} + +const logsClearRaw = call<{ removed: number }>('logs_clear', ['person', 'device', 'category', 'older_days']); +const logsClear = (f: LogFilter = {}) => logsClearRaw(f.person ?? '', f.device ?? '', f.category ?? '', f.older_days ?? ''); + +/** Fields for person_update; send strings ('' clears an optional value). */ +export type PersonPatch = Partial< + Record< + | 'name' + | 'access' + | 'device_limit' + | 'expires' + | 'expire_action' + | 'expire_warn' + | 'quota_gb' + | 'quota_period' + | 'bonus_gb' + | 'hours' + | 'note' + | 'dns_mode', + string + > +> & { paused?: boolean; services?: string[] }; + +const personUpdateRaw = 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', + ], +}); + +async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: Person }> { + const keys = [ + 'name', + 'access', + 'device_limit', + 'expires', + 'expire_action', + 'expire_warn', + 'quota_gb', + 'quota_period', + 'bonus_gb', + 'hours', + 'note', + 'dns_mode', + ] as const; + const args: unknown[] = [id, ...keys.map((k) => patch[k]), patch.paused, patch.services]; + const r = await personUpdateRaw(...args); + if (r && typeof r.error === 'string') throw new Error(r.error); + 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; +} + +export const api = { + personUpdate, + settingsGet: call('settings_get'), + settingsUpdate: call('settings_update', ['values']), + serviceSet: call<{ id: string }>('service_set', ['id', 'name', 'address', 'ports']), + serviceDelete: call('service_delete', ['id']), + geoClear: call('geo_clear'), + events: call<{ events: LogEvent[]; total: number; policy: LogsInfo['policy'] }>('events', ['limit']), + logsClear, + interfaces: call('interfaces', ['id']), + serverInterfaces: call('server_interfaces', ['id', 'auto_wan', 'wan_device', 'auto_lan', 'lan_devices', 'lan_like']), + usageClear: call('usage_clear', ['scope', 'id']), + uninstall: call('uninstall', ['confirm']), + status, + setupDefaults: call('setup_defaults'), + serverCreate: call<{ id: string }>('server_create', [ + 'id', + 'name', + 'ifname', + 'port', + 'subnet', + 'endpoint', + 'mtu', + 'preset', + 'lan_zone', + 'wan_zone', + 'lan_like', + 'portal_enabled', + 'portal_port', + ]), + serverObfuscation: call('server_obfuscation', ['id', 'preset']), + serverUpdate: call('server_update', ['id', 'values']), + serverDelete: call('server_delete', ['id']), + personCreate: call<{ id: string; link: string | null }>('person_create', [ + 'name', + 'slug', + 'server', + 'access', + 'device_limit', + 'expires', + 'quota_gb', + 'quota_period', + ]), + personPause: call('person_pause', ['id', 'paused']), + personRegen: call<{ link: string | null }>('person_regen', ['id']), + personDelete: call('person_delete', ['id']), + personUsage: call<{ person: DayUsage[]; devices: Record }>('person_usage', ['id', 'days']), + pauseAll: call('pause_all', ['paused']), + deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']), + deviceConfig: call('device_config', ['id']), + deviceUpdate: call('device_update', ['id', 'name', 'disabled']), + deviceDelete: call('device_delete', ['id']), + deviceRotate: call('device_rotate', ['id']), + apply: call('apply'), + health: call<{ checks: HealthCheck[] }>('health'), + healthFix: call<{ checks: HealthCheck[] }>('health_fix', ['id']), + backupList: call<{ backups: Backup[] }>('backup_list'), + backupCreate: call<{ name: string }>('backup_create'), + backupRestore: call('backup_restore', ['name']), + backupDelete: call('backup_delete', ['name']), + backupRead: call<{ data: string }>('backup_read', ['name']), + backupUpload: call('backup_upload', ['data']), + exportJson: call>('export'), + importJson: call('import', ['data']), + updatesStatus: call('updates_status'), + updatesRun: call<{ started: boolean }>('updates_run', ['what']), +}; diff --git a/web/src/admin/backups.ts b/web/src/admin/backups.ts new file mode 100644 index 0000000..91be402 --- /dev/null +++ b/web/src/admin/backups.ts @@ -0,0 +1,171 @@ +// Backups: a section of the Settings page. The three newest are rows, the +// rest fold away; moving to another router lives in the footer. + +import { E } from './e'; +import { api, type Backup } from './api'; +import { attempt, button, confirmDialog, downloadFile, dropdown, iconButton, notify, pickFile } from './ui'; +import { icon } from '../shared/icons'; +import { bytes } from '../shared/format'; + +const REASON: Record = { + manual: 'Manual', + auto: 'Nightly', + 'pre-restore': 'Before restore', + 'pre-import': 'Before import', + 'pre-delete': 'Before removing a server', + 'pre-update': 'Before update', +}; +const SHOWN = 3; + +/** "Today, 03:00", "Yesterday, 03:00" or "12 Oct, 03:00". */ +function when(ts: number): string { + const d = new Date(ts * 1000); + const t = d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }); + const days = Math.round((new Date(new Date().toDateString()).getTime() - new Date(d.toDateString()).getTime()) / 86400000); + return `${days === 0 ? 'Today' : days === 1 ? 'Yesterday' : d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })}, ${t}`; +} + +async function download(b: Backup) { + const r = await attempt(() => api.backupRead(b.name)); + if (!r) return; + const bin = atob(r.data); + const arr = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i); + const g = globalThis as unknown as { Blob: typeof Blob }; + downloadFile(b.name, new g.Blob([arr], { type: 'application/gzip' })); +} + +function backupRow(b: Backup, done: () => void): HTMLElement { + return E('div', { class: 'dl-row dl-bk-row' }, [ + E('span', { class: 'dl-group-ic' }, icon('archive')), + E('span', { class: 'dl-row-main dl-stack' }, [ + E('b', {}, when(b.created)), + E('span', { class: 'dl-sub' }, `${REASON[b.reason] ?? b.reason} · ${bytes(b.size)}`), + ]), + E('span', { class: 'dl-pcard-actions' }, [ + iconButton('download', 'Download', () => download(b), 'neutral', 'dl-icon-only'), + iconButton( + 'more', + 'More', + (ev: MouseEvent) => + dropdown(ev.currentTarget as HTMLElement, [ + { + label: 'Restore', + icon: icon('reset'), + run: async () => { + const ok = await confirmDialog( + 'Restore this backup?', + `Everything returns to ${when(b.created)}. The current state is backed up first.`, + 'Restore', + true, + ); + if (ok && (await attempt(() => api.backupRestore(b.name), 'Restored'))) done(); + }, + }, + { + label: 'Delete', + icon: icon('trash'), + danger: true, + run: async () => { + if ( + !(await confirmDialog( + 'Delete this backup?', + `The backup from ${when(b.created)} is removed from the router.`, + 'Delete', + true, + )) + ) + return; + if (await attempt(() => api.backupDelete(b.name), 'Backup deleted')) done(); + }, + }, + ]), + 'neutral', + 'dl-icon-only', + ), + ]), + ]); +} + +/** The Backups section; `done` reloads the list (and the page data after a restore). */ +export function backupsSection(list: Backup[], done: () => void): HTMLElement { + const rows = list.slice(0, SHOWN).map((b) => backupRow(b, done)); + const older = list.slice(SHOWN); + const body = list.length + ? E('div', { class: 'dl-list' }, [ + ...rows, + older.length + ? E('details', { class: 'dl-bk-older' }, [ + E('summary', {}, [icon('chevron'), `${older.length} older backup${older.length === 1 ? '' : 's'}`]), + ...older.map((b) => backupRow(b, done)), + ]) + : '', + ]) + : E('div', { class: 'dl-list' }, [E('div', { class: 'dl-row dl-muted' }, 'No backups yet.')]); + + const restoreFile = button('Restore from file', async () => { + const f = await pickFile('.tar.gz,.tgz,application/gzip', 'base64'); + if (!f) return; + const ok = await confirmDialog( + 'Restore from file?', + `Replace the current Dawnline configuration with ${f.name}? The current state is backed up first.`, + 'Restore', + true, + ); + if (ok && (await attempt(() => api.backupUpload(f.data), 'Restored'))) done(); + }); + const exportJson = button('Export JSON', async () => { + const r = await attempt(() => api.exportJson()); + if (r) downloadFile(`dawnline-export-${new Date().toISOString().slice(0, 10)}.json`, JSON.stringify(r, null, 2), 'application/json'); + }); + const importJson = button('Import JSON', async () => { + const f = await pickFile('.json,application/json', 'text'); + if (!f) return; + let data: unknown; + try { + data = JSON.parse(f.data); + } catch { + notify('Not a JSON file.', 'error'); + return; + } + const ok = await confirmDialog( + 'Import?', + 'This replaces the whole Dawnline configuration on this router. The current state is backed up first.', + 'Import', + true, + ); + if (ok && (await attempt(() => api.importJson(data), 'Imported'))) done(); + }); + + 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' }), + button( + [icon('plus'), ' Back up now'], + async () => { + if (await attempt(() => api.backupCreate(), 'Backup created')) done(); + }, + 'positive', + ), + ]), + body, + ]), + 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' }, [restoreFile, exportJson, importJson]), + ]), + ]); +} diff --git a/web/src/admin/charts.ts b/web/src/admin/charts.ts new file mode 100644 index 0000000..7166000 --- /dev/null +++ b/web/src/admin/charts.ts @@ -0,0 +1,96 @@ +// 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/device.ts b/web/src/admin/device.ts new file mode 100644 index 0000000..48a311a --- /dev/null +++ b/web/src/admin/device.ts @@ -0,0 +1,532 @@ +// Device drawer: a right-hand panel with the device's status, connection +// (QR / key / file), details and actions. Replaces the old tabbed modal. + +import type { ClientConfig, Device, Geo, Kind, LogEvent, Person } from '../shared/types'; +import { E } from './e'; +import { api } from './api'; +import { attempt, button, closeModal, confirmDialog, copyText, downloadFile, modal, notify, svg } from './ui'; +import { qrSvg } from '../shared/qr'; +import { vpnKey } from '../shared/vpnkey'; +import { ago, bytes, KIND_LABEL, KINDS } from '../shared/format'; +import { icon } from '../shared/icons'; +import { spark } from './charts'; +import { clearLogDialog, exportEvents, resetUsageDialog } from './logs'; + +let current: { close: () => void } | null = null; + +function iso(ts: number): string { + return ts + ? new Date(ts * 1000).toLocaleString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' }) + : '—'; +} + +function copyRow(label: string, value: string, mono = true): HTMLElement { + return E('div', { class: 'dl-kvrow' }, [ + E('span', { class: 'dl-kvrow-k' }, label), + E( + 'button', + { type: 'button', class: `dl-kvrow-v copy${mono ? ' dl-mono' : ''}`, title: 'Copy', click: () => copyText(value, `${label} copied`) }, + [E('span', {}, value), icon('copy')], + ), + ]); +} + +function row(label: string, value: Node | string): HTMLElement { + return E('div', { class: 'dl-kvrow' }, [E('span', { class: 'dl-kvrow-k' }, label), E('span', { class: 'dl-kvrow-v' }, value)]); +} + +/** 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: ClientConfig): 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, + ]), + ]); +} + +/** QR / key / file switcher for a client configuration. */ +export async function connectBlock(cfg: ClientConfig): 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 [ + ['qr', 'QR code'], + ['key', 'Key'], + ['file', 'File'], + ]) + seg.appendChild(E('button', { type: 'button', 'data-id': id, click: () => show(id) }, label)); + show('qr'); + return E('div', { class: 'dl-stack gap12' }, [seg, body]); +} + +function drawer(title: Node, body: Node, foot: Node | null, onClose: () => void): { close: () => void; panel: HTMLElement } { + current?.close(); + const panel = E('aside', { class: 'dl-drawer', role: 'dialog', 'aria-modal': 'true' }, [ + E('div', { class: 'dl-drawer-head' }, [ + title, + E('button', { type: 'button', class: 'dl-drawer-x', 'aria-label': 'Close', click: () => close() }, icon('x')), + ]), + E('div', { class: 'dl-drawer-body' }, body), + foot ? E('div', { class: 'dl-drawer-foot' }, foot) : '', + ]); + const overlay = E( + 'div', + { + class: 'dl-drawer-overlay dl-root', + click: (ev: Event) => { + if (ev.target === overlay) close(); + }, + }, + panel, + ); + const onKey = (ev: KeyboardEvent) => { + // LuCI keeps an empty .modal in the page; the body class says whether one is open. + if (ev.key === 'Escape' && !document.body.classList.contains('modal-overlay-active')) close(); + }; + function close() { + document.removeEventListener('keydown', onKey); + overlay.classList.remove('open'); + setTimeout(() => overlay.remove(), 220); + if (current === handle) current = null; + onClose(); + } + const handle = { close, panel }; + document.addEventListener('keydown', onKey); + document.body.appendChild(overlay); + requestAnimationFrame(() => overlay.classList.add('open')); + current = handle; + return handle; +} + +const DEV_EVENT: Record = { + connect: ['ok', 'Connected'], + disconnect: ['', 'Went offline'], + roam: ['', 'Changed network'], + device_added: ['accent', 'Added'], + device_removed: ['', 'Removed'], +}; + +/** Activity of one device, newest first. */ +function deviceEvents(events: LogEvent[], id: string): HTMLElement { + const mine = events + .filter((e) => e.device === id && DEV_EVENT[e.type]) + .reverse() + .slice(0, 12); + if (!mine.length) return E('div', { class: 'dl-sub' }, 'No activity yet.'); + return E( + 'div', + { class: 'dl-dev-log' }, + mine.map((e) => { + const [tone, label] = DEV_EVENT[e.type]; + const extra = + e.type === 'connect' + ? [ + e.detail ? E('span', { class: 'dl-mono' }, ` ${e.detail}`) : '', + e.where ? E('span', { class: 'dl-faint' }, ` · ${e.where}`) : '', + ] + : e.type === 'roam' + ? [E('span', { class: 'dl-mono dl-faint' }, ` ${e.detail ?? ''}`)] + : e.type === 'device_added' + ? [E('span', { class: 'dl-faint' }, (e.detail ?? '').includes('(portal)') ? ' from the portal' : ' by you')] + : []; + const t = new Date(e.ts * 1000); + return E('div', { class: 'dl-dev-log-row' }, [ + E('span', { class: `dl-ev-dot ${tone}` }), + E('span', { class: 'dl-row-main' }, [E('span', {}, label), ...extra]), + E('span', { class: 'dl-faint dl-nowrap', title: t.toLocaleString() }, ago(e.ts)), + ]); + }), + ); +} + +function statusLine(d: Device): HTMLElement { + if (d.disabled) return E('span', { class: 'dl-dstat' }, [E('i', { class: 'dot' }), 'Disabled']); + if (d.online) return E('span', { class: 'dl-dstat ok' }, [E('i', { class: 'dot ok' }), `Online from ${d.endpoint}`]); + if (!d.handshake) return E('span', { class: 'dl-dstat warn' }, [E('i', { class: 'dot warn' }), 'Waiting for the first connection']); + return E('span', { class: 'dl-dstat' }, [E('i', { class: 'dot' }), `Last seen ${ago(d.handshake)}`]); +} + +/** Device drawer; `refresh` reloads the page after changes. */ +export async function openDevice(person: Person, dev: Device, refresh: () => unknown, geo?: Geo) { + const cfg = await attempt(() => api.deviceConfig(dev.id)); + if (!cfg) return; + let d = dev; + let p = person; + const connect = await connectBlock(cfg); + const titleEl = E('div', { class: 'dl-drawer-title' }); + const stats = E('div', {}); + const details = E('div', {}); + const live = E('div', { class: 'dl-live' }); + const log = E('div', {}, E('div', { class: 'dl-sub' }, 'Loading…')); + let logEvents: LogEvent[] = []; + const loadLog = async () => { + const ev = await api.events(5000).catch(() => null); + if (!ev) return; + logEvents = ev.events.filter((e) => e.device === d.id); + dom.content(log, deviceEvents(ev.events, d.id)); + }; + + const paint = () => { + const place = geo?.points.find((x) => x.device === d.id && x.ip === d.endpoint); + dom.content(titleEl, [ + E('span', { class: `dl-dcard-ic${d.online ? ' on' : ''}` }, icon(d.kind)), + E('div', { class: 'dl-stack' }, [ + E('div', { class: 'dl-title-row' }, [ + E('h3', {}, d.name), + button([icon('edit')], () => rename(), 'neutral', { title: 'Rename', class: 'cbi-button cbi-button-neutral dl-icon-only sm' }), + ]), + E('span', { class: 'dl-sub' }, [`${p.name} · ${KIND_LABEL[d.kind]}`]), + ]), + ]); + const week = d.spark.reduce((a, b) => a + b, 0); + dom.content( + stats, + E('div', { class: 'dl-dstats' }, [ + E('div', { class: 'dl-dstats-cell wide' }, [E('span', { class: 'dl-metric-label' }, 'Status'), statusLine(d)]), + E('div', { class: 'dl-dstats-cell' }, [ + E('span', { class: 'dl-metric-label' }, 'This month'), + E('b', {}, bytes(d.month[0] + d.month[1])), + E('span', { class: 'dl-sub dl-mono' }, `↓ ${bytes(d.month[1])} ↑ ${bytes(d.month[0])}`), + ]), + E('div', { class: 'dl-dstats-cell' }, [ + E('span', { class: 'dl-metric-label' }, 'Last 7 days'), + E('b', {}, bytes(week)), + spark(d.spark, 120, 22), + ]), + ]), + ); + dom.content( + details, + E('div', { class: 'dl-kv2' }, [ + copyRow('Tunnel address', d.address), + d.hostname && p.access !== 'internet' ? copyRow('Local address', d.hostname) : '', + d.endpoint + ? row( + 'Client IP', + E('span', {}, [ + E('span', { class: 'dl-mono' }, d.endpoint), + place ? E('span', { class: 'dl-faint' }, ` · ${[place.city, place.org].filter(Boolean).join(' · ')}`) : '', + ]), + ) + : '', + row( + 'Total', + E('span', { class: 'dl-kv-act' }, [ + `↓ ${bytes(d.total[1])} · ↑ ${bytes(d.total[0])}`, + E( + 'button', + { + type: 'button', + class: 'dl-linkbtn danger', + click: () => resetUsageDialog('device', d.id, d.name, () => setTimeout(reload, 300)), + }, + 'Reset', + ), + ]), + ), + row('Added', `${iso(d.created)} · ${d.created_by === 'portal' ? 'from the portal' : 'by you'}`), + row( + 'Public key', + E('span', { class: 'dl-mono dl-faint' }, cfg.amnezia.client_pub_key ? `${cfg.amnezia.client_pub_key.slice(0, 16)}…` : '—'), + ), + ]), + ); + dom.content( + live, + d.online + ? [E('i', { class: 'dot ok' }), E('span', { class: 'dl-ok' }, 'Connected')] + : d.handshake + ? [E('i', { class: 'dot' }), E('span', { class: 'dl-muted' }, `Last connected ${ago(d.handshake)}`)] + : [E('i', { class: 'dot warn pulse' }), E('span', { class: 'dl-muted' }, 'Waiting for the first connection…')], + ); + dom.content(foot, [ + button( + [icon(d.disabled ? 'play' : 'pause'), d.disabled ? ' Enable' : ' Disable'], + async () => { + if (await attempt(() => api.deviceUpdate(d.id, undefined, !d.disabled), d.disabled ? 'Device enabled' : 'Device disabled')) + await reload(); + }, + 'neutral', + d.disabled ? {} : { class: 'cbi-button cbi-button-neutral dl-btn-warn' }, + ), + button([icon('key'), ' New keys'], async () => { + if ( + !(await confirmDialog( + 'Generate new keys?', + 'The current configuration on this device stops working until it is imported again.', + 'Generate', + true, + )) + ) + return; + const c = await attempt(() => api.deviceRotate(d.id), 'New keys generated'); + if (c) { + refresh(); + handle.close(); + const st = await api.status(1); + const p2 = st.people.find((x) => x.id === p.id); + const d2 = p2?.devices.find((x) => x.id === d.id); + if (p2 && d2) openDevice(p2, d2, refresh, st.geo); + } + }), + E('span', { class: 'dl-spacer' }), + button( + [icon('trash'), ' Remove'], + async () => { + if ( + !(await confirmDialog( + `Remove ${d.name}?`, + 'The device is disconnected immediately and its configuration stops working.', + 'Remove', + true, + )) + ) + return; + if (await attempt(() => api.deviceDelete(d.id), 'Device removed')) { + handle.close(); + refresh(); + } + }, + 'negative', + ), + ]); + }; + + const reload = async () => { + const st = await api.status(1).catch(() => null); + const p2 = st?.people.find((x) => x.id === p.id); + const d2 = p2?.devices.find((x) => x.id === d.id); + if (!st || !p2 || !d2) return; + p = p2; + d = d2; + geo = st.geo; + paint(); + refresh(); + }; + + const rename = () => { + const input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name, maxlength: 48 }) as HTMLInputElement; + modal( + `Rename ${d.name}`, + [E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, 'Name'), E('div', { class: 'cbi-value-field' }, input)])], + [ + E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + ' ', + button( + 'Save', + async () => { + if (await attempt(() => api.deviceUpdate(d.id, input.value, undefined), 'Renamed')) { + closeModal(); + await reload(); + } + }, + 'positive', + ), + ], + ); + setTimeout(() => input.select(), 50); + }; + + const foot = E('div', { class: 'dl-drawer-actions' }); + const body = E('div', { class: 'dl-stack gap16' }, [ + stats, + E('section', { class: 'dl-dsec' }, [ + E('div', { class: 'dl-dsec-head' }, [E('h4', {}, 'Connect'), live]), + d.config_stale + ? E('div', { class: 'dl-note warn' }, [ + icon('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.', + ), + ]) + : '', + connect, + ]), + 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: () => exportEvents({ people: [p] }, logEvents, 'csv', d.id) }, + 'Export', + ), + E( + 'button', + { + type: 'button', + class: 'dl-linkbtn danger', + click: () => clearLogDialog(`Clear ${d.name}'s activity`, `Removes events about ${d.name}.`, { device: d.id }, loadLog), + }, + 'Clear', + ), + E('a', { href: L.url('admin/network/dawnline/activity') }, 'All activity'), + ]), + ]), + log, + ]), + E('section', { class: 'dl-dsec' }, [E('div', { class: 'dl-dsec-head' }, E('h4', {}, 'Details')), details]), + ]); + loadLog(); + const watch = window.setInterval(() => { + reload(); + loadLog(); + }, 8000); + const handle = drawer(titleEl, body, foot, () => clearInterval(watch)); + paint(); +} + +/** Admin "Add device" dialog for a person; opens the new device's drawer. */ +export function addDevice(person: Person, refresh: () => unknown) { + const nameInput = E('input', { type: 'text', class: 'cbi-input-text', placeholder: KIND_LABEL.phone, maxlength: 48 }) as HTMLInputElement; + let kind: Kind = 'phone'; + const kinds = E( + 'div', + { class: 'dl-kinds', role: 'radiogroup', 'aria-label': 'Type' }, + KINDS.map((k) => + E( + 'button', + { + type: 'button', + role: 'radio', + class: k === kind ? 'on' : '', + 'aria-checked': k === kind ? 'true' : 'false', + 'data-kind': k, + click: () => { + kind = k; + kinds.querySelectorAll('button').forEach((c) => { + const on = (c as HTMLElement).dataset.kind === k; + c.classList.toggle('on', on); + c.setAttribute('aria-checked', on ? 'true' : 'false'); + }); + nameInput.placeholder = KIND_LABEL[k]; + }, + }, + [icon(k), E('span', {}, KIND_LABEL[k])], + ), + ), + ); + const over = person.devices.length >= person.device_limit; + modal( + `Add a device for ${person.name}`, + [ + over + ? E( + 'p', + { class: 'dl-hint' }, + `${person.name} already has ${person.devices.length} of ${person.device_limit} devices. As admin you can still add one.`, + ) + : '', + E('div', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Type'), kinds]), + E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Name'), nameInput]), + ], + [ + E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + ' ', + button( + 'Add device', + async () => { + const name = nameInput.value.trim() || nameInput.placeholder.replace(/^e\.g\. /, ''); + const r = await attempt(() => api.deviceCreate(person.id, name, kind)); + if (!r) return; + closeModal(); + notify(`${name} added`, 'success', 3000); + refresh(); + const st = await api.status(1); + const p2 = st.people.find((x) => x.id === person.id); + const d2 = p2?.devices.find((x) => x.id === r.id); + if (p2 && d2) openDevice(p2, d2, refresh, st.geo); + }, + 'positive', + ), + ], + ); + setTimeout(() => nameInput.focus(), 50); +} diff --git a/web/src/admin/disguise.ts b/web/src/admin/disguise.ts new file mode 100644 index 0000000..cff4ff4 --- /dev/null +++ b/web/src/admin/disguise.ts @@ -0,0 +1,137 @@ +// Disguise methods: one picker for the Server page and the setup wizard. + +import type { AwgCaps } from '../shared/types'; +import { E } from './e'; +import { icon } from '../shared/icons'; + +export type Method = 'standard' | 'strong' | 'max' | 'off'; + +export interface MethodInfo { + id: Method; + title: string; + ic: string; + text: string; + /** 0-4, shown as dots. */ + stealth: number; + speed: number; + /** Which apps can connect. */ + apps: string; + /** The same, short (server header). */ + short: string; + /** Router capability it needs. */ + needs?: keyof AwgCaps; +} + +export const METHODS: MethodInfo[] = [ + { + 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', + }, +]; + +export const methodInfo = (id: string): MethodInfo | undefined => METHODS.find((x) => x.id === id); + +const NEEDS: Record = { + 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 dots(n: number, label: string): HTMLElement { + return E('span', { class: 'dl-dots', title: `${label}: ${n} of 4` }, [ + E('span', { class: 'dl-dots-label' }, label), + E( + 'span', + { class: 'dl-dots-row' }, + [0, 1, 2, 3].map((i) => E('i', { class: i < n ? 'on' : '' })), + ), + ]); +} + +/** + * Method cards. `current` gets a badge; unavailable methods stay visible but + * disabled with the reason, so it is clear what an upgrade would bring. + */ +export function methodPicker(caps: AwgCaps, selected: Method, onSelect: (m: Method) => void, current?: string): HTMLElement { + const el = E('div', { class: 'dl-methods', role: 'radiogroup', 'aria-label': 'Disguise method' }); + const paint = () => + dom.content( + el, + METHODS.map((m) => { + const ok = !m.needs || caps[m.needs]; + const on = m.id === selected; + return E( + 'button', + { + type: 'button', + role: 'radio', + 'aria-checked': on ? 'true' : 'false', + 'aria-disabled': ok ? null : 'true', + class: `dl-method${on ? ' on' : ''}${ok ? '' : ' off'}`, + click: () => { + if (!ok || on) return; + selected = m.id; + paint(); + onSelect(m.id); + }, + }, + [ + E('div', { class: 'dl-method-head' }, [ + E('span', { class: 'dl-method-ic' }, icon(m.ic)), + E('b', {}, m.title), + m.id === current + ? E('span', { class: 'dl-pill ok' }, 'Current') + : m.id === 'standard' && !current + ? E('span', { class: 'dl-pill' }, 'Recommended') + : '', + ]), + E('p', {}, m.text), + E('div', { class: 'dl-method-meters' }, [dots(m.stealth, 'Stealth'), dots(m.speed, 'Speed')]), + E( + 'div', + { class: 'dl-method-foot' }, + ok ? [icon('phone'), E('span', {}, m.apps)] : [icon('alert'), E('span', {}, NEEDS[m.needs!])], + ), + ], + ); + }), + ); + paint(); + return el; +} diff --git a/web/src/admin/e.ts b/web/src/admin/e.ts new file mode 100644 index 0000000..6de4232 --- /dev/null +++ b/web/src/admin/e.ts @@ -0,0 +1,20 @@ +// LuCI's global E() appends array children only one level deep and +// stringifies nested arrays ("[object HTMLDivElement]"). This wrapper +// flattens children recursively and drops empty values, so components can +// compose freely. Modules import it and thereby shadow the global. + +import type { Child } from './luci.d'; + +function flatten(c: Child, out: (Node | string)[]): (Node | string)[] { + if (c == null || c === false || c === '') return out; + if (Array.isArray(c)) c.forEach((x) => flatten(x, out)); + else out.push(c instanceof Node ? c : String(c)); + return out; +} + +export function E(tag: string, attrs?: Record | Child, children?: Child): HTMLElement { + const luciE = (window as unknown as { E: (t: string, a: Record, c: Child) => HTMLElement }).E; + const isAttrs = attrs != null && typeof attrs === 'object' && !Array.isArray(attrs) && !(attrs instanceof Node); + if (!isAttrs && children === undefined) return luciE(tag, {}, flatten(attrs as Child, [])); + return luciE(tag, (isAttrs ? attrs : {}) as Record, flatten(children, [])); +} diff --git a/web/src/admin/interfaces.ts b/web/src/admin/interfaces.ts new file mode 100644 index 0000000..83bf725 --- /dev/null +++ b/web/src/admin/interfaces.ts @@ -0,0 +1,319 @@ +// Interfaces card (Server page): auto-detected WAN and LAN, plus a picker for +// the interfaces that make up a server's home network. + +import { E } from './e'; +import { api, type IfaceCategory, type InterfacesData, type NetDevice } from './api'; +import { attempt, button, notify } from './ui'; +import { installMissing } from './pkgs'; +import { attachTip } from './charts'; +import { icon } from '../shared/icons'; + +const GROUPS: [IfaceCategory, string][] = [ + ['wan', 'WAN'], + ['ethernet', 'Ethernet'], + ['wifi', 'Wi-Fi'], + ['vpn', 'VPN & tunnels'], + ['other', 'Other'], +]; + +const ICON: Record = { + wan: 'globe', + ethernet: 'ethernet', + bridge: 'bridge', + wifi: 'wifi', + vpn: 'tunnel', + other: 'link', +}; + +function sw(on: boolean, label: string, onChange: (v: boolean) => void): HTMLButtonElement { + const b = E( + 'button', + { + type: 'button', + role: 'switch', + class: `dl-switch${on ? ' on' : ''}`, + 'aria-checked': on ? 'true' : 'false', + 'aria-label': label, + click: () => { + const v = !b.classList.contains('on'); + b.classList.toggle('on', v); + b.setAttribute('aria-checked', v ? 'true' : 'false'); + onChange(v); + }, + }, + E('i'), + ) as HTMLButtonElement; + return b; +} + +export function interfacesCard(serverId: string, title = 'Interfaces'): HTMLElement { + const root = E( + 'section', + { class: 'dl-setsec dl-ifcard' }, + E('div', { class: 'dl-setsec-body' }, E('p', { class: 'dl-muted' }, 'Loading interfaces…')), + ); + let d: InterfacesData; + let autoWan = true, + wanDev = '', + autoLan = true, + lanLike = true; + let lans = new Set(); + let initial = ''; + + const snapshot = () => JSON.stringify([lanLike, autoWan, autoWan ? '' : wanDev, autoLan, [...lans].sort()]); + const liveLan = () => d.detected.lan || d.saved.lan || ''; + const currentWan = () => (autoWan ? d.detected.wan || d.saved.wan : wanDev) || ''; + const byName = () => new Map(d.devices.map((x) => [x.name, x])); + + /** Home devices as the server would use them after Save. */ + const homeDevs = (): NetDevice[] => { + const m = byName(); + const names = [...(autoLan && liveLan() ? [liveLan()] : []), ...[...lans].filter((n) => n !== liveLan())]; + return names.filter((n) => n !== currentWan()).map((n) => m.get(n) ?? ({ name: n, nets: [], missing: true } as unknown as NetDevice)); + }; + + const take = (r: InterfacesData, resetChoice: boolean) => { + d = r; + if (resetChoice) { + autoWan = r.config.auto_wan; + wanDev = r.config.wan_device || r.detected.wan || r.saved.wan || ''; + autoLan = r.config.auto_lan; + lanLike = r.config.lan_like; + lans = new Set(r.config.lan_devices); + initial = snapshot(); + } + paint(); + }; + + const load = async (reset: boolean) => { + const r = await api.interfaces(serverId).catch((e: Error) => { + notify(e.message, 'error'); + return null; + }); + if (r) take(r, reset); + }; + + function tile(x: NetDevice): HTMLElement { + const isAuto = autoLan && x.name === liveLan(); + const isWan = x.name === currentWan(); + const sel = !isAuto && lans.has(x.name); + const blocked = !!x.own || !!x.master || isWan || isAuto; + const usable = !blocked && (x.nets.length > 0 || sel || !!x.missing); + const noZone = (sel || isAuto) && !x.zone && !x.missing; + const sub = x.missing + ? 'Not present right now' + : x.own + ? 'This server' + : x.master + ? `Port of ${x.master}` + : isWan + ? `Internet${x.zone ? ` · zone ${x.zone}` : ''}` + : x.nets.length + ? x.nets.join(', ') + : 'No IPv4 network'; + const el = E( + 'button', + { + type: 'button', + class: `dl-if${sel ? ' sel' : ''}${isAuto ? ' auto' : ''}${!usable && !sel && !isAuto ? ' off' : ''}${noZone ? ' warn' : ''}`, + 'aria-pressed': sel || isAuto ? 'true' : 'false', + // aria-disabled, not disabled: the tooltip should still explain why. + 'aria-disabled': usable ? null : 'true', + click: () => { + if (!usable) return; + if (lans.has(x.name)) lans.delete(x.name); + else lans.add(x.name); + paint(); + }, + }, + [ + E('span', { class: 'dl-if-ic' }, icon(ICON[x.kind] ?? 'link')), + E('span', { class: 'dl-if-main' }, [E('span', { class: 'dl-if-name' }, x.name), E('span', { class: 'dl-if-sub' }, sub)]), + isAuto + ? E('span', { class: 'dl-if-badge ok' }, [E('i', { class: 'dot ok' }), 'Auto']) + : sel + ? E('span', { class: 'dl-if-check' }, icon('check')) + : '', + ], + ); + attachTip(el, () => [ + E('div', { class: 'dl-tip-title' }, x.name), + E('div', { class: 'dl-muted' }, [ + x.logical ? `Interface ${x.logical}` : 'No netifd interface', + x.zone ? ` · zone ${x.zone}` : ' · no firewall zone', + ]), + x.members.length ? E('div', { class: 'dl-muted' }, `Ports: ${x.members.join(', ')}`) : '', + x.nets.length ? E('div', { class: 'dl-mono' }, x.nets.join(', ')) : '', + noZone ? E('div', { class: 'dl-warn' }, 'Not in a firewall zone: the firewall rejects this traffic.') : '', + x.master ? E('div', { class: 'dl-muted' }, `Choose ${x.master} to include it.`) : '', + ]); + return el; + } + + /** Tile colour: green while traffic really enters the LAN, orange when it should but can't. */ + function likeHomeTone(): string { + const lh = d.like_home; + if (!lanLike || !d.config.lan_like) return ''; + return !d.needs?.length && lh.active && lh.bridged ? 'ok' : 'warn'; + } + + function likeHomeText(): (Node | string)[] { + const lh = d.like_home; + if (!lanLike) return ['Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router.']; + if (d.needs?.length) + return [ + E('span', { class: 'dl-warn' }, `Needs ${d.needs.join(' and ')}.`), + ' Until they are installed, internet traffic goes straight to the WAN.', + ]; + if (!d.config.lan_like) + return ['Internet traffic will enter the router from your LAN, so it is handled like any home device. Save to turn on.']; + if (lh.active && lh.bridged) + return [ + 'Internet traffic enters ', + E('span', { class: 'dl-mono' }, lh.dev ?? ''), + ' as ', + E('span', { class: 'dl-mono' }, lh.address ?? ''), + ', so whatever handles home traffic (proxies, filters, DNS) handles it too.', + ]; + return [ + E('span', { class: 'dl-warn' }, `Not working: ${lh.error ?? 'the link is down'}`), + ' Internet traffic goes straight to the WAN for now.', + ]; + } + + function paint() { + const wanSel = E( + 'select', + { + class: 'cbi-input-select', + 'aria-label': 'Internet interface', + change: (ev: Event) => { + wanDev = (ev.target as HTMLSelectElement).value; + paint(); + }, + }, + d.devices + .filter((x) => !x.own && !x.master && x.zone && !x.missing) + .map((x) => E('option', { value: x.name, selected: x.name === wanDev ? 'selected' : null }, `${x.name} · zone ${x.zone}`)), + ) as HTMLSelectElement; + + const hint = (live: string | null, saved: string) => + E('span', {}, [' Live: ', E('span', { class: 'dl-mono' }, live || '—'), ' · Saved: ', E('span', { class: 'dl-mono' }, saved || '—')]); + + const groups = GROUPS.map(([cat, label]) => { + const list = d.devices.filter((x) => x.category === cat); + return list.length ? E('div', { class: 'dl-ifgroup' }, [E('h4', {}, label), E('div', { class: 'dl-ifgrid' }, list.map(tile))]) : ''; + }); + + const home = homeDevs(); + const nets = home.flatMap((x) => x.nets.map((n) => [n, x.name] as const)); + const dirty = snapshot() !== initial; + const save = button( + 'Save', + async () => { + const r = await attempt( + () => api.serverInterfaces(serverId, autoWan, autoWan ? '' : wanDev, autoLan, [...lans], lanLike), + 'Interfaces saved', + ); + if (!r) return; + take(r, true); + if (r.nets_changed && r.lan_only) + notify( + `${r.lan_only} ${r.lan_only === 1 ? 'person has' : 'people have'} Home-only access: their devices need the configuration again to reach the new networks.`, + 'warning', + 10000, + ); + }, + 'positive', + { disabled: !dirty }, + ); + + dom.content(root, [ + E('div', { class: 'dl-setsec-body' }, [ + E('div', { class: 'dl-panel-head' }, [ + E('h3', {}, title), + E('span', { class: 'dl-spacer' }), + button([icon('reset'), ' Rescan'], () => load(false), 'neutral', { title: 'Read the interfaces again' }), + ]), + E('div', { class: 'dl-setrow' }, [ + E('div', { class: 'dl-lh-main' }, [ + E('span', { class: `dl-need-ic ${likeHomeTone()}` }, icon('home')), + E('div', { class: 'dl-stack' }, [ + E('span', { class: 'dl-setrow-label' }, 'Internet like a home device'), + E('span', { class: 'dl-sub' }, likeHomeText()), + ]), + ]), + E('div', { class: 'dl-setrow-ctl dl-if-wanctl' }, [ + lanLike && d.needs?.length ? button('Install', () => installMissing('home', d.needs!, () => load(false)), 'positive') : '', + sw(lanLike, 'Internet like a home device', (v) => { + lanLike = v; + paint(); + }), + ]), + ]), + E('div', { class: 'dl-setrow' }, [ + E('div', { class: 'dl-lh-main' }, [ + E('span', { class: 'dl-need-ic' }, icon('globe')), + E('div', { class: 'dl-stack' }, [ + E('span', { class: 'dl-setrow-label' }, 'Auto-detect WAN'), + E('span', { class: 'dl-sub' }, [ + 'The interface with the default route: the server port opens there and Internet access leaves through it.', + hint(d.detected.wan, d.saved.wan), + ]), + ]), + ]), + E('div', { class: 'dl-setrow-ctl dl-if-wanctl' }, [ + autoWan ? '' : wanSel, + sw(autoWan, 'Auto-detect WAN', (v) => { + autoWan = v; + paint(); + }), + ]), + ]), + E('div', { class: 'dl-setrow' }, [ + E('div', { class: 'dl-lh-main' }, [ + E('span', { class: 'dl-need-ic' }, icon('network')), + E('div', { class: 'dl-stack' }, [ + E('span', { class: 'dl-setrow-label' }, 'Auto-detect LAN'), + E('span', { class: 'dl-sub' }, ['Adds the detected LAN to the home network.', hint(d.detected.lan, d.saved.lan)]), + ]), + ]), + E( + 'div', + { class: 'dl-setrow-ctl' }, + sw(autoLan, 'Auto-detect LAN', (v) => { + autoLan = v; + paint(); + }), + ), + ]), + E('div', { class: 'dl-iflead' }, [ + E('b', {}, 'Home network'), + E( + 'span', + { class: 'dl-sub' }, + 'What people with Home access can reach. Click to add an interface; bridge ports and Wi-Fi in a bridge come with the bridge.', + ), + ]), + ...groups, + ]), + E('div', { class: 'dl-setsec-foot' }, [ + E( + 'span', + { class: 'dl-sub dl-if-summary' }, + nets.length + ? [ + 'Home access reaches ', + ...nets.flatMap(([n, dev], i) => [i ? ', ' : '', E('span', { class: 'dl-mono' }, n), ` (${dev})`]), + lanLike ? ' · Internet like a home device' : currentWan() ? ` · Internet via ${currentWan()}` : '', + ] + : ['No home network: Home access reaches nothing but this router.', currentWan() ? ` Internet via ${currentWan()}.` : ''], + ), + save, + ]), + ]); + } + + load(true); + return root; +} diff --git a/web/src/admin/invite.ts b/web/src/admin/invite.ts new file mode 100644 index 0000000..703d35e --- /dev/null +++ b/web/src/admin/invite.ts @@ -0,0 +1,135 @@ +// Invite card: a picture with the person's QR code, link and three steps, +// made in the browser to share (Telegram, AirDrop) or print. + +import type { Person } from '../shared/types'; +import { E } from './e'; +import { attempt, button, closeModal, copyText, downloadFile, modal, notify } from './ui'; +import { icon } from '../shared/icons'; +import { qrSvg } from '../shared/qr'; + +const W = 1080, + H = 1512; +/** One margin for everything: header, greeting and the QR tile share both edges. */ +const M = 96; +const SANS = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"; +const MONO = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace'; + +const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!); + +function cardSvg(p: Person, server: string, link: string): string { + const url = new URL(link); + const word = url.pathname.slice(1); + // Long names shrink to stay on one line (roughly 0.58 em per character). + const nameSize = Math.min(92, Math.floor((W - 2 * M) / (0.58 * (4 + p.name.length)))); + const tile = W - 2 * M, + top = 392, + pad = 40; + const qr = qrSvg(link, 2).replace(' + `${body}`; + return ( + `` + + `` + + // Mark and server name + `` + + `` + + text(M + 82, M + 42, 36, '#a3a3a3', esc(server)) + + // Greeting + text(M, 276, nameSize, '#ffffff', `Hi, ${esc(p.name)}`, 'font-weight="600"') + + text(M, 340, 40, '#8a8a8a', `Scan to connect to ${esc(server)}`) + + // Big QR on a white tile, edge to edge with the text above + `` + + qr + + // The link: three words, then the host + `${esc(word)}` + + text(W / 2, top + tile + 156, 34, '#737373', esc(url.host), 'text-anchor="middle"') + + `` + ); +} + +async function toPng(svg: string): Promise { + const img = new Image(); + img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`; + await img.decode(); + const canvas = document.createElement('canvas'); + canvas.width = W; + canvas.height = H; + canvas.getContext('2d')!.drawImage(img, 0, 0, W, H); + return new Promise((resolve, reject) => + canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('Could not draw the card'))), 'image/png'), + ); +} + +type Invitee = Pick & { links?: string[] }; + +/** + * The card with Copy link and Share / Download. Also the "is ready" step + * after adding someone. + */ +export async function inviteCard(p: Invitee, server: string, opts: { title?: string; lead?: string } = {}) { + if (!p.link) { + notify('The personal portal is off. Turn it on in Settings.', 'warning'); + return; + } + const link = p.link; + const png = await attempt(() => toPng(cardSvg(p as Person, server, link))); + if (!png) return; + const file = new File([png], `${p.id}-invite.png`, { type: 'image/png' }); + const url = URL.createObjectURL(png); + const nav = navigator as Navigator & { canShare?: (d: unknown) => boolean }; + const canShare = !!nav.canShare?.({ files: [file] }); + const close = () => { + URL.revokeObjectURL(url); + closeModal(); + }; + const share = canShare + ? button( + [icon('link'), ' Share card'], + async () => { + try { + await nav.share({ files: [file], title: `Invite ${p.name}` }); + } catch { + /* cancelled */ + } + }, + 'positive', + ) + : button([icon('download'), ' Download card'], () => downloadFile(file.name, png), 'positive'); + modal( + opts.title ?? `Invite ${p.name}`, + E('div', { class: 'dl-invite' }, [ + E('img', { src: url, alt: `Invite card for ${p.name}` }), + E('div', { class: 'dl-invite-side' }, [ + E( + 'p', + { class: 'dl-muted' }, + opts.lead ?? `Send ${p.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: () => copyText(link, 'Personal link copied') }, [ + E('span', {}, link.replace(/^https:\/\//, '')), + icon('copy'), + ]), + ...(p.links ?? []) + .filter((l) => l !== link) + .map((l) => + E('button', { type: 'button', class: 'dl-invite-link alt', title: 'Copy this link', click: () => copyText(l, 'Link copied') }, [ + E('span', {}, l.replace(/^https?:\/\//, '')), + E('span', { class: `dl-pill ${l.startsWith('http:') ? 'warn' : ''}` }, l.startsWith('http:') ? 'HTTP' : 'Also'), + icon('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' }, [ + share, + button([icon('copy'), ' Copy link'], () => copyText(link, 'Personal link copied')), + ]), + ]), + ]), + [E('button', { class: 'cbi-button cbi-button-neutral', click: close }, 'Done')], + 'wide', + ); +} diff --git a/web/src/admin/kit.ts b/web/src/admin/kit.ts new file mode 100644 index 0000000..87fc1d0 --- /dev/null +++ b/web/src/admin/kit.ts @@ -0,0 +1,62 @@ +// Small form pieces shared by Settings and Server: a switch, a text input and +// a labelled setting row (label + help on the left, control on the right). + +import { E } from './e'; +import { icon } from '../shared/icons'; + +export function sw(on: boolean, label: string, onChange?: (v: boolean) => void): HTMLButtonElement { + const b = E( + 'button', + { + type: 'button', + role: 'switch', + class: `dl-switch${on ? ' on' : ''}`, + 'aria-checked': on ? 'true' : 'false', + 'aria-label': label, + click: () => { + const v = !b.classList.contains('on'); + b.classList.toggle('on', v); + b.setAttribute('aria-checked', v ? 'true' : 'false'); + onChange?.(v); + }, + }, + E('i'), + ) as HTMLButtonElement; + return b; +} + +export const isOn = (b: HTMLElement) => b.classList.contains('on'); + +export function input(value: string, attrs: Record = {}): HTMLInputElement { + return E('input', { type: 'text', class: 'cbi-input-text', value, ...attrs }) as HTMLInputElement; +} + +export function row(label: string, control: Node, help?: string): HTMLElement { + return E('div', { class: 'dl-setrow' }, [ + E('div', { class: 'dl-stack' }, [E('span', { class: 'dl-setrow-label' }, label), help ? E('span', { class: 'dl-sub' }, help) : '']), + E('div', { class: 'dl-setrow-ctl' }, control), + ]); +} + +/** A section card with its own footer (Save etc.). */ +export function card(title: string, body: (Node | string)[], foot: (Node | string)[], extra = ''): HTMLElement { + return E('section', { class: `dl-setsec ${extra}` }, [ + E('div', { class: 'dl-setsec-body' }, [title ? E('h3', {}, title) : '', ...body]), + foot.length ? E('div', { class: 'dl-setsec-foot' }, foot) : '', + ]); +} + +/** A titled group inside a settings card: icon, title and a short line, then its rows separated by hairlines. */ +export function group(ic: string, title: string, sub: string, items: (Node | string)[]): HTMLElement { + return E('div', { class: 'dl-group' }, [ + E('div', { class: 'dl-group-head' }, [ + E('span', { class: 'dl-group-ic' }, icon(ic)), + E('span', { class: 'dl-stack' }, [E('b', {}, title), sub ? E('span', { class: 'dl-sub' }, sub) : '']), + ]), + E( + 'div', + { class: 'dl-group-body' }, + items.filter((x) => x !== ''), + ), + ]); +} diff --git a/web/src/admin/logs.ts b/web/src/admin/logs.ts new file mode 100644 index 0000000..63871d5 --- /dev/null +++ b/web/src/admin/logs.ts @@ -0,0 +1,152 @@ +// Activity log helpers shared by Activity, Settings, the person page and the +// device drawer: categories, export, and the clear / reset dialogs. + +import type { LogEvent, Status } from '../shared/types'; +import { E } from './e'; +import { api, type LogCategory, type LogFilter } from './api'; +import { attempt, button, closeModal, downloadFile, modal, notify } from './ui'; + +/** Mirrors CATEGORY in dawnline.live. */ +const CATEGORY: Record = { + connect: 'connections', + disconnect: 'connections', + roam: 'connections', + device_added: 'devices', + device_removed: 'devices', + devices_removed: 'devices', + person_added: 'people', + person_removed: 'people', + person_changed: 'people', + paused: 'people', + resumed: 'people', + paused_all: 'people', + resumed_all: 'people', + server_down: 'problems', + server_up: 'problems', + portal_blocked: 'problems', +}; + +export const CATEGORIES: LogCategory[] = ['connections', 'devices', 'people', 'problems']; + +export const CATEGORY_LABEL: Record = { + connections: 'Connections', + devices: 'Devices', + people: 'People', + problems: 'Problems', +}; + +export const CATEGORY_HELP: Record = { + connections: 'Connects, disconnects and IP changes', + devices: 'Devices added and removed', + people: 'People added, changed, paused', + problems: 'Tunnel down, blocked portal sign-ins', +}; + +export const categoryOf = (type: string): LogCategory => CATEGORY[type] ?? 'problems'; + +function names(st: Pick) { + const people = new Map(st.people.map((p) => [p.id, p.name])); + const devices = new Map(st.people.flatMap((p) => p.devices.map((d) => [d.id, d.name] as [string, string]))); + return { people, devices }; +} + +function csvCell(v: unknown): string { + const s = v == null ? '' : String(v); + return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; +} + +/** Download events as CSV or JSON (person and device names resolved). */ +export function exportEvents(st: Pick, events: LogEvent[], format: 'csv' | 'json', suffix = '') { + const n = names(st); + const rows = events.map((e) => ({ + time: new Date(e.ts * 1000).toISOString(), + category: categoryOf(e.type), + type: e.type, + person: e.person ? (n.people.get(e.person) ?? e.person) : '', + device: e.device ? (n.devices.get(e.device) ?? e.device) : '', + detail: e.detail ?? '', + where: e.where ?? '', + })); + const stamp = new Date().toISOString().slice(0, 10); + const name = `dawnline-activity${suffix ? `-${suffix}` : ''}-${stamp}.${format}`; + if (format === 'json') { + downloadFile(name, JSON.stringify(rows, null, 2), 'application/json'); + return; + } + const cols = ['time', 'category', 'type', 'person', 'device', 'detail', 'where'] as const; + const csv = [cols.join(','), ...rows.map((r) => cols.map((c) => csvCell(r[c])).join(','))].join('\n'); + downloadFile(name, csv, 'text/csv'); +} + +const AGES: [string, string][] = [ + ['', 'Everything'], + ['7', 'Older than 7 days'], + ['30', 'Older than 30 days'], + ['90', 'Older than 90 days'], +]; + +/** + * Ask what to clear and do it. `base` pins person/device; the dialog lets you + * pick a category (unless `category` is given) and an age. + */ +export function clearLogDialog(title: string, what: string, base: LogFilter, done: () => unknown, category?: LogCategory) { + const cat = E('select', { class: 'cbi-input-select' }, [ + E('option', { value: '' }, 'All categories'), + ...CATEGORIES.map((c) => E('option', { value: c, selected: c === category ? 'selected' : null }, CATEGORY_LABEL[c])), + ]) as HTMLSelectElement; + const age = E( + 'select', + { class: 'cbi-input-select' }, + AGES.map(([v, t]) => E('option', { value: v }, t)), + ) as HTMLSelectElement; + modal( + title, + [ + E('p', { class: 'dl-muted' }, `${what} This cannot be undone; export first if you want a copy.`), + E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Category'), cat]), + E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Which events'), age]), + ], + [ + E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + ' ', + button( + 'Clear', + async () => { + const r = await attempt(() => api.logsClear({ ...base, category: cat.value, older_days: age.value })); + if (!r) return; + closeModal(); + notify(r.removed ? `${r.removed} event${r.removed === 1 ? '' : 's'} removed` : 'Nothing matched', 'success', 3000); + done(); + }, + 'negative', + ), + ], + ); +} + +/** Confirm and reset traffic history for everyone, a person or a device. */ +export function resetUsageDialog(scope: 'all' | 'person' | 'device', id: string, label: string, done: () => unknown) { + const body = + scope === 'device' + ? `Clears ${label}'s daily and monthly traffic history. Their person's totals and data limit are not changed.` + : scope === 'person' + ? `Clears ${label}'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.'; + modal( + scope === 'all' ? 'Reset all traffic history?' : `Reset traffic history for ${label}?`, + [E('p', { class: 'dl-muted' }, body)], + [ + E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + ' ', + button( + 'Reset', + async () => { + if (!(await attempt(() => api.usageClear(scope, id), 'Traffic history reset'))) return; + closeModal(); + done(); + }, + 'negative', + ), + ], + ); +} diff --git a/web/src/admin/luci.d.ts b/web/src/admin/luci.d.ts new file mode 100644 index 0000000..9a3872e --- /dev/null +++ b/web/src/admin/luci.d.ts @@ -0,0 +1,129 @@ +// Minimal typings for the parts of the LuCI client SDK (luci.js / ui.js / +// rpc.js / poll.js / dom.js) that Dawnline uses. The module is evaluated by +// LuCI's loader, which injects the `'require'`d classes as these identifiers. + +type Child = Node | string | number | null | undefined | false | Child[]; + +interface ElementAttrs { + [key: string]: unknown; + class?: string; + style?: string; + click?: (ev: MouseEvent) => void; + change?: (ev: Event) => void; + input?: (ev: Event) => void; + keydown?: (ev: KeyboardEvent) => void; +} + +interface LuciWidget { + render(): Node | Promise; + getValue(): any; + setValue(v: any): void; + isValid(): boolean; + triggerValidation(): void; + setChangeEvents?(node: Node, ...events: string[]): void; + node?: HTMLElement; +} + +interface WidgetOptions { + id?: string; + name?: string; + optional?: boolean; + datatype?: string; + placeholder?: string; + validate?: (value: string) => true | string; + disabled?: boolean; + readonly?: boolean; + widget?: 'select' | 'radio' | 'checkbox'; + sort?: boolean | string[]; + create?: boolean; + multiple?: boolean; + size?: number; + rows?: number; + cols?: number; + monospace?: boolean; + password?: boolean; + value_enabled?: string; + value_disabled?: string; + hiddenname?: string; +} + +interface LuciUI { + showModal(title: string | null, children: Child, ...classes: string[]): HTMLElement; + hideModal(): void; + addNotification(title: string | null, children: Child, ...classes: string[]): HTMLElement; + addTimeLimitedNotification(title: string | null, children: Child, timeout?: number, ...classes: string[]): HTMLElement; + changes: any; + itemlist(node: Node, items: unknown[], separators?: unknown): HTMLElement; + createHandlerFn(ctx: unknown, fn: string | ((...args: any[]) => unknown), ...args: unknown[]): (ev: Event) => void; + Textfield: new (value: string | null, options?: WidgetOptions) => LuciWidget; + Textarea: new (value: string | null, options?: WidgetOptions) => LuciWidget; + Select: new (value: string | string[] | null, choices: Record, options?: WidgetOptions) => LuciWidget; + Checkbox: new (value: string | null, options?: WidgetOptions) => LuciWidget; + DynamicList: new (values: string[] | null, choices?: Record, options?: WidgetOptions) => LuciWidget; + Dropdown: new (value: string | string[] | null, choices: Record, options?: WidgetOptions) => LuciWidget; +} + +interface LuciRpc { + declare(spec: { + object: string; + method: string; + params?: string[]; + expect?: Record; + filter?: (data: any, args: unknown[], ...extra: unknown[]) => any; + reject?: boolean; + }): (...args: any[]) => Promise; +} + +interface LuciPoll { + add(fn: () => unknown, interval?: number): boolean; + remove(fn: () => unknown): boolean; + start(): void; + stop(): void; + active(): boolean; +} + +interface LuciDom { + content(node: Node, children: Child): Node; + findClassInstance(node: Node): any; + append(node: Node, children: Child): Node; + isEmpty(node: Node): boolean; +} + +interface LuciEnv { + sessionid?: string; + rpctimeout?: number; + [key: string]: unknown; +} + +interface LuciL { + env: LuciEnv; + url(...parts: string[]): string; + resolveDefault(p: Promise, def: T): Promise; + resource(...parts: string[]): string; + itemlist(node: Node, items: unknown[], separators?: unknown): HTMLElement; + bind any>(fn: F, self: unknown, ...args: unknown[]): F; + raise(type: string, fmt: string, ...args: unknown[]): never; +} + +declare global { + interface String { + format(...args: unknown[]): string; + } + + const E: (tag: string, attrs?: ElementAttrs | Child, children?: Child) => HTMLElement; + const _: (msg: string, ctx?: string) => string; + const N_: (n: number, singular: string, plural: string, ctx?: string) => string; + const L: LuciL; + const ui: LuciUI; + const rpc: LuciRpc; + const poll: LuciPoll; + const dom: LuciDom; + const baseclass: { extend(props: T): T }; + // LuCI form/network/firewall/uci classes are used dynamically. + const form: any; + const network: any; + const firewall: any; + const uci: any; +} + +export type { Child, LuciWidget, WidgetOptions }; diff --git a/web/src/admin/main.ts b/web/src/admin/main.ts new file mode 100644 index 0000000..a4def25 --- /dev/null +++ b/web/src/admin/main.ts @@ -0,0 +1,51 @@ +// LuCI module `dawnline.app`: one factory per admin view. The thin files in +// view/dawnline/*.js do `return view.extend(app.())`. + +import { PeoplePage } from './pages/people'; +import { ServerPage } from './pages/server'; +import { SettingsPage } from './pages/settings'; +import { HealthPage, UpdatesPage } from './pages/maintenance'; +import { PersonPage } from './pages/person'; +import { ActivityPage } from './pages/activity'; +import { styleNode } from './styles'; + +interface Page { + load(): Promise; + render(data: any): Node | Promise; + /** Set by a form page when it rendered something without a form. */ + noFooter?: boolean; +} + +function factory

(Cls: new () => P, formBased: boolean) { + return () => { + const page = new Cls(); + const v: Record = { + load: () => page.load(), + render: async (data: unknown) => { + const node = await page.render(data); + const root = document.createElement('div'); + root.className = 'dl-root'; + root.append(styleNode(), node); + return root; + }, + addFooter(this: any) { + return page.noFooter ? document.createElement('div') : this.super('addFooter', []); + }, + }; + // Pages without a form.Map have nothing to save: hide the footer buttons. + if (!formBased) Object.assign(v, { handleSave: null, handleSaveApply: null, handleReset: null }); + return v; + }; +} + +// The old Overview address opens the Servers page (it holds each server's overview now). +const overview = factory(ServerPage, false); +const people = factory(PeoplePage, true); +const server = factory(ServerPage, false); +const settings = factory(SettingsPage, false); +const person = factory(PersonPage, false); +const activity = factory(ActivityPage, false); +const health = factory(HealthPage, false); +const updates = factory(UpdatesPage, false); + +export { overview, people, person, activity, server, settings, health, updates }; diff --git a/web/src/admin/map.ts b/web/src/admin/map.ts new file mode 100644 index 0000000..915384b --- /dev/null +++ b/web/src/admin/map.ts @@ -0,0 +1,476 @@ +// Connection map: MapLibre GL with a CARTO basemap (light or dark, following +// the Outline theme), the router as origin, one marker per device and an arc +// from the router to each one — solid and animated while the tunnel is live, +// dashed for recently seen. MapLibre loads from a CDN on first use. + +import type { Geo, GeoPoint, Person } from '../shared/types'; +import { E } from './e'; +import { ago } from '../shared/format'; +import { icon, iconSvg } from '../shared/icons'; + +const MAPLIBRE = 'https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl'; +const STYLE_DARK = 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json'; +const STYLE_LIGHT = 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json'; + +export type Range = 'online' | '24h' | '7d' | '30d'; +const WINDOW: Record = { online: 0, '24h': 86400, '7d': 7 * 86400, '30d': 30 * 86400 }; + +let loading: Promise | null = null; + +/** + * Load MapLibre once; tags go inside `host` so Outline's router is not + * disturbed. The stylesheet goes into every map's own container: Outline + * drops the previous page's DOM on navigation (and with it a shared link), + * and without it HTML markers lose their positioning and vanish. + */ +function loadMapLibre(host: HTMLElement): Promise { + const w = window as any; + host.appendChild(E('link', { rel: 'stylesheet', href: `${MAPLIBRE}.css` })); + if (w.maplibregl) return Promise.resolve(w.maplibregl); + if (loading) return loading; + loading = new Promise((resolve, reject) => { + const s = E('script', { src: `${MAPLIBRE}.js` }) as HTMLScriptElement; + s.onload = () => (w.maplibregl ? resolve(w.maplibregl) : reject(new Error('MapLibre failed to load'))); + s.onerror = () => { + loading = null; + reject(new Error('Could not load the map library (no internet access from this browser?)')); + }; + host.appendChild(s); + }); + return loading; +} + +function isDark(): boolean { + const attr = document.documentElement.getAttribute('data-darkmode'); + if (attr != null) return attr === 'true'; + return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false; +} + +/** A gentle arc between two [lng, lat] points (quadratic Bézier in map space). */ +function arc(a: [number, number], b: [number, number], steps = 48): [number, number][] { + const mx = (a[0] + b[0]) / 2; + const my = (a[1] + b[1]) / 2; + const dx = b[0] - a[0]; + const dy = b[1] - a[1]; + const len = Math.hypot(dx, dy) || 1; + // Bend to the left of the direction of travel, proportional to distance. + const k = Math.min(0.25 * len, 12); + const cx = mx - (dy / len) * k; + const cy = my + (dx / len) * k; + const out: [number, number][] = []; + for (let i = 0; i <= steps; i++) { + const t = i / steps; + const u = 1 - t; + out.push([u * u * a[0] + 2 * u * t * cx + t * t * b[0], u * u * a[1] + 2 * u * t * cy + t * t * b[1]]); + } + return out; +} + +export interface MapCallbacks { + openPerson: (personId: string) => void; + openDevice: (personId: string, deviceId: string) => void; +} + +export interface MapData { + geo: Geo; + people: Person[]; + now: number; + /** Restrict to one person (person page). */ + person?: string; +} + +/** Latest point per device inside the time window. */ +export function visiblePoints(data: MapData, range: Range): GeoPoint[] { + const best = new Map(); + for (const p of data.geo.points) { + if (data.person && p.person !== data.person) continue; + if (range === 'online' ? !p.online : data.now - p.ts > WINDOW[range]) continue; + const cur = best.get(p.device); + if (!cur || (p.online && !cur.online) || (p.online === cur.online && p.ts > cur.ts)) best.set(p.device, p); + } + return [...best.values()]; +} + +export class ConnectionMap { + private map: any = null; + private gl: any = null; + private markers: any[] = []; + private popup: any = null; + private anim = 0; + private data: MapData | null = null; + private range: Range; + private fitted = false; + readonly el: HTMLElement; + private status: HTMLElement; + + constructor( + private cb: MapCallbacks, + range: Range = 'online', + height = 380, + ) { + this.range = range; + this.status = E('div', { class: 'dl-map-status' }); + this.el = E('div', { class: 'dl-geomap', style: `height:${height}px` }, this.status); + } + + async mount(data: MapData) { + this.data = data; + try { + this.gl = await loadMapLibre(this.el); + } catch (e) { + this.status.textContent = (e as Error).message; + return; + } + this.map = new this.gl.Map({ + container: this.el, + style: isDark() ? STYLE_DARK : STYLE_LIGHT, + center: [data.geo.home?.lon ?? 20, data.geo.home?.lat ?? 50], + zoom: 3, + attributionControl: { compact: true }, + dragRotate: false, + pitchWithRotate: false, + cooperativeGestures: true, + }); + this.map.addControl(new this.gl.NavigationControl({ showCompass: false }), 'bottom-right'); + this.map.on('load', () => { + // City-level accuracy: a soft zone instead of a precise pin. + 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', isDark() ? '#ededed' : '#0d0d0d'], + 'circle-opacity': ['case', ['get', 'online'], 0.12, 0.06], + 'circle-stroke-width': 1, + 'circle-stroke-color': ['case', ['get', 'online'], '#40c977', isDark() ? '#ededed' : '#0d0d0d'], + 'circle-stroke-opacity': ['case', ['get', 'online'], 0.35, 0.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'], false], + layout: { 'line-cap': 'round' }, + paint: { 'line-color': isDark() ? '#ededed' : '#0d0d0d', 'line-opacity': 0.35, 'line-width': 1.5, 'line-dasharray': [2, 3] }, + }); + this.map.addLayer({ + id: 'dl-arc-glow', + type: 'line', + source: 'dl-arcs', + filter: ['==', ['get', 'online'], true], + layout: { 'line-cap': 'round' }, + paint: { 'line-color': '#40c977', 'line-opacity': 0.18, 'line-width': 7 }, + }); + this.map.addLayer({ + id: 'dl-arc-live', + type: 'line', + source: 'dl-arcs', + filter: ['==', ['get', 'online'], true], + 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'], true], + layout: { 'line-cap': 'round' }, + paint: { 'line-color': '#ffffff', 'line-width': 2, 'line-opacity': 0.8, 'line-dasharray': [0, 4, 3] }, + }); + this.animate(); + this.draw(); + }); + } + + setRange(r: Range) { + this.range = r; + this.fitted = false; + this.draw(); + } + + update(data: MapData) { + this.data = data; + this.draw(); + } + + destroy() { + cancelAnimationFrame(this.anim); + this.map?.remove(); + this.map = null; + } + + /** Moving highlight along live arcs (MapLibre "animated line" technique). */ + private animate() { + const seq = [ + [0, 4, 3], + [0.5, 4, 2.5], + [1, 4, 2], + [1.5, 4, 1.5], + [2, 4, 1], + [2.5, 4, 0.5], + [3, 4, 0], + [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, 0.5], + ]; + let step = -1; + let last = 0; + const tick = (t: number) => { + if (!this.map) return; + if (t - last > 70) { + last = t; + step = (step + 1) % seq.length; + if (this.map.getLayer('dl-arc-flow')) this.map.setPaintProperty('dl-arc-flow', 'line-dasharray', seq[step]); + } + this.anim = requestAnimationFrame(tick); + }; + this.anim = requestAnimationFrame(tick); + } + + /** Devices grouped by network operator and city: one marker per group. */ + private groups(pts: GeoPoint[]): Group[] { + const map = new Map(); + for (const p of pts) { + const key = `${p.asn || p.org || p.ip}|${p.city}|${p.cc}`; + let g = map.get(key); + if (!g) { + g = { + key, + lat: p.lat, + lon: p.lon, + city: p.city, + country: p.country, + cc: p.cc, + asn: p.asn, + org: p.org, + online: false, + ts: 0, + points: [], + }; + map.set(key, g); + } + g.points.push(p); + g.online ||= p.online; + g.ts = Math.max(g.ts, p.ts); + } + return [...map.values()]; + } + + private draw() { + if (!this.map || !this.data || !this.map.getSource('dl-arcs')) return; + const data = this.data; + const groups = this.groups(visiblePoints(data, this.range)); + const home = data.geo.home; + for (const m of this.markers) m.remove(); + this.markers = []; + + // Operators in the same city sit side by side so every marker stays clickable. + const perCity = new Map(); + const placed = groups.map((g) => { + const c = `${g.lat.toFixed(2)},${g.lon.toFixed(2)}`; + const n = perCity.get(c) ?? 0; + perCity.set(c, n + 1); + return { g, at: [g.lon + n * 0.25, g.lat] as [number, number] }; + }); + + this.map.getSource('dl-areas').setData({ + type: 'FeatureCollection', + features: placed.map(({ g, at }) => ({ + type: 'Feature', + properties: { online: g.online }, + geometry: { type: 'Point', coordinates: at }, + })), + }); + this.map.getSource('dl-arcs').setData({ + type: 'FeatureCollection', + features: home + ? placed.map(({ g, at }) => ({ + type: 'Feature', + properties: { online: g.online }, + geometry: { type: 'LineString', coordinates: arc([home.lon, home.lat], at) }, + })) + : [], + }); + + if (home) { + const el = E('div', { + class: 'dl-mk-home', + title: `Home router${home.city ? ` · ${home.city}` : ''}${home.org ? ` · ${home.org}` : ''}`, + }); + el.innerHTML = iconSvg('home', 'dl-mk-home-ic'); + this.markers.push(new this.gl.Marker({ element: el }).setLngLat([home.lon, home.lat]).addTo(this.map)); + } + + for (const { g, at } of placed) { + const n = g.points.length; + const el = E( + 'button', + { + type: 'button', + class: `dl-mk${g.online ? ' online' : ''}${n > 1 ? ' multi' : ''}`, + 'aria-label': `${n} device${n === 1 ? '' : 's'} via ${g.org || 'unknown network'} in ${g.city || 'unknown city'}`, + }, + n > 1 ? E('span', { class: 'dl-mk-count' }, String(n)) : E('span', { class: 'dl-mk-dot' }), + ); + const nearHome = !!home && Math.abs(at[0] - home.lon) < 0.02 && Math.abs(at[1] - home.lat) < 0.02; + const shift: [number, number] = nearHome ? [22, -16] : [0, 0]; + el.addEventListener('click', (ev) => { + ev.stopPropagation(); + this.openPopup(g, at, shift); + }); + this.markers.push(new this.gl.Marker({ element: el, offset: shift }).setLngLat(at).addTo(this.map)); + } + + if (!this.fitted) { + const coords: [number, number][] = placed.map((x) => x.at); + if (home && (coords.length === 0 || this.range !== 'online' || placed.some((x) => x.g.online))) coords.push([home.lon, home.lat]); + this.fit(coords); + this.fitted = true; + } + this.status.textContent = placed.length || home ? '' : 'No locations yet'; + this.status.style.display = this.status.textContent ? '' : 'none'; + } + + /** + * Zoom to what matters: a single city fills the map at city level, a few + * places get just enough room, and lone outliers never shrink everything to + * a continent (the farthest 10% are left out when the rest are clustered). + */ + private fit(coords: [number, number][]) { + if (!coords.length) return; + const km = (a: [number, number], b: [number, number]) => { + const r = Math.PI / 180; + const dLat = (b[1] - a[1]) * r, + dLon = (b[0] - a[0]) * r; + const h = Math.sin(dLat / 2) ** 2 + Math.cos(a[1] * r) * Math.cos(b[1] * r) * Math.sin(dLon / 2) ** 2; + return 12742 * Math.asin(Math.sqrt(h)); + }; + const center: [number, number] = [ + coords.reduce((s, c) => s + c[0], 0) / coords.length, + coords.reduce((s, c) => s + c[1], 0) / coords.length, + ]; + let pts = coords; + if (coords.length >= 5) { + const sorted = [...coords].sort((a, b) => km(center, a) - km(center, b)); + pts = sorted.slice(0, Math.ceil(sorted.length * 0.9)); + } + const spread = Math.max(...pts.map((c) => km(center, c))); + if (spread < 25) { + // Everyone in one city: show the city, accuracy zones included. + this.map.jumpTo({ center, zoom: 9.5 }); + return; + } + const b = new this.gl.LngLatBounds(pts[0], pts[0]); + pts.forEach((c) => b.extend(c)); + const h = this.el.clientHeight || 380; + this.map.fitBounds(b, { + padding: { top: Math.min(90, h / 4), bottom: Math.min(70, h / 5), left: 60, right: 60 }, + maxZoom: 9, + duration: 0, + }); + } + + private openPopup(g: Group, at: [number, number], shift: [number, number] = [0, 0]) { + const data = this.data!; + this.popup?.remove(); + const where = [g.city, g.cc || g.country].filter(Boolean).join(', '); + const people = [...new Set(g.points.map((p) => p.person))]; + const rows = g.points + .sort((a, b) => Number(b.online) - Number(a.online) || b.ts - a.ts) + .map((p) => { + const person = data.people.find((x) => x.id === p.person); + const dev = person?.devices.find((d) => d.id === p.device); + return E('button', { type: 'button', class: 'dl-pop-row', click: () => this.cb.openDevice(p.person, p.device) }, [ + E('span', { class: `dl-pop-dot${p.online ? ' on' : ''}` }), + E('span', { class: 'dl-pop-name' }, [E('b', {}, person?.name ?? p.person), ` · ${dev?.name ?? 'device'}`]), + E('span', { class: 'dl-faint dl-nowrap' }, p.online ? 'now' : ago(p.ts, data.now)), + ]); + }); + const body = E('div', { class: 'dl-pop' }, [ + E('div', { class: 'dl-pop-head' }, [ + E('span', { class: 'dl-pop-net' }, icon('globe')), + E('div', { class: 'dl-stack' }, [ + E('strong', {}, g.org || 'Unknown network'), + E('span', { class: 'dl-faint' }, [g.asn ? `AS${g.asn} · ` : '', where ? `${where} · approximate` : 'approximate location']), + ]), + ]), + E('div', { class: 'dl-pop-list' }, rows), + people.length === 1 + ? E('div', { class: 'dl-pop-actions' }, [ + E( + 'button', + { type: 'button', class: 'cbi-button cbi-button-positive important', click: () => this.cb.openPerson(people[0]) }, + `Open ${data.people.find((x) => x.id === people[0])?.name ?? 'person'}`, + ), + ]) + : '', + ]); + // Make room above the marker so the popup is never cut by the map edge. + const h = this.el.clientHeight || 380; + this.map.easeTo({ center: at, offset: [0, Math.min(140, h * 0.32)], duration: 300 }); + this.popup = new this.gl.Popup({ + offset: [shift[0], shift[1] - 18], + anchor: 'bottom', + closeButton: false, + focusAfterOpen: false, + maxWidth: '300px', + className: 'dl-popup', + }) + .setLngLat(at) + .setDOMContent(body) + .addTo(this.map); + } +} + +interface Group { + key: string; + lat: number; + lon: number; + city: string; + country: string; + cc: string; + asn: number; + org: string; + online: boolean; + ts: number; + points: GeoPoint[]; +} + +/** Segmented range control for the map header. */ +export function rangeControl(initial: Range, onChange: (r: Range) => void, online = true): HTMLElement { + const opts: [Range, string][] = [ + ['online', 'Online now'], + ['24h', '24h'], + ['7d', '7 days'], + ['30d', '30 days'], + ]; + const el = E('div', { class: 'dl-seg', role: 'tablist' }); + for (const [v, label] of opts) { + if (v === 'online' && !online) continue; + el.appendChild( + E( + 'button', + { + type: 'button', + role: 'tab', + class: v === initial ? 'on' : '', + 'data-v': v, + click: () => { + el.querySelectorAll('button').forEach((b) => b.classList.toggle('on', b.dataset.v === v)); + onChange(v); + }, + }, + label, + ), + ); + } + return el; +} diff --git a/web/src/admin/pages/activity.ts b/web/src/admin/pages/activity.ts new file mode 100644 index 0000000..78c9444 --- /dev/null +++ b/web/src/admin/pages/activity.ts @@ -0,0 +1,196 @@ +// Activity: the full event log, grouped by day, with filters, search, +// export and clearing. + +import type { LogEvent, Status } from '../../shared/types'; +import { E } from '../e'; +import { api, type LogCategory, type LogsInfo } from '../api'; +import { button, dropdown } from '../ui'; +import { icon } from '../../shared/icons'; +import { installPalette } from '../palette'; +import { CATEGORIES, CATEGORY_LABEL, categoryOf, clearLogDialog, exportEvents } from '../logs'; +import { eventRow, eventText } from './overview'; + +type Kind = 'all' | LogCategory; +type Loaded = [Status, Awaited>]; + +/** Rows painted at a time; "Show more" adds another page. */ +const PAGE = 300; + +function dayTitle(ts: number): string { + const d = new Date(ts * 1000); + const today = new Date(); + const y = new Date(); + y.setDate(today.getDate() - 1); + if (d.toDateString() === today.toDateString()) return 'Today'; + if (d.toDateString() === y.toDateString()) return 'Yesterday'; + return d.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' }); +} + +export function retentionText(p: LogsInfo['policy']): string { + const age = p.keep_days > 0 ? `${p.keep_days} day${p.keep_days === 1 ? '' : 's'}` : 'no age limit'; + const where = + p.persist === 'off' + ? 'kept in memory only (lost on reboot)' + : `saved to flash ${p.persist === '10min' ? 'every 10 minutes' : 'hourly'}`; + return `Kept for ${age}, up to ${p.max.toLocaleString('en-GB')} events, ${where}.`; +} + +export class ActivityPage { + st!: Status; + events: LogEvent[] = []; + policy!: LogsInfo['policy']; + kind: Kind = 'all'; + query = ''; + shown = PAGE; + list = E('div', {}); + sub = E('span', { class: 'dl-muted' }); + tabs = E('div', { class: 'dl-seg', role: 'tablist' }); + + async load(): Promise { + return Promise.all([api.status(1), api.events(20000)]); + } + + render([st, ev]: Loaded): HTMLElement { + this.st = st; + this.take(ev); + installPalette(st); + const search = E('input', { + type: 'search', + class: 'dl-search-input', + placeholder: 'Search people, devices, IPs', + input: (e: Event) => { + this.query = (e.target as HTMLInputElement).value.trim().toLowerCase(); + this.shown = PAGE; + this.paint(); + }, + }); + const exp = button([icon('download'), ' Export'], () => + dropdown(exp, [ + { + label: 'CSV (spreadsheet)', + icon: icon('download'), + run: () => exportEvents(this.st, this.filtered().reverse(), 'csv', this.kind === 'all' ? '' : this.kind), + }, + { + label: 'JSON', + icon: icon('download'), + run: () => exportEvents(this.st, this.filtered().reverse(), 'json', this.kind === 'all' ? '' : this.kind), + }, + ]), + ); + const clear = button([icon('trash'), ' Clear'], () => + clearLogDialog( + 'Clear activity', + 'Removes events from the log on the router.', + {}, + () => this.reload(), + this.kind === 'all' ? undefined : this.kind, + ), + ); + this.paint(); + poll.add(async () => { + const r = await api.events(20000).catch(() => null); + if (r) { + this.take(r); + this.paint(); + } + }, 15); + return E('div', {}, [ + E('div', { class: 'dl-pagehead' }, [ + E('div', { class: 'dl-stack' }, [E('h2', { class: 'dl-h1' }, 'Activity'), this.sub]), + E('div', { class: 'dl-row-actions' }, [exp, clear]), + ]), + E('div', { class: 'dl-toolbar' }, [ + this.tabs, + E('span', { class: 'dl-spacer' }), + E('label', { class: 'dl-search' }, [icon('search'), search]), + ]), + this.list, + ]); + } + + take(r: Awaited>) { + this.events = r.events; + this.policy = r.policy; + const off = CATEGORIES.filter((c) => !r.policy.categories.includes(c)); + this.sub.textContent = `${retentionText(r.policy)}${off.length ? ` Not recorded: ${off.map((c) => CATEGORY_LABEL[c].toLowerCase()).join(', ')}.` : ''}`; + } + + async reload() { + const r = await api.events(20000).catch(() => null); + if (r) { + this.take(r); + this.paint(); + } + } + + /** Newest first, matching the current tab and search. */ + filtered(): LogEvent[] { + return [...this.events].reverse().filter((e) => { + if (this.kind !== 'all' && categoryOf(e.type) !== this.kind) return false; + if (!this.query) return true; + const text = eventText(this.st, e) + .map((n) => n.textContent ?? '') + .join(' '); + return `${text} ${e.detail ?? ''} ${e.where ?? ''}`.toLowerCase().includes(this.query); + }); + } + + paintTabs() { + const count = (k: Kind) => (k === 'all' ? this.events.length : this.events.filter((e) => categoryOf(e.type) === k).length); + dom.content( + this.tabs, + (['all', ...CATEGORIES] as Kind[]).map((k) => + E( + 'button', + { + type: 'button', + role: 'tab', + class: k === this.kind ? 'on' : '', + click: () => { + this.kind = k; + this.shown = PAGE; + this.paint(); + }, + }, + [k === 'all' ? 'All' : CATEGORY_LABEL[k], E('b', {}, String(count(k)))], + ), + ), + ); + } + + paint() { + this.paintTabs(); + const evs = this.filtered(); + if (!evs.length) { + dom.content(this.list, E('div', { class: 'dl-empty' }, [E('p', {}, this.events.length ? 'No events match.' : 'The log is empty.')])); + return; + } + const groups: HTMLElement[] = []; + let day = ''; + let panel: HTMLElement | null = null; + for (const e of evs.slice(0, this.shown)) { + const t = dayTitle(e.ts); + if (t !== day) { + day = t; + panel = E('div', { class: 'dl-panel flush' }, E('div', { class: 'dl-panel-head pad' }, E('h3', {}, t))); + groups.push(panel); + } + const row = eventRow(this.st, e); + row.lastElementChild!.textContent = new Date(e.ts * 1000).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }); + panel!.appendChild(row); + } + if (evs.length > this.shown) + groups.push( + E( + 'div', + { class: 'dl-more-row' }, + button(`Show ${Math.min(PAGE, evs.length - this.shown)} more of ${evs.length - this.shown}`, () => { + this.shown += PAGE; + this.paint(); + }), + ), + ); + dom.content(this.list, groups); + } +} diff --git a/web/src/admin/pages/maintenance.ts b/web/src/admin/pages/maintenance.ts new file mode 100644 index 0000000..95c8525 --- /dev/null +++ b/web/src/admin/pages/maintenance.ts @@ -0,0 +1,356 @@ +// Health and Updates pages. + +import type { HealthCheck } from '../../shared/types'; +import { E } from '../e'; +import { api, type AwgSource, type Needs, type UpdatesStatus } from '../api'; +import { installFeature } from '../pkgs'; +import { attempt, button, callout, confirmDialog } from '../ui'; +import { icon } from '../../shared/icons'; +import { clock } from '../../shared/format'; + +const ICON: Record = { ok: 'check', warn: 'alert', error: 'x', skip: 'pause' }; +const FIX_LABEL: Record = { apply: 'Repair', sync: 'Reload devices', restart: 'Restart service', updates: 'Open updates' }; + +export class HealthPage { + root!: HTMLElement; + + load() { + return api.health(); + } + + render(r: { checks: HealthCheck[] }) { + this.root = E('div', { class: 'dl-root' }); + this.paint(r.checks); + return E('div', {}, [ + E('h2', {}, 'Health'), + E( + 'div', + { class: 'cbi-map-descr' }, + 'Everything Dawnline depends on, checked live. Problems come with a fix button where one exists.', + ), + this.root, + ]); + } + + paint(checks: HealthCheck[]) { + const bad = checks.filter((c) => c.status === 'error').length; + const warn = checks.filter((c) => c.status === 'warn').length; + dom.content(this.root, [ + bad + ? callout('error', `${bad} problem${bad > 1 ? 's' : ''} need attention.`) + : warn + ? callout('warn', `${warn} warning${warn > 1 ? 's' : ''}.`) + : callout('ok', 'All checks passed.'), + E('div', { class: 'dl-panel' }, [ + E('div', { class: 'dl-panel-head' }, [ + E('h3', {}, 'Checks'), + E('span', { class: 'dl-spacer' }), + button('Run again', async () => { + const r = await attempt(() => api.health()); + if (r) this.paint(r.checks); + }), + ]), + E( + 'ul', + { class: 'dl-checks' }, + checks.map((c) => + E('li', {}, [ + E('span', { class: `dl-check-icon ${c.status}` }, icon(ICON[c.status])), + E('div', { class: 'dl-check-body' }, [ + E('div', { class: 'dl-check-title' }, c.title), + E('div', { class: 'dl-check-detail' }, c.detail), + ]), + c.fix + ? c.fix.startsWith('install:') + ? button( + 'Install', + () => + installFeature(c.fix!.slice(8) as keyof Needs, async () => { + const r = await api.health().catch(() => null); + if (r) this.paint(r.checks); + }), + 'action', + ) + : c.fix === 'updates' + ? E('a', { class: 'cbi-button cbi-button-action', href: L.url('admin/network/dawnline/updates') }, FIX_LABEL.updates) + : button( + FIX_LABEL[c.fix] ?? 'Fix', + async () => { + const r = await attempt(() => api.healthFix(c.fix!), 'Done'); + if (r) this.paint(r.checks); + }, + 'action', + ) + : '', + ]), + ), + ), + ]), + ]); + } +} + +/** What Dawnline adds to OpenWrt; the portal's HTTPS and certificates only matter while it is on. */ +const SYS_ITEMS: { title: string; sub: string; pkgs: string[]; feature: keyof Needs; optional?: boolean }[] = [ + { 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: true }, +]; + +export class UpdatesPage { + root!: HTMLElement; + running = false; + + load() { + return api.updatesStatus(); + } + + render(st: UpdatesStatus) { + this.root = E('div', { class: 'dl-root dl-upd' }); + this.paint(st); + poll.add(async () => { + const n = await api.updatesStatus().catch(() => null); + if (n && n.job?.state === 'running') this.paint(n); + else if (n && this.running) { + this.running = false; + this.paint(n); + // A new Dawnline is installed: load its pages instead of running the old bundle. + if (n.job?.component === 'app' && n.job.state === 'done') setTimeout(() => location.reload(), 1500); + } + }, 3); + return this.root; + } + + paint(st: UpdatesStatus) { + const job = st.job; + this.running = job?.state === 'running'; + const c = st.check?.components ?? {}; + const fw = st.firmware; + const app = c.app, + awg = c.amneziawg, + pk = c.packages; + const busy = { disabled: this.running }; + const pill = (tone: '' | 'ok' | 'accent' | 'warn' | 'bad', text: string) => E('span', { class: `dl-pill ${tone}` }, text); + const row = (title: Node | string | (Node | string)[], sub: Node | string | (Node | string)[], right: Node | string) => + E('div', { class: 'dl-upd-row' }, [ + E('span', { class: 'dl-stack' }, [E('span', { class: 'dl-upd-name' }, title), E('span', { class: 'dl-sub' }, sub)]), + right, + ]); + const sec = (ic: string, title: string, sub: string, right: Node | string, rows: Node[] = []) => + E('section', { class: 'dl-setsec dl-upd-sec' }, [ + E('div', { class: 'dl-upd-head' }, [ + E('span', { class: 'dl-group-ic' }, icon(ic)), + E('span', { class: 'dl-stack' }, [E('b', {}, title), E('span', { class: 'dl-sub' }, sub)]), + right, + ]), + ...rows, + ]); + const date = (d: string | null) => + d ? new Date(d).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }) : ''; + + // Dawnline + const appSec = sec( + 'sunrise', + 'Dawnline', + app?.repo ? `${st.version} · ${app.repo}` : st.version, + !app + ? pill('', 'Not checked') + : app.update + ? button(`Update to ${app.latest}`, () => this.run('app'), 'positive', busy) + : app.latest + ? pill('ok', 'Up to date') + : pill('', 'No releases yet'), + ); + + // AmneziaWG: one row per build source, then the translation + const srcs = awg?.sources ?? {}; + const ids = Object.keys(srcs) as AwgSource[]; + const awgRows = ids.map((id) => { + const x = srcs[id]!; + const mine = awg?.current === id; + const sub: (Node | string)[] = [ + x.version + ? `${x.tag} build${x.date ? ` · ${date(x.date)}` : ''} · ${x.gen === '3.1' ? 'devices need AmneziaVPN with 3.1' : 'works with every AmneziaWG app'}` + : `No build for OpenWrt ${fw?.version ?? ''}`, + ]; + const right = !x.version + ? pill('', 'No build') + : mine + ? awg?.update + ? button('Update', () => this.runAwg(id, !!awg.ru, x.gen), 'positive', busy) + : pill('ok', 'Installed') + : button('Switch', () => this.runAwg(id, !!awg?.ru, x.gen), 'neutral', busy); + return row([x.gen ? `AmneziaWG ${x.gen}` : 'AmneziaWG', E('span', { class: 'dl-faint' }, ` · ${x.label}`)], sub, right); + }); + if (awg?.current && srcs[awg.current]?.version) + awgRows.push( + row( + 'Russian translation', + 'LuCI pages for AmneziaWG in Russian', + button(awg.ru ? 'Remove' : 'Add', () => this.runAwg(awg.current!, !awg.ru, awg.gen), 'neutral', busy), + ), + ); + const awgSec = sec( + 'shield', + 'AmneziaWG', + awg?.installed ? `${awg.gen ? `${awg.gen} · ` : ''}${awg.installed} · changing it restarts every tunnel` : 'Not installed', + !awg ? pill('', 'Not checked') : '', + awgRows.length ? awgRows : [row('Builds for this router', 'Check for updates to see them.', '')], + ); + + // System packages: one row per thing Dawnline adds + const pkgs = pk?.pkgs ?? {}; + const rows: Node[] = []; + // Only what the features in use need: the home-like link, and HTTPS and certificates while the portal is on. + const items = SYS_ITEMS.filter((it) => (it.feature === 'home' ? st.home : st.portal)); + for (const it of items) { + const present = it.pkgs.filter((p) => pkgs[p]?.installed); + // The package itself and what is released with it (the rest of LuCI, libopenssl, rpcd) + const upd = [...new Set(present.flatMap((p) => [...(pkgs[p]?.latest ? [p] : []), ...(pkgs[p]?.with ?? [])]))]; + // What the router lacks for this feature (any TLS module counts for HTTPS, not only OpenSSL's). + const lacks = st.needs?.[it.feature] ?? it.pkgs.filter((p) => !pkgs[p]?.installed); + if (lacks.length) { + rows.push( + row( + it.title, + it.optional ? `Not installed · ${it.sub}` : E('span', { class: 'dl-upd-bad' }, `Missing ${lacks.join(', ')} · ${it.sub}`), + button('Install', () => this.runPkgs(lacks, it.title), 'neutral', busy), + ), + ); + } else if (upd.length) { + const main = present.find((p) => pkgs[p]?.latest); + const v: (Node | string)[] = main + ? [E('span', { class: 'dl-mono' }, [`${pkgs[main]!.installed} → `, E('b', {}, pkgs[main]!.latest!)])] + : []; + const rel = upd.filter((p) => p !== main); + if (rel.length) + v.push( + `${main ? ' · ' : ''}${rel.length <= 2 ? `${main ? 'with ' : ''}${rel.join(', ')}` : `${main ? '+' : ''}${rel.length} related packages`}`, + ); + rows.push( + row( + it.title, + v, + button( + 'Update', + () => + this.runPkgs( + present.filter((p) => pkgs[p]?.latest || pkgs[p]?.with?.length), + it.title, + upd, + ), + 'neutral', + busy, + ), + ), + ); + } else rows.push(row(it.title, it.sub, pill('ok', 'Up to date'))); + } + const shown = items.flatMap((it) => it.pkgs).filter((k) => pkgs[k]?.installed); + const allUpd = [...new Set(shown.flatMap((k) => [...(pkgs[k].latest ? [k] : []), ...(pkgs[k].with ?? [])]))]; + const pkgSec = sec( + 'package', + 'System packages', + !pk + ? 'What Dawnline adds to OpenWrt' + : allUpd.length + ? `${allUpd.length} update${allUpd.length === 1 ? '' : 's'} from the OpenWrt ${fw?.version?.replace(/\.\d+$/, '') ?? ''} feeds` + : 'What Dawnline adds to OpenWrt is current', + !pk + ? pill('', 'Not checked') + : allUpd.length + ? button( + 'Update all', + () => + this.runPkgs( + shown.filter((k) => pkgs[k].latest || pkgs[k].with?.length), + 'all packages', + allUpd, + ), + 'positive', + busy, + ) + : '', + pk ? rows : [], + ); + + // The last job, folded + const jobCard = job + ? E('details', { class: 'dl-params dl-upd-job', open: this.running ? 'open' : null }, [ + E('summary', {}, [ + icon('chevron'), + E('span', {}, 'Last job'), + pill( + job.state === 'done' ? 'ok' : job.state === 'failed' ? 'bad' : 'warn', + job.state === 'running' ? job.phase || 'Running' : job.state === 'done' ? 'Finished' : 'Failed', + ), + E( + 'span', + { class: 'dl-sub' }, + `${job.action === 'check' ? 'check' : (job.component ?? '')} · ${clock(job.started)}${job.finished ? ` · ${job.finished - job.started} s` : ''}`, + ), + ]), + job.error ? callout('error', job.error) : '', + E('pre', { class: 'dl-log' }, job.log.join('\n')), + ]) + : ''; + + const total = allUpd.length + (app?.update ? 1 : 0) + (awg?.update ? 1 : 0); + const facts = [ + fw?.version ? `OpenWrt ${fw.version} · ${fw.target}` : '', + st.check ? (total ? `${total} update${total === 1 ? '' : 's'} ready` : 'everything is current') : 'not checked yet', + st.check ? `checked ${clock(st.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' }, facts)]), + button([icon('refresh'), ' Check now'], () => this.run('check'), 'neutral', busy), + ]), + appSec, + awgSec, + pkgSec, + jobCard, + ]); + } + + async runAwg(id: AwgSource, ru: boolean, gen: string | null | undefined) { + const ok = await confirmDialog( + gen ? `Install AmneziaWG ${gen}?` : 'Install AmneziaWG?', + 'Every AmneziaWG tunnel on the router restarts for a few seconds, HomeTunnel too. Devices stay configured.', + 'Install', + ); + if (ok) this.start(`amneziawg:${id}${ru ? ':ru' : ''}`); + } + + /** names: Dawnline's own packages (the updater adds their family); shown: everything that will change. */ + async runPkgs(names: string[], what: string, shown = names) { + const ok = await confirmDialog( + `Update ${what}?`, + `${shown.join(', ')} from the OpenWrt feeds. Services that use them restart for a moment.`, + 'Update', + ); + if (ok) this.start(`pkgs:${names.join(',')}`); + } + + async run(what: string) { + if (what !== 'check') { + const ok = await confirmDialog( + `Update ${what === 'app' ? 'Dawnline' : what}?`, + 'A backup is made first. The page reloads when it finishes.', + 'Update', + ); + if (!ok) return; + } + this.start(what); + } + + async start(what: string) { + if (await attempt(() => api.updatesRun(what))) { + this.running = true; + const n = await api.updatesStatus().catch(() => null); + if (n) this.paint(n); + } + } +} diff --git a/web/src/admin/pages/overview.ts b/web/src/admin/pages/overview.ts new file mode 100644 index 0000000..de13e4c --- /dev/null +++ b/web/src/admin/pages/overview.ts @@ -0,0 +1,605 @@ +// A server's Overview section (first tab on the Servers page): who is +// online, traffic, disguise, the connection map, activity and what needs +// attention — all limited to the people on that server. + +import type { DayUsage, Device, LogEvent, Person, Status } from '../../shared/types'; +import { E } from '../e'; +import { api } from '../api'; +import { svg } from '../ui'; +import { icon } from '../../shared/icons'; +import { ago, bits, bytes, daysLeft, initials } from '../../shared/format'; +import { ConnectionMap, rangeControl, type Range } from '../map'; +import { attachTip } from '../charts'; +import { methodInfo } from '../disguise'; +import { personUrl } from '../palette'; + +const EVENT_TONE: Record = { + connect: 'ok', + disconnect: '', + roam: '', + device_added: 'accent', + device_removed: '', + person_added: '', + person_removed: '', + paused: 'warn', + resumed: 'ok', + paused_all: 'warn', + resumed_all: 'ok', + server_down: 'bad', + server_up: 'ok', + portal_blocked: 'bad', + person_changed: '', + devices_removed: 'warn', +}; + +export function eventText(st: Status, e: LogEvent): Node[] { + const person = st.people.find((p) => p.id === e.person); + const who = person?.name ?? e.person ?? ''; + const dev = person?.devices.find((d) => d.id === e.device)?.name ?? ''; + const b = (t: string) => E('b', {}, t); + const m = (t: string) => E('span', { class: 'dl-muted' }, t); + const mono = (t: string) => E('span', { class: 'dl-mono' }, t); + const wd = dev ? `${who} · ${dev}` : who; + switch (e.type) { + case 'connect': + return [b(wd), m(' connected'), ...(e.detail ? [m(' from '), mono(e.detail)] : []), ...(e.where ? [m(` · ${e.where}`)] : [])]; + case 'disconnect': + return [b(wd), m(' went offline')]; + case 'roam': + return [b(wd), m(' changed network '), mono(e.detail ?? '')]; + case 'device_added': + return [b(who), m(' added '), E('span', {}, e.detail ?? 'a device')]; + case 'device_removed': + return [b(who), m(' removed '), E('span', {}, e.detail ?? 'a device')]; + case 'person_added': + return [m('You added '), b(e.detail ?? who)]; + case 'person_removed': + return [m('You removed '), b(e.detail ?? who)]; + case 'person_changed': + return [m('You changed '), b(who), m(` · ${e.detail ?? ''}`)]; + case 'paused': + return [b(who), m(` paused — ${e.detail ?? ''}`)]; + case 'resumed': + return [b(who), m(' resumed'), ...(e.detail && e.detail !== 'active' ? [m(` — ${e.detail}`)] : [])]; + case 'paused_all': + return [m('Everyone paused')]; + case 'resumed_all': + return [m('Everyone resumed')]; + case 'server_down': + return [m('Tunnel '), mono(e.detail ?? ''), m(' went down')]; + case 'server_up': + return [m('Tunnel '), mono(e.detail ?? ''), m(' is back up')]; + case 'portal_blocked': + return [m('Portal blocked '), mono(e.detail ?? ''), m(' for 15 min after too many wrong codes')]; + case 'devices_removed': + return [b(who), m('’s devices were removed — end date reached')]; + default: + return [m(`${e.type}${e.detail ? `: ${e.detail}` : ''}`)]; + } +} + +export function eventRow(st: Status, e: LogEvent): HTMLElement { + return E('div', { class: 'dl-row' }, [ + E('span', { class: `dl-ev-dot ${EVENT_TONE[e.type] ?? ''}` }), + E('span', { class: 'dl-row-main' }, eventText(st, e)), + E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, ago(e.ts, st.now)), + ]); +} + +/** Things worth the admin's attention, most important first. */ +function attention(st: Status): { tone: string; text: (Node | string)[] }[] { + const out: { tone: string; text: (Node | string)[] }[] = []; + const link = (href: string, t: string) => E('a', { href }, t); + for (const s of st.servers) + if (s.enabled && !s.up) + out.push({ tone: 'bad', text: [`Tunnel ${s.ifname} is down. `, link(L.url('admin/network/dawnline/health'), 'Open Health')] }); + if (st.settings.paused_all) out.push({ tone: 'warn', text: ['Everyone is paused.'] }); + for (const p of st.people) { + if (p.state === 'quota') out.push({ tone: 'warn', text: [link(personUrl(p.id), p.name), ' reached the data limit.'] }); + else if (p.state === 'expired') out.push({ tone: 'warn', text: [link(personUrl(p.id), p.name), '’s access has ended.'] }); + else { + const left = daysLeft(p.expires); + if (left != null && left >= 0 && left <= Math.max(p.expire_warn, 3)) + out.push({ tone: '', text: [link(personUrl(p.id), p.name), `’s access ends in ${left} day${left === 1 ? '' : 's'}.`] }); + if (p.quota_limit && p.quota_used >= p.quota_limit * 0.9) + out.push({ tone: '', text: [link(personUrl(p.id), p.name), ' has used 90% of the data limit.'] }); + } + } + const stale = st.people.flatMap((p) => p.devices.filter((d) => d.config_stale).map((d) => [p, d] as const)); + if (stale.length) + out.push({ + tone: 'warn', + text: + stale.length === 1 + ? [ + link(personUrl(stale[0][0].id, stale[0][1].id), `${stale[0][0].name} · ${stale[0][1].name}`), + ' needs its configuration again.', + ] + : [`${stale.length} devices need their configuration again (networks or DNS changed).`], + }); + if (st.servers.some((s) => s.lan_like) && st.like_home.error) + out.push({ + tone: 'warn', + text: [`Internet through the LAN is off: ${st.like_home.error} `, link(L.url('admin/network/dawnline/health'), 'Details')], + }); + if (!st.settings.portal_enabled) + out.push({ tone: '', text: ['The personal portal is off. ', link(L.url('admin/network/dawnline/settings'), 'Turn on')] }); + return out; +} + +/** + * The status as seen from one server: its people, their devices, traffic, + * map points and events (plus router-wide events without a person). + */ +export function scoped(st: Status, srvId: string): Status { + const srv = st.servers.find((s) => s.id === srvId) ?? st.servers[0]; + const people = st.people.filter((p) => p.server === srv.id); + const ids = new Set(people.map((p) => p.id)); + const devices = people.flatMap((p) => p.devices); + const sum = (f: (p: Person) => [number, number]) => + people.reduce<[number, number]>( + (a, p) => { + const v = f(p); + return [a[0] + v[0], a[1] + v[1]]; + }, + [0, 0], + ); + const today = srv.series?.[srv.series.length - 1]; + return { + ...st, + servers: [srv], + people, + series: srv.series ?? st.series, + events: st.events.filter((e) => (e.person ? ids.has(e.person) : true)), + geo: { ...st.geo, points: st.geo.points.filter((g) => ids.has(g.person)) }, + totals: { + people: people.length, + devices: devices.length, + online: devices.filter((d) => d.online).length, + active: people.filter((p) => p.state === 'active').length, + today: today ? [today.rx, today.tx] : [0, 0], + month: sum((p) => p.month), + }, + }; +} + +export class ServerOverview { + st!: Status; + el = E('div', { class: 'dl-srvov' }); + map: ConnectionMap | null = null; + range: Range = 'online'; + parts: Record = {}; + healthAt = 0; + + /** `go` switches the Servers page to another section in place. */ + constructor( + readonly srvId: string, + private go?: (section: string, filter?: string) => void, + ) {} + + /** Build once; later calls to update() keep the map instance. */ + mount(st: Status): HTMLElement { + this.st = scoped(st, this.srvId); + for (const k of ['health', 'bento', 'side', 'activity']) this.parts[k] = E('div', {}); + 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(); + void this.loadHealth(); + return this.el; + } + + update(st: Status) { + this.st = scoped(st, this.srvId); + this.paint(); + this.map?.update(this.mapData()); + // Health checks cost more than a status call: once a minute is plenty. + if (Date.now() - this.healthAt > 60_000) void this.loadHealth(); + } + + /** A strip above the bento, only while Health has warnings or errors. */ + async loadHealth() { + this.healthAt = Date.now(); + const r = await api.health().catch(() => null); + if (!r) return; + const bad = r.checks.filter((c) => c.status === 'warn' || c.status === 'error'); + if (!bad.length) { + dom.content(this.parts.health, ''); + return; + } + const errors = bad.filter((c) => c.status === 'error').length; + const label = `${bad.length} ${errors ? (bad.length === 1 ? 'problem' : 'problems') : bad.length === 1 ? 'warning' : 'warnings'}`; + dom.content( + this.parts.health, + E('div', { class: `dl-healthstrip ${errors ? 'bad' : 'warn'}` }, [ + E('span', { class: 'dl-healthstrip-title' }, [icon('alert'), label]), + ...bad.slice(0, 3).map((c) => { + const it = E('span', { class: 'dl-healthstrip-item' }, c.title); + attachTip(it, () => [E('div', { class: 'dl-tip-title' }, c.title), E('div', { class: 'dl-muted' }, c.detail)]); + return it; + }), + bad.length > 3 ? E('span', { class: 'dl-sub' }, `+${bad.length - 3} more`) : '', + E('a', { href: L.url('admin/network/dawnline/health') }, bad.some((c) => c.fix) ? 'Fix in Health →' : 'Open Health →'), + ]), + ); + } + + mapData() { + return { geo: this.st.geo, people: this.st.people, now: this.st.now }; + } + + mapCard(): HTMLElement { + const st = this.st; + const head = 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' }), + rangeControl(this.range, (r) => { + this.range = r; + this.map?.setRange(r); + }), + ]); + if (!st.geo.enabled) + return E('div', { class: 'dl-panel flush' }, [ + head, + 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 ConnectionMap( + { + openPerson: (id) => (location.href = personUrl(id)), + openDevice: (id, dev) => (location.href = personUrl(id, dev)), + }, + this.range, + ); + const legend = 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']), + ]); + const wrap = E('div', { class: 'dl-map-wrap' }, [this.map.el, legend]); + requestAnimationFrame(() => this.map!.mount(this.mapData())); + return E('div', { class: 'dl-panel flush' }, [head, wrap]); + } + + paint() { + const st = this.st; + const srv = st.servers[0]; + const slots = st.people.reduce((a, p) => a + Math.max(0, p.device_limit - p.devices.length), 0); + const online = st.people.flatMap((p) => p.devices.filter((d) => d.online)); + + dom.content( + this.parts.bento, + E('div', { class: 'dl-bento' }, [this.onlineTile(online), this.speedTile(), this.disguiseTile(srv), this.monthTile(slots)]), + ); + + const att = attention(st); + 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/health') }, 'Health'), + ]), + att.length + ? att + .slice(0, 8) + .map((a) => E('div', { class: 'dl-attn-item dl-row' }, [E('span', { class: `dl-ev-dot ${a.tone}` }), E('span', {}, a.text)])) + : E('div', { class: 'dl-row dl-muted' }, [icon('check'), 'All good. Nothing needs you right now.']), + ]), + ); + + const events = [...st.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/activity') }, 'View all'), + ]), + events.length + ? events.map((e) => eventRow(st, e)) + : E('div', { class: 'dl-row dl-muted' }, 'Nothing yet. Connections, new devices and pauses appear here.'), + ]), + ); + } + + /** + * Who is connected right now, and nothing else. One or two people: avatar, + * name, device icons and city; three or more: a grid of avatars (two rows, + * then +N). The device badge is the main device, or a count. Hover: a live + * card with speed, devices and today's traffic. Nobody: when someone was last seen. + */ + onlineTile(_online: Device[]): HTMLElement { + const st = this.st; + const CAP = 12; + const today = (d: Device) => d.spark[d.spark.length - 1] ?? 0; + const cityOf = (d: Device) => st.geo.points.find((g) => g.device === d.id && g.city)?.city; + const home = (d: Device) => /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(d.endpoint ?? ''); + const where = (d: Device) => (home(d) ? 'home' : cityOf(d)) ?? ''; + const connectedAt = (d: Device) => [...st.events].reverse().find((e) => e.type === 'connect' && e.device === d.id)?.ts ?? 0; + const on = st.people + .map((p) => ({ p, devs: p.devices.filter((d) => d.online).sort((a, b) => today(b) - today(a)) })) + .filter((x) => x.devs.length) + .sort((a, b) => b.devs.reduce((n, d) => n + today(d), 0) - a.devs.reduce((n, d) => n + today(d), 0)); + const big = on.length <= 2; + + const card = ({ p, devs }: { p: Person; devs: Device[] }): Node[] => { + const starts = devs.map(connectedAt).filter(Boolean); + const since = starts.length ? Math.min(...starts) : 0; + const pts = (p.rate ?? []).slice(-15); + const last = pts[pts.length - 1]; + const fresh = last && st.now - last[0] < 180 ? last : null; + const W = 200, + H = 30, + max = Math.max(1, ...pts.map((x) => Math.max(x[1], x[2]))); + const line = (k: 1 | 2) => pts.map((x, i) => `${pts.length > 1 ? (i / (pts.length - 1)) * W : W},${H - 2 - (x[k] / max) * (H - 6)}`); + const chart = + pts.length > 1 + ? svg( + ``, + ) + : ''; + const idle = !fresh || (fresh[1] < 64 && fresh[2] < 64); + const reach = p.access === 'both' ? ['home', 'globe'] : p.access === 'lan' ? ['home'] : ['globe']; + return [ + E('div', { class: 'dl-hc' }, [ + E('div', { class: 'dl-hc-head' }, [ + E('span', { class: 'dl-onl-av sm' }, initials(p.name)), + E('span', { class: 'dl-stack' }, [ + E('b', {}, p.name), + E('span', { class: 'dl-hc-since' }, since ? `online for ${ago(since, st.now).replace(' ago', '')}` : 'online'), + ]), + E( + 'span', + { class: 'dl-hc-reach' }, + reach.map((r) => E('span', { class: `dl-ibadge ${r === 'home' ? 'lan' : 'inet'}` }, icon(r))), + ), + ]), + E('div', { class: 'dl-hc-speed' }, [ + E( + 'div', + { class: 'dl-hc-speed-row' }, + idle + ? [E('span', { class: 'dl-faint' }, 'Idle right now')] + : [ + E('span', {}, [E('span', { class: 'dl-dn' }, '↓'), ` ${bits(fresh![2])}`]), + E('span', {}, [E('span', { class: 'dl-up' }, '↑'), ` ${bits(fresh![1])}`]), + E('span', { class: 'dl-spacer' }), + E('span', { class: 'dl-faint' }, '15 min'), + ], + ), + chart, + ]), + E( + 'div', + { class: 'dl-hc-devs' }, + devs.map((d) => E('span', { class: 'dl-hc-dev' }, [icon(d.kind), [d.name, where(d)].filter(Boolean).join(' · ')])), + ), + E('div', { class: 'dl-hc-foot' }, [ + E( + 'span', + { class: 'dl-faint' }, + `${bytes(devs.reduce((n, d) => n + today(d), 0))} today · ${bytes(p.month[0] + p.month[1])} this month`, + ), + ]), + ]), + ]; + }; + + const person = (x: { p: Person; devs: Device[] }) => { + const { p, devs } = x; + const badge = E('span', { class: 'dl-onl-dev' }, devs.length > 1 ? String(devs.length) : icon(devs[0].kind)); + const el = E('a', { class: `dl-onl-p${big ? '' : ' sm'}`, href: personUrl(p.id), 'aria-label': `${p.name}, online` }, [ + E('span', { class: 'dl-onl-av' }, [initials(p.name), badge]), + big ? E('span', { class: 'dl-onl-name' }, p.name) : '', + big + ? E('span', { class: 'dl-onl-meta' }, [ + ...devs.slice(0, 3).map((d) => icon(d.kind)), + devs.length > 3 ? `+${devs.length - 3}` : '', + where(devs[0]) ? E('span', {}, ` · ${where(devs[0])}`) : '', + ]) + : '', + ]); + attachTip(el, () => card(x)); + return el; + }; + + const count = E('b', { class: `dl-onl-count${on.length ? '' : ' none'}` }, String(on.length)); + const ndev = on.reduce((n, x) => n + x.devs.length, 0); + if (on.length) + attachTip(count, () => [`${on.length} ${on.length === 1 ? 'person' : 'people'} · ${ndev} device${ndev === 1 ? '' : 's'}`]); + const shown = on.length > CAP ? on.slice(0, CAP - 1) : on; + const last = st.people + .flatMap((p) => p.devices.map((d) => ({ p, d }))) + .filter((x) => x.d.handshake) + .sort((a, b) => b.d.handshake - a.d.handshake)[0]; + return E('div', { class: 'dl-bento-tile online' }, [ + E('div', { class: 'dl-bento-head' }, [E('span', { class: 'dl-metric-label' }, 'Online'), count]), + on.length + ? E('div', { class: `dl-onl-row${big ? '' : ' grid'}` }, [ + ...shown.map(person), + on.length > CAP + ? 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: (ev: Event) => { + if (this.go) { + ev.preventDefault(); + this.go('people', 'online'); + } + }, + }, + [E('span', { class: 'dl-onl-av' }, `+${on.length - shown.length}`)], + ) + : '', + ]) + : E('div', { class: 'dl-onl-empty' }, [ + E('span', {}, 'Nobody is connected'), + last + ? E('span', { class: 'dl-sub' }, `Last: ${last.p.name}, ${ago(last.d.handshake, st.now)}`) + : E('span', { class: 'dl-sub' }, 'No device has connected yet'), + ]), + ]); + } + + /** + * Throughput right now (from the agent's minute samples): download and + * upload side by side, the last 15 minutes as a small chart, today's total. + */ + speedTile(): HTMLElement { + return speedTile(this.st.servers[0]?.rate ?? [], this.st.now, this.st.totals.today); + } + + disguiseTile(srv: Status['servers'][number]): 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' : '' })), + ); + // The values devices carry, in words. + 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=disguise` }, '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)), + ), + ]); + } + + /** The last 30 days, today on the right, with the peak; plus the people summary. */ + monthTile(slots: number): HTMLElement { + const t = this.st.totals; + const paused = this.st.people.filter((p) => p.state !== 'active').length; + return daysTile( + this.st.series, + `${t.people} ${t.people === 1 ? 'person' : 'people'}${paused ? ` · ${paused} paused` : ''} · ${slots} device slot${slots === 1 ? '' : 's'} free`, + ); + } +} + +/** Throughput over the last 15 minutes plus today's total. */ +export function speedTile(rate: [number, number, number][], now: number, today: [number, number]): HTMLElement { + const pts = rate.slice(-15); + const last = pts[pts.length - 1]; + const fresh = last && now - last[0] < 180; + const down = fresh ? last[2] : 0, + up = fresh ? last[1] : 0; + const [rx, tx] = today; + const W = 200, + H = 40; + const max = Math.max(1, ...pts.map((p) => Math.max(p[1], p[2]))); + const line = (k: 1 | 2) => pts.map((p, i) => `${pts.length > 1 ? (i / (pts.length - 1)) * W : W},${H - 2 - (p[k] / max) * (H - 6)}`); + const dl = line(2), + ul = line(1); + const chart = + pts.length > 1 + ? svg( + ``, + ) + : E('div', { class: 'dl-speed-wait' }, [E('i'), E('span', {}, 'Collecting… 1 point a minute')]); + const col = (label: string, ic: string, cls: string, v: number) => + E('div', { class: 'dl-speed-col' }, [ + E('span', { class: 'dl-sub' }, [E('span', { class: cls }, ic), ` ${label}`]), + E('span', { class: 'dl-speed-val' }, bits(v)), + ]); + if (pts.length > 1) + attachTip(chart as HTMLElement, () => { + const p = pts[pts.length - 1]; + return [ + E('div', { class: 'dl-tip-title' }, new Date(p[0] * 1000).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })), + E('div', {}, `↓ ${bits(p[2])} · ↑ ${bits(p[1])}`), + ]; + }); + return 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' }, [col('Download', '↓', 'dl-dn', down), col('Upload', '↑', 'dl-up', up)]), + chart, + E('div', { class: 'dl-speed-today' }, [ + E('span', {}, ['Today ', E('b', {}, bytes(rx + tx))]), + E('span', {}, [E('span', { class: 'dl-dn' }, '↓'), ` ${bytes(tx)} `, E('span', { class: 'dl-up' }, '↑'), ` ${bytes(rx)}`]), + ]), + ]); +} + +/** Daily traffic for the last 30 days, today on the right. */ +export function daysTile(series: DayUsage[], note: string): HTMLElement { + const days = series.slice(-30); + const vals = days.map((d) => d.rx + d.tx); + const max = Math.max(1, ...vals); + const total = vals.reduce((a, v) => a + v, 0); + const peakI = vals.reduce((a, v, i) => (v > vals[a] ? i : a), 0); + const label = (day: string) => new Date(`${day}T12:00:00`).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }); + const bars = E( + 'div', + { class: 'dl-bento-bars' }, + days.map((d, i) => { + const v = vals[i]; + const bar = E('i', { class: i === days.length - 1 ? 'hi' : '', style: `height:${Math.max(4, (v / max) * 100)}%` }); + attachTip(bar, () => [ + E('div', { class: 'dl-tip-title' }, i === days.length - 1 ? `Today · ${label(d.day)}` : label(d.day)), + E('div', {}, bytes(v)), + E('div', { class: 'dl-muted dl-mono' }, `↓ ${bytes(d.tx)} ↑ ${bytes(d.rx)}`), + ]); + return bar; + }), + ); + 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' }, bytes(total))]), + vals[peakI] > 0 ? E('span', { class: 'dl-sub' }, `peak ${bytes(vals[peakI])} · ${label(days[peakI].day)}`) : '', + ]), + days.length ? bars : E('p', { class: 'dl-muted' }, 'No traffic yet.'), + E('div', { class: 'dl-bento-head' }, [ + E('span', { class: 'dl-sub' }, days.length ? label(days[0].day) : ''), + E('span', { class: 'dl-sub' }, note), + E('span', { class: 'dl-sub' }, 'today'), + ]), + ]); +} diff --git a/web/src/admin/pages/people.ts b/web/src/admin/pages/people.ts new file mode 100644 index 0000000..62885bf --- /dev/null +++ b/web/src/admin/pages/people.ts @@ -0,0 +1,726 @@ +// People: a native GridSection over `person` sections rendered as cards. +// Edits in the modal are staged (Save & Apply with rollback); creating, +// pausing and device actions take effect immediately through RPC. + +import type { Person, Status } from '../../shared/types'; +import { E } from '../e'; +import { api } from '../api'; +import { attempt, button, closeModal, confirmDialog, copyText, dropdown, iconButton, modal, notify, type MenuItem } from '../ui'; +import { addDevice, openDevice } from '../device'; +import { inviteCard } from '../invite'; +import { installPalette, personUrl } from '../palette'; +import { scoped } from './overview'; +import { attachTip } from '../charts'; +import { icon } from '../../shared/icons'; +import { ACCESS_LABEL, KIND_LABEL, STATE_LABEL, ago, bits, bytes, date, daysLeft, initials } from '../../shared/format'; + +type Sid = string; + +const STATE_ICON: Record = { + active: '', + paused: 'pause', + paused_all: 'pause', + expired: 'calendar', + quota: 'chart', + hours: 'clock', + no_server: 'alert', +}; + +/** Nothing while active; otherwise a small icon with the state as tooltip. */ +export function stateBadge(p: Person): HTMLElement | '' { + if (p.state === 'active') return ''; + const el = E('span', { class: `dl-ibadge ${stateTone(p)}`, 'aria-label': STATE_LABEL[p.state] }, icon(STATE_ICON[p.state] || 'alert')); + attachTip(el, () => [E('div', { class: 'dl-tip-title' }, STATE_LABEL[p.state])]); + return el; +} + +/** What the person can reach, as icons: home network, internet, or both. */ +export function accessBadge(p: Person): HTMLElement { + const kinds = p.access === 'both' ? ['lan', 'inet'] : p.access === 'lan' ? ['lan'] : ['inet']; + const el = E( + 'span', + { class: 'dl-access', 'aria-label': ACCESS_LABEL[p.access] }, + kinds.map((k) => E('span', { class: `dl-ibadge ${k}` }, icon(k === 'lan' ? 'home' : 'globe'))), + ); + attachTip(el, () => [ + E('div', { class: 'dl-tip-title' }, ACCESS_LABEL[p.access]), + p.access === 'lan' && p.services?.length + ? E('div', { class: 'dl-muted' }, `${p.services.length} home service${p.services.length === 1 ? '' : 's'} only`) + : '', + ]); + return el; +} + +export function stateTone(p: Person): string { + if (p.state === 'active') return 'ok'; + if (p.state === 'quota' || p.state === 'expired') return 'bad'; + return 'warn'; +} + +/** Access choice cards; returns the element and a getter. */ +export function accessPicker(initial: Person['access'], onChange?: (v: Person['access']) => void) { + let value = initial; + const opts: { v: Person['access']; ic: string; text: string }[] = [ + { 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.' }, + ]; + const el = E( + 'div', + { class: 'dl-choices' }, + opts.map((o) => + E( + 'button', + { + type: 'button', + class: `dl-choice${o.v === value ? ' selected' : ''}`, + 'data-v': o.v, + click: () => { + value = o.v; + el.querySelectorAll('.dl-choice').forEach((c) => c.classList.toggle('selected', (c as HTMLElement).dataset.v === o.v)); + onChange?.(o.v); + }, + }, + [E('span', { class: 'dl-choice-title' }, [icon(o.ic), ACCESS_LABEL[o.v]]), E('span', { class: 'dl-choice-text' }, o.text)], + ), + ), + ); + return { el, get: () => value }; +} + +function isoDate(d: Date): string { + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; +} + +type Filter = 'all' | 'online' | 'attention' | 'paused'; +type SortBy = 'seen' | 'name' | 'usage'; + +function needsAttention(p: Person): boolean { + const left = daysLeft(p.expires); + return ( + p.state === 'quota' || + p.state === 'expired' || + (left != null && left <= Math.max(p.expire_warn, 3)) || + (!!p.quota_limit && p.quota_used >= p.quota_limit * 0.9) + ); +} + +function addMonth(iso: string): string { + const d = iso ? new Date(`${iso}T12:00:00`) : new Date(); + const from = d.getTime() < Date.now() ? new Date() : d; + from.setMonth(from.getMonth() + 1); + return `${from.getFullYear()}-${String(from.getMonth() + 1).padStart(2, '0')}-${String(from.getDate()).padStart(2, '0')}`; +} + +let addOpened = false; + +export class PeoplePage { + st!: Status; + map: any; + query = ''; + // `?filter=online` (from Overview) preselects a tab. + filter: Filter = + (['all', 'online', 'attention', 'paused'] as Filter[]).find((f) => f === new URLSearchParams(location.search).get('filter')) ?? 'all'; + sort: SortBy = 'seen'; + noFooter = true; + /** Set when shown as a server's People section: only that server's people. */ + serverId: string | null = null; + polling = false; + el: HTMLElement | null = null; + + async load(): Promise { + return api.status(30); + } + + /** The status limited to this page's server (or everything). */ + scope(st: Status): Status { + return this.serverId ? scoped(st, this.serverId) : st; + } + + /** Render as a section of the Servers page. */ + embed(st: Status, serverId: string): Promise { + this.serverId = serverId; + return this.render(st); + } + + person(sid: Sid): Person | undefined { + return this.st.people.find((p) => p.id === sid); + } + + /** + * Status for this page, newest request wins: a poll that started before an + * edit must not paint its older answer over the refresh that follows it. + */ + private statusSeq = 0; + private statusShown = 0; + async latestStatus(): Promise { + const seq = ++this.statusSeq; + const st = await api.status(30).catch(() => null); + if (!st || seq < this.statusShown) return null; + this.statusShown = seq; + return st; + } + + async refresh() { + const st = await this.latestStatus(); + if (!st) return; + this.st = this.scope(st); + uci.unload('dawnline'); + await this.map.load(); + await this.map.reset(); + // The map keeps cards it already drew: paint them from the new status, like poll(). + this.paintCards(); + this.decorate(); + } + + paintCards() { + for (const p of this.st.people) { + const card = document.getElementById(`dl-card-${p.id}`); + if (card) this.renderCard(card, p.id); + } + } + + render(stAll: Status): Promise { + const st = this.scope(stAll); + this.st = st; + const page = this; + let o: any; + + const m = new form.Map('dawnline'); + this.map = m; + + const s = m.section(form.GridSection, 'person'); + s.anonymous = true; + s.addremove = true; + s.addbtntitle = 'Add person'; + s.nodescriptions = true; + s.renderSectionPlaceholder = () => + E( + 'em', + {}, + st.servers.length ? 'No people yet. Add someone and send them their personal link.' : 'Set up the server first, then add people.', + ); + + // As a server section: only rows of people on that server. + if (page.serverId) s.filter = (sid: Sid) => page.st.people.some((p) => p.id === sid); + s.handleAdd = () => page.openCreate(); + s.handleRemove = (sid: Sid) => page.remove(sid); + + // Actions live inside the card (title row). + s.renderRowActions = () => E('div', { class: 'dl-none' }); + + o = s.option(form.DummyValue, '_card'); + o.modalonly = false; + o.textvalue = (sid: Sid) => page.renderCard(E('div', { class: 'dl-card', id: `dl-card-${sid}` }), sid); + + return m.render().then((node: HTMLElement) => { + node.classList.add('dl-map', 'dl-root'); + installPalette(st); + const search = E('input', { + type: 'search', + class: 'dl-search-input', + placeholder: 'Search people, devices, IPs', + input: (ev: Event) => { + page.query = (ev.target as HTMLInputElement).value.trim().toLowerCase(); + page.decorate(); + }, + }); + const sort = E( + 'select', + { + class: 'dl-select', + 'aria-label': 'Sort', + change: (ev: Event) => { + page.sort = (ev.target as HTMLSelectElement).value as SortBy; + page.decorate(); + }, + }, + [E('option', { value: 'seen' }, 'Last seen'), E('option', { value: 'name' }, 'Name'), E('option', { value: 'usage' }, 'Usage')], + ); + const wrap = E('div', { class: 'dl-root' }, [ + page.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()), + ]), + st.servers.length ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '', + ]), + st.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' }), + // Search, sort and add stay together on the right, wrapping as one group. + E('div', { class: 'dl-toolbar-end' }, [ + E('label', { class: 'dl-search' }, [icon('search'), search, E('kbd', {}, '/')]), + sort, + page.serverId ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '', + ]), + ]), + node, + ]); + this.el = wrap; + requestAnimationFrame(() => this.decorate()); + if (!this.polling) { + this.polling = true; + // Only while visible (a server section may be swapped out). + poll.add(() => (page.el?.isConnected ? page.poll() : Promise.resolve()), 10); + } + // ?add=1 opens Add person once, not again on every server's People tab. + if (!addOpened && new URLSearchParams(location.search).get('add')) { + addOpened = true; + setTimeout(() => page.openCreate(), 100); + } + return wrap; + }); + } + + countText(): string { + const t = this.st.totals; + return `${t.people} ${t.people === 1 ? 'person' : 'people'} · ${t.devices} device${t.devices === 1 ? '' : 's'} · ${t.online} online`; + } + + /** Row classes, counters, filter tabs, search and sort order. */ + decorate() { + const c = document.getElementById('dl-people-count'); + if (c) c.textContent = this.countText(); + const people = this.st.people; + const counts: Record = { + all: people.length, + online: people.filter((p) => p.online > 0).length, + attention: people.filter(needsAttention).length, + paused: people.filter((p) => p.state !== 'active' && p.state !== 'quota' && p.state !== 'expired').length, + }; + const tabs = document.getElementById('dl-people-tabs'); + if (tabs) { + const label: Record = { all: 'All', online: 'Online', attention: 'Needs attention', paused: 'Paused' }; + dom.content( + tabs, + (Object.keys(label) as Filter[]).map((f) => + E( + 'button', + { + type: 'button', + role: 'tab', + class: f === this.filter ? 'on' : '', + click: () => { + this.filter = f; + this.decorate(); + }, + }, + [label[f], E('b', { class: f === 'attention' && counts[f] ? 'warn' : '' }, String(counts[f]))], + ), + ), + ); + } + const match = (p: Person) => { + if (this.filter === 'online' && !p.online) return false; + if (this.filter === 'attention' && !needsAttention(p)) return false; + if (this.filter === 'paused' && !(p.state !== 'active' && p.state !== 'quota' && p.state !== 'expired')) return false; + if (!this.query) return true; + const hay = [p.name, p.id, ...p.devices.flatMap((d) => [d.name, d.address, d.endpoint, d.hostname])].join(' ').toLowerCase(); + return hay.includes(this.query); + }; + const order = [...people].sort((a, b) => + this.sort === 'name' + ? a.name.localeCompare(b.name) + : this.sort === 'usage' + ? b.month[0] + b.month[1] - (a.month[0] + a.month[1]) + : b.online - a.online || b.last_seen - a.last_seen, + ); + let tbody: Element | null = null; + let shown = 0; + for (const p of order) { + const card = document.getElementById(`dl-card-${p.id}`); + const row = card?.closest('.cbi-section-table-row') as HTMLElement | null; + if (!row) continue; + tbody ??= row.parentElement; + tbody?.appendChild(row); + row.classList.toggle('dl-off', p.state !== 'active'); + row.classList.toggle('dl-attn-row', p.state === 'quota' || p.state === 'expired'); + // A class, not an inline style: the card layout sets display with !important. + const hit = match(p); + row.classList.toggle('dl-filtered', !hit); + if (hit) shown++; + } + // Say so when the filter or search leaves nobody. + const table = tbody?.closest('.cbi-section-table') ?? tbody; + let none = document.getElementById('dl-people-none'); + if (table && people.length && !shown) { + none ??= E('div', { id: 'dl-people-none', class: 'dl-empty' }); + dom.content(none, E('p', {}, this.query ? `No one matches “${this.query}”.` : 'No one here right now.')); + if (none.parentElement !== table.parentElement) table.after(none); + } else none?.remove(); + } + + async poll() { + const stAll = await this.latestStatus(); + if (!stAll) return; + const st = this.scope(stAll); + this.st = st; + this.paintCards(); + this.decorate(); + } + + async quick(p: Person, patch: Parameters[1], ok: string) { + if (await attempt(() => api.personUpdate(p.id, patch), ok)) await this.poll(); + } + + renderCard(node: HTMLElement, sid: Sid): HTMLElement { + const p = this.person(sid); + if (!p) { + dom.content(node, E('em', {}, 'Not saved yet — use “Save & Apply”.')); + return node; + } + const left = daysLeft(p.expires); + const free = Math.max(0, p.device_limit - p.devices.length); + + // Term and hours sit by the name; online/last seen lives in the strip below. + const pills: Node[] = []; + if (p.expires) { + const soon = left != null && left >= 0 && left <= Math.max(p.expire_warn, 3); + const over = left != null && left < 0; + pills.push( + E('span', { class: `dl-pill-ic${over ? ' bad' : soon ? ' warn' : ''}`, title: `Access ends ${date(p.expires)}` }, [ + icon('calendar'), + over ? `ended ${date(p.expires)}` : soon ? `ends in ${left} day${left === 1 ? '' : 's'}` : `until ${date(p.expires)}`, + ]), + ); + } + if (p.hours) pills.push(E('span', { class: 'dl-pill-ic', title: 'Allowed hours' }, [icon('clock'), p.hours.replace('-', '–')])); + + const chips = p.devices.map((d) => { + return E( + 'button', + { + type: 'button', + class: `dl-chip${d.disabled ? ' disabled' : ''}${d.online ? ' live' : ''}`, + title: `${KIND_LABEL[d.kind]} · ${d.address}${d.online ? ` · online from ${d.endpoint}` : d.handshake ? ` · seen ${ago(d.handshake, this.st.now)}` : ''}`, + click: (ev: Event) => { + ev.preventDefault(); + openDevice(p, d, () => this.refresh(), this.st.geo); + }, + }, + [ + icon(d.kind), + E('span', { class: 'dl-chip-name' }, d.name), + !d.handshake && !d.disabled ? E('span', { class: 'dl-chip-tag' }, 'not set up') : '', + // Online shows as the green dashed chip (.dl-chip.live); no dots. + ], + ); + }); + if (free > 0) + chips.push( + E( + 'button', + { + type: 'button', + class: 'dl-chip add', + title: `${p.devices.length} of ${p.device_limit} devices`, + click: (ev: Event) => { + ev.preventDefault(); + addDevice(p, () => this.refresh()); + }, + }, + [icon('plus'), E('span', { class: 'dl-chip-name' }, 'Add device')], + ), + ); + + const fixes: Node[] = []; + if (p.state === 'quota' && p.quota_period === 'month') + fixes.push( + E( + 'button', + { + type: 'button', + class: 'dl-fix', + click: () => this.quick(p, { bonus_gb: String((p.bonus_gb || 0) + 10) }, '+10 GB this month'), + }, + '+10 GB this month', + ), + ); + if (p.expires && left != null && left <= Math.max(p.expire_warn, 3)) + fixes.push( + E( + 'button', + { type: 'button', class: 'dl-fix', click: () => this.quick(p, { expires: addMonth(p.expires) }, 'Extended by 1 month') }, + 'Extend 1 month', + ), + ); + + const more = iconButton( + 'more', + 'More', + (ev: MouseEvent) => + dropdown( + ev.currentTarget as HTMLElement, + [ + { + label: 'Open', + icon: icon('open'), + run: () => { + location.href = personUrl(p.id); + }, + }, + p.link + ? { + label: 'Invite card', + icon: icon('qr'), + run: () => inviteCard(p, this.st.servers.find((s) => s.id === p.server)?.name ?? 'Home'), + } + : null, + free > 0 ? { label: 'Add device', icon: icon('plus'), run: () => addDevice(p, () => this.refresh()) } : null, + null, + { + label: p.paused ? 'Resume' : 'Pause', + icon: icon(p.paused ? 'play' : 'pause'), + warn: !p.paused, + run: () => this.togglePause(p), + }, + { label: 'Delete', icon: icon('trash'), danger: true, run: () => this.remove(p.id) }, + ].filter((x, i, a) => x || (i > 0 && a[i - 1])) as MenuItem[], + ), + 'neutral', + 'dl-icon-only', + ); + const actions = E('div', { class: 'dl-pcard-actions' }, [ + p.link ? iconButton('link', 'Copy link', () => copyText(p.link!, 'Personal link copied'), 'neutral', 'dl-icon-only') : '', + more, + ]); + + dom.content( + node, + E('div', { class: 'dl-pcard' }, [ + E('div', { class: 'dl-pcard-main' }, [ + E('div', { class: 'dl-card-head' }, [ + E('span', { class: `dl-avatar${p.online ? ' online' : ''}` }, initials(p.name)), + E('a', { class: 'dl-card-name', href: personUrl(p.id) }, p.name), + stateBadge(p), + accessBadge(p), + ...pills, + ]), + E('div', { class: 'dl-meta' }, [ + E('span', {}, `${p.devices.length} of ${p.device_limit} devices`), + E('span', { class: 'dl-sep' }, '·'), + E('span', {}, p.online ? 'online now' : p.last_seen ? `seen ${ago(p.last_seen, this.st.now)}` : 'never connected'), + ]), + E('div', { class: 'dl-chips' }, chips), + fixes.length ? E('div', { class: 'dl-fixes' }, fixes) : '', + ]), + this.usageSide(p, actions), + ]), + ); + return node; + } + + /** Status and actions, this month's usage, a bar split by device (or filled toward the limit), today or live speed. */ + usageSide(p: Person, actions: HTMLElement): HTMLElement { + const used = p.quota_used || p.month[0] + p.month[1]; + const pct = p.quota_limit ? Math.min(100, (p.quota_used / p.quota_limit) * 100) : 0; + const today = p.devices.reduce((a, d) => a + (d.spark[d.spark.length - 1] ?? 0), 0); + const r = p.rate?.[p.rate.length - 1]; + const live = p.online && r && this.st.now - r[0] < 180; + + const bar = E('div', { class: `dl-usebar${pct >= 100 ? ' bad' : pct >= 90 ? ' warn' : ''}` }); + if (p.quota_limit) { + const fill = E('i', { class: 'fill' }); + fill.style.width = `${pct}%`; + bar.appendChild(fill); + attachTip(bar, () => [ + E('div', { class: 'dl-tip-title' }, `${pct.toFixed(1)}% used`), + E( + 'div', + { class: 'dl-muted' }, + `${bytes(p.quota_used)} of ${bytes(p.quota_limit)} · ${bytes(Math.max(0, p.quota_limit - p.quota_used))} left`, + ), + E( + 'div', + { class: 'dl-faint' }, + p.quota_period === 'total' ? 'In total' : `This month${p.bonus_gb ? ` · includes +${p.bonus_gb} GB extra` : ''}`, + ), + ]); + } else { + const devs = p.devices + .map((d) => ({ d, v: d.month[0] + d.month[1] })) + .filter((x) => x.v > 0) + .sort((a, b) => b.v - a.v); + devs.forEach((x, i) => { + const seg = E('i', { class: `c${Math.min(i, 4)}` }); + seg.style.flexGrow = String(x.v); + bar.appendChild(seg); + }); + if (devs.length) + attachTip(bar, () => [ + E('div', { class: 'dl-tip-title' }, 'This month by device'), + ...devs.map((x, i) => + E('div', { class: 'dl-tip-row' }, [ + E('span', { class: `dl-swatch c${Math.min(i, 4)}` }), + E('span', {}, x.d.name), + E('b', {}, bytes(x.v)), + ]), + ), + ]); + } + + const limitText = p.quota_limit ? `${bytes(Math.max(0, p.quota_limit - p.quota_used))} left` : 'no limit'; + return E('div', { class: 'dl-pside' }, [ + E('div', { class: 'dl-pside-top' }, [ + live + ? E('span', { class: 'dl-pside-state live' }, [E('i', { class: 'dl-dot online' }), 'Live']) + : E('span', { class: 'dl-pside-state' }, p.online ? 'Online' : p.last_seen ? 'Offline' : 'Not connected'), + actions, + ]), + E('div', { class: 'dl-use-num' }, [ + E('b', { class: used ? '' : 'dl-faint' }, bytes(used)), + E( + 'span', + { class: 'dl-faint' }, + p.quota_limit ? `of ${bytes(p.quota_limit)}` : p.quota_period === 'total' && p.quota_gb ? 'in total' : 'this month', + ), + ]), + bar, + live + ? E('div', { class: 'dl-use-live', title: 'Right now' }, [`↓ ${bits(r![2])}`, E('span', { class: 'dl-faint' }, `↑ ${bits(r![1])}`)]) + : E('div', { class: 'dl-faint dl-pside-foot' }, today ? `today ${bytes(today)} · ${limitText}` : limitText), + ]); + } + + async togglePause(p: Person) { + if (await attempt(() => api.personPause(p.id, !p.paused), p.paused ? `${p.name} resumed` : `${p.name} paused`)) await this.refresh(); + } + + async remove(sid: Sid) { + const p = this.person(sid); + const ok = await confirmDialog( + `Remove ${p?.name ?? sid}?`, + `All ${p?.devices.length ?? 0} devices are disconnected immediately and the personal link stops working. Usage history is kept in backups.`, + 'Remove', + true, + ); + if (ok && (await attempt(() => api.personDelete(sid), 'Person removed'))) await this.refresh(); + } + + openCreate() { + const st = this.st; + if (!st.servers.length) { + notify('Set up the server first.', 'warning'); + return; + } + const name = E('input', { type: 'text', class: 'cbi-input-text', placeholder: 'e.g. Myata', maxlength: 48 }) as HTMLInputElement; + const access = accessPicker('internet'); + const limit = E('input', { + type: 'number', + class: 'cbi-input-text', + min: 1, + max: 32, + value: st.settings.default_device_limit, + }) as HTMLInputElement; + const expires = E('input', { type: 'date', class: 'cbi-input-text' }) as HTMLInputElement; + const quota = E('input', { + type: 'number', + class: 'cbi-input-text', + min: 0, + step: 'any', + placeholder: 'Unlimited', + }) as HTMLInputElement; + const quick = (label: string, months: number) => + E( + 'button', + { + type: 'button', + class: 'cbi-button cbi-button-neutral', + click: () => { + if (!months) expires.value = ''; + else { + const d = new Date(); + d.setMonth(d.getMonth() + months); + expires.value = isoDate(d); + } + }, + }, + label, + ); + const srv = st.servers[0]; + const server = + !this.serverId && st.servers.length > 1 + ? (E( + 'select', + { class: 'cbi-input-select' }, + st.servers.map((s) => E('option', { value: s.id }, s.name)), + ) as HTMLSelectElement) + : null; + + const row = (label: string, w: Node, help?: string) => + E('div', { class: 'cbi-value' }, [ + E('label', { class: 'cbi-value-title' }, label), + E('div', { class: 'cbi-value-field' }, [w, help ? E('div', { class: 'cbi-value-description' }, help) : '']), + ]); + + modal( + 'Add person', + [ + row('Name', name), + server ? row('Server', server) : '', + E('div', { class: 'cbi-value dl-block' }, [ + E('label', { class: 'cbi-value-title' }, 'Access'), + E('div', { class: 'cbi-value-field' }, access.el), + ]), + row('Devices', limit, 'How many devices they can add themselves.'), + row( + 'End date', + E('div', { class: 'dl-actions' }, [expires, quick('1 month', 1), quick('3 months', 3), quick('1 year', 12), quick('None', 0)]), + 'Optional.', + ), + row('Monthly data (GB)', quota, 'Optional. They are paused when it runs out and resumed next month.'), + ], + [ + E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + ' ', + button( + 'Create and copy link', + async () => { + const r = await attempt(() => + api.personCreate( + name.value.trim(), + '', + server?.value ?? srv.id, + access.get(), + Number(limit.value) || st.settings.default_device_limit, + expires.value, + Number(quota.value) || 0, + 'month', + ), + ); + if (!r) return; + if (r.link) await copyText(r.link, 'Personal link copied'); + this.showCreated(r.id, name.value.trim(), r.link, st.servers.find((x) => x.id === (server?.value ?? srv.id))?.name ?? srv.name); + await this.refresh(); + }, + 'positive', + ), + ], + ); + setTimeout(() => name.focus(), 50); + } + + showCreated(id: string, name: string, link: string | null, server: string) { + if (link) { + inviteCard({ id, name, link }, server, { + title: `${name} is ready`, + lead: `Send ${name} the card or the link. They open it, add their devices and connect — no account needed.`, + }); + return; + } + modal( + `${name} 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: closeModal }, 'Done')], + ); + } +} diff --git a/web/src/admin/pages/person.ts b/web/src/admin/pages/person.ts new file mode 100644 index 0000000..780b0c6 --- /dev/null +++ b/web/src/admin/pages/person.ts @@ -0,0 +1,1046 @@ +// Person page (admin/network/dawnline/person?id=…): devices as cards, +// locations, activity, and access & limits that apply immediately. + +import type { DayUsage, Device, LogEvent, Person, Status } from '../../shared/types'; +import { E } from '../e'; +import { api, type PersonPatch } from '../api'; +import { + attempt, + button, + closeModal, + confirmDialog, + copyText, + downloadFile, + dropdown, + iconButton, + modal, + notify, + svg, + type MenuItem, +} from '../ui'; +import { clearLogDialog, exportEvents, resetUsageDialog } from '../logs'; +import { addDevice, connectBlock, openDevice } from '../device'; +import { inviteCard } from '../invite'; +import { icon } from '../../shared/icons'; +import { qrSvg } from '../../shared/qr'; +import { ACCESS_LABEL, KIND_LABEL, ago, bytes, date, daysLeft, initials } from '../../shared/format'; +import { ConnectionMap, rangeControl } from '../map'; +import { attachTip } from '../charts'; +import { installPalette, peopleUrl } from '../palette'; +import { daysTile, eventRow, eventText, speedTile } from './overview'; +import { stateBadge } from './people'; + +type Step = 'day' | 'week' | 'month' | 'year' | 'custom'; + +function iso(d: Date): string { + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; +} + +/** Move an end date by n steps (negative shortens). An empty date counts from today. */ +export function shiftDate(cur: string, step: Step, n: number, customDays = 30): string { + const d = cur ? new Date(`${cur}T12:00:00`) : new Date(); + if (step === 'day') d.setDate(d.getDate() + n); + else if (step === 'week') d.setDate(d.getDate() + 7 * n); + else if (step === 'month') d.setMonth(d.getMonth() + n); + else if (step === 'year') d.setFullYear(d.getFullYear() + n); + else d.setDate(d.getDate() + customDays * n); + return iso(d); +} + +const ACCESS_TEXT: Record = { + internet: 'Browse the internet through your router. No access to devices at home.', + lan: 'Reach devices at home. Internet stays on their own connection.', + both: 'Home devices and the internet, all through your router.', +}; + +export class PersonPage { + st!: Status; + id = ''; + p!: Person; + events: LogEvent[] = []; + /** The map stays folded into one line until asked for. */ + mapOpen = false; + map: ConnectionMap | null = null; + parts: Record = {}; + /** Daily traffic for the last 30 days. */ + series: DayUsage[] = []; + /** The same per device. */ + devSeries: Record = {}; + + async load(): Promise<[Status, LogEvent[]]> { + this.id = new URLSearchParams(location.search).get('id') ?? ''; + const [st, ev, use] = await Promise.all([ + api.status(30), + api.events(5000).catch(() => ({ events: [] as LogEvent[] })), + api.personUsage(this.id, 30).catch(() => null), + ]); + this.series = use?.person ?? []; + this.devSeries = use?.devices ?? {}; + return [st, ev.events]; + } + + render([st, events]: [Status, LogEvent[]]): HTMLElement { + this.st = st; + this.events = events; + installPalette(st); + const p = st.people.find((x) => x.id === this.id); + if (!p) + 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 = p; + for (const k of ['head', 'devices', 'traffic', 'places', 'activity', 'limits']) this.parts[k] = E('div', {}); + this.parts.devices.className = 'dl-person-devices'; + const root = E('div', {}, [ + E('nav', { class: 'dl-crumbs', 'aria-label': 'Breadcrumb' }, [ + E('a', { href: peopleUrl(p.server) }, st.servers.find((x) => x.id === p.server)?.name ?? 'Servers'), + E('span', {}, '/'), + E('a', { href: peopleUrl(p.server) }, 'People'), + E('span', {}, '/'), + E('span', {}, p.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(); + const q = new URLSearchParams(location.search); + const dev = q.get('device') && p.devices.find((d) => d.id === q.get('device')); + if (dev) setTimeout(() => openDevice(this.p, dev, () => this.refresh(), this.st.geo), 50); + else if (q.get('add')) setTimeout(() => addDevice(this.p, () => this.refresh()), 50); + poll.add(() => this.refresh(true), 15); + return root; + } + + // Newest request wins: a quiet poll that started before an edit must not + // paint its older answer over the refresh that follows the edit. + private refreshSeq = 0; + private refreshShown = 0; + + async refresh(quiet = false) { + const seq = ++this.refreshSeq; + const [st, ev, use] = await Promise.all([ + api.status(30).catch(() => null), + api.events(5000).catch(() => null), + api.personUsage(this.id, 30).catch(() => null), + ]); + if (!st || seq < this.refreshShown) return; + this.refreshShown = seq; + this.st = st; + if (ev) this.events = ev.events; + if (use) { + this.series = use.person; + this.devSeries = use.devices; + } + const p = st.people.find((x) => x.id === this.id); + if (!p) { + if (!quiet) location.href = peopleUrl(this.p?.server); + return; + } + this.p = p; + this.paint(); + this.map?.update(this.mapData()); + } + + /** Apply a change now and repaint from the server's answer. */ + async patch(patch: PersonPatch, ok?: string) { + const r = await attempt(() => api.personUpdate(this.p.id, patch), ok); + if (!r) return; + const i = this.st.people.findIndex((x) => x.id === this.p.id); + r.person.rate ??= this.p.rate; + if (i >= 0) this.st.people[i] = r.person; + this.p = r.person; + this.paint(); + } + + mapData() { + return { geo: this.st.geo, people: this.st.people, now: this.st.now, person: this.p.id }; + } + + mapCard(): HTMLElement { + const head = E('div', { class: 'dl-panel-head pad' }, [ + E('h3', {}, 'Locations'), + E('span', { class: 'dl-spacer' }), + this.st.geo.enabled ? rangeControl('30d', (r) => this.map?.setRange(r), false) : '', + button( + 'Hide', + () => { + this.mapOpen = false; + this.map?.destroy(); + this.map = null; + this.paintPlaces(); + }, + 'neutral', + ), + ]); + if (!this.st.geo.enabled) + return E('div', { class: 'dl-panel flush' }, [ + head, + 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 ConnectionMap( + { + openPerson: () => undefined, + openDevice: (_pid, did) => { + const d = this.p.devices.find((x) => x.id === did); + if (d) openDevice(this.p, d, () => this.refresh(), this.st.geo); + }, + }, + '30d', + 280, + ); + requestAnimationFrame(() => this.map!.mount(this.mapData())); + return E('div', { class: 'dl-panel flush' }, [head, this.map.el]); + } + + paint() { + const p = this.p; + const st = this.st; + const lastSeen = p.online ? 'online now' : p.last_seen ? `last seen ${ago(p.last_seen, st.now)}` : 'never connected'; + + // Speed now and the last 30 days, the same tiles as the server Overview. + const todayUse = this.series.find((d) => d.day === iso(new Date())); + // Speed only while a device is online; otherwise the 30 days take the row. + dom.content( + this.parts.traffic, + E('div', { class: `dl-person-live${p.online ? '' : ' solo'}` }, [ + p.online ? speedTile(p.rate ?? [], st.now, todayUse ? [todayUse.rx, todayUse.tx] : [0, 0]) : '', + daysTile(this.series, `${bytes(p.month[0] + p.month[1])} this month`), + ]), + ); + + const added = p.created ? `Added ${date(iso(new Date(p.created * 1000)))}` : ''; + const menu: (MenuItem | null)[] = [ + { label: 'Rename', icon: icon('edit'), run: () => this.rename() }, + { label: p.note ? 'Edit note' : 'Add note', icon: icon('file'), run: () => this.editNote() }, + ...(p.link + ? [ + null, + { label: 'Invite card', icon: icon('qr'), run: () => this.invite() }, + { label: 'New link', icon: icon('key'), run: () => this.newLink() }, + ] + : []), + null, + { + label: p.paused ? 'Resume' : 'Pause', + icon: icon(p.paused ? 'play' : 'pause'), + warn: !p.paused, + run: () => this.patch({ paused: !p.paused }, p.paused ? 'Resumed' : 'Paused'), + }, + { label: 'Delete', icon: icon('trash'), danger: true, 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${p.online ? ' online' : ''}` }, initials(p.name)), + E('div', { class: 'dl-stack' }, [ + E('div', { class: 'dl-title-row' }, [E('h2', { class: 'dl-h1' }, p.name), stateBadge(p)]), + E('span', { class: 'dl-faint', title: added }, `${p.devices.length} of ${p.device_limit} devices · ${lastSeen}`), + ]), + ]), + E('div', { class: 'dl-pcard-actions' }, [ + p.link ? iconButton('link', 'Copy link', () => copyText(p.link!, 'Personal link copied'), 'neutral', 'dl-icon-only') : '', + iconButton('more', 'More', (ev: MouseEvent) => dropdown(ev.currentTarget as HTMLElement, menu), 'neutral', 'dl-icon-only'), + ]), + ]), + // Under the name block, not inside it, so the avatar centres on name + status; indented to the name. + p.note + ? E('button', { type: 'button', class: 'dl-pnote', title: 'Edit note', click: () => this.editNote() }, [ + icon('file'), + E('span', {}, p.note), + ]) + : '', + ]), + ); + + this.paintDevices(); + this.paintLimits(); + this.paintPlaces(); + + const all = this.events.filter((e) => e.person === p.id); + // Back-and-forth network changes (Wi-Fi <-> mobile) fold into one row. + const rows: HTMLElement[] = []; + const latest = [...all].reverse(); + for (let i = 0; i < latest.length && rows.length < 10; i++) { + const e = latest[i]; + let n = 1; + while (e.type === 'roam' && latest[i + n]?.type === 'roam' && latest[i + n].device === e.device) n++; + const row = eventRow(st, e); + if (n > 1) { + const main = row.querySelector('.dl-row-main') as HTMLElement; + dom.content(main, [...eventText(st, e).slice(0, 2), E('span', { class: 'dl-muted' }, `${n} times`)]); + main.title = latest + .slice(i, i + n) + .map((x) => x.detail ?? '') + .join('\n'); + } + rows.push(row); + i += n - 1; + } + const more = button( + [icon('more')], + () => + dropdown(more, [ + { label: 'Export CSV', icon: icon('download'), run: () => exportEvents(this.st, all, 'csv', p.id) }, + { label: 'Export JSON', icon: icon('download'), run: () => exportEvents(this.st, all, 'json', p.id) }, + null, + { + label: `Clear ${p.name}'s activity`, + icon: icon('trash'), + danger: true, + run: () => + clearLogDialog(`Clear ${p.name}'s activity`, `Removes events about ${p.name} and their devices.`, { person: p.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' }, all.length > 10 ? `latest 10 of ${all.length}` : ''), + E('span', { class: 'dl-spacer' }), + more, + ]), + rows.length ? rows : E('div', { class: 'dl-row dl-muted' }, 'Nothing yet.'), + ]), + ); + } + + deviceStatus(d: Device): HTMLElement { + if (d.disabled) return E('span', { class: 'dl-dstat' }, [E('i', { class: 'dot' }), 'Disabled']); + if (d.online) + return E('span', { class: 'dl-dstat ok' }, [ + E('i', { class: 'dot ok' }), + `Online · ${ago(d.handshake, this.st.now).replace(' ago', '')}`, + ]); + if (!d.handshake) + return E('span', { class: 'dl-dstat warn', title: 'Waiting for the first connection' }, [ + E('i', { class: 'dot warn' }), + 'Not set up yet', + ]); + return E('span', { class: 'dl-dstat' }, [E('i', { class: 'dot' }), `Last seen ${ago(d.handshake, this.st.now)}`]); + } + + /** While online: the client IP (copyable). Tunnel address and home name live in the device drawer. */ + addrs(d: Device): HTMLElement | '' { + if (!d.online || !d.endpoint) return ''; + const where = this.st.geo?.points.find((g) => g.device === d.id && g.ip === d.endpoint); + const tip = where?.city ? `Client IP · ${where.city}${where.org ? ` · ${where.org}` : ''}` : 'Client IP'; + const b = E( + 'button', + { type: 'button', class: 'dl-addr wan', 'aria-label': `Copy ${d.endpoint}`, click: () => copyText(d.endpoint, 'Client IP copied') }, + [icon('globe'), E('span', {}, d.endpoint)], + ); + attachTip(b, () => [E('div', { class: 'dl-tip-title' }, tip), E('div', { class: 'dl-muted' }, 'Click to copy')]); + return E('div', { class: 'dl-addrs' }, b); + } + + /** Daily traffic of one device over the last 30 days, today on the right. */ + deviceBars(id: string): HTMLElement { + const days = (this.devSeries[id] ?? []).slice(-30); + const vals = days.map((x) => x.rx + x.tx); + const max = Math.max(1, ...vals); + const label = (day: string) => new Date(`${day}T12:00:00`).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }); + return E( + 'div', + { class: 'dl-dbars' }, + days.map((x, i) => { + const bar = E('i', { class: `${vals[i] ? '' : 'zero'}${i === days.length - 1 ? ' hi' : ''}` }); + bar.style.height = `${Math.max(8, (vals[i] / max) * 100)}%`; + attachTip(bar, () => [ + E('div', { class: 'dl-tip-title' }, i === days.length - 1 ? `Today · ${label(x.day)}` : label(x.day)), + E('div', {}, bytes(vals[i])), + ]); + return bar; + }), + ); + } + + paintDevices() { + const p = this.p; + const refresh = () => this.refresh(); + const cards = p.devices.map((d) => { + const open = () => openDevice(p, d, refresh, this.st.geo); + return E('article', { class: `dl-dcard${d.online ? ' online' : ''}${d.disabled ? ' off' : ''}` }, [ + E('div', { class: 'dl-dcard-head' }, [ + E('span', { class: 'dl-dcard-ic' }, icon(d.kind)), + E('button', { type: 'button', class: 'dl-dcard-title', click: open }, [ + E('b', {}, d.name), + this.deviceStatus(d), + d.config_stale ? E('span', { class: 'dl-pill warn dl-stale' }, 'Update config') : '', + ]), + button([icon('more')], open, 'neutral', { + title: `${d.name}: connect, rename, keys, remove`, + class: 'cbi-button cbi-button-neutral dl-icon-only', + }), + ]), + d.handshake + ? E('div', { class: 'dl-dcard-trend' }, [ + E('div', { class: 'dl-stack' }, [E('b', {}, bytes(d.month[0] + d.month[1])), E('span', { class: 'dl-sub' }, 'this month')]), + this.deviceBars(d.id), + ]) + : d.disabled + ? E( + 'div', + { class: 'dl-sub' }, + `${KIND_LABEL[d.kind]} · created ${ago(d.created, this.st.now)} ${d.created_by === 'portal' ? 'in the portal' : 'by you'}.`, + ) + : E('div', { class: 'dl-chips-row' }, [ + E('button', { type: 'button', class: 'dl-chipbtn', click: () => this.showDeviceQr(d) }, [icon('qr'), 'Show QR']), + E('button', { type: 'button', class: 'dl-chipbtn', click: () => this.downloadConfig(d) }, [icon('download'), 'Config']), + ]), + this.addrs(d), + ]); + }); + const free = Math.max(0, p.device_limit - p.devices.length); + if (free) + cards.push( + E('button', { type: 'button', class: 'dl-dslot add', click: () => addDevice(p, refresh) }, [ + E('span', { class: 'dl-dslot-ic' }, icon('plus')), + E('b', {}, 'Add device'), + ]), + ); + dom.content( + this.parts.devices, + E('section', { class: 'dl-devsec' }, [ + E('div', { class: 'dl-panel-head' }, [ + E('h3', {}, 'Devices'), + E('span', { class: 'dl-sub' }, `${p.online} online`), + E('span', { class: 'dl-spacer' }), + // Over the limit there is no Add card; the admin can still add one. + free + ? '' + : button([icon('plus'), ' Add device'], () => addDevice(p, refresh), 'neutral', { + title: 'Over the limit — admins can still add', + }), + ]), + E('div', { class: 'dl-dgrid' }, cards), + ]), + ); + } + + paintLimits() { + const p = this.p; + const seg = E( + 'div', + { class: 'dl-seg wide', role: 'radiogroup', 'aria-label': 'Access' }, + (['internet', 'lan', 'both'] as const).map((a) => + E( + 'button', + { + type: 'button', + role: 'radio', + class: p.access === a ? 'on' : '', + 'aria-checked': p.access === a ? 'true' : 'false', + click: () => p.access !== a && this.patch({ access: a }, `Access: ${ACCESS_LABEL[a]}`), + }, + [ + icon(a === 'internet' ? 'globe' : a === 'lan' ? 'home' : 'shield'), + a === 'internet' ? 'Internet' : a === 'lan' ? 'Home' : 'Both', + ], + ), + ), + ); + + // End date + const left = daysLeft(p.expires); + const dateInput = E('input', { + type: 'date', + class: 'dl-date-hidden', + value: p.expires, + tabindex: '-1', + 'aria-hidden': 'true', + }) as HTMLInputElement; + dateInput.addEventListener( + 'change', + () => dateInput.value && this.patch({ expires: dateInput.value }, `Access until ${date(dateInput.value)}`), + ); + // Extend from the current end, or from today when there is none or it has passed. + const extend = (step: 'week' | 'month' | 'year', n: number, label: string) => { + const next = shiftDate(p.expires && (left ?? -1) >= 0 ? p.expires : '', step, n); + this.patch({ expires: next }, `Access until ${date(next)}`); + return label; + }; + const ext = ( + [ + ['week', 1, '+1 week'], + ['month', 1, '+1 month'], + ['month', 3, '+3 months'], + ['year', 1, '+1 year'], + ] as const + ).map(([st, n, label]) => E('button', { type: 'button', class: 'dl-chipbtn', click: () => extend(st, n, label) }, label)); + // The native date input stays hidden behind the chip and only opens its picker. + const pick = E('span', { class: 'dl-datechip' }, [ + E( + 'button', + { + type: 'button', + class: 'dl-chipbtn', + click: () => { + try { + dateInput.showPicker(); + } catch { + dateInput.focus(); + } + }, + }, + [icon('calendar'), p.expires ? date(p.expires) : 'Date'], + ), + dateInput, + ]); + const action = { pause: 'pause access', notify: 'keep access', remove: 'remove their devices' }[p.expire_action]; + const endTile = E('div', { class: 'dl-tile2' }, [ + E('div', { class: 'dl-tile2-label' }, [ + E('span', {}, 'Access ends'), + p.expires + ? E( + 'span', + { class: left != null && left < 0 ? 'dl-bad' : left != null && left <= p.expire_warn ? 'dl-warn' : 'dl-ok' }, + left != null && left < 0 ? 'ended' : `${left} day${left === 1 ? '' : 's'} left`, + ) + : E('span', { class: 'dl-faint' }, 'no end date'), + ]), + E('div', { class: 'dl-chips-row' }, [ + ...ext, + pick, + p.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: ${action}${p.expire_warn ? `, warn ${p.expire_warn} day${p.expire_warn === 1 ? '' : 's'} before` : ''}`, + ), + E( + 'a', + { + href: '#', + click: (ev: Event) => { + ev.preventDefault(); + this.endSettings(); + }, + }, + 'Change', + ), + ]), + ]); + + // Data + const used = p.quota_used || p.month[0] + p.month[1]; + const pct = p.quota_limit ? Math.min(100, (p.quota_used / p.quota_limit) * 100) : 0; + const bar = E('div', { class: `dl-meter${pct >= 100 ? ' bad' : pct >= 90 ? ' warn' : ''}` }, [ + E('i'), + p.quota_limit ? E('span', { class: 'mark', title: 'Alert at 90%' }) : '', + ]); + (bar.firstChild as HTMLElement).style.width = `${pct}%`; + if (p.quota_limit) + attachTip(bar, () => [ + E('div', { class: 'dl-tip-title' }, `${pct.toFixed(1)}% used`), + E( + 'div', + { class: 'dl-muted' }, + `${bytes(p.quota_used)} of ${bytes(p.quota_limit)} · ${bytes(Math.max(0, p.quota_limit - p.quota_used))} left`, + ), + E('div', { class: 'dl-faint' }, 'Alert at 90%'), + ]); + const period = E( + 'div', + { class: 'dl-seg sm' }, + (['month', 'total'] as const).map((v) => + E( + 'button', + { type: 'button', class: p.quota_period === v ? 'on' : '', click: () => p.quota_period !== v && this.patch({ quota_period: v }) }, + v === 'month' ? 'Monthly' : 'Total', + ), + ), + ); + const presets = [10, 50, 100].map((gb) => + E( + 'button', + { + type: 'button', + class: `dl-chipbtn${p.quota_gb === gb ? ' on' : ''}`, + click: () => this.patch({ quota_gb: String(gb) }, `Data limit ${gb} GB`), + }, + `${gb} GB`, + ), + ); + presets.push( + E( + 'button', + { type: 'button', class: `dl-chipbtn${!p.quota_gb ? ' on' : ''}`, click: () => this.patch({ quota_gb: '' }, 'No data limit') }, + 'Unlimited', + ), + ); + presets.push( + E( + 'button', + { + type: 'button', + class: 'dl-chipbtn', + click: () => { + const v = prompt('Data limit in GB', p.quota_gb ? String(p.quota_gb) : ''); + if (v != null && v.trim() !== '' && Number(v) > 0) this.patch({ quota_gb: v.trim() }, `Data limit ${v.trim()} GB`); + }, + }, + 'Custom', + ), + ); + const dataTile = E('div', { class: 'dl-tile2' }, [ + E('div', { class: 'dl-tile2-label' }, [E('span', {}, 'Data'), period]), + E('div', { class: 'dl-tile2-row' }, [ + E('span', { class: 'dl-tile2-value' }, [ + bytes(used), + p.quota_limit ? E('span', { class: 'dl-faint' }, ` of ${bytes(p.quota_limit)}`) : E('span', { class: 'dl-faint' }, ' · no limit'), + ]), + p.quota_period === 'month' ? E('span', { class: 'dl-sub' }, 'resets on the 1st') : '', + ]), + p.quota_limit ? bar : '', + E('div', { class: 'dl-chips-row' }, presets), + p.quota_gb && p.quota_period === 'month' + ? E('div', { class: 'dl-tile2-foot' }, [ + E('span', { class: 'dl-muted' }, p.bonus_gb ? `Includes +${p.bonus_gb} GB extra this month` : 'Need a little more this month?'), + E( + 'a', + { + href: '#', + click: (ev: Event) => { + ev.preventDefault(); + this.patch({ bonus_gb: String((p.bonus_gb || 0) + 10) }, '+10 GB this month'); + }, + }, + '+10 GB this month', + ), + ]) + : '', + E('div', { class: 'dl-tile2-foot' }, [ + E('span', { class: 'dl-muted' }, `${bytes(p.total[0] + p.total[1])} in total`), + E( + 'button', + { + type: 'button', + class: 'dl-linkbtn danger', + click: () => resetUsageDialog('person', p.id, p.name, () => setTimeout(() => this.refresh(), 300)), + }, + 'Reset usage', + ), + ]), + ]); + + // Hours + const hoursOn = !!p.hours; + const [h1, h2] = (p.hours || '07:00-23:00').split('-'); + const from = E('input', { type: 'time', class: 'cbi-input-text', value: h1 }) as HTMLInputElement; + const to = E('input', { type: 'time', class: 'cbi-input-text', value: h2 }) as HTMLInputElement; + const saveHours = () => this.patch({ hours: `${from.value}-${to.value}` }, `Allowed ${from.value}–${to.value}`); + from.addEventListener('change', saveHours); + to.addEventListener('change', saveHours); + const sw = E( + 'button', + { + type: 'button', + role: 'switch', + 'aria-checked': hoursOn ? 'true' : 'false', + class: `dl-switch${hoursOn ? ' on' : ''}`, + 'aria-label': 'Limit hours', + click: () => this.patch({ hours: hoursOn ? '' : '07:00-23:00' }, hoursOn ? 'Any time' : 'Allowed 07:00–23:00'), + }, + E('i'), + ); + const hoursTile = 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', {}, hoursOn ? `${h1} – ${h2} (router time)` : 'Any time'), + ]), + sw, + ]), + hoursOn ? E('div', { class: 'dl-tile2-row' }, [from, E('span', { class: 'dl-faint' }, 'to'), to]) : '', + ]); + + dom.content( + this.parts.limits, + E('section', { class: 'dl-panel', 'aria-label': 'Access and limits' }, [ + E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Access & limits')]), + E('div', { class: 'dl-stack gap8' }, [ + E('span', { class: 'dl-tile2-label' }, 'Can reach'), + seg, + E('span', { class: 'dl-sub' }, ACCESS_TEXT[p.access]), + p.access === 'lan' && this.st.services.length ? this.servicesPicker() : '', + p.access === 'lan' ? this.dnsPicker() : '', + ]), + E('div', { class: 'dl-tiles2' }, [this.devTile(), endTile, dataTile, hoursTile]), + ]), + ); + } + + /** + * DNS for Home-only access. The internet does not go through the tunnel, so + * by default the device keeps its own DNS; home names are opt-in. + */ + dnsPicker(): HTMLElement { + const p = this.p; + const seg = E( + 'div', + { class: 'dl-seg sm', role: 'radiogroup', 'aria-label': 'DNS' }, + ( + [ + ['device', 'Device’s own DNS'], + ['home', 'Home names'], + ] as const + ).map(([v, t]) => + E( + 'button', + { + type: 'button', + role: 'radio', + class: p.dns_mode === v ? 'on' : '', + 'aria-checked': p.dns_mode === v ? 'true' : 'false', + click: () => + p.dns_mode !== v && + this.patch( + { dns_mode: v }, + v === 'home' + ? 'Home names on — devices need their configuration again' + : 'Device DNS — devices need their configuration again', + ), + }, + t, + ), + ), + ); + const fb = 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'), seg]), + E( + 'span', + { class: 'dl-sub' }, + p.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', + fb + ? [' (', E('span', { class: 'dl-mono' }, fb), ' 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.', + ), + ]); + } + + /** Optional narrowing of home-network access to selected services. */ + servicesPicker(): HTMLElement { + const chosen = new Set(this.p.services ?? []); + return E('div', { class: 'dl-stack gap4' }, [ + E( + 'div', + { class: 'dl-chips-row' }, + this.st.services.map((sv) => + E( + 'button', + { + type: 'button', + class: `dl-chipbtn${chosen.has(sv.id) ? ' on' : ''}`, + title: `${sv.address}${sv.ports.length ? ` · ${sv.ports.join(', ')}` : ''}`, + click: () => { + if (chosen.has(sv.id)) chosen.delete(sv.id); + else chosen.add(sv.id); + this.patch({ services: [...chosen] }, chosen.size ? 'Home services updated' : 'Whole home network'); + }, + }, + sv.name, + ), + ), + ), + E( + 'span', + { class: 'dl-sub' }, + chosen.size ? 'Only the selected services at home.' : 'Whole home network. Pick services to narrow it down.', + ), + ]); + } + + /** Device limit with a slot per device; never below the devices in use. */ + devTile(): HTMLElement { + const p = this.p; + const slots = E('div', { class: 'dl-slots' }); + for (let i = 0; i < p.device_limit; i++) { + const d = p.devices[i]; + const slot = E('i', { class: d ? 'used' : '' }); + attachTip(slot, () => [ + E('div', { class: 'dl-tip-title' }, d ? d.name : 'Free slot'), + E( + 'div', + { class: 'dl-muted' }, + d + ? d.online + ? 'Online' + : d.handshake + ? `Last seen ${ago(d.handshake, this.st.now)}` + : 'Not set up yet' + : 'They can add a device here', + ), + ]); + slots.appendChild(slot); + } + const floor = Math.max(1, p.devices.length); + const minus = E( + 'button', + { + type: 'button', + 'aria-label': 'Allow fewer devices', + disabled: p.device_limit <= floor ? 'disabled' : null, + click: () => this.patch({ device_limit: String(p.device_limit - 1) }), + }, + '−', + ); + if (p.device_limit <= floor && p.devices.length > 1) + attachTip(minus, () => [ + E('div', { class: 'dl-tip-title' }, `${p.devices.length} devices in use`), + E('div', { class: 'dl-muted' }, 'Remove a device first to lower the limit'), + ]); + return 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(p.devices.length), E('span', { class: 'dl-faint' }, ` / ${p.device_limit}`)]), + E('div', { class: 'dl-stepper' }, [ + minus, + E( + 'button', + { + type: 'button', + 'aria-label': 'Allow more devices', + disabled: p.device_limit >= 32 ? 'disabled' : null, + click: () => this.patch({ device_limit: String(p.device_limit + 1) }), + }, + '+', + ), + ]), + ]), + slots, + ]); + } + + /** Where they connected from: one line, the map on request. */ + paintPlaces() { + const st = this.st; + if (!st.geo.enabled) { + dom.content( + this.parts.places, + E('div', { class: 'dl-places' }, [ + icon('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) { + if (!this.map || !this.parts.places.contains(this.map.el)) dom.content(this.parts.places, this.mapCard()); + return; + } + const since = st.now - 30 * 86400; + const pts = st.geo.points.filter((g) => g.person === this.p.id && g.ts >= since).sort((a, b) => b.ts - a.ts); + const places = [...new Set(pts.map((g) => g.city || g.country).filter(Boolean))]; + const last = pts[0]; + dom.content( + this.parts.places, + E('div', { class: 'dl-places' }, [ + icon('pin'), + E('div', { class: 'dl-stack' }, [ + E('span', {}, last ? last.city || last.country : 'No locations yet'), + E( + 'span', + { class: 'dl-sub' }, + last + ? `${places.length} place${places.length === 1 ? '' : 's'} in 30 days${last.org ? ` · ${last.org}` : ''}` + : 'Shown after a device connects', + ), + ]), + E('span', { class: 'dl-spacer' }), + pts.length + ? button( + 'Show map', + () => { + this.mapOpen = true; + this.paintPlaces(); + }, + 'neutral', + ) + : '', + ]), + ); + } + + invite() { + const server = this.st.servers.find((s) => s.id === this.p.server)?.name ?? 'Home'; + inviteCard(this.p, server); + } + + showQr() { + const p = this.p; + if (!p.link) return; + modal( + `${p.name}’s link`, + [ + E('div', { class: 'dl-qr-pane' }, [ + svg(qrSvg(p.link), 'dl-qr'), + E('div', { class: 'dl-hint' }, 'Scan with the phone camera to open the portal.'), + ]), + ], + [E('button', { class: 'cbi-button', click: closeModal }, 'Close')], + ); + } + + async newLink() { + const p = this.p; + if (!(await confirmDialog('Create a new link?', 'The old link stops working right away.', 'Create new link', true))) return; + const r = await attempt(() => api.personRegen(p.id), 'New link created'); + if (r?.link) { + p.link = r.link; + copyText(r.link, 'New link copied'); + this.paint(); + } + } + + /** Setting up a device: its QR code (key and file one tap away). */ + async showDeviceQr(d: Device) { + const cfg = await attempt(() => api.deviceConfig(d.id)); + if (!cfg) return; + modal(`Set up ${d.name}`, [await connectBlock(cfg)], [E('button', { class: 'cbi-button', click: closeModal }, 'Close')]); + } + + async downloadConfig(d: Device) { + const cfg = await attempt(() => api.deviceConfig(d.id)); + if (!cfg) return; + if (!cfg.has_private_key) { + notify('This device made its own keys in the browser; its configuration only exists there.', 'warning'); + return; + } + downloadFile(cfg.filename, cfg.conf, 'application/octet-stream'); + } + + editNote() { + const input = E( + 'textarea', + { class: 'cbi-input-textarea dl-note-input', rows: 3, maxlength: 500, placeholder: 'Only you see this' }, + this.p.note ?? '', + ) as HTMLTextAreaElement; + modal( + 'Note', + [input], + [ + E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + ' ', + button( + 'Save', + async () => { + closeModal(); + await this.patch({ note: input.value.trim() }, input.value.trim() ? 'Note saved' : 'Note removed'); + }, + 'positive', + ), + ], + ); + setTimeout(() => input.focus(), 50); + } + + endSettings() { + const p = this.p; + const act = E('select', { class: 'cbi-input-select' }, [ + E('option', { value: 'pause', selected: p.expire_action === 'pause' ? 'selected' : null }, 'Pause access'), + E('option', { value: 'notify', selected: p.expire_action === 'notify' ? 'selected' : null }, 'Keep access'), + E('option', { value: 'remove', selected: p.expire_action === 'remove' ? 'selected' : null }, 'Remove their devices'), + ]) as HTMLSelectElement; + const warn = E( + 'select', + { class: 'cbi-input-select' }, + [0, 1, 3, 7, 14].map((n) => + E( + 'option', + { value: n, selected: p.expire_warn === n ? 'selected' : null }, + n ? `${n} day${n === 1 ? '' : 's'} before` : 'Don’t warn', + ), + ), + ) as HTMLSelectElement; + modal( + 'When access ends', + [ + E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, 'Then'), E('div', { class: 'cbi-value-field' }, act)]), + E('div', { class: 'cbi-value' }, [ + E('label', { class: 'cbi-value-title' }, 'Warn'), + E('div', { class: 'cbi-value-field' }, [ + warn, + E('div', { class: 'cbi-value-description' }, 'Shown in their portal and on the Overview.'), + ]), + ]), + ], + [ + E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + ' ', + button( + 'Save', + async () => { + closeModal(); + await this.patch({ expire_action: act.value, expire_warn: warn.value }, 'Saved'); + }, + 'positive', + ), + ], + ); + } + + rename() { + const input = E('input', { type: 'text', class: 'cbi-input-text', value: this.p.name, maxlength: 48 }) as HTMLInputElement; + modal( + 'Rename', + [E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, 'Name'), E('div', { class: 'cbi-value-field' }, input)])], + [ + E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + ' ', + button( + 'Save', + async () => { + closeModal(); + await this.patch({ name: input.value }, 'Renamed'); + }, + 'positive', + ), + ], + ); + setTimeout(() => input.select(), 50); + } + + async remove() { + const p = this.p; + const ok = await confirmDialog( + `Delete ${p.name}?`, + `All ${p.devices.length} devices are disconnected immediately and the personal link stops working.`, + 'Delete', + true, + ); + if (ok && (await attempt(() => api.personDelete(p.id), 'Deleted'))) location.href = peopleUrl(p.server); + } +} diff --git a/web/src/admin/pages/server.ts b/web/src/admin/pages/server.ts new file mode 100644 index 0000000..6a8b7fa --- /dev/null +++ b/web/src/admin/pages/server.ts @@ -0,0 +1,834 @@ +// Servers: a setup wizard when nothing is configured; otherwise one tab per +// server. Each opens on its Overview (who is online, traffic, map, activity) +// followed by its settings (General, Interfaces, Network, Disguise, +// Advanced); every settings section saves on its own and applies at once. + +import type { Server, Status } from '../../shared/types'; +import { E } from '../e'; +import { api, type SetupDefaults } from '../api'; +import { attempt, button, callout, closeModal, confirmDialog, copyText, modal, notify } from '../ui'; +import { icon } from '../../shared/icons'; +import { duration } from '../../shared/format'; +import { interfacesCard } from '../interfaces'; +import { card, group, input, row } from '../kit'; +import { methodInfo, methodPicker, type Method } from '../disguise'; +import { ServerOverview } from './overview'; +import { PeoplePage } from './people'; +import { installPalette, openPalette } from '../palette'; + +type Section = 'overview' | 'people' | 'connection' | 'access' | 'disguise' | 'tunnel'; +const SECTIONS: [Section, string][] = [ + ['overview', 'Overview'], + ['people', 'People'], + ['connection', 'Connection'], + ['access', 'Access'], + ['disguise', 'Disguise'], + ['tunnel', 'Tunnel'], +]; +/** Section names from before the regrouping, for old links. */ +const OLD_SECTIONS: Record = { general: 'connection', network: 'connection', interfaces: 'access', advanced: 'tunnel' }; +function choices(items: { v: T; title: string; text: string; ic?: string }[], initial: T, onChange: (v: T) => void) { + const el = E( + 'div', + { class: 'dl-choices' }, + items.map((o) => + E( + 'button', + { + type: 'button', + class: `dl-choice${o.v === initial ? ' selected' : ''}`, + 'data-v': o.v, + click: () => { + el.querySelectorAll('.dl-choice').forEach((c) => c.classList.toggle('selected', (c as HTMLElement).dataset.v === o.v)); + onChange(o.v); + }, + }, + [E('span', { class: 'dl-choice-title' }, [o.ic ? icon(o.ic) : '', o.title]), E('span', { class: 'dl-choice-text' }, o.text)], + ), + ), + ); + return el; +} + +/** `.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, + ]); +} + +const url = (server?: string, section?: string) => { + const q = new URLSearchParams(); + if (server) q.set('server', server); + if (section && section !== 'overview') q.set('section', section); + const s = q.toString(); + return `${L.url('admin/network/dawnline/server')}${s ? `?${s}` : ''}`; +}; + +export class ServerPage { + st!: Status; + noFooter = true; + root = E('div', { class: 'dl-root' }); + section: Section = 'overview'; + srvId = ''; + /** Per-server sections kept between switches (the map stays mounted). */ + ov: Record = {}; + pp: Record = {}; + tabsEl = E('div', {}); + headEl = E('div', {}); + secEl = E('div', {}); + bodyEl = E('div', { class: 'dl-srvbody' }); + + async load(): Promise<[Status, SetupDefaults | null]> { + const st = await api.status(31); + const d = st.servers.length ? null : await api.setupDefaults(); + return [st, d]; + } + + render([st, d]: [Status, SetupDefaults | null]): Node { + this.st = st; + if (!st.servers.length && d) return this.wizard(d); + // Deep links (?server=…§ion=…) pick the starting tab; switching later + // happens in place, without touching the URL (the theme's router would + // treat that as a navigation and redraw the page). + const q = new URLSearchParams(location.search); + const raw = q.get('section') ?? ''; + const want = (OLD_SECTIONS[raw] ?? raw) as Section; + if (SECTIONS.some(([k]) => k === want)) this.section = want; + this.srvId = (st.servers.find((x) => x.id === q.get('server')) ?? st.servers[0]).id; + installPalette(st); + dom.content(this.root, [this.tabsEl, this.headEl, this.secEl, this.bodyEl]); + this.paint(); + // Live numbers on the Overview; settings forms are left alone while open. + poll.add(async () => { + if (this.section !== 'overview') return; + const n = await api.status(31).catch(() => null); + if (!n || !n.servers.length) return; + this.st = n; + const srv = this.current(); + dom.content(this.headEl, this.head(srv)); + this.paintTabs(); + this.ov[srv.id]?.update(n); + }, 10); + return this.root; + } + + current(): Server { + return this.st.servers.find((x) => x.id === this.srvId) ?? this.st.servers[0]; + } + + async refresh() { + const st = await api.status(31).catch(() => null); + if (!st) return; + this.st = st; + if (!st.servers.length) location.href = url(); + else this.paint(); + } + + /* ---------------- page ---------------- */ + + /** Everything: server tabs, head, section tabs and the current section. */ + paint() { + this.paintTabs(); + dom.content(this.headEl, this.head(this.current())); + this.paintSections(); + this.showSection(this.section); + } + + paintTabs() { + const srv = this.current(); + dom.content( + this.tabsEl, + E('div', { class: 'dl-srvtabs', role: 'tablist', 'aria-label': 'Servers' }, [ + ...this.st.servers.map((x) => + E( + 'button', + { + type: 'button', + role: 'tab', + class: `dl-srvtab${x.id === srv.id ? ' on' : ''}`, + 'aria-selected': x.id === srv.id ? 'true' : 'false', + click: () => { + if (x.id === this.srvId) return; + this.srvId = x.id; + this.paint(); + }, + }, + [E('i', { class: `dot ${x.up ? 'ok' : 'bad'}` }), E('b', {}, x.name), E('span', { class: 'dl-mono dl-faint' }, `:${x.port}`)], + ), + ), + E('button', { type: 'button', class: 'dl-srvtab add', click: () => this.addServer() }, [icon('plus'), 'Add server']), + ]), + ); + } + + paintSections() { + dom.content( + this.secEl, + E( + 'div', + { class: 'dl-seg dl-srvsections', role: 'tablist', 'aria-label': 'Server' }, + SECTIONS.map(([k, t]) => + E( + 'button', + { + type: 'button', + role: 'tab', + 'data-section': k, + class: k === this.section ? 'on' : '', + 'aria-selected': k === this.section ? 'true' : 'false', + click: () => this.showSection(k), + }, + t, + ), + ), + ), + ); + } + + /** Jump to a section, optionally with a People filter (from the Overview). */ + go(k: Section, filter?: string) { + const pp = this.pp[this.current().id]; + if (filter && pp) { + pp.filter = filter as PeoplePage['filter']; + if (pp.el) pp.decorate(); + } else if (filter) { + const page = (this.pp[this.current().id] = new PeoplePage()); + page.filter = filter as PeoplePage['filter']; + } + this.showSection(k); + window.scrollTo({ top: 0, behavior: 'smooth' }); + } + + /** Swap only the section body; the rest of the page stays as it is. */ + showSection(k: Section) { + this.section = k; + this.secEl.querySelectorAll('[data-section]').forEach((b) => { + const on = b.dataset.section === k; + b.classList.toggle('on', on); + b.setAttribute('aria-selected', on ? 'true' : 'false'); + }); + const st = this.st; + const srv = this.current(); + const body: Record Node> = { + overview: () => { + const ov = this.ov[srv.id]; + if (!ov) return (this.ov[srv.id] = new ServerOverview(srv.id, (k, f) => this.go(k as Section, f))).mount(st); + ov.update(st); + return ov.el; + }, + people: () => { + const pp = this.pp[srv.id]; + if (pp?.el) { + void pp.poll(); + return pp.el; + } + const holder = E('div', {}, E('p', { class: 'dl-muted' }, 'Loading people…')); + const page = (this.pp[srv.id] ??= new PeoplePage()); + page.embed(st, srv.id).then((node) => { + if (holder.isConnected) dom.content(holder, node); + else holder.replaceChildren(node); + }); + return holder; + }, + connection: () => this.connection(srv), + access: () => this.access(srv), + disguise: () => this.disguise(srv), + tunnel: () => this.tunnel(srv), + }; + dom.content(this.bodyEl, body[k]()); + } + + /** Name and state, the address bar, and the page actions. */ + head(srv: Server): HTMLElement { + const st = this.st; + const seg = (ic: string, body: (Node | string)[]) => E('span', { class: 'dl-addrbar-seg' }, [icon(ic), ...body]); + const addr = `${srv.endpoint || '—'}:${srv.port}`; + // Search, plus "Turn on" while the server is off (turning off lives in Tunnel; + // the same button also lifts an old router-wide pause). + const off = !srv.enabled || st.settings.paused_all; + const actions = E('div', { class: 'dl-actions' }, [ + button([icon('search'), ' Search ', E('kbd', {}, '⌘K')], () => openPalette(), 'neutral', { + class: 'cbi-button cbi-button-neutral dl-searchbtn', + }), + off + ? button( + [icon('play'), ' Turn on'], + async () => { + if (st.settings.paused_all && !(await attempt(() => api.pauseAll(false)))) return; + if (!srv.enabled) await this.save(srv, { enabled: '1' }, 'Server turned on'); + else await this.refresh(); + }, + 'positive', + ) + : '', + ]); + // Actions sit on the name's line; the address bar gets the whole next line. + return E('div', { class: 'dl-srvpagehead' }, [ + E('div', { class: 'dl-title-row' }, [ + E('h2', { class: 'dl-h1' }, srv.name), + E('span', { class: `dl-pill ${!srv.enabled ? 'off' : srv.up ? 'ok' : 'bad'}` }, [ + E('i', { class: 'dl-pill-dot' }), + !srv.enabled ? 'Disabled' : srv.up ? 'Ready' : 'Down', + ]), + st.settings.paused_all && srv.enabled ? E('span', { class: 'dl-pill warn' }, 'Off') : '', + E('span', { class: 'dl-spacer' }), + actions, + ]), + E('div', { class: 'dl-addrbar' }, [ + E( + 'button', + { type: 'button', class: 'dl-addrbar-seg main', title: 'Copy address and port', click: () => copyText(addr, 'Address copied') }, + [icon('globe'), E('span', { class: 'dl-mono' }, addr), icon('copy')], + ), + seg('tunnel', [E('span', { class: 'dl-mono' }, srv.ifname)]), + seg('network', [E('span', { class: 'dl-mono' }, srv.subnet)]), + srv.up ? seg('clock', [`up ${duration(srv.uptime)}`]) : '', + ]), + ]); + } + + async save(srv: Server, values: Record, ok = 'Saved') { + if (await attempt(() => api.serverUpdate(srv.id, values), ok)) await this.refresh(); + } + + /** How devices find the server and what goes into their configuration. */ + connection(srv: Server): HTMLElement { + const name = input(srv.name, { placeholder: 'Home' }); + const endpoint = input(srv.endpoint, { placeholder: 'vpn.example.com', class: 'cbi-input-text dl-mono' }); + const port = input(String(srv.port), { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }); + const dns = input(srv.dns.join(', '), { placeholder: 'This router (recommended)', class: 'cbi-input-text 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' }); + return card( + 'Connection', + [ + E('p', { class: 'dl-muted' }, 'How devices find this server, and what goes into their configuration.'), + group('router', 'Server', 'What people see', [row('Name', name, 'Shown to people in their portal.')]), + group('globe', 'Devices connect to', 'Where the tunnel answers from the internet', [ + row( + 'Public address', + endpoint, + 'Hostname or IP of the router on the internet. A DDNS name keeps links working when your IP changes.', + ), + 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('DNS for devices', dns, 'Empty = this router, which sends each query where your home network would.'), + 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.'), + ]), + ], + [ + E('span'), + button( + 'Save', + () => + this.save(srv, { + name: name.value, + endpoint: endpoint.value, + port: port.value, + dns: dns.value, + mtu: mtu.value, + keepalive: ka.value, + }), + 'positive', + ), + ], + ); + } + + /** Where devices may go and how their traffic leaves: internet path, WAN, home network, services. */ + access(srv: Server): HTMLElement { + const svcs = this.st.services; + return E('div', { class: 'dl-stack gap16' }, [ + interfacesCard(srv.id, 'Access'), + card( + 'Home services', + [ + E( + 'p', + { class: 'dl-muted' }, + 'People with Home-only access can be limited to these services instead of the whole home network (chosen per person). The list is shared by all servers.', + ), + E( + 'div', + { class: 'dl-list' }, + svcs.length + ? svcs.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'}`, + ), + ]), + ]), + ) + : [E('div', { class: 'dl-row dl-muted' }, 'No services yet.')], + ), + ], + [ + E('span'), + E( + 'a', + { class: 'cbi-button cbi-button-neutral', href: `${L.url('admin/network/dawnline/settings')}#dl-set-services` }, + 'Edit in Settings', + ), + ], + ), + ]); + } + + disguise(srv: Server): HTMLElement { + const current = methodInfo(srv.preset) ? (srv.preset as Method) : undefined; + let selected: Method = current ?? 'standard'; + const action = button('', () => this.applyDisguise(srv, selected, selected === current), 'positive'); + const label = () => { + dom.content(action, selected === current ? [icon('reset'), ' Generate new values'] : `Switch to ${methodInfo(selected)!.title}`); + }; + label(); + const params = paramsView(srv.obf ?? {}); + return card( + '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.', + ), + methodPicker( + this.st.awg, + selected, + (m) => { + selected = m; + label(); + }, + current, + ), + !this.st.awg.v3 + ? callout('info', [ + 'This router runs an older AmneziaWG. ', + E('b', {}, 'Maximum'), + ' becomes available with kmod-amneziawg and amneziawg-tools 3.1.', + ]) + : '', + params ?? '', + ], + [E('span', { class: 'dl-sub' }, 'Applies at once. Every device on this server must import its configuration again.'), action], + ); + } + + async applyDisguise(srv: Server, m: Method, same: boolean) { + const info = methodInfo(m)!; + const people = this.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} 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 this.refresh(); + } + } + + /** Technical details that rarely change, then the danger zone. */ + tunnel(srv: Server): HTMLElement { + const people = this.st.people.filter((p) => p.server === srv.id).length; + const toggle = button( + srv.enabled ? 'Turn off' : 'Turn on', + async () => { + if ( + srv.enabled && + !(await confirmDialog( + `Turn off ${srv.name}?`, + `The tunnel stops and ${people} ${people === 1 ? 'person is' : 'people are'} disconnected until you turn it back on. Nothing is deleted.`, + 'Turn off', + true, + )) + ) + return; + await this.save(srv, { enabled: srv.enabled ? '0' : '1' }, srv.enabled ? 'Server turned off' : 'Server turned on'); + }, + srv.enabled ? 'negative' : 'positive', + ); + return E('div', { class: 'dl-stack gap16' }, [ + card( + 'Tunnel', + [ + E('p', { class: 'dl-muted' }, 'Technical details. They are set when the server is created and rarely change.'), + 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', + }), + ]), + ), + row('Link path', E('span', { class: 'dl-mono' }, `/${srv.id}/`), 'Changing it would break every personal link already sent.'), + ], + [], + ), + card( + 'Danger zone', + [ + E('div', { class: 'dl-setrow' }, [ + E('div', { class: 'dl-stack' }, [ + E('span', { class: 'dl-setrow-label' }, srv.enabled ? 'Turn off this server' : 'This server is off'), + E( + 'span', + { class: 'dl-sub' }, + srv.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' }, toggle), + ]), + 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 ${people} ${people === 1 ? 'person' : 'people'} with all their devices. A backup is made first.`, + ), + ]), + E( + 'div', + { class: 'dl-setrow-ctl' }, + button([icon('trash'), ' Remove'], () => this.remove(srv), 'negative'), + ), + ]), + ], + [], + 'danger', + ), + ]); + } + + /* ---------------- add / remove ---------------- */ + + async addServer() { + const d = await attempt(() => api.setupDefaults()); + if (!d) return; + dom.content( + this.root, + this.wizard(d, true, () => { + dom.content(this.root, [this.tabsEl, this.headEl, this.secEl, this.bodyEl]); + this.paint(); + }), + ); + } + + async remove(srv: Server) { + const people = this.st.people.filter((p) => p.server === srv.id); + modal( + `Remove ${srv.name}?`, + [ + E( + 'p', + {}, + `This removes the tunnel, its firewall rules and ${people.length} ${people.length === 1 ? 'person' : 'people'} with all their devices. A backup is made first.`, + ), + ], + [ + E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + ' ', + button( + 'Remove', + async () => { + closeModal(); + if (await attempt(() => api.serverDelete(srv.id), 'Server removed')) + setTimeout(() => { + location.href = url(); + }, 800); + }, + 'negative', + ), + ], + ); + } + + /* ---------------- wizard ---------------- */ + + /** + * Setup wizard. `extra` adds one more server next to existing ones: the + * portal is already set up then, so that step is left out. + */ + wizard(d: SetupDefaults, extra = false, onCancel?: () => void): HTMLElement { + const state = { + id: d.id, + name: d.name, + endpoint: d.endpoint, + port: d.port, + subnet: d.subnet, + preset: 'standard' as Method, + portal: true, + portal_port: d.portal_port || 8443, + lan_zone: d.lan_zone, + wan_zone: d.wan_zone, + }; + let step = 0; + const root = E('div', { class: 'dl-wizard' }); + const field = (key: 'id' | 'name' | 'endpoint' | 'port' | 'subnet' | 'portal_port', attrs: Record = {}) => { + const el = input(String(state[key]), attrs); + el.addEventListener('input', () => { + (state as any)[key] = key === 'port' || key === 'portal_port' ? Number(el.value) : el.value.trim(); + }); + return el; + }; + + const steps = extra ? ['Connection', 'Disguise'] : ['Connection', 'Disguise', 'Portal']; + const pages: (() => Node)[] = [ + () => + E('div', {}, [ + E( + 'p', + {}, + 'Where devices connect to. Use a hostname that always points at your router (DDNS), so links keep working when your IP changes.', + ), + row('Name', field('name'), 'Shown to people in their portal.'), + row( + 'Link path', + field('id', { maxlength: 24, class: 'cbi-input-text dl-mono' }), + 'First part of personal links: https://address:port//.', + ), + row( + 'Public address', + field('endpoint', { placeholder: 'vpn.example.com', class: 'cbi-input-text dl-mono' }), + 'Hostname or IP address of your router on the internet.', + ), + row( + 'UDP port', + field('port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }), + 'Opened on the WAN firewall automatically. A random high port is fine.', + ), + row( + 'Tunnel subnet', + field('subnet', { class: 'cbi-input-text dl-mono' }), + `Addresses for devices. Must not overlap your networks (${d.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.', + ), + methodPicker(d.awg, state.preset, (m) => (state.preset = m)), + ]), + () => { + const portalPort = field('portal_port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }); + return E('div', {}, [ + callout( + 'info', + 'Devices reach the internet the way devices on your home network do: whatever handles home traffic on this router handles theirs too. You can change this later under Servers → Access.', + ), + E('h4', {}, 'Personal portal'), + E('p', {}, 'A small page where each person adds their own devices, with their personal link. It gets its own HTTPS port on WAN.'), + choices( + [ + { v: 'on', title: 'On', ic: 'link', text: 'People manage their devices themselves within the limits you set.' }, + { v: 'off', title: 'Off', ic: 'x', text: 'Only you add devices, from LuCI.' }, + ], + 'on', + (v) => { + state.portal = v === 'on'; + portalPort.disabled = !state.portal; + }, + ), + row('Portal port', portalPort, 'TCP port on WAN. The whole port belongs to the portal.'), + ]); + }, + ]; + + const paint = () => { + dom.content(root, [ + E('h2', {}, extra ? 'Add a server' : 'Set up Dawnline'), + E( + 'div', + { class: 'dl-steps' }, + steps.map((s, i) => + E('span', { class: `dl-step${i === step ? ' current' : i < step ? ' done' : ''}` }, [ + E('b', {}, i < step ? '✓' : String(i + 1)), + s, + ]), + ), + ), + E('div', { class: 'dl-panel' }, pages[step]()), + E('div', { class: 'dl-actions' }, [ + step > 0 + ? button('Back', () => { + step--; + paint(); + }) + : onCancel + ? button('Cancel', onCancel) + : '', + E('span', { class: 'dl-spacer' }), + step < steps.length - 1 + ? button( + 'Next', + () => { + if (step === 0 && (!state.endpoint || !state.port || !state.subnet)) { + notify('Fill in the public address, port and subnet.', 'warning'); + return; + } + step++; + paint(); + }, + 'positive', + ) + : button( + 'Create server', + async () => { + // An extra server leaves the portal settings alone (undefined is not sent). + const r = await attempt( + () => + api.serverCreate( + state.id, + state.name, + d.ifname, + state.port, + state.subnet, + state.endpoint, + d.mtu, + state.preset, + state.lan_zone, + state.wan_zone, + true, + extra ? undefined : state.portal, + extra ? undefined : state.portal_port, + ), + 'Server created', + ); + if (r) + setTimeout(() => { + location.href = url(r.id); + }, 1500); + }, + 'positive', + ), + ]), + ]); + }; + paint(); + return root; + } +} diff --git a/web/src/admin/pages/settings.ts b/web/src/admin/pages/settings.ts new file mode 100644 index 0000000..fdfd39f --- /dev/null +++ b/web/src/admin/pages/settings.ts @@ -0,0 +1,839 @@ +// Settings: section cards, each with its own Save (applied immediately). + +import { E } from '../e'; +import { api, type Backup, type SettingsData } from '../api'; +import { attempt, button, closeModal, confirmDialog, modal } from '../ui'; +import { icon } from '../../shared/icons'; +import { installPalette } from '../palette'; +import { group, input, isOn, row, sw } from '../kit'; +import { CATEGORIES, CATEGORY_HELP, CATEGORY_LABEL, clearLogDialog, exportEvents, resetUsageDialog } from '../logs'; +import { retentionText } from './activity'; +import { backupsSection } from '../backups'; +import { installMissing } from '../pkgs'; + +type Values = Record; + +/** Single-choice pill row; read the choice with `.dataset.value`. */ +function seg(options: [string, string][], value: string, label: string): HTMLElement { + if (!options.some(([v]) => v === value)) options = [...options, [value, value]]; + const el = E('div', { class: 'dl-seg sm', role: 'radiogroup', 'aria-label': label, 'data-value': value }); + const paint = () => + dom.content( + el, + options.map(([v, t]) => + E( + 'button', + { + type: 'button', + role: 'radio', + class: v === el.dataset.value ? 'on' : '', + 'aria-checked': v === el.dataset.value ? 'true' : 'false', + click: () => { + el.dataset.value = v; + paint(); + }, + }, + t, + ), + ), + ); + paint(); + return el; +} + +function plural(n: number, one: string, many = `${one}s`): string { + return `${n.toLocaleString('en-GB')} ${n === 1 ? one : many}`; +} + +function kb(n: number): string { + return n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(n < 10240 ? 1 : 0)} KB` : `${(n / 1048576).toFixed(1)} MB`; +} + +export class SettingsPage { + d!: SettingsData; + root = E('div', { class: 'dl-settings-main' }); + backups: Backup[] = []; + + load() { + return api.settingsGet(); + } + + render(d: SettingsData): HTMLElement { + this.d = d; + installPalette(); + this.paint(); + this.loadBackups().then(() => { + if (new URLSearchParams(location.search).get('section') === 'backups') + document.getElementById('dl-set-backups')?.scrollIntoView({ block: 'start' }); + }); + return E('div', {}, [E('div', { class: 'dl-pagehead' }, [E('h2', { class: 'dl-h1' }, 'Settings')]), this.root]); + } + + async save(values: Values, ok = 'Saved') { + const r = await attempt(() => api.settingsUpdate(values), ok); + if (r) { + this.d = r; + this.paint(); + } + } + + section(id: string, title: string, body: (Node | string)[], foot: Node[], extra = '', head: (Node | string)[] = []): HTMLElement { + return E('section', { class: `dl-setsec ${extra}`, id: `dl-set-${id}` }, [ + E('div', { class: 'dl-setsec-body' }, [ + head.length + ? E('div', { class: 'dl-setsec-head' }, [E('h3', {}, title), E('span', { class: 'dl-spacer' }), ...head]) + : E('h3', {}, title), + ...body, + ]), + foot.length ? E('div', { class: 'dl-setsec-foot' }, foot) : '', + ]); + } + + /** Personal portal: the address in links (picked from what the router found), a preview, readiness, and the rest folded away. */ + portalSection(): HTMLElement { + const s = this.d.settings; + const eff = this.d.effective as Record; + const c = this.d.cert; + const cands = this.d.portal_candidates ?? []; + const checks = this.d.portal_checks ?? []; + const pOn = sw(eff.portal_enabled, 'Enable portal'); + const port = input(s.portal_port, { placeholder: '8443', inputmode: 'numeric', class: 'cbi-input-text dl-w-port' }); + const on443 = sw(eff.portal_443, 'Standard ports', () => paintLinks()); + const title = input(s.portal_title, { placeholder: 'Dawnline' }); + const redirect = input(s.portal_redirect, { placeholder: 'Show “Not found”', class: 'cbi-input-text dl-mono' }); + const other = input('', { placeholder: 'vpn.example.com or an IP', 'aria-label': 'Other address' }); + const isIp = (h: string) => /^\d{1,3}(\.\d{1,3}){3}$/.test(h); + // Chosen addresses, the main one first; custom ones join the list of options. + let picked: string[] = [eff.portal_host, ...(eff.portal_alt ?? [])].filter( + (h: string, i: number, a: string[]) => h && a.indexOf(h) === i, + ); + if (!picked.length && cands[0]) picked = [cands[0].host]; + const rows = [...cands]; + const addRow = (h: string) => { + if (h && !rows.some((x) => x.host === h)) + rows.push({ host: h, kind: isIp(h) ? 'ip' : 'name', ips: [], here: false, cloudflare: false, cert: false }); + }; + picked.forEach(addRow); + + const note = (x: (typeof cands)[number]): Node => + x.kind === 'ip' + ? E('span', { class: 'dl-addr-warn' }, [icon('alert'), 'Plain HTTP: the link and VPN keys travel unencrypted']) + : E( + 'span', + { class: 'dl-sub' }, + x.cloudflare + ? 'Behind Cloudflare · often stalls in Russia' + : !x.ips.length + ? 'Your address' + : x.here + ? `Points at this router${x.cert ? ' · Let’s Encrypt certificate' : ' · no certificate yet'}` + : `Points at ${x.ips.join(', ')}, not this router`, + ); + const opts = E('div', { class: 'dl-addr-opts', role: 'group', 'aria-label': 'Portal addresses' }); + const toggle = (h: string) => { + if (picked.includes(h)) { + if (picked.length > 1) picked = picked.filter((x) => x !== h); + } else picked = [...picked, h]; + paintOpts(); + paintLinks(); + }; + const paintOpts = () => + dom.content(opts, [ + ...rows.map((x) => { + const on = picked.includes(x.host), + main = picked[0] === x.host; + return E( + 'div', + { + class: `dl-addr-opt${on ? ' on' : ''}`, + role: 'checkbox', + 'aria-checked': on ? 'true' : 'false', + tabindex: '0', + click: () => toggle(x.host), + keydown: (ev: KeyboardEvent) => { + if (ev.key === ' ' || ev.key === 'Enter') { + ev.preventDefault(); + toggle(x.host); + } + }, + }, + [ + E('i', { class: 'dl-addr-check' }, on ? icon('check') : ''), + E('span', { class: 'dl-stack' }, [E('span', { class: 'dl-mono' }, x.host), note(x)]), + main + ? E('span', { class: 'dl-pill info' }, 'Main') + : on + ? E( + 'button', + { + type: 'button', + class: 'dl-linkbtn', + click: (ev: Event) => { + ev.stopPropagation(); + picked = [x.host, ...picked.filter((h) => h !== x.host)]; + paintOpts(); + paintLinks(); + }, + }, + 'Make main', + ) + : x.cloudflare + ? E('span', { class: 'dl-pill warn' }, 'Cloudflare') + : x.kind === 'ip' + ? E('span', { class: 'dl-pill' }, 'IP') + : x.here && x.cert + ? E('span', { class: 'dl-pill ok' }, 'Recommended') + : '', + ], + ); + }), + E('div', { class: 'dl-addr-opt other' }, [ + E('i', { class: 'dl-addr-check' }, icon('plus')), + other, + button('Add', () => { + const h = other.value.trim().toLowerCase(); + if (!h) return; + addRow(h); + if (!picked.includes(h)) picked = [...picked, h]; + other.value = ''; + paintOpts(); + paintLinks(); + }), + ]), + ]); + other.addEventListener('keydown', (ev: KeyboardEvent) => { + if (ev.key === 'Enter') { + ev.preventDefault(); + (other.nextElementSibling as HTMLElement)?.click(); + } + }); + + // One row per link, as people will see it (example code). + const links = E('div', { class: 'dl-links' }); + const paintLinks = () => { + const std = isOn(on443); + const lport = Number(port.value) || eff.portal_port; + dom.content( + links, + picked.map((h, i) => { + const ip = isIp(h); + const p = ip ? (std ? 80 : lport + 1) : std && !this.d.wan443_taken ? 443 : lport; + const base = `${ip ? 'http' : 'https'}://${h}${p === (ip ? 80 : 443) ? '' : `:${p}`}/`; + return E('div', { class: 'dl-link-row' }, [ + E('span', { class: `dl-link-ic ${ip ? 'warn' : 'ok'}` }, icon(ip ? 'alert' : 'lock')), + E('span', { class: 'dl-mono dl-link-url' }, [base, E('b', {}, 'kamiro-telosu-bavine')]), + i === 0 ? E('span', { class: 'dl-pill info' }, 'Main') : ip ? E('span', { class: 'dl-pill warn' }, 'HTTP') : '', + ]); + }), + ); + }; + paintOpts(); + paintLinks(); + port.addEventListener('input', () => paintLinks()); + + // Readiness: one summary line, the checks as chips, details on demand. + const SHORT: Record = { + 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', + }; + const shown = checks.filter((x) => x.status !== 'skip'); + const bad = shown.filter((x) => x.status === 'error' || x.status === 'warn'); + const worst = shown.some((x) => x.status === 'error') ? 'error' : bad.length ? 'warn' : 'ok'; + const details = E( + 'div', + { class: 'dl-ready-details', hidden: true }, + shown.map((x) => + E('div', { class: `dl-ready-item ${x.status}` }, [ + icon(x.status === 'ok' ? 'check' : 'alert'), + E('span', { class: 'dl-stack' }, [E('span', {}, x.title), E('span', { class: 'dl-sub' }, x.detail)]), + ]), + ), + ); + const ready = E('div', { class: 'dl-stack gap8' }, [ + E('div', { class: `dl-ready-sum ${worst}` }, [ + icon(worst === 'ok' ? 'check' : 'alert'), + E('span', { class: 'dl-stack' }, [ + E( + 'b', + {}, + worst === 'ok' ? `All ${shown.length} checks passed` : `${shown.length - bad.length} of ${shown.length} checks passed`, + ), + bad.length + ? E('span', { class: 'dl-sub' }, bad.map((x) => x.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: (ev: Event) => { + details.hidden = !details.hidden; + (ev.currentTarget as HTMLElement).textContent = details.hidden ? 'Details' : 'Hide'; + }, + }, + 'Details', + ), + ]), + E( + 'div', + { class: 'dl-chips-row' }, + shown.map((x) => + E('span', { class: `dl-check-chip ${x.status}`, title: x.detail }, [ + icon(x.status === 'ok' ? 'check' : 'alert'), + SHORT[x.id] ?? x.title, + ]), + ), + ), + details, + ]); + + const until = + c && !c.self_signed && c.expires + ? new Date(c.expires).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }) + : ''; + const portsRow = row( + 'Standard ports', + on443, + 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.', + ); + const listenRow = row( + 'Listening port', + port, + this.d.port_owners.length + ? `Port ${eff.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 ${eff.portal_port + 1}.`, + ); + const custom = !!(s.portal_cert && s.portal_key); + const kind = !c ? 'Portal is off' : custom ? 'Your files' : c.self_signed ? 'Self-signed' : 'Let’s Encrypt'; + const certFiles = () => { + const fc = input(s.portal_cert, { placeholder: '/etc/ssl/…/fullchain.crt' }); + const fk = input(s.portal_key, { placeholder: '/etc/ssl/…/key' }); + modal( + 'Use your own certificate', + [ + E('p', { class: 'dl-muted' }, 'Paths on the router. Leave both empty to pick a certificate automatically.'), + row('Certificate file', fc), + row('Key file', fk), + ], + [ + E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + ' ', + button( + 'Save', + () => { + closeModal(); + this.save({ portal_cert: fc.value.trim(), portal_key: fk.value.trim() }, 'Certificate saved'); + }, + 'positive', + ), + ], + ); + }; + const need = this.d.needs ?? { https: [], acme: [], home: [] }; + const needRow = (ic: string, tone: string, title: string, sub: string, feature: 'https' | 'acme', label: string) => + E('div', { class: `dl-row dl-need-row ${tone}` }, [ + tone ? E('span', { class: 'dl-need-ic' }, icon(ic)) : icon(ic), + E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, title), E('span', { class: 'dl-sub' }, sub)]), + button(label, () => installMissing(feature, need[feature], () => this.reload()), 'positive'), + ]); + const httpsRow = need.https.length + ? needRow( + 'lock', + 'bad', + 'HTTPS isn’t available on this router', + `The portal needs ${need.https.join(' and ')}. It can’t start without them.`, + 'https', + 'Install', + ) + : ''; + const acmeRow = + need.acme.length && (!c || c.self_signed) + ? needRow( + 'lock', + '', + 'Free certificate from Let’s Encrypt', + `ACME isn’t installed. With it the router gets a certificate${s.portal_host ? ` for ${s.portal_host}` : ''} and browsers stop warning.`, + 'acme', + 'Install ACME', + ) + : ''; + const certRows = [ + E('div', { class: 'dl-row' }, [ + icon('lock'), + E('span', { class: 'dl-row-main dl-stack' }, [ + E('b', {}, [kind, until ? E('span', { class: 'dl-faint' }, ` · until ${until}`) : '']), + E( + 'span', + { class: 'dl-sub dl-ellipsis', title: c?.path ?? '' }, + !c + ? 'Turn the portal on to see its certificate.' + : c.self_signed + ? 'Made by the router: browsers warn until a certificate covers the address.' + : `${custom ? 'Your files' : 'Found automatically'} · ${c.path}`, + ), + ]), + ]), + E('div', { class: 'dl-row' }, [ + icon('file'), + E('span', { class: 'dl-row-main dl-stack' }, [ + E('b', {}, 'Your own files'), + E( + 'span', + { class: 'dl-sub' }, + custom ? `${s.portal_cert} · ${s.portal_key}` : 'Not set: the certificate is picked automatically.', + ), + ]), + custom ? button('Reset', () => this.save({ portal_cert: '', portal_key: '' }, 'Automatic certificate'), 'negative') : '', + button(custom ? 'Change' : 'Use files', certFiles), + ]), + acmeRow, + ]; + + 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.'), + httpsRow ? E('div', { class: 'dl-list' }, [httpsRow]) : '', + group('network', 'Ports', 'How the portal listens', [portsRow, listenRow]), + group('edit', 'Appearance', 'What people see', [ + row('Title', title, 'Shown at the top of the portal.'), + row('Unknown links', redirect, 'Where a wrong or old link goes, for example your website. Empty shows a plain “Not found”.'), + ]), + group('link', 'Addresses', 'Pick one or more; the first is the main link', [ + opts, + E('div', { class: 'dl-stack gap8' }, [ + links, + E('span', { class: 'dl-sub' }, 'Example code; each person gets their own three words.'), + ]), + ]), + group('lock', 'Certificate', 'Used for HTTPS links', certRows), + eff.portal_enabled && shown.length ? group('check', 'Ready to share', 'The portal’s checks from Health', [ready]) : '', + ], + [ + E('span'), + button( + 'Save', + () => + this.save({ + portal_enabled: isOn(pOn) ? '1' : '0', + portal_443: isOn(on443) ? '1' : '0', + portal_host: picked[0] ?? '', + portal_alt: picked.slice(1), + portal_port: port.value, + portal_title: title.value, + portal_redirect: redirect.value.trim(), + }), + 'positive', + ), + ], + '', + [ + eff.portal_enabled + ? need.https.length + ? E('span', { class: 'dl-pill bad' }, 'Can’t start') + : E( + 'span', + { class: `dl-pill ${worst === 'ok' ? 'ok' : worst === 'error' ? 'bad' : 'warn'}` }, + worst === 'error' ? 'Needs attention' : 'Ready', + ) + : '', + pOn, + ], + ); + } + + paint() { + const s = this.d.settings; + const eff = this.d.effective as Record; + + // Personal portal + const portal = this.portalSection(); + + // Defaults + const limit = input(s.default_device_limit, { placeholder: '3', inputmode: 'numeric', class: 'cbi-input-text dl-w-port' }); + const hn = sw(eff.hostnames, 'Device hostnames'); + const domain = input(s.domain, { placeholder: 'lan', class: 'cbi-input-text dl-w-port' }); + const fallback = input(s.home_dns_fallback === 'none' ? '' : s.home_dns_fallback || eff.home_dns_fallback || '', { + placeholder: 'None', + inputmode: 'decimal', + class: 'cbi-input-text dl-w-ip dl-mono', + }); + const defaults = this.section( + 'defaults', + 'Defaults', + [ + row('Devices per person', limit, 'Pre-filled when you add someone.'), + row( + 'Device hostnames', + E('div', { class: 'dl-hostport' }, [hn, E('span', { class: 'dl-faint dl-mono' }, 'phone.myata.'), domain]), + 'Name devices in your home DNS.', + ), + row( + 'Fallback DNS', + fallback, + 'For Home-only devices using home names: the second DNS server, used by the device when the tunnel is down. Empty = none.', + ), + ], + [ + E('span'), + button( + 'Save', + () => + this.save({ + default_device_limit: limit.value, + hostnames: isOn(hn) ? '1' : '0', + domain: domain.value, + home_dns_fallback: fallback.value, + }), + 'positive', + ), + ], + ); + + // Map + const gOn = sw(eff.geo_enabled, 'Locations'); + const prov = E('select', { class: 'cbi-input-select' }, [ + E('option', { value: 'ipwho.is', selected: eff.geo_provider !== 'ipapi.co' ? 'selected' : null }, 'ipwho.is (fallback: ipapi.co)'), + E('option', { value: 'ipapi.co', selected: eff.geo_provider === 'ipapi.co' ? 'selected' : null }, 'ipapi.co (fallback: ipwho.is)'), + ]) as HTMLSelectElement; + const map = 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.'), + gOn, + ]), + row('Provider', prov), + ], + [ + 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.', + ), + button('Save', () => this.save({ geo_enabled: isOn(gOn) ? '1' : '0', geo_provider: prov.value }), 'positive'), + ], + ); + + const logs = this.logsSection(); + + // Home services + const svcRows = this.d.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', () => this.editService(sv)), + 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')) + ) + this.reload(); + }, + 'negative', + { title: 'Remove' }, + ), + ]), + ); + const services = this.section( + 'services', + 'Home services', + [ + E( + 'p', + { class: 'dl-muted' }, + 'Give people with home-network access only specific services instead of the whole network (choose them per person).', + ), + E('div', { class: 'dl-list' }, svcRows.length ? svcRows : [E('div', { class: 'dl-row dl-muted' }, 'No services yet.')]), + ], + [E('span'), button([icon('plus'), ' Add service'], () => this.editService(null), 'add')], + ); + + const danger = 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'), button('Remove', () => this.uninstall(), 'negative')], + 'danger', + ); + + const backups = backupsSection(this.backups, () => { + this.reload(); + this.loadBackups(); + }); + dom.content(this.root, [portal, defaults, map, logs, services, backups, danger]); + } + + logsSection(): HTMLElement { + const L = this.d.logs; + const p = L.policy; + const keep = seg( + [ + ['7', '7 days'], + ['30', '30 days'], + ['90', '90 days'], + ['365', '1 year'], + ['0', 'No limit'], + ], + String(p.keep_days), + 'Keep activity', + ); + const size = seg( + [ + ['500', '500'], + ['2000', '2,000'], + ['5000', '5,000'], + ['20000', '20,000'], + ], + String(p.max), + 'Maximum events', + ); + const persist = seg( + [ + ['10min', 'Every 10 min'], + ['hourly', 'Hourly'], + ['off', 'Memory only'], + ], + p.persist, + 'Save to flash', + ); + const days = seg( + [ + ['31', '1 month'], + ['62', '2 months'], + ['180', '6 months'], + ['365', '1 year'], + ['730', '2 years'], + ], + String(p.usage_days), + 'Daily traffic', + ); + const months = seg( + [ + ['12', '1 year'], + ['24', '2 years'], + ['60', '5 years'], + ['120', '10 years'], + ], + String(p.usage_months), + 'Monthly traffic', + ); + const chosen = new Set(p.categories); + const cats = E( + 'div', + { class: 'dl-chips-row' }, + CATEGORIES.map((c) => { + const b = E( + 'button', + { + type: 'button', + class: `dl-chipbtn${chosen.has(c) ? ' on' : ''}`, + title: CATEGORY_HELP[c], + click: () => { + if (chosen.has(c)) chosen.delete(c); + else chosen.add(c); + b.classList.toggle('on', chosen.has(c)); + }, + }, + [CATEGORY_LABEL[c], E('b', {}, String(L.by_category[c] ?? 0))], + ); + return b; + }), + ); + + const fmtDay = (d: Date | string) => new Date(d).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }); + const since = L.oldest ? fmtDay(new Date(L.oldest * 1000)) : ''; + const stored = (ic: string, title: string, detail: string, actions: Node[]) => + E('div', { class: 'dl-row' }, [ + icon(ic), + E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, title), E('span', { class: 'dl-sub' }, detail)]), + ...actions, + ]); + const exportBtn = (fmt: 'csv' | 'json') => + button( + fmt.toUpperCase(), + async () => { + const [st, ev] = await Promise.all([api.status(1), api.events(20000)]); + exportEvents(st, ev.events, fmt); + }, + 'neutral', + { title: `Download the log as ${fmt.toUpperCase()}` }, + ); + + return this.section( + 'logs', + 'Logs & history', + [ + E('p', { class: 'dl-muted' }, retentionText(p)), + row('Keep activity', keep, 'Older events are removed automatically.'), + row('Maximum size', size, 'Newest events are kept when the log is full.'), + row('Record', cats, 'Switched-off categories are not logged from now on.'), + row( + 'Save to flash', + persist, + 'The log lives in memory and is copied to flash. Memory only saves flash writes but is lost on reboot.', + ), + row('Daily traffic', days, 'Per-day history behind the charts.'), + row('Monthly traffic', months, 'Per-month totals; data limits use the current month.'), + E('h4', { class: 'dl-setsub' }, 'Stored data'), + E('div', { class: 'dl-list' }, [ + stored( + 'activity', + 'Activity log', + L.events + ? `${plural(L.events, 'event')} since ${since} · ${kb(L.log_ram)} in memory${p.persist === 'off' ? '' : `, ${kb(L.log_flash)} on flash`}` + : 'Empty', + [ + exportBtn('csv'), + exportBtn('json'), + button( + 'Clear', + () => clearLogDialog('Clear activity', 'Removes events from the log on the router.', {}, () => this.reload()), + 'negative', + ), + ], + ), + stored( + 'chart', + 'Traffic history', + L.usage_days ? `${plural(L.usage_days, 'day')} since ${fmtDay(L.usage_since)} · ${kb(L.usage_flash)} on flash` : 'Empty', + [button('Reset', () => resetUsageDialog('all', '', '', () => setTimeout(() => this.reload(), 300)), 'negative')], + ), + stored('pin', 'Location cache', `${plural(this.d.geo_cached, 'address', 'addresses')} · ${kb(L.geo_flash)} on flash`, [ + button( + 'Clear', + async () => { + if (await attempt(() => api.geoClear(), 'Location cache cleared')) this.reload(); + }, + 'negative', + ), + ]), + ]), + ], + [ + E('span', { class: 'dl-sub' }, 'Clear one person or device from their own page.'), + button( + 'Save', + () => + this.save({ + log_keep_days: keep.dataset.value!, + log_max: size.dataset.value!, + log_persist: persist.dataset.value!, + usage_keep_days: days.dataset.value!, + usage_keep_months: months.dataset.value!, + log_category: [...chosen], + }), + 'positive', + ), + ], + ); + } + + async loadBackups() { + const r = await api.backupList().catch(() => null); + if (r) { + this.backups = r.backups; + const old = document.getElementById('dl-set-backups'); + if (old) + old.replaceWith( + backupsSection(this.backups, () => { + this.reload(); + this.loadBackups(); + }), + ); + } + } + + async reload() { + const d = await api.settingsGet().catch(() => null); + if (d) { + this.d = d; + this.paint(); + } + } + + editService(sv: SettingsData['services'][number] | null) { + const name = input(sv?.name ?? '', { placeholder: 'NAS' }); + const addr = input(sv?.address ?? '', { placeholder: '192.168.1.10' }); + const ports = input(sv?.ports.join(', ') ?? '', { placeholder: 'All ports, or e.g. 445, 5000' }); + modal( + sv ? `Edit ${sv.name}` : 'Add service', + [ + E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, 'Name'), E('div', { class: 'cbi-value-field' }, name)]), + E('div', { class: 'cbi-value' }, [ + E('label', { class: 'cbi-value-title' }, 'Address'), + E('div', { class: 'cbi-value-field' }, addr), + ]), + E('div', { class: 'cbi-value' }, [ + E('label', { class: 'cbi-value-title' }, 'Ports'), + E('div', { class: 'cbi-value-field' }, ports), + ]), + ], + [ + E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + ' ', + button( + 'Save', + async () => { + const list = ports.value.split(/[ ,]+/).filter(Boolean); + if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), 'Saved')) { + closeModal(); + this.reload(); + } + }, + 'positive', + ), + ], + ); + } + + uninstall() { + const confirmInput = input('', { placeholder: 'remove' }); + modal( + '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.', + ), + confirmInput, + ], + [ + E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'), + ' ', + button( + 'Remove Dawnline', + async () => { + if (await attempt(() => api.uninstall(confirmInput.value.trim()), 'Dawnline removed')) { + closeModal(); + setTimeout(() => location.reload(), 800); + } + }, + 'negative', + ), + ], + ); + } +} diff --git a/web/src/admin/palette.ts b/web/src/admin/palette.ts new file mode 100644 index 0000000..35bc3e4 --- /dev/null +++ b/web/src/admin/palette.ts @@ -0,0 +1,255 @@ +// ⌘K / Ctrl+K command menu: jump to people and devices (also by IP or +// address) and run the common actions without leaving the keyboard. + +import type { Person, Status } from '../shared/types'; +import { E } from './e'; +import { api } from './api'; +import { attempt, copyText } from './ui'; +import { icon } from '../shared/icons'; +import { ACCESS_SHORT, initials } from '../shared/format'; + +interface Item { + group: string; + label: string; + hint?: string; + icon?: string; + avatar?: string; + kbd?: string; + run: () => unknown; +} + +let cache: { st: Status; at: number } | null = null; +let open = false; + +/** A server's People section (Servers page). */ +export function peopleUrl(server?: string): string { + return `${L.url('admin/network/dawnline/server')}?${server ? `server=${encodeURIComponent(server)}&` : ''}section=people`; +} + +export function personUrl(id: string, device?: string): string { + return `${L.url('admin/network/dawnline/person')}?id=${encodeURIComponent(id)}${device ? `&device=${encodeURIComponent(device)}` : ''}`; +} + +function go(path: string) { + location.href = L.url(`admin/network/dawnline/${path}`); +} + +function addMonths(iso: string, n: number): string { + const base = iso ? new Date(`${iso}T12:00:00`) : new Date(); + const from = base.getTime() < Date.now() ? new Date() : base; + from.setMonth(from.getMonth() + n); + return `${from.getFullYear()}-${String(from.getMonth() + 1).padStart(2, '0')}-${String(from.getDate()).padStart(2, '0')}`; +} + +function personActions(p: Person, done: () => void): Item[] { + const g = `Actions for ${p.name}`; + const items: Item[] = []; + if (p.link) + items.push({ group: g, label: 'Copy personal link', icon: 'link', kbd: 'C', run: () => copyText(p.link!, 'Personal link copied') }); + items.push({ group: g, label: `Add device for ${p.name}`, icon: 'plus', run: () => (location.href = `${personUrl(p.id)}&add=1`) }); + items.push({ + group: g, + label: p.paused ? `Resume ${p.name}` : `Pause ${p.name}`, + icon: p.paused ? 'play' : 'pause', + kbd: 'P', + run: async () => { + await attempt(() => api.personPause(p.id, !p.paused), p.paused ? `${p.name} resumed` : `${p.name} paused`); + done(); + }, + }); + items.push({ + group: g, + label: 'Extend access by 1 month', + icon: 'key', + run: async () => { + await attempt(() => api.personUpdate(p.id, { expires: addMonths(p.expires, 1) }), 'Access extended'); + done(); + }, + }); + return items; +} + +function build(st: Status, q: string, done: () => void): Item[] { + const query = q.trim().toLowerCase(); + const items: Item[] = []; + const people = st.people.filter((p) => !query || [p.name, p.id].some((x) => x.toLowerCase().includes(query))); + for (const p of people.slice(0, 6)) + items.push({ + group: 'People', + label: p.name, + hint: `${ACCESS_SHORT[p.access]} · ${p.online ? `${p.online} online` : `${p.devices.length} devices`}`, + avatar: initials(p.name), + run: () => (location.href = personUrl(p.id)), + }); + for (const p of st.people) + for (const d of p.devices) { + const hay = [d.name, d.address, d.endpoint, d.hostname].join(' ').toLowerCase(); + if (query && !hay.includes(query)) continue; + if (!query && !d.online) continue; + items.push({ + group: 'Devices', + label: d.name, + hint: `${p.name} · ${d.address}${d.online ? ` · ${d.endpoint}` : ''}`, + icon: d.kind, + run: () => (location.href = personUrl(p.id, d.id)), + }); + } + if (people.length === 1 || (people.length && query)) items.push(...personActions(people[0], done)); + const pages: [string, string, string][] = [ + ['overview', 'Overview', 'globe'], + ['people', 'People', 'shield'], + ['activity', 'Activity', 'file'], + ['server', 'Server', 'key'], + ['health', 'Health', 'check'], + ['settings?section=backups', 'Backups', 'archive'], + ['settings', 'Settings', 'edit'], + ]; + for (const [path, label, ic] of pages) + if (!query || label.toLowerCase().includes(query)) items.push({ group: 'Go to', label, icon: ic, run: () => go(path) }); + if (!query || 'add person'.includes(query)) + items.push({ + group: 'Go to', + label: 'Add person', + icon: 'plus', + run: () => (location.href = `${L.url('admin/network/dawnline/server')}?section=people&add=1`), + }); + return items; +} + +export async function openPalette() { + if (open) return; + open = true; + const input = E('input', { + type: 'text', + class: 'dl-pal-input', + placeholder: 'Search people, devices, IPs or actions…', + 'aria-label': 'Search', + }) as HTMLInputElement; + const list = E('div', { class: 'dl-pal-list', role: 'listbox' }); + const box = E('div', { class: 'dl-pal', role: 'dialog', 'aria-label': 'Command menu' }, [ + E('label', { class: 'dl-pal-search' }, [icon('search'), input, E('kbd', {}, 'Esc')]), + list, + E('div', { class: 'dl-pal-foot' }, [ + E('span', {}, [E('kbd', {}, '↑↓'), ' navigate']), + E('span', {}, [E('kbd', {}, '↵'), ' open']), + E('span', {}, [E('kbd', {}, '⌘K'), ' toggle']), + ]), + ]); + const overlay = E('div', { class: 'dl-pal-overlay dl-root' }, box); + let items: Item[] = []; + let sel = 0; + const close = () => { + overlay.remove(); + document.removeEventListener('keydown', onKey, true); + open = false; + }; + const render = () => { + const st = cache?.st; + if (!st) { + list.replaceChildren(E('div', { class: 'dl-pal-empty' }, 'Loading…')); + return; + } + items = build(st, input.value, () => { + cache = null; + close(); + location.reload(); + }); + sel = Math.min(sel, Math.max(0, items.length - 1)); + const nodes: Node[] = []; + let group = ''; + items.forEach((it, i) => { + if (it.group !== group) { + group = it.group; + nodes.push(E('div', { class: 'dl-pal-group' }, group)); + } + const row = E( + 'div', + { + class: `dl-pal-item${i === sel ? ' sel' : ''}`, + role: 'option', + 'aria-selected': i === sel ? 'true' : 'false', + click: () => { + close(); + it.run(); + }, + mousemove: () => { + if (sel !== i) { + sel = i; + render(); + } + }, + }, + [ + it.avatar ? E('span', { class: 'dl-avatar sm' }, it.avatar) : it.icon ? icon(it.icon) : E('span', { class: 'dl-pal-ic' }), + E('span', { class: 'dl-pal-label' }, [it.label, it.hint ? E('span', { class: 'dl-faint' }, ` · ${it.hint}`) : '']), + it.kbd ? E('kbd', {}, it.kbd) : '', + ], + ); + nodes.push(row); + }); + if (!items.length) nodes.push(E('div', { class: 'dl-pal-empty' }, 'Nothing found.')); + list.replaceChildren(...nodes); + list.querySelector('.sel')?.scrollIntoView({ block: 'nearest' }); + }; + const onKey = (ev: KeyboardEvent) => { + if (ev.key === 'Escape') { + ev.preventDefault(); + close(); + } else if (ev.key === 'ArrowDown') { + ev.preventDefault(); + sel = Math.min(items.length - 1, sel + 1); + render(); + } else if (ev.key === 'ArrowUp') { + ev.preventDefault(); + sel = Math.max(0, sel - 1); + render(); + } else if (ev.key === 'Enter') { + ev.preventDefault(); + const it = items[sel]; + if (it) { + close(); + it.run(); + } + } + }; + input.addEventListener('input', () => { + sel = 0; + render(); + }); + overlay.addEventListener('click', (ev) => { + if (ev.target === overlay) close(); + }); + document.addEventListener('keydown', onKey, true); + document.body.appendChild(overlay); + input.focus(); + render(); + if (!cache || Date.now() - cache.at > 10000) { + const st = await api.status(1).catch(() => null); + if (st) cache = { st, at: Date.now() }; + if (open) render(); + } +} + +/** Install the global shortcut once per page load. */ +export function installPalette(seed?: Status) { + if (seed) cache = { st: seed, at: Date.now() }; + const w = window as any; + if (w.__dlPalette) return; + w.__dlPalette = true; + // Capture phase on window, so Outline's own ⌘K search does not open too. + window.addEventListener( + 'keydown', + (ev) => { + if (!location.pathname.includes('/admin/network/dawnline')) return; + const typing = + /^(INPUT|TEXTAREA|SELECT)$/.test((ev.target as HTMLElement)?.tagName ?? '') || (ev.target as HTMLElement)?.isContentEditable; + const cmdK = (ev.key === 'k' || ev.key === 'K') && (ev.metaKey || ev.ctrlKey); + const slash = ev.key === '/' && !typing && !document.body.classList.contains('modal-overlay-active'); + if (!cmdK && !slash) return; + ev.preventDefault(); + ev.stopImmediatePropagation(); + openPalette(); + }, + true, + ); +} diff --git a/web/src/admin/pkgs.ts b/web/src/admin/pkgs.ts new file mode 100644 index 0000000..aeebea9 --- /dev/null +++ b/web/src/admin/pkgs.ts @@ -0,0 +1,47 @@ +// Installing a missing package from wherever a feature is turned on: runs the +// updater job and follows it with toasts. + +import { api, type Needs } from './api'; +import { attempt, confirmDialog, notify } from './ui'; + +const WHAT: Record = { https: 'HTTPS for the portal', acme: 'ACME certificates', home: 'the home-like link' }; +const WAIT_MS = 5 * 60 * 1000; + +/** Install `names` for `feature`; resolves true when the job finished, then calls `done`. */ +export async function installMissing(feature: keyof Needs, names: string[], done?: () => void): Promise { + if (!names.length) return true; + const ok = await confirmDialog( + `Install ${WHAT[feature]}?`, + `${names.join(', ')} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`, + 'Install', + ); + if (!ok) return false; + // The previous job stays in the status until the updater starts: wait for a new one. + const before = (await api.updatesStatus().catch(() => null))?.job?.started ?? 0; + if (!(await attempt(() => api.updatesRun(`pkgs:${names.join(',')}`)))) return false; + notify(`Installing ${names.join(', ')}…`, 'info', 4000); + const until = Date.now() + WAIT_MS; + while (Date.now() < until) { + await new Promise((r) => setTimeout(r, 2000)); + const st = await api.updatesStatus().catch(() => null); + const job = st?.job; + if (!job || job.started === before || job.state === 'running') continue; + if (job.state === 'done') { + notify(`${names.join(', ')} installed`, 'success'); + // The service restarts to pick them up; give it a moment before reloading. + setTimeout(() => done?.(), 4000); + return true; + } + notify(job.error ?? 'Installation failed', 'error'); + return false; + } + notify('Still installing: see Updates for the log.', 'warning'); + return false; +} + +/** Install what a feature is missing, asking the router what that is now. */ +export async function installFeature(feature: keyof Needs, done?: () => void) { + const st = await attempt(() => api.updatesStatus()); + if (st) return installMissing(feature, st.needs?.[feature] ?? [], done); + return false; +} diff --git a/web/src/admin/styles.ts b/web/src/admin/styles.ts new file mode 100644 index 0000000..fc9ac1e --- /dev/null +++ b/web/src/admin/styles.ts @@ -0,0 +1,1051 @@ +// Dawnline admin styles, built on the Outline theme's design tokens +// (luci-theme-outline: --panel-bg, --border, --muted, --accent, --success-a15, +// …). Every token has a fallback so other themes still get a sane look. +// Outline switches dark mode with html[data-darkmode], and its tokens follow +// it automatically, so nothing here needs a dark variant. +// +// The diff --git a/web/src/portal/main.ts b/web/src/portal/main.ts new file mode 100644 index 0000000..a0994c0 --- /dev/null +++ b/web/src/portal/main.ts @@ -0,0 +1,970 @@ +// Dawnline personal portal: one person's devices, served by the router on +// its own HTTPS port. No framework; strict CSP (no inline scripts/styles). +// +// Layout: phone = "Your access" on top, devices below; desktop (≥ 960px) = +// devices on the left, access on the right. + +import type { ClientConfig, Device, Kind, Person } from '../shared/types'; +import { ACCESS_LABEL, KIND_LABEL, STATE_LABEL, ago, bytes, date, daysLeft, initials } from '../shared/format'; +import { iconSvg } from '../shared/icons'; +import { qrSvg } from '../shared/qr'; +import { vpnKey } from '../shared/vpnkey'; + +interface State { + title: string; + person: Person; + server: { name: string; endpoint: string }; + can_add: boolean; + kinds: Kind[]; + version: string; +} + +type Attrs = Record; +type Kid = Node | string | null | undefined | false | Kid[]; + +function h(tag: string, attrs: Attrs = {}, ...kids: Kid[]): HTMLElement { + const el = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (v == null || v === false) continue; + if (k.startsWith('on') && typeof v === 'function') el.addEventListener(k.slice(2), v as EventListener); + else if (k === 'class') el.className = String(v); + else if (v === true) el.setAttribute(k, ''); + else el.setAttribute(k, String(v)); + } + const add = (c: Kid) => { + if (c == null || c === false) return; + if (Array.isArray(c)) c.forEach(add); + else el.appendChild(typeof c === 'string' ? document.createTextNode(c) : c); + }; + kids.forEach(add); + return el; +} + +function ic(name: string): HTMLElement { + const s = h('span', { class: 'ic' }); + s.innerHTML = iconSvg(name, 'ic-svg'); + return s; +} + +const LOGO = + ''; + +const app = document.getElementById('app')!; +const base = app.dataset.base ?? ''; +const pageTitle = app.dataset.title || 'Dawnline'; +const isMobile = () => window.matchMedia('(max-width: 959px)').matches || /Android|iPhone|iPad/.test(navigator.userAgent); +let state: State | null = null; +let pollTimer = 0; +/** The personal link is the key: its path is the code (no sessions). */ +const code = /^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(base) ? base.slice(1) : ''; + +/* ---------- API ---------- */ + +class ApiError extends Error { + constructor( + public status: number, + message: string, + ) { + super(message); + } +} + +async function call(path: string, body?: unknown): Promise { + const res = await fetch(`${base}/api/${path}`, { + method: body === undefined ? 'GET' : 'POST', + credentials: 'omit', + headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + cache: 'no-store', + }); + let data: any = null; + try { + data = await res.json(); + } catch { + /* empty */ + } + if (!res.ok) throw new ApiError(res.status, data?.error ?? `Request failed (${res.status})`); + return data as T; +} + +/* ---------- small UI pieces ---------- */ + +function toast(msg: string, bad = false) { + const t = h('div', { class: `toast${bad ? ' bad' : ''}`, role: 'status' }, msg); + document.body.appendChild(t); + requestAnimationFrame(() => t.classList.add('show')); + setTimeout(() => { + t.classList.remove('show'); + setTimeout(() => t.remove(), 300); + }, 2600); +} + +async function copy(text: string, what = 'Copied') { + try { + await navigator.clipboard.writeText(text); + } catch { + const ta = h('textarea', { class: 'offscreen' }, text) as HTMLTextAreaElement; + document.body.appendChild(ta); + ta.select(); + document.execCommand('copy'); + ta.remove(); + } + toast(what); +} + +function download(name: string, text: string) { + // Not text/plain: Safari would save "name.conf.txt". + const url = URL.createObjectURL(new Blob([text], { type: 'application/octet-stream' })); + const a = h('a', { href: url, download: name, class: 'offscreen' }); + document.body.appendChild(a); + a.click(); + setTimeout(() => { + URL.revokeObjectURL(url); + a.remove(); + }, 1000); +} + +let tipEl: HTMLElement | null = null; +function tip(el: HTMLElement, lines: () => string[]) { + const show = (ev: MouseEvent) => { + tipEl ??= document.body.appendChild(h('div', { class: 'tip' })); + tipEl.replaceChildren(...lines().map((l, i) => h('div', { class: i ? 'muted' : 'tip-title' }, l))); + tipEl.style.display = ''; + tipEl.style.left = `${ev.clientX}px`; + tipEl.style.top = `${ev.clientY - 10}px`; + }; + el.addEventListener('mouseenter', show); + el.addEventListener('mousemove', show); + el.addEventListener('mouseleave', () => tipEl && (tipEl.style.display = 'none')); +} + +function spark(values: number[]): HTMLElement { + const max = Math.max(1, ...values); + const el = h('div', { class: 'spark' }); + values.forEach((v, i) => { + const b = h('i', { class: v ? '' : 'zero' }); + b.style.height = `${Math.max(8, (v / max) * 100)}%`; + const back = values.length - 1 - i; + const d = new Date(Date.now() - back * 86400000); + tip(b, () => [ + back === 0 ? 'Today' : back === 1 ? 'Yesterday' : d.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' }), + bytes(v), + ]); + el.appendChild(b); + }); + return el; +} + +/* ---------- sheets (bottom sheet on phones, dialog on desktop) ---------- */ + +let sheetEl: HTMLElement | null = null; +let sheetClosed: (() => void) | null = null; + +function closeSheet(immediate = false) { + if (!sheetEl) return; + const s = sheetEl; + sheetEl = null; + document.body.classList.remove('locked'); + sheetClosed?.(); + sheetClosed = null; + if (immediate) { + s.remove(); + return; + } + s.classList.remove('open'); + setTimeout(() => s.remove(), 250); +} + +function sheet(title: string, sub: string | null, ...content: Kid[]) { + const replacing = !!sheetEl; + closeSheet(true); + const panel = h( + 'div', + { class: 'sheet-panel', role: 'dialog', 'aria-modal': 'true', 'aria-label': title }, + h('div', { class: 'grab' }), + h( + 'div', + { class: 'sheet-head' }, + h('div', { class: 'stack' }, h('h2', {}, title), sub ? h('span', { class: 'muted s' }, sub) : null), + h('button', { class: 'icon-btn', 'aria-label': 'Close', onclick: () => closeSheet() }, ic('x')), + ), + h('div', { class: 'sheet-body' }, ...content), + ); + const s = h( + 'div', + { + class: 'sheet', + onclick: (e: Event) => { + if (e.target === s) closeSheet(); + }, + }, + panel, + ); + document.body.appendChild(s); + document.body.classList.add('locked'); + if (replacing) s.classList.add('open'); + else requestAnimationFrame(() => s.classList.add('open')); + sheetEl = s; + return panel; +} + +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + closeMenu(); + closeSheet(); + } +}); + +/* ---------- dropdown menu ---------- */ + +let menuEl: HTMLElement | null = null; +function closeMenu() { + menuEl?.remove(); + menuEl = null; +} +document.addEventListener('click', (e) => { + if (menuEl && !menuEl.contains(e.target as Node)) closeMenu(); +}); + +function menu(anchor: HTMLElement, items: ({ label: string; icon: string; danger?: boolean; run: () => unknown } | null)[]) { + closeMenu(); + const m = h( + 'div', + { class: 'menu', role: 'menu' }, + items.map((it) => + it + ? h( + 'button', + { + type: 'button', + role: 'menuitem', + class: `menu-item${it.danger ? ' danger' : ''}`, + onclick: () => { + closeMenu(); + it.run(); + }, + }, + ic(it.icon), + h('span', {}, it.label), + ) + : h('div', { class: 'menu-sep' }), + ), + ); + document.body.appendChild(m); + const r = anchor.getBoundingClientRect(); + const w = 230; + m.style.left = `${Math.max(8, Math.min(window.innerWidth - w - 8, r.right - w))}px`; + m.style.top = `${r.bottom + 6 + window.scrollY}px`; + menuEl = m; +} + +/* ---------- views ---------- */ + +function shell(...content: Kid[]) { + app.replaceChildren( + h( + 'header', + { class: 'top' }, + h( + 'div', + { class: 'brand' }, + (() => { + const l = h('span', { class: 'logo' }); + l.innerHTML = LOGO; + return l; + })(), + h('span', {}, state?.server.name || pageTitle), + h('span', { class: 'faint' }, '· Dawnline'), + ), + ), + h('main', { class: 'wrap' }, ...content), + ); +} + +/** The link stopped working while the page was open (code regenerated, person removed). */ +function linkGone() { + shell( + h( + 'div', + { class: 'card signin' }, + h('div', { class: 'hero-ic' }, ic('key')), + h('h1', {}, 'This link no longer works'), + h('p', { class: 'muted' }, 'Ask for a new personal link.'), + ), + ); +} + +function stateTone(p: Person) { + return p.state === 'active' ? 'ok' : p.state === 'quota' || p.state === 'expired' ? 'bad' : 'warn'; +} + +const ACCESS_TEXT: Record = { + internet: 'The internet, through the router', + lan: 'Devices at home', + both: 'Devices at home and the internet, through the router', +}; + +function accessCard(st: State): HTMLElement { + const p = st.person; + const pct = p.quota_limit ? Math.min(100, (p.quota_used / p.quota_limit) * 100) : 0; + const bar = h('div', { class: `meter${pct >= 100 ? ' bad' : pct >= 90 ? ' warn' : ''}` }, h('i')); + (bar.firstChild as HTMLElement).style.width = `${pct}%`; + if (p.quota_limit) tip(bar, () => [`${pct.toFixed(1)}% used`, `${bytes(Math.max(0, p.quota_limit - p.quota_used))} left`]); + const left = daysLeft(p.expires); + const slots = h('div', { class: 'slots' }); + for (let i = 0; i < p.device_limit; i++) slots.appendChild(h('i', { class: i < p.devices.length ? 'used' : '' })); + const used = p.quota_used || p.month[0] + p.month[1]; + const icon = p.access === 'internet' ? 'globe' : p.access === 'lan' ? 'home' : 'shield'; + // Heading outside the card, like "Your devices", so both columns line up. + return h( + 'section', + { class: 'access', 'aria-label': 'Your access' }, + h( + 'div', + { class: 'card-head' }, + h('div', { class: 'row-baseline' }, h('h2', {}, 'Your access'), h('span', { class: 'faint s' }, 'set by the admin')), + ), + h( + 'div', + { class: 'card access-card' }, + h( + 'div', + { class: 'reach' }, + h('span', { class: 'reach-ic' }, ic(icon)), + h( + 'div', + { class: 'stack' }, + h('span', { class: 'strong' }, ACCESS_LABEL[p.access]), + h('span', { class: 'muted s' }, ACCESS_TEXT[p.access]), + ), + ), + h( + 'div', + { class: 'tile' }, + h( + 'div', + { class: 'tile-label' }, + h('span', {}, p.quota_period === 'total' && p.quota_gb ? 'Data used' : 'Data this month'), + p.quota_period === 'month' ? h('span', {}, 'resets on the 1st') : null, + ), + h( + 'span', + { class: 'tile-value' }, + bytes(used), + h('span', { class: 'faint' }, p.quota_limit ? ` of ${bytes(p.quota_limit)}` : ' · no limit'), + ), + p.quota_limit ? bar : null, + ), + h( + 'div', + { class: 'tiles2' }, + h( + 'div', + { class: 'tile' }, + h('div', { class: 'tile-label' }, 'Devices'), + h('span', { class: 'tile-value' }, String(p.devices.length), h('span', { class: 'faint' }, ` / ${p.device_limit}`)), + slots, + ), + h( + 'div', + { class: 'tile' }, + h('div', { class: 'tile-label' }, 'Access until'), + h('span', { class: 'tile-value sm' }, p.expires ? date(p.expires) : 'No end date'), + left != null + ? h( + 'span', + { class: `s ${left <= Math.max(p.expire_warn, 3) ? 'warn' : 'ok'}` }, + left >= 0 ? `${left} day${left === 1 ? '' : 's'} left` : 'ended', + ) + : null, + ), + ), + h( + 'span', + { class: 'faint s' }, + p.hours ? `Available ${p.hours.replace('-', '–')} (router time). Need a change? Ask the admin.` : 'Need a change? Ask the admin.', + ), + ), + ); +} + +function deviceStatus(d: Device): HTMLElement { + if (d.disabled) return h('span', { class: 'dstat' }, h('i', { class: 'dot' }), 'Disabled by the admin'); + if (d.online) return h('span', { class: 'dstat ok' }, h('i', { class: 'dot ok' }), 'Connected'); + if (!d.handshake) return h('span', { class: 'dstat warn' }, h('i', { class: 'dot warn' }), 'Not set up yet'); + return h('span', { class: 'dstat' }, h('i', { class: 'dot' }), `Last connected ${ago(d.handshake)}`); +} + +function localAddress(d: Device, p: Person): HTMLElement | null { + if (!d.hostname || p.access === 'internet') return null; + return h( + 'div', + { class: 'dfoot' }, + h('span', { class: 'faint s' }, 'Local address'), + h( + 'button', + { type: 'button', class: 'lan-pill', 'aria-label': `Copy ${d.hostname}`, onclick: () => copy(d.hostname, 'Address copied') }, + h('span', { class: 'lan-ic' }, ic('home')), + h('span', { class: 'mono' }, d.hostname), + h('span', { class: 'lan-sep' }), + ic('copy'), + ), + ); +} + +function deviceCard(d: Device, st: State): HTMLElement { + const p = st.person; + const more = h('button', { type: 'button', class: 'icon-btn soft', 'aria-label': `${d.name} options` }, ic('more')); + more.addEventListener('click', (ev) => { + ev.stopPropagation(); + menu(more, [ + { label: 'Show QR code', icon: 'qr', run: () => connect(d, 'qr') }, + { label: 'Copy AmneziaVPN key', icon: 'key', run: () => copyKey(d) }, + { label: 'Download .conf', icon: 'download', run: () => downloadConf(d) }, + null, + { label: 'Rename', icon: 'edit', run: () => rename(d) }, + { label: 'Remove', icon: 'trash', danger: true, run: () => removeDevice(d) }, + ]); + }); + const week = d.spark.reduce((a, b) => a + b, 0); + const setUp = !d.handshake && !d.disabled; + return h( + 'article', + { class: `dcard${d.online ? ' online' : ''}${d.disabled ? ' off' : ''}` }, + h( + 'div', + { class: 'dhead' }, + h('span', { class: 'dic' }, ic(d.kind)), + h('div', { class: 'stack grow' }, h('span', { class: 'dname' }, d.name), deviceStatus(d)), + more, + ), + setUp + ? [ + h( + 'button', + { type: 'button', class: 'btn primary block', onclick: () => connect(d) }, + ic(isMobile() ? 'open' : 'qr'), + h('span', {}, isMobile() ? 'Open in AmneziaVPN' : 'Connect this device'), + ), + h('span', { class: 'faint s center' }, 'Setting up another device? QR, key and file are under ⋯'), + ] + : h( + 'div', + { class: 'duse' }, + h('div', { class: 'stack' }, h('span', { class: 'faint s' }, 'Last 7 days'), h('span', { class: 'mono' }, bytes(week))), + spark(d.spark), + ), + d.config_stale && !setUp + ? h( + 'div', + { class: 'notice' }, + ic('alert'), + h('span', { class: 'grow' }, 'Connection settings changed. Update this device to keep everything working.'), + h('button', { type: 'button', class: 'btn small', onclick: () => connect(d) }, 'Update'), + ) + : null, + localAddress(d, p), + ); +} + +function main(st: State) { + const p = st.person; + const left = daysLeft(p.expires); + const notice = + p.state !== 'active' + ? h( + 'div', + { class: 'notice bad' }, + ic('alert'), + h( + 'span', + {}, + p.state === 'quota' + ? 'You have used all your data for this period. Your devices are paused until it resets.' + : p.state === 'expired' + ? 'Your access has ended. Ask the admin to extend it.' + : p.state === 'hours' + ? `Access is available ${p.hours.replace('-', '–')} (router time).` + : 'Your access is paused by the admin.', + ), + ) + : left != null && left >= 0 && left <= Math.max(p.expire_warn, 1) + ? h( + 'div', + { class: 'notice' }, + ic('alert'), + h('span', {}, `Your access ends ${left === 0 ? 'today' : `in ${left} day${left === 1 ? '' : 's'}`} (${date(p.expires)}).`), + ) + : null; + + const cards: HTMLElement[] = p.devices.map((d) => deviceCard(d, st)); + const free = Math.max(0, p.device_limit - p.devices.length); + if (free) + cards.push( + h( + 'button', + { type: 'button', class: 'slot add', onclick: addDevice }, + h('span', { class: 'slot-ic' }, ic('plus')), + h( + 'span', + { class: 'stack' }, + h('span', { class: 'strong' }, 'Add device'), + h('span', { class: 'faint s' }, `${free} slot${free === 1 ? '' : 's'} free`), + ), + ), + ); + + const devices = h( + 'section', + { class: 'devices', 'aria-label': 'Your devices' }, + h( + 'div', + { class: 'card-head' }, + h( + 'div', + { class: 'row-baseline' }, + h('h2', {}, 'Your devices'), + h('span', { class: 'faint s' }, `${p.devices.length} of ${p.device_limit} · ${p.online} online`), + ), + ), + h('div', { class: 'dgrid' }, cards), + !st.can_add + ? h('span', { class: 'faint s' }, `You have reached your limit of ${p.device_limit} devices. Remove one or ask the admin for more.`) + : null, + h( + 'span', + { class: 'faint s' }, + 'New device? Install ', + h('a', { href: 'https://amnezia.org/downloads', target: '_blank', rel: 'noopener noreferrer' }, 'AmneziaVPN'), + ' on it first.', + ), + ); + + shell( + h( + 'div', + { class: 'hello' }, + h('span', { class: `avatar${p.online ? ' online' : ''}` }, initials(p.name)), + h( + 'div', + { class: 'stack' }, + h('div', { class: 'row' }, h('h1', {}, `Hi, ${p.name}`), h('span', { class: `pill ${stateTone(p)}` }, STATE_LABEL[p.state])), + h( + 'span', + { class: 'faint s' }, + `${p.online ? `${p.online} device${p.online === 1 ? '' : 's'} online` : 'Nothing connected right now'} · ${bytes(p.month[0] + p.month[1])} this month`, + ), + ), + ), + notice, + h('div', { class: 'layout' }, accessCard(st), devices), + ); +} + +/* ---------- device flows ---------- */ + +async function getConfig(d: Device): Promise { + try { + return await call(`devices/${d.id}/config`); + } catch (e) { + toast((e as Error).message, true); + return null; + } +} + +async function copyKey(d: Device) { + const cfg = await getConfig(d); + if (cfg) copy(await vpnKey(cfg, `${cfg.server} · ${cfg.name}`), 'Key copied'); +} + +async function downloadConf(d: Device) { + const cfg = await getConfig(d); + if (cfg) download(cfg.filename, cfg.conf); +} + +/** Connection sheet: open-in-app / QR / key / file, plus live status. */ +/** One configuration line, highlighted; private and preshared keys masked unless shown. */ +function confLine(line: string, reveal: boolean): Node { + if (/^\s*\[.+\]\s*$/.test(line)) return h('span', { class: '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 h( + 'span', + {}, + h('span', { class: 'conf-k' }, m[1]), + ' ', + secret && !reveal ? h('span', { class: 'conf-mask' }, '••••••••••••••••') : m[2], + ); +} + +/** The .conf as a file card (download) and a folded, highlighted view with copy and a hidden key. */ +function filePane(cfg: ClientConfig): HTMLElement { + let reveal = false; + const pre = h('pre', { class: 'conf' }); + const paint = () => + pre.replaceChildren(...cfg.conf.split('\n').flatMap((l, i) => (i ? ['\n', confLine(l, reveal)] : [confLine(l, reveal)]))); + const eye = h( + 'button', + { + class: 'btn small', + onclick: (ev: Event) => { + ev.preventDefault(); + reveal = !reveal; + eye.replaceChildren(ic(reveal ? 'x' : 'key'), h('span', {}, reveal ? 'Hide key' : 'Show key')); + paint(); + }, + }, + ic('key'), + h('span', {}, 'Show key'), + ); + paint(); + return h( + 'div', + { class: 'pane' }, + h( + 'div', + { class: 'filecard' }, + h('span', { class: 'filecard-ic' }, '.conf'), + h( + 'span', + { class: 'stack' }, + h('span', { class: 'mono ellipsis' }, cfg.filename), + h('span', { class: 'faint s' }, 'For computers and routers: import it in AmneziaWG or AmneziaVPN'), + ), + h('button', { class: 'btn primary', onclick: () => download(cfg.filename, cfg.conf) }, ic('download'), h('span', {}, 'Download')), + ), + h( + 'details', + { class: 'confbox' }, + h( + 'summary', + {}, + ic('chevron'), + h('span', {}, 'Configuration'), + h('span', { class: 'grow' }), + eye, + h( + 'button', + { + class: 'btn small', + onclick: (ev: Event) => { + ev.preventDefault(); + copy(cfg.conf, 'Configuration copied'); + }, + }, + ic('copy'), + h('span', {}, 'Copy'), + ), + ), + pre, + ), + ); +} + +async function connect(d: Device, initial?: 'app' | 'qr' | 'key' | 'file', cfgIn?: ClientConfig) { + const cfg = cfgIn ?? (await getConfig(d)); + if (!cfg) return; + const key = await vpnKey(cfg, `${cfg.server} · ${cfg.name}`); + const mobile = isMobile(); + const panes: Record HTMLElement> = { + app: () => + h( + 'div', + { class: 'pane' }, + h('a', { class: 'btn primary block big', href: key }, ic('open'), h('span', {}, 'Open in AmneziaVPN')), + h( + 'ol', + { class: 'steps' }, + h( + 'li', + {}, + 'No AmneziaVPN yet? ', + h('a', { href: 'https://amnezia.org/downloads', target: '_blank', rel: 'noopener noreferrer' }, 'Get it here'), + '.', + ), + h('li', {}, 'Tap ', h('b', {}, 'Open in AmneziaVPN'), ' and confirm the import.'), + h('li', {}, 'Turn the connection on — this page shows ', h('span', { class: 'ok' }, 'Connected'), ' within a minute.'), + ), + ), + qr: () => { + const q = h('div', { class: 'qr' }); + q.innerHTML = qrSvg(cfg.conf); + return h('div', { class: 'pane center' }, q, h('p', { class: 'muted s' }, 'Scan with the phone’s camera or AmneziaVPN / AmneziaWG.')); + }, + key: () => + h( + 'div', + { class: 'pane' }, + h('p', { class: 'muted s' }, 'In AmneziaVPN choose “Add server → Insert key”.'), + h( + 'div', + { class: 'keybox' }, + h('span', { class: 'mono' }, key), + h('button', { class: 'btn small', onclick: () => copy(key, 'Key copied') }, 'Copy'), + ), + h('p', { class: 'faint s' }, 'Keep it private: anyone with the key can use your connection.'), + ), + file: () => filePane(cfg), + }; + const order = mobile ? ['app', 'qr', 'key', 'file'] : ['qr', 'key', 'file']; + const labels: Record = { app: 'Open in app', qr: 'QR code', key: 'Key', file: 'File' }; + const body = h('div', { class: 'tab-body' }); + const tabs = h('div', { class: 'tabs', role: 'tablist' }); + const show = (id: string) => { + tabs.querySelectorAll('button').forEach((b) => b.classList.toggle('on', (b as HTMLElement).dataset.id === id)); + body.replaceChildren(panes[id]()); + }; + for (const id of order) tabs.appendChild(h('button', { role: 'tab', 'data-id': id, onclick: () => show(id) }, labels[id])); + show(initial && order.includes(initial) ? initial : order[0]); + + const live = h('div', { class: 'waiting' }); + const paintLive = (dev: Device | undefined) => { + if (dev?.online) live.replaceChildren(h('i', { class: 'dot ok' }), h('span', { class: 'ok' }, `${d.name} is connected`)); + else if (dev?.handshake) + live.replaceChildren(h('i', { class: 'dot' }), h('span', { class: 'muted' }, `Last connected ${ago(dev.handshake)}`)); + else live.replaceChildren(h('i', { class: 'dot warn pulse' }), h('span', { class: 'muted' }, 'Waiting for the first connection…')); + }; + paintLive(d); + const watch = window.setInterval(async () => { + try { + const st = await call('state'); + state = st; + paintLive(st.person.devices.find((x) => x.id === d.id)); + } catch { + /* ignore */ + } + }, 5000); + sheet( + d.handshake ? `Connect ${d.name}` : `${d.name} is ready`, + mobile ? 'Add it to AmneziaVPN on this phone' : 'Scan with the phone’s camera or AmneziaVPN', + tabs, + body, + live, + ); + sheetClosed = () => { + clearInterval(watch); + if (state) main(state); + }; +} + +function rename(d: Device) { + const name = h('input', { type: 'text', value: d.name, maxlength: 48, 'aria-label': 'Device name' }) as HTMLInputElement; + sheet( + `Rename ${d.name}`, + null, + h( + 'form', + { + class: 'stack gap', + onsubmit: async (e: Event) => { + e.preventDefault(); + try { + const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'rename', name: name.value }); + state = r.state; + closeSheet(); + main(state); + toast('Renamed'); + } catch (er) { + toast((er as Error).message, true); + } + }, + }, + name, + h('button', { class: 'btn primary block', type: 'submit' }, 'Save'), + ), + ); + setTimeout(() => name.select(), 50); +} + +function removeDevice(d: Device) { + sheet( + `Remove ${d.name}?`, + null, + h('p', { class: 'muted' }, 'Its connection stops working immediately. You can add it again later.'), + h( + 'div', + { class: 'row gap' }, + h('button', { class: 'btn block', onclick: () => closeSheet() }, 'Cancel'), + h( + 'button', + { + class: 'btn danger-solid block', + onclick: async () => { + try { + const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'delete' }); + state = r.state; + closeSheet(); + main(state); + toast('Device removed'); + } catch (er) { + toast((er as Error).message, true); + } + }, + }, + 'Remove', + ), + ), + ); +} + +// Best guess at the device this page is open on (the browser never tells its real name). +const UA = navigator.userAgent; +const IPAD = /iPad/.test(UA) || (/Macintosh/.test(UA) && navigator.maxTouchPoints > 1); + +function guessKind(): Kind { + if (IPAD || /Tablet/i.test(UA) || (/Android/.test(UA) && !/Mobile/.test(UA))) return 'tablet'; + if (/Android|iPhone|Mobile/i.test(UA)) return 'phone'; + return 'computer'; +} + +/** Samsung model codes → names people know (S and A series; the code stays in brackets). */ +const GALAXY: [RegExp, string][] = [ + [/^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'], +]; + +/** Android model from Client Hints (Chrome); filled in shortly after the page loads. */ +let MODEL = ''; +const modelReady: Promise = (async () => { + const uad = (navigator as Navigator & { userAgentData?: { getHighEntropyValues(h: string[]): Promise<{ model?: string }> } }) + .userAgentData; + if (!uad || !/Android/.test(UA)) return ''; + try { + const m = ((await uad.getHighEntropyValues(['model'])).model ?? '').trim(); + if (!m || m === 'K') return ''; + const g = GALAXY.find(([re]) => re.test(m)); + MODEL = g ? `${g[1]} (${m})` : /^SM-/.test(m) ? `Galaxy ${m}` : m; + } catch { + /* not offered */ + } + return MODEL; +})(); + +function guessName(kind: Kind): string { + if (/iPhone/.test(UA)) return 'iPhone'; + if (IPAD) return 'iPad'; + if (/Android/.test(UA)) return MODEL || (kind === 'tablet' ? 'Android tablet' : 'Android phone'); + if (/CrOS/.test(UA)) return 'Chromebook'; + if (/Mac OS X/.test(UA)) return 'Mac'; + if (/Windows/.test(UA)) return 'Windows PC'; + if (/Linux/.test(UA)) return 'Linux PC'; + return KIND_LABEL[kind]; +} + +function addDevice() { + if (!state) return; + let kind: Kind = guessKind(); + const taken = new Set(state.person.devices.map((d) => d.name.toLowerCase())); + const suggest = (k: Kind) => { + const n = k === guessKind() ? guessName(k) : KIND_LABEL[k]; + if (!taken.has(n.toLowerCase())) return n; + for (let i = 2; i < 20; i++) if (!taken.has(`${n} ${i}`.toLowerCase())) return `${n} ${i}`; + return n; + }; + const name = h('input', { + type: 'text', + value: suggest(kind), + maxlength: 48, + 'aria-label': 'Device name', + required: true, + }) as HTMLInputElement; + let edited = false; + name.addEventListener('input', () => (edited = true)); + // The Android model arrives a moment later: use it unless they started typing. + modelReady.then(() => { + if (!edited && kind === guessKind()) name.value = suggest(kind); + }); + const kinds = h( + 'div', + { class: 'kinds' }, + (state.kinds as Kind[]).map((k) => + h( + 'button', + { + type: 'button', + class: `kind${k === kind ? ' on' : ''}`, + 'data-k': k, + onclick: () => { + kind = k; + kinds.querySelectorAll('.kind').forEach((b) => b.classList.toggle('on', (b as HTMLElement).dataset.k === k)); + if (!edited) name.value = suggest(k); + }, + }, + ic(k), + h('span', {}, KIND_LABEL[k]), + ), + ), + ); + const err = h('p', { class: 'err' }); + const submit = h('button', { class: 'btn primary block', type: 'submit' }, 'Create connection') as HTMLButtonElement; + sheet( + 'Add a device', + `${state.person.device_limit - state.person.devices.length} of ${state.person.device_limit} slots free`, + h( + 'form', + { + class: 'add', + onsubmit: async (e: Event) => { + e.preventDefault(); + submit.disabled = true; + err.textContent = ''; + try { + const r = await call<{ id: string; config: ClientConfig; state: State }>('devices', { name: name.value.trim(), kind }); + state = r.state; + const dev = r.state.person.devices.find((d) => d.id === r.id)!; + await connect(dev, undefined, r.config); + } catch (er) { + err.textContent = (er as Error).message; + submit.disabled = false; + } + }, + }, + h('label', { class: 'lbl' }, 'What is it?'), + kinds, + h('label', { class: 'lbl' }, 'Name'), + name, + err, + submit, + ), + ); +} + +/* ---------- boot ---------- */ + +async function refresh() { + try { + state = await call('state'); + document.title = `${state.person.name} · ${state.title}`; + if (!sheetEl && !menuEl) main(state); + } catch (e) { + const er = e as ApiError; + if (er.status === 404 || er.status === 401) { + state = null; + linkGone(); + } + // A network hiccup: keep showing the last state and try again on the next poll. + else if (!state) shell(h('div', { class: 'card' }, h('p', {}, er.message))); + } +} + +function startPolling() { + clearInterval(pollTimer); + pollTimer = window.setInterval(() => { + if (state && document.visibilityState === 'visible') void refresh(); + }, 15000); +} + +if (!base || !code) linkGone(); +else { + void refresh(); + startPolling(); +} diff --git a/web/src/portal/portal.css b/web/src/portal/portal.css new file mode 100644 index 0000000..18463fd --- /dev/null +++ b/web/src/portal/portal.css @@ -0,0 +1,1268 @@ +/* Dawnline personal portal — Vercel-like, same palette as the Outline admin. */ +@font-face { + font-family: Geist; + src: url(geist-latin-wght-normal.woff2) format('woff2'); + font-weight: 100 900; + font-display: swap; + unicode-range: + U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+20AC, U+2122, U+2190-21FF, U+2212, U+2215; +} +@font-face { + font-family: Geist; + src: url(geist-cyrillic-wght-normal.woff2) format('woff2'); + font-weight: 100 900; + font-display: swap; + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +@font-face { + font-family: 'Geist Mono'; + src: url(geist-mono-latin-wght-normal.woff2) format('woff2'); + font-weight: 100 900; + font-display: swap; +} + +:root { + --bg: #fcfcfc; + --card: #ffffff; + --elevated: #ffffff; + --text: #0d0d0d; + --muted: #5d5d5d; + --faint: #8f8f8f; + --line: #0000001a; + --input: #00000026; + --soft: #0d0d0d0d; + --soft-hover: #0d0d0d1a; + --primary: #0d0d0d; + --primary-fg: #ffffff; + --accent: #3a83f7; + --info: #2c67c5; + --ok: #00a240; + --ok-wash: #00a24026; + --warn: #e25507; + --warn-wash: #e2550726; + --bad: #e02e2a; + --bad-wash: #e02e2a1f; + --chart: #3a83f7; + --track: #0d0d0d1a; + --scrim: #00000040; + --shadow: 0 1px 2px -1px #00000014; + --shadow-xl: 0 8px 16px -4px #0000001f; + --radius: 16px; + --mono: 'Geist Mono', ui-monospace, Menlo, monospace; + color-scheme: light dark; +} +@media (prefers-color-scheme: dark) { + :root { + --bg: #000000; + --card: #0a0a0a; + --elevated: #131313; + --text: #ededed; + --muted: #edededa6; + --faint: #ededed78; + --line: #ededed13; + --input: #ededed24; + --soft: #ededed0d; + --soft-hover: #ededed1a; + --primary: #ededed; + --primary-fg: #131313; + --accent: #006efe; + --info: #5ba2fe; + --ok: #40c977; + --ok-wash: #40c97726; + --warn: #ff8549; + --warn-wash: #ff854926; + --bad: #ff6764; + --bad-wash: #ff676422; + --chart: #3a83f7; + --track: #ededed1a; + --scrim: #00000099; + --shadow: none; + --shadow-xl: 0 8px 16px -4px #00000080; + } +} +* { + box-sizing: border-box; +} +html, +body { + margin: 0; +} +body { + background: var(--bg); + color: var(--text); + font: + 400 15px/22px Geist, + -apple-system, + system-ui, + 'Segoe UI', + sans-serif; + -webkit-font-smoothing: antialiased; + min-height: 100vh; + min-height: 100dvh; +} +body.locked { + overflow: hidden; +} +a { + color: var(--info); + text-decoration: none; +} +a:hover { + text-decoration: underline; +} +h1, +h2 { + margin: 0; + font-weight: 500; + letter-spacing: -0.01em; +} +h1 { + font-size: 24px; + line-height: 32px; +} +h2 { + font-size: 16px; + line-height: 24px; +} +.muted { + color: var(--muted); +} +.faint { + color: var(--faint); +} +.s { + font-size: 13px; + line-height: 18px; +} +.ok { + color: var(--ok); +} +.warn { + color: var(--warn); +} +.strong { + font-weight: 500; +} +.center { + text-align: center; +} +.mono { + font-family: var(--mono); + font-size: 12px; +} +.stack { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; +} +.stack.gap { + gap: 10px; +} +.grow { + flex: 1; +} +.row { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} +.row.gap { + gap: 8px; + flex-wrap: nowrap; +} +.row-baseline { + display: flex; + align-items: baseline; + gap: 10px; + flex-wrap: wrap; +} +.offscreen { + position: fixed; + left: -9999px; + opacity: 0; +} + +/* header */ +.top { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: max(12px, env(safe-area-inset-top)) 16px 12px; + border-bottom: 1px solid var(--line); + position: sticky; + top: 0; + background: color-mix(in srgb, var(--bg) 85%, transparent); + backdrop-filter: saturate(180%) blur(12px); + z-index: 5; +} +.brand { + display: flex; + align-items: center; + gap: 8px; + font-weight: 500; + min-width: 0; +} +.brand .faint { + font-weight: 400; +} +.logo { + display: inline-flex; + width: 22px; + height: 22px; + color: var(--text); +} +.logo svg { + width: 100%; + height: 100%; +} +.wrap { + width: 100%; + max-width: 1048px; + margin: 0 auto; + padding: 20px 16px max(32px, env(safe-area-inset-bottom)); + display: flex; + flex-direction: column; + gap: 20px; +} + +/* greeting */ +.hello { + display: flex; + align-items: center; + gap: 12px; +} +.avatar { + width: 44px; + height: 44px; + border-radius: 50%; + background: var(--soft-hover); + display: inline-flex; + align-items: center; + justify-content: center; + font-size: 14px; + font-weight: 600; + position: relative; + flex: 0 0 auto; +} +.avatar.online::after { + content: ''; + position: absolute; + right: 0; + bottom: 0; + width: 10px; + height: 10px; + border-radius: 50%; + background: var(--ok); + box-shadow: 0 0 0 3px var(--bg); +} +.pill { + display: inline-flex; + align-items: center; + height: 22px; + padding: 0 9px; + border-radius: 999px; + font-size: 12px; + font-weight: 500; + background: var(--soft); + color: var(--muted); +} +.pill.ok { + background: var(--ok-wash); + color: var(--ok); +} +.pill.warn { + background: var(--warn-wash); + color: var(--warn); +} +.pill.bad { + background: var(--bad-wash); + color: var(--bad); +} +.notice { + display: flex; + gap: 10px; + align-items: flex-start; + padding: 12px 14px; + border-radius: 12px; + background: var(--warn-wash); + font-size: 14px; +} +.notice.bad { + background: var(--bad-wash); +} +.notice .ic { + color: var(--warn); +} +.notice.bad .ic { + color: var(--bad); +} + +/* layout: phone = access then devices; desktop = devices | access */ +.layout { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 20px; + grid-template-areas: 'access' 'devices'; +} +.access { + grid-area: access; +} +.devices { + grid-area: devices; + display: flex; + flex-direction: column; + gap: 12px; + min-width: 0; +} +.desktop-only { + display: none !important; +} +@media (min-width: 960px) { + .top { + padding-left: max(16px, calc((100vw - 1048px) / 2 + 16px)); + padding-right: max(16px, calc((100vw - 1048px) / 2 + 16px)); + } + .layout { + grid-template-columns: minmax(0, 1.7fr) minmax(0, 1fr); + grid-template-areas: 'devices access'; + align-items: start; + gap: 16px; + } + .desktop-only { + display: inline-flex !important; + } + .wrap { + padding-top: 28px; + } +} + +/* cards */ +.card { + background: var(--card); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 16px; + box-shadow: var(--shadow); + min-width: 0; +} +.card-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} +.access { + display: flex; + flex-direction: column; + gap: 12px; + min-width: 0; +} +.access-card { + display: flex; + flex-direction: column; + gap: 12px; +} +.reach { + display: flex; + align-items: center; + gap: 12px; + padding: 12px; + border-radius: 12px; + background: var(--soft); +} +.reach-ic { + width: 36px; + height: 36px; + border-radius: 10px; + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + background: color-mix(in srgb, var(--info) 14%, transparent); + color: var(--info); +} +.tile { + border: 1px solid var(--line); + border-radius: 14px; + padding: 14px; + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; +} +.tiles2 { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; +} +.tile-label { + display: flex; + justify-content: space-between; + gap: 8px; + font-size: 12px; + font-weight: 500; + color: var(--faint); +} +.tile-value { + font-size: 20px; + line-height: 28px; + font-weight: 500; + letter-spacing: -0.01em; + font-variant-numeric: tabular-nums; +} +.tile-value.sm { + font-size: 16px; +} +.tile-value .faint { + font-size: 14px; + font-weight: 400; +} +.meter { + position: relative; + height: 6px; + border-radius: 999px; + background: var(--track); + cursor: default; +} +.meter i { + display: block; + height: 100%; + border-radius: 999px; + background: var(--accent); +} +.meter.warn i { + background: var(--warn); +} +.meter.bad i { + background: var(--bad); +} +.slots { + display: grid; + grid-auto-flow: column; + grid-auto-columns: minmax(0, 1fr); + gap: 3px; +} +.slots i { + display: block; + height: 4px; + border-radius: 999px; + background: var(--track); +} +.slots i.used { + background: var(--text); +} + +/* devices */ +.dgrid { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 10px; +} +@media (min-width: 640px) { + .dgrid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; + } +} +/* No devices yet: the add card takes the whole row instead of leaving a hole. */ +.dgrid > .slot.add:only-child { + grid-column: 1 / -1; +} +.dcard { + background: var(--card); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 14px; + display: flex; + flex-direction: column; + gap: 12px; + min-width: 0; + box-shadow: var(--shadow); +} +.dcard.online { + border-color: color-mix(in srgb, var(--ok) 35%, transparent); +} +.dcard.off { + opacity: 0.7; +} +.dhead { + display: flex; + align-items: center; + gap: 12px; +} +.dic { + width: 40px; + height: 40px; + border-radius: 12px; + background: var(--soft); + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + color: var(--muted); +} +.dic .ic-svg { + width: 20px; + height: 20px; +} +.dcard.online .dic { + background: var(--ok-wash); + color: var(--ok); +} +.dname { + font-weight: 500; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.dstat { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 13px; + color: var(--muted); +} +.dstat.ok { + color: var(--ok); +} +.dstat.warn { + color: var(--warn); +} +.dot { + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--faint); + display: inline-block; + flex: 0 0 auto; +} +.dot.ok { + background: var(--ok); + box-shadow: 0 0 0 3px var(--ok-wash); +} +.dot.warn { + background: var(--warn); +} +.dot.pulse { + animation: pulse 1.6s ease-in-out infinite; +} +@keyframes pulse { + 0%, + 100% { + box-shadow: 0 0 0 0 var(--warn-wash); + } + 50% { + box-shadow: 0 0 0 6px transparent; + } +} +.duse { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 12px; +} +.spark { + display: flex; + align-items: flex-end; + gap: 3px; + height: 26px; + width: 128px; +} +.spark i { + flex: 1; + display: block; + border-radius: 2px 2px 0 0; + background: var(--chart); + opacity: 0.85; + cursor: default; +} +.spark i.zero { + opacity: 0.22; +} +.spark i:hover { + opacity: 1; + filter: brightness(1.2); +} +.dfoot { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px; + padding-top: 12px; + border-top: 1px solid var(--line); +} +.dfoot > .faint { + white-space: nowrap; +} +.lan-pill { + all: unset; + cursor: pointer; + display: inline-flex; + align-items: center; + height: 26px; + padding: 0 3px; + border-radius: 999px; + max-width: 100%; + min-width: 0; + background: linear-gradient(180deg, color-mix(in srgb, var(--text) 6%, transparent), color-mix(in srgb, var(--text) 2.5%, transparent)); + box-shadow: + inset 0 0 0 1px var(--line), + 0 1px 2px #0003; +} +.lan-pill:hover { + box-shadow: + inset 0 0 0 1px var(--input), + 0 1px 2px #0003; +} +.lan-pill:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} +.lan-ic { + width: 20px; + height: 20px; + border-radius: 50%; + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + background: color-mix(in srgb, var(--info) 14%, transparent); + color: var(--info); +} +.lan-ic .ic-svg { + width: 11px; + height: 11px; +} +.lan-pill .mono { + padding: 0 8px 0 7px; + font-weight: 500; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.lan-sep { + width: 1px; + height: 14px; + background: var(--line); + flex: 0 0 auto; +} +.lan-pill > .ic:last-child { + width: 22px; + justify-content: center; + color: var(--muted); +} +.lan-pill > .ic:last-child .ic-svg { + width: 12px; + height: 12px; +} +.slot.add { + all: unset; + box-sizing: border-box; + cursor: pointer; + display: flex; + align-items: center; + gap: 14px; + padding: 16px; + min-height: 72px; + border: 1px dashed var(--input); + border-radius: var(--radius); + color: var(--text); + text-align: left; + transition: + background 0.15s, + border-color 0.15s; +} +.slot.add:hover { + background: var(--soft); + border-color: color-mix(in srgb, var(--text) 30%, transparent); +} +.slot-ic { + width: 40px; + height: 40px; + border-radius: 12px; + background: var(--soft); + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + color: var(--muted); +} +.slot.add:hover .slot-ic { + background: var(--primary); + color: var(--primary-fg); +} +.slot.add:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} +@media (min-width: 960px) { + .slot.add { + flex-direction: column; + justify-content: center; + gap: 10px; + min-height: 140px; + text-align: center; + color: var(--muted); + } + .slot.add .stack { + align-items: center; + } + .slot.add .strong { + color: var(--text); + } + .slot.add .slot-ic { + border-radius: 999px; + width: 36px; + height: 36px; + } +} + +/* buttons */ +.ic { + display: inline-flex; + line-height: 0; +} +.ic-svg { + width: 16px; + height: 16px; +} +.btn { + all: unset; + box-sizing: border-box; + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + height: 40px; + padding: 0 16px; + border-radius: 999px; + font-size: 14px; + font-weight: 500; + background: var(--soft); + color: var(--text); + -webkit-tap-highlight-color: transparent; + white-space: nowrap; +} +.btn:hover { + background: var(--soft-hover); +} +.btn.primary { + background: var(--primary); + color: var(--primary-fg); +} +.btn.primary:hover { + opacity: 0.9; +} +.btn.danger-solid { + background: var(--bad); + color: #fff; +} +.btn.small { + height: 32px; + padding: 0 12px; + font-size: 13px; +} +.btn.big { + height: 48px; + font-size: 15px; +} +.btn.block { + display: flex; + width: 100%; +} +.btn[disabled] { + opacity: 0.45; + cursor: not-allowed; +} +.btn:focus-visible, +.kind:focus-visible, +.icon-btn:focus-visible, +.slot:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} +.icon-btn { + all: unset; + cursor: pointer; + width: 36px; + height: 36px; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 50%; + color: var(--muted); + flex: 0 0 auto; +} +.icon-btn:hover { + background: var(--soft); + color: var(--text); +} +.icon-btn.soft { + background: var(--soft); +} +@media (pointer: coarse) { + .icon-btn { + width: 40px; + height: 40px; + } +} + +/* inputs */ +input[type='text'] { + width: 100%; + font: inherit; + color: var(--text); + background: var(--card); + border: 1px solid var(--input); + border-radius: 10px; + padding: 0 12px; + height: 44px; +} +input[type='text']:focus { + outline: 2px solid color-mix(in srgb, var(--accent) 60%, transparent); + outline-offset: 0; + border-color: transparent; +} +.lbl { + display: block; + font-size: 13px; + font-weight: 500; + color: var(--muted); + margin: 14px 2px 6px; +} +.err { + color: var(--bad); + min-height: 1.2em; + margin: 8px 2px; + font-size: 14px; +} +.kinds { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + gap: 6px; +} +.kind { + all: unset; + box-sizing: border-box; + cursor: pointer; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 6px; + height: 68px; + min-width: 0; + border-radius: 12px; + box-shadow: inset 0 0 0 1px var(--line); + color: var(--muted); + font-size: 12.5px; + font-weight: 500; + text-align: center; +} +.kind .ic-svg { + width: 20px; + height: 20px; +} +.kind:hover { + color: var(--text); + background: color-mix(in srgb, var(--text) 4%, transparent); +} +.kind.on { + box-shadow: inset 0 0 0 1.5px var(--accent); + color: var(--text); + background: color-mix(in srgb, var(--accent) 10%, transparent); +} +.kind.on .ic { + color: var(--accent); +} + +/* sign-in */ +.signin { + text-align: center; + max-width: 420px; + margin: 8vh auto 0; + width: 100%; + padding: 28px 20px; + display: flex; + flex-direction: column; + gap: 10px; +} +.hero-ic { + width: 52px; + height: 52px; + margin: 0 auto 6px; + border-radius: 16px; + display: grid; + place-items: center; + background: var(--primary); + color: var(--primary-fg); +} +.hero-ic .ic-svg { + width: 24px; + height: 24px; +} +.signin input { + text-align: center; + margin-top: 8px; +} + +/* dropdown menu */ +.menu { + position: absolute; + z-index: 30; + width: 230px; + padding: 4px; + border-radius: 14px; + background: var(--elevated); + border: 1px solid var(--line); + box-shadow: var(--shadow-xl); +} +.menu-item { + all: unset; + box-sizing: border-box; + cursor: pointer; + display: flex; + align-items: center; + gap: 10px; + width: 100%; + height: 40px; + padding: 0 12px; + border-radius: 10px; + font-size: 14px; +} +.menu-item:hover, +.menu-item:focus-visible { + background: var(--soft-hover); +} +.menu-item .ic { + color: var(--muted); +} +.menu-item.danger { + color: var(--bad); +} +.menu-item.danger .ic { + color: var(--bad); +} +.menu-sep { + height: 1px; + background: var(--line); + margin: 4px 8px; +} +@media (pointer: coarse) { + .menu-item { + height: 44px; + } +} + +/* sheet: bottom sheet on phones, centred dialog on desktop */ +.sheet { + position: fixed; + inset: 0; + z-index: 20; + display: flex; + align-items: flex-end; + justify-content: center; + background: transparent; + transition: background 0.2s; +} +.sheet.open { + background: var(--scrim); +} +.sheet-panel { + width: 100%; + max-width: 520px; + max-height: 92vh; + max-height: 92dvh; + overflow: auto; + background: var(--elevated); + border-radius: 20px 20px 0 0; + border: 1px solid var(--line); + border-bottom: 0; + padding: 6px 16px max(20px, env(safe-area-inset-bottom)); + transform: translateY(100%); + transition: transform 0.25s cubic-bezier(0.2, 0.8, 0.2, 1); +} +.sheet.open .sheet-panel { + transform: none; +} +.grab { + width: 36px; + height: 4px; + border-radius: 999px; + background: var(--input); + margin: 4px auto 8px; +} +.sheet-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 8px; + padding: 4px 0 12px; +} +.sheet-head h2 { + font-size: 20px; + line-height: 28px; + font-weight: 600; +} +.sheet-body { + display: flex; + flex-direction: column; + gap: 14px; +} +@media (min-width: 640px) { + .sheet { + align-items: center; + } + .sheet-panel { + border-radius: 16px; + border-bottom: 1px solid var(--line); + padding: 20px; + max-width: 480px; + transform: scale(0.97); + opacity: 0; + transition: + transform 0.18s ease, + opacity 0.18s ease; + } + .sheet.open .sheet-panel { + transform: none; + opacity: 1; + } + .grab { + display: none; + } +} +.tabs { + display: flex; + gap: 4px; + padding: 4px; + background: var(--soft); + border-radius: 999px; +} +.tabs button { + all: unset; + cursor: pointer; + flex: 1 1 auto; + white-space: nowrap; + text-align: center; + padding: 7px 10px; + border-radius: 999px; + font-weight: 500; + font-size: 13px; + color: var(--muted); +} +.tabs button.on { + background: var(--soft-hover); + color: var(--text); +} +.pane { + display: flex; + flex-direction: column; + gap: 10px; +} +.pane.center { + align-items: center; + text-align: center; +} +.qr { + width: min(240px, 70vw); + aspect-ratio: 1; + background: #fff; + border-radius: 12px; + padding: 10px; + box-shadow: inset 0 0 0 1px var(--line); +} +.qr svg { + display: block; + width: 100%; + height: 100%; +} +.steps { + margin: 4px 0 0; + padding: 14px 16px 14px 34px; + border-radius: 14px; + border: 1px solid var(--line); + background: var(--card); + display: flex; + flex-direction: column; + gap: 8px; + font-size: 14px; +} +.keybox { + display: flex; + align-items: center; + gap: 8px; + height: 44px; + padding: 0 6px 0 12px; + border: 1px solid var(--input); + border-radius: 10px; +} +.keybox .mono { + flex: 1; + min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: var(--muted); +} +.filecard { + display: flex; + align-items: center; + gap: 12px; + padding: 12px; + border-radius: 14px; + background: var(--soft); + min-width: 0; +} +.filecard > .stack { + flex: 1; + min-width: 0; +} +.filecard-ic { + width: 40px; + height: 46px; + border-radius: 8px; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + font: 10px var(--mono); + color: var(--muted); + background: var(--card); + box-shadow: inset 0 0 0 1px var(--line); +} +.ellipsis { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; +} +/* Phones: the config file name wraps instead of being cut */ +@media (max-width: 480px) { + .filecard .ellipsis { + white-space: normal; + overflow-wrap: anywhere; + } +} +.confbox { + border: 1px solid var(--line); + border-radius: 12px; +} +.confbox > summary { + list-style: none; + display: flex; + align-items: center; + gap: 8px; + padding: 8px 10px 8px 12px; + color: var(--text); +} +.confbox > summary::-webkit-details-marker { + display: none; +} +.confbox > summary > .ic:first-child { + transition: transform 0.15s; + color: var(--muted); +} +.confbox[open] > summary > .ic:first-child { + transform: rotate(90deg); +} +.confbox .grow { + flex: 1; +} +.confbox > .conf { + margin: 0; + border-top: 1px solid var(--line); + border-radius: 0 0 12px 12px; + background: none; +} +.conf-sec { + color: var(--accent, var(--info)); +} +.conf-k { + color: var(--faint); +} +.conf-mask { + padding: 0 6px; + border-radius: 4px; + background: var(--soft); + color: var(--muted); +} +.conf { + white-space: pre-wrap; + word-break: break-all; + font: 12px/18px var(--mono); + background: var(--soft); + border-radius: 10px; + padding: 12px; + max-height: 16rem; + overflow: auto; +} +details > summary { + cursor: pointer; + color: var(--muted); + font-size: 13px; + font-weight: 500; +} +.waiting { + display: flex; + align-items: center; + gap: 10px; + padding: 12px 14px; + border-radius: 12px; + background: var(--soft); + font-size: 14px; +} + +/* tooltip & toast */ +.tip { + position: fixed; + z-index: 50; + transform: translate(-50%, -100%); + padding: 6px 10px; + border-radius: 10px; + font-size: 12px; + line-height: 17px; + white-space: nowrap; + background: var(--elevated); + border: 1px solid var(--line); + box-shadow: var(--shadow-xl); + pointer-events: none; +} +.tip-title { + font-weight: 500; +} +.toast { + position: fixed; + left: 50%; + bottom: max(20px, env(safe-area-inset-bottom)); + transform: translate(-50%, 20px); + opacity: 0; + z-index: 60; + background: var(--primary); + color: var(--primary-fg); + padding: 10px 16px; + border-radius: 999px; + font-weight: 500; + font-size: 14px; + transition: all 0.25s; + max-width: 90vw; +} +.toast.show { + opacity: 1; + transform: translate(-50%, 0); +} +.toast.bad { + background: var(--bad); + color: #fff; +} +@media (prefers-reduced-motion: reduce) { + * { + transition: none !important; + animation: none !important; + } +} diff --git a/web/src/shared/chart.ts b/web/src/shared/chart.ts new file mode 100644 index 0000000..840af6d --- /dev/null +++ b/web/src/shared/chart.ts @@ -0,0 +1,26 @@ +// Tiny SVG bar chart for daily traffic (download stacked over upload). + +import type { DayUsage } from './types'; +import { bytes } from './format'; + +export function trafficChart(series: DayUsage[], height = 120): string { + const w = 600; + const pad = 2; + const n = Math.max(series.length, 1); + const bw = w / n; + const max = Math.max(1, ...series.map((d) => d.rx + d.tx)); + let bars = ''; + series.forEach((d, i) => { + const x = i * bw + pad / 2; + // From the person's point of view: router tx = download, rx = upload. + const hDown = (d.tx / max) * (height - 4); + const hUp = (d.rx / max) * (height - 4); + const title = `${d.day}: ↓ ${bytes(d.tx)} · ↑ ${bytes(d.rx)}`; + bars += + `${title}` + + `` + + `` + + ``; + }); + return `${bars}`; +} diff --git a/web/src/shared/format.ts b/web/src/shared/format.ts new file mode 100644 index 0000000..3bfc1d7 --- /dev/null +++ b/web/src/shared/format.ts @@ -0,0 +1,120 @@ +// Formatting helpers shared by the admin UI and the portal (English only). + +import type { Access, Kind, PersonState } from './types'; + +export function bytes(n: number): string { + if (!n || n < 0) return '0 B'; + const units = ['B', 'KB', 'MB', 'GB', 'TB']; + let i = 0; + let v = n; + while (v >= 1024 && i < units.length - 1) { + v /= 1024; + i++; + } + return `${v >= 100 || i === 0 ? Math.round(v) : v.toFixed(1)} ${units[i]}`; +} + +/** Bytes per second as a bit rate. */ +export function bits(bps: number): string { + const b = bps * 8; + if (b < 1000) return `${Math.round(b)} bit/s`; + if (b < 1e6) return `${(b / 1e3).toFixed(b < 1e4 ? 1 : 0)} kbit/s`; + if (b < 1e9) return `${(b / 1e6).toFixed(b < 1e7 ? 1 : 0)} Mbit/s`; + return `${(b / 1e9).toFixed(1)} Gbit/s`; +} + +export function ago(ts: number, now = Date.now() / 1000): string { + if (!ts) return 'never'; + const d = Math.max(0, Math.round(now - ts)); + if (d < 60) return 'just now'; + if (d < 3600) return `${Math.floor(d / 60)} min ago`; + if (d < 86400) return `${Math.floor(d / 3600)} h ago`; + if (d < 86400 * 30) return `${Math.floor(d / 86400)} d ago`; + return new Date(ts * 1000).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }); +} + +export function duration(sec: number): string { + if (!sec || sec < 0) return '—'; + const d = Math.floor(sec / 86400); + const h = Math.floor((sec % 86400) / 3600); + const m = Math.floor((sec % 3600) / 60); + if (d) return `${d}d ${h}h`; + if (h) return `${h}h ${m}m`; + return `${m}m`; +} + +export function clock(ts: number): string { + const d = new Date(ts * 1000); + const today = new Date(); + const sameDay = d.toDateString() === today.toDateString(); + const t = d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }); + return sameDay ? t : `${d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })} ${t}`; +} + +export function date(s: string): string { + if (!s) return ''; + const [y, m, d] = s.split('-').map(Number); + return new Date(y, m - 1, d).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }); +} + +/** Whole days until the end of the given YYYY-MM-DD (negative when past). */ +export function daysLeft(s: string, now = Date.now()): number | null { + if (!s) return null; + const [y, m, d] = s.split('-').map(Number); + const end = new Date(y, m - 1, d, 23, 59, 59).getTime(); + return Math.ceil((end - now) / 86400000); +} + +export const ACCESS_LABEL: Record = { + lan: 'Home network', + internet: 'Internet', + both: 'Home network + Internet', +}; + +export const ACCESS_SHORT: Record = { lan: 'LAN', internet: 'Internet', both: 'LAN + Internet' }; + +/** In picker order. */ +export const KINDS: Kind[] = ['computer', 'phone', 'tablet', 'router', 'other']; + +export const KIND_LABEL: Record = { + computer: 'PC', + phone: 'Phone', + tablet: 'Tablet', + router: 'Router', + other: 'Other', +}; + +export const STATE_LABEL: Record = { + active: 'Active', + paused: 'Paused', + paused_all: 'Paused (everyone)', + expired: 'Expired', + quota: 'Data limit reached', + hours: 'Outside allowed hours', + no_server: 'No server', +}; + +export function initials(name: string): string { + const parts = name.trim().split(/\s+/).filter(Boolean); + if (!parts.length) return '?'; + const a = parts[0][0] ?? ''; + const b = parts.length > 1 ? (parts[parts.length - 1][0] ?? '') : (parts[0][1] ?? ''); + return (a + b).toUpperCase(); +} + +/** "1.2 GB of 50 GB" style quota text, or just usage when unlimited. */ +export function quotaText(used: number, quotaGb: number, period: 'month' | 'total'): string { + const u = bytes(used); + if (!quotaGb) return `${u} ${period === 'total' ? 'in total' : 'this month'}`; + return `${u} of ${quotaGb} GB${period === 'total' ? '' : ' this month'}`; +} + +export function slugify(s: string): string { + return s + .toLowerCase() + .normalize('NFKD') + .replace(/[̀-ͯ]/g, '') + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 32); +} diff --git a/web/src/shared/icons.ts b/web/src/shared/icons.ts new file mode 100644 index 0000000..5d5707c --- /dev/null +++ b/web/src/shared/icons.ts @@ -0,0 +1,67 @@ +// Inline SVG icons (stroke = currentColor), sized by CSS. + +const P: Record = { + 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: '', + shield: '', + shieldplus: '', + lock: '', + zap: '', + check: '', + alert: '', + x: '', + globe: '', + home: '', + open: '', + file: '', + search: '', + network: + '', + moon: '', + chevron: '', + clock: '', + calendar: '', + minus: '', + more: '', + pin: '', + activity: '', +}; + +export function iconSvg(name: string, cls = 'dl-icon'): string { + const body = P[name] ?? P.phone; + return ``; +} + +export function icon(name: string, cls = 'dl-icon'): HTMLElement { + const span = document.createElement('span'); + span.className = 'dl-icon-wrap'; + span.innerHTML = iconSvg(name, cls); + return span; +} diff --git a/web/src/shared/qr.ts b/web/src/shared/qr.ts new file mode 100644 index 0000000..5f6c0e5 --- /dev/null +++ b/web/src/shared/qr.ts @@ -0,0 +1,49 @@ +// QR codes rendered in the browser as a single-path SVG, with the Dawnline +// mark in the middle. The mark hides about 5% of the code; error correction +// H (30%) covers that for links, Q (25%) keeps long configurations scannable. + +import qrcode from 'qrcode-generator'; + +/** The icon's dome and bar (64×64 viewBox, see portal/icon.svg). */ +const MARK = ''; + +export function qrSvg(text: string, margin = 3, logo = true): string { + const qr = qrcode(0, text.length > 300 ? 'Q' : 'H'); + qr.addData(text, 'Byte'); + qr.make(); + const n = qr.getModuleCount(); + const size = n + margin * 2; + // A centred, module-aligned hole for the mark (same parity as n). + let hole = logo ? Math.round(n * 0.22) : 0; + if (hole && (n - hole) % 2) hole++; + const h0 = (n - hole) / 2, + h1 = h0 + hole; + const inHole = (x: number, y: number) => hole > 0 && x >= h0 && x < h1 && y >= h0 && y < h1; + let d = ''; + for (let y = 0; y < n; y++) { + let x = 0; + while (x < n) { + if (!qr.isDark(y, x) || inHole(x, y)) { + x++; + continue; + } + let w = 1; + while (x + w < n && qr.isDark(y, x + w) && !inHole(x + w, y)) w++; + d += `M${x + margin} ${y + margin}h${w}v1h-${w}z`; + x += w; + } + } + let mark = ''; + if (hole) { + const pad = 0.6, + s = hole - pad * 2, + o = h0 + margin + pad; + mark = + `` + + `${MARK}`; + } + return ( + `` + + `${mark}` + ); +} diff --git a/web/src/shared/types.ts b/web/src/shared/types.ts new file mode 100644 index 0000000..add34e7 --- /dev/null +++ b/web/src/shared/types.ts @@ -0,0 +1,202 @@ +// Shapes returned by the luci.dawnline RPC object and the portal API. + +export type Access = 'lan' | 'internet' | 'both'; +export type Kind = 'computer' | 'phone' | 'tablet' | 'router' | 'other'; +export type PersonState = 'active' | 'paused' | 'paused_all' | 'expired' | 'quota' | 'hours' | 'no_server'; +export type Pair = [number, number]; // [rx, tx] from the router's point of view + +export interface Device { + id: string; + name: string; + kind: Kind; + address: string; + disabled: boolean; + created: number; + created_by: 'admin' | 'portal'; + online: boolean; + handshake: number; + endpoint: string; + active: boolean; + month: Pair; + total: Pair; + /** Daily totals (rx+tx) for the last 7 days, oldest first. */ + spark: number[]; + hostname: string; + browser_key: boolean; + /** Its configuration changed (networks, DNS, keys...) since it was last shown or downloaded. */ + config_stale: boolean; +} + +export interface Person { + id: string; + name: string; + server: string; + access: Access; + device_limit: number; + expires: string; + quota_gb: number; + quota_period: 'month' | 'total'; + quota_used: number; + /** Effective limit in bytes for the current period (incl. this month's extra), 0 = unlimited. */ + quota_limit: number; + bonus_gb: number; + expire_action: 'pause' | 'notify' | 'remove'; + expire_warn: number; + /** Home-only access: the device keeps its own DNS, or uses home names through the tunnel. */ + dns_mode: 'device' | 'home'; + paused: boolean; + hours: string; + state: PersonState; + month: Pair; + total: Pair; + online: number; + last_seen: number; + devices: Device[]; + /** Throughput, one point a minute (last 15): [ts, rx, tx] in bytes/s (rx = from devices); admin only. */ + rate?: [number, number, number][]; + // admin only + code?: string; + link?: string | null; + /** Every link to the same portal (main first), one per address; admin only. */ + links?: string[]; + note?: string; + services?: string[]; + created?: number; +} + +export interface Server { + id: string; + name: string; + ifname: string; + port: number; + subnet: string; + endpoint: string; + public_key: string; + enabled: boolean; + /** Internet traffic enters the router from the LAN, like a home device's. */ + lan_like: boolean; + preset: string; + mtu: number; + keepalive: number; + /** DNS servers given to devices; empty = this router. */ + dns: string[]; + /** Daily traffic of the people on this server. */ + series: DayUsage[]; + /** Throughput, one point a minute: [ts, rx, tx] in bytes/s (rx = from devices). */ + rate: [number, number, number][]; + address: string; + up: boolean; + uptime: number; + peers: number; + online: number; + obf: Record; +} + +export interface DayUsage { + day: string; + rx: number; + tx: number; +} + +export interface LogEvent { + ts: number; + type: string; + person?: string; + device?: string; + server?: string; + detail?: string; + /** City · network operator, when known at the time of the event. */ + where?: string | null; +} + +export interface GeoPoint { + person: string; + device: string; + ip: string; + ts: number; + online: boolean; + lat: number; + lon: number; + city: string; + country: string; + cc: string; + /** Network operator (from the geolocation service); 0 / '' when unknown. */ + asn: number; + org: string; +} + +export interface Geo { + enabled: boolean; + provider?: string; + cached?: number; + home: { lat: number; lon: number; city: string; country: string; cc: string; asn?: number; org?: string } | null; + points: GeoPoint[]; +} + +export interface AwgCaps { + v2: boolean; + v3: boolean; +} + +export interface Status { + geo: Geo; + version: string; + now: number; + hostname: string; + settings: { + portal_enabled: boolean; + portal_port: number; + /** The port in personal links (443 when the portal also answers there). */ + portal_public_port?: number; + portal_443?: boolean; + portal_host: string; + paused_all: boolean; + default_device_limit: number; + domain: string; + hostnames: boolean; + geo_enabled: boolean; + home_dns_fallback: string; + }; + servers: Server[]; + people: Person[]; + services: { id: string; name: string; address: string; ports: string[] }[]; + totals: { people: number; devices: number; online: number; active: number; today: Pair; month: Pair }; + series: DayUsage[]; + events: LogEvent[]; + /** What the installed AmneziaWG supports: v2 (1.5/2.0 parameters), v3 (3.1). */ + awg: AwgCaps; + like_home: { active: boolean; dev?: string; address?: string; bridged?: boolean; off?: boolean; error?: string }; +} + +export interface AmneziaFields { + host: string; + port: number; + mtu: string; + dns: string[]; + allowed_ips: string[]; + client_ip: string; + client_priv_key: string; + client_pub_key: string; + psk_key: string; + server_pub_key: string; + persistent_keep_alive: string; + obfuscation: Record; +} + +export interface ClientConfig { + name: string; + person: string; + server: string; + filename: string; + conf: string; + has_private_key: boolean; + amnezia: AmneziaFields; +} + +export interface HealthCheck { + id: string; + title: string; + status: 'ok' | 'warn' | 'error' | 'skip'; + detail: string; + fix: string | null; +} diff --git a/web/src/shared/vpnkey.ts b/web/src/shared/vpnkey.ts new file mode 100644 index 0000000..28ef316 --- /dev/null +++ b/web/src/shared/vpnkey.ts @@ -0,0 +1,146 @@ +// AmneziaVPN `vpn://` keys: "vpn://" + base64url (no padding) of Qt's +// qCompress(JSON) — a 4-byte big-endian length followed by a zlib stream. +// AmneziaVPN also accepts plain JSON, used when CompressionStream is missing. + +import type { ClientConfig } from './types'; + +const DEFAULTS: Record = { + 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: '', +}; + +/** AmneziaWG 3.1 settings, under the names AmneziaVPN uses; only those that are set. */ +const AWG3: Record = { + 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 awg3(o: Record): Record { + const out: Record = {}; + for (const [k, name] of Object.entries(AWG3)) if (o[k] != null && o[k] !== '') out[name] = String(o[k]); + return out; +} + +export function amneziaJson(cfg: ClientConfig, description: string): Record { + const a = cfg.amnezia; + const o = a.obfuscation ?? {}; + const v = (k: string) => (o[k] != null && o[k] !== '' ? String(o[k]) : DEFAULTS[k]); + const host = a.host.replace(/^\[(.*)\]$/, '$1'); + const last = { + 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'), + ...awg3(o), + 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: cfg.conf.replace(/\r?\n/g, '\r\n'), + hostName: host, + 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, + }; + const out: Record = { + containers: [ + { + container: 'amnezia-awg', + awg: { + isThirdPartyConfig: true, + last_config: JSON.stringify(last), + port: String(a.port), + protocol_version: o.header_protection_key ? '3.1' : '2', + transport_proto: 'udp', + }, + }, + ], + defaultContainer: 'amnezia-awg', + description, + hostName: host, + }; + if (a.dns[0]) out.dns1 = a.dns[0]; + if (a.dns[1]) out.dns2 = a.dns[1]; + return out; +} + +export function base64Url(bytes: Uint8Array): string { + let bin = ''; + for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} + +export function fromBase64Url(s: string): Uint8Array { + const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4); + const bin = atob(b64); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} + +export async function qCompress(data: Uint8Array): Promise { + // LuCI's module loader shadows some globals; always go through globalThis. + const g = globalThis as unknown as { CompressionStream?: typeof CompressionStream; Blob: typeof Blob; Response: typeof Response }; + if (typeof g.CompressionStream === 'undefined') return null; + try { + const stream = new g.Blob([data as Uint8Array]).stream().pipeThrough(new g.CompressionStream('deflate')); + const zlib = new Uint8Array(await new g.Response(stream).arrayBuffer()); + const out = new Uint8Array(4 + zlib.length); + new DataView(out.buffer).setUint32(0, data.length, false); + out.set(zlib, 4); + return out; + } catch { + return null; + } +} + +export async function vpnKey(cfg: ClientConfig, description: string, compress = true): Promise { + const json = new TextEncoder().encode(JSON.stringify(amneziaJson(cfg, description))); + const packed = compress ? await qCompress(json) : null; + return `vpn://${base64Url(packed ?? json)}`; +} + +/** The .conf with a browser-held private key substituted in. */ +export function withPrivateKey(cfg: ClientConfig, priv: string): ClientConfig { + return { + ...cfg, + has_private_key: true, + conf: cfg.conf.replace(/^PrivateKey = .*$/m, `PrivateKey = ${priv}`), + amnezia: { ...cfg.amnezia, client_priv_key: priv }, + }; +} diff --git a/web/tests/shared.test.ts b/web/tests/shared.test.ts new file mode 100644 index 0000000..88ca270 --- /dev/null +++ b/web/tests/shared.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from 'vitest'; +import { inflateSync } from 'node:zlib'; +import { bytes, daysLeft, initials, quotaText, slugify } from '../src/shared/format'; +import { amneziaJson, base64Url, fromBase64Url, vpnKey, withPrivateKey } from '../src/shared/vpnkey'; +import type { ClientConfig } from '../src/shared/types'; + +const cfg: ClientConfig = { + name: 'Phone', + person: 'Myata', + server: 'Home', + filename: 'myata-phone.conf', + conf: '[Interface]\nPrivateKey = AAA=\nAddress = 10.77.0.2/32\n\n[Peer]\nPublicKey = BBB=\n', + has_private_key: true, + amnezia: { + host: 'vpn.example.com', + port: 51830, + mtu: '1380', + dns: ['10.0.1.1'], + allowed_ips: ['0.0.0.0/0', '::/0'], + client_ip: '10.77.0.2', + client_priv_key: 'AAA=', + client_pub_key: 'CCC=', + psk_key: 'DDD=', + server_pub_key: 'BBB=', + persistent_keep_alive: '25', + obfuscation: { jc: '4', jmin: '70', jmax: '120', s1: '20', s2: '30', h1: '11', h2: '22', h3: '33', h4: '44' }, + }, +}; + +describe('format', () => { + it('formats bytes', () => { + expect(bytes(0)).toBe('0 B'); + expect(bytes(1536)).toBe('1.5 KB'); + expect(bytes(5 * 1073741824)).toBe('5.0 GB'); + }); + it('makes initials and slugs', () => { + expect(initials('myata')).toBe('MY'); + expect(initials('Anna Maria Lee')).toBe('AL'); + expect(slugify('Ünïcode Name!')).toBe('unicode-name'); + }); + it('describes quotas', () => { + expect(quotaText(1073741824, 0, 'month')).toBe('1.0 GB this month'); + expect(quotaText(1073741824, 50, 'month')).toBe('1.0 GB of 50 GB this month'); + expect(quotaText(0, 10, 'total')).toBe('0 B of 10 GB'); + }); + it('counts days left', () => { + const now = new Date(2026, 9, 14, 12).getTime(); + expect(daysLeft('2026-10-14', now)).toBe(1); + expect(daysLeft('2026-10-20', now)).toBe(7); + expect(daysLeft('2026-10-01', now)).toBeLessThan(0); + expect(daysLeft('', now)).toBeNull(); + }); +}); + +describe('vpn:// keys', () => { + it('round-trips base64url', () => { + const b = new Uint8Array([0, 1, 250, 251, 252, 253, 254, 255]); + expect(Array.from(fromBase64Url(base64Url(b)))).toEqual(Array.from(b)); + }); + + it('builds the AmneziaVPN structure', () => { + const j = amneziaJson(cfg, 'Home · Myata · Phone') as any; + expect(j.defaultContainer).toBe('amnezia-awg'); + expect(j.dns1).toBe('10.0.1.1'); + const last = JSON.parse(j.containers[0].awg.last_config); + expect(last.Jc).toBe('4'); + expect(last.S3).toBe('0'); + expect(last.H1).toBe('11'); + expect(last.port).toBe(51830); + expect(last.config).toContain('\r\n'); + }); + + it('produces a qCompress payload AmneziaVPN can read', async () => { + const key = await vpnKey(cfg, 'x'); + expect(key.startsWith('vpn://')).toBe(true); + const raw = fromBase64Url(key.slice(6)); + const len = new DataView(raw.buffer).getUint32(0, false); + const json = inflateSync(Buffer.from(raw.slice(4))).toString('utf8'); + expect(json.length).toBe(len); + expect(JSON.parse(json).hostName).toBe('vpn.example.com'); + }); + + it('substitutes a browser-held private key', () => { + const c = withPrivateKey( + { ...cfg, has_private_key: false, conf: cfg.conf.replace('AAA=', '') }, + 'ZZZ=', + ); + expect(c.conf).toContain('PrivateKey = ZZZ='); + expect(c.amnezia.client_priv_key).toBe('ZZZ='); + }); +}); diff --git a/web/tsconfig.json b/web/tsconfig.json new file mode 100644 index 0000000..dc721b4 --- /dev/null +++ b/web/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2021", "DOM", "DOM.Iterable"], + "strict": true, + "noUnusedLocals": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true + }, + "include": ["src"] +} diff --git a/web/tsup.config.ts b/web/tsup.config.ts new file mode 100644 index 0000000..b464308 --- /dev/null +++ b/web/tsup.config.ts @@ -0,0 +1,104 @@ +import { defineConfig } from 'tsup'; +import { transform, type Plugin } from 'esbuild'; +import fs from 'node:fs'; +import path from 'node:path'; + +const PKG = '../package/luci-app-dawnline'; +const ADMIN_OUT = `${PKG}/htdocs/luci-static/resources/dawnline`; +// Outside the web root: the portal CGI serves them only with a valid code. +const PORTAL_OUT = `${PKG}/root/usr/share/dawnline/portal/assets`; + +// LuCI evaluates a module's source as a function body whose parameters are +// the `'require x'` directives; it must `return` its class. tsup emits ESM, +// so the trailing `export { ... }` is rewritten into a baseclass. +function patchForLuci(file: string) { + const code = fs.readFileSync(file, 'utf8'); + const patched = code.replace(/export\s*{([\s\S]*?)};?\s*$/, (_m, body: string) => { + const props = body + .split(',') + .map((s) => s.trim()) + .filter(Boolean) + .map((s) => { + const [local, exported] = s.split(/\s+as\s+/); + return exported ? `${exported}: ${local}` : local; + }); + return `return baseclass.extend({ ${props.join(', ')} });\n`; + }); + if (patched === code) throw new Error(`LuCI patch failed: no export block in ${file}`); + fs.writeFileSync(file, patched); +} + +/** Minify CSS with esbuild (the same engine that bundles the scripts). */ +async function minifyCss(css: string): Promise { + return (await transform(css, { loader: 'css', minify: true, legalComments: 'none' })).code.trim(); +} + +// The admin styles live in a template string in styles.ts (rendered inside each +// view); squeeze that string before bundling. It has no ${} and no backslashes. +const minifyStylesTs: Plugin = { + name: 'minify-styles-ts', + setup(build) { + build.onLoad({ filter: /admin[\\/]styles\.ts$/ }, async (args) => { + const src = fs.readFileSync(args.path, 'utf8'); + const m = /const CSS = `([\s\S]*?)`;/.exec(src); + if (!m) throw new Error('styles.ts: CSS template not found'); + if (/\$\{|\\/.test(m[1])) throw new Error('styles.ts: the CSS must not contain ${} or backslashes'); + const css = await minifyCss(m[1]); + return { contents: src.replace(m[0], `const CSS = \`${css}\`;`), loader: 'ts' }; + }); + }, +}; + +export default defineConfig([ + { + entry: { app: 'src/admin/main.ts' }, + format: ['esm'], + outDir: ADMIN_OUT, + outExtension: () => ({ js: '.js' }), + target: 'es2020', + clean: false, + sourcemap: false, + // Identifiers only: LuCI's require directives in the banner must stay as written. + minify: true, + noExternal: ['qrcode-generator'], + esbuildPlugins: [minifyStylesTs], + banner: { + js: [ + '// Generated from dawnline/web — do not edit by hand.', + "'use strict';", + "'require baseclass';", + "'require dom';", + "'require form';", + "'require poll';", + "'require rpc';", + "'require uci';", + "'require ui';", + ].join('\n'), + }, + esbuildOptions(o) { + o.legalComments = 'none'; + o.charset = 'utf8'; + }, + onSuccess: async () => patchForLuci(path.join(ADMIN_OUT, 'app.js')), + }, + { + entry: { portal: 'src/portal/main.ts' }, + format: ['iife'], + outDir: PORTAL_OUT, + outExtension: () => ({ js: '.js' }), + target: 'es2019', + clean: false, + sourcemap: false, + minify: true, + noExternal: ['qrcode-generator'], + esbuildOptions(o) { + o.legalComments = 'none'; + o.charset = 'utf8'; + }, + onSuccess: async () => { + fs.writeFileSync(path.join(PORTAL_OUT, 'portal.css'), (await minifyCss(fs.readFileSync('src/portal/portal.css', 'utf8'))) + '\n'); + fs.copyFileSync('src/portal/icon.svg', path.join(PORTAL_OUT, 'icon.svg')); + for (const f of fs.readdirSync('src/portal/fonts')) fs.copyFileSync(path.join('src/portal/fonts', f), path.join(PORTAL_OUT, f)); + }, + }, +]); diff --git a/web/vitest.config.ts b/web/vitest.config.ts new file mode 100644 index 0000000..b0e95a5 --- /dev/null +++ b/web/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['tests/**/*.test.ts'], + environment: 'node', + }, +});