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
No files matched your search
@@ -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.
|
||||
@@ -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"
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.DS_Store
|
||||
web/coverage/
|
||||
@@ -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.
|
||||
@@ -0,0 +1,154 @@
|
||||
# Dawnline
|
||||
|
||||
[](https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml)
|
||||
[](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.
|
||||
|
||||

|
||||
|
||||
| People | A person |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|
||||
| Personal portal | Where people connect from |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|
||||
## 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)
|
||||
@@ -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/ \;
|
||||
|
After Width: | Height: | Size: 418 KiB |
|
After Width: | Height: | Size: 277 KiB |
|
After Width: | Height: | Size: 283 KiB |
|
After Width: | Height: | Size: 301 KiB |
|
After Width: | Height: | Size: 291 KiB |
|
After Width: | Height: | Size: 328 KiB |
|
After Width: | Height: | Size: 153 KiB |
|
After Width: | Height: | Size: 159 KiB |
|
After Width: | Height: | Size: 176 KiB |
|
After Width: | Height: | Size: 169 KiB |
@@ -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: <name>_v<release>_<arch>_<target>_<subtarget>.<ext>
|
||||
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 "$@"
|
||||
@@ -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
|
||||
@@ -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<x;A+=1){E[A]=new Array(x);for(var I=0;I<x;I+=1)E[A][I]=null}return E})(p),q(0,0),q(p-7,0),q(0,p-7),ee(),Z(),ue(M,S),g>=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<p-8;M+=1)c[M][6]==null&&(c[M][6]=M%2==0);for(var S=8;S<p-8;S+=1)c[6][S]==null&&(c[6][S]=S%2==0)},ee=function(){for(var M=i.getPatternPosition(g),S=0;S<M.length;S+=1)for(var x=0;x<M.length;x+=1){var E=M[S],A=M[x];if(c[E][A]==null)for(var I=-2;I<=2;I+=1)for(var G=-2;G<=2;G+=1)I==-2||I==2||G==-2||G==2||I==0&&G==0?c[E+I][A+G]=!0:c[E+I][A+G]=!1}},ie=function(M){for(var S=i.getBCHTypeNumber(g),x=0;x<18;x+=1){var E=!M&&(S>>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<M.length&&(de=(M[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<S.length;U+=1){var te=S[U].dataCount,de=S[U].totalCount-te;E=Math.max(E,te),A=Math.max(A,de),I[U]=new Array(te);for(var F=0;F<I[U].length;F+=1)I[U][F]=255&M.getBuffer()[F+x];x+=te;var fe=i.getErrorCorrectPolynomial(de),me=r(I[U],fe.getLength()-1),qt=me.mod(fe);G[U]=new Array(fe.getLength()-1);for(var F=0;F<G[U].length;F+=1){var Ut=F+qt.getLength()-G[U].length;G[U][F]=Ut>=0?qt.getAt(Ut):0}}for(var Gt=0,F=0;F<S.length;F+=1)Gt+=S[F].totalCount;for(var kt=new Array(Gt),ot=0,F=0;F<E;F+=1)for(var U=0;U<S.length;U+=1)F<I[U].length&&(kt[ot]=I[U][F],ot+=1);for(var F=0;F<A;F+=1)for(var U=0;U<S.length;U+=1)F<G[U].length&&(kt[ot]=G[U][F],ot+=1);return kt},yt=function(M,S,x){for(var E=l.getRSBlocks(M,S),A=d(),I=0;I<x.length;I+=1){var G=x[I];A.put(G.getMode(),4),A.put(G.getLength(),i.getLengthInBits(G.getMode(),M)),G.write(A)}for(var U=0,I=0;I<E.length;I+=1)U+=E[I].dataCount;if(A.getLengthInBits()>U*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<v.length;E++){var A=v[E];x.put(A.getMode(),4),x.put(A.getLength(),i.getLengthInBits(A.getMode(),M)),A.write(x)}for(var I=0,E=0;E<S.length;E++)I+=S[E].dataCount;if(x.getLengthInBits()<=I*8)break}g=M}j(!1,H())},b.createTableTag=function(M,S){M=M||2,S=typeof S>"u"?M*4:S;var x="";x+='<table style="',x+=" border-width: 0px; border-style: none;",x+=" border-collapse: collapse;",x+=" padding: 0px; margin: "+S+"px;",x+='">',x+="<tbody>";for(var E=0;E<b.getModuleCount();E+=1){x+="<tr>";for(var A=0;A<b.getModuleCount();A+=1)x+='<td style="',x+=" border-width: 0px; border-style: none;",x+=" border-collapse: collapse;",x+=" padding: 0px; margin: 0px;",x+=" width: "+M+"px;",x+=" height: "+M+"px;",x+=" background-color: ",x+=b.isDark(E,A)?"#000000":"#ffffff",x+=";",x+='"/>';x+="</tr>"}return x+="</tbody>",x+="</table>",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,Line truncated
|
||||
`}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<x;I+=1){for(U=Math.floor((I-E)/M),me="",G=0;G<x;G+=1)te=1,E<=G&&G<A&&E<=I&&I<A&&b.isDark(U,Math.floor((G-E)/M))&&(te=0),me+=te?de:F;for(U=0;U<M;U+=1)fe+=me+`
|
||||
`}return fe.substring(0,fe.length-1)},b.renderTo2dContext=function(M,S){S=S||2;for(var x=b.getModuleCount(),E=0;E<x;E++)for(var A=0;A<x;A++)M.fillStyle=b.isDark(E,A)?"black":"white",M.fillRect(E*S,A*S,S,S)},b};s.stringToBytesFuncs={default:function(y){for(var D=[],T=0;T<y.length;T+=1){var f=y.charCodeAt(T);D.push(f&255)}return D}},s.stringToBytes=s.stringToBytesFuncs.default,s.createStringToBytes=function(y,D){var T=(function(){for(var g=J(y),k=function(){var Z=g.read();if(Z==-1)throw"eof";return Z},c=0,p={};;){var C=g.read();if(C==-1)break;var v=k(),b=k(),j=k(),q=String.fromCharCode(C<<8|v),H=b<<8|j;p[q]=H,c+=1}if(c!=D)throw c+" != "+D;return p})(),f=63;return function(g){for(var k=[],c=0;c<g.length;c+=1){var p=g.charCodeAt(c);if(p<128)k.push(p);else{var C=T[g.charAt(c)];typeof C=="number"?(C&255)==C?k.push(C):(k.push(C>>>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<<k(p)-k(D);return(c<<10|p)^f},g.getBCHTypeNumber=function(c){for(var p=c<<12;k(p)-k(T)>=0;)p^=T<<k(p)-k(T);return c<<12|p},g.getPatternPosition=function(c){return y[c-1]},g.getMaskFunction=function(c){switch(c){case n.PATTERN000:return function(p,C){return(p+C)%2==0};case n.PATTERN001:return function(p,C){return p%2==0};case n.PATTERN010:return function(p,C){return C%3==0};case n.PATTERN011:return function(p,C){return(p+C)%3==0};case n.PATTERN100:return function(p,C){return(Math.floor(p/2)+Math.floor(C/3))%2==0};case n.PATTERN101:return function(p,C){return p*C%2+p*C%3==0};case n.PATTERN110:return function(p,C){return(p*C%2+p*C%3)%2==0};case n.PATTERN111:return function(p,C){return(p*C%3+(p+C)%2)%2==0};default:throw"bad maskPattern:"+c}},g.getErrorCorrectPolynomial=function(c){for(var p=r([1],0),C=0;C<c;C+=1)p=p.multiply(r([1,o.gexp(C)],0));return p},g.getLengthInBits=function(c,p){if(1<=p&&p<10)switch(c){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+c}else if(p<27)switch(c){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+c}else if(p<41)switch(c){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+c}else throw"type:"+p},g.getLostPoint=function(c){for(var p=c.getModuleCount(),C=0,v=0;v<p;v+=1)for(var b=0;b<p;b+=1){for(var j=0,q=c.isDark(v,b),H=-1;H<=1;H+=1)if(!(v+H<0||p<=v+H))for(var Z=-1;Z<=1;Z+=1)b+Z<0||p<=b+Z||H==0&&Z==0||q==c.isDark(v+H,b+Z)&&(j+=1);j>5&&(C+=3+j-5)}for(var v=0;v<p-1;v+=1)for(var b=0;b<p-1;b+=1){var ee=0;c.isDark(v,b)&&(ee+=1),c.isDark(v+1,b)&&(ee+=1),c.isDark(v,b+1)&&(ee+=1),c.isDark(v+1,b+1)&&(ee+=1),(ee==0||ee==4)&&(C+=3)}for(var v=0;v<p;v+=1)for(var b=0;b<p-6;b+=1)c.isDark(v,b)&&!c.isDark(v,b+1)&&c.isDark(v,b+2)&&c.isDark(v,b+3)&&c.isDark(v,b+4)&&!c.isDark(v,b+5)&&c.isDark(v,b+6)&&(C+=40);for(var b=0;b<p;b+=1)for(var v=0;v<p-6;v+=1)c.isDark(v,b)&&!c.isDark(v+1,b)&&c.isDark(v+2,b)&&c.isDark(v+3,b)&&c.isDark(v+4,b)&&!c.isDark(v+5,b)&&c.isDark(v+6,b)&&(C+=40);for(var ie=0,b=0;b<p;b+=1)for(var v=0;v<p;v+=1)c.isDark(v,b)&&(ie+=1);var ue=Math.abs(100*ie/p/p-50)/5;return C+=ue*10,C},g})(),o=(function(){for(var y=new Array(256),D=new Array(256),T=0;T<8;T+=1)y[T]=1<<T;for(var T=8;T<256;T+=1)y[T]=y[T-4]^y[T-5]^y[T-6]^y[T-8];for(var T=0;T<255;T+=1)D[y[T]]=T;var f={};return f.glog=function(g){if(g<1)throw"glog("+g+")";return D[g]},f.gexp=function(g){for(;g<0;)g+=255;for(;g>=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<y.length&&y[g]==0;)g+=1;for(var k=new Array(y.length-g+D),c=0;c<y.length-g;c+=1)k[c]=y[c+g];return k})(),f={};return f.getAt=function(g){return T[g]},f.getLength=function(){return T.length},f.multiply=function(g){for(var k=new Array(f.getLength()+g.getLength()-1),c=0;c<f.getLength();c+=1)for(var p=0;p<g.getLength();p+=1)k[c+p]^=o.gexp(o.glog(f.getAt(c))+o.glog(g.getAt(p)));return r(k,0)},f.mod=function(g){if(f.g
Line truncated
|
||||
`),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<s.length;a+=32768)t+=String.fromCharCode(...s.subarray(a,a+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function qn(s){let t=globalThis;if(typeof t.CompressionStream>"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<t.length-1;)n/=1024,a++;return`${n>=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.
Line truncated
|
||||
`);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",
Line truncated
|
||||
`),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"):""]);r
Line truncated
|
||||
`))]):"",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||a<this.refreshShown)return;this.refreshShown=a,this.st=n,i&&(this.events=i.events),o&&(this.series=o.person,this.devSeries=o.devices);let r=n.people.find(l=>l.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":
Line truncated
|
||||
`)}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 acc
Line truncated
|
||||
@@ -0,0 +1,5 @@
|
||||
'use strict';
|
||||
'require view';
|
||||
'require dawnline.app as app';
|
||||
|
||||
return view.extend(app.activity());
|
||||
@@ -0,0 +1,5 @@
|
||||
'use strict';
|
||||
'require view';
|
||||
'require dawnline.app as app';
|
||||
|
||||
return view.extend(app.health());
|
||||
@@ -0,0 +1,5 @@
|
||||
'use strict';
|
||||
'require view';
|
||||
'require dawnline.app as app';
|
||||
|
||||
return view.extend(app.overview());
|
||||
@@ -0,0 +1,5 @@
|
||||
'use strict';
|
||||
'require view';
|
||||
'require dawnline.app as app';
|
||||
|
||||
return view.extend(app.people());
|
||||
@@ -0,0 +1,5 @@
|
||||
'use strict';
|
||||
'require view';
|
||||
'require dawnline.app as app';
|
||||
|
||||
return view.extend(app.person());
|
||||
@@ -0,0 +1,5 @@
|
||||
'use strict';
|
||||
'require view';
|
||||
'require dawnline.app as app';
|
||||
|
||||
return view.extend(app.server());
|
||||
@@ -0,0 +1,5 @@
|
||||
'use strict';
|
||||
'require view';
|
||||
'require dawnline.app as app';
|
||||
|
||||
return view.extend(app.settings());
|
||||
@@ -0,0 +1,5 @@
|
||||
'use strict';
|
||||
'require view';
|
||||
'require dawnline.app as app';
|
||||
|
||||
return view.extend(app.updates());
|
||||
@@ -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 &
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
@@ -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 <command>
|
||||
|
||||
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 <name> [--slug s] [--access lan|internet|both] [--devices n]
|
||||
[--expires YYYY-MM-DD] [--quota GB]
|
||||
person link <slug> Print the personal portal link
|
||||
person rm <slug> Remove a person and their devices
|
||||
device add <slug> <name> [--kind phone|computer|tablet|router]
|
||||
device conf <id> Print a device configuration
|
||||
device rm <id> 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);
|
||||
}
|
||||
@@ -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();
|
||||
@@ -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"
|
||||
@@ -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:<name,…>|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-<version>.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 >/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 >/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 >/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:<names>|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();
|
||||
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><style>.t{fill:#0a0a0a}.g{fill:#fff}@media (prefers-color-scheme:dark){.t{fill:#fff}.g{fill:#0a0a0a}}</style><rect class="t" width="64" height="64" rx="16"/><path class="g" d="M14 38a18 18 0 0 1 36 0z"/><rect class="g" x="12" y="43" width="40" height="4" rx="2" opacity=".5"/></svg>
|
||||
|
After Width: | Height: | Size: 343 B |
@@ -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);mLine truncated
|
||||
@@ -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<s;h+=1){d[h]=new Array(s);for(var x=0;x<s;x+=1)d[h][x]=null}return d})(r),E(0,0),E(r-7,0),E(0,r-7),q(),I(),Q(c,u),l>=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<r-8;c+=1)i[c][6]==null&&(i[c][6]=c%2==0);for(var u=8;u<r-8;u+=1)i[6][u]==null&&(i[6][u]=u%2==0)},q=function(){for(var c=v.getPatternPosition(l),u=0;u<c.length;u+=1)for(var s=0;s<c.length;s+=1){var d=c[u],h=c[s];if(i[d][h]==null)for(var x=-2;x<=2;x+=1)for(var C=-2;C<=2;C+=1)x==-2||x==2||C==-2||C==2||x==0&&C==0?i[d+x][h+C]=!0:i[d+x][h+C]=!1}},z=function(c){for(var u=v.getBCHTypeNumber(l),s=0;s<18;s+=1){var d=!c&&(u>>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<c.length&&(K=(c[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<u.length;A+=1){var S=u[A].dataCount,K=u[A].totalCount-S;d=Math.max(d,S),h=Math.max(h,K),x[A]=new Array(S);for(var L=0;L<x[A].length;L+=1)x[A][L]=255&c.getBuffer()[L+s];s+=S;var Y=v.getErrorCorrectPolynomial(K),j=_(x[A],Y.getLength()-1),Ee=j.mod(Y);C[A]=new Array(Y.getLength()-1);for(var L=0;L<C[A].length;L+=1){var Be=L+Ee.getLength()-C[A].length;C[A][L]=Be>=0?Ee.getAt(Be):0}}for(var De=0,L=0;L<u.length;L+=1)De+=u[L].totalCount;for(var me=new Array(De),ce=0,L=0;L<d;L+=1)for(var A=0;A<u.length;A+=1)L<x[A].length&&(me[ce]=x[A][L],ce+=1);for(var L=0;L<h;L+=1)for(var A=0;A<u.length;A+=1)L<C[A].length&&(me[ce]=C[A][L],ce+=1);return me},Xe=function(c,u,s){for(var d=$.getRSBlocks(c,u),h=B(),x=0;x<s.length;x+=1){var C=s[x];h.put(C.getMode(),4),h.put(C.getLength(),v.getLengthInBits(C.getMode(),c)),C.write(h)}for(var A=0,x=0;x<d.length;x+=1)A+=d[x].dataCount;if(h.getLengthInBits()>A*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<f.length;d++){var h=f[d];s.put(h.getMode(),4),s.put(h.getLength(),v.getLengthInBits(h.getMode(),c)),h.write(s)}for(var x=0,d=0;d<u.length;d++)x+=u[d].dataCount;if(s.getLengthInBits()<=x*8)break}l=c}T(!1,P())},g.createTableTag=function(c,u){c=c||2,u=typeof u=="undefined"?c*4:u;var s="";s+='<table style="',s+=" border-width: 0px; border-style: none;",s+=" border-collapse: collapse;",s+=" padding: 0px; margin: "+u+"px;",s+='">',s+="<tbody>";for(var d=0;d<g.getModuleCount();d+=1){s+="<tr>";for(var h=0;h<g.getModuleCount();h+=1)s+='<td style="',s+=" border-width: 0px; border-style: none;",s+=" border-collapse: collapse;",s+=" padding: 0px; margin: 0px;",s+=" width: "+c+"px;",s+=" height: "+c+"px;",s+=" background-color: ",s+=g.isDark(d,h)?"#000000":"#ffffff",s+=";",s+='"/>';s+="</tr>"}return s+="</tbody>",s+="</table>",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||nLine truncated
|
||||
`}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<s;x+=1){for(A=Math.floor((x-d)/c),j="",C=0;C<s;C+=1)S=1,d<=C&&C<h&&d<=x&&x<h&&g.isDark(A,Math.floor((C-d)/c))&&(S=0),j+=S?K:L;for(A=0;A<c;A+=1)Y+=j+`
|
||||
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(c,u){u=u||2;for(var s=g.getModuleCount(),d=0;d<s;d++)for(var h=0;h<s;h++)c.fillStyle=g.isDark(d,h)?"black":"white",c.fillRect(d*u,h*u,u,u)},g};n.stringToBytesFuncs={default:function(M){for(var k=[],w=0;w<M.length;w+=1){var b=M.charCodeAt(w);k.push(b&255)}return k}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(M,k){var w=(function(){for(var l=H(M),m=function(){var I=l.read();if(I==-1)throw"eof";return I},i=0,r={};;){var y=l.read();if(y==-1)break;var f=m(),g=m(),T=m(),E=String.fromCharCode(y<<8|f),P=g<<8|T;r[E]=P,i+=1}if(i!=k)throw i+" != "+k;return r})(),b=63;return function(l){for(var m=[],i=0;i<l.length;i+=1){var r=l.charCodeAt(i);if(r<128)m.push(r);else{var y=w[l.charAt(i)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>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<<m(r)-m(k);return(i<<10|r)^b},l.getBCHTypeNumber=function(i){for(var r=i<<12;m(r)-m(w)>=0;)r^=w<<m(r)-m(w);return i<<12|r},l.getPatternPosition=function(i){return M[i-1]},l.getMaskFunction=function(i){switch(i){case o.PATTERN000:return function(r,y){return(r+y)%2==0};case o.PATTERN001:return function(r,y){return r%2==0};case o.PATTERN010:return function(r,y){return y%3==0};case o.PATTERN011:return function(r,y){return(r+y)%3==0};case o.PATTERN100:return function(r,y){return(Math.floor(r/2)+Math.floor(y/3))%2==0};case o.PATTERN101:return function(r,y){return r*y%2+r*y%3==0};case o.PATTERN110:return function(r,y){return(r*y%2+r*y%3)%2==0};case o.PATTERN111:return function(r,y){return(r*y%3+(r+y)%2)%2==0};default:throw"bad maskPattern:"+i}},l.getErrorCorrectPolynomial=function(i){for(var r=_([1],0),y=0;y<i;y+=1)r=r.multiply(_([1,p.gexp(y)],0));return r},l.getLengthInBits=function(i,r){if(1<=r&&r<10)switch(i){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+i}else if(r<27)switch(i){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+i}else if(r<41)switch(i){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+i}else throw"type:"+r},l.getLostPoint=function(i){for(var r=i.getModuleCount(),y=0,f=0;f<r;f+=1)for(var g=0;g<r;g+=1){for(var T=0,E=i.isDark(f,g),P=-1;P<=1;P+=1)if(!(f+P<0||r<=f+P))for(var I=-1;I<=1;I+=1)g+I<0||r<=g+I||P==0&&I==0||E==i.isDark(f+P,g+I)&&(T+=1);T>5&&(y+=3+T-5)}for(var f=0;f<r-1;f+=1)for(var g=0;g<r-1;g+=1){var q=0;i.isDark(f,g)&&(q+=1),i.isDark(f+1,g)&&(q+=1),i.isDark(f,g+1)&&(q+=1),i.isDark(f+1,g+1)&&(q+=1),(q==0||q==4)&&(y+=3)}for(var f=0;f<r;f+=1)for(var g=0;g<r-6;g+=1)i.isDark(f,g)&&!i.isDark(f,g+1)&&i.isDark(f,g+2)&&i.isDark(f,g+3)&&i.isDark(f,g+4)&&!i.isDark(f,g+5)&&i.isDark(f,g+6)&&(y+=40);for(var g=0;g<r;g+=1)for(var f=0;f<r-6;f+=1)i.isDark(f,g)&&!i.isDark(f+1,g)&&i.isDark(f+2,g)&&i.isDark(f+3,g)&&i.isDark(f+4,g)&&!i.isDark(f+5,g)&&i.isDark(f+6,g)&&(y+=40);for(var z=0,g=0;g<r;g+=1)for(var f=0;f<r;f+=1)i.isDark(f,g)&&(z+=1);var Q=Math.abs(100*z/r/r-50)/5;return y+=Q*10,y},l})(),p=(function(){for(var M=new Array(256),k=new Array(256),w=0;w<8;w+=1)M[w]=1<<w;for(var w=8;w<256;w+=1)M[w]=M[w-4]^M[w-5]^M[w-6]^M[w-8];for(var w=0;w<255;w+=1)k[M[w]]=w;var b={};return b.glog=function(l){if(l<1)throw"glog("+l+")";return k[l]},b.gexp=function(l){for(;l<0;)l+=255;for(;l>=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<M.length&&M[l]==0;)l+=1;for(var m=new Array(M.length-l+k),i=0;i<M.length-l;i+=1)m[i]=M[i+l];return m})(),b={};return b.getAt=function(l){return w[l]},b.getLength=function(){return w.length},b.multiply=function(l){for(var m=new Array(b.getLength()+l.getLength()-1),i=0;i<b.getLength();i+=1)for(var r=0;r<l.getLength();r+=1)m[i+r]^=p.gexp(p.glog(b.getAt(i))+p.glog(l.getAt(r)));return _(m,0)},b.mod=function(l){if(b.getLen
Line truncated
|
||||
`),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<n.length;a+=32768)e+=String.fromCharCode(...n.subarray(a,a+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function pt(n){let e=globalThis;if(typeof e.CompressionStream=="undefined")return null;try{let a=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),o=new Uint8Array(await new e.Response(a).arrayBuffer()),v=new Uint8Array(4+o.length);return new DataView(v.buffer).setUint32(0,n.length,!1),v.set(o,4),v}catch{return null}}async function xe(n,e,a=!0){let o=new TextEncoder().encode(JSON.stringify(ht(n,e))),v=a?await pt(o):null;return`vpn://${vt(v!=null?v:o)}`}function t(n,e={},...a){let o=document.createElement(n);for(let[p,_]of Object.entries(e))_==null||_===!1||(p.startsWith("on")&&typeof _=="function"?o.addEventListener(p.slice(2),_):p==="class"?o.className=String(_):_===!0?o.setAttribute(p,""):o.setAttribute(p,String(_)));let v=p=>{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='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 15a9 9 0 0 1 18 0z" fill="currentColor"/><rect x="2" y="17" width="20" height="2" rx="1" fill="currentColor" opacity=".45"/></svg>',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("
Line truncated
|
||||
`).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
Line truncated
|
||||
@@ -0,0 +1,344 @@
|
||||
#!/usr/bin/ucode
|
||||
// Dawnline personal portal (CGI behind a dedicated uhttpd instance).
|
||||
//
|
||||
// GET /<code> the app shell (<code> = three words, the personal link)
|
||||
// GET /<code>/assets/<file> its script, styles, fonts
|
||||
// GET /<code>/api/state
|
||||
// POST /<code>/api/devices { name, kind, public_key? }
|
||||
// GET /<code>/api/devices/<id>/config
|
||||
// POST /<code>/api/devices/<id> { 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(`<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>${html_escape(title)}</title>
|
||||
<link rel="icon" href="${base}/assets/icon.svg${q}" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="${base}/assets/portal.css${q}">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" data-base="${html_escape(base ?? '')}" data-title="${html_escape(title)}"></div>
|
||||
<script src="${base}/assets/portal.js${q}" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
`);
|
||||
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 /<word-code>[/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.');
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <p> sport <port> 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');
|
||||
};
|
||||
@@ -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_<key>`. */
|
||||
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 = '<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>';
|
||||
|
||||
/**
|
||||
* 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 || '<private key stays on your device>'}`);
|
||||
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);
|
||||
};
|
||||
@@ -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 });
|
||||
};
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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 };
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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();
|
||||
};
|
||||
@@ -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 </dev/null &`);
|
||||
};
|
||||
|
||||
/* ---------- randomness ---------- */
|
||||
|
||||
export function rand_bytes(n) {
|
||||
let f = open('/dev/urandom', 'r');
|
||||
let b = f.read(n);
|
||||
f.close();
|
||||
return b;
|
||||
};
|
||||
|
||||
export function rand_hex(n) {
|
||||
return hexenc(rand_bytes(n));
|
||||
};
|
||||
|
||||
const ALNUM = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
|
||||
/** URL-safe random token without look-alike characters. */
|
||||
export function rand_token(len) {
|
||||
let b = rand_bytes(len), s = '';
|
||||
for (let i = 0; i < len; i++)
|
||||
s += substr(ALNUM, ord(b, i) % length(ALNUM), 1);
|
||||
return s;
|
||||
};
|
||||
|
||||
export function rand_int(lo, hi) {
|
||||
let b = rand_bytes(4);
|
||||
let n = (ord(b, 0) << 24 | ord(b, 1) << 16 | ord(b, 2) << 8 | ord(b, 3)) & 0x7fffffff;
|
||||
return lo + n % (hi - lo + 1);
|
||||
};
|
||||
|
||||
/* ---------- files ---------- */
|
||||
|
||||
export function ensure_dir(path, mode) {
|
||||
let parts = split(path, '/'), cur = '';
|
||||
for (let p in parts) {
|
||||
if (p == '')
|
||||
continue;
|
||||
cur += '/' + p;
|
||||
if (!stat(cur))
|
||||
mkdir(cur, mode ?? 0o755);
|
||||
}
|
||||
};
|
||||
|
||||
export function read_json(path, fallback) {
|
||||
let s = readfile(path);
|
||||
if (s == null || s == '')
|
||||
return fallback;
|
||||
try {
|
||||
let v = json(s);
|
||||
return v ?? fallback;
|
||||
}
|
||||
catch (e) {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
/** Atomic write (temp file + rename). `mode` defaults to 0600. */
|
||||
export function write_file(path, data, mode) {
|
||||
let tmp = `${path}.tmp${rand_hex(3)}`;
|
||||
let f = open(tmp, 'w', mode ?? 0o600);
|
||||
if (!f)
|
||||
return false;
|
||||
f.write(data);
|
||||
f.close();
|
||||
return rename(tmp, path);
|
||||
};
|
||||
|
||||
export function write_json(path, data, mode) {
|
||||
return write_file(path, sprintf('%J', data), mode);
|
||||
};
|
||||
|
||||
export function file_exists(path) {
|
||||
return stat(path) != null;
|
||||
};
|
||||
|
||||
/** Exclusive lock on a file under RUN_DIR; returns a handle to pass to unlock(). */
|
||||
export function lock(name) {
|
||||
ensure_dir(RUN_DIR);
|
||||
let f = open(`${RUN_DIR}/${name}.lock`, 'w');
|
||||
if (f)
|
||||
f.lock('x');
|
||||
return f;
|
||||
};
|
||||
|
||||
export function unlock(f) {
|
||||
if (f) {
|
||||
f.lock('u');
|
||||
f.close();
|
||||
}
|
||||
};
|
||||
|
||||
/* ---------- IPv4 ---------- */
|
||||
|
||||
export function ip2int(ip) {
|
||||
let m = match(ip, /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let n = 0;
|
||||
for (let i = 1; i <= 4; i++) {
|
||||
let o = +m[i];
|
||||
if (o > 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();
|
||||
};
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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-<version>.{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"
|
||||
@@ -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-<version>.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"
|
||||
@@ -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
|
||||
@@ -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-<ts>/ 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
|
||||
@@ -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/<name>.png; the framed images are
|
||||
written to docs/screenshots/<name>.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 = """<!doctype html><html><head><meta charset="utf-8"><style>
|
||||
html,body{{margin:0;width:{w}px;height:{h}px;overflow:hidden}}
|
||||
body{{display:flex;align-items:center;justify-content:center;
|
||||
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;
|
||||
background:
|
||||
radial-gradient({gw}px {gh}px at 50% 118%, rgba(255,140,70,.55), rgba(255,140,70,0) 70%),
|
||||
radial-gradient({gw2}px {gh2}px at 50% 100%, rgba(250,90,120,.30), rgba(250,90,120,0) 70%),
|
||||
linear-gradient(180deg,#070a14 0%,#0c1226 55%,#1a1430 100%)}}
|
||||
.win{{width:{iw}px;border-radius:14px;overflow:hidden;background:#000;
|
||||
box-shadow:0 0 0 1px rgba(255,255,255,.08),0 40px 120px rgba(0,0,0,.65),0 10px 30px rgba(0,0,0,.4)}}
|
||||
.bar{{height:{bar}px;background:#15171c;display:flex;align-items:center;gap:8px;padding:0 16px;
|
||||
border-bottom:1px solid rgba(255,255,255,.06);position:relative}}
|
||||
.dot{{width:12px;height:12px;border-radius:50%}}
|
||||
.url{{position:absolute;left:50%;transform:translateX(-50%);height:24px;padding:0 14px;border-radius:7px;
|
||||
background:#0d0f13;color:#8b8f98;font-size:13px;display:flex;align-items:center;gap:6px;white-space:nowrap}}
|
||||
.url svg{{width:11px;height:11px;fill:none;stroke:#8b8f98;stroke-width:2}}
|
||||
img{{display:block;width:{iw}px;height:{ih}px}}
|
||||
</style></head><body><div class="win"><div class="bar">
|
||||
<span class="dot" style="background:#ff5f57"></span><span class="dot" style="background:#febc2e"></span><span class="dot" style="background:#28c840"></span>
|
||||
<span class="url"><svg viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>{url}</span>
|
||||
</div><img src="file://{src}"></div></body></html>"""
|
||||
|
||||
|
||||
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()
|
||||
@@ -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'(?<![\w.\'"`])' + name + r'\(', code[:pos]):
|
||||
line = code[: m.start()].count('\n') + 1
|
||||
print(f"{f}:{line}: {name}() is used before its definition")
|
||||
bad = 1
|
||||
print(f"lint-ucode: {checked} files checked" + (", problems found" if bad else ", ok"))
|
||||
sys.exit(bad)
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
coverage/
|
||||
package-lock.json
|
||||
src/portal/fonts/
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"printWidth": 140,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"semi": true,
|
||||
"arrowParens": "always",
|
||||
"endOfLine": "lf"
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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<T>(method: string, params: string[] = []) {
|
||||
const fn = rpc.declare<any>({ object: 'luci.dawnline', method, params });
|
||||
return async (...args: unknown[]): Promise<T> => {
|
||||
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<string, string | null>;
|
||||
// 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<string, { installed: string | null; latest: string | null; with?: string[] }>;
|
||||
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<string, UpdateComponent> } | 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<string, string>;
|
||||
needs?: Needs;
|
||||
effective: Record<string, unknown>;
|
||||
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<LogCategory, number>;
|
||||
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<any>({
|
||||
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>('status', ['days']);
|
||||
export let lastStatusAt = 0;
|
||||
|
||||
async function status(days?: number): Promise<Status> {
|
||||
const st = await statusRaw(days);
|
||||
lastStatusAt = Date.now();
|
||||
return st;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
personUpdate,
|
||||
settingsGet: call<SettingsData>('settings_get'),
|
||||
settingsUpdate: call<SettingsData>('settings_update', ['values']),
|
||||
serviceSet: call<{ id: string }>('service_set', ['id', 'name', 'address', 'ports']),
|
||||
serviceDelete: call<unknown>('service_delete', ['id']),
|
||||
geoClear: call<unknown>('geo_clear'),
|
||||
events: call<{ events: LogEvent[]; total: number; policy: LogsInfo['policy'] }>('events', ['limit']),
|
||||
logsClear,
|
||||
interfaces: call<InterfacesData>('interfaces', ['id']),
|
||||
serverInterfaces: call<InterfacesData>('server_interfaces', ['id', 'auto_wan', 'wan_device', 'auto_lan', 'lan_devices', 'lan_like']),
|
||||
usageClear: call<unknown>('usage_clear', ['scope', 'id']),
|
||||
uninstall: call<unknown>('uninstall', ['confirm']),
|
||||
status,
|
||||
setupDefaults: call<SetupDefaults>('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<unknown>('server_obfuscation', ['id', 'preset']),
|
||||
serverUpdate: call<unknown>('server_update', ['id', 'values']),
|
||||
serverDelete: call<unknown>('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<unknown>('person_pause', ['id', 'paused']),
|
||||
personRegen: call<{ link: string | null }>('person_regen', ['id']),
|
||||
personDelete: call<unknown>('person_delete', ['id']),
|
||||
personUsage: call<{ person: DayUsage[]; devices: Record<string, DayUsage[]> }>('person_usage', ['id', 'days']),
|
||||
pauseAll: call<unknown>('pause_all', ['paused']),
|
||||
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']),
|
||||
deviceConfig: call<ClientConfig>('device_config', ['id']),
|
||||
deviceUpdate: call<unknown>('device_update', ['id', 'name', 'disabled']),
|
||||
deviceDelete: call<unknown>('device_delete', ['id']),
|
||||
deviceRotate: call<ClientConfig>('device_rotate', ['id']),
|
||||
apply: call<unknown>('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<unknown>('backup_restore', ['name']),
|
||||
backupDelete: call<unknown>('backup_delete', ['name']),
|
||||
backupRead: call<{ data: string }>('backup_read', ['name']),
|
||||
backupUpload: call<unknown>('backup_upload', ['data']),
|
||||
exportJson: call<Record<string, unknown>>('export'),
|
||||
importJson: call<unknown>('import', ['data']),
|
||||
updatesStatus: call<UpdatesStatus>('updates_status'),
|
||||
updatesRun: call<{ started: boolean }>('updates_run', ['what']),
|
||||
};
|
||||
@@ -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<string, string> = {
|
||||
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]),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<HTMLElement> {
|
||||
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<string, () => 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<string, [string, string]> = {
|
||||
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);
|
||||
}
|
||||
@@ -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<keyof AwgCaps, string> = {
|
||||
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;
|
||||
}
|
||||
@@ -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<string, unknown> | Child, children?: Child): HTMLElement {
|
||||
const luciE = (window as unknown as { E: (t: string, a: Record<string, unknown>, 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<string, unknown>, flatten(children, []));
|
||||
}
|
||||
@@ -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<NetDevice['kind'], string> = {
|
||||
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<string>();
|
||||
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;
|
||||
}
|
||||
@@ -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('<svg ', `<svg x="${M + pad}" y="${top + pad}" width="${tile - 2 * pad}" height="${tile - 2 * pad}" `);
|
||||
const text = (x: number, y: number, size: number, fill: string, body: string, extra = '') =>
|
||||
`<text x="${x}" y="${y}" font-size="${size}" fill="${fill}" font-family="${SANS}" ${extra}>${body}</text>`;
|
||||
return (
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">` +
|
||||
`<rect width="${W}" height="${H}" rx="72" fill="#0b0b0b"/>` +
|
||||
// Mark and server name
|
||||
`<g transform="translate(${M} ${M})"><rect width="60" height="60" rx="15" fill="#fff"/>` +
|
||||
`<g transform="scale(.9375)"><path d="M14 38a18 18 0 0 1 36 0z" fill="#0b0b0b"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#0b0b0b" opacity=".5"/></g></g>` +
|
||||
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
|
||||
`<rect x="${M}" y="${top}" width="${tile}" height="${tile}" rx="52" fill="#ffffff"/>` +
|
||||
qr +
|
||||
// The link: three words, then the host
|
||||
`<text x="${W / 2}" y="${top + tile + 100}" font-size="58" fill="#ffffff" font-family="${MONO}" text-anchor="middle">${esc(word)}</text>` +
|
||||
text(W / 2, top + tile + 156, 34, '#737373', esc(url.host), 'text-anchor="middle"') +
|
||||
`</svg>`
|
||||
);
|
||||
}
|
||||
|
||||
async function toPng(svg: string): Promise<Blob> {
|
||||
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<Person, 'id' | 'name' | 'link'> & { 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',
|
||||
);
|
||||
}
|
||||
@@ -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<string, unknown> = {}): 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 !== ''),
|
||||
),
|
||||
]);
|
||||
}
|
||||
@@ -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<string, LogCategory> = {
|
||||
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<LogCategory, string> = {
|
||||
connections: 'Connections',
|
||||
devices: 'Devices',
|
||||
people: 'People',
|
||||
problems: 'Problems',
|
||||
};
|
||||
|
||||
export const CATEGORY_HELP: Record<LogCategory, string> = {
|
||||
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<Status, 'people'>) {
|
||||
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<Status, 'people'>, 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',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -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<Node>;
|
||||
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<string, string | Node>, options?: WidgetOptions) => LuciWidget;
|
||||
Checkbox: new (value: string | null, options?: WidgetOptions) => LuciWidget;
|
||||
DynamicList: new (values: string[] | null, choices?: Record<string, string>, options?: WidgetOptions) => LuciWidget;
|
||||
Dropdown: new (value: string | string[] | null, choices: Record<string, string | Node>, options?: WidgetOptions) => LuciWidget;
|
||||
}
|
||||
|
||||
interface LuciRpc {
|
||||
declare<T = any>(spec: {
|
||||
object: string;
|
||||
method: string;
|
||||
params?: string[];
|
||||
expect?: Record<string, unknown>;
|
||||
filter?: (data: any, args: unknown[], ...extra: unknown[]) => any;
|
||||
reject?: boolean;
|
||||
}): (...args: any[]) => Promise<T>;
|
||||
}
|
||||
|
||||
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<T>(p: Promise<T>, def: T): Promise<T>;
|
||||
resource(...parts: string[]): string;
|
||||
itemlist(node: Node, items: unknown[], separators?: unknown): HTMLElement;
|
||||
bind<F extends (...args: any[]) => 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<T>(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 };
|
||||
@@ -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.<page>())`.
|
||||
|
||||
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<any>;
|
||||
render(data: any): Node | Promise<Node>;
|
||||
/** Set by a form page when it rendered something without a form. */
|
||||
noFooter?: boolean;
|
||||
}
|
||||
|
||||
function factory<P extends Page>(Cls: new () => P, formBased: boolean) {
|
||||
return () => {
|
||||
const page = new Cls();
|
||||
const v: Record<string, unknown> = {
|
||||
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 };
|
||||
@@ -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<Range, number> = { online: 0, '24h': 86400, '7d': 7 * 86400, '30d': 30 * 86400 };
|
||||
|
||||
let loading: Promise<any> | 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<any> {
|
||||
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<string, GeoPoint>();
|
||||
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<string, Group>();
|
||||
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<string, number>();
|
||||
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;
|
||||
}
|
||||
@@ -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<ReturnType<typeof api.events>>];
|
||||
|
||||
/** 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<Loaded> {
|
||||
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<ReturnType<typeof api.events>>) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<HealthCheck['status'], string> = { ok: 'check', warn: 'alert', error: 'x', skip: 'pause' };
|
||||
const FIX_LABEL: Record<string, string> = { 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<string, string> = {
|
||||
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<string, HTMLElement> = {};
|
||||
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(
|
||||
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-hc-chart" aria-hidden="true">` +
|
||||
`<path d="M${line(2).join(' L')} L${W},${H} L0,${H}Z" class="area"/><path d="M${line(2).join(' L')}" class="dn"/><path d="M${line(1).join(' L')}" class="up"/></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(
|
||||
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true">` +
|
||||
`<path d="M${dl.join(' L')} L${W},${H} L0,${H}Z" class="area"/><path d="M${dl.join(' L')}" class="line"/>` +
|
||||
`<path d="M${ul.join(' L')}" class="line up"/></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'),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
@@ -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<Person['state'], string> = {
|
||||
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<Status> {
|
||||
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<Node> {
|
||||
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<Status | null> {
|
||||
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<Node> {
|
||||
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<Filter, number> = {
|
||||
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<Filter, string> = { 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<typeof api.personUpdate>[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')],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<string, Section> = { general: 'connection', network: 'connection', interfaces: 'access', advanced: 'tunnel' };
|
||||
function choices<T extends string>(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<string, string>): 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<string, ServerOverview> = {};
|
||||
pp: Record<string, PeoplePage> = {};
|
||||
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<HTMLElement>('[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<Section, () => 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<string, unknown>, 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<string, unknown> = {}) => {
|
||||
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/<path>/<person>.',
|
||||
),
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<string, string | string[]>;
|
||||
|
||||
/** 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<string, any>;
|
||||
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<string, string> = {
|
||||
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<string, any>;
|
||||
|
||||
// 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',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
@@ -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<keyof Needs, string> = { 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<boolean> {
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
// UI helpers on top of LuCI's `ui` and `E()`; markup stays stock LuCI
|
||||
// (cbi-button, cbi-tabmenu, alert-message) so themes style it.
|
||||
|
||||
import type { Child } from './luci.d';
|
||||
import { E } from './e';
|
||||
import { icon } from '../shared/icons';
|
||||
|
||||
type ButtonKind = 'action' | 'positive' | 'negative' | 'neutral' | 'apply' | 'remove' | 'edit' | 'add' | 'reset' | 'save';
|
||||
|
||||
export function button(
|
||||
label: Child,
|
||||
onClick: (ev: MouseEvent) => unknown,
|
||||
kind: ButtonKind = 'neutral',
|
||||
extra: Record<string, unknown> = {},
|
||||
): HTMLButtonElement {
|
||||
// E() sets every non-null attribute, so `disabled: false` would still
|
||||
// disable the button: boolean state goes through the property.
|
||||
const { disabled, ...attrs } = extra;
|
||||
const btn = E(
|
||||
'button',
|
||||
{
|
||||
class: `cbi-button cbi-button-${kind}`,
|
||||
type: 'button',
|
||||
...attrs,
|
||||
click: async (ev: MouseEvent) => {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
if (btn.disabled) return;
|
||||
btn.disabled = true;
|
||||
btn.classList.add('spinning');
|
||||
try {
|
||||
await onClick(ev);
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.classList.remove('spinning');
|
||||
}
|
||||
},
|
||||
},
|
||||
label,
|
||||
) as HTMLButtonElement;
|
||||
btn.disabled = !!disabled;
|
||||
return btn;
|
||||
}
|
||||
|
||||
export function iconButton(name: string, title: string, onClick: (ev: MouseEvent) => unknown, kind: ButtonKind = 'neutral', cls = '') {
|
||||
return button([icon(name), E('span', { class: 'dl-btn-label' }, title)], onClick, kind, {
|
||||
title,
|
||||
class: `cbi-button cbi-button-${kind} dl-icon-btn ${cls}`.trim(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A small toast at the bottom of the screen, above modals; replaces LuCI's
|
||||
* banner at the top of the page. Errors stay longer and can be closed.
|
||||
*/
|
||||
export function notify(message: Child, tone: 'info' | 'error' | 'warning' | 'success' = 'info', timeout = 0) {
|
||||
let stack = document.querySelector('.dl-toasts') as HTMLElement | null;
|
||||
if (!stack) {
|
||||
stack = E('div', { class: 'dl-toasts dl-root', role: 'status', 'aria-live': 'polite' });
|
||||
document.body.appendChild(stack);
|
||||
}
|
||||
const ic = tone === 'error' ? 'x' : tone === 'warning' ? 'alert' : tone === 'success' ? 'check' : null;
|
||||
const close = () => {
|
||||
t.classList.remove('show');
|
||||
setTimeout(() => t.remove(), 200);
|
||||
};
|
||||
const t = E('div', { class: `dl-toast ${tone}` }, [
|
||||
ic ? icon(ic) : '',
|
||||
E('span', {}, message),
|
||||
tone === 'error' ? E('button', { type: 'button', 'aria-label': 'Close', click: close }, icon('x')) : '',
|
||||
]);
|
||||
stack.appendChild(t);
|
||||
requestAnimationFrame(() => t.classList.add('show'));
|
||||
setTimeout(close, timeout || (tone === 'error' ? 8000 : tone === 'warning' ? 5000 : 2600));
|
||||
}
|
||||
|
||||
export function errorText(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
/** Run an action; failures become a toast. Returns undefined on error. */
|
||||
export async function attempt<T>(fn: () => Promise<T>, ok?: Child): Promise<T | undefined> {
|
||||
try {
|
||||
const r = await fn();
|
||||
if (ok) notify(ok, 'success', 3500);
|
||||
return r;
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function modal(title: string, body: Child, actions: Child, cls = '') {
|
||||
ui.showModal(title, [E('div', { class: `dl-modal ${cls}` }, body), E('div', { class: 'button-row' }, actions)]);
|
||||
}
|
||||
|
||||
export function closeModal() {
|
||||
ui.hideModal();
|
||||
}
|
||||
|
||||
export function confirmDialog(title: string, body: Child, confirmLabel = 'Confirm', danger = false): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
modal(title, body, [
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
class: 'cbi-button cbi-button-neutral',
|
||||
type: 'button',
|
||||
click: () => {
|
||||
closeModal();
|
||||
resolve(false);
|
||||
},
|
||||
},
|
||||
'Cancel',
|
||||
),
|
||||
' ',
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
class: `cbi-button ${danger ? 'cbi-button-negative' : 'cbi-button-positive'}`,
|
||||
type: 'button',
|
||||
click: () => {
|
||||
closeModal();
|
||||
resolve(true);
|
||||
},
|
||||
},
|
||||
confirmLabel,
|
||||
),
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
export async function copyText(text: string, what = 'Copied to clipboard') {
|
||||
try {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} else {
|
||||
const ta = E('textarea', { style: 'position:fixed;opacity:0' }, text) as HTMLTextAreaElement;
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
document.execCommand('copy');
|
||||
ta.remove();
|
||||
}
|
||||
notify(what, 'success', 2500);
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves a file; pass application/octet-stream for .conf, or Safari appends .txt. */
|
||||
export function downloadFile(name: string, content: string | Blob, type = 'text/plain') {
|
||||
const g = globalThis as unknown as { Blob: typeof Blob };
|
||||
const blob = typeof content === 'string' ? new g.Blob([content], { type }) : content;
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = E('a', { href: url, download: name, style: 'display:none' });
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
setTimeout(() => {
|
||||
URL.revokeObjectURL(url);
|
||||
a.remove();
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
/** LuCI-style tab strip (cbi-tabmenu) for custom modal content. */
|
||||
export function tabs(panes: { id: string; label: string; content: Child }[], initial?: string): HTMLElement {
|
||||
const head = E('ul', { class: 'cbi-tabmenu' });
|
||||
const body = E('div', { class: 'dl-tab-body' });
|
||||
const show = (id: string) => {
|
||||
head.querySelectorAll('li').forEach((li) => {
|
||||
li.classList.toggle('cbi-tab', li.dataset.id === id);
|
||||
li.classList.toggle('cbi-tab-disabled', li.dataset.id !== id);
|
||||
});
|
||||
body.querySelectorAll<HTMLElement>(':scope > [data-pane]').forEach((p) => (p.style.display = p.dataset.pane === id ? '' : 'none'));
|
||||
};
|
||||
for (const p of panes) {
|
||||
head.appendChild(
|
||||
E(
|
||||
'li',
|
||||
{ 'data-id': p.id },
|
||||
E(
|
||||
'a',
|
||||
{
|
||||
href: '#',
|
||||
click: (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
show(p.id);
|
||||
},
|
||||
},
|
||||
p.label,
|
||||
),
|
||||
),
|
||||
);
|
||||
body.appendChild(E('div', { 'data-pane': p.id }, p.content));
|
||||
}
|
||||
show(initial ?? panes[0]?.id);
|
||||
return E('div', { class: 'dl-tabs' }, [head, body]);
|
||||
}
|
||||
|
||||
export function field(label: Child, widget: Child, description?: Child): HTMLElement {
|
||||
return E('div', { class: 'cbi-value' }, [
|
||||
E('label', { class: 'cbi-value-title' }, label),
|
||||
E('div', { class: 'cbi-value-field' }, [widget, description ? E('div', { class: 'cbi-value-description' }, description) : '']),
|
||||
]);
|
||||
}
|
||||
|
||||
export function callout(tone: 'ok' | 'warn' | 'error' | 'info', children: Child): HTMLElement {
|
||||
const cls = { ok: 'success', warn: 'warning', error: 'error', info: 'notice' }[tone];
|
||||
return E('div', { class: `alert-message ${cls}` }, children);
|
||||
}
|
||||
|
||||
export function pill(text: Child, tone = '', title = ''): HTMLElement {
|
||||
return E('span', { class: `dl-pill ${tone}`, title }, text);
|
||||
}
|
||||
|
||||
export function svg(markup: string, cls = ''): HTMLElement {
|
||||
const el = E('div', { class: cls });
|
||||
el.innerHTML = markup;
|
||||
return el;
|
||||
}
|
||||
|
||||
/** Read a picked file as text or base64. */
|
||||
export function pickFile(accept: string, as: 'text' | 'base64'): Promise<{ name: string; data: string } | null> {
|
||||
return new Promise((resolve) => {
|
||||
const input = E('input', { type: 'file', accept, style: 'display:none' }) as HTMLInputElement;
|
||||
// Closing the file picker fires "cancel" (no "change"); without it the caller waits forever.
|
||||
input.addEventListener('cancel', () => {
|
||||
input.remove();
|
||||
resolve(null);
|
||||
});
|
||||
input.addEventListener('change', () => {
|
||||
const f = input.files?.[0];
|
||||
input.remove();
|
||||
if (!f) return resolve(null);
|
||||
const r = new FileReader();
|
||||
r.onload = () => {
|
||||
const res = String(r.result ?? '');
|
||||
resolve({ name: f.name, data: as === 'base64' ? res.replace(/^data:[^,]*,/, '') : res });
|
||||
};
|
||||
r.onerror = () => resolve(null);
|
||||
if (as === 'base64') r.readAsDataURL(f);
|
||||
else r.readAsText(f);
|
||||
});
|
||||
document.body.appendChild(input);
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
export interface MenuItem {
|
||||
label: string;
|
||||
icon?: Node;
|
||||
danger?: boolean;
|
||||
warn?: boolean;
|
||||
run: () => unknown;
|
||||
}
|
||||
|
||||
/** Small dropdown under `anchor`; closes on pick, outside click or Escape. */
|
||||
type OpenMenu = HTMLElement & { dlAnchor?: HTMLElement; dlClose?: () => void };
|
||||
|
||||
export function dropdown(anchor: HTMLElement, items: (MenuItem | null)[]) {
|
||||
// A second click on the same button closes its menu instead of reopening it.
|
||||
const prev = document.querySelector('.dl-dd') as OpenMenu | null;
|
||||
if (prev) {
|
||||
prev.dlClose ? prev.dlClose() : prev.remove();
|
||||
if (prev.dlAnchor === anchor) return;
|
||||
}
|
||||
const menu: OpenMenu = E(
|
||||
'div',
|
||||
{ class: 'dl-dd dl-root', role: 'menu' },
|
||||
items.map((it) =>
|
||||
it
|
||||
? E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'menuitem',
|
||||
class: it.danger ? 'danger' : it.warn ? 'warn' : '',
|
||||
click: () => {
|
||||
close();
|
||||
it.run();
|
||||
},
|
||||
},
|
||||
[it.icon ?? '', E('span', {}, it.label)],
|
||||
)
|
||||
: E('hr'),
|
||||
),
|
||||
);
|
||||
document.body.appendChild(menu);
|
||||
const r = anchor.getBoundingClientRect();
|
||||
const w = menu.offsetWidth,
|
||||
h = menu.offsetHeight;
|
||||
// Open upwards when the menu would run off the bottom of the screen.
|
||||
menu.style.top = `${r.bottom + 6 + h > window.innerHeight - 8 && r.top - 6 - h > 8 ? r.top - 6 - h : r.bottom + 6}px`;
|
||||
menu.style.left = `${Math.max(8, Math.min(r.right - w, window.innerWidth - w - 8))}px`;
|
||||
const onDoc = (ev: Event) => {
|
||||
if (!menu.contains(ev.target as Node) && !anchor.contains(ev.target as Node)) close();
|
||||
};
|
||||
const onKey = (ev: KeyboardEvent) => {
|
||||
if (ev.key === 'Escape') close();
|
||||
};
|
||||
menu.dlAnchor = anchor;
|
||||
menu.dlClose = close;
|
||||
function close() {
|
||||
menu.remove();
|
||||
document.removeEventListener('mousedown', onDoc, true);
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
window.removeEventListener('scroll', close, true);
|
||||
}
|
||||
setTimeout(() => {
|
||||
document.addEventListener('mousedown', onDoc, true);
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
window.addEventListener('scroll', close, true);
|
||||
});
|
||||
(menu.querySelector('button') as HTMLElement | null)?.focus({ preventScroll: true });
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><style>.t{fill:#0a0a0a}.g{fill:#fff}@media (prefers-color-scheme:dark){.t{fill:#fff}.g{fill:#0a0a0a}}</style><rect class="t" width="64" height="64" rx="16"/><path class="g" d="M14 38a18 18 0 0 1 36 0z"/><rect class="g" x="12" y="43" width="40" height="4" rx="2" opacity=".5"/></svg>
|
||||
|
After Width: | Height: | Size: 343 B |
@@ -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<string, string | number | boolean | EventListener | null | undefined>;
|
||||
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 =
|
||||
'<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 15a9 9 0 0 1 18 0z" fill="currentColor"/><rect x="2" y="17" width="20" height="2" rx="1" fill="currentColor" opacity=".45"/></svg>';
|
||||
|
||||
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<T>(path: string, body?: unknown): Promise<T> {
|
||||
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<Person['access'], string> = {
|
||||
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<ClientConfig | null> {
|
||||
try {
|
||||
return await call<ClientConfig>(`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<string, () => 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<string, string> = { 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');
|
||||
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<string> = (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>('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();
|
||||
}
|
||||
@@ -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 +=
|
||||
`<g><title>${title}</title>` +
|
||||
`<rect x="${x.toFixed(1)}" y="${(height - hDown - hUp).toFixed(1)}" width="${(bw - pad).toFixed(1)}" height="${hDown.toFixed(1)}" rx="1.5" class="dl-bar-down"/>` +
|
||||
`<rect x="${x.toFixed(1)}" y="${(height - hUp).toFixed(1)}" width="${(bw - pad).toFixed(1)}" height="${hUp.toFixed(1)}" rx="1.5" class="dl-bar-up"/>` +
|
||||
`<rect x="${(i * bw).toFixed(1)}" y="0" width="${bw.toFixed(1)}" height="${height}" fill="transparent"/></g>`;
|
||||
});
|
||||
return `<svg class="dl-chart" viewBox="0 0 ${w} ${height}" preserveAspectRatio="none" role="img" aria-label="Traffic per day">${bars}</svg>`;
|
||||
}
|
||||
@@ -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<Access, string> = {
|
||||
lan: 'Home network',
|
||||
internet: 'Internet',
|
||||
both: 'Home network + Internet',
|
||||
};
|
||||
|
||||
export const ACCESS_SHORT: Record<Access, string> = { lan: 'LAN', internet: 'Internet', both: 'LAN + Internet' };
|
||||
|
||||
/** In picker order. */
|
||||
export const KINDS: Kind[] = ['computer', 'phone', 'tablet', 'router', 'other'];
|
||||
|
||||
export const KIND_LABEL: Record<Kind, string> = {
|
||||
computer: 'PC',
|
||||
phone: 'Phone',
|
||||
tablet: 'Tablet',
|
||||
router: 'Router',
|
||||
other: 'Other',
|
||||
};
|
||||
|
||||
export const STATE_LABEL: Record<PersonState, string> = {
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// Inline SVG icons (stroke = currentColor), sized by CSS.
|
||||
|
||||
const P: Record<string, string> = {
|
||||
phone: '<rect x="7" y="2.5" width="10" height="19" rx="2.2"/><path d="M11 18.5h2"/>',
|
||||
computer: '<rect x="3" y="4.5" width="18" height="12" rx="1.8"/><path d="M2 19.5h20"/>',
|
||||
tablet: '<rect x="4.5" y="2.5" width="15" height="19" rx="2.2"/><path d="M11 18.5h2"/>',
|
||||
router: '<rect x="3" y="13" width="18" height="7" rx="1.8"/><path d="M7 16.5h.01M10.5 16.5h.01M8 13l-2-6M16 13l2-6"/>',
|
||||
other: '<path d="M12 3 20 7.5v9L12 21l-8-4.5v-9L12 3Z"/><path d="M4 7.5 12 12l8-4.5M12 12v9"/>',
|
||||
ethernet:
|
||||
'<rect x="9" y="3" width="6" height="5" rx="1"/><rect x="3" y="16" width="6" height="5" rx="1"/><rect x="15" y="16" width="6" height="5" rx="1"/><path d="M12 8v4M6 16v-4h12v4"/>',
|
||||
bridge: '<circle cx="6" cy="6" r="2.2"/><circle cx="18" cy="18" r="2.2"/><path d="M6 8.2v4.3a4 4 0 0 0 4 4h5.8"/>',
|
||||
wifi: '<path d="M4.5 9.5a11 11 0 0 1 15 0M7.5 12.8a6.5 6.5 0 0 1 9 0M10.6 16a2 2 0 0 1 2.8 0"/><circle cx="12" cy="19" r=".6"/>',
|
||||
tunnel: '<path d="M9.5 14.5 14.5 9.5"/><path d="M11 6.5l1.5-1.5a4.2 4.2 0 0 1 6 6L17 12.5M13 17.5 11.5 19a4.2 4.2 0 0 1-6-6L7 11.5"/>',
|
||||
plus: '<path d="M12 5v14M5 12h14"/>',
|
||||
chart: '<path d="M4 20V10M10 20V4M16 20v-7M22 20H2"/>',
|
||||
reset: '<path d="M4 12a8 8 0 1 0 2.4-5.7L4 8.5"/><path d="M4 4v4.5h4.5"/>',
|
||||
package: '<path d="M12 3 20 7.5v9L12 21l-8-4.5v-9L12 3Z"/><path d="M4 7.5 12 12l8-4.5M12 12v9M8 5.3l8 4.5"/>',
|
||||
code: '<path d="m8 8-4 4 4 4M16 8l4 4-4 4M13.5 5l-3 14"/>',
|
||||
plug: '<path d="M9 3v5M15 3v5M6 8h12v3a6 6 0 0 1-12 0V8ZM12 17v4"/>',
|
||||
sunrise: '<path d="M4 16a8 8 0 0 1 16 0z"/><path d="M2 19.5h20"/>',
|
||||
refresh: '<path d="M20 12a8 8 0 1 1-2.4-5.7L20 8.5"/><path d="M20 4v4.5h-4.5"/>',
|
||||
archive: '<rect x="3" y="4" width="18" height="5" rx="1.2"/><path d="M5 9v10h14V9M10 13h4"/>',
|
||||
qr: '<rect x="4" y="4" width="6" height="6" rx="1"/><rect x="14" y="4" width="6" height="6" rx="1"/><rect x="4" y="14" width="6" height="6" rx="1"/><path d="M14 14h2v2h-2zM18 18h2v2h-2zM14 18h2M18 14h2"/>',
|
||||
copy: '<rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/>',
|
||||
download: '<path d="M12 4v11M7 10l5 5 5-5M5 20h14"/>',
|
||||
link: '<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/>',
|
||||
trash: '<path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/>',
|
||||
edit: '<path d="M4 20h4L19 9l-4-4L4 16z"/>',
|
||||
pause: '<path d="M9 5v14M15 5v14"/>',
|
||||
play: '<path d="M7 4l13 8-13 8z"/>',
|
||||
key: '<circle cx="8" cy="15" r="4"/><path d="M11 12l8-8M16 7l2 2"/>',
|
||||
out: '<path d="M14 4h6v16h-6M10 8l-4 4 4 4M6 12h10"/>',
|
||||
shield: '<path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"/>',
|
||||
shieldplus: '<path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"/><path d="M12 9v6M9 12h6"/>',
|
||||
lock: '<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/><path d="M12 14.5v2"/>',
|
||||
zap: '<path d="M13 3 5 13.5h6L10 21l8-10.5h-6L13 3z"/>',
|
||||
check: '<path d="M5 12.5l4.5 4.5L19 7.5"/>',
|
||||
alert: '<path d="M12 3l9.5 17h-19z"/><path d="M12 10v4M12 17h.01"/>',
|
||||
x: '<path d="M6 6l12 12M18 6L6 18"/>',
|
||||
globe: '<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3.5 3 14.5 0 18M12 3c-3 3.5-3 14.5 0 18"/>',
|
||||
home: '<path d="M3 11l9-7 9 7"/><path d="M5 10v10h14V10"/>',
|
||||
open: '<path d="M14 4h6v6M20 4l-9 9M18 14v6H4V6h6"/>',
|
||||
file: '<path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4"/>',
|
||||
search: '<circle cx="11" cy="11" r="7"/><path d="M20 20l-4-4"/>',
|
||||
network:
|
||||
'<circle cx="12" cy="12" r="2.5"/><circle cx="5" cy="5" r="1.8"/><circle cx="19" cy="5" r="1.8"/><circle cx="5" cy="19" r="1.8"/><circle cx="19" cy="19" r="1.8"/><path d="m6.4 6.4 3.8 3.8M17.6 6.4l-3.8 3.8M6.4 17.6l3.8-3.8M17.6 17.6l-3.8-3.8"/>',
|
||||
moon: '<path d="M20 14.5A8 8 0 1 1 9.5 4a6.5 6.5 0 0 0 10.5 10.5z"/>',
|
||||
chevron: '<path d="m9 6 6 6-6 6"/>',
|
||||
clock: '<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5V12l3 2"/>',
|
||||
calendar: '<rect x="4" y="5" width="16" height="16" rx="2"/><path d="M8 3v4M16 3v4M4 10h16"/>',
|
||||
minus: '<path d="M5 12h14"/>',
|
||||
more: '<circle cx="5" cy="12" r="1.2"/><circle cx="12" cy="12" r="1.2"/><circle cx="19" cy="12" r="1.2"/>',
|
||||
pin: '<path d="M12 21s7-6.2 7-11.5A7 7 0 0 0 5 9.5C5 14.8 12 21 12 21z"/><circle cx="12" cy="9.5" r="2.5"/>',
|
||||
activity: '<path d="M3 12h4l3-8 4 16 3-8h4"/>',
|
||||
};
|
||||
|
||||
export function iconSvg(name: string, cls = 'dl-icon'): string {
|
||||
const body = P[name] ?? P.phone;
|
||||
return `<svg class="${cls}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -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 = '<path d="M14 38a18 18 0 0 1 36 0z" fill="#fff"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#fff" opacity=".5"/>';
|
||||
|
||||
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 =
|
||||
`<rect x="${o}" y="${o}" width="${s}" height="${s}" rx="${s * 0.25}" fill="#0a0a0a"/>` +
|
||||
`<g transform="translate(${o} ${o}) scale(${s / 64})">${MARK}</g>`;
|
||||
}
|
||||
return (
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" role="img" aria-label="QR code">` +
|
||||
`<rect width="${size}" height="${size}" fill="#fff"/><path d="${d}" fill="#000" shape-rendering="crispEdges"/>${mark}</svg>`
|
||||
);
|
||||
}
|
||||
@@ -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<string, string>;
|
||||
}
|
||||
|
||||
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<string, string>;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||